LCOV - code coverage report
Current view: top level - src/backend/commands - tablecmds.c (source / functions) Coverage Total Hit
Test: PostgreSQL 19devel Lines: 92.5 % 7247 6704
Test Date: 2026-03-25 21:16:15 Functions: 100.0 % 222 222
Legend: Lines:     hit not hit

            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-2026, 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/tupconvert.h"
      29              : #include "access/xact.h"
      30              : #include "access/xlog.h"
      31              : #include "access/xloginsert.h"
      32              : #include "catalog/catalog.h"
      33              : #include "catalog/heap.h"
      34              : #include "catalog/index.h"
      35              : #include "catalog/namespace.h"
      36              : #include "catalog/objectaccess.h"
      37              : #include "catalog/partition.h"
      38              : #include "catalog/pg_am.h"
      39              : #include "catalog/pg_attrdef.h"
      40              : #include "catalog/pg_collation.h"
      41              : #include "catalog/pg_constraint.h"
      42              : #include "catalog/pg_depend.h"
      43              : #include "catalog/pg_foreign_table.h"
      44              : #include "catalog/pg_inherits.h"
      45              : #include "catalog/pg_largeobject.h"
      46              : #include "catalog/pg_largeobject_metadata.h"
      47              : #include "catalog/pg_namespace.h"
      48              : #include "catalog/pg_opclass.h"
      49              : #include "catalog/pg_policy.h"
      50              : #include "catalog/pg_proc.h"
      51              : #include "catalog/pg_publication_rel.h"
      52              : #include "catalog/pg_rewrite.h"
      53              : #include "catalog/pg_statistic_ext.h"
      54              : #include "catalog/pg_tablespace.h"
      55              : #include "catalog/pg_trigger.h"
      56              : #include "catalog/pg_type.h"
      57              : #include "catalog/storage.h"
      58              : #include "catalog/storage_xlog.h"
      59              : #include "catalog/toasting.h"
      60              : #include "commands/cluster.h"
      61              : #include "commands/comment.h"
      62              : #include "commands/defrem.h"
      63              : #include "commands/event_trigger.h"
      64              : #include "commands/sequence.h"
      65              : #include "commands/tablecmds.h"
      66              : #include "commands/tablespace.h"
      67              : #include "commands/trigger.h"
      68              : #include "commands/typecmds.h"
      69              : #include "commands/user.h"
      70              : #include "commands/vacuum.h"
      71              : #include "common/int.h"
      72              : #include "executor/executor.h"
      73              : #include "foreign/fdwapi.h"
      74              : #include "foreign/foreign.h"
      75              : #include "miscadmin.h"
      76              : #include "nodes/makefuncs.h"
      77              : #include "nodes/nodeFuncs.h"
      78              : #include "nodes/parsenodes.h"
      79              : #include "optimizer/optimizer.h"
      80              : #include "parser/parse_coerce.h"
      81              : #include "parser/parse_collate.h"
      82              : #include "parser/parse_expr.h"
      83              : #include "parser/parse_relation.h"
      84              : #include "parser/parse_type.h"
      85              : #include "parser/parse_utilcmd.h"
      86              : #include "parser/parser.h"
      87              : #include "partitioning/partbounds.h"
      88              : #include "partitioning/partdesc.h"
      89              : #include "pgstat.h"
      90              : #include "rewrite/rewriteDefine.h"
      91              : #include "rewrite/rewriteHandler.h"
      92              : #include "rewrite/rewriteManip.h"
      93              : #include "storage/bufmgr.h"
      94              : #include "storage/lmgr.h"
      95              : #include "storage/lock.h"
      96              : #include "storage/predicate.h"
      97              : #include "storage/smgr.h"
      98              : #include "tcop/utility.h"
      99              : #include "utils/acl.h"
     100              : #include "utils/builtins.h"
     101              : #include "utils/fmgroids.h"
     102              : #include "utils/inval.h"
     103              : #include "utils/lsyscache.h"
     104              : #include "utils/memutils.h"
     105              : #include "utils/partcache.h"
     106              : #include "utils/relcache.h"
     107              : #include "utils/ruleutils.h"
     108              : #include "utils/snapmgr.h"
     109              : #include "utils/syscache.h"
     110              : #include "utils/timestamp.h"
     111              : #include "utils/typcache.h"
     112              : #include "utils/usercontext.h"
     113              : 
     114              : /*
     115              :  * ON COMMIT action list
     116              :  */
     117              : typedef struct OnCommitItem
     118              : {
     119              :     Oid         relid;          /* relid of relation */
     120              :     OnCommitAction oncommit;    /* what to do at end of xact */
     121              : 
     122              :     /*
     123              :      * If this entry was created during the current transaction,
     124              :      * creating_subid is the ID of the creating subxact; if created in a prior
     125              :      * transaction, creating_subid is zero.  If deleted during the current
     126              :      * transaction, deleting_subid is the ID of the deleting subxact; if no
     127              :      * deletion request is pending, deleting_subid is zero.
     128              :      */
     129              :     SubTransactionId creating_subid;
     130              :     SubTransactionId deleting_subid;
     131              : } OnCommitItem;
     132              : 
     133              : static List *on_commits = NIL;
     134              : 
     135              : 
     136              : /*
     137              :  * State information for ALTER TABLE
     138              :  *
     139              :  * The pending-work queue for an ALTER TABLE is a List of AlteredTableInfo
     140              :  * structs, one for each table modified by the operation (the named table
     141              :  * plus any child tables that are affected).  We save lists of subcommands
     142              :  * to apply to this table (possibly modified by parse transformation steps);
     143              :  * these lists will be executed in Phase 2.  If a Phase 3 step is needed,
     144              :  * necessary information is stored in the constraints and newvals lists.
     145              :  *
     146              :  * Phase 2 is divided into multiple passes; subcommands are executed in
     147              :  * a pass determined by subcommand type.
     148              :  */
     149              : 
     150              : typedef enum AlterTablePass
     151              : {
     152              :     AT_PASS_UNSET = -1,         /* UNSET will cause ERROR */
     153              :     AT_PASS_DROP,               /* DROP (all flavors) */
     154              :     AT_PASS_ALTER_TYPE,         /* ALTER COLUMN TYPE */
     155              :     AT_PASS_ADD_COL,            /* ADD COLUMN */
     156              :     AT_PASS_SET_EXPRESSION,     /* ALTER SET EXPRESSION */
     157              :     AT_PASS_OLD_INDEX,          /* re-add existing indexes */
     158              :     AT_PASS_OLD_CONSTR,         /* re-add existing constraints */
     159              :     /* We could support a RENAME COLUMN pass here, but not currently used */
     160              :     AT_PASS_ADD_CONSTR,         /* ADD constraints (initial examination) */
     161              :     AT_PASS_COL_ATTRS,          /* set column attributes, eg NOT NULL */
     162              :     AT_PASS_ADD_INDEXCONSTR,    /* ADD index-based constraints */
     163              :     AT_PASS_ADD_INDEX,          /* ADD indexes */
     164              :     AT_PASS_ADD_OTHERCONSTR,    /* ADD other constraints, defaults */
     165              :     AT_PASS_MISC,               /* other stuff */
     166              : } AlterTablePass;
     167              : 
     168              : #define AT_NUM_PASSES           (AT_PASS_MISC + 1)
     169              : 
     170              : typedef struct AlteredTableInfo
     171              : {
     172              :     /* Information saved before any work commences: */
     173              :     Oid         relid;          /* Relation to work on */
     174              :     char        relkind;        /* Its relkind */
     175              :     TupleDesc   oldDesc;        /* Pre-modification tuple descriptor */
     176              : 
     177              :     /*
     178              :      * Transiently set during Phase 2, normally set to NULL.
     179              :      *
     180              :      * ATRewriteCatalogs sets this when it starts, and closes when ATExecCmd
     181              :      * returns control.  This can be exploited by ATExecCmd subroutines to
     182              :      * close/reopen across transaction boundaries.
     183              :      */
     184              :     Relation    rel;
     185              : 
     186              :     /* Information saved by Phase 1 for Phase 2: */
     187              :     List       *subcmds[AT_NUM_PASSES]; /* Lists of AlterTableCmd */
     188              :     /* Information saved by Phases 1/2 for Phase 3: */
     189              :     List       *constraints;    /* List of NewConstraint */
     190              :     List       *newvals;        /* List of NewColumnValue */
     191              :     List       *afterStmts;     /* List of utility command parsetrees */
     192              :     bool        verify_new_notnull; /* T if we should recheck NOT NULL */
     193              :     int         rewrite;        /* Reason for forced rewrite, if any */
     194              :     bool        chgAccessMethod;    /* T if SET ACCESS METHOD is used */
     195              :     Oid         newAccessMethod;    /* new access method; 0 means no change,
     196              :                                      * if above is true */
     197              :     Oid         newTableSpace;  /* new tablespace; 0 means no change */
     198              :     bool        chgPersistence; /* T if SET LOGGED/UNLOGGED is used */
     199              :     char        newrelpersistence;  /* if above is true */
     200              :     Expr       *partition_constraint;   /* for attach partition validation */
     201              :     /* true, if validating default due to some other attach/detach */
     202              :     bool        validate_default;
     203              :     /* Objects to rebuild after completing ALTER TYPE operations */
     204              :     List       *changedConstraintOids;  /* OIDs of constraints to rebuild */
     205              :     List       *changedConstraintDefs;  /* string definitions of same */
     206              :     List       *changedIndexOids;   /* OIDs of indexes to rebuild */
     207              :     List       *changedIndexDefs;   /* string definitions of same */
     208              :     char       *replicaIdentityIndex;   /* index to reset as REPLICA IDENTITY */
     209              :     char       *clusterOnIndex; /* index to use for CLUSTER */
     210              :     List       *changedStatisticsOids;  /* OIDs of statistics to rebuild */
     211              :     List       *changedStatisticsDefs;  /* string definitions of same */
     212              : } AlteredTableInfo;
     213              : 
     214              : /* Struct describing one new constraint to check in Phase 3 scan */
     215              : /* Note: new not-null constraints are handled elsewhere */
     216              : typedef struct NewConstraint
     217              : {
     218              :     char       *name;           /* Constraint name, or NULL if none */
     219              :     ConstrType  contype;        /* CHECK or FOREIGN */
     220              :     Oid         refrelid;       /* PK rel, if FOREIGN */
     221              :     Oid         refindid;       /* OID of PK's index, if FOREIGN */
     222              :     bool        conwithperiod;  /* Whether the new FOREIGN KEY uses PERIOD */
     223              :     Oid         conid;          /* OID of pg_constraint entry, if FOREIGN */
     224              :     Node       *qual;           /* Check expr or CONSTR_FOREIGN Constraint */
     225              :     ExprState  *qualstate;      /* Execution state for CHECK expr */
     226              : } NewConstraint;
     227              : 
     228              : /*
     229              :  * Struct describing one new column value that needs to be computed during
     230              :  * Phase 3 copy (this could be either a new column with a non-null default, or
     231              :  * a column that we're changing the type of).  Columns without such an entry
     232              :  * are just copied from the old table during ATRewriteTable.  Note that the
     233              :  * expr is an expression over *old* table values, except when is_generated
     234              :  * is true; then it is an expression over columns of the *new* tuple.
     235              :  */
     236              : typedef struct NewColumnValue
     237              : {
     238              :     AttrNumber  attnum;         /* which column */
     239              :     Expr       *expr;           /* expression to compute */
     240              :     ExprState  *exprstate;      /* execution state */
     241              :     bool        is_generated;   /* is it a GENERATED expression? */
     242              : } NewColumnValue;
     243              : 
     244              : /*
     245              :  * Error-reporting support for RemoveRelations
     246              :  */
     247              : struct dropmsgstrings
     248              : {
     249              :     char        kind;
     250              :     int         nonexistent_code;
     251              :     const char *nonexistent_msg;
     252              :     const char *skipping_msg;
     253              :     const char *nota_msg;
     254              :     const char *drophint_msg;
     255              : };
     256              : 
     257              : static const struct dropmsgstrings dropmsgstringarray[] = {
     258              :     {RELKIND_RELATION,
     259              :         ERRCODE_UNDEFINED_TABLE,
     260              :         gettext_noop("table \"%s\" does not exist"),
     261              :         gettext_noop("table \"%s\" does not exist, skipping"),
     262              :         gettext_noop("\"%s\" is not a table"),
     263              :     gettext_noop("Use DROP TABLE to remove a table.")},
     264              :     {RELKIND_SEQUENCE,
     265              :         ERRCODE_UNDEFINED_TABLE,
     266              :         gettext_noop("sequence \"%s\" does not exist"),
     267              :         gettext_noop("sequence \"%s\" does not exist, skipping"),
     268              :         gettext_noop("\"%s\" is not a sequence"),
     269              :     gettext_noop("Use DROP SEQUENCE to remove a sequence.")},
     270              :     {RELKIND_VIEW,
     271              :         ERRCODE_UNDEFINED_TABLE,
     272              :         gettext_noop("view \"%s\" does not exist"),
     273              :         gettext_noop("view \"%s\" does not exist, skipping"),
     274              :         gettext_noop("\"%s\" is not a view"),
     275              :     gettext_noop("Use DROP VIEW to remove a view.")},
     276              :     {RELKIND_MATVIEW,
     277              :         ERRCODE_UNDEFINED_TABLE,
     278              :         gettext_noop("materialized view \"%s\" does not exist"),
     279              :         gettext_noop("materialized view \"%s\" does not exist, skipping"),
     280              :         gettext_noop("\"%s\" is not a materialized view"),
     281              :     gettext_noop("Use DROP MATERIALIZED VIEW to remove a materialized view.")},
     282              :     {RELKIND_INDEX,
     283              :         ERRCODE_UNDEFINED_OBJECT,
     284              :         gettext_noop("index \"%s\" does not exist"),
     285              :         gettext_noop("index \"%s\" does not exist, skipping"),
     286              :         gettext_noop("\"%s\" is not an index"),
     287              :     gettext_noop("Use DROP INDEX to remove an index.")},
     288              :     {RELKIND_COMPOSITE_TYPE,
     289              :         ERRCODE_UNDEFINED_OBJECT,
     290              :         gettext_noop("type \"%s\" does not exist"),
     291              :         gettext_noop("type \"%s\" does not exist, skipping"),
     292              :         gettext_noop("\"%s\" is not a type"),
     293              :     gettext_noop("Use DROP TYPE to remove a type.")},
     294              :     {RELKIND_FOREIGN_TABLE,
     295              :         ERRCODE_UNDEFINED_OBJECT,
     296              :         gettext_noop("foreign table \"%s\" does not exist"),
     297              :         gettext_noop("foreign table \"%s\" does not exist, skipping"),
     298              :         gettext_noop("\"%s\" is not a foreign table"),
     299              :     gettext_noop("Use DROP FOREIGN TABLE to remove a foreign table.")},
     300              :     {RELKIND_PARTITIONED_TABLE,
     301              :         ERRCODE_UNDEFINED_TABLE,
     302              :         gettext_noop("table \"%s\" does not exist"),
     303              :         gettext_noop("table \"%s\" does not exist, skipping"),
     304              :         gettext_noop("\"%s\" is not a table"),
     305              :     gettext_noop("Use DROP TABLE to remove a table.")},
     306              :     {RELKIND_PARTITIONED_INDEX,
     307              :         ERRCODE_UNDEFINED_OBJECT,
     308              :         gettext_noop("index \"%s\" does not exist"),
     309              :         gettext_noop("index \"%s\" does not exist, skipping"),
     310              :         gettext_noop("\"%s\" is not an index"),
     311              :     gettext_noop("Use DROP INDEX to remove an index.")},
     312              :     {RELKIND_PROPGRAPH,
     313              :         ERRCODE_UNDEFINED_OBJECT,
     314              :         gettext_noop("property graph \"%s\" does not exist"),
     315              :         gettext_noop("property graph \"%s\" does not exist, skipping"),
     316              :         gettext_noop("\"%s\" is not a property graph"),
     317              :     gettext_noop("Use DROP PROPERTY GRAPH to remove a property graph.")},
     318              :     {'\0', 0, NULL, NULL, NULL, NULL}
     319              : };
     320              : 
     321              : /* communication between RemoveRelations and RangeVarCallbackForDropRelation */
     322              : struct DropRelationCallbackState
     323              : {
     324              :     /* These fields are set by RemoveRelations: */
     325              :     char        expected_relkind;
     326              :     LOCKMODE    heap_lockmode;
     327              :     /* These fields are state to track which subsidiary locks are held: */
     328              :     Oid         heapOid;
     329              :     Oid         partParentOid;
     330              :     /* These fields are passed back by RangeVarCallbackForDropRelation: */
     331              :     char        actual_relkind;
     332              :     char        actual_relpersistence;
     333              : };
     334              : 
     335              : /* Alter table target-type flags for ATSimplePermissions */
     336              : #define     ATT_TABLE               0x0001
     337              : #define     ATT_VIEW                0x0002
     338              : #define     ATT_MATVIEW             0x0004
     339              : #define     ATT_INDEX               0x0008
     340              : #define     ATT_COMPOSITE_TYPE      0x0010
     341              : #define     ATT_FOREIGN_TABLE       0x0020
     342              : #define     ATT_PARTITIONED_INDEX   0x0040
     343              : #define     ATT_SEQUENCE            0x0080
     344              : #define     ATT_PARTITIONED_TABLE   0x0100
     345              : 
     346              : /*
     347              :  * ForeignTruncateInfo
     348              :  *
     349              :  * Information related to truncation of foreign tables.  This is used for
     350              :  * the elements in a hash table. It uses the server OID as lookup key,
     351              :  * and includes a per-server list of all foreign tables involved in the
     352              :  * truncation.
     353              :  */
     354              : typedef struct ForeignTruncateInfo
     355              : {
     356              :     Oid         serverid;
     357              :     List       *rels;
     358              : } ForeignTruncateInfo;
     359              : 
     360              : /* Partial or complete FK creation in addFkConstraint() */
     361              : typedef enum addFkConstraintSides
     362              : {
     363              :     addFkReferencedSide,
     364              :     addFkReferencingSide,
     365              :     addFkBothSides,
     366              : } addFkConstraintSides;
     367              : 
     368              : /*
     369              :  * Partition tables are expected to be dropped when the parent partitioned
     370              :  * table gets dropped. Hence for partitioning we use AUTO dependency.
     371              :  * Otherwise, for regular inheritance use NORMAL dependency.
     372              :  */
     373              : #define child_dependency_type(child_is_partition)   \
     374              :     ((child_is_partition) ? DEPENDENCY_AUTO : DEPENDENCY_NORMAL)
     375              : 
     376              : static void truncate_check_rel(Oid relid, Form_pg_class reltuple);
     377              : static void truncate_check_perms(Oid relid, Form_pg_class reltuple);
     378              : static void truncate_check_activity(Relation rel);
     379              : static void RangeVarCallbackForTruncate(const RangeVar *relation,
     380              :                                         Oid relId, Oid oldRelId, void *arg);
     381              : static List *MergeAttributes(List *columns, const List *supers, char relpersistence,
     382              :                              bool is_partition, List **supconstr,
     383              :                              List **supnotnulls);
     384              : static List *MergeCheckConstraint(List *constraints, const char *name, Node *expr, bool is_enforced);
     385              : static void MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const ColumnDef *newdef);
     386              : static ColumnDef *MergeInheritedAttribute(List *inh_columns, int exist_attno, const ColumnDef *newdef);
     387              : static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition);
     388              : static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel);
     389              : static void StoreCatalogInheritance(Oid relationId, List *supers,
     390              :                                     bool child_is_partition);
     391              : static void StoreCatalogInheritance1(Oid relationId, Oid parentOid,
     392              :                                      int32 seqNumber, Relation inhRelation,
     393              :                                      bool child_is_partition);
     394              : static int  findAttrByName(const char *attributeName, const List *columns);
     395              : static void AlterIndexNamespaces(Relation classRel, Relation rel,
     396              :                                  Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved);
     397              : static void AlterSeqNamespaces(Relation classRel, Relation rel,
     398              :                                Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved,
     399              :                                LOCKMODE lockmode);
     400              : static ObjectAddress ATExecAlterConstraint(List **wqueue, Relation rel,
     401              :                                            ATAlterConstraint *cmdcon,
     402              :                                            bool recurse, LOCKMODE lockmode);
     403              : static bool ATExecAlterConstraintInternal(List **wqueue, ATAlterConstraint *cmdcon, Relation conrel,
     404              :                                           Relation tgrel, Relation rel, HeapTuple contuple,
     405              :                                           bool recurse, LOCKMODE lockmode);
     406              : static bool ATExecAlterFKConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon,
     407              :                                               Relation conrel, Relation tgrel,
     408              :                                               Oid fkrelid, Oid pkrelid,
     409              :                                               HeapTuple contuple, LOCKMODE lockmode,
     410              :                                               Oid ReferencedParentDelTrigger,
     411              :                                               Oid ReferencedParentUpdTrigger,
     412              :                                               Oid ReferencingParentInsTrigger,
     413              :                                               Oid ReferencingParentUpdTrigger);
     414              : static bool ATExecAlterCheckConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon,
     415              :                                                  Relation conrel, HeapTuple contuple,
     416              :                                                  bool recurse, bool recursing,
     417              :                                                  LOCKMODE lockmode);
     418              : static bool ATExecAlterConstrDeferrability(List **wqueue, ATAlterConstraint *cmdcon,
     419              :                                            Relation conrel, Relation tgrel, Relation rel,
     420              :                                            HeapTuple contuple, bool recurse,
     421              :                                            List **otherrelids, LOCKMODE lockmode);
     422              : static bool ATExecAlterConstrInheritability(List **wqueue, ATAlterConstraint *cmdcon,
     423              :                                             Relation conrel, Relation rel,
     424              :                                             HeapTuple contuple, LOCKMODE lockmode);
     425              : static void AlterConstrTriggerDeferrability(Oid conoid, Relation tgrel, Relation rel,
     426              :                                             bool deferrable, bool initdeferred,
     427              :                                             List **otherrelids);
     428              : static void AlterFKConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
     429              :                                                Relation conrel, Relation tgrel,
     430              :                                                Oid fkrelid, Oid pkrelid,
     431              :                                                HeapTuple contuple, LOCKMODE lockmode,
     432              :                                                Oid ReferencedParentDelTrigger,
     433              :                                                Oid ReferencedParentUpdTrigger,
     434              :                                                Oid ReferencingParentInsTrigger,
     435              :                                                Oid ReferencingParentUpdTrigger);
     436              : static void AlterCheckConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
     437              :                                                   Relation conrel, Oid conrelid,
     438              :                                                   bool recurse, bool recursing,
     439              :                                                   LOCKMODE lockmode);
     440              : static void AlterConstrDeferrabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
     441              :                                             Relation conrel, Relation tgrel, Relation rel,
     442              :                                             HeapTuple contuple, bool recurse,
     443              :                                             List **otherrelids, LOCKMODE lockmode);
     444              : static void AlterConstrUpdateConstraintEntry(ATAlterConstraint *cmdcon, Relation conrel,
     445              :                                              HeapTuple contuple);
     446              : static ObjectAddress ATExecValidateConstraint(List **wqueue,
     447              :                                               Relation rel, char *constrName,
     448              :                                               bool recurse, bool recursing, LOCKMODE lockmode);
     449              : static void QueueFKConstraintValidation(List **wqueue, Relation conrel, Relation fkrel,
     450              :                                         Oid pkrelid, HeapTuple contuple, LOCKMODE lockmode);
     451              : static void QueueCheckConstraintValidation(List **wqueue, Relation conrel, Relation rel,
     452              :                                            char *constrName, HeapTuple contuple,
     453              :                                            bool recurse, bool recursing, LOCKMODE lockmode);
     454              : static void QueueNNConstraintValidation(List **wqueue, Relation conrel, Relation rel,
     455              :                                         HeapTuple contuple, bool recurse, bool recursing,
     456              :                                         LOCKMODE lockmode);
     457              : static int  transformColumnNameList(Oid relId, List *colList,
     458              :                                     int16 *attnums, Oid *atttypids, Oid *attcollids);
     459              : static int  transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
     460              :                                        List **attnamelist,
     461              :                                        int16 *attnums, Oid *atttypids, Oid *attcollids,
     462              :                                        Oid *opclasses, bool *pk_has_without_overlaps);
     463              : static Oid  transformFkeyCheckAttrs(Relation pkrel,
     464              :                                     int numattrs, int16 *attnums,
     465              :                                     bool with_period, Oid *opclasses,
     466              :                                     bool *pk_has_without_overlaps);
     467              : static void checkFkeyPermissions(Relation rel, int16 *attnums, int natts);
     468              : static CoercionPathType findFkeyCast(Oid targetTypeId, Oid sourceTypeId,
     469              :                                      Oid *funcid);
     470              : static void validateForeignKeyConstraint(char *conname,
     471              :                                          Relation rel, Relation pkrel,
     472              :                                          Oid pkindOid, Oid constraintOid, bool hasperiod);
     473              : static void CheckAlterTableIsSafe(Relation rel);
     474              : static void ATController(AlterTableStmt *parsetree,
     475              :                          Relation rel, List *cmds, bool recurse, LOCKMODE lockmode,
     476              :                          AlterTableUtilityContext *context);
     477              : static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
     478              :                       bool recurse, bool recursing, LOCKMODE lockmode,
     479              :                       AlterTableUtilityContext *context);
     480              : static void ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode,
     481              :                               AlterTableUtilityContext *context);
     482              : static void ATExecCmd(List **wqueue, AlteredTableInfo *tab,
     483              :                       AlterTableCmd *cmd, LOCKMODE lockmode, AlterTablePass cur_pass,
     484              :                       AlterTableUtilityContext *context);
     485              : static AlterTableCmd *ATParseTransformCmd(List **wqueue, AlteredTableInfo *tab,
     486              :                                           Relation rel, AlterTableCmd *cmd,
     487              :                                           bool recurse, LOCKMODE lockmode,
     488              :                                           AlterTablePass cur_pass,
     489              :                                           AlterTableUtilityContext *context);
     490              : static void ATRewriteTables(AlterTableStmt *parsetree,
     491              :                             List **wqueue, LOCKMODE lockmode,
     492              :                             AlterTableUtilityContext *context);
     493              : static void ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap);
     494              : static AlteredTableInfo *ATGetQueueEntry(List **wqueue, Relation rel);
     495              : static void ATSimplePermissions(AlterTableType cmdtype, Relation rel, int allowed_targets);
     496              : static void ATSimpleRecursion(List **wqueue, Relation rel,
     497              :                               AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode,
     498              :                               AlterTableUtilityContext *context);
     499              : static void ATCheckPartitionsNotInUse(Relation rel, LOCKMODE lockmode);
     500              : static void ATTypedTableRecursion(List **wqueue, Relation rel, AlterTableCmd *cmd,
     501              :                                   LOCKMODE lockmode,
     502              :                                   AlterTableUtilityContext *context);
     503              : static List *find_typed_table_dependencies(Oid typeOid, const char *typeName,
     504              :                                            DropBehavior behavior);
     505              : static void ATPrepAddColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
     506              :                             bool is_view, AlterTableCmd *cmd, LOCKMODE lockmode,
     507              :                             AlterTableUtilityContext *context);
     508              : static ObjectAddress ATExecAddColumn(List **wqueue, AlteredTableInfo *tab,
     509              :                                      Relation rel, AlterTableCmd **cmd,
     510              :                                      bool recurse, bool recursing,
     511              :                                      LOCKMODE lockmode, AlterTablePass cur_pass,
     512              :                                      AlterTableUtilityContext *context);
     513              : static bool check_for_column_name_collision(Relation rel, const char *colname,
     514              :                                             bool if_not_exists);
     515              : static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid);
     516              : static void add_column_collation_dependency(Oid relid, int32 attnum, Oid collid);
     517              : static ObjectAddress ATExecDropNotNull(Relation rel, const char *colName, bool recurse,
     518              :                                        LOCKMODE lockmode);
     519              : static void set_attnotnull(List **wqueue, Relation rel, AttrNumber attnum,
     520              :                            bool is_valid, bool queue_validation);
     521              : static ObjectAddress ATExecSetNotNull(List **wqueue, Relation rel,
     522              :                                       char *conName, char *colName,
     523              :                                       bool recurse, bool recursing,
     524              :                                       LOCKMODE lockmode);
     525              : static bool NotNullImpliedByRelConstraints(Relation rel, Form_pg_attribute attr);
     526              : static bool ConstraintImpliedByRelConstraint(Relation scanrel,
     527              :                                              List *testConstraint, List *provenConstraint);
     528              : static ObjectAddress ATExecColumnDefault(Relation rel, const char *colName,
     529              :                                          Node *newDefault, LOCKMODE lockmode);
     530              : static ObjectAddress ATExecCookedColumnDefault(Relation rel, AttrNumber attnum,
     531              :                                                Node *newDefault);
     532              : static ObjectAddress ATExecAddIdentity(Relation rel, const char *colName,
     533              :                                        Node *def, LOCKMODE lockmode, bool recurse, bool recursing);
     534              : static ObjectAddress ATExecSetIdentity(Relation rel, const char *colName,
     535              :                                        Node *def, LOCKMODE lockmode, bool recurse, bool recursing);
     536              : static ObjectAddress ATExecDropIdentity(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode,
     537              :                                         bool recurse, bool recursing);
     538              : static ObjectAddress ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName,
     539              :                                          Node *newExpr, LOCKMODE lockmode);
     540              : static void ATPrepDropExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode);
     541              : static ObjectAddress ATExecDropExpression(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode);
     542              : static ObjectAddress ATExecSetStatistics(Relation rel, const char *colName, int16 colNum,
     543              :                                          Node *newValue, LOCKMODE lockmode);
     544              : static ObjectAddress ATExecSetOptions(Relation rel, const char *colName,
     545              :                                       Node *options, bool isReset, LOCKMODE lockmode);
     546              : static ObjectAddress ATExecSetStorage(Relation rel, const char *colName,
     547              :                                       Node *newValue, LOCKMODE lockmode);
     548              : static void ATPrepDropColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
     549              :                              AlterTableCmd *cmd, LOCKMODE lockmode,
     550              :                              AlterTableUtilityContext *context);
     551              : static ObjectAddress ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
     552              :                                       DropBehavior behavior,
     553              :                                       bool recurse, bool recursing,
     554              :                                       bool missing_ok, LOCKMODE lockmode,
     555              :                                       ObjectAddresses *addrs);
     556              : static void ATPrepAddPrimaryKey(List **wqueue, Relation rel, AlterTableCmd *cmd,
     557              :                                 bool recurse, LOCKMODE lockmode,
     558              :                                 AlterTableUtilityContext *context);
     559              : static void verifyNotNullPKCompatible(HeapTuple tuple, const char *colname);
     560              : static ObjectAddress ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
     561              :                                     IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode);
     562              : static ObjectAddress ATExecAddStatistics(AlteredTableInfo *tab, Relation rel,
     563              :                                          CreateStatsStmt *stmt, bool is_rebuild, LOCKMODE lockmode);
     564              : static ObjectAddress ATExecAddConstraint(List **wqueue,
     565              :                                          AlteredTableInfo *tab, Relation rel,
     566              :                                          Constraint *newConstraint, bool recurse, bool is_readd,
     567              :                                          LOCKMODE lockmode);
     568              : static char *ChooseForeignKeyConstraintNameAddition(List *colnames);
     569              : static ObjectAddress ATExecAddIndexConstraint(AlteredTableInfo *tab, Relation rel,
     570              :                                               IndexStmt *stmt, LOCKMODE lockmode);
     571              : static ObjectAddress ATAddCheckNNConstraint(List **wqueue,
     572              :                                             AlteredTableInfo *tab, Relation rel,
     573              :                                             Constraint *constr,
     574              :                                             bool recurse, bool recursing, bool is_readd,
     575              :                                             LOCKMODE lockmode);
     576              : static ObjectAddress ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab,
     577              :                                                Relation rel, Constraint *fkconstraint,
     578              :                                                bool recurse, bool recursing,
     579              :                                                LOCKMODE lockmode);
     580              : static int  validateFkOnDeleteSetColumns(int numfks, const int16 *fkattnums,
     581              :                                          int numfksetcols, int16 *fksetcolsattnums,
     582              :                                          List *fksetcols);
     583              : static ObjectAddress addFkConstraint(addFkConstraintSides fkside,
     584              :                                      char *constraintname,
     585              :                                      Constraint *fkconstraint, Relation rel,
     586              :                                      Relation pkrel, Oid indexOid,
     587              :                                      Oid parentConstr,
     588              :                                      int numfks, int16 *pkattnum, int16 *fkattnum,
     589              :                                      Oid *pfeqoperators, Oid *ppeqoperators,
     590              :                                      Oid *ffeqoperators, int numfkdelsetcols,
     591              :                                      int16 *fkdelsetcols, bool is_internal,
     592              :                                      bool with_period);
     593              : static void addFkRecurseReferenced(Constraint *fkconstraint,
     594              :                                    Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr,
     595              :                                    int numfks, int16 *pkattnum, int16 *fkattnum,
     596              :                                    Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators,
     597              :                                    int numfkdelsetcols, int16 *fkdelsetcols,
     598              :                                    bool old_check_ok,
     599              :                                    Oid parentDelTrigger, Oid parentUpdTrigger,
     600              :                                    bool with_period);
     601              : static void addFkRecurseReferencing(List **wqueue, Constraint *fkconstraint,
     602              :                                     Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr,
     603              :                                     int numfks, int16 *pkattnum, int16 *fkattnum,
     604              :                                     Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators,
     605              :                                     int numfkdelsetcols, int16 *fkdelsetcols,
     606              :                                     bool old_check_ok, LOCKMODE lockmode,
     607              :                                     Oid parentInsTrigger, Oid parentUpdTrigger,
     608              :                                     bool with_period);
     609              : static void CloneForeignKeyConstraints(List **wqueue, Relation parentRel,
     610              :                                        Relation partitionRel);
     611              : static void CloneFkReferenced(Relation parentRel, Relation partitionRel);
     612              : static void CloneFkReferencing(List **wqueue, Relation parentRel,
     613              :                                Relation partRel);
     614              : static void createForeignKeyCheckTriggers(Oid myRelOid, Oid refRelOid,
     615              :                                           Constraint *fkconstraint, Oid constraintOid,
     616              :                                           Oid indexOid,
     617              :                                           Oid parentInsTrigger, Oid parentUpdTrigger,
     618              :                                           Oid *insertTrigOid, Oid *updateTrigOid);
     619              : static void createForeignKeyActionTriggers(Oid myRelOid, Oid refRelOid,
     620              :                                            Constraint *fkconstraint, Oid constraintOid,
     621              :                                            Oid indexOid,
     622              :                                            Oid parentDelTrigger, Oid parentUpdTrigger,
     623              :                                            Oid *deleteTrigOid, Oid *updateTrigOid);
     624              : static bool tryAttachPartitionForeignKey(List **wqueue,
     625              :                                          ForeignKeyCacheInfo *fk,
     626              :                                          Relation partition,
     627              :                                          Oid parentConstrOid, int numfks,
     628              :                                          AttrNumber *mapped_conkey, AttrNumber *confkey,
     629              :                                          Oid *conpfeqop,
     630              :                                          Oid parentInsTrigger,
     631              :                                          Oid parentUpdTrigger,
     632              :                                          Relation trigrel);
     633              : static void AttachPartitionForeignKey(List **wqueue, Relation partition,
     634              :                                       Oid partConstrOid, Oid parentConstrOid,
     635              :                                       Oid parentInsTrigger, Oid parentUpdTrigger,
     636              :                                       Relation trigrel);
     637              : static void RemoveInheritedConstraint(Relation conrel, Relation trigrel,
     638              :                                       Oid conoid, Oid conrelid);
     639              : static void DropForeignKeyConstraintTriggers(Relation trigrel, Oid conoid,
     640              :                                              Oid confrelid, Oid conrelid);
     641              : static void GetForeignKeyActionTriggers(Relation trigrel,
     642              :                                         Oid conoid, Oid confrelid, Oid conrelid,
     643              :                                         Oid *deleteTriggerOid,
     644              :                                         Oid *updateTriggerOid);
     645              : static void GetForeignKeyCheckTriggers(Relation trigrel,
     646              :                                        Oid conoid, Oid confrelid, Oid conrelid,
     647              :                                        Oid *insertTriggerOid,
     648              :                                        Oid *updateTriggerOid);
     649              : static void ATExecDropConstraint(Relation rel, const char *constrName,
     650              :                                  DropBehavior behavior, bool recurse,
     651              :                                  bool missing_ok, LOCKMODE lockmode);
     652              : static ObjectAddress dropconstraint_internal(Relation rel,
     653              :                                              HeapTuple constraintTup, DropBehavior behavior,
     654              :                                              bool recurse, bool recursing,
     655              :                                              bool missing_ok, LOCKMODE lockmode);
     656              : static void ATPrepAlterColumnType(List **wqueue,
     657              :                                   AlteredTableInfo *tab, Relation rel,
     658              :                                   bool recurse, bool recursing,
     659              :                                   AlterTableCmd *cmd, LOCKMODE lockmode,
     660              :                                   AlterTableUtilityContext *context);
     661              : static bool ATColumnChangeRequiresRewrite(Node *expr, AttrNumber varattno);
     662              : static ObjectAddress ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
     663              :                                            AlterTableCmd *cmd, LOCKMODE lockmode);
     664              : static void RememberAllDependentForRebuilding(AlteredTableInfo *tab, AlterTableType subtype,
     665              :                                               Relation rel, AttrNumber attnum, const char *colName);
     666              : static void RememberConstraintForRebuilding(Oid conoid, AlteredTableInfo *tab);
     667              : static void RememberIndexForRebuilding(Oid indoid, AlteredTableInfo *tab);
     668              : static void RememberStatisticsForRebuilding(Oid stxoid, AlteredTableInfo *tab);
     669              : static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab,
     670              :                                    LOCKMODE lockmode);
     671              : static void ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId,
     672              :                                  char *cmd, List **wqueue, LOCKMODE lockmode,
     673              :                                  bool rewrite);
     674              : static void RebuildConstraintComment(AlteredTableInfo *tab, AlterTablePass pass,
     675              :                                      Oid objid, Relation rel, List *domname,
     676              :                                      const char *conname);
     677              : static void TryReuseIndex(Oid oldId, IndexStmt *stmt);
     678              : static void TryReuseForeignKey(Oid oldId, Constraint *con);
     679              : static ObjectAddress ATExecAlterColumnGenericOptions(Relation rel, const char *colName,
     680              :                                                      List *options, LOCKMODE lockmode);
     681              : static void change_owner_fix_column_acls(Oid relationOid,
     682              :                                          Oid oldOwnerId, Oid newOwnerId);
     683              : static void change_owner_recurse_to_sequences(Oid relationOid,
     684              :                                               Oid newOwnerId, LOCKMODE lockmode);
     685              : static ObjectAddress ATExecClusterOn(Relation rel, const char *indexName,
     686              :                                      LOCKMODE lockmode);
     687              : static void ATExecDropCluster(Relation rel, LOCKMODE lockmode);
     688              : static void ATPrepSetAccessMethod(AlteredTableInfo *tab, Relation rel, const char *amname);
     689              : static void ATExecSetAccessMethodNoStorage(Relation rel, Oid newAccessMethodId);
     690              : static void ATPrepChangePersistence(AlteredTableInfo *tab, Relation rel,
     691              :                                     bool toLogged);
     692              : static void ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel,
     693              :                                 const char *tablespacename, LOCKMODE lockmode);
     694              : static void ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode);
     695              : static void ATExecSetTableSpaceNoStorage(Relation rel, Oid newTableSpace);
     696              : static void ATExecSetRelOptions(Relation rel, List *defList,
     697              :                                 AlterTableType operation,
     698              :                                 LOCKMODE lockmode);
     699              : static void ATExecEnableDisableTrigger(Relation rel, const char *trigname,
     700              :                                        char fires_when, bool skip_system, bool recurse,
     701              :                                        LOCKMODE lockmode);
     702              : static void ATExecEnableDisableRule(Relation rel, const char *rulename,
     703              :                                     char fires_when, LOCKMODE lockmode);
     704              : static void ATPrepChangeInherit(Relation child_rel);
     705              : static ObjectAddress ATExecAddInherit(Relation child_rel, RangeVar *parent, LOCKMODE lockmode);
     706              : static ObjectAddress ATExecDropInherit(Relation rel, RangeVar *parent, LOCKMODE lockmode);
     707              : static void drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid,
     708              :                                    DependencyType deptype);
     709              : static ObjectAddress ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode);
     710              : static void ATExecDropOf(Relation rel, LOCKMODE lockmode);
     711              : static void ATExecReplicaIdentity(Relation rel, ReplicaIdentityStmt *stmt, LOCKMODE lockmode);
     712              : static void ATExecGenericOptions(Relation rel, List *options);
     713              : static void ATExecSetRowSecurity(Relation rel, bool rls);
     714              : static void ATExecForceNoForceRowSecurity(Relation rel, bool force_rls);
     715              : static ObjectAddress ATExecSetCompression(Relation rel,
     716              :                                           const char *column, Node *newValue, LOCKMODE lockmode);
     717              : 
     718              : static void index_copy_data(Relation rel, RelFileLocator newrlocator);
     719              : static const char *storage_name(char c);
     720              : 
     721              : static void RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid,
     722              :                                             Oid oldRelOid, void *arg);
     723              : static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid,
     724              :                                              Oid oldrelid, void *arg);
     725              : static PartitionSpec *transformPartitionSpec(Relation rel, PartitionSpec *partspec);
     726              : static void ComputePartitionAttrs(ParseState *pstate, Relation rel, List *partParams, AttrNumber *partattrs,
     727              :                                   List **partexprs, Oid *partopclass, Oid *partcollation,
     728              :                                   PartitionStrategy strategy);
     729              : static void CreateInheritance(Relation child_rel, Relation parent_rel, bool ispartition);
     730              : static void RemoveInheritance(Relation child_rel, Relation parent_rel,
     731              :                               bool expect_detached);
     732              : static ObjectAddress ATExecAttachPartition(List **wqueue, Relation rel,
     733              :                                            PartitionCmd *cmd,
     734              :                                            AlterTableUtilityContext *context);
     735              : static void AttachPartitionEnsureIndexes(List **wqueue, Relation rel, Relation attachrel);
     736              : static void QueuePartitionConstraintValidation(List **wqueue, Relation scanrel,
     737              :                                                List *partConstraint,
     738              :                                                bool validate_default);
     739              : static void CloneRowTriggersToPartition(Relation parent, Relation partition);
     740              : static void DropClonedTriggersFromPartition(Oid partitionId);
     741              : static ObjectAddress ATExecDetachPartition(List **wqueue, AlteredTableInfo *tab,
     742              :                                            Relation rel, RangeVar *name,
     743              :                                            bool concurrent);
     744              : static void DetachPartitionFinalize(Relation rel, Relation partRel,
     745              :                                     bool concurrent, Oid defaultPartOid);
     746              : static ObjectAddress ATExecDetachPartitionFinalize(Relation rel, RangeVar *name);
     747              : static ObjectAddress ATExecAttachPartitionIdx(List **wqueue, Relation parentIdx,
     748              :                                               RangeVar *name);
     749              : static void validatePartitionedIndex(Relation partedIdx, Relation partedTbl);
     750              : static void refuseDupeIndexAttach(Relation parentIdx, Relation partIdx,
     751              :                                   Relation partitionTbl);
     752              : static void verifyPartitionIndexNotNull(IndexInfo *iinfo, Relation partition);
     753              : static List *GetParentedForeignKeyRefs(Relation partition);
     754              : static void ATDetachCheckNoForeignKeyRefs(Relation partition);
     755              : static char GetAttributeCompression(Oid atttypid, const char *compression);
     756              : static char GetAttributeStorage(Oid atttypid, const char *storagemode);
     757              : 
     758              : static void ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel,
     759              :                                   PartitionCmd *cmd, AlterTableUtilityContext *context);
     760              : static void ATExecSplitPartition(List **wqueue, AlteredTableInfo *tab,
     761              :                                  Relation rel, PartitionCmd *cmd,
     762              :                                  AlterTableUtilityContext *context);
     763              : 
     764              : /* ----------------------------------------------------------------
     765              :  *      DefineRelation
     766              :  *              Creates a new relation.
     767              :  *
     768              :  * stmt carries parsetree information from an ordinary CREATE TABLE statement.
     769              :  * The other arguments are used to extend the behavior for other cases:
     770              :  * relkind: relkind to assign to the new relation
     771              :  * ownerId: if not InvalidOid, use this as the new relation's owner.
     772              :  * typaddress: if not null, it's set to the pg_type entry's address.
     773              :  * queryString: for error reporting
     774              :  *
     775              :  * Note that permissions checks are done against current user regardless of
     776              :  * ownerId.  A nonzero ownerId is used when someone is creating a relation
     777              :  * "on behalf of" someone else, so we still want to see that the current user
     778              :  * has permissions to do it.
     779              :  *
     780              :  * If successful, returns the address of the new relation.
     781              :  * ----------------------------------------------------------------
     782              :  */
     783              : ObjectAddress
     784        39800 : DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId,
     785              :                ObjectAddress *typaddress, const char *queryString)
     786              : {
     787              :     char        relname[NAMEDATALEN];
     788              :     Oid         namespaceId;
     789              :     Oid         relationId;
     790              :     Oid         tablespaceId;
     791              :     Relation    rel;
     792              :     TupleDesc   descriptor;
     793              :     List       *inheritOids;
     794              :     List       *old_constraints;
     795              :     List       *old_notnulls;
     796              :     List       *rawDefaults;
     797              :     List       *cookedDefaults;
     798              :     List       *nncols;
     799        39800 :     List       *connames = NIL;
     800              :     Datum       reloptions;
     801              :     ListCell   *listptr;
     802              :     AttrNumber  attnum;
     803              :     bool        partitioned;
     804        39800 :     const char *const validnsps[] = HEAP_RELOPT_NAMESPACES;
     805              :     Oid         ofTypeId;
     806              :     ObjectAddress address;
     807              :     LOCKMODE    parentLockmode;
     808        39800 :     Oid         accessMethodId = InvalidOid;
     809              : 
     810              :     /*
     811              :      * Truncate relname to appropriate length (probably a waste of time, as
     812              :      * parser should have done this already).
     813              :      */
     814        39800 :     strlcpy(relname, stmt->relation->relname, NAMEDATALEN);
     815              : 
     816              :     /*
     817              :      * Check consistency of arguments
     818              :      */
     819        39800 :     if (stmt->oncommit != ONCOMMIT_NOOP
     820          128 :         && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
     821            8 :         ereport(ERROR,
     822              :                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
     823              :                  errmsg("ON COMMIT can only be used on temporary tables")));
     824              : 
     825        39792 :     if (stmt->partspec != NULL)
     826              :     {
     827         3558 :         if (relkind != RELKIND_RELATION)
     828            0 :             elog(ERROR, "unexpected relkind: %d", (int) relkind);
     829              : 
     830         3558 :         relkind = RELKIND_PARTITIONED_TABLE;
     831         3558 :         partitioned = true;
     832              :     }
     833              :     else
     834        36234 :         partitioned = false;
     835              : 
     836        39792 :     if (relkind == RELKIND_PARTITIONED_TABLE &&
     837         3558 :         stmt->relation->relpersistence == RELPERSISTENCE_UNLOGGED)
     838            4 :         ereport(ERROR,
     839              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     840              :                  errmsg("partitioned tables cannot be unlogged")));
     841              : 
     842              :     /*
     843              :      * Look up the namespace in which we are supposed to create the relation,
     844              :      * check we have permission to create there, lock it against concurrent
     845              :      * drop, and mark stmt->relation as RELPERSISTENCE_TEMP if a temporary
     846              :      * namespace is selected.
     847              :      */
     848              :     namespaceId =
     849        39788 :         RangeVarGetAndCheckCreationNamespace(stmt->relation, NoLock, NULL);
     850              : 
     851              :     /*
     852              :      * Security check: disallow creating temp tables from security-restricted
     853              :      * code.  This is needed because calling code might not expect untrusted
     854              :      * tables to appear in pg_temp at the front of its search path.
     855              :      */
     856        39788 :     if (stmt->relation->relpersistence == RELPERSISTENCE_TEMP
     857         2294 :         && InSecurityRestrictedOperation())
     858            0 :         ereport(ERROR,
     859              :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     860              :                  errmsg("cannot create temporary table within security-restricted operation")));
     861              : 
     862              :     /*
     863              :      * Determine the lockmode to use when scanning parents.  A self-exclusive
     864              :      * lock is needed here.
     865              :      *
     866              :      * For regular inheritance, if two backends attempt to add children to the
     867              :      * same parent simultaneously, and that parent has no pre-existing
     868              :      * children, then both will attempt to update the parent's relhassubclass
     869              :      * field, leading to a "tuple concurrently updated" error.  Also, this
     870              :      * interlocks against a concurrent ANALYZE on the parent table, which
     871              :      * might otherwise be attempting to clear the parent's relhassubclass
     872              :      * field, if its previous children were recently dropped.
     873              :      *
     874              :      * If the child table is a partition, then we instead grab an exclusive
     875              :      * lock on the parent because its partition descriptor will be changed by
     876              :      * addition of the new partition.
     877              :      */
     878        39788 :     parentLockmode = (stmt->partbound != NULL ? AccessExclusiveLock :
     879              :                       ShareUpdateExclusiveLock);
     880              : 
     881              :     /* Determine the list of OIDs of the parents. */
     882        39788 :     inheritOids = NIL;
     883        47560 :     foreach(listptr, stmt->inhRelations)
     884              :     {
     885         7772 :         RangeVar   *rv = (RangeVar *) lfirst(listptr);
     886              :         Oid         parentOid;
     887              : 
     888         7772 :         parentOid = RangeVarGetRelid(rv, parentLockmode, false);
     889              : 
     890              :         /*
     891              :          * Reject duplications in the list of parents.
     892              :          */
     893         7772 :         if (list_member_oid(inheritOids, parentOid))
     894            0 :             ereport(ERROR,
     895              :                     (errcode(ERRCODE_DUPLICATE_TABLE),
     896              :                      errmsg("relation \"%s\" would be inherited from more than once",
     897              :                             get_rel_name(parentOid))));
     898              : 
     899         7772 :         inheritOids = lappend_oid(inheritOids, parentOid);
     900              :     }
     901              : 
     902              :     /*
     903              :      * Select tablespace to use: an explicitly indicated one, or (in the case
     904              :      * of a partitioned table) the parent's, if it has one.
     905              :      */
     906        39788 :     if (stmt->tablespacename)
     907              :     {
     908           85 :         tablespaceId = get_tablespace_oid(stmt->tablespacename, false);
     909              : 
     910           81 :         if (partitioned && tablespaceId == MyDatabaseTableSpace)
     911            4 :             ereport(ERROR,
     912              :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     913              :                      errmsg("cannot specify default tablespace for partitioned relations")));
     914              :     }
     915        39703 :     else if (stmt->partbound)
     916              :     {
     917              :         Assert(list_length(inheritOids) == 1);
     918         6135 :         tablespaceId = get_rel_tablespace(linitial_oid(inheritOids));
     919              :     }
     920              :     else
     921        33568 :         tablespaceId = InvalidOid;
     922              : 
     923              :     /* still nothing? use the default */
     924        39780 :     if (!OidIsValid(tablespaceId))
     925        39677 :         tablespaceId = GetDefaultTablespace(stmt->relation->relpersistence,
     926              :                                             partitioned);
     927              : 
     928              :     /* Check permissions except when using database's default */
     929        39776 :     if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
     930              :     {
     931              :         AclResult   aclresult;
     932              : 
     933          119 :         aclresult = object_aclcheck(TableSpaceRelationId, tablespaceId, GetUserId(),
     934              :                                     ACL_CREATE);
     935          119 :         if (aclresult != ACLCHECK_OK)
     936            4 :             aclcheck_error(aclresult, OBJECT_TABLESPACE,
     937            4 :                            get_tablespace_name(tablespaceId));
     938              :     }
     939              : 
     940              :     /* In all cases disallow placing user relations in pg_global */
     941        39772 :     if (tablespaceId == GLOBALTABLESPACE_OID)
     942           12 :         ereport(ERROR,
     943              :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     944              :                  errmsg("only shared relations can be placed in pg_global tablespace")));
     945              : 
     946              :     /* Identify user ID that will own the table */
     947        39760 :     if (!OidIsValid(ownerId))
     948        39605 :         ownerId = GetUserId();
     949              : 
     950              :     /*
     951              :      * Parse and validate reloptions, if any.
     952              :      */
     953        39760 :     reloptions = transformRelOptions((Datum) 0, stmt->options, NULL, validnsps,
     954              :                                      true, false);
     955              : 
     956        39748 :     switch (relkind)
     957              :     {
     958         9640 :         case RELKIND_VIEW:
     959         9640 :             (void) view_reloptions(reloptions, true);
     960         9628 :             break;
     961         3542 :         case RELKIND_PARTITIONED_TABLE:
     962         3542 :             (void) partitioned_table_reloptions(reloptions, true);
     963         3538 :             break;
     964        26566 :         default:
     965        26566 :             (void) heap_reloptions(relkind, reloptions, true);
     966              :     }
     967              : 
     968        39668 :     if (stmt->ofTypename)
     969              :     {
     970              :         AclResult   aclresult;
     971              : 
     972           57 :         ofTypeId = typenameTypeId(NULL, stmt->ofTypename);
     973              : 
     974           57 :         aclresult = object_aclcheck(TypeRelationId, ofTypeId, GetUserId(), ACL_USAGE);
     975           57 :         if (aclresult != ACLCHECK_OK)
     976            4 :             aclcheck_error_type(aclresult, ofTypeId);
     977              :     }
     978              :     else
     979        39611 :         ofTypeId = InvalidOid;
     980              : 
     981              :     /*
     982              :      * Look up inheritance ancestors and generate relation schema, including
     983              :      * inherited attributes.  (Note that stmt->tableElts is destructively
     984              :      * modified by MergeAttributes.)
     985              :      */
     986        39504 :     stmt->tableElts =
     987        39664 :         MergeAttributes(stmt->tableElts, inheritOids,
     988        39664 :                         stmt->relation->relpersistence,
     989        39664 :                         stmt->partbound != NULL,
     990              :                         &old_constraints, &old_notnulls);
     991              : 
     992              :     /*
     993              :      * Create a tuple descriptor from the relation schema.  Note that this
     994              :      * deals with column names, types, and in-descriptor NOT NULL flags, but
     995              :      * not default values, NOT NULL or CHECK constraints; we handle those
     996              :      * below.
     997              :      */
     998        39504 :     descriptor = BuildDescForRelation(stmt->tableElts);
     999              : 
    1000              :     /*
    1001              :      * Find columns with default values and prepare for insertion of the
    1002              :      * defaults.  Pre-cooked (that is, inherited) defaults go into a list of
    1003              :      * CookedConstraint structs that we'll pass to heap_create_with_catalog,
    1004              :      * while raw defaults go into a list of RawColumnDefault structs that will
    1005              :      * be processed by AddRelationNewConstraints.  (We can't deal with raw
    1006              :      * expressions until we can do transformExpr.)
    1007              :      */
    1008        39472 :     rawDefaults = NIL;
    1009        39472 :     cookedDefaults = NIL;
    1010        39472 :     attnum = 0;
    1011              : 
    1012       192381 :     foreach(listptr, stmt->tableElts)
    1013              :     {
    1014       152909 :         ColumnDef  *colDef = lfirst(listptr);
    1015              : 
    1016       152909 :         attnum++;
    1017       152909 :         if (colDef->raw_default != NULL)
    1018              :         {
    1019              :             RawColumnDefault *rawEnt;
    1020              : 
    1021              :             Assert(colDef->cooked_default == NULL);
    1022              : 
    1023         2120 :             rawEnt = palloc_object(RawColumnDefault);
    1024         2120 :             rawEnt->attnum = attnum;
    1025         2120 :             rawEnt->raw_default = colDef->raw_default;
    1026         2120 :             rawEnt->generated = colDef->generated;
    1027         2120 :             rawDefaults = lappend(rawDefaults, rawEnt);
    1028              :         }
    1029       150789 :         else if (colDef->cooked_default != NULL)
    1030              :         {
    1031              :             CookedConstraint *cooked;
    1032              : 
    1033          338 :             cooked = palloc_object(CookedConstraint);
    1034          338 :             cooked->contype = CONSTR_DEFAULT;
    1035          338 :             cooked->conoid = InvalidOid; /* until created */
    1036          338 :             cooked->name = NULL;
    1037          338 :             cooked->attnum = attnum;
    1038          338 :             cooked->expr = colDef->cooked_default;
    1039          338 :             cooked->is_enforced = true;
    1040          338 :             cooked->skip_validation = false;
    1041          338 :             cooked->is_local = true; /* not used for defaults */
    1042          338 :             cooked->inhcount = 0;    /* ditto */
    1043          338 :             cooked->is_no_inherit = false;
    1044          338 :             cookedDefaults = lappend(cookedDefaults, cooked);
    1045              :         }
    1046              :     }
    1047              : 
    1048        39472 :     TupleDescFinalize(descriptor);
    1049              : 
    1050              :     /*
    1051              :      * For relations with table AM and partitioned tables, select access
    1052              :      * method to use: an explicitly indicated one, or (in the case of a
    1053              :      * partitioned table) the parent's, if it has one.
    1054              :      */
    1055        39472 :     if (stmt->accessMethod != NULL)
    1056              :     {
    1057              :         Assert(RELKIND_HAS_TABLE_AM(relkind) || relkind == RELKIND_PARTITIONED_TABLE);
    1058           87 :         accessMethodId = get_table_am_oid(stmt->accessMethod, false);
    1059              :     }
    1060        39385 :     else if (RELKIND_HAS_TABLE_AM(relkind) || relkind == RELKIND_PARTITIONED_TABLE)
    1061              :     {
    1062        25760 :         if (stmt->partbound)
    1063              :         {
    1064              :             Assert(list_length(inheritOids) == 1);
    1065         6021 :             accessMethodId = get_rel_relam(linitial_oid(inheritOids));
    1066              :         }
    1067              : 
    1068        25760 :         if (RELKIND_HAS_TABLE_AM(relkind) && !OidIsValid(accessMethodId))
    1069        22209 :             accessMethodId = get_table_am_oid(default_table_access_method, false);
    1070              :     }
    1071              : 
    1072              :     /*
    1073              :      * Create the relation.  Inherited defaults and CHECK constraints are
    1074              :      * passed in for immediate handling --- since they don't need parsing,
    1075              :      * they can be stored immediately.
    1076              :      */
    1077        39460 :     relationId = heap_create_with_catalog(relname,
    1078              :                                           namespaceId,
    1079              :                                           tablespaceId,
    1080              :                                           InvalidOid,
    1081              :                                           InvalidOid,
    1082              :                                           ofTypeId,
    1083              :                                           ownerId,
    1084              :                                           accessMethodId,
    1085              :                                           descriptor,
    1086              :                                           list_concat(cookedDefaults,
    1087              :                                                       old_constraints),
    1088              :                                           relkind,
    1089        39460 :                                           stmt->relation->relpersistence,
    1090              :                                           false,
    1091              :                                           false,
    1092              :                                           stmt->oncommit,
    1093              :                                           reloptions,
    1094              :                                           true,
    1095              :                                           allowSystemTableMods,
    1096              :                                           false,
    1097              :                                           InvalidOid,
    1098              :                                           typaddress);
    1099              : 
    1100              :     /*
    1101              :      * We must bump the command counter to make the newly-created relation
    1102              :      * tuple visible for opening.
    1103              :      */
    1104        39425 :     CommandCounterIncrement();
    1105              : 
    1106              :     /*
    1107              :      * Open the new relation and acquire exclusive lock on it.  This isn't
    1108              :      * really necessary for locking out other backends (since they can't see
    1109              :      * the new rel anyway until we commit), but it keeps the lock manager from
    1110              :      * complaining about deadlock risks.
    1111              :      */
    1112        39425 :     rel = relation_open(relationId, AccessExclusiveLock);
    1113              : 
    1114              :     /*
    1115              :      * Now add any newly specified column default and generation expressions
    1116              :      * to the new relation.  These are passed to us in the form of raw
    1117              :      * parsetrees; we need to transform them to executable expression trees
    1118              :      * before they can be added. The most convenient way to do that is to
    1119              :      * apply the parser's transformExpr routine, but transformExpr doesn't
    1120              :      * work unless we have a pre-existing relation. So, the transformation has
    1121              :      * to be postponed to this final step of CREATE TABLE.
    1122              :      *
    1123              :      * This needs to be before processing the partitioning clauses because
    1124              :      * those could refer to generated columns.
    1125              :      */
    1126        39425 :     if (rawDefaults)
    1127         1790 :         AddRelationNewConstraints(rel, rawDefaults, NIL,
    1128              :                                   true, true, false, queryString);
    1129              : 
    1130              :     /*
    1131              :      * Make column generation expressions visible for use by partitioning.
    1132              :      */
    1133        39297 :     CommandCounterIncrement();
    1134              : 
    1135              :     /* Process and store partition bound, if any. */
    1136        39297 :     if (stmt->partbound)
    1137              :     {
    1138              :         PartitionBoundSpec *bound;
    1139              :         ParseState *pstate;
    1140         6083 :         Oid         parentId = linitial_oid(inheritOids),
    1141              :                     defaultPartOid;
    1142              :         Relation    parent,
    1143         6083 :                     defaultRel = NULL;
    1144              :         ParseNamespaceItem *nsitem;
    1145              : 
    1146              :         /* Already have strong enough lock on the parent */
    1147         6083 :         parent = table_open(parentId, NoLock);
    1148              : 
    1149              :         /*
    1150              :          * We are going to try to validate the partition bound specification
    1151              :          * against the partition key of parentRel, so it better have one.
    1152              :          */
    1153         6083 :         if (parent->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
    1154           12 :             ereport(ERROR,
    1155              :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1156              :                      errmsg("\"%s\" is not partitioned",
    1157              :                             RelationGetRelationName(parent))));
    1158              : 
    1159              :         /*
    1160              :          * The partition constraint of the default partition depends on the
    1161              :          * partition bounds of every other partition. It is possible that
    1162              :          * another backend might be about to execute a query on the default
    1163              :          * partition table, and that the query relies on previously cached
    1164              :          * default partition constraints. We must therefore take a table lock
    1165              :          * strong enough to prevent all queries on the default partition from
    1166              :          * proceeding until we commit and send out a shared-cache-inval notice
    1167              :          * that will make them update their index lists.
    1168              :          *
    1169              :          * Order of locking: The relation being added won't be visible to
    1170              :          * other backends until it is committed, hence here in
    1171              :          * DefineRelation() the order of locking the default partition and the
    1172              :          * relation being added does not matter. But at all other places we
    1173              :          * need to lock the default relation before we lock the relation being
    1174              :          * added or removed i.e. we should take the lock in same order at all
    1175              :          * the places such that lock parent, lock default partition and then
    1176              :          * lock the partition so as to avoid a deadlock.
    1177              :          */
    1178              :         defaultPartOid =
    1179         6071 :             get_default_oid_from_partdesc(RelationGetPartitionDesc(parent,
    1180              :                                                                    true));
    1181         6071 :         if (OidIsValid(defaultPartOid))
    1182          251 :             defaultRel = table_open(defaultPartOid, AccessExclusiveLock);
    1183              : 
    1184              :         /* Transform the bound values */
    1185         6071 :         pstate = make_parsestate(NULL);
    1186         6071 :         pstate->p_sourcetext = queryString;
    1187              : 
    1188              :         /*
    1189              :          * Add an nsitem containing this relation, so that transformExpr
    1190              :          * called on partition bound expressions is able to report errors
    1191              :          * using a proper context.
    1192              :          */
    1193         6071 :         nsitem = addRangeTableEntryForRelation(pstate, rel, AccessShareLock,
    1194              :                                                NULL, false, false);
    1195         6071 :         addNSItemToQuery(pstate, nsitem, false, true, true);
    1196              : 
    1197         6071 :         bound = transformPartitionBound(pstate, parent, stmt->partbound);
    1198              : 
    1199              :         /*
    1200              :          * Check first that the new partition's bound is valid and does not
    1201              :          * overlap with any of existing partitions of the parent.
    1202              :          */
    1203         5935 :         check_new_partition_bound(relname, parent, bound, pstate);
    1204              : 
    1205              :         /*
    1206              :          * If the default partition exists, its partition constraints will
    1207              :          * change after the addition of this new partition such that it won't
    1208              :          * allow any row that qualifies for this new partition. So, check that
    1209              :          * the existing data in the default partition satisfies the constraint
    1210              :          * as it will exist after adding this partition.
    1211              :          */
    1212         5859 :         if (OidIsValid(defaultPartOid))
    1213              :         {
    1214          231 :             check_default_partition_contents(parent, defaultRel, bound);
    1215              :             /* Keep the lock until commit. */
    1216          219 :             table_close(defaultRel, NoLock);
    1217              :         }
    1218              : 
    1219              :         /* Update the pg_class entry. */
    1220         5847 :         StorePartitionBound(rel, parent, bound);
    1221              : 
    1222         5847 :         table_close(parent, NoLock);
    1223              :     }
    1224              : 
    1225              :     /* Store inheritance information for new rel. */
    1226        39061 :     StoreCatalogInheritance(relationId, inheritOids, stmt->partbound != NULL);
    1227              : 
    1228              :     /*
    1229              :      * Process the partitioning specification (if any) and store the partition
    1230              :      * key information into the catalog.
    1231              :      */
    1232        39061 :     if (partitioned)
    1233              :     {
    1234              :         ParseState *pstate;
    1235              :         int         partnatts;
    1236              :         AttrNumber  partattrs[PARTITION_MAX_KEYS];
    1237              :         Oid         partopclass[PARTITION_MAX_KEYS];
    1238              :         Oid         partcollation[PARTITION_MAX_KEYS];
    1239         3538 :         List       *partexprs = NIL;
    1240              : 
    1241         3538 :         pstate = make_parsestate(NULL);
    1242         3538 :         pstate->p_sourcetext = queryString;
    1243              : 
    1244         3538 :         partnatts = list_length(stmt->partspec->partParams);
    1245              : 
    1246              :         /* Protect fixed-size arrays here and in executor */
    1247         3538 :         if (partnatts > PARTITION_MAX_KEYS)
    1248            0 :             ereport(ERROR,
    1249              :                     (errcode(ERRCODE_TOO_MANY_COLUMNS),
    1250              :                      errmsg("cannot partition using more than %d columns",
    1251              :                             PARTITION_MAX_KEYS)));
    1252              : 
    1253              :         /*
    1254              :          * We need to transform the raw parsetrees corresponding to partition
    1255              :          * expressions into executable expression trees.  Like column defaults
    1256              :          * and CHECK constraints, we could not have done the transformation
    1257              :          * earlier.
    1258              :          */
    1259         3538 :         stmt->partspec = transformPartitionSpec(rel, stmt->partspec);
    1260              : 
    1261         3518 :         ComputePartitionAttrs(pstate, rel, stmt->partspec->partParams,
    1262              :                               partattrs, &partexprs, partopclass,
    1263         3518 :                               partcollation, stmt->partspec->strategy);
    1264              : 
    1265         3430 :         StorePartitionKey(rel, stmt->partspec->strategy, partnatts, partattrs,
    1266              :                           partexprs,
    1267              :                           partopclass, partcollation);
    1268              : 
    1269              :         /* make it all visible */
    1270         3430 :         CommandCounterIncrement();
    1271              :     }
    1272              : 
    1273              :     /*
    1274              :      * If we're creating a partition, create now all the indexes, triggers,
    1275              :      * FKs defined in the parent.
    1276              :      *
    1277              :      * We can't do it earlier, because DefineIndex wants to know the partition
    1278              :      * key which we just stored.
    1279              :      */
    1280        38953 :     if (stmt->partbound)
    1281              :     {
    1282         5843 :         Oid         parentId = linitial_oid(inheritOids);
    1283              :         Relation    parent;
    1284              :         List       *idxlist;
    1285              :         ListCell   *cell;
    1286              : 
    1287              :         /* Already have strong enough lock on the parent */
    1288         5843 :         parent = table_open(parentId, NoLock);
    1289         5843 :         idxlist = RelationGetIndexList(parent);
    1290              : 
    1291              :         /*
    1292              :          * For each index in the parent table, create one in the partition
    1293              :          */
    1294         6916 :         foreach(cell, idxlist)
    1295              :         {
    1296         1085 :             Relation    idxRel = index_open(lfirst_oid(cell), AccessShareLock);
    1297              :             AttrMap    *attmap;
    1298              :             IndexStmt  *idxstmt;
    1299              :             Oid         constraintOid;
    1300              : 
    1301         1085 :             if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
    1302              :             {
    1303           24 :                 if (idxRel->rd_index->indisunique)
    1304            8 :                     ereport(ERROR,
    1305              :                             (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    1306              :                              errmsg("cannot create foreign partition of partitioned table \"%s\"",
    1307              :                                     RelationGetRelationName(parent)),
    1308              :                              errdetail("Table \"%s\" contains indexes that are unique.",
    1309              :                                        RelationGetRelationName(parent))));
    1310              :                 else
    1311              :                 {
    1312           16 :                     index_close(idxRel, AccessShareLock);
    1313           16 :                     continue;
    1314              :                 }
    1315              :             }
    1316              : 
    1317         1061 :             attmap = build_attrmap_by_name(RelationGetDescr(rel),
    1318              :                                            RelationGetDescr(parent),
    1319              :                                            false);
    1320              :             idxstmt =
    1321         1061 :                 generateClonedIndexStmt(NULL, idxRel,
    1322              :                                         attmap, &constraintOid);
    1323         1061 :             DefineIndex(NULL,
    1324              :                         RelationGetRelid(rel),
    1325              :                         idxstmt,
    1326              :                         InvalidOid,
    1327              :                         RelationGetRelid(idxRel),
    1328              :                         constraintOid,
    1329              :                         -1,
    1330              :                         false, false, false, false, false);
    1331              : 
    1332         1057 :             index_close(idxRel, AccessShareLock);
    1333              :         }
    1334              : 
    1335         5831 :         list_free(idxlist);
    1336              : 
    1337              :         /*
    1338              :          * If there are any row-level triggers, clone them to the new
    1339              :          * partition.
    1340              :          */
    1341         5831 :         if (parent->trigdesc != NULL)
    1342          316 :             CloneRowTriggersToPartition(parent, rel);
    1343              : 
    1344              :         /*
    1345              :          * And foreign keys too.  Note that because we're freshly creating the
    1346              :          * table, there is no need to verify these new constraints.
    1347              :          */
    1348         5831 :         CloneForeignKeyConstraints(NULL, parent, rel);
    1349              : 
    1350         5831 :         table_close(parent, NoLock);
    1351              :     }
    1352              : 
    1353              :     /*
    1354              :      * Now add any newly specified CHECK constraints to the new relation. Same
    1355              :      * as for defaults above, but these need to come after partitioning is set
    1356              :      * up.  We save the constraint names that were used, to avoid dupes below.
    1357              :      */
    1358        38941 :     if (stmt->constraints)
    1359              :     {
    1360              :         List       *conlist;
    1361              : 
    1362          498 :         conlist = AddRelationNewConstraints(rel, NIL, stmt->constraints,
    1363              :                                             true, true, false, queryString);
    1364         1509 :         foreach_ptr(CookedConstraint, cons, conlist)
    1365              :         {
    1366          553 :             if (cons->name != NULL)
    1367          553 :                 connames = lappend(connames, cons->name);
    1368              :         }
    1369              :     }
    1370              : 
    1371              :     /*
    1372              :      * Finally, merge the not-null constraints that are declared directly with
    1373              :      * those that come from parent relations (making sure to count inheritance
    1374              :      * appropriately for each), create them, and set the attnotnull flag on
    1375              :      * columns that don't yet have it.
    1376              :      */
    1377        38921 :     nncols = AddRelationNotNullConstraints(rel, stmt->nnconstraints,
    1378              :                                            old_notnulls, connames);
    1379        87281 :     foreach_int(attrnum, nncols)
    1380         9543 :         set_attnotnull(NULL, rel, attrnum, true, false);
    1381              : 
    1382        38869 :     ObjectAddressSet(address, RelationRelationId, relationId);
    1383              : 
    1384              :     /*
    1385              :      * Clean up.  We keep lock on new relation (although it shouldn't be
    1386              :      * visible to anyone else anyway, until commit).
    1387              :      */
    1388        38869 :     relation_close(rel, NoLock);
    1389              : 
    1390        38869 :     return address;
    1391              : }
    1392              : 
    1393              : /*
    1394              :  * BuildDescForRelation
    1395              :  *
    1396              :  * Given a list of ColumnDef nodes, build a TupleDesc.
    1397              :  *
    1398              :  * Note: This is only for the limited purpose of table and view creation.  Not
    1399              :  * everything is filled in.  A real tuple descriptor should be obtained from
    1400              :  * the relcache.
    1401              :  */
    1402              : TupleDesc
    1403        42036 : BuildDescForRelation(const List *columns)
    1404              : {
    1405              :     int         natts;
    1406              :     AttrNumber  attnum;
    1407              :     ListCell   *l;
    1408              :     TupleDesc   desc;
    1409              :     char       *attname;
    1410              :     Oid         atttypid;
    1411              :     int32       atttypmod;
    1412              :     Oid         attcollation;
    1413              :     int         attdim;
    1414              : 
    1415              :     /*
    1416              :      * allocate a new tuple descriptor
    1417              :      */
    1418        42036 :     natts = list_length(columns);
    1419        42036 :     desc = CreateTemplateTupleDesc(natts);
    1420              : 
    1421        42036 :     attnum = 0;
    1422              : 
    1423       198402 :     foreach(l, columns)
    1424              :     {
    1425       156406 :         ColumnDef  *entry = lfirst(l);
    1426              :         AclResult   aclresult;
    1427              :         Form_pg_attribute att;
    1428              : 
    1429              :         /*
    1430              :          * for each entry in the list, get the name and type information from
    1431              :          * the list and have TupleDescInitEntry fill in the attribute
    1432              :          * information we need.
    1433              :          */
    1434       156406 :         attnum++;
    1435              : 
    1436       156406 :         attname = entry->colname;
    1437       156406 :         typenameTypeIdAndMod(NULL, entry->typeName, &atttypid, &atttypmod);
    1438              : 
    1439       156406 :         aclresult = object_aclcheck(TypeRelationId, atttypid, GetUserId(), ACL_USAGE);
    1440       156406 :         if (aclresult != ACLCHECK_OK)
    1441           28 :             aclcheck_error_type(aclresult, atttypid);
    1442              : 
    1443       156378 :         attcollation = GetColumnDefCollation(NULL, entry, atttypid);
    1444       156378 :         attdim = list_length(entry->typeName->arrayBounds);
    1445       156378 :         if (attdim > PG_INT16_MAX)
    1446            0 :             ereport(ERROR,
    1447              :                     errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    1448              :                     errmsg("too many array dimensions"));
    1449              : 
    1450       156378 :         if (entry->typeName->setof)
    1451            0 :             ereport(ERROR,
    1452              :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    1453              :                      errmsg("column \"%s\" cannot be declared SETOF",
    1454              :                             attname)));
    1455              : 
    1456       156378 :         TupleDescInitEntry(desc, attnum, attname,
    1457              :                            atttypid, atttypmod, attdim);
    1458       156378 :         att = TupleDescAttr(desc, attnum - 1);
    1459              : 
    1460              :         /* Override TupleDescInitEntry's settings as requested */
    1461       156378 :         TupleDescInitEntryCollation(desc, attnum, attcollation);
    1462              : 
    1463              :         /* Fill in additional stuff not handled by TupleDescInitEntry */
    1464       156378 :         att->attnotnull = entry->is_not_null;
    1465       156378 :         att->attislocal = entry->is_local;
    1466       156378 :         att->attinhcount = entry->inhcount;
    1467       156378 :         att->attidentity = entry->identity;
    1468       156378 :         att->attgenerated = entry->generated;
    1469       156378 :         att->attcompression = GetAttributeCompression(att->atttypid, entry->compression);
    1470       156370 :         if (entry->storage)
    1471        16265 :             att->attstorage = entry->storage;
    1472       140105 :         else if (entry->storage_name)
    1473           39 :             att->attstorage = GetAttributeStorage(att->atttypid, entry->storage_name);
    1474              : 
    1475       156366 :         populate_compact_attribute(desc, attnum - 1);
    1476              :     }
    1477              : 
    1478        41996 :     TupleDescFinalize(desc);
    1479              : 
    1480        41996 :     return desc;
    1481              : }
    1482              : 
    1483              : /*
    1484              :  * Emit the right error or warning message for a "DROP" command issued on a
    1485              :  * non-existent relation
    1486              :  */
    1487              : static void
    1488          625 : DropErrorMsgNonExistent(RangeVar *rel, char rightkind, bool missing_ok)
    1489              : {
    1490              :     const struct dropmsgstrings *rentry;
    1491              : 
    1492          705 :     if (rel->schemaname != NULL &&
    1493           80 :         !OidIsValid(LookupNamespaceNoError(rel->schemaname)))
    1494              :     {
    1495           28 :         if (!missing_ok)
    1496              :         {
    1497            0 :             ereport(ERROR,
    1498              :                     (errcode(ERRCODE_UNDEFINED_SCHEMA),
    1499              :                      errmsg("schema \"%s\" does not exist", rel->schemaname)));
    1500              :         }
    1501              :         else
    1502              :         {
    1503           28 :             ereport(NOTICE,
    1504              :                     (errmsg("schema \"%s\" does not exist, skipping",
    1505              :                             rel->schemaname)));
    1506              :         }
    1507           28 :         return;
    1508              :     }
    1509              : 
    1510          882 :     for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
    1511              :     {
    1512          882 :         if (rentry->kind == rightkind)
    1513              :         {
    1514          597 :             if (!missing_ok)
    1515              :             {
    1516           90 :                 ereport(ERROR,
    1517              :                         (errcode(rentry->nonexistent_code),
    1518              :                          errmsg(rentry->nonexistent_msg, rel->relname)));
    1519              :             }
    1520              :             else
    1521              :             {
    1522          507 :                 ereport(NOTICE, (errmsg(rentry->skipping_msg, rel->relname)));
    1523          507 :                 break;
    1524              :             }
    1525              :         }
    1526              :     }
    1527              : 
    1528              :     Assert(rentry->kind != '\0');    /* Should be impossible */
    1529              : }
    1530              : 
    1531              : /*
    1532              :  * Emit the right error message for a "DROP" command issued on a
    1533              :  * relation of the wrong type
    1534              :  */
    1535              : static void
    1536            4 : DropErrorMsgWrongType(const char *relname, char wrongkind, char rightkind)
    1537              : {
    1538              :     const struct dropmsgstrings *rentry;
    1539              :     const struct dropmsgstrings *wentry;
    1540              : 
    1541            4 :     for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
    1542            4 :         if (rentry->kind == rightkind)
    1543            4 :             break;
    1544              :     Assert(rentry->kind != '\0');
    1545              : 
    1546           40 :     for (wentry = dropmsgstringarray; wentry->kind != '\0'; wentry++)
    1547           40 :         if (wentry->kind == wrongkind)
    1548            4 :             break;
    1549              :     /* wrongkind could be something we don't have in our table... */
    1550              : 
    1551            4 :     ereport(ERROR,
    1552              :             (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    1553              :              errmsg(rentry->nota_msg, relname),
    1554              :              (wentry->kind != '\0') ? errhint("%s", _(wentry->drophint_msg)) : 0));
    1555              : }
    1556              : 
    1557              : /*
    1558              :  * RemoveRelations
    1559              :  *      Implements DROP TABLE, DROP INDEX, DROP SEQUENCE, DROP VIEW,
    1560              :  *      DROP MATERIALIZED VIEW, DROP FOREIGN TABLE, DROP PROPERTY GRAPH
    1561              :  */
    1562              : void
    1563        11235 : RemoveRelations(DropStmt *drop)
    1564              : {
    1565              :     ObjectAddresses *objects;
    1566              :     char        relkind;
    1567              :     ListCell   *cell;
    1568        11235 :     int         flags = 0;
    1569        11235 :     LOCKMODE    lockmode = AccessExclusiveLock;
    1570              : 
    1571              :     /* DROP CONCURRENTLY uses a weaker lock, and has some restrictions */
    1572        11235 :     if (drop->concurrent)
    1573              :     {
    1574              :         /*
    1575              :          * Note that for temporary relations this lock may get upgraded later
    1576              :          * on, but as no other session can access a temporary relation, this
    1577              :          * is actually fine.
    1578              :          */
    1579          107 :         lockmode = ShareUpdateExclusiveLock;
    1580              :         Assert(drop->removeType == OBJECT_INDEX);
    1581          107 :         if (list_length(drop->objects) != 1)
    1582            4 :             ereport(ERROR,
    1583              :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1584              :                      errmsg("DROP INDEX CONCURRENTLY does not support dropping multiple objects")));
    1585          103 :         if (drop->behavior == DROP_CASCADE)
    1586            0 :             ereport(ERROR,
    1587              :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1588              :                      errmsg("DROP INDEX CONCURRENTLY does not support CASCADE")));
    1589              :     }
    1590              : 
    1591              :     /*
    1592              :      * First we identify all the relations, then we delete them in a single
    1593              :      * performMultipleDeletions() call.  This is to avoid unwanted DROP
    1594              :      * RESTRICT errors if one of the relations depends on another.
    1595              :      */
    1596              : 
    1597              :     /* Determine required relkind */
    1598        11231 :     switch (drop->removeType)
    1599              :     {
    1600         9687 :         case OBJECT_TABLE:
    1601         9687 :             relkind = RELKIND_RELATION;
    1602         9687 :             break;
    1603              : 
    1604          553 :         case OBJECT_INDEX:
    1605          553 :             relkind = RELKIND_INDEX;
    1606          553 :             break;
    1607              : 
    1608          119 :         case OBJECT_SEQUENCE:
    1609          119 :             relkind = RELKIND_SEQUENCE;
    1610          119 :             break;
    1611              : 
    1612          647 :         case OBJECT_VIEW:
    1613          647 :             relkind = RELKIND_VIEW;
    1614          647 :             break;
    1615              : 
    1616           79 :         case OBJECT_MATVIEW:
    1617           79 :             relkind = RELKIND_MATVIEW;
    1618           79 :             break;
    1619              : 
    1620          100 :         case OBJECT_FOREIGN_TABLE:
    1621          100 :             relkind = RELKIND_FOREIGN_TABLE;
    1622          100 :             break;
    1623              : 
    1624           46 :         case OBJECT_PROPGRAPH:
    1625           46 :             relkind = RELKIND_PROPGRAPH;
    1626           46 :             break;
    1627              : 
    1628            0 :         default:
    1629            0 :             elog(ERROR, "unrecognized drop object type: %d",
    1630              :                  (int) drop->removeType);
    1631              :             relkind = 0;        /* keep compiler quiet */
    1632              :             break;
    1633              :     }
    1634              : 
    1635              :     /* Lock and validate each relation; build a list of object addresses */
    1636        11231 :     objects = new_object_addresses();
    1637              : 
    1638        24776 :     foreach(cell, drop->objects)
    1639              :     {
    1640        13656 :         RangeVar   *rel = makeRangeVarFromNameList((List *) lfirst(cell));
    1641              :         Oid         relOid;
    1642              :         ObjectAddress obj;
    1643              :         struct DropRelationCallbackState state;
    1644              : 
    1645              :         /*
    1646              :          * These next few steps are a great deal like relation_openrv, but we
    1647              :          * don't bother building a relcache entry since we don't need it.
    1648              :          *
    1649              :          * Check for shared-cache-inval messages before trying to access the
    1650              :          * relation.  This is needed to cover the case where the name
    1651              :          * identifies a rel that has been dropped and recreated since the
    1652              :          * start of our transaction: if we don't flush the old syscache entry,
    1653              :          * then we'll latch onto that entry and suffer an error later.
    1654              :          */
    1655        13656 :         AcceptInvalidationMessages();
    1656              : 
    1657              :         /* Look up the appropriate relation using namespace search. */
    1658        13656 :         state.expected_relkind = relkind;
    1659        27312 :         state.heap_lockmode = drop->concurrent ?
    1660        13656 :             ShareUpdateExclusiveLock : AccessExclusiveLock;
    1661              :         /* We must initialize these fields to show that no locks are held: */
    1662        13656 :         state.heapOid = InvalidOid;
    1663        13656 :         state.partParentOid = InvalidOid;
    1664              : 
    1665        13656 :         relOid = RangeVarGetRelidExtended(rel, lockmode, RVR_MISSING_OK,
    1666              :                                           RangeVarCallbackForDropRelation,
    1667              :                                           &state);
    1668              : 
    1669              :         /* Not there? */
    1670        13639 :         if (!OidIsValid(relOid))
    1671              :         {
    1672          625 :             DropErrorMsgNonExistent(rel, relkind, drop->missing_ok);
    1673          535 :             continue;
    1674              :         }
    1675              : 
    1676              :         /*
    1677              :          * Decide if concurrent mode needs to be used here or not.  The
    1678              :          * callback retrieved the rel's persistence for us.
    1679              :          */
    1680        13014 :         if (drop->concurrent &&
    1681           99 :             state.actual_relpersistence != RELPERSISTENCE_TEMP)
    1682              :         {
    1683              :             Assert(list_length(drop->objects) == 1 &&
    1684              :                    drop->removeType == OBJECT_INDEX);
    1685           87 :             flags |= PERFORM_DELETION_CONCURRENTLY;
    1686              :         }
    1687              : 
    1688              :         /*
    1689              :          * Concurrent index drop cannot be used with partitioned indexes,
    1690              :          * either.
    1691              :          */
    1692        13014 :         if ((flags & PERFORM_DELETION_CONCURRENTLY) != 0 &&
    1693           87 :             state.actual_relkind == RELKIND_PARTITIONED_INDEX)
    1694            4 :             ereport(ERROR,
    1695              :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1696              :                      errmsg("cannot drop partitioned index \"%s\" concurrently",
    1697              :                             rel->relname)));
    1698              : 
    1699              :         /*
    1700              :          * If we're told to drop a partitioned index, we must acquire lock on
    1701              :          * all the children of its parent partitioned table before proceeding.
    1702              :          * Otherwise we'd try to lock the child index partitions before their
    1703              :          * tables, leading to potential deadlock against other sessions that
    1704              :          * will lock those objects in the other order.
    1705              :          */
    1706        13010 :         if (state.actual_relkind == RELKIND_PARTITIONED_INDEX)
    1707           50 :             (void) find_all_inheritors(state.heapOid,
    1708              :                                        state.heap_lockmode,
    1709              :                                        NULL);
    1710              : 
    1711              :         /* OK, we're ready to delete this one */
    1712        13010 :         obj.classId = RelationRelationId;
    1713        13010 :         obj.objectId = relOid;
    1714        13010 :         obj.objectSubId = 0;
    1715              : 
    1716        13010 :         add_exact_object_address(&obj, objects);
    1717              :     }
    1718              : 
    1719        11120 :     performMultipleDeletions(objects, drop->behavior, flags);
    1720              : 
    1721        11018 :     free_object_addresses(objects);
    1722        11018 : }
    1723              : 
    1724              : /*
    1725              :  * Before acquiring a table lock, check whether we have sufficient rights.
    1726              :  * In the case of DROP INDEX, also try to lock the table before the index.
    1727              :  * Also, if the table to be dropped is a partition, we try to lock the parent
    1728              :  * first.
    1729              :  */
    1730              : static void
    1731        13872 : RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid, Oid oldRelOid,
    1732              :                                 void *arg)
    1733              : {
    1734              :     HeapTuple   tuple;
    1735              :     struct DropRelationCallbackState *state;
    1736              :     char        expected_relkind;
    1737              :     bool        is_partition;
    1738              :     Form_pg_class classform;
    1739              :     LOCKMODE    heap_lockmode;
    1740        13872 :     bool        invalid_system_index = false;
    1741              : 
    1742        13872 :     state = (struct DropRelationCallbackState *) arg;
    1743        13872 :     heap_lockmode = state->heap_lockmode;
    1744              : 
    1745              :     /*
    1746              :      * If we previously locked some other index's heap, and the name we're
    1747              :      * looking up no longer refers to that relation, release the now-useless
    1748              :      * lock.
    1749              :      */
    1750        13872 :     if (relOid != oldRelOid && OidIsValid(state->heapOid))
    1751              :     {
    1752            0 :         UnlockRelationOid(state->heapOid, heap_lockmode);
    1753            0 :         state->heapOid = InvalidOid;
    1754              :     }
    1755              : 
    1756              :     /*
    1757              :      * Similarly, if we previously locked some other partition's heap, and the
    1758              :      * name we're looking up no longer refers to that relation, release the
    1759              :      * now-useless lock.
    1760              :      */
    1761        13872 :     if (relOid != oldRelOid && OidIsValid(state->partParentOid))
    1762              :     {
    1763            0 :         UnlockRelationOid(state->partParentOid, AccessExclusiveLock);
    1764            0 :         state->partParentOid = InvalidOid;
    1765              :     }
    1766              : 
    1767              :     /* Didn't find a relation, so no need for locking or permission checks. */
    1768        13872 :     if (!OidIsValid(relOid))
    1769          627 :         return;
    1770              : 
    1771        13245 :     tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid));
    1772        13245 :     if (!HeapTupleIsValid(tuple))
    1773            0 :         return;                 /* concurrently dropped, so nothing to do */
    1774        13245 :     classform = (Form_pg_class) GETSTRUCT(tuple);
    1775        13245 :     is_partition = classform->relispartition;
    1776              : 
    1777              :     /* Pass back some data to save lookups in RemoveRelations */
    1778        13245 :     state->actual_relkind = classform->relkind;
    1779        13245 :     state->actual_relpersistence = classform->relpersistence;
    1780              : 
    1781              :     /*
    1782              :      * Both RELKIND_RELATION and RELKIND_PARTITIONED_TABLE are OBJECT_TABLE,
    1783              :      * but RemoveRelations() can only pass one relkind for a given relation.
    1784              :      * It chooses RELKIND_RELATION for both regular and partitioned tables.
    1785              :      * That means we must be careful before giving the wrong type error when
    1786              :      * the relation is RELKIND_PARTITIONED_TABLE.  An equivalent problem
    1787              :      * exists with indexes.
    1788              :      */
    1789        13245 :     if (classform->relkind == RELKIND_PARTITIONED_TABLE)
    1790         2167 :         expected_relkind = RELKIND_RELATION;
    1791        11078 :     else if (classform->relkind == RELKIND_PARTITIONED_INDEX)
    1792           55 :         expected_relkind = RELKIND_INDEX;
    1793              :     else
    1794        11023 :         expected_relkind = classform->relkind;
    1795              : 
    1796        13245 :     if (state->expected_relkind != expected_relkind)
    1797            4 :         DropErrorMsgWrongType(rel->relname, classform->relkind,
    1798            4 :                               state->expected_relkind);
    1799              : 
    1800              :     /* Allow DROP to either table owner or schema owner */
    1801        13241 :     if (!object_ownercheck(RelationRelationId, relOid, GetUserId()) &&
    1802           12 :         !object_ownercheck(NamespaceRelationId, classform->relnamespace, GetUserId()))
    1803           12 :         aclcheck_error(ACLCHECK_NOT_OWNER,
    1804           12 :                        get_relkind_objtype(classform->relkind),
    1805           12 :                        rel->relname);
    1806              : 
    1807              :     /*
    1808              :      * Check the case of a system index that might have been invalidated by a
    1809              :      * failed concurrent process and allow its drop. For the time being, this
    1810              :      * only concerns indexes of toast relations that became invalid during a
    1811              :      * REINDEX CONCURRENTLY process.
    1812              :      */
    1813        13229 :     if (IsSystemClass(relOid, classform) && classform->relkind == RELKIND_INDEX)
    1814              :     {
    1815              :         HeapTuple   locTuple;
    1816              :         Form_pg_index indexform;
    1817              :         bool        indisvalid;
    1818              : 
    1819            0 :         locTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(relOid));
    1820            0 :         if (!HeapTupleIsValid(locTuple))
    1821              :         {
    1822            0 :             ReleaseSysCache(tuple);
    1823            0 :             return;
    1824              :         }
    1825              : 
    1826            0 :         indexform = (Form_pg_index) GETSTRUCT(locTuple);
    1827            0 :         indisvalid = indexform->indisvalid;
    1828            0 :         ReleaseSysCache(locTuple);
    1829              : 
    1830              :         /* Mark object as being an invalid index of system catalogs */
    1831            0 :         if (!indisvalid)
    1832            0 :             invalid_system_index = true;
    1833              :     }
    1834              : 
    1835              :     /* In the case of an invalid index, it is fine to bypass this check */
    1836        13229 :     if (!invalid_system_index && !allowSystemTableMods && IsSystemClass(relOid, classform))
    1837            1 :         ereport(ERROR,
    1838              :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
    1839              :                  errmsg("permission denied: \"%s\" is a system catalog",
    1840              :                         rel->relname)));
    1841              : 
    1842        13228 :     ReleaseSysCache(tuple);
    1843              : 
    1844              :     /*
    1845              :      * In DROP INDEX, attempt to acquire lock on the parent table before
    1846              :      * locking the index.  index_drop() will need this anyway, and since
    1847              :      * regular queries lock tables before their indexes, we risk deadlock if
    1848              :      * we do it the other way around.  No error if we don't find a pg_index
    1849              :      * entry, though --- the relation may have been dropped.  Note that this
    1850              :      * code will execute for either plain or partitioned indexes.
    1851              :      */
    1852        13228 :     if (expected_relkind == RELKIND_INDEX &&
    1853              :         relOid != oldRelOid)
    1854              :     {
    1855          545 :         state->heapOid = IndexGetRelation(relOid, true);
    1856          545 :         if (OidIsValid(state->heapOid))
    1857          545 :             LockRelationOid(state->heapOid, heap_lockmode);
    1858              :     }
    1859              : 
    1860              :     /*
    1861              :      * Similarly, if the relation is a partition, we must acquire lock on its
    1862              :      * parent before locking the partition.  That's because queries lock the
    1863              :      * parent before its partitions, so we risk deadlock if we do it the other
    1864              :      * way around.
    1865              :      */
    1866        13228 :     if (is_partition && relOid != oldRelOid)
    1867              :     {
    1868          393 :         state->partParentOid = get_partition_parent(relOid, true);
    1869          393 :         if (OidIsValid(state->partParentOid))
    1870          393 :             LockRelationOid(state->partParentOid, AccessExclusiveLock);
    1871              :     }
    1872              : }
    1873              : 
    1874              : /*
    1875              :  * ExecuteTruncate
    1876              :  *      Executes a TRUNCATE command.
    1877              :  *
    1878              :  * This is a multi-relation truncate.  We first open and grab exclusive
    1879              :  * lock on all relations involved, checking permissions and otherwise
    1880              :  * verifying that the relation is OK for truncation.  Note that if relations
    1881              :  * are foreign tables, at this stage, we have not yet checked that their
    1882              :  * foreign data in external data sources are OK for truncation.  These are
    1883              :  * checked when foreign data are actually truncated later.  In CASCADE mode,
    1884              :  * relations having FK references to the targeted relations are automatically
    1885              :  * added to the group; in RESTRICT mode, we check that all FK references are
    1886              :  * internal to the group that's being truncated.  Finally all the relations
    1887              :  * are truncated and reindexed.
    1888              :  */
    1889              : void
    1890         1140 : ExecuteTruncate(TruncateStmt *stmt)
    1891              : {
    1892         1140 :     List       *rels = NIL;
    1893         1140 :     List       *relids = NIL;
    1894         1140 :     List       *relids_logged = NIL;
    1895              :     ListCell   *cell;
    1896              : 
    1897              :     /*
    1898              :      * Open, exclusive-lock, and check all the explicitly-specified relations
    1899              :      */
    1900         2417 :     foreach(cell, stmt->relations)
    1901              :     {
    1902         1312 :         RangeVar   *rv = lfirst(cell);
    1903              :         Relation    rel;
    1904         1312 :         bool        recurse = rv->inh;
    1905              :         Oid         myrelid;
    1906         1312 :         LOCKMODE    lockmode = AccessExclusiveLock;
    1907              : 
    1908         1312 :         myrelid = RangeVarGetRelidExtended(rv, lockmode,
    1909              :                                            0, RangeVarCallbackForTruncate,
    1910              :                                            NULL);
    1911              : 
    1912              :         /* don't throw error for "TRUNCATE foo, foo" */
    1913         1289 :         if (list_member_oid(relids, myrelid))
    1914            1 :             continue;
    1915              : 
    1916              :         /* open the relation, we already hold a lock on it */
    1917         1288 :         rel = table_open(myrelid, NoLock);
    1918              : 
    1919              :         /*
    1920              :          * RangeVarGetRelidExtended() has done most checks with its callback,
    1921              :          * but other checks with the now-opened Relation remain.
    1922              :          */
    1923         1288 :         truncate_check_activity(rel);
    1924              : 
    1925         1284 :         rels = lappend(rels, rel);
    1926         1284 :         relids = lappend_oid(relids, myrelid);
    1927              : 
    1928              :         /* Log this relation only if needed for logical decoding */
    1929         1284 :         if (RelationIsLogicallyLogged(rel))
    1930           39 :             relids_logged = lappend_oid(relids_logged, myrelid);
    1931              : 
    1932         1284 :         if (recurse)
    1933              :         {
    1934              :             ListCell   *child;
    1935              :             List       *children;
    1936              : 
    1937         1247 :             children = find_all_inheritors(myrelid, lockmode, NULL);
    1938              : 
    1939         3714 :             foreach(child, children)
    1940              :             {
    1941         2467 :                 Oid         childrelid = lfirst_oid(child);
    1942              : 
    1943         2467 :                 if (list_member_oid(relids, childrelid))
    1944         1247 :                     continue;
    1945              : 
    1946              :                 /* find_all_inheritors already got lock */
    1947         1220 :                 rel = table_open(childrelid, NoLock);
    1948              : 
    1949              :                 /*
    1950              :                  * It is possible that the parent table has children that are
    1951              :                  * temp tables of other backends.  We cannot safely access
    1952              :                  * such tables (because of buffering issues), and the best
    1953              :                  * thing to do is to silently ignore them.  Note that this
    1954              :                  * check is the same as one of the checks done in
    1955              :                  * truncate_check_activity() called below, still it is kept
    1956              :                  * here for simplicity.
    1957              :                  */
    1958         1220 :                 if (RELATION_IS_OTHER_TEMP(rel))
    1959              :                 {
    1960            4 :                     table_close(rel, lockmode);
    1961            4 :                     continue;
    1962              :                 }
    1963              : 
    1964              :                 /*
    1965              :                  * Inherited TRUNCATE commands perform access permission
    1966              :                  * checks on the parent table only. So we skip checking the
    1967              :                  * children's permissions and don't call
    1968              :                  * truncate_check_perms() here.
    1969              :                  */
    1970         1216 :                 truncate_check_rel(RelationGetRelid(rel), rel->rd_rel);
    1971         1216 :                 truncate_check_activity(rel);
    1972              : 
    1973         1216 :                 rels = lappend(rels, rel);
    1974         1216 :                 relids = lappend_oid(relids, childrelid);
    1975              : 
    1976              :                 /* Log this relation only if needed for logical decoding */
    1977         1216 :                 if (RelationIsLogicallyLogged(rel))
    1978           11 :                     relids_logged = lappend_oid(relids_logged, childrelid);
    1979              :             }
    1980              :         }
    1981           37 :         else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
    1982            8 :             ereport(ERROR,
    1983              :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    1984              :                      errmsg("cannot truncate only a partitioned table"),
    1985              :                      errhint("Do not specify the ONLY keyword, or use TRUNCATE ONLY on the partitions directly.")));
    1986              :     }
    1987              : 
    1988         1105 :     ExecuteTruncateGuts(rels, relids, relids_logged,
    1989         1105 :                         stmt->behavior, stmt->restart_seqs, false);
    1990              : 
    1991              :     /* And close the rels */
    1992         3443 :     foreach(cell, rels)
    1993              :     {
    1994         2391 :         Relation    rel = (Relation) lfirst(cell);
    1995              : 
    1996         2391 :         table_close(rel, NoLock);
    1997              :     }
    1998         1052 : }
    1999              : 
    2000              : /*
    2001              :  * ExecuteTruncateGuts
    2002              :  *
    2003              :  * Internal implementation of TRUNCATE.  This is called by the actual TRUNCATE
    2004              :  * command (see above) as well as replication subscribers that execute a
    2005              :  * replicated TRUNCATE action.
    2006              :  *
    2007              :  * explicit_rels is the list of Relations to truncate that the command
    2008              :  * specified.  relids is the list of Oids corresponding to explicit_rels.
    2009              :  * relids_logged is the list of Oids (a subset of relids) that require
    2010              :  * WAL-logging.  This is all a bit redundant, but the existing callers have
    2011              :  * this information handy in this form.
    2012              :  */
    2013              : void
    2014         1125 : ExecuteTruncateGuts(List *explicit_rels,
    2015              :                     List *relids,
    2016              :                     List *relids_logged,
    2017              :                     DropBehavior behavior, bool restart_seqs,
    2018              :                     bool run_as_table_owner)
    2019              : {
    2020              :     List       *rels;
    2021         1125 :     List       *seq_relids = NIL;
    2022         1125 :     HTAB       *ft_htab = NULL;
    2023              :     EState     *estate;
    2024              :     ResultRelInfo *resultRelInfos;
    2025              :     ResultRelInfo *resultRelInfo;
    2026              :     SubTransactionId mySubid;
    2027              :     ListCell   *cell;
    2028              :     Oid        *logrelids;
    2029              : 
    2030              :     /*
    2031              :      * Check the explicitly-specified relations.
    2032              :      *
    2033              :      * In CASCADE mode, suck in all referencing relations as well.  This
    2034              :      * requires multiple iterations to find indirectly-dependent relations. At
    2035              :      * each phase, we need to exclusive-lock new rels before looking for their
    2036              :      * dependencies, else we might miss something.  Also, we check each rel as
    2037              :      * soon as we open it, to avoid a faux pas such as holding lock for a long
    2038              :      * time on a rel we have no permissions for.
    2039              :      */
    2040         1125 :     rels = list_copy(explicit_rels);
    2041         1125 :     if (behavior == DROP_CASCADE)
    2042              :     {
    2043              :         for (;;)
    2044           26 :         {
    2045              :             List       *newrelids;
    2046              : 
    2047           51 :             newrelids = heap_truncate_find_FKs(relids);
    2048           51 :             if (newrelids == NIL)
    2049           25 :                 break;          /* nothing else to add */
    2050              : 
    2051           88 :             foreach(cell, newrelids)
    2052              :             {
    2053           62 :                 Oid         relid = lfirst_oid(cell);
    2054              :                 Relation    rel;
    2055              : 
    2056           62 :                 rel = table_open(relid, AccessExclusiveLock);
    2057           62 :                 ereport(NOTICE,
    2058              :                         (errmsg("truncate cascades to table \"%s\"",
    2059              :                                 RelationGetRelationName(rel))));
    2060           62 :                 truncate_check_rel(relid, rel->rd_rel);
    2061           62 :                 truncate_check_perms(relid, rel->rd_rel);
    2062           62 :                 truncate_check_activity(rel);
    2063           62 :                 rels = lappend(rels, rel);
    2064           62 :                 relids = lappend_oid(relids, relid);
    2065              : 
    2066              :                 /* Log this relation only if needed for logical decoding */
    2067           62 :                 if (RelationIsLogicallyLogged(rel))
    2068            0 :                     relids_logged = lappend_oid(relids_logged, relid);
    2069              :             }
    2070              :         }
    2071              :     }
    2072              : 
    2073              :     /*
    2074              :      * Check foreign key references.  In CASCADE mode, this should be
    2075              :      * unnecessary since we just pulled in all the references; but as a
    2076              :      * cross-check, do it anyway if in an Assert-enabled build.
    2077              :      */
    2078              : #ifdef USE_ASSERT_CHECKING
    2079              :     heap_truncate_check_FKs(rels, false);
    2080              : #else
    2081         1125 :     if (behavior == DROP_RESTRICT)
    2082         1100 :         heap_truncate_check_FKs(rels, false);
    2083              : #endif
    2084              : 
    2085              :     /*
    2086              :      * If we are asked to restart sequences, find all the sequences, lock them
    2087              :      * (we need AccessExclusiveLock for ResetSequence), and check permissions.
    2088              :      * We want to do this early since it's pointless to do all the truncation
    2089              :      * work only to fail on sequence permissions.
    2090              :      */
    2091         1076 :     if (restart_seqs)
    2092              :     {
    2093           30 :         foreach(cell, rels)
    2094              :         {
    2095           15 :             Relation    rel = (Relation) lfirst(cell);
    2096           15 :             List       *seqlist = getOwnedSequences(RelationGetRelid(rel));
    2097              :             ListCell   *seqcell;
    2098              : 
    2099           37 :             foreach(seqcell, seqlist)
    2100              :             {
    2101           22 :                 Oid         seq_relid = lfirst_oid(seqcell);
    2102              :                 Relation    seq_rel;
    2103              : 
    2104           22 :                 seq_rel = relation_open(seq_relid, AccessExclusiveLock);
    2105              : 
    2106              :                 /* This check must match AlterSequence! */
    2107           22 :                 if (!object_ownercheck(RelationRelationId, seq_relid, GetUserId()))
    2108            0 :                     aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_SEQUENCE,
    2109            0 :                                    RelationGetRelationName(seq_rel));
    2110              : 
    2111           22 :                 seq_relids = lappend_oid(seq_relids, seq_relid);
    2112              : 
    2113           22 :                 relation_close(seq_rel, NoLock);
    2114              :             }
    2115              :         }
    2116              :     }
    2117              : 
    2118              :     /* Prepare to catch AFTER triggers. */
    2119         1076 :     AfterTriggerBeginQuery();
    2120              : 
    2121              :     /*
    2122              :      * To fire triggers, we'll need an EState as well as a ResultRelInfo for
    2123              :      * each relation.  We don't need to call ExecOpenIndices, though.
    2124              :      *
    2125              :      * We put the ResultRelInfos in the es_opened_result_relations list, even
    2126              :      * though we don't have a range table and don't populate the
    2127              :      * es_result_relations array.  That's a bit bogus, but it's enough to make
    2128              :      * ExecGetTriggerResultRel() find them.
    2129              :      */
    2130         1076 :     estate = CreateExecutorState();
    2131              :     resultRelInfos = (ResultRelInfo *)
    2132         1076 :         palloc(list_length(rels) * sizeof(ResultRelInfo));
    2133         1076 :     resultRelInfo = resultRelInfos;
    2134         3569 :     foreach(cell, rels)
    2135              :     {
    2136         2493 :         Relation    rel = (Relation) lfirst(cell);
    2137              : 
    2138         2493 :         InitResultRelInfo(resultRelInfo,
    2139              :                           rel,
    2140              :                           0,    /* dummy rangetable index */
    2141              :                           NULL,
    2142              :                           0);
    2143         2493 :         estate->es_opened_result_relations =
    2144         2493 :             lappend(estate->es_opened_result_relations, resultRelInfo);
    2145         2493 :         resultRelInfo++;
    2146              :     }
    2147              : 
    2148              :     /*
    2149              :      * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
    2150              :      * truncating (this is because one of them might throw an error). Also, if
    2151              :      * we were to allow them to prevent statement execution, that would need
    2152              :      * to be handled here.
    2153              :      */
    2154         1076 :     resultRelInfo = resultRelInfos;
    2155         3569 :     foreach(cell, rels)
    2156              :     {
    2157              :         UserContext ucxt;
    2158              : 
    2159         2493 :         if (run_as_table_owner)
    2160           36 :             SwitchToUntrustedUser(resultRelInfo->ri_RelationDesc->rd_rel->relowner,
    2161              :                                   &ucxt);
    2162         2493 :         ExecBSTruncateTriggers(estate, resultRelInfo);
    2163         2493 :         if (run_as_table_owner)
    2164           36 :             RestoreUserContext(&ucxt);
    2165         2493 :         resultRelInfo++;
    2166              :     }
    2167              : 
    2168              :     /*
    2169              :      * OK, truncate each table.
    2170              :      */
    2171         1076 :     mySubid = GetCurrentSubTransactionId();
    2172              : 
    2173         3569 :     foreach(cell, rels)
    2174              :     {
    2175         2493 :         Relation    rel = (Relation) lfirst(cell);
    2176              : 
    2177              :         /* Skip partitioned tables as there is nothing to do */
    2178         2493 :         if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
    2179          477 :             continue;
    2180              : 
    2181              :         /*
    2182              :          * Build the lists of foreign tables belonging to each foreign server
    2183              :          * and pass each list to the foreign data wrapper's callback function,
    2184              :          * so that each server can truncate its all foreign tables in bulk.
    2185              :          * Each list is saved as a single entry in a hash table that uses the
    2186              :          * server OID as lookup key.
    2187              :          */
    2188         2016 :         if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
    2189           17 :         {
    2190           17 :             Oid         serverid = GetForeignServerIdByRelId(RelationGetRelid(rel));
    2191              :             bool        found;
    2192              :             ForeignTruncateInfo *ft_info;
    2193              : 
    2194              :             /* First time through, initialize hashtable for foreign tables */
    2195           17 :             if (!ft_htab)
    2196              :             {
    2197              :                 HASHCTL     hctl;
    2198              : 
    2199           15 :                 memset(&hctl, 0, sizeof(HASHCTL));
    2200           15 :                 hctl.keysize = sizeof(Oid);
    2201           15 :                 hctl.entrysize = sizeof(ForeignTruncateInfo);
    2202           15 :                 hctl.hcxt = CurrentMemoryContext;
    2203              : 
    2204           15 :                 ft_htab = hash_create("TRUNCATE for Foreign Tables",
    2205              :                                       32,   /* start small and extend */
    2206              :                                       &hctl,
    2207              :                                       HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
    2208              :             }
    2209              : 
    2210              :             /* Find or create cached entry for the foreign table */
    2211           17 :             ft_info = hash_search(ft_htab, &serverid, HASH_ENTER, &found);
    2212           17 :             if (!found)
    2213           15 :                 ft_info->rels = NIL;
    2214              : 
    2215              :             /*
    2216              :              * Save the foreign table in the entry of the server that the
    2217              :              * foreign table belongs to.
    2218              :              */
    2219           17 :             ft_info->rels = lappend(ft_info->rels, rel);
    2220           17 :             continue;
    2221              :         }
    2222              : 
    2223              :         /*
    2224              :          * Normally, we need a transaction-safe truncation here.  However, if
    2225              :          * the table was either created in the current (sub)transaction or has
    2226              :          * a new relfilenumber in the current (sub)transaction, then we can
    2227              :          * just truncate it in-place, because a rollback would cause the whole
    2228              :          * table or the current physical file to be thrown away anyway.
    2229              :          */
    2230         1999 :         if (rel->rd_createSubid == mySubid ||
    2231         1984 :             rel->rd_newRelfilelocatorSubid == mySubid)
    2232              :         {
    2233              :             /* Immediate, non-rollbackable truncation is OK */
    2234           47 :             heap_truncate_one_rel(rel);
    2235              :         }
    2236              :         else
    2237              :         {
    2238              :             Oid         heap_relid;
    2239              :             Oid         toast_relid;
    2240         1952 :             ReindexParams reindex_params = {0};
    2241              : 
    2242              :             /*
    2243              :              * This effectively deletes all rows in the table, and may be done
    2244              :              * in a serializable transaction.  In that case we must record a
    2245              :              * rw-conflict in to this transaction from each transaction
    2246              :              * holding a predicate lock on the table.
    2247              :              */
    2248         1952 :             CheckTableForSerializableConflictIn(rel);
    2249              : 
    2250              :             /*
    2251              :              * Need the full transaction-safe pushups.
    2252              :              *
    2253              :              * Create a new empty storage file for the relation, and assign it
    2254              :              * as the relfilenumber value. The old storage file is scheduled
    2255              :              * for deletion at commit.
    2256              :              */
    2257         1952 :             RelationSetNewRelfilenumber(rel, rel->rd_rel->relpersistence);
    2258              : 
    2259         1952 :             heap_relid = RelationGetRelid(rel);
    2260              : 
    2261              :             /*
    2262              :              * The same for the toast table, if any.
    2263              :              */
    2264         1952 :             toast_relid = rel->rd_rel->reltoastrelid;
    2265         1952 :             if (OidIsValid(toast_relid))
    2266              :             {
    2267         1169 :                 Relation    toastrel = relation_open(toast_relid,
    2268              :                                                      AccessExclusiveLock);
    2269              : 
    2270         1169 :                 RelationSetNewRelfilenumber(toastrel,
    2271         1169 :                                             toastrel->rd_rel->relpersistence);
    2272         1169 :                 table_close(toastrel, NoLock);
    2273              :             }
    2274              : 
    2275              :             /*
    2276              :              * Reconstruct the indexes to match, and we're done.
    2277              :              */
    2278         1952 :             reindex_relation(NULL, heap_relid, REINDEX_REL_PROCESS_TOAST,
    2279              :                              &reindex_params);
    2280              :         }
    2281              : 
    2282         1999 :         pgstat_count_truncate(rel);
    2283              :     }
    2284              : 
    2285              :     /* Now go through the hash table, and truncate foreign tables */
    2286         1076 :     if (ft_htab)
    2287              :     {
    2288              :         ForeignTruncateInfo *ft_info;
    2289              :         HASH_SEQ_STATUS seq;
    2290              : 
    2291           15 :         hash_seq_init(&seq, ft_htab);
    2292              : 
    2293           15 :         PG_TRY();
    2294              :         {
    2295           26 :             while ((ft_info = hash_seq_search(&seq)) != NULL)
    2296              :             {
    2297           15 :                 FdwRoutine *routine = GetFdwRoutineByServerId(ft_info->serverid);
    2298              : 
    2299              :                 /* truncate_check_rel() has checked that already */
    2300              :                 Assert(routine->ExecForeignTruncate != NULL);
    2301              : 
    2302           15 :                 routine->ExecForeignTruncate(ft_info->rels,
    2303              :                                              behavior,
    2304              :                                              restart_seqs);
    2305              :             }
    2306              :         }
    2307            4 :         PG_FINALLY();
    2308              :         {
    2309           15 :             hash_destroy(ft_htab);
    2310              :         }
    2311           15 :         PG_END_TRY();
    2312              :     }
    2313              : 
    2314              :     /*
    2315              :      * Restart owned sequences if we were asked to.
    2316              :      */
    2317         1094 :     foreach(cell, seq_relids)
    2318              :     {
    2319           22 :         Oid         seq_relid = lfirst_oid(cell);
    2320              : 
    2321           22 :         ResetSequence(seq_relid);
    2322              :     }
    2323              : 
    2324              :     /*
    2325              :      * Write a WAL record to allow this set of actions to be logically
    2326              :      * decoded.
    2327              :      *
    2328              :      * Assemble an array of relids so we can write a single WAL record for the
    2329              :      * whole action.
    2330              :      */
    2331         1072 :     if (relids_logged != NIL)
    2332              :     {
    2333              :         xl_heap_truncate xlrec;
    2334           33 :         int         i = 0;
    2335              : 
    2336              :         /* should only get here if effective_wal_level is 'logical' */
    2337              :         Assert(XLogLogicalInfoActive());
    2338              : 
    2339           33 :         logrelids = palloc(list_length(relids_logged) * sizeof(Oid));
    2340           84 :         foreach(cell, relids_logged)
    2341           51 :             logrelids[i++] = lfirst_oid(cell);
    2342              : 
    2343           33 :         xlrec.dbId = MyDatabaseId;
    2344           33 :         xlrec.nrelids = list_length(relids_logged);
    2345           33 :         xlrec.flags = 0;
    2346           33 :         if (behavior == DROP_CASCADE)
    2347            1 :             xlrec.flags |= XLH_TRUNCATE_CASCADE;
    2348           33 :         if (restart_seqs)
    2349            2 :             xlrec.flags |= XLH_TRUNCATE_RESTART_SEQS;
    2350              : 
    2351           33 :         XLogBeginInsert();
    2352           33 :         XLogRegisterData(&xlrec, SizeOfHeapTruncate);
    2353           33 :         XLogRegisterData(logrelids, list_length(relids_logged) * sizeof(Oid));
    2354              : 
    2355           33 :         XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
    2356              : 
    2357           33 :         (void) XLogInsert(RM_HEAP_ID, XLOG_HEAP_TRUNCATE);
    2358              :     }
    2359              : 
    2360              :     /*
    2361              :      * Process all AFTER STATEMENT TRUNCATE triggers.
    2362              :      */
    2363         1072 :     resultRelInfo = resultRelInfos;
    2364         3561 :     foreach(cell, rels)
    2365              :     {
    2366              :         UserContext ucxt;
    2367              : 
    2368         2489 :         if (run_as_table_owner)
    2369           36 :             SwitchToUntrustedUser(resultRelInfo->ri_RelationDesc->rd_rel->relowner,
    2370              :                                   &ucxt);
    2371         2489 :         ExecASTruncateTriggers(estate, resultRelInfo);
    2372         2489 :         if (run_as_table_owner)
    2373           36 :             RestoreUserContext(&ucxt);
    2374         2489 :         resultRelInfo++;
    2375              :     }
    2376              : 
    2377              :     /* Handle queued AFTER triggers */
    2378         1072 :     AfterTriggerEndQuery(estate);
    2379              : 
    2380              :     /* We can clean up the EState now */
    2381         1072 :     FreeExecutorState(estate);
    2382              : 
    2383              :     /*
    2384              :      * Close any rels opened by CASCADE (can't do this while EState still
    2385              :      * holds refs)
    2386              :      */
    2387         1072 :     rels = list_difference_ptr(rels, explicit_rels);
    2388         1134 :     foreach(cell, rels)
    2389              :     {
    2390           62 :         Relation    rel = (Relation) lfirst(cell);
    2391              : 
    2392           62 :         table_close(rel, NoLock);
    2393              :     }
    2394         1072 : }
    2395              : 
    2396              : /*
    2397              :  * Check that a given relation is safe to truncate.  Subroutine for
    2398              :  * ExecuteTruncate() and RangeVarCallbackForTruncate().
    2399              :  */
    2400              : static void
    2401         2687 : truncate_check_rel(Oid relid, Form_pg_class reltuple)
    2402              : {
    2403         2687 :     char       *relname = NameStr(reltuple->relname);
    2404              : 
    2405              :     /*
    2406              :      * Only allow truncate on regular tables, foreign tables using foreign
    2407              :      * data wrappers supporting TRUNCATE and partitioned tables (although, the
    2408              :      * latter are only being included here for the following checks; no
    2409              :      * physical truncation will occur in their case.).
    2410              :      */
    2411         2687 :     if (reltuple->relkind == RELKIND_FOREIGN_TABLE)
    2412              :     {
    2413           19 :         Oid         serverid = GetForeignServerIdByRelId(relid);
    2414           19 :         FdwRoutine *fdwroutine = GetFdwRoutineByServerId(serverid);
    2415              : 
    2416           18 :         if (!fdwroutine->ExecForeignTruncate)
    2417            1 :             ereport(ERROR,
    2418              :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2419              :                      errmsg("cannot truncate foreign table \"%s\"",
    2420              :                             relname)));
    2421              :     }
    2422         2668 :     else if (reltuple->relkind != RELKIND_RELATION &&
    2423          497 :              reltuple->relkind != RELKIND_PARTITIONED_TABLE)
    2424            0 :         ereport(ERROR,
    2425              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2426              :                  errmsg("\"%s\" is not a table", relname)));
    2427              : 
    2428              :     /*
    2429              :      * Most system catalogs can't be truncated at all, or at least not unless
    2430              :      * allow_system_table_mods=on. As an exception, however, we allow
    2431              :      * pg_largeobject and pg_largeobject_metadata to be truncated as part of
    2432              :      * pg_upgrade, because we need to change its relfilenode to match the old
    2433              :      * cluster, and allowing a TRUNCATE command to be executed is the easiest
    2434              :      * way of doing that.
    2435              :      */
    2436         2685 :     if (!allowSystemTableMods && IsSystemClass(relid, reltuple)
    2437           65 :         && (!IsBinaryUpgrade ||
    2438           32 :             (relid != LargeObjectRelationId &&
    2439              :              relid != LargeObjectMetadataRelationId)))
    2440            1 :         ereport(ERROR,
    2441              :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
    2442              :                  errmsg("permission denied: \"%s\" is a system catalog",
    2443              :                         relname)));
    2444              : 
    2445         2684 :     InvokeObjectTruncateHook(relid);
    2446         2684 : }
    2447              : 
    2448              : /*
    2449              :  * Check that current user has the permission to truncate given relation.
    2450              :  */
    2451              : static void
    2452         1468 : truncate_check_perms(Oid relid, Form_pg_class reltuple)
    2453              : {
    2454         1468 :     char       *relname = NameStr(reltuple->relname);
    2455              :     AclResult   aclresult;
    2456              : 
    2457              :     /* Permissions checks */
    2458         1468 :     aclresult = pg_class_aclcheck(relid, GetUserId(), ACL_TRUNCATE);
    2459         1468 :     if (aclresult != ACLCHECK_OK)
    2460           20 :         aclcheck_error(aclresult, get_relkind_objtype(reltuple->relkind),
    2461              :                        relname);
    2462         1448 : }
    2463              : 
    2464              : /*
    2465              :  * Set of extra sanity checks to check if a given relation is safe to
    2466              :  * truncate.  This is split with truncate_check_rel() as
    2467              :  * RangeVarCallbackForTruncate() cannot open a Relation yet.
    2468              :  */
    2469              : static void
    2470         2566 : truncate_check_activity(Relation rel)
    2471              : {
    2472              :     /*
    2473              :      * Don't allow truncate on temp tables of other backends ... their local
    2474              :      * buffer manager is not going to cope.
    2475              :      */
    2476         2566 :     if (RELATION_IS_OTHER_TEMP(rel))
    2477            0 :         ereport(ERROR,
    2478              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2479              :                  errmsg("cannot truncate temporary tables of other sessions")));
    2480              : 
    2481              :     /*
    2482              :      * Also check for active uses of the relation in the current transaction,
    2483              :      * including open scans and pending AFTER trigger events.
    2484              :      */
    2485         2566 :     CheckTableNotInUse(rel, "TRUNCATE");
    2486         2562 : }
    2487              : 
    2488              : /*
    2489              :  * storage_name
    2490              :  *    returns the name corresponding to a typstorage/attstorage enum value
    2491              :  */
    2492              : static const char *
    2493           16 : storage_name(char c)
    2494              : {
    2495           16 :     switch (c)
    2496              :     {
    2497            0 :         case TYPSTORAGE_PLAIN:
    2498            0 :             return "PLAIN";
    2499            0 :         case TYPSTORAGE_EXTERNAL:
    2500            0 :             return "EXTERNAL";
    2501            8 :         case TYPSTORAGE_EXTENDED:
    2502            8 :             return "EXTENDED";
    2503            8 :         case TYPSTORAGE_MAIN:
    2504            8 :             return "MAIN";
    2505            0 :         default:
    2506            0 :             return "???";
    2507              :     }
    2508              : }
    2509              : 
    2510              : /*----------
    2511              :  * MergeAttributes
    2512              :  *      Returns new schema given initial schema and superclasses.
    2513              :  *
    2514              :  * Input arguments:
    2515              :  * 'columns' is the column/attribute definition for the table. (It's a list
    2516              :  *      of ColumnDef's.) It is destructively changed.
    2517              :  * 'supers' is a list of OIDs of parent relations, already locked by caller.
    2518              :  * 'relpersistence' is the persistence type of the table.
    2519              :  * 'is_partition' tells if the table is a partition.
    2520              :  *
    2521              :  * Output arguments:
    2522              :  * 'supconstr' receives a list of CookedConstraint representing
    2523              :  *      CHECK constraints belonging to parent relations, updated as
    2524              :  *      necessary to be valid for the child.
    2525              :  * 'supnotnulls' receives a list of CookedConstraint representing
    2526              :  *      not-null constraints based on those from parent relations.
    2527              :  *
    2528              :  * Return value:
    2529              :  * Completed schema list.
    2530              :  *
    2531              :  * Notes:
    2532              :  *    The order in which the attributes are inherited is very important.
    2533              :  *    Intuitively, the inherited attributes should come first. If a table
    2534              :  *    inherits from multiple parents, the order of those attributes are
    2535              :  *    according to the order of the parents specified in CREATE TABLE.
    2536              :  *
    2537              :  *    Here's an example:
    2538              :  *
    2539              :  *      create table person (name text, age int4, location point);
    2540              :  *      create table emp (salary int4, manager text) inherits(person);
    2541              :  *      create table student (gpa float8) inherits (person);
    2542              :  *      create table stud_emp (percent int4) inherits (emp, student);
    2543              :  *
    2544              :  *    The order of the attributes of stud_emp is:
    2545              :  *
    2546              :  *                          person {1:name, 2:age, 3:location}
    2547              :  *                          /    \
    2548              :  *             {6:gpa}  student   emp {4:salary, 5:manager}
    2549              :  *                          \    /
    2550              :  *                         stud_emp {7:percent}
    2551              :  *
    2552              :  *     If the same attribute name appears multiple times, then it appears
    2553              :  *     in the result table in the proper location for its first appearance.
    2554              :  *
    2555              :  *     Constraints (including not-null constraints) for the child table
    2556              :  *     are the union of all relevant constraints, from both the child schema
    2557              :  *     and parent tables.  In addition, in legacy inheritance, each column that
    2558              :  *     appears in a primary key in any of the parents also gets a NOT NULL
    2559              :  *     constraint (partitioning doesn't need this, because the PK itself gets
    2560              :  *     inherited.)
    2561              :  *
    2562              :  *     The default value for a child column is defined as:
    2563              :  *      (1) If the child schema specifies a default, that value is used.
    2564              :  *      (2) If neither the child nor any parent specifies a default, then
    2565              :  *          the column will not have a default.
    2566              :  *      (3) If conflicting defaults are inherited from different parents
    2567              :  *          (and not overridden by the child), an error is raised.
    2568              :  *      (4) Otherwise the inherited default is used.
    2569              :  *
    2570              :  *      Note that the default-value infrastructure is used for generated
    2571              :  *      columns' expressions too, so most of the preceding paragraph applies
    2572              :  *      to generation expressions too.  We insist that a child column be
    2573              :  *      generated if and only if its parent(s) are, but it need not have
    2574              :  *      the same generation expression.
    2575              :  *----------
    2576              :  */
    2577              : static List *
    2578        39664 : MergeAttributes(List *columns, const List *supers, char relpersistence,
    2579              :                 bool is_partition, List **supconstr, List **supnotnulls)
    2580              : {
    2581        39664 :     List       *inh_columns = NIL;
    2582        39664 :     List       *constraints = NIL;
    2583        39664 :     List       *nnconstraints = NIL;
    2584        39664 :     bool        have_bogus_defaults = false;
    2585              :     int         child_attno;
    2586              :     static Node bogus_marker = {0}; /* marks conflicting defaults */
    2587        39664 :     List       *saved_columns = NIL;
    2588              :     ListCell   *lc;
    2589              : 
    2590              :     /*
    2591              :      * Check for and reject tables with too many columns. We perform this
    2592              :      * check relatively early for two reasons: (a) we don't run the risk of
    2593              :      * overflowing an AttrNumber in subsequent code (b) an O(n^2) algorithm is
    2594              :      * okay if we're processing <= 1600 columns, but could take minutes to
    2595              :      * execute if the user attempts to create a table with hundreds of
    2596              :      * thousands of columns.
    2597              :      *
    2598              :      * Note that we also need to check that we do not exceed this figure after
    2599              :      * including columns from inherited relations.
    2600              :      */
    2601        39664 :     if (list_length(columns) > MaxHeapAttributeNumber)
    2602            0 :         ereport(ERROR,
    2603              :                 (errcode(ERRCODE_TOO_MANY_COLUMNS),
    2604              :                  errmsg("tables can have at most %d columns",
    2605              :                         MaxHeapAttributeNumber)));
    2606              : 
    2607              :     /*
    2608              :      * Check for duplicate names in the explicit list of attributes.
    2609              :      *
    2610              :      * Although we might consider merging such entries in the same way that we
    2611              :      * handle name conflicts for inherited attributes, it seems to make more
    2612              :      * sense to assume such conflicts are errors.
    2613              :      *
    2614              :      * We don't use foreach() here because we have two nested loops over the
    2615              :      * columns list, with possible element deletions in the inner one.  If we
    2616              :      * used foreach_delete_current() it could only fix up the state of one of
    2617              :      * the loops, so it seems cleaner to use looping over list indexes for
    2618              :      * both loops.  Note that any deletion will happen beyond where the outer
    2619              :      * loop is, so its index never needs adjustment.
    2620              :      */
    2621       178037 :     for (int coldefpos = 0; coldefpos < list_length(columns); coldefpos++)
    2622              :     {
    2623       138389 :         ColumnDef  *coldef = list_nth_node(ColumnDef, columns, coldefpos);
    2624              : 
    2625       138389 :         if (!is_partition && coldef->typeName == NULL)
    2626              :         {
    2627              :             /*
    2628              :              * Typed table column option that does not belong to a column from
    2629              :              * the type.  This works because the columns from the type come
    2630              :              * first in the list.  (We omit this check for partition column
    2631              :              * lists; those are processed separately below.)
    2632              :              */
    2633            4 :             ereport(ERROR,
    2634              :                     (errcode(ERRCODE_UNDEFINED_COLUMN),
    2635              :                      errmsg("column \"%s\" does not exist",
    2636              :                             coldef->colname)));
    2637              :         }
    2638              : 
    2639              :         /* restpos scans all entries beyond coldef; incr is in loop body */
    2640      3993289 :         for (int restpos = coldefpos + 1; restpos < list_length(columns);)
    2641              :         {
    2642      3854916 :             ColumnDef  *restdef = list_nth_node(ColumnDef, columns, restpos);
    2643              : 
    2644      3854916 :             if (strcmp(coldef->colname, restdef->colname) == 0)
    2645              :             {
    2646           33 :                 if (coldef->is_from_type)
    2647              :                 {
    2648              :                     /*
    2649              :                      * merge the column options into the column from the type
    2650              :                      */
    2651           21 :                     coldef->is_not_null = restdef->is_not_null;
    2652           21 :                     coldef->raw_default = restdef->raw_default;
    2653           21 :                     coldef->cooked_default = restdef->cooked_default;
    2654           21 :                     coldef->constraints = restdef->constraints;
    2655           21 :                     coldef->is_from_type = false;
    2656           21 :                     columns = list_delete_nth_cell(columns, restpos);
    2657              :                 }
    2658              :                 else
    2659           12 :                     ereport(ERROR,
    2660              :                             (errcode(ERRCODE_DUPLICATE_COLUMN),
    2661              :                              errmsg("column \"%s\" specified more than once",
    2662              :                                     coldef->colname)));
    2663              :             }
    2664              :             else
    2665      3854883 :                 restpos++;
    2666              :         }
    2667              :     }
    2668              : 
    2669              :     /*
    2670              :      * In case of a partition, there are no new column definitions, only dummy
    2671              :      * ColumnDefs created for column constraints.  Set them aside for now and
    2672              :      * process them at the end.
    2673              :      */
    2674        39648 :     if (is_partition)
    2675              :     {
    2676         6127 :         saved_columns = columns;
    2677         6127 :         columns = NIL;
    2678              :     }
    2679              : 
    2680              :     /*
    2681              :      * Scan the parents left-to-right, and merge their attributes to form a
    2682              :      * list of inherited columns (inh_columns).
    2683              :      */
    2684        39648 :     child_attno = 0;
    2685        47348 :     foreach(lc, supers)
    2686              :     {
    2687         7756 :         Oid         parent = lfirst_oid(lc);
    2688              :         Relation    relation;
    2689              :         TupleDesc   tupleDesc;
    2690              :         TupleConstr *constr;
    2691              :         AttrMap    *newattmap;
    2692              :         List       *inherited_defaults;
    2693              :         List       *cols_with_defaults;
    2694              :         List       *nnconstrs;
    2695              :         ListCell   *lc1;
    2696              :         ListCell   *lc2;
    2697         7756 :         Bitmapset  *nncols = NULL;
    2698              : 
    2699              :         /* caller already got lock */
    2700         7756 :         relation = table_open(parent, NoLock);
    2701              : 
    2702              :         /*
    2703              :          * Check for active uses of the parent partitioned table in the
    2704              :          * current transaction, such as being used in some manner by an
    2705              :          * enclosing command.
    2706              :          */
    2707         7756 :         if (is_partition)
    2708         6127 :             CheckTableNotInUse(relation, "CREATE TABLE .. PARTITION OF");
    2709              : 
    2710              :         /*
    2711              :          * We do not allow partitioned tables and partitions to participate in
    2712              :          * regular inheritance.
    2713              :          */
    2714         7752 :         if (relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && !is_partition)
    2715            4 :             ereport(ERROR,
    2716              :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2717              :                      errmsg("cannot inherit from partitioned table \"%s\"",
    2718              :                             RelationGetRelationName(relation))));
    2719         7748 :         if (relation->rd_rel->relispartition && !is_partition)
    2720            4 :             ereport(ERROR,
    2721              :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2722              :                      errmsg("cannot inherit from partition \"%s\"",
    2723              :                             RelationGetRelationName(relation))));
    2724              : 
    2725         7744 :         if (relation->rd_rel->relkind != RELKIND_RELATION &&
    2726         6123 :             relation->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
    2727         6111 :             relation->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
    2728            0 :             ereport(ERROR,
    2729              :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2730              :                      errmsg("inherited relation \"%s\" is not a table or foreign table",
    2731              :                             RelationGetRelationName(relation))));
    2732              : 
    2733              :         /*
    2734              :          * If the parent is permanent, so must be all of its partitions.  Note
    2735              :          * that inheritance allows that case.
    2736              :          */
    2737         7744 :         if (is_partition &&
    2738         6123 :             relation->rd_rel->relpersistence != RELPERSISTENCE_TEMP &&
    2739              :             relpersistence == RELPERSISTENCE_TEMP)
    2740            4 :             ereport(ERROR,
    2741              :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2742              :                      errmsg("cannot create a temporary relation as partition of permanent relation \"%s\"",
    2743              :                             RelationGetRelationName(relation))));
    2744              : 
    2745              :         /* Permanent rels cannot inherit from temporary ones */
    2746         7740 :         if (relpersistence != RELPERSISTENCE_TEMP &&
    2747         7470 :             relation->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
    2748           16 :             ereport(ERROR,
    2749              :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2750              :                      errmsg(!is_partition
    2751              :                             ? "cannot inherit from temporary relation \"%s\""
    2752              :                             : "cannot create a permanent relation as partition of temporary relation \"%s\"",
    2753              :                             RelationGetRelationName(relation))));
    2754              : 
    2755              :         /* If existing rel is temp, it must belong to this session */
    2756         7724 :         if (RELATION_IS_OTHER_TEMP(relation))
    2757            0 :             ereport(ERROR,
    2758              :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2759              :                      errmsg(!is_partition
    2760              :                             ? "cannot inherit from temporary relation of another session"
    2761              :                             : "cannot create as partition of temporary relation of another session")));
    2762              : 
    2763              :         /*
    2764              :          * We should have an UNDER permission flag for this, but for now,
    2765              :          * demand that creator of a child table own the parent.
    2766              :          */
    2767         7724 :         if (!object_ownercheck(RelationRelationId, RelationGetRelid(relation), GetUserId()))
    2768            0 :             aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(relation->rd_rel->relkind),
    2769            0 :                            RelationGetRelationName(relation));
    2770              : 
    2771         7724 :         tupleDesc = RelationGetDescr(relation);
    2772         7724 :         constr = tupleDesc->constr;
    2773              : 
    2774              :         /*
    2775              :          * newattmap->attnums[] will contain the child-table attribute numbers
    2776              :          * for the attributes of this parent table.  (They are not the same
    2777              :          * for parents after the first one, nor if we have dropped columns.)
    2778              :          */
    2779         7724 :         newattmap = make_attrmap(tupleDesc->natts);
    2780              : 
    2781              :         /* We can't process inherited defaults until newattmap is complete. */
    2782         7724 :         inherited_defaults = cols_with_defaults = NIL;
    2783              : 
    2784              :         /*
    2785              :          * Request attnotnull on columns that have a not-null constraint
    2786              :          * that's not marked NO INHERIT (even if not valid).
    2787              :          */
    2788         7724 :         nnconstrs = RelationGetNotNullConstraints(RelationGetRelid(relation),
    2789              :                                                   true, false);
    2790        17162 :         foreach_ptr(CookedConstraint, cc, nnconstrs)
    2791         1714 :             nncols = bms_add_member(nncols, cc->attnum);
    2792              : 
    2793        23375 :         for (AttrNumber parent_attno = 1; parent_attno <= tupleDesc->natts;
    2794        15651 :              parent_attno++)
    2795              :         {
    2796        15675 :             Form_pg_attribute attribute = TupleDescAttr(tupleDesc,
    2797              :                                                         parent_attno - 1);
    2798        15675 :             char       *attributeName = NameStr(attribute->attname);
    2799              :             int         exist_attno;
    2800              :             ColumnDef  *newdef;
    2801              :             ColumnDef  *mergeddef;
    2802              : 
    2803              :             /*
    2804              :              * Ignore dropped columns in the parent.
    2805              :              */
    2806        15675 :             if (attribute->attisdropped)
    2807          132 :                 continue;       /* leave newattmap->attnums entry as zero */
    2808              : 
    2809              :             /*
    2810              :              * Create new column definition
    2811              :              */
    2812        15543 :             newdef = makeColumnDef(attributeName, attribute->atttypid,
    2813              :                                    attribute->atttypmod, attribute->attcollation);
    2814        15543 :             newdef->storage = attribute->attstorage;
    2815        15543 :             newdef->generated = attribute->attgenerated;
    2816        15543 :             if (CompressionMethodIsValid(attribute->attcompression))
    2817           24 :                 newdef->compression =
    2818           24 :                     pstrdup(GetCompressionMethodName(attribute->attcompression));
    2819              : 
    2820              :             /*
    2821              :              * Regular inheritance children are independent enough not to
    2822              :              * inherit identity columns.  But partitions are integral part of
    2823              :              * a partitioned table and inherit identity column.
    2824              :              */
    2825        15543 :             if (is_partition)
    2826        12597 :                 newdef->identity = attribute->attidentity;
    2827              : 
    2828              :             /*
    2829              :              * Does it match some previously considered column from another
    2830              :              * parent?
    2831              :              */
    2832        15543 :             exist_attno = findAttrByName(attributeName, inh_columns);
    2833        15543 :             if (exist_attno > 0)
    2834              :             {
    2835              :                 /*
    2836              :                  * Yes, try to merge the two column definitions.
    2837              :                  */
    2838          245 :                 mergeddef = MergeInheritedAttribute(inh_columns, exist_attno, newdef);
    2839              : 
    2840          221 :                 newattmap->attnums[parent_attno - 1] = exist_attno;
    2841              : 
    2842              :                 /*
    2843              :                  * Partitions have only one parent, so conflict should never
    2844              :                  * occur.
    2845              :                  */
    2846              :                 Assert(!is_partition);
    2847              :             }
    2848              :             else
    2849              :             {
    2850              :                 /*
    2851              :                  * No, create a new inherited column
    2852              :                  */
    2853        15298 :                 newdef->inhcount = 1;
    2854        15298 :                 newdef->is_local = false;
    2855        15298 :                 inh_columns = lappend(inh_columns, newdef);
    2856              : 
    2857        15298 :                 newattmap->attnums[parent_attno - 1] = ++child_attno;
    2858        15298 :                 mergeddef = newdef;
    2859              :             }
    2860              : 
    2861              :             /*
    2862              :              * mark attnotnull if parent has it
    2863              :              */
    2864        15519 :             if (bms_is_member(parent_attno, nncols))
    2865         1714 :                 mergeddef->is_not_null = true;
    2866              : 
    2867              :             /*
    2868              :              * Locate default/generation expression if any
    2869              :              */
    2870        15519 :             if (attribute->atthasdef)
    2871              :             {
    2872              :                 Node       *this_default;
    2873              : 
    2874          530 :                 this_default = TupleDescGetDefault(tupleDesc, parent_attno);
    2875          530 :                 if (this_default == NULL)
    2876            0 :                     elog(ERROR, "default expression not found for attribute %d of relation \"%s\"",
    2877              :                          parent_attno, RelationGetRelationName(relation));
    2878              : 
    2879              :                 /*
    2880              :                  * If it's a GENERATED default, it might contain Vars that
    2881              :                  * need to be mapped to the inherited column(s)' new numbers.
    2882              :                  * We can't do that till newattmap is ready, so just remember
    2883              :                  * all the inherited default expressions for the moment.
    2884              :                  */
    2885          530 :                 inherited_defaults = lappend(inherited_defaults, this_default);
    2886          530 :                 cols_with_defaults = lappend(cols_with_defaults, mergeddef);
    2887              :             }
    2888              :         }
    2889              : 
    2890              :         /*
    2891              :          * Now process any inherited default expressions, adjusting attnos
    2892              :          * using the completed newattmap map.
    2893              :          */
    2894         8230 :         forboth(lc1, inherited_defaults, lc2, cols_with_defaults)
    2895              :         {
    2896          530 :             Node       *this_default = (Node *) lfirst(lc1);
    2897          530 :             ColumnDef  *def = (ColumnDef *) lfirst(lc2);
    2898              :             bool        found_whole_row;
    2899              : 
    2900              :             /* Adjust Vars to match new table's column numbering */
    2901          530 :             this_default = map_variable_attnos(this_default,
    2902              :                                                1, 0,
    2903              :                                                newattmap,
    2904              :                                                InvalidOid, &found_whole_row);
    2905              : 
    2906              :             /*
    2907              :              * For the moment we have to reject whole-row variables.  We could
    2908              :              * convert them, if we knew the new table's rowtype OID, but that
    2909              :              * hasn't been assigned yet.  (A variable could only appear in a
    2910              :              * generation expression, so the error message is correct.)
    2911              :              */
    2912          530 :             if (found_whole_row)
    2913            0 :                 ereport(ERROR,
    2914              :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2915              :                          errmsg("cannot convert whole-row table reference"),
    2916              :                          errdetail("Generation expression for column \"%s\" contains a whole-row reference to table \"%s\".",
    2917              :                                    def->colname,
    2918              :                                    RelationGetRelationName(relation))));
    2919              : 
    2920              :             /*
    2921              :              * If we already had a default from some prior parent, check to
    2922              :              * see if they are the same.  If so, no problem; if not, mark the
    2923              :              * column as having a bogus default.  Below, we will complain if
    2924              :              * the bogus default isn't overridden by the child columns.
    2925              :              */
    2926              :             Assert(def->raw_default == NULL);
    2927          530 :             if (def->cooked_default == NULL)
    2928          502 :                 def->cooked_default = this_default;
    2929           28 :             else if (!equal(def->cooked_default, this_default))
    2930              :             {
    2931           24 :                 def->cooked_default = &bogus_marker;
    2932           24 :                 have_bogus_defaults = true;
    2933              :             }
    2934              :         }
    2935              : 
    2936              :         /*
    2937              :          * Now copy the CHECK constraints of this parent, adjusting attnos
    2938              :          * using the completed newattmap map.  Identically named constraints
    2939              :          * are merged if possible, else we throw error.
    2940              :          */
    2941         7700 :         if (constr && constr->num_check > 0)
    2942              :         {
    2943          245 :             ConstrCheck *check = constr->check;
    2944              : 
    2945          770 :             for (int i = 0; i < constr->num_check; i++)
    2946              :             {
    2947          525 :                 char       *name = check[i].ccname;
    2948              :                 Node       *expr;
    2949              :                 bool        found_whole_row;
    2950              : 
    2951              :                 /* ignore if the constraint is non-inheritable */
    2952          525 :                 if (check[i].ccnoinherit)
    2953           32 :                     continue;
    2954              : 
    2955              :                 /* Adjust Vars to match new table's column numbering */
    2956          493 :                 expr = map_variable_attnos(stringToNode(check[i].ccbin),
    2957              :                                            1, 0,
    2958              :                                            newattmap,
    2959              :                                            InvalidOid, &found_whole_row);
    2960              : 
    2961              :                 /*
    2962              :                  * For the moment we have to reject whole-row variables. We
    2963              :                  * could convert them, if we knew the new table's rowtype OID,
    2964              :                  * but that hasn't been assigned yet.
    2965              :                  */
    2966          493 :                 if (found_whole_row)
    2967            0 :                     ereport(ERROR,
    2968              :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2969              :                              errmsg("cannot convert whole-row table reference"),
    2970              :                              errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
    2971              :                                        name,
    2972              :                                        RelationGetRelationName(relation))));
    2973              : 
    2974          493 :                 constraints = MergeCheckConstraint(constraints, name, expr,
    2975          493 :                                                    check[i].ccenforced);
    2976              :             }
    2977              :         }
    2978              : 
    2979              :         /*
    2980              :          * Also copy the not-null constraints from this parent.  The
    2981              :          * attnotnull markings were already installed above.
    2982              :          */
    2983        17114 :         foreach_ptr(CookedConstraint, nn, nnconstrs)
    2984              :         {
    2985              :             Assert(nn->contype == CONSTR_NOTNULL);
    2986              : 
    2987         1714 :             nn->attnum = newattmap->attnums[nn->attnum - 1];
    2988              : 
    2989         1714 :             nnconstraints = lappend(nnconstraints, nn);
    2990              :         }
    2991              : 
    2992         7700 :         free_attrmap(newattmap);
    2993              : 
    2994              :         /*
    2995              :          * Close the parent rel, but keep our lock on it until xact commit.
    2996              :          * That will prevent someone else from deleting or ALTERing the parent
    2997              :          * before the child is committed.
    2998              :          */
    2999         7700 :         table_close(relation, NoLock);
    3000              :     }
    3001              : 
    3002              :     /*
    3003              :      * If we had no inherited attributes, the result columns are just the
    3004              :      * explicitly declared columns.  Otherwise, we need to merge the declared
    3005              :      * columns into the inherited column list.  Although, we never have any
    3006              :      * explicitly declared columns if the table is a partition.
    3007              :      */
    3008        39592 :     if (inh_columns != NIL)
    3009              :     {
    3010         7410 :         int         newcol_attno = 0;
    3011              : 
    3012         8058 :         foreach(lc, columns)
    3013              :         {
    3014          700 :             ColumnDef  *newdef = lfirst_node(ColumnDef, lc);
    3015          700 :             char       *attributeName = newdef->colname;
    3016              :             int         exist_attno;
    3017              : 
    3018              :             /*
    3019              :              * Partitions have only one parent and have no column definitions
    3020              :              * of their own, so conflict should never occur.
    3021              :              */
    3022              :             Assert(!is_partition);
    3023              : 
    3024          700 :             newcol_attno++;
    3025              : 
    3026              :             /*
    3027              :              * Does it match some inherited column?
    3028              :              */
    3029          700 :             exist_attno = findAttrByName(attributeName, inh_columns);
    3030          700 :             if (exist_attno > 0)
    3031              :             {
    3032              :                 /*
    3033              :                  * Yes, try to merge the two column definitions.
    3034              :                  */
    3035          251 :                 MergeChildAttribute(inh_columns, exist_attno, newcol_attno, newdef);
    3036              :             }
    3037              :             else
    3038              :             {
    3039              :                 /*
    3040              :                  * No, attach new column unchanged to result columns.
    3041              :                  */
    3042          449 :                 inh_columns = lappend(inh_columns, newdef);
    3043              :             }
    3044              :         }
    3045              : 
    3046         7358 :         columns = inh_columns;
    3047              : 
    3048              :         /*
    3049              :          * Check that we haven't exceeded the legal # of columns after merging
    3050              :          * in inherited columns.
    3051              :          */
    3052         7358 :         if (list_length(columns) > MaxHeapAttributeNumber)
    3053            0 :             ereport(ERROR,
    3054              :                     (errcode(ERRCODE_TOO_MANY_COLUMNS),
    3055              :                      errmsg("tables can have at most %d columns",
    3056              :                             MaxHeapAttributeNumber)));
    3057              :     }
    3058              : 
    3059              :     /*
    3060              :      * Now that we have the column definition list for a partition, we can
    3061              :      * check whether the columns referenced in the column constraint specs
    3062              :      * actually exist.  Also, merge column defaults.
    3063              :      */
    3064        39540 :     if (is_partition)
    3065              :     {
    3066         6234 :         foreach(lc, saved_columns)
    3067              :         {
    3068          151 :             ColumnDef  *restdef = lfirst(lc);
    3069          151 :             bool        found = false;
    3070              :             ListCell   *l;
    3071              : 
    3072          549 :             foreach(l, columns)
    3073              :             {
    3074          422 :                 ColumnDef  *coldef = lfirst(l);
    3075              : 
    3076          422 :                 if (strcmp(coldef->colname, restdef->colname) == 0)
    3077              :                 {
    3078          151 :                     found = true;
    3079              : 
    3080              :                     /*
    3081              :                      * Check for conflicts related to generated columns.
    3082              :                      *
    3083              :                      * Same rules as above: generated-ness has to match the
    3084              :                      * parent, but the contents of the generation expression
    3085              :                      * can be different.
    3086              :                      */
    3087          151 :                     if (coldef->generated)
    3088              :                     {
    3089           80 :                         if (restdef->raw_default && !restdef->generated)
    3090            8 :                             ereport(ERROR,
    3091              :                                     (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
    3092              :                                      errmsg("column \"%s\" inherits from generated column but specifies default",
    3093              :                                             restdef->colname)));
    3094           72 :                         if (restdef->identity)
    3095            0 :                             ereport(ERROR,
    3096              :                                     (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
    3097              :                                      errmsg("column \"%s\" inherits from generated column but specifies identity",
    3098              :                                             restdef->colname)));
    3099              :                     }
    3100              :                     else
    3101              :                     {
    3102           71 :                         if (restdef->generated)
    3103            8 :                             ereport(ERROR,
    3104              :                                     (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
    3105              :                                      errmsg("child column \"%s\" specifies generation expression",
    3106              :                                             restdef->colname),
    3107              :                                      errhint("A child table column cannot be generated unless its parent column is.")));
    3108              :                     }
    3109              : 
    3110          135 :                     if (coldef->generated && restdef->generated && coldef->generated != restdef->generated)
    3111            8 :                         ereport(ERROR,
    3112              :                                 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
    3113              :                                  errmsg("column \"%s\" inherits from generated column of different kind",
    3114              :                                         restdef->colname),
    3115              :                                  errdetail("Parent column is %s, child column is %s.",
    3116              :                                            coldef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL",
    3117              :                                            restdef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL")));
    3118              : 
    3119              :                     /*
    3120              :                      * Override the parent's default value for this column
    3121              :                      * (coldef->cooked_default) with the partition's local
    3122              :                      * definition (restdef->raw_default), if there's one. It
    3123              :                      * should be physically impossible to get a cooked default
    3124              :                      * in the local definition or a raw default in the
    3125              :                      * inherited definition, but make sure they're nulls, for
    3126              :                      * future-proofing.
    3127              :                      */
    3128              :                     Assert(restdef->cooked_default == NULL);
    3129              :                     Assert(coldef->raw_default == NULL);
    3130          127 :                     if (restdef->raw_default)
    3131              :                     {
    3132           79 :                         coldef->raw_default = restdef->raw_default;
    3133           79 :                         coldef->cooked_default = NULL;
    3134              :                     }
    3135              :                 }
    3136              :             }
    3137              : 
    3138              :             /* complain for constraints on columns not in parent */
    3139          127 :             if (!found)
    3140            0 :                 ereport(ERROR,
    3141              :                         (errcode(ERRCODE_UNDEFINED_COLUMN),
    3142              :                          errmsg("column \"%s\" does not exist",
    3143              :                                 restdef->colname)));
    3144              :         }
    3145              :     }
    3146              : 
    3147              :     /*
    3148              :      * If we found any conflicting parent default values, check to make sure
    3149              :      * they were overridden by the child.
    3150              :      */
    3151        39516 :     if (have_bogus_defaults)
    3152              :     {
    3153           60 :         foreach(lc, columns)
    3154              :         {
    3155           48 :             ColumnDef  *def = lfirst(lc);
    3156              : 
    3157           48 :             if (def->cooked_default == &bogus_marker)
    3158              :             {
    3159           12 :                 if (def->generated)
    3160            8 :                     ereport(ERROR,
    3161              :                             (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
    3162              :                              errmsg("column \"%s\" inherits conflicting generation expressions",
    3163              :                                     def->colname),
    3164              :                              errhint("To resolve the conflict, specify a generation expression explicitly.")));
    3165              :                 else
    3166            4 :                     ereport(ERROR,
    3167              :                             (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
    3168              :                              errmsg("column \"%s\" inherits conflicting default values",
    3169              :                                     def->colname),
    3170              :                              errhint("To resolve the conflict, specify a default explicitly.")));
    3171              :             }
    3172              :         }
    3173              :     }
    3174              : 
    3175        39504 :     *supconstr = constraints;
    3176        39504 :     *supnotnulls = nnconstraints;
    3177              : 
    3178        39504 :     return columns;
    3179              : }
    3180              : 
    3181              : 
    3182              : /*
    3183              :  * MergeCheckConstraint
    3184              :  *      Try to merge an inherited CHECK constraint with previous ones
    3185              :  *
    3186              :  * If we inherit identically-named constraints from multiple parents, we must
    3187              :  * merge them, or throw an error if they don't have identical definitions.
    3188              :  *
    3189              :  * constraints is a list of CookedConstraint structs for previous constraints.
    3190              :  *
    3191              :  * If the new constraint matches an existing one, then the existing
    3192              :  * constraint's inheritance count is updated.  If there is a conflict (same
    3193              :  * name but different expression), throw an error.  If the constraint neither
    3194              :  * matches nor conflicts with an existing one, a new constraint is appended to
    3195              :  * the list.
    3196              :  */
    3197              : static List *
    3198          493 : MergeCheckConstraint(List *constraints, const char *name, Node *expr, bool is_enforced)
    3199              : {
    3200              :     ListCell   *lc;
    3201              :     CookedConstraint *newcon;
    3202              : 
    3203         1521 :     foreach(lc, constraints)
    3204              :     {
    3205         1128 :         CookedConstraint *ccon = (CookedConstraint *) lfirst(lc);
    3206              : 
    3207              :         Assert(ccon->contype == CONSTR_CHECK);
    3208              : 
    3209              :         /* Non-matching names never conflict */
    3210         1128 :         if (strcmp(ccon->name, name) != 0)
    3211         1028 :             continue;
    3212              : 
    3213          100 :         if (equal(expr, ccon->expr))
    3214              :         {
    3215              :             /* OK to merge constraint with existing */
    3216          100 :             if (pg_add_s16_overflow(ccon->inhcount, 1,
    3217              :                                     &ccon->inhcount))
    3218            0 :                 ereport(ERROR,
    3219              :                         errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    3220              :                         errmsg("too many inheritance parents"));
    3221              : 
    3222              :             /*
    3223              :              * When enforceability differs, the merged constraint should be
    3224              :              * marked as ENFORCED because one of the parents is ENFORCED.
    3225              :              */
    3226          100 :             if (!ccon->is_enforced && is_enforced)
    3227              :             {
    3228           32 :                 ccon->is_enforced = true;
    3229           32 :                 ccon->skip_validation = false;
    3230              :             }
    3231              : 
    3232          100 :             return constraints;
    3233              :         }
    3234              : 
    3235            0 :         ereport(ERROR,
    3236              :                 (errcode(ERRCODE_DUPLICATE_OBJECT),
    3237              :                  errmsg("check constraint name \"%s\" appears multiple times but with different expressions",
    3238              :                         name)));
    3239              :     }
    3240              : 
    3241              :     /*
    3242              :      * Constraint couldn't be merged with an existing one and also didn't
    3243              :      * conflict with an existing one, so add it as a new one to the list.
    3244              :      */
    3245          393 :     newcon = palloc0_object(CookedConstraint);
    3246          393 :     newcon->contype = CONSTR_CHECK;
    3247          393 :     newcon->name = pstrdup(name);
    3248          393 :     newcon->expr = expr;
    3249          393 :     newcon->inhcount = 1;
    3250          393 :     newcon->is_enforced = is_enforced;
    3251          393 :     newcon->skip_validation = !is_enforced;
    3252          393 :     return lappend(constraints, newcon);
    3253              : }
    3254              : 
    3255              : /*
    3256              :  * MergeChildAttribute
    3257              :  *      Merge given child attribute definition into given inherited attribute.
    3258              :  *
    3259              :  * Input arguments:
    3260              :  * 'inh_columns' is the list of inherited ColumnDefs.
    3261              :  * 'exist_attno' is the number of the inherited attribute in inh_columns
    3262              :  * 'newcol_attno' is the attribute number in child table's schema definition
    3263              :  * 'newdef' is the column/attribute definition from the child table.
    3264              :  *
    3265              :  * The ColumnDef in 'inh_columns' list is modified.  The child attribute's
    3266              :  * ColumnDef remains unchanged.
    3267              :  *
    3268              :  * Notes:
    3269              :  * - The attribute is merged according to the rules laid out in the prologue
    3270              :  *   of MergeAttributes().
    3271              :  * - If matching inherited attribute exists but the child attribute can not be
    3272              :  *   merged into it, the function throws respective errors.
    3273              :  * - A partition can not have its own column definitions. Hence this function
    3274              :  *   is applicable only to a regular inheritance child.
    3275              :  */
    3276              : static void
    3277          251 : MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const ColumnDef *newdef)
    3278              : {
    3279          251 :     char       *attributeName = newdef->colname;
    3280              :     ColumnDef  *inhdef;
    3281              :     Oid         inhtypeid,
    3282              :                 newtypeid;
    3283              :     int32       inhtypmod,
    3284              :                 newtypmod;
    3285              :     Oid         inhcollid,
    3286              :                 newcollid;
    3287              : 
    3288          251 :     if (exist_attno == newcol_attno)
    3289          229 :         ereport(NOTICE,
    3290              :                 (errmsg("merging column \"%s\" with inherited definition",
    3291              :                         attributeName)));
    3292              :     else
    3293           22 :         ereport(NOTICE,
    3294              :                 (errmsg("moving and merging column \"%s\" with inherited definition", attributeName),
    3295              :                  errdetail("User-specified column moved to the position of the inherited column.")));
    3296              : 
    3297          251 :     inhdef = list_nth_node(ColumnDef, inh_columns, exist_attno - 1);
    3298              : 
    3299              :     /*
    3300              :      * Must have the same type and typmod
    3301              :      */
    3302          251 :     typenameTypeIdAndMod(NULL, inhdef->typeName, &inhtypeid, &inhtypmod);
    3303          251 :     typenameTypeIdAndMod(NULL, newdef->typeName, &newtypeid, &newtypmod);
    3304          251 :     if (inhtypeid != newtypeid || inhtypmod != newtypmod)
    3305            8 :         ereport(ERROR,
    3306              :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    3307              :                  errmsg("column \"%s\" has a type conflict",
    3308              :                         attributeName),
    3309              :                  errdetail("%s versus %s",
    3310              :                            format_type_with_typemod(inhtypeid, inhtypmod),
    3311              :                            format_type_with_typemod(newtypeid, newtypmod))));
    3312              : 
    3313              :     /*
    3314              :      * Must have the same collation
    3315              :      */
    3316          243 :     inhcollid = GetColumnDefCollation(NULL, inhdef, inhtypeid);
    3317          243 :     newcollid = GetColumnDefCollation(NULL, newdef, newtypeid);
    3318          243 :     if (inhcollid != newcollid)
    3319            4 :         ereport(ERROR,
    3320              :                 (errcode(ERRCODE_COLLATION_MISMATCH),
    3321              :                  errmsg("column \"%s\" has a collation conflict",
    3322              :                         attributeName),
    3323              :                  errdetail("\"%s\" versus \"%s\"",
    3324              :                            get_collation_name(inhcollid),
    3325              :                            get_collation_name(newcollid))));
    3326              : 
    3327              :     /*
    3328              :      * Identity is never inherited by a regular inheritance child. Pick
    3329              :      * child's identity definition if there's one.
    3330              :      */
    3331          239 :     inhdef->identity = newdef->identity;
    3332              : 
    3333              :     /*
    3334              :      * Copy storage parameter
    3335              :      */
    3336          239 :     if (inhdef->storage == 0)
    3337            0 :         inhdef->storage = newdef->storage;
    3338          239 :     else if (newdef->storage != 0 && inhdef->storage != newdef->storage)
    3339            4 :         ereport(ERROR,
    3340              :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    3341              :                  errmsg("column \"%s\" has a storage parameter conflict",
    3342              :                         attributeName),
    3343              :                  errdetail("%s versus %s",
    3344              :                            storage_name(inhdef->storage),
    3345              :                            storage_name(newdef->storage))));
    3346              : 
    3347              :     /*
    3348              :      * Copy compression parameter
    3349              :      */
    3350          235 :     if (inhdef->compression == NULL)
    3351          231 :         inhdef->compression = newdef->compression;
    3352            4 :     else if (newdef->compression != NULL)
    3353              :     {
    3354            4 :         if (strcmp(inhdef->compression, newdef->compression) != 0)
    3355            4 :             ereport(ERROR,
    3356              :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    3357              :                      errmsg("column \"%s\" has a compression method conflict",
    3358              :                             attributeName),
    3359              :                      errdetail("%s versus %s", inhdef->compression, newdef->compression)));
    3360              :     }
    3361              : 
    3362              :     /*
    3363              :      * Merge of not-null constraints = OR 'em together
    3364              :      */
    3365          231 :     inhdef->is_not_null |= newdef->is_not_null;
    3366              : 
    3367              :     /*
    3368              :      * Check for conflicts related to generated columns.
    3369              :      *
    3370              :      * If the parent column is generated, the child column will be made a
    3371              :      * generated column if it isn't already.  If it is a generated column,
    3372              :      * we'll take its generation expression in preference to the parent's.  We
    3373              :      * must check that the child column doesn't specify a default value or
    3374              :      * identity, which matches the rules for a single column in
    3375              :      * parse_utilcmd.c.
    3376              :      *
    3377              :      * Conversely, if the parent column is not generated, the child column
    3378              :      * can't be either.  (We used to allow that, but it results in being able
    3379              :      * to override the generation expression via UPDATEs through the parent.)
    3380              :      */
    3381          231 :     if (inhdef->generated)
    3382              :     {
    3383           41 :         if (newdef->raw_default && !newdef->generated)
    3384            8 :             ereport(ERROR,
    3385              :                     (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
    3386              :                      errmsg("column \"%s\" inherits from generated column but specifies default",
    3387              :                             inhdef->colname)));
    3388           33 :         if (newdef->identity)
    3389            8 :             ereport(ERROR,
    3390              :                     (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
    3391              :                      errmsg("column \"%s\" inherits from generated column but specifies identity",
    3392              :                             inhdef->colname)));
    3393              :     }
    3394              :     else
    3395              :     {
    3396          190 :         if (newdef->generated)
    3397            8 :             ereport(ERROR,
    3398              :                     (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
    3399              :                      errmsg("child column \"%s\" specifies generation expression",
    3400              :                             inhdef->colname),
    3401              :                      errhint("A child table column cannot be generated unless its parent column is.")));
    3402              :     }
    3403              : 
    3404          207 :     if (inhdef->generated && newdef->generated && newdef->generated != inhdef->generated)
    3405            8 :         ereport(ERROR,
    3406              :                 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
    3407              :                  errmsg("column \"%s\" inherits from generated column of different kind",
    3408              :                         inhdef->colname),
    3409              :                  errdetail("Parent column is %s, child column is %s.",
    3410              :                            inhdef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL",
    3411              :                            newdef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL")));
    3412              : 
    3413              :     /*
    3414              :      * If new def has a default, override previous default
    3415              :      */
    3416          199 :     if (newdef->raw_default != NULL)
    3417              :     {
    3418           20 :         inhdef->raw_default = newdef->raw_default;
    3419           20 :         inhdef->cooked_default = newdef->cooked_default;
    3420              :     }
    3421              : 
    3422              :     /* Mark the column as locally defined */
    3423          199 :     inhdef->is_local = true;
    3424          199 : }
    3425              : 
    3426              : /*
    3427              :  * MergeInheritedAttribute
    3428              :  *      Merge given parent attribute definition into specified attribute
    3429              :  *      inherited from the previous parents.
    3430              :  *
    3431              :  * Input arguments:
    3432              :  * 'inh_columns' is the list of previously inherited ColumnDefs.
    3433              :  * 'exist_attno' is the number the existing matching attribute in inh_columns.
    3434              :  * 'newdef' is the new parent column/attribute definition to be merged.
    3435              :  *
    3436              :  * The matching ColumnDef in 'inh_columns' list is modified and returned.
    3437              :  *
    3438              :  * Notes:
    3439              :  * - The attribute is merged according to the rules laid out in the prologue
    3440              :  *   of MergeAttributes().
    3441              :  * - If matching inherited attribute exists but the new attribute can not be
    3442              :  *   merged into it, the function throws respective errors.
    3443              :  * - A partition inherits from only a single parent. Hence this function is
    3444              :  *   applicable only to a regular inheritance.
    3445              :  */
    3446              : static ColumnDef *
    3447          245 : MergeInheritedAttribute(List *inh_columns,
    3448              :                         int exist_attno,
    3449              :                         const ColumnDef *newdef)
    3450              : {
    3451          245 :     char       *attributeName = newdef->colname;
    3452              :     ColumnDef  *prevdef;
    3453              :     Oid         prevtypeid,
    3454              :                 newtypeid;
    3455              :     int32       prevtypmod,
    3456              :                 newtypmod;
    3457              :     Oid         prevcollid,
    3458              :                 newcollid;
    3459              : 
    3460          245 :     ereport(NOTICE,
    3461              :             (errmsg("merging multiple inherited definitions of column \"%s\"",
    3462              :                     attributeName)));
    3463          245 :     prevdef = list_nth_node(ColumnDef, inh_columns, exist_attno - 1);
    3464              : 
    3465              :     /*
    3466              :      * Must have the same type and typmod
    3467              :      */
    3468          245 :     typenameTypeIdAndMod(NULL, prevdef->typeName, &prevtypeid, &prevtypmod);
    3469          245 :     typenameTypeIdAndMod(NULL, newdef->typeName, &newtypeid, &newtypmod);
    3470          245 :     if (prevtypeid != newtypeid || prevtypmod != newtypmod)
    3471            0 :         ereport(ERROR,
    3472              :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    3473              :                  errmsg("inherited column \"%s\" has a type conflict",
    3474              :                         attributeName),
    3475              :                  errdetail("%s versus %s",
    3476              :                            format_type_with_typemod(prevtypeid, prevtypmod),
    3477              :                            format_type_with_typemod(newtypeid, newtypmod))));
    3478              : 
    3479              :     /*
    3480              :      * Must have the same collation
    3481              :      */
    3482          245 :     prevcollid = GetColumnDefCollation(NULL, prevdef, prevtypeid);
    3483          245 :     newcollid = GetColumnDefCollation(NULL, newdef, newtypeid);
    3484          245 :     if (prevcollid != newcollid)
    3485            0 :         ereport(ERROR,
    3486              :                 (errcode(ERRCODE_COLLATION_MISMATCH),
    3487              :                  errmsg("inherited column \"%s\" has a collation conflict",
    3488              :                         attributeName),
    3489              :                  errdetail("\"%s\" versus \"%s\"",
    3490              :                            get_collation_name(prevcollid),
    3491              :                            get_collation_name(newcollid))));
    3492              : 
    3493              :     /*
    3494              :      * Copy/check storage parameter
    3495              :      */
    3496          245 :     if (prevdef->storage == 0)
    3497            0 :         prevdef->storage = newdef->storage;
    3498          245 :     else if (prevdef->storage != newdef->storage)
    3499            4 :         ereport(ERROR,
    3500              :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    3501              :                  errmsg("inherited column \"%s\" has a storage parameter conflict",
    3502              :                         attributeName),
    3503              :                  errdetail("%s versus %s",
    3504              :                            storage_name(prevdef->storage),
    3505              :                            storage_name(newdef->storage))));
    3506              : 
    3507              :     /*
    3508              :      * Copy/check compression parameter
    3509              :      */
    3510          241 :     if (prevdef->compression == NULL)
    3511          229 :         prevdef->compression = newdef->compression;
    3512           12 :     else if (newdef->compression != NULL)
    3513              :     {
    3514            4 :         if (strcmp(prevdef->compression, newdef->compression) != 0)
    3515            4 :             ereport(ERROR,
    3516              :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    3517              :                      errmsg("column \"%s\" has a compression method conflict",
    3518              :                             attributeName),
    3519              :                      errdetail("%s versus %s",
    3520              :                                prevdef->compression, newdef->compression)));
    3521              :     }
    3522              : 
    3523              :     /*
    3524              :      * Check for GENERATED conflicts
    3525              :      */
    3526          237 :     if (prevdef->generated != newdef->generated)
    3527           16 :         ereport(ERROR,
    3528              :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    3529              :                  errmsg("inherited column \"%s\" has a generation conflict",
    3530              :                         attributeName)));
    3531              : 
    3532              :     /*
    3533              :      * Default and other constraints are handled by the caller.
    3534              :      */
    3535              : 
    3536          221 :     if (pg_add_s16_overflow(prevdef->inhcount, 1,
    3537              :                             &prevdef->inhcount))
    3538            0 :         ereport(ERROR,
    3539              :                 errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    3540              :                 errmsg("too many inheritance parents"));
    3541              : 
    3542          221 :     return prevdef;
    3543              : }
    3544              : 
    3545              : /*
    3546              :  * StoreCatalogInheritance
    3547              :  *      Updates the system catalogs with proper inheritance information.
    3548              :  *
    3549              :  * supers is a list of the OIDs of the new relation's direct ancestors.
    3550              :  */
    3551              : static void
    3552        39061 : StoreCatalogInheritance(Oid relationId, List *supers,
    3553              :                         bool child_is_partition)
    3554              : {
    3555              :     Relation    relation;
    3556              :     int32       seqNumber;
    3557              :     ListCell   *entry;
    3558              : 
    3559              :     /*
    3560              :      * sanity checks
    3561              :      */
    3562              :     Assert(OidIsValid(relationId));
    3563              : 
    3564        39061 :     if (supers == NIL)
    3565        31943 :         return;
    3566              : 
    3567              :     /*
    3568              :      * Store INHERITS information in pg_inherits using direct ancestors only.
    3569              :      * Also enter dependencies on the direct ancestors, and make sure they are
    3570              :      * marked with relhassubclass = true.
    3571              :      *
    3572              :      * (Once upon a time, both direct and indirect ancestors were found here
    3573              :      * and then entered into pg_ipl.  Since that catalog doesn't exist
    3574              :      * anymore, there's no need to look for indirect ancestors.)
    3575              :      */
    3576         7118 :     relation = table_open(InheritsRelationId, RowExclusiveLock);
    3577              : 
    3578         7118 :     seqNumber = 1;
    3579        14458 :     foreach(entry, supers)
    3580              :     {
    3581         7340 :         Oid         parentOid = lfirst_oid(entry);
    3582              : 
    3583         7340 :         StoreCatalogInheritance1(relationId, parentOid, seqNumber, relation,
    3584              :                                  child_is_partition);
    3585         7340 :         seqNumber++;
    3586              :     }
    3587              : 
    3588         7118 :     table_close(relation, RowExclusiveLock);
    3589              : }
    3590              : 
    3591              : /*
    3592              :  * Make catalog entries showing relationId as being an inheritance child
    3593              :  * of parentOid.  inhRelation is the already-opened pg_inherits catalog.
    3594              :  */
    3595              : static void
    3596         9383 : StoreCatalogInheritance1(Oid relationId, Oid parentOid,
    3597              :                          int32 seqNumber, Relation inhRelation,
    3598              :                          bool child_is_partition)
    3599              : {
    3600              :     ObjectAddress childobject,
    3601              :                 parentobject;
    3602              : 
    3603              :     /* store the pg_inherits row */
    3604         9383 :     StoreSingleInheritance(relationId, parentOid, seqNumber);
    3605              : 
    3606              :     /*
    3607              :      * Store a dependency too
    3608              :      */
    3609         9383 :     parentobject.classId = RelationRelationId;
    3610         9383 :     parentobject.objectId = parentOid;
    3611         9383 :     parentobject.objectSubId = 0;
    3612         9383 :     childobject.classId = RelationRelationId;
    3613         9383 :     childobject.objectId = relationId;
    3614         9383 :     childobject.objectSubId = 0;
    3615              : 
    3616         9383 :     recordDependencyOn(&childobject, &parentobject,
    3617              :                        child_dependency_type(child_is_partition));
    3618              : 
    3619              :     /*
    3620              :      * Post creation hook of this inheritance. Since object_access_hook
    3621              :      * doesn't take multiple object identifiers, we relay oid of parent
    3622              :      * relation using auxiliary_id argument.
    3623              :      */
    3624         9383 :     InvokeObjectPostAlterHookArg(InheritsRelationId,
    3625              :                                  relationId, 0,
    3626              :                                  parentOid, false);
    3627              : 
    3628              :     /*
    3629              :      * Mark the parent as having subclasses.
    3630              :      */
    3631         9383 :     SetRelationHasSubclass(parentOid, true);
    3632         9383 : }
    3633              : 
    3634              : /*
    3635              :  * Look for an existing column entry with the given name.
    3636              :  *
    3637              :  * Returns the index (starting with 1) if attribute already exists in columns,
    3638              :  * 0 if it doesn't.
    3639              :  */
    3640              : static int
    3641        16243 : findAttrByName(const char *attributeName, const List *columns)
    3642              : {
    3643              :     ListCell   *lc;
    3644        16243 :     int         i = 1;
    3645              : 
    3646        29659 :     foreach(lc, columns)
    3647              :     {
    3648        13912 :         if (strcmp(attributeName, lfirst_node(ColumnDef, lc)->colname) == 0)
    3649          496 :             return i;
    3650              : 
    3651        13416 :         i++;
    3652              :     }
    3653        15747 :     return 0;
    3654              : }
    3655              : 
    3656              : 
    3657              : /*
    3658              :  * SetRelationHasSubclass
    3659              :  *      Set the value of the relation's relhassubclass field in pg_class.
    3660              :  *
    3661              :  * It's always safe to set this field to true, because all SQL commands are
    3662              :  * ready to see true and then find no children.  On the other hand, commands
    3663              :  * generally assume zero children if this is false.
    3664              :  *
    3665              :  * Caller must hold any self-exclusive lock until end of transaction.  If the
    3666              :  * new value is false, caller must have acquired that lock before reading the
    3667              :  * evidence that justified the false value.  That way, it properly waits if
    3668              :  * another backend is simultaneously concluding no need to change the tuple
    3669              :  * (new and old values are true).
    3670              :  *
    3671              :  * NOTE: an important side-effect of this operation is that an SI invalidation
    3672              :  * message is sent out to all backends --- including me --- causing plans
    3673              :  * referencing the relation to be rebuilt with the new list of children.
    3674              :  * This must happen even if we find that no change is needed in the pg_class
    3675              :  * row.
    3676              :  */
    3677              : void
    3678        11816 : SetRelationHasSubclass(Oid relationId, bool relhassubclass)
    3679              : {
    3680              :     Relation    relationRelation;
    3681              :     HeapTuple   tuple;
    3682              :     Form_pg_class classtuple;
    3683              : 
    3684              :     Assert(CheckRelationOidLockedByMe(relationId,
    3685              :                                       ShareUpdateExclusiveLock, false) ||
    3686              :            CheckRelationOidLockedByMe(relationId,
    3687              :                                       ShareRowExclusiveLock, true));
    3688              : 
    3689              :     /*
    3690              :      * Fetch a modifiable copy of the tuple, modify it, update pg_class.
    3691              :      */
    3692        11816 :     relationRelation = table_open(RelationRelationId, RowExclusiveLock);
    3693        11816 :     tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
    3694        11816 :     if (!HeapTupleIsValid(tuple))
    3695            0 :         elog(ERROR, "cache lookup failed for relation %u", relationId);
    3696        11816 :     classtuple = (Form_pg_class) GETSTRUCT(tuple);
    3697              : 
    3698        11816 :     if (classtuple->relhassubclass != relhassubclass)
    3699              :     {
    3700         5447 :         classtuple->relhassubclass = relhassubclass;
    3701         5447 :         CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
    3702              :     }
    3703              :     else
    3704              :     {
    3705              :         /* no need to change tuple, but force relcache rebuild anyway */
    3706         6369 :         CacheInvalidateRelcacheByTuple(tuple);
    3707              :     }
    3708              : 
    3709        11816 :     heap_freetuple(tuple);
    3710        11816 :     table_close(relationRelation, RowExclusiveLock);
    3711        11816 : }
    3712              : 
    3713              : /*
    3714              :  * CheckRelationTableSpaceMove
    3715              :  *      Check if relation can be moved to new tablespace.
    3716              :  *
    3717              :  * NOTE: The caller must hold AccessExclusiveLock on the relation.
    3718              :  *
    3719              :  * Returns true if the relation can be moved to the new tablespace; raises
    3720              :  * an error if it is not possible to do the move; returns false if the move
    3721              :  * would have no effect.
    3722              :  */
    3723              : bool
    3724          151 : CheckRelationTableSpaceMove(Relation rel, Oid newTableSpaceId)
    3725              : {
    3726              :     Oid         oldTableSpaceId;
    3727              : 
    3728              :     /*
    3729              :      * No work if no change in tablespace.  Note that MyDatabaseTableSpace is
    3730              :      * stored as 0.
    3731              :      */
    3732          151 :     oldTableSpaceId = rel->rd_rel->reltablespace;
    3733          151 :     if (newTableSpaceId == oldTableSpaceId ||
    3734          146 :         (newTableSpaceId == MyDatabaseTableSpace && oldTableSpaceId == 0))
    3735           10 :         return false;
    3736              : 
    3737              :     /*
    3738              :      * We cannot support moving mapped relations into different tablespaces.
    3739              :      * (In particular this eliminates all shared catalogs.)
    3740              :      */
    3741          141 :     if (RelationIsMapped(rel))
    3742            0 :         ereport(ERROR,
    3743              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3744              :                  errmsg("cannot move system relation \"%s\"",
    3745              :                         RelationGetRelationName(rel))));
    3746              : 
    3747              :     /* Cannot move a non-shared relation into pg_global */
    3748          141 :     if (newTableSpaceId == GLOBALTABLESPACE_OID)
    3749            8 :         ereport(ERROR,
    3750              :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    3751              :                  errmsg("only shared relations can be placed in pg_global tablespace")));
    3752              : 
    3753              :     /*
    3754              :      * Do not allow moving temp tables of other backends ... their local
    3755              :      * buffer manager is not going to cope.
    3756              :      */
    3757          133 :     if (RELATION_IS_OTHER_TEMP(rel))
    3758            0 :         ereport(ERROR,
    3759              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3760              :                  errmsg("cannot move temporary tables of other sessions")));
    3761              : 
    3762          133 :     return true;
    3763              : }
    3764              : 
    3765              : /*
    3766              :  * SetRelationTableSpace
    3767              :  *      Set new reltablespace and relfilenumber in pg_class entry.
    3768              :  *
    3769              :  * newTableSpaceId is the new tablespace for the relation, and
    3770              :  * newRelFilenumber its new filenumber.  If newRelFilenumber is
    3771              :  * InvalidRelFileNumber, this field is not updated.
    3772              :  *
    3773              :  * NOTE: The caller must hold AccessExclusiveLock on the relation.
    3774              :  *
    3775              :  * The caller of this routine had better check if a relation can be
    3776              :  * moved to this new tablespace by calling CheckRelationTableSpaceMove()
    3777              :  * first, and is responsible for making the change visible with
    3778              :  * CommandCounterIncrement().
    3779              :  */
    3780              : void
    3781          133 : SetRelationTableSpace(Relation rel,
    3782              :                       Oid newTableSpaceId,
    3783              :                       RelFileNumber newRelFilenumber)
    3784              : {
    3785              :     Relation    pg_class;
    3786              :     HeapTuple   tuple;
    3787              :     ItemPointerData otid;
    3788              :     Form_pg_class rd_rel;
    3789          133 :     Oid         reloid = RelationGetRelid(rel);
    3790              : 
    3791              :     Assert(CheckRelationTableSpaceMove(rel, newTableSpaceId));
    3792              : 
    3793              :     /* Get a modifiable copy of the relation's pg_class row. */
    3794          133 :     pg_class = table_open(RelationRelationId, RowExclusiveLock);
    3795              : 
    3796          133 :     tuple = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(reloid));
    3797          133 :     if (!HeapTupleIsValid(tuple))
    3798            0 :         elog(ERROR, "cache lookup failed for relation %u", reloid);
    3799          133 :     otid = tuple->t_self;
    3800          133 :     rd_rel = (Form_pg_class) GETSTRUCT(tuple);
    3801              : 
    3802              :     /* Update the pg_class row. */
    3803          266 :     rd_rel->reltablespace = (newTableSpaceId == MyDatabaseTableSpace) ?
    3804          133 :         InvalidOid : newTableSpaceId;
    3805          133 :     if (RelFileNumberIsValid(newRelFilenumber))
    3806          104 :         rd_rel->relfilenode = newRelFilenumber;
    3807          133 :     CatalogTupleUpdate(pg_class, &otid, tuple);
    3808          133 :     UnlockTuple(pg_class, &otid, InplaceUpdateTupleLock);
    3809              : 
    3810              :     /*
    3811              :      * Record dependency on tablespace.  This is only required for relations
    3812              :      * that have no physical storage.
    3813              :      */
    3814          133 :     if (!RELKIND_HAS_STORAGE(rel->rd_rel->relkind))
    3815           20 :         changeDependencyOnTablespace(RelationRelationId, reloid,
    3816              :                                      rd_rel->reltablespace);
    3817              : 
    3818          133 :     heap_freetuple(tuple);
    3819          133 :     table_close(pg_class, RowExclusiveLock);
    3820          133 : }
    3821              : 
    3822              : /*
    3823              :  *      renameatt_check         - basic sanity checks before attribute rename
    3824              :  */
    3825              : static void
    3826          669 : renameatt_check(Oid myrelid, Form_pg_class classform, bool recursing)
    3827              : {
    3828          669 :     char        relkind = classform->relkind;
    3829              : 
    3830          669 :     if (classform->reloftype && !recursing)
    3831            4 :         ereport(ERROR,
    3832              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    3833              :                  errmsg("cannot rename column of typed table")));
    3834              : 
    3835              :     /*
    3836              :      * Renaming the columns of sequences or toast tables doesn't actually
    3837              :      * break anything from the system's point of view, since internal
    3838              :      * references are by attnum.  But it doesn't seem right to allow users to
    3839              :      * change names that are hardcoded into the system, hence the following
    3840              :      * restriction.
    3841              :      */
    3842          665 :     if (relkind != RELKIND_RELATION &&
    3843           56 :         relkind != RELKIND_VIEW &&
    3844           56 :         relkind != RELKIND_MATVIEW &&
    3845           24 :         relkind != RELKIND_COMPOSITE_TYPE &&
    3846           24 :         relkind != RELKIND_INDEX &&
    3847           24 :         relkind != RELKIND_PARTITIONED_INDEX &&
    3848            0 :         relkind != RELKIND_FOREIGN_TABLE &&
    3849              :         relkind != RELKIND_PARTITIONED_TABLE)
    3850            0 :         ereport(ERROR,
    3851              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    3852              :                  errmsg("cannot rename columns of relation \"%s\"",
    3853              :                         NameStr(classform->relname)),
    3854              :                  errdetail_relkind_not_supported(relkind)));
    3855              : 
    3856              :     /*
    3857              :      * permissions checking.  only the owner of a class can change its schema.
    3858              :      */
    3859          665 :     if (!object_ownercheck(RelationRelationId, myrelid, GetUserId()))
    3860            0 :         aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(myrelid)),
    3861            0 :                        NameStr(classform->relname));
    3862          665 :     if (!allowSystemTableMods && IsSystemClass(myrelid, classform))
    3863            1 :         ereport(ERROR,
    3864              :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
    3865              :                  errmsg("permission denied: \"%s\" is a system catalog",
    3866              :                         NameStr(classform->relname))));
    3867          664 : }
    3868              : 
    3869              : /*
    3870              :  *      renameatt_internal      - workhorse for renameatt
    3871              :  *
    3872              :  * Return value is the attribute number in the 'myrelid' relation.
    3873              :  */
    3874              : static AttrNumber
    3875          366 : renameatt_internal(Oid myrelid,
    3876              :                    const char *oldattname,
    3877              :                    const char *newattname,
    3878              :                    bool recurse,
    3879              :                    bool recursing,
    3880              :                    int expected_parents,
    3881              :                    DropBehavior behavior)
    3882              : {
    3883              :     Relation    targetrelation;
    3884              :     Relation    attrelation;
    3885              :     HeapTuple   atttup;
    3886              :     Form_pg_attribute attform;
    3887              :     AttrNumber  attnum;
    3888              : 
    3889              :     /*
    3890              :      * Grab an exclusive lock on the target table, which we will NOT release
    3891              :      * until end of transaction.
    3892              :      */
    3893          366 :     targetrelation = relation_open(myrelid, AccessExclusiveLock);
    3894          366 :     renameatt_check(myrelid, RelationGetForm(targetrelation), recursing);
    3895              : 
    3896              :     /*
    3897              :      * if the 'recurse' flag is set then we are supposed to rename this
    3898              :      * attribute in all classes that inherit from 'relname' (as well as in
    3899              :      * 'relname').
    3900              :      *
    3901              :      * any permissions or problems with duplicate attributes will cause the
    3902              :      * whole transaction to abort, which is what we want -- all or nothing.
    3903              :      */
    3904          366 :     if (recurse)
    3905              :     {
    3906              :         List       *child_oids,
    3907              :                    *child_numparents;
    3908              :         ListCell   *lo,
    3909              :                    *li;
    3910              : 
    3911              :         /*
    3912              :          * we need the number of parents for each child so that the recursive
    3913              :          * calls to renameatt() can determine whether there are any parents
    3914              :          * outside the inheritance hierarchy being processed.
    3915              :          */
    3916          164 :         child_oids = find_all_inheritors(myrelid, AccessExclusiveLock,
    3917              :                                          &child_numparents);
    3918              : 
    3919              :         /*
    3920              :          * find_all_inheritors does the recursive search of the inheritance
    3921              :          * hierarchy, so all we have to do is process all of the relids in the
    3922              :          * list that it returns.
    3923              :          */
    3924          486 :         forboth(lo, child_oids, li, child_numparents)
    3925              :         {
    3926          342 :             Oid         childrelid = lfirst_oid(lo);
    3927          342 :             int         numparents = lfirst_int(li);
    3928              : 
    3929          342 :             if (childrelid == myrelid)
    3930          164 :                 continue;
    3931              :             /* note we need not recurse again */
    3932          178 :             renameatt_internal(childrelid, oldattname, newattname, false, true, numparents, behavior);
    3933              :         }
    3934              :     }
    3935              :     else
    3936              :     {
    3937              :         /*
    3938              :          * If we are told not to recurse, there had better not be any child
    3939              :          * tables; else the rename would put them out of step.
    3940              :          *
    3941              :          * expected_parents will only be 0 if we are not already recursing.
    3942              :          */
    3943          226 :         if (expected_parents == 0 &&
    3944           24 :             find_inheritance_children(myrelid, NoLock) != NIL)
    3945            8 :             ereport(ERROR,
    3946              :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    3947              :                      errmsg("inherited column \"%s\" must be renamed in child tables too",
    3948              :                             oldattname)));
    3949              :     }
    3950              : 
    3951              :     /* rename attributes in typed tables of composite type */
    3952          338 :     if (targetrelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
    3953              :     {
    3954              :         List       *child_oids;
    3955              :         ListCell   *lo;
    3956              : 
    3957           16 :         child_oids = find_typed_table_dependencies(targetrelation->rd_rel->reltype,
    3958           16 :                                                    RelationGetRelationName(targetrelation),
    3959              :                                                    behavior);
    3960              : 
    3961           16 :         foreach(lo, child_oids)
    3962            4 :             renameatt_internal(lfirst_oid(lo), oldattname, newattname, true, true, 0, behavior);
    3963              :     }
    3964              : 
    3965          334 :     attrelation = table_open(AttributeRelationId, RowExclusiveLock);
    3966              : 
    3967          334 :     atttup = SearchSysCacheCopyAttName(myrelid, oldattname);
    3968          334 :     if (!HeapTupleIsValid(atttup))
    3969           16 :         ereport(ERROR,
    3970              :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    3971              :                  errmsg("column \"%s\" does not exist",
    3972              :                         oldattname)));
    3973          318 :     attform = (Form_pg_attribute) GETSTRUCT(atttup);
    3974              : 
    3975          318 :     attnum = attform->attnum;
    3976          318 :     if (attnum <= 0)
    3977            0 :         ereport(ERROR,
    3978              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3979              :                  errmsg("cannot rename system column \"%s\"",
    3980              :                         oldattname)));
    3981              : 
    3982              :     /*
    3983              :      * if the attribute is inherited, forbid the renaming.  if this is a
    3984              :      * top-level call to renameatt(), then expected_parents will be 0, so the
    3985              :      * effect of this code will be to prohibit the renaming if the attribute
    3986              :      * is inherited at all.  if this is a recursive call to renameatt(),
    3987              :      * expected_parents will be the number of parents the current relation has
    3988              :      * within the inheritance hierarchy being processed, so we'll prohibit the
    3989              :      * renaming only if there are additional parents from elsewhere.
    3990              :      */
    3991          318 :     if (attform->attinhcount > expected_parents)
    3992           20 :         ereport(ERROR,
    3993              :                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    3994              :                  errmsg("cannot rename inherited column \"%s\"",
    3995              :                         oldattname)));
    3996              : 
    3997              :     /* new name should not already exist */
    3998          298 :     (void) check_for_column_name_collision(targetrelation, newattname, false);
    3999              : 
    4000              :     /* apply the update */
    4001          290 :     namestrcpy(&(attform->attname), newattname);
    4002              : 
    4003          290 :     CatalogTupleUpdate(attrelation, &atttup->t_self, atttup);
    4004              : 
    4005          290 :     InvokeObjectPostAlterHook(RelationRelationId, myrelid, attnum);
    4006              : 
    4007          290 :     heap_freetuple(atttup);
    4008              : 
    4009          290 :     table_close(attrelation, RowExclusiveLock);
    4010              : 
    4011          290 :     relation_close(targetrelation, NoLock); /* close rel but keep lock */
    4012              : 
    4013          290 :     return attnum;
    4014              : }
    4015              : 
    4016              : /*
    4017              :  * Perform permissions and integrity checks before acquiring a relation lock.
    4018              :  */
    4019              : static void
    4020          271 : RangeVarCallbackForRenameAttribute(const RangeVar *rv, Oid relid, Oid oldrelid,
    4021              :                                    void *arg)
    4022              : {
    4023              :     HeapTuple   tuple;
    4024              :     Form_pg_class form;
    4025              : 
    4026          271 :     tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
    4027          271 :     if (!HeapTupleIsValid(tuple))
    4028           24 :         return;                 /* concurrently dropped */
    4029          247 :     form = (Form_pg_class) GETSTRUCT(tuple);
    4030          247 :     renameatt_check(relid, form, false);
    4031          242 :     ReleaseSysCache(tuple);
    4032              : }
    4033              : 
    4034              : /*
    4035              :  *      renameatt       - changes the name of an attribute in a relation
    4036              :  *
    4037              :  * The returned ObjectAddress is that of the renamed column.
    4038              :  */
    4039              : ObjectAddress
    4040          209 : renameatt(RenameStmt *stmt)
    4041              : {
    4042              :     Oid         relid;
    4043              :     AttrNumber  attnum;
    4044              :     ObjectAddress address;
    4045              : 
    4046              :     /* lock level taken here should match renameatt_internal */
    4047          209 :     relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
    4048          209 :                                      stmt->missing_ok ? RVR_MISSING_OK : 0,
    4049              :                                      RangeVarCallbackForRenameAttribute,
    4050              :                                      NULL);
    4051              : 
    4052          200 :     if (!OidIsValid(relid))
    4053              :     {
    4054           16 :         ereport(NOTICE,
    4055              :                 (errmsg("relation \"%s\" does not exist, skipping",
    4056              :                         stmt->relation->relname)));
    4057           16 :         return InvalidObjectAddress;
    4058              :     }
    4059              : 
    4060              :     attnum =
    4061          184 :         renameatt_internal(relid,
    4062          184 :                            stmt->subname,    /* old att name */
    4063          184 :                            stmt->newname,    /* new att name */
    4064          184 :                            stmt->relation->inh, /* recursive? */
    4065              :                            false,   /* recursing? */
    4066              :                            0,   /* expected inhcount */
    4067              :                            stmt->behavior);
    4068              : 
    4069          128 :     ObjectAddressSubSet(address, RelationRelationId, relid, attnum);
    4070              : 
    4071          128 :     return address;
    4072              : }
    4073              : 
    4074              : /*
    4075              :  * same logic as renameatt_internal
    4076              :  */
    4077              : static ObjectAddress
    4078           60 : rename_constraint_internal(Oid myrelid,
    4079              :                            Oid mytypid,
    4080              :                            const char *oldconname,
    4081              :                            const char *newconname,
    4082              :                            bool recurse,
    4083              :                            bool recursing,
    4084              :                            int expected_parents)
    4085              : {
    4086           60 :     Relation    targetrelation = NULL;
    4087              :     Oid         constraintOid;
    4088              :     HeapTuple   tuple;
    4089              :     Form_pg_constraint con;
    4090              :     ObjectAddress address;
    4091              : 
    4092              :     Assert(!myrelid || !mytypid);
    4093              : 
    4094           60 :     if (mytypid)
    4095              :     {
    4096            4 :         constraintOid = get_domain_constraint_oid(mytypid, oldconname, false);
    4097              :     }
    4098              :     else
    4099              :     {
    4100           56 :         targetrelation = relation_open(myrelid, AccessExclusiveLock);
    4101              : 
    4102              :         /*
    4103              :          * don't tell it whether we're recursing; we allow changing typed
    4104              :          * tables here
    4105              :          */
    4106           56 :         renameatt_check(myrelid, RelationGetForm(targetrelation), false);
    4107              : 
    4108           56 :         constraintOid = get_relation_constraint_oid(myrelid, oldconname, false);
    4109              :     }
    4110              : 
    4111           60 :     tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constraintOid));
    4112           60 :     if (!HeapTupleIsValid(tuple))
    4113            0 :         elog(ERROR, "cache lookup failed for constraint %u",
    4114              :              constraintOid);
    4115           60 :     con = (Form_pg_constraint) GETSTRUCT(tuple);
    4116              : 
    4117           60 :     if (myrelid &&
    4118           56 :         (con->contype == CONSTRAINT_CHECK ||
    4119           16 :          con->contype == CONSTRAINT_NOTNULL) &&
    4120           44 :         !con->connoinherit)
    4121              :     {
    4122           36 :         if (recurse)
    4123              :         {
    4124              :             List       *child_oids,
    4125              :                        *child_numparents;
    4126              :             ListCell   *lo,
    4127              :                        *li;
    4128              : 
    4129           24 :             child_oids = find_all_inheritors(myrelid, AccessExclusiveLock,
    4130              :                                              &child_numparents);
    4131              : 
    4132           56 :             forboth(lo, child_oids, li, child_numparents)
    4133              :             {
    4134           32 :                 Oid         childrelid = lfirst_oid(lo);
    4135           32 :                 int         numparents = lfirst_int(li);
    4136              : 
    4137           32 :                 if (childrelid == myrelid)
    4138           24 :                     continue;
    4139              : 
    4140            8 :                 rename_constraint_internal(childrelid, InvalidOid, oldconname, newconname, false, true, numparents);
    4141              :             }
    4142              :         }
    4143              :         else
    4144              :         {
    4145           16 :             if (expected_parents == 0 &&
    4146            4 :                 find_inheritance_children(myrelid, NoLock) != NIL)
    4147            4 :                 ereport(ERROR,
    4148              :                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    4149              :                          errmsg("inherited constraint \"%s\" must be renamed in child tables too",
    4150              :                                 oldconname)));
    4151              :         }
    4152              : 
    4153           32 :         if (con->coninhcount > expected_parents)
    4154            4 :             ereport(ERROR,
    4155              :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    4156              :                      errmsg("cannot rename inherited constraint \"%s\"",
    4157              :                             oldconname)));
    4158              :     }
    4159              : 
    4160           52 :     if (con->conindid
    4161           12 :         && (con->contype == CONSTRAINT_PRIMARY
    4162            4 :             || con->contype == CONSTRAINT_UNIQUE
    4163            0 :             || con->contype == CONSTRAINT_EXCLUSION))
    4164              :         /* rename the index; this renames the constraint as well */
    4165           12 :         RenameRelationInternal(con->conindid, newconname, false, true);
    4166              :     else
    4167           40 :         RenameConstraintById(constraintOid, newconname);
    4168              : 
    4169           52 :     ObjectAddressSet(address, ConstraintRelationId, constraintOid);
    4170              : 
    4171           52 :     ReleaseSysCache(tuple);
    4172              : 
    4173           52 :     if (targetrelation)
    4174              :     {
    4175              :         /*
    4176              :          * Invalidate relcache so as others can see the new constraint name.
    4177              :          */
    4178           48 :         CacheInvalidateRelcache(targetrelation);
    4179              : 
    4180           48 :         relation_close(targetrelation, NoLock); /* close rel but keep lock */
    4181              :     }
    4182              : 
    4183           52 :     return address;
    4184              : }
    4185              : 
    4186              : ObjectAddress
    4187           56 : RenameConstraint(RenameStmt *stmt)
    4188              : {
    4189           56 :     Oid         relid = InvalidOid;
    4190           56 :     Oid         typid = InvalidOid;
    4191              : 
    4192           56 :     if (stmt->renameType == OBJECT_DOMCONSTRAINT)
    4193              :     {
    4194              :         Relation    rel;
    4195              :         HeapTuple   tup;
    4196              : 
    4197            4 :         typid = typenameTypeId(NULL, makeTypeNameFromNameList(castNode(List, stmt->object)));
    4198            4 :         rel = table_open(TypeRelationId, RowExclusiveLock);
    4199            4 :         tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
    4200            4 :         if (!HeapTupleIsValid(tup))
    4201            0 :             elog(ERROR, "cache lookup failed for type %u", typid);
    4202            4 :         checkDomainOwner(tup);
    4203            4 :         ReleaseSysCache(tup);
    4204            4 :         table_close(rel, NoLock);
    4205              :     }
    4206              :     else
    4207              :     {
    4208              :         /* lock level taken here should match rename_constraint_internal */
    4209           52 :         relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
    4210           52 :                                          stmt->missing_ok ? RVR_MISSING_OK : 0,
    4211              :                                          RangeVarCallbackForRenameAttribute,
    4212              :                                          NULL);
    4213           52 :         if (!OidIsValid(relid))
    4214              :         {
    4215            4 :             ereport(NOTICE,
    4216              :                     (errmsg("relation \"%s\" does not exist, skipping",
    4217              :                             stmt->relation->relname)));
    4218            4 :             return InvalidObjectAddress;
    4219              :         }
    4220              :     }
    4221              : 
    4222              :     return
    4223           52 :         rename_constraint_internal(relid, typid,
    4224           52 :                                    stmt->subname,
    4225           52 :                                    stmt->newname,
    4226          100 :                                    (stmt->relation &&
    4227           48 :                                     stmt->relation->inh), /* recursive? */
    4228              :                                    false,   /* recursing? */
    4229           52 :                                    0 /* expected inhcount */ );
    4230              : }
    4231              : 
    4232              : /*
    4233              :  * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW/MATERIALIZED VIEW/FOREIGN TABLE/PROPERTY GRAPH
    4234              :  * RENAME
    4235              :  */
    4236              : ObjectAddress
    4237          327 : RenameRelation(RenameStmt *stmt)
    4238              : {
    4239          327 :     bool        is_index_stmt = stmt->renameType == OBJECT_INDEX;
    4240              :     Oid         relid;
    4241              :     ObjectAddress address;
    4242              : 
    4243              :     /*
    4244              :      * Grab an exclusive lock on the target table, index, sequence, view,
    4245              :      * materialized view, or foreign table, which we will NOT release until
    4246              :      * end of transaction.
    4247              :      *
    4248              :      * Lock level used here should match RenameRelationInternal, to avoid lock
    4249              :      * escalation.  However, because ALTER INDEX can be used with any relation
    4250              :      * type, we mustn't believe without verification.
    4251              :      */
    4252              :     for (;;)
    4253            8 :     {
    4254              :         LOCKMODE    lockmode;
    4255              :         char        relkind;
    4256              :         bool        obj_is_index;
    4257              : 
    4258          335 :         lockmode = is_index_stmt ? ShareUpdateExclusiveLock : AccessExclusiveLock;
    4259              : 
    4260          335 :         relid = RangeVarGetRelidExtended(stmt->relation, lockmode,
    4261          335 :                                          stmt->missing_ok ? RVR_MISSING_OK : 0,
    4262              :                                          RangeVarCallbackForAlterRelation,
    4263              :                                          stmt);
    4264              : 
    4265          298 :         if (!OidIsValid(relid))
    4266              :         {
    4267           12 :             ereport(NOTICE,
    4268              :                     (errmsg("relation \"%s\" does not exist, skipping",
    4269              :                             stmt->relation->relname)));
    4270           12 :             return InvalidObjectAddress;
    4271              :         }
    4272              : 
    4273              :         /*
    4274              :          * We allow mismatched statement and object types (e.g., ALTER INDEX
    4275              :          * to rename a table), but we might've used the wrong lock level.  If
    4276              :          * that happens, retry with the correct lock level.  We don't bother
    4277              :          * if we already acquired AccessExclusiveLock with an index, however.
    4278              :          */
    4279          286 :         relkind = get_rel_relkind(relid);
    4280          286 :         obj_is_index = (relkind == RELKIND_INDEX ||
    4281              :                         relkind == RELKIND_PARTITIONED_INDEX);
    4282          286 :         if (obj_is_index || is_index_stmt == obj_is_index)
    4283              :             break;
    4284              : 
    4285            8 :         UnlockRelationOid(relid, lockmode);
    4286            8 :         is_index_stmt = obj_is_index;
    4287              :     }
    4288              : 
    4289              :     /* Do the work */
    4290          278 :     RenameRelationInternal(relid, stmt->newname, false, is_index_stmt);
    4291              : 
    4292          266 :     ObjectAddressSet(address, RelationRelationId, relid);
    4293              : 
    4294          266 :     return address;
    4295              : }
    4296              : 
    4297              : /*
    4298              :  *      RenameRelationInternal - change the name of a relation
    4299              :  */
    4300              : void
    4301         1102 : RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal, bool is_index)
    4302              : {
    4303              :     Relation    targetrelation;
    4304              :     Relation    relrelation;    /* for RELATION relation */
    4305              :     ItemPointerData otid;
    4306              :     HeapTuple   reltup;
    4307              :     Form_pg_class relform;
    4308              :     Oid         namespaceId;
    4309              : 
    4310              :     /*
    4311              :      * Grab a lock on the target relation, which we will NOT release until end
    4312              :      * of transaction.  We need at least a self-exclusive lock so that
    4313              :      * concurrent DDL doesn't overwrite the rename if they start updating
    4314              :      * while still seeing the old version.  The lock also guards against
    4315              :      * triggering relcache reloads in concurrent sessions, which might not
    4316              :      * handle this information changing under them.  For indexes, we can use a
    4317              :      * reduced lock level because RelationReloadIndexInfo() handles indexes
    4318              :      * specially.
    4319              :      */
    4320         1102 :     targetrelation = relation_open(myrelid, is_index ? ShareUpdateExclusiveLock : AccessExclusiveLock);
    4321         1102 :     namespaceId = RelationGetNamespace(targetrelation);
    4322              : 
    4323              :     /*
    4324              :      * Find relation's pg_class tuple, and make sure newrelname isn't in use.
    4325              :      */
    4326         1102 :     relrelation = table_open(RelationRelationId, RowExclusiveLock);
    4327              : 
    4328         1102 :     reltup = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(myrelid));
    4329         1102 :     if (!HeapTupleIsValid(reltup))  /* shouldn't happen */
    4330            0 :         elog(ERROR, "cache lookup failed for relation %u", myrelid);
    4331         1102 :     otid = reltup->t_self;
    4332         1102 :     relform = (Form_pg_class) GETSTRUCT(reltup);
    4333              : 
    4334         1102 :     if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
    4335           12 :         ereport(ERROR,
    4336              :                 (errcode(ERRCODE_DUPLICATE_TABLE),
    4337              :                  errmsg("relation \"%s\" already exists",
    4338              :                         newrelname)));
    4339              : 
    4340              :     /*
    4341              :      * RenameRelation is careful not to believe the caller's idea of the
    4342              :      * relation kind being handled.  We don't have to worry about this, but
    4343              :      * let's not be totally oblivious to it.  We can process an index as
    4344              :      * not-an-index, but not the other way around.
    4345              :      */
    4346              :     Assert(!is_index ||
    4347              :            is_index == (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
    4348              :                         targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX));
    4349              : 
    4350              :     /*
    4351              :      * Update pg_class tuple with new relname.  (Scribbling on reltup is OK
    4352              :      * because it's a copy...)
    4353              :      */
    4354         1090 :     namestrcpy(&(relform->relname), newrelname);
    4355              : 
    4356         1090 :     CatalogTupleUpdate(relrelation, &otid, reltup);
    4357         1090 :     UnlockTuple(relrelation, &otid, InplaceUpdateTupleLock);
    4358              : 
    4359         1090 :     InvokeObjectPostAlterHookArg(RelationRelationId, myrelid, 0,
    4360              :                                  InvalidOid, is_internal);
    4361              : 
    4362         1090 :     heap_freetuple(reltup);
    4363         1090 :     table_close(relrelation, RowExclusiveLock);
    4364              : 
    4365              :     /*
    4366              :      * Also rename the associated type, if any.
    4367              :      */
    4368         1090 :     if (OidIsValid(targetrelation->rd_rel->reltype))
    4369          144 :         RenameTypeInternal(targetrelation->rd_rel->reltype,
    4370              :                            newrelname, namespaceId);
    4371              : 
    4372              :     /*
    4373              :      * Also rename the associated constraint, if any.
    4374              :      */
    4375         1090 :     if (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
    4376          603 :         targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
    4377              :     {
    4378          499 :         Oid         constraintId = get_index_constraint(myrelid);
    4379              : 
    4380          499 :         if (OidIsValid(constraintId))
    4381           24 :             RenameConstraintById(constraintId, newrelname);
    4382              :     }
    4383              : 
    4384              :     /*
    4385              :      * Close rel, but keep lock!
    4386              :      */
    4387         1090 :     relation_close(targetrelation, NoLock);
    4388         1090 : }
    4389              : 
    4390              : /*
    4391              :  *      ResetRelRewrite - reset relrewrite
    4392              :  */
    4393              : void
    4394          378 : ResetRelRewrite(Oid myrelid)
    4395              : {
    4396              :     Relation    relrelation;    /* for RELATION relation */
    4397              :     HeapTuple   reltup;
    4398              :     Form_pg_class relform;
    4399              : 
    4400              :     /*
    4401              :      * Find relation's pg_class tuple.
    4402              :      */
    4403          378 :     relrelation = table_open(RelationRelationId, RowExclusiveLock);
    4404              : 
    4405          378 :     reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
    4406          378 :     if (!HeapTupleIsValid(reltup))  /* shouldn't happen */
    4407            0 :         elog(ERROR, "cache lookup failed for relation %u", myrelid);
    4408          378 :     relform = (Form_pg_class) GETSTRUCT(reltup);
    4409              : 
    4410              :     /*
    4411              :      * Update pg_class tuple.
    4412              :      */
    4413          378 :     relform->relrewrite = InvalidOid;
    4414              : 
    4415          378 :     CatalogTupleUpdate(relrelation, &reltup->t_self, reltup);
    4416              : 
    4417          378 :     heap_freetuple(reltup);
    4418          378 :     table_close(relrelation, RowExclusiveLock);
    4419          378 : }
    4420              : 
    4421              : /*
    4422              :  * Disallow ALTER TABLE (and similar commands) when the current backend has
    4423              :  * any open reference to the target table besides the one just acquired by
    4424              :  * the calling command; this implies there's an open cursor or active plan.
    4425              :  * We need this check because our lock doesn't protect us against stomping
    4426              :  * on our own foot, only other people's feet!
    4427              :  *
    4428              :  * For ALTER TABLE, the only case known to cause serious trouble is ALTER
    4429              :  * COLUMN TYPE, and some changes are obviously pretty benign, so this could
    4430              :  * possibly be relaxed to only error out for certain types of alterations.
    4431              :  * But the use-case for allowing any of these things is not obvious, so we
    4432              :  * won't work hard at it for now.
    4433              :  *
    4434              :  * We also reject these commands if there are any pending AFTER trigger events
    4435              :  * for the rel.  This is certainly necessary for the rewriting variants of
    4436              :  * ALTER TABLE, because they don't preserve tuple TIDs and so the pending
    4437              :  * events would try to fetch the wrong tuples.  It might be overly cautious
    4438              :  * in other cases, but again it seems better to err on the side of paranoia.
    4439              :  *
    4440              :  * REINDEX calls this with "rel" referencing the index to be rebuilt; here
    4441              :  * we are worried about active indexscans on the index.  The trigger-event
    4442              :  * check can be skipped, since we are doing no damage to the parent table.
    4443              :  *
    4444              :  * The statement name (eg, "ALTER TABLE") is passed for use in error messages.
    4445              :  */
    4446              : void
    4447       110026 : CheckTableNotInUse(Relation rel, const char *stmt)
    4448              : {
    4449              :     int         expected_refcnt;
    4450              : 
    4451       110026 :     expected_refcnt = rel->rd_isnailed ? 2 : 1;
    4452       110026 :     if (rel->rd_refcnt != expected_refcnt)
    4453           28 :         ereport(ERROR,
    4454              :                 (errcode(ERRCODE_OBJECT_IN_USE),
    4455              :         /* translator: first %s is a SQL command, eg ALTER TABLE */
    4456              :                  errmsg("cannot %s \"%s\" because it is being used by active queries in this session",
    4457              :                         stmt, RelationGetRelationName(rel))));
    4458              : 
    4459       109998 :     if (rel->rd_rel->relkind != RELKIND_INDEX &&
    4460       179818 :         rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX &&
    4461        89186 :         AfterTriggerPendingOnRel(RelationGetRelid(rel)))
    4462           12 :         ereport(ERROR,
    4463              :                 (errcode(ERRCODE_OBJECT_IN_USE),
    4464              :         /* translator: first %s is a SQL command, eg ALTER TABLE */
    4465              :                  errmsg("cannot %s \"%s\" because it has pending trigger events",
    4466              :                         stmt, RelationGetRelationName(rel))));
    4467       109986 : }
    4468              : 
    4469              : /*
    4470              :  * CheckAlterTableIsSafe
    4471              :  *      Verify that it's safe to allow ALTER TABLE on this relation.
    4472              :  *
    4473              :  * This consists of CheckTableNotInUse() plus a check that the relation
    4474              :  * isn't another session's temp table.  We must split out the temp-table
    4475              :  * check because there are callers of CheckTableNotInUse() that don't want
    4476              :  * that, notably DROP TABLE.  (We must allow DROP or we couldn't clean out
    4477              :  * an orphaned temp schema.)  Compare truncate_check_activity().
    4478              :  */
    4479              : static void
    4480        38457 : CheckAlterTableIsSafe(Relation rel)
    4481              : {
    4482              :     /*
    4483              :      * Don't allow ALTER on temp tables of other backends.  Their local buffer
    4484              :      * manager is not going to cope if we need to change the table's contents.
    4485              :      * Even if we don't, there may be optimizations that assume temp tables
    4486              :      * aren't subject to such interference.
    4487              :      */
    4488        38457 :     if (RELATION_IS_OTHER_TEMP(rel))
    4489            0 :         ereport(ERROR,
    4490              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    4491              :                  errmsg("cannot alter temporary tables of other sessions")));
    4492              : 
    4493              :     /*
    4494              :      * Also check for active uses of the relation in the current transaction,
    4495              :      * including open scans and pending AFTER trigger events.
    4496              :      */
    4497        38457 :     CheckTableNotInUse(rel, "ALTER TABLE");
    4498        38433 : }
    4499              : 
    4500              : /*
    4501              :  * AlterTableLookupRelation
    4502              :  *      Look up, and lock, the OID for the relation named by an alter table
    4503              :  *      statement.
    4504              :  */
    4505              : Oid
    4506        20650 : AlterTableLookupRelation(AlterTableStmt *stmt, LOCKMODE lockmode)
    4507              : {
    4508        41235 :     return RangeVarGetRelidExtended(stmt->relation, lockmode,
    4509        20650 :                                     stmt->missing_ok ? RVR_MISSING_OK : 0,
    4510              :                                     RangeVarCallbackForAlterRelation,
    4511              :                                     stmt);
    4512              : }
    4513              : 
    4514              : /*
    4515              :  * AlterTable
    4516              :  *      Execute ALTER TABLE, which can be a list of subcommands
    4517              :  *
    4518              :  * ALTER TABLE is performed in three phases:
    4519              :  *      1. Examine subcommands and perform pre-transformation checking.
    4520              :  *      2. Validate and transform subcommands, and update system catalogs.
    4521              :  *      3. Scan table(s) to check new constraints, and optionally recopy
    4522              :  *         the data into new table(s).
    4523              :  * Phase 3 is not performed unless one or more of the subcommands requires
    4524              :  * it.  The intention of this design is to allow multiple independent
    4525              :  * updates of the table schema to be performed with only one pass over the
    4526              :  * data.
    4527              :  *
    4528              :  * ATPrepCmd performs phase 1.  A "work queue" entry is created for
    4529              :  * each table to be affected (there may be multiple affected tables if the
    4530              :  * commands traverse a table inheritance hierarchy).  Also we do preliminary
    4531              :  * validation of the subcommands.  Because earlier subcommands may change
    4532              :  * the catalog state seen by later commands, there are limits to what can
    4533              :  * be done in this phase.  Generally, this phase acquires table locks,
    4534              :  * checks permissions and relkind, and recurses to find child tables.
    4535              :  *
    4536              :  * ATRewriteCatalogs performs phase 2 for each affected table.
    4537              :  * Certain subcommands need to be performed before others to avoid
    4538              :  * unnecessary conflicts; for example, DROP COLUMN should come before
    4539              :  * ADD COLUMN.  Therefore phase 1 divides the subcommands into multiple
    4540              :  * lists, one for each logical "pass" of phase 2.
    4541              :  *
    4542              :  * ATRewriteTables performs phase 3 for those tables that need it.
    4543              :  *
    4544              :  * For most subcommand types, phases 2 and 3 do no explicit recursion,
    4545              :  * since phase 1 already does it.  However, for certain subcommand types
    4546              :  * it is only possible to determine how to recurse at phase 2 time; for
    4547              :  * those cases, phase 1 sets the cmd->recurse flag.
    4548              :  *
    4549              :  * Thanks to the magic of MVCC, an error anywhere along the way rolls back
    4550              :  * the whole operation; we don't have to do anything special to clean up.
    4551              :  *
    4552              :  * The caller must lock the relation, with an appropriate lock level
    4553              :  * for the subcommands requested, using AlterTableGetLockLevel(stmt->cmds)
    4554              :  * or higher. We pass the lock level down
    4555              :  * so that we can apply it recursively to inherited tables. Note that the
    4556              :  * lock level we want as we recurse might well be higher than required for
    4557              :  * that specific subcommand. So we pass down the overall lock requirement,
    4558              :  * rather than reassess it at lower levels.
    4559              :  *
    4560              :  * The caller also provides a "context" which is to be passed back to
    4561              :  * utility.c when we need to execute a subcommand such as CREATE INDEX.
    4562              :  * Some of the fields therein, such as the relid, are used here as well.
    4563              :  */
    4564              : void
    4565        20477 : AlterTable(AlterTableStmt *stmt, LOCKMODE lockmode,
    4566              :            AlterTableUtilityContext *context)
    4567              : {
    4568              :     Relation    rel;
    4569              : 
    4570              :     /* Caller is required to provide an adequate lock. */
    4571        20477 :     rel = relation_open(context->relid, NoLock);
    4572              : 
    4573        20477 :     CheckAlterTableIsSafe(rel);
    4574              : 
    4575        20465 :     ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode, context);
    4576        17618 : }
    4577              : 
    4578              : /*
    4579              :  * AlterTableInternal
    4580              :  *
    4581              :  * ALTER TABLE with target specified by OID
    4582              :  *
    4583              :  * We do not reject if the relation is already open, because it's quite
    4584              :  * likely that one or more layers of caller have it open.  That means it
    4585              :  * is unsafe to use this entry point for alterations that could break
    4586              :  * existing query plans.  On the assumption it's not used for such, we
    4587              :  * don't have to reject pending AFTER triggers, either.
    4588              :  *
    4589              :  * Also, since we don't have an AlterTableUtilityContext, this cannot be
    4590              :  * used for any subcommand types that require parse transformation or
    4591              :  * could generate subcommands that have to be passed to ProcessUtility.
    4592              :  */
    4593              : void
    4594          194 : AlterTableInternal(Oid relid, List *cmds, bool recurse)
    4595              : {
    4596              :     Relation    rel;
    4597          194 :     LOCKMODE    lockmode = AlterTableGetLockLevel(cmds);
    4598              : 
    4599          194 :     rel = relation_open(relid, lockmode);
    4600              : 
    4601          194 :     EventTriggerAlterTableRelid(relid);
    4602              : 
    4603          194 :     ATController(NULL, rel, cmds, recurse, lockmode, NULL);
    4604          194 : }
    4605              : 
    4606              : /*
    4607              :  * AlterTableGetLockLevel
    4608              :  *
    4609              :  * Sets the overall lock level required for the supplied list of subcommands.
    4610              :  * Policy for doing this set according to needs of AlterTable(), see
    4611              :  * comments there for overall explanation.
    4612              :  *
    4613              :  * Function is called before and after parsing, so it must give same
    4614              :  * answer each time it is called. Some subcommands are transformed
    4615              :  * into other subcommand types, so the transform must never be made to a
    4616              :  * lower lock level than previously assigned. All transforms are noted below.
    4617              :  *
    4618              :  * Since this is called before we lock the table we cannot use table metadata
    4619              :  * to influence the type of lock we acquire.
    4620              :  *
    4621              :  * There should be no lockmodes hardcoded into the subcommand functions. All
    4622              :  * lockmode decisions for ALTER TABLE are made here only. The one exception is
    4623              :  * ALTER TABLE RENAME which is treated as a different statement type T_RenameStmt
    4624              :  * and does not travel through this section of code and cannot be combined with
    4625              :  * any of the subcommands given here.
    4626              :  *
    4627              :  * Note that Hot Standby only knows about AccessExclusiveLocks on the primary
    4628              :  * so any changes that might affect SELECTs running on standbys need to use
    4629              :  * AccessExclusiveLocks even if you think a lesser lock would do, unless you
    4630              :  * have a solution for that also.
    4631              :  *
    4632              :  * Also note that pg_dump uses only an AccessShareLock, meaning that anything
    4633              :  * that takes a lock less than AccessExclusiveLock can change object definitions
    4634              :  * while pg_dump is running. Be careful to check that the appropriate data is
    4635              :  * derived by pg_dump using an MVCC snapshot, rather than syscache lookups,
    4636              :  * otherwise we might end up with an inconsistent dump that can't restore.
    4637              :  */
    4638              : LOCKMODE
    4639        20844 : AlterTableGetLockLevel(List *cmds)
    4640              : {
    4641              :     /*
    4642              :      * This only works if we read catalog tables using MVCC snapshots.
    4643              :      */
    4644              :     ListCell   *lcmd;
    4645        20844 :     LOCKMODE    lockmode = ShareUpdateExclusiveLock;
    4646              : 
    4647        42516 :     foreach(lcmd, cmds)
    4648              :     {
    4649        21672 :         AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
    4650        21672 :         LOCKMODE    cmd_lockmode = AccessExclusiveLock; /* default for compiler */
    4651              : 
    4652        21672 :         switch (cmd->subtype)
    4653              :         {
    4654              :                 /*
    4655              :                  * These subcommands rewrite the heap, so require full locks.
    4656              :                  */
    4657         2586 :             case AT_AddColumn:  /* may rewrite heap, in some cases and visible
    4658              :                                  * to SELECT */
    4659              :             case AT_SetAccessMethod:    /* must rewrite heap */
    4660              :             case AT_SetTableSpace:  /* must rewrite heap */
    4661              :             case AT_AlterColumnType:    /* must rewrite heap */
    4662         2586 :                 cmd_lockmode = AccessExclusiveLock;
    4663         2586 :                 break;
    4664              : 
    4665              :                 /*
    4666              :                  * These subcommands may require addition of toast tables. If
    4667              :                  * we add a toast table to a table currently being scanned, we
    4668              :                  * might miss data added to the new toast table by concurrent
    4669              :                  * insert transactions.
    4670              :                  */
    4671          159 :             case AT_SetStorage: /* may add toast tables, see
    4672              :                                  * ATRewriteCatalogs() */
    4673          159 :                 cmd_lockmode = AccessExclusiveLock;
    4674          159 :                 break;
    4675              : 
    4676              :                 /*
    4677              :                  * Removing constraints can affect SELECTs that have been
    4678              :                  * optimized assuming the constraint holds true. See also
    4679              :                  * CloneFkReferenced.
    4680              :                  */
    4681          759 :             case AT_DropConstraint: /* as DROP INDEX */
    4682              :             case AT_DropNotNull:    /* may change some SQL plans */
    4683          759 :                 cmd_lockmode = AccessExclusiveLock;
    4684          759 :                 break;
    4685              : 
    4686              :                 /*
    4687              :                  * Subcommands that may be visible to concurrent SELECTs
    4688              :                  */
    4689         1191 :             case AT_DropColumn: /* change visible to SELECT */
    4690              :             case AT_AddColumnToView:    /* CREATE VIEW */
    4691              :             case AT_DropOids:   /* used to equiv to DropColumn */
    4692              :             case AT_EnableAlwaysRule:   /* may change SELECT rules */
    4693              :             case AT_EnableReplicaRule:  /* may change SELECT rules */
    4694              :             case AT_EnableRule: /* may change SELECT rules */
    4695              :             case AT_DisableRule:    /* may change SELECT rules */
    4696         1191 :                 cmd_lockmode = AccessExclusiveLock;
    4697         1191 :                 break;
    4698              : 
    4699              :                 /*
    4700              :                  * Changing owner may remove implicit SELECT privileges
    4701              :                  */
    4702         1140 :             case AT_ChangeOwner:    /* change visible to SELECT */
    4703         1140 :                 cmd_lockmode = AccessExclusiveLock;
    4704         1140 :                 break;
    4705              : 
    4706              :                 /*
    4707              :                  * Changing foreign table options may affect optimization.
    4708              :                  */
    4709          140 :             case AT_GenericOptions:
    4710              :             case AT_AlterColumnGenericOptions:
    4711          140 :                 cmd_lockmode = AccessExclusiveLock;
    4712          140 :                 break;
    4713              : 
    4714              :                 /*
    4715              :                  * These subcommands affect write operations only.
    4716              :                  */
    4717          191 :             case AT_EnableTrig:
    4718              :             case AT_EnableAlwaysTrig:
    4719              :             case AT_EnableReplicaTrig:
    4720              :             case AT_EnableTrigAll:
    4721              :             case AT_EnableTrigUser:
    4722              :             case AT_DisableTrig:
    4723              :             case AT_DisableTrigAll:
    4724              :             case AT_DisableTrigUser:
    4725          191 :                 cmd_lockmode = ShareRowExclusiveLock;
    4726          191 :                 break;
    4727              : 
    4728              :                 /*
    4729              :                  * These subcommands affect write operations only. XXX
    4730              :                  * Theoretically, these could be ShareRowExclusiveLock.
    4731              :                  */
    4732         2026 :             case AT_ColumnDefault:
    4733              :             case AT_CookedColumnDefault:
    4734              :             case AT_AlterConstraint:
    4735              :             case AT_AddIndex:   /* from ADD CONSTRAINT */
    4736              :             case AT_AddIndexConstraint:
    4737              :             case AT_ReplicaIdentity:
    4738              :             case AT_SetNotNull:
    4739              :             case AT_EnableRowSecurity:
    4740              :             case AT_DisableRowSecurity:
    4741              :             case AT_ForceRowSecurity:
    4742              :             case AT_NoForceRowSecurity:
    4743              :             case AT_AddIdentity:
    4744              :             case AT_DropIdentity:
    4745              :             case AT_SetIdentity:
    4746              :             case AT_SetExpression:
    4747              :             case AT_DropExpression:
    4748              :             case AT_SetCompression:
    4749         2026 :                 cmd_lockmode = AccessExclusiveLock;
    4750         2026 :                 break;
    4751              : 
    4752         9232 :             case AT_AddConstraint:
    4753              :             case AT_ReAddConstraint:    /* becomes AT_AddConstraint */
    4754              :             case AT_ReAddDomainConstraint:  /* becomes AT_AddConstraint */
    4755         9232 :                 if (IsA(cmd->def, Constraint))
    4756              :                 {
    4757         9232 :                     Constraint *con = (Constraint *) cmd->def;
    4758              : 
    4759         9232 :                     switch (con->contype)
    4760              :                     {
    4761         6742 :                         case CONSTR_EXCLUSION:
    4762              :                         case CONSTR_PRIMARY:
    4763              :                         case CONSTR_UNIQUE:
    4764              : 
    4765              :                             /*
    4766              :                              * Cases essentially the same as CREATE INDEX. We
    4767              :                              * could reduce the lock strength to ShareLock if
    4768              :                              * we can work out how to allow concurrent catalog
    4769              :                              * updates. XXX Might be set down to
    4770              :                              * ShareRowExclusiveLock but requires further
    4771              :                              * analysis.
    4772              :                              */
    4773         6742 :                             cmd_lockmode = AccessExclusiveLock;
    4774         6742 :                             break;
    4775         1687 :                         case CONSTR_FOREIGN:
    4776              : 
    4777              :                             /*
    4778              :                              * We add triggers to both tables when we add a
    4779              :                              * Foreign Key, so the lock level must be at least
    4780              :                              * as strong as CREATE TRIGGER.
    4781              :                              */
    4782         1687 :                             cmd_lockmode = ShareRowExclusiveLock;
    4783         1687 :                             break;
    4784              : 
    4785          803 :                         default:
    4786          803 :                             cmd_lockmode = AccessExclusiveLock;
    4787              :                     }
    4788              :                 }
    4789         9232 :                 break;
    4790              : 
    4791              :                 /*
    4792              :                  * These subcommands affect inheritance behaviour. Queries
    4793              :                  * started before us will continue to see the old inheritance
    4794              :                  * behaviour, while queries started after we commit will see
    4795              :                  * new behaviour. No need to prevent reads or writes to the
    4796              :                  * subtable while we hook it up though. Changing the TupDesc
    4797              :                  * may be a problem, so keep highest lock.
    4798              :                  */
    4799          386 :             case AT_AddInherit:
    4800              :             case AT_DropInherit:
    4801          386 :                 cmd_lockmode = AccessExclusiveLock;
    4802          386 :                 break;
    4803              : 
    4804              :                 /*
    4805              :                  * These subcommands affect implicit row type conversion. They
    4806              :                  * have affects similar to CREATE/DROP CAST on queries. don't
    4807              :                  * provide for invalidating parse trees as a result of such
    4808              :                  * changes, so we keep these at AccessExclusiveLock.
    4809              :                  */
    4810           46 :             case AT_AddOf:
    4811              :             case AT_DropOf:
    4812           46 :                 cmd_lockmode = AccessExclusiveLock;
    4813           46 :                 break;
    4814              : 
    4815              :                 /*
    4816              :                  * Only used by CREATE OR REPLACE VIEW which must conflict
    4817              :                  * with an SELECTs currently using the view.
    4818              :                  */
    4819          133 :             case AT_ReplaceRelOptions:
    4820          133 :                 cmd_lockmode = AccessExclusiveLock;
    4821          133 :                 break;
    4822              : 
    4823              :                 /*
    4824              :                  * These subcommands affect general strategies for performance
    4825              :                  * and maintenance, though don't change the semantic results
    4826              :                  * from normal data reads and writes. Delaying an ALTER TABLE
    4827              :                  * behind currently active writes only delays the point where
    4828              :                  * the new strategy begins to take effect, so there is no
    4829              :                  * benefit in waiting. In this case the minimum restriction
    4830              :                  * applies: we don't currently allow concurrent catalog
    4831              :                  * updates.
    4832              :                  */
    4833          154 :             case AT_SetStatistics:  /* Uses MVCC in getTableAttrs() */
    4834              :             case AT_ClusterOn:  /* Uses MVCC in getIndexes() */
    4835              :             case AT_DropCluster:    /* Uses MVCC in getIndexes() */
    4836              :             case AT_SetOptions: /* Uses MVCC in getTableAttrs() */
    4837              :             case AT_ResetOptions:   /* Uses MVCC in getTableAttrs() */
    4838          154 :                 cmd_lockmode = ShareUpdateExclusiveLock;
    4839          154 :                 break;
    4840              : 
    4841           74 :             case AT_SetLogged:
    4842              :             case AT_SetUnLogged:
    4843           74 :                 cmd_lockmode = AccessExclusiveLock;
    4844           74 :                 break;
    4845              : 
    4846          275 :             case AT_ValidateConstraint: /* Uses MVCC in getConstraints() */
    4847          275 :                 cmd_lockmode = ShareUpdateExclusiveLock;
    4848          275 :                 break;
    4849              : 
    4850              :                 /*
    4851              :                  * Rel options are more complex than first appears. Options
    4852              :                  * are set here for tables, views and indexes; for historical
    4853              :                  * reasons these can all be used with ALTER TABLE, so we can't
    4854              :                  * decide between them using the basic grammar.
    4855              :                  */
    4856          491 :             case AT_SetRelOptions:  /* Uses MVCC in getIndexes() and
    4857              :                                      * getTables() */
    4858              :             case AT_ResetRelOptions:    /* Uses MVCC in getIndexes() and
    4859              :                                          * getTables() */
    4860          491 :                 cmd_lockmode = AlterTableGetRelOptionsLockLevel((List *) cmd->def);
    4861          491 :                 break;
    4862              : 
    4863         1869 :             case AT_AttachPartition:
    4864         1869 :                 cmd_lockmode = ShareUpdateExclusiveLock;
    4865         1869 :                 break;
    4866              : 
    4867          377 :             case AT_DetachPartition:
    4868          377 :                 if (((PartitionCmd *) cmd->def)->concurrent)
    4869           87 :                     cmd_lockmode = ShareUpdateExclusiveLock;
    4870              :                 else
    4871          290 :                     cmd_lockmode = AccessExclusiveLock;
    4872          377 :                 break;
    4873              : 
    4874           11 :             case AT_DetachPartitionFinalize:
    4875           11 :                 cmd_lockmode = ShareUpdateExclusiveLock;
    4876           11 :                 break;
    4877              : 
    4878          432 :             case AT_MergePartitions:
    4879              :             case AT_SplitPartition:
    4880          432 :                 cmd_lockmode = AccessExclusiveLock;
    4881          432 :                 break;
    4882              : 
    4883            0 :             default:            /* oops */
    4884            0 :                 elog(ERROR, "unrecognized alter table type: %d",
    4885              :                      (int) cmd->subtype);
    4886              :                 break;
    4887              :         }
    4888              : 
    4889              :         /*
    4890              :          * Take the greatest lockmode from any subcommand
    4891              :          */
    4892        21672 :         if (cmd_lockmode > lockmode)
    4893        18075 :             lockmode = cmd_lockmode;
    4894              :     }
    4895              : 
    4896        20844 :     return lockmode;
    4897              : }
    4898              : 
    4899              : /*
    4900              :  * ATController provides top level control over the phases.
    4901              :  *
    4902              :  * parsetree is passed in to allow it to be passed to event triggers
    4903              :  * when requested.
    4904              :  */
    4905              : static void
    4906        20659 : ATController(AlterTableStmt *parsetree,
    4907              :              Relation rel, List *cmds, bool recurse, LOCKMODE lockmode,
    4908              :              AlterTableUtilityContext *context)
    4909              : {
    4910        20659 :     List       *wqueue = NIL;
    4911              :     ListCell   *lcmd;
    4912              : 
    4913              :     /* Phase 1: preliminary examination of commands, create work queue */
    4914        41845 :     foreach(lcmd, cmds)
    4915              :     {
    4916        21483 :         AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
    4917              : 
    4918        21483 :         ATPrepCmd(&wqueue, rel, cmd, recurse, false, lockmode, context);
    4919              :     }
    4920              : 
    4921              :     /* Close the relation, but keep lock until commit */
    4922        20362 :     relation_close(rel, NoLock);
    4923              : 
    4924              :     /* Phase 2: update system catalogs */
    4925        20362 :     ATRewriteCatalogs(&wqueue, lockmode, context);
    4926              : 
    4927              :     /* Phase 3: scan/rewrite tables as needed, and run afterStmts */
    4928        18193 :     ATRewriteTables(parsetree, &wqueue, lockmode, context);
    4929        17812 : }
    4930              : 
    4931              : /*
    4932              :  * ATPrepCmd
    4933              :  *
    4934              :  * Traffic cop for ALTER TABLE Phase 1 operations, including simple
    4935              :  * recursion and permission checks.
    4936              :  *
    4937              :  * Caller must have acquired appropriate lock type on relation already.
    4938              :  * This lock should be held until commit.
    4939              :  */
    4940              : static void
    4941        22094 : ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
    4942              :           bool recurse, bool recursing, LOCKMODE lockmode,
    4943              :           AlterTableUtilityContext *context)
    4944              : {
    4945              :     AlteredTableInfo *tab;
    4946        22094 :     AlterTablePass pass = AT_PASS_UNSET;
    4947              : 
    4948              :     /* Find or create work queue entry for this table */
    4949        22094 :     tab = ATGetQueueEntry(wqueue, rel);
    4950              : 
    4951              :     /*
    4952              :      * Disallow any ALTER TABLE other than ALTER TABLE DETACH FINALIZE on
    4953              :      * partitions that are pending detach.
    4954              :      */
    4955        22094 :     if (rel->rd_rel->relispartition &&
    4956         1794 :         cmd->subtype != AT_DetachPartitionFinalize &&
    4957          897 :         PartitionHasPendingDetach(RelationGetRelid(rel)))
    4958            1 :         ereport(ERROR,
    4959              :                 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    4960              :                 errmsg("cannot alter partition \"%s\" with an incomplete detach",
    4961              :                        RelationGetRelationName(rel)),
    4962              :                 errhint("Use ALTER TABLE ... DETACH PARTITION ... FINALIZE to complete the pending detach operation."));
    4963              : 
    4964              :     /*
    4965              :      * Copy the original subcommand for each table, so we can scribble on it.
    4966              :      * This avoids conflicts when different child tables need to make
    4967              :      * different parse transformations (for example, the same column may have
    4968              :      * different column numbers in different children).
    4969              :      */
    4970        22093 :     cmd = copyObject(cmd);
    4971              : 
    4972              :     /*
    4973              :      * Do permissions and relkind checking, recursion to child tables if
    4974              :      * needed, and any additional phase-1 processing needed.  (But beware of
    4975              :      * adding any processing that looks at table details that another
    4976              :      * subcommand could change.  In some cases we reject multiple subcommands
    4977              :      * that could try to change the same state in contrary ways.)
    4978              :      */
    4979        22093 :     switch (cmd->subtype)
    4980              :     {
    4981         1560 :         case AT_AddColumn:      /* ADD COLUMN */
    4982         1560 :             ATSimplePermissions(cmd->subtype, rel,
    4983              :                                 ATT_TABLE | ATT_PARTITIONED_TABLE |
    4984              :                                 ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
    4985         1560 :             ATPrepAddColumn(wqueue, rel, recurse, recursing, false, cmd,
    4986              :                             lockmode, context);
    4987              :             /* Recursion occurs during execution phase */
    4988         1552 :             pass = AT_PASS_ADD_COL;
    4989         1552 :             break;
    4990           21 :         case AT_AddColumnToView:    /* add column via CREATE OR REPLACE VIEW */
    4991           21 :             ATSimplePermissions(cmd->subtype, rel, ATT_VIEW);
    4992           21 :             ATPrepAddColumn(wqueue, rel, recurse, recursing, true, cmd,
    4993              :                             lockmode, context);
    4994              :             /* Recursion occurs during execution phase */
    4995           21 :             pass = AT_PASS_ADD_COL;
    4996           21 :             break;
    4997          407 :         case AT_ColumnDefault:  /* ALTER COLUMN DEFAULT */
    4998              : 
    4999              :             /*
    5000              :              * We allow defaults on views so that INSERT into a view can have
    5001              :              * default-ish behavior.  This works because the rewriter
    5002              :              * substitutes default values into INSERTs before it expands
    5003              :              * rules.
    5004              :              */
    5005          407 :             ATSimplePermissions(cmd->subtype, rel,
    5006              :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
    5007              :                                 ATT_FOREIGN_TABLE);
    5008          407 :             ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
    5009              :             /* No command-specific prep needed */
    5010          407 :             pass = cmd->def ? AT_PASS_ADD_OTHERCONSTR : AT_PASS_DROP;
    5011          407 :             break;
    5012           53 :         case AT_CookedColumnDefault:    /* add a pre-cooked default */
    5013              :             /* This is currently used only in CREATE TABLE */
    5014              :             /* (so the permission check really isn't necessary) */
    5015           53 :             ATSimplePermissions(cmd->subtype, rel,
    5016              :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
    5017              :             /* This command never recurses */
    5018           53 :             pass = AT_PASS_ADD_OTHERCONSTR;
    5019           53 :             break;
    5020          107 :         case AT_AddIdentity:
    5021          107 :             ATSimplePermissions(cmd->subtype, rel,
    5022              :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
    5023              :                                 ATT_FOREIGN_TABLE);
    5024              :             /* Set up recursion for phase 2; no other prep needed */
    5025          107 :             if (recurse)
    5026          103 :                 cmd->recurse = true;
    5027          107 :             pass = AT_PASS_ADD_OTHERCONSTR;
    5028          107 :             break;
    5029           41 :         case AT_SetIdentity:
    5030           41 :             ATSimplePermissions(cmd->subtype, rel,
    5031              :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
    5032              :                                 ATT_FOREIGN_TABLE);
    5033              :             /* Set up recursion for phase 2; no other prep needed */
    5034           41 :             if (recurse)
    5035           37 :                 cmd->recurse = true;
    5036              :             /* This should run after AddIdentity, so do it in MISC pass */
    5037           41 :             pass = AT_PASS_MISC;
    5038           41 :             break;
    5039           37 :         case AT_DropIdentity:
    5040           37 :             ATSimplePermissions(cmd->subtype, rel,
    5041              :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
    5042              :                                 ATT_FOREIGN_TABLE);
    5043              :             /* Set up recursion for phase 2; no other prep needed */
    5044           37 :             if (recurse)
    5045           33 :                 cmd->recurse = true;
    5046           37 :             pass = AT_PASS_DROP;
    5047           37 :             break;
    5048          181 :         case AT_DropNotNull:    /* ALTER COLUMN DROP NOT NULL */
    5049          181 :             ATSimplePermissions(cmd->subtype, rel,
    5050              :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
    5051              :             /* Set up recursion for phase 2; no other prep needed */
    5052          177 :             if (recurse)
    5053          165 :                 cmd->recurse = true;
    5054          177 :             pass = AT_PASS_DROP;
    5055          177 :             break;
    5056          276 :         case AT_SetNotNull:     /* ALTER COLUMN SET NOT NULL */
    5057          276 :             ATSimplePermissions(cmd->subtype, rel,
    5058              :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
    5059              :             /* Set up recursion for phase 2; no other prep needed */
    5060          272 :             if (recurse)
    5061          252 :                 cmd->recurse = true;
    5062          272 :             pass = AT_PASS_COL_ATTRS;
    5063          272 :             break;
    5064          153 :         case AT_SetExpression:  /* ALTER COLUMN SET EXPRESSION */
    5065          153 :             ATSimplePermissions(cmd->subtype, rel,
    5066              :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
    5067          153 :             ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
    5068          153 :             pass = AT_PASS_SET_EXPRESSION;
    5069          153 :             break;
    5070           57 :         case AT_DropExpression: /* ALTER COLUMN DROP EXPRESSION */
    5071           57 :             ATSimplePermissions(cmd->subtype, rel,
    5072              :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
    5073           57 :             ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
    5074           57 :             ATPrepDropExpression(rel, cmd, recurse, recursing, lockmode);
    5075           41 :             pass = AT_PASS_DROP;
    5076           41 :             break;
    5077          107 :         case AT_SetStatistics:  /* ALTER COLUMN SET STATISTICS */
    5078          107 :             ATSimplePermissions(cmd->subtype, rel,
    5079              :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW |
    5080              :                                 ATT_INDEX | ATT_PARTITIONED_INDEX | ATT_FOREIGN_TABLE);
    5081          107 :             ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
    5082              :             /* No command-specific prep needed */
    5083          107 :             pass = AT_PASS_MISC;
    5084          107 :             break;
    5085           29 :         case AT_SetOptions:     /* ALTER COLUMN SET ( options ) */
    5086              :         case AT_ResetOptions:   /* ALTER COLUMN RESET ( options ) */
    5087           29 :             ATSimplePermissions(cmd->subtype, rel,
    5088              :                                 ATT_TABLE | ATT_PARTITIONED_TABLE |
    5089              :                                 ATT_MATVIEW | ATT_FOREIGN_TABLE);
    5090              :             /* This command never recurses */
    5091           21 :             pass = AT_PASS_MISC;
    5092           21 :             break;
    5093          173 :         case AT_SetStorage:     /* ALTER COLUMN SET STORAGE */
    5094          173 :             ATSimplePermissions(cmd->subtype, rel,
    5095              :                                 ATT_TABLE | ATT_PARTITIONED_TABLE |
    5096              :                                 ATT_MATVIEW | ATT_FOREIGN_TABLE);
    5097          173 :             ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
    5098              :             /* No command-specific prep needed */
    5099          173 :             pass = AT_PASS_MISC;
    5100          173 :             break;
    5101           47 :         case AT_SetCompression: /* ALTER COLUMN SET COMPRESSION */
    5102           47 :             ATSimplePermissions(cmd->subtype, rel,
    5103              :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW);
    5104              :             /* This command never recurses */
    5105              :             /* No command-specific prep needed */
    5106           47 :             pass = AT_PASS_MISC;
    5107           47 :             break;
    5108         1117 :         case AT_DropColumn:     /* DROP COLUMN */
    5109         1117 :             ATSimplePermissions(cmd->subtype, rel,
    5110              :                                 ATT_TABLE | ATT_PARTITIONED_TABLE |
    5111              :                                 ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
    5112         1113 :             ATPrepDropColumn(wqueue, rel, recurse, recursing, cmd,
    5113              :                              lockmode, context);
    5114              :             /* Recursion occurs during execution phase */
    5115         1105 :             pass = AT_PASS_DROP;
    5116         1105 :             break;
    5117            0 :         case AT_AddIndex:       /* ADD INDEX */
    5118            0 :             ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE);
    5119              :             /* This command never recurses */
    5120              :             /* No command-specific prep needed */
    5121            0 :             pass = AT_PASS_ADD_INDEX;
    5122            0 :             break;
    5123         9529 :         case AT_AddConstraint:  /* ADD CONSTRAINT */
    5124         9529 :             ATSimplePermissions(cmd->subtype, rel,
    5125              :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
    5126         9529 :             ATPrepAddPrimaryKey(wqueue, rel, cmd, recurse, lockmode, context);
    5127         9509 :             if (recurse)
    5128              :             {
    5129              :                 /* recurses at exec time; lock descendants and set flag */
    5130         9268 :                 (void) find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
    5131         9268 :                 cmd->recurse = true;
    5132              :             }
    5133         9509 :             pass = AT_PASS_ADD_CONSTR;
    5134         9509 :             break;
    5135            0 :         case AT_AddIndexConstraint: /* ADD CONSTRAINT USING INDEX */
    5136            0 :             ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE);
    5137              :             /* This command never recurses */
    5138              :             /* No command-specific prep needed */
    5139            0 :             pass = AT_PASS_ADD_INDEXCONSTR;
    5140            0 :             break;
    5141          553 :         case AT_DropConstraint: /* DROP CONSTRAINT */
    5142          553 :             ATSimplePermissions(cmd->subtype, rel,
    5143              :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
    5144          553 :             ATCheckPartitionsNotInUse(rel, lockmode);
    5145              :             /* Other recursion occurs during execution phase */
    5146              :             /* No command-specific prep needed except saving recurse flag */
    5147          549 :             if (recurse)
    5148          525 :                 cmd->recurse = true;
    5149          549 :             pass = AT_PASS_DROP;
    5150          549 :             break;
    5151          940 :         case AT_AlterColumnType:    /* ALTER COLUMN TYPE */
    5152          940 :             ATSimplePermissions(cmd->subtype, rel,
    5153              :                                 ATT_TABLE | ATT_PARTITIONED_TABLE |
    5154              :                                 ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
    5155              :             /* See comments for ATPrepAlterColumnType */
    5156          940 :             cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, recurse, lockmode,
    5157              :                                       AT_PASS_UNSET, context);
    5158              :             Assert(cmd != NULL);
    5159              :             /* Performs own recursion */
    5160          936 :             ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd,
    5161              :                                   lockmode, context);
    5162          805 :             pass = AT_PASS_ALTER_TYPE;
    5163          805 :             break;
    5164           93 :         case AT_AlterColumnGenericOptions:
    5165           93 :             ATSimplePermissions(cmd->subtype, rel, ATT_FOREIGN_TABLE);
    5166              :             /* This command never recurses */
    5167              :             /* No command-specific prep needed */
    5168           93 :             pass = AT_PASS_MISC;
    5169           93 :             break;
    5170         1124 :         case AT_ChangeOwner:    /* ALTER OWNER */
    5171              :             /* This command never recurses */
    5172              :             /* No command-specific prep needed */
    5173         1124 :             pass = AT_PASS_MISC;
    5174         1124 :             break;
    5175           43 :         case AT_ClusterOn:      /* CLUSTER ON */
    5176              :         case AT_DropCluster:    /* SET WITHOUT CLUSTER */
    5177           43 :             ATSimplePermissions(cmd->subtype, rel,
    5178              :                                 ATT_TABLE | ATT_MATVIEW);
    5179              :             /* These commands never recurse */
    5180              :             /* No command-specific prep needed */
    5181           35 :             pass = AT_PASS_MISC;
    5182           35 :             break;
    5183           74 :         case AT_SetLogged:      /* SET LOGGED */
    5184              :         case AT_SetUnLogged:    /* SET UNLOGGED */
    5185           74 :             ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_SEQUENCE);
    5186           66 :             if (tab->chgPersistence)
    5187            0 :                 ereport(ERROR,
    5188              :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    5189              :                          errmsg("cannot change persistence setting twice")));
    5190           66 :             ATPrepChangePersistence(tab, rel, cmd->subtype == AT_SetLogged);
    5191           58 :             pass = AT_PASS_MISC;
    5192           58 :             break;
    5193            4 :         case AT_DropOids:       /* SET WITHOUT OIDS */
    5194            4 :             ATSimplePermissions(cmd->subtype, rel,
    5195              :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
    5196            4 :             pass = AT_PASS_DROP;
    5197            4 :             break;
    5198           85 :         case AT_SetAccessMethod:    /* SET ACCESS METHOD */
    5199           85 :             ATSimplePermissions(cmd->subtype, rel,
    5200              :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW);
    5201              : 
    5202              :             /* check if another access method change was already requested */
    5203           85 :             if (tab->chgAccessMethod)
    5204           12 :                 ereport(ERROR,
    5205              :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    5206              :                          errmsg("cannot have multiple SET ACCESS METHOD subcommands")));
    5207              : 
    5208           73 :             ATPrepSetAccessMethod(tab, rel, cmd->name);
    5209           73 :             pass = AT_PASS_MISC;    /* does not matter; no work in Phase 2 */
    5210           73 :             break;
    5211          107 :         case AT_SetTableSpace:  /* SET TABLESPACE */
    5212          107 :             ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE |
    5213              :                                 ATT_MATVIEW | ATT_INDEX | ATT_PARTITIONED_INDEX);
    5214              :             /* This command never recurses */
    5215          107 :             ATPrepSetTableSpace(tab, rel, cmd->name, lockmode);
    5216          107 :             pass = AT_PASS_MISC;    /* doesn't actually matter */
    5217          107 :             break;
    5218          623 :         case AT_SetRelOptions:  /* SET (...) */
    5219              :         case AT_ResetRelOptions:    /* RESET (...) */
    5220              :         case AT_ReplaceRelOptions:  /* reset them all, then set just these */
    5221          623 :             ATSimplePermissions(cmd->subtype, rel,
    5222              :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
    5223              :                                 ATT_MATVIEW | ATT_INDEX);
    5224              :             /* This command never recurses */
    5225              :             /* No command-specific prep needed */
    5226          622 :             pass = AT_PASS_MISC;
    5227          622 :             break;
    5228          305 :         case AT_AddInherit:     /* INHERIT */
    5229          305 :             ATSimplePermissions(cmd->subtype, rel,
    5230              :                                 ATT_TABLE | ATT_FOREIGN_TABLE);
    5231              :             /* This command never recurses */
    5232          301 :             ATPrepChangeInherit(rel);
    5233          289 :             pass = AT_PASS_MISC;
    5234          289 :             break;
    5235           81 :         case AT_DropInherit:    /* NO INHERIT */
    5236           81 :             ATSimplePermissions(cmd->subtype, rel,
    5237              :                                 ATT_TABLE | ATT_FOREIGN_TABLE);
    5238              :             /* This command never recurses */
    5239           77 :             ATPrepChangeInherit(rel);
    5240           69 :             pass = AT_PASS_MISC;
    5241           69 :             break;
    5242          288 :         case AT_AlterConstraint:    /* ALTER CONSTRAINT */
    5243          288 :             ATSimplePermissions(cmd->subtype, rel,
    5244              :                                 ATT_TABLE | ATT_PARTITIONED_TABLE);
    5245              :             /* Recursion occurs during execution phase */
    5246          284 :             if (recurse)
    5247          276 :                 cmd->recurse = true;
    5248          284 :             pass = AT_PASS_MISC;
    5249          284 :             break;
    5250          275 :         case AT_ValidateConstraint: /* VALIDATE CONSTRAINT */
    5251          275 :             ATSimplePermissions(cmd->subtype, rel,
    5252              :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
    5253              :             /* Recursion occurs during execution phase */
    5254              :             /* No command-specific prep needed except saving recurse flag */
    5255          275 :             if (recurse)
    5256          275 :                 cmd->recurse = true;
    5257          275 :             pass = AT_PASS_MISC;
    5258          275 :             break;
    5259          301 :         case AT_ReplicaIdentity:    /* REPLICA IDENTITY ... */
    5260          301 :             ATSimplePermissions(cmd->subtype, rel,
    5261              :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW);
    5262          301 :             pass = AT_PASS_MISC;
    5263              :             /* This command never recurses */
    5264              :             /* No command-specific prep needed */
    5265          301 :             break;
    5266          191 :         case AT_EnableTrig:     /* ENABLE TRIGGER variants */
    5267              :         case AT_EnableAlwaysTrig:
    5268              :         case AT_EnableReplicaTrig:
    5269              :         case AT_EnableTrigAll:
    5270              :         case AT_EnableTrigUser:
    5271              :         case AT_DisableTrig:    /* DISABLE TRIGGER variants */
    5272              :         case AT_DisableTrigAll:
    5273              :         case AT_DisableTrigUser:
    5274          191 :             ATSimplePermissions(cmd->subtype, rel,
    5275              :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
    5276              :             /* Set up recursion for phase 2; no other prep needed */
    5277          191 :             if (recurse)
    5278          174 :                 cmd->recurse = true;
    5279          191 :             pass = AT_PASS_MISC;
    5280          191 :             break;
    5281          407 :         case AT_EnableRule:     /* ENABLE/DISABLE RULE variants */
    5282              :         case AT_EnableAlwaysRule:
    5283              :         case AT_EnableReplicaRule:
    5284              :         case AT_DisableRule:
    5285              :         case AT_AddOf:          /* OF */
    5286              :         case AT_DropOf:         /* NOT OF */
    5287              :         case AT_EnableRowSecurity:
    5288              :         case AT_DisableRowSecurity:
    5289              :         case AT_ForceRowSecurity:
    5290              :         case AT_NoForceRowSecurity:
    5291          407 :             ATSimplePermissions(cmd->subtype, rel,
    5292              :                                 ATT_TABLE | ATT_PARTITIONED_TABLE);
    5293              :             /* These commands never recurse */
    5294              :             /* No command-specific prep needed */
    5295          407 :             pass = AT_PASS_MISC;
    5296          407 :             break;
    5297           31 :         case AT_GenericOptions:
    5298           31 :             ATSimplePermissions(cmd->subtype, rel, ATT_FOREIGN_TABLE);
    5299              :             /* No command-specific prep needed */
    5300           31 :             pass = AT_PASS_MISC;
    5301           31 :             break;
    5302         1861 :         case AT_AttachPartition:
    5303         1861 :             ATSimplePermissions(cmd->subtype, rel,
    5304              :                                 ATT_PARTITIONED_TABLE | ATT_PARTITIONED_INDEX);
    5305              :             /* No command-specific prep needed */
    5306         1857 :             pass = AT_PASS_MISC;
    5307         1857 :             break;
    5308          377 :         case AT_DetachPartition:
    5309          377 :             ATSimplePermissions(cmd->subtype, rel, ATT_PARTITIONED_TABLE);
    5310              :             /* No command-specific prep needed */
    5311          365 :             pass = AT_PASS_MISC;
    5312          365 :             break;
    5313           11 :         case AT_DetachPartitionFinalize:
    5314           11 :             ATSimplePermissions(cmd->subtype, rel, ATT_PARTITIONED_TABLE);
    5315              :             /* No command-specific prep needed */
    5316            7 :             pass = AT_PASS_MISC;
    5317            7 :             break;
    5318          424 :         case AT_MergePartitions:
    5319              :         case AT_SplitPartition:
    5320          424 :             ATSimplePermissions(cmd->subtype, rel, ATT_PARTITIONED_TABLE);
    5321              :             /* No command-specific prep needed */
    5322          420 :             pass = AT_PASS_MISC;
    5323          420 :             break;
    5324            0 :         default:                /* oops */
    5325            0 :             elog(ERROR, "unrecognized alter table type: %d",
    5326              :                  (int) cmd->subtype);
    5327              :             pass = AT_PASS_UNSET;   /* keep compiler quiet */
    5328              :             break;
    5329              :     }
    5330              :     Assert(pass > AT_PASS_UNSET);
    5331              : 
    5332              :     /* Add the subcommand to the appropriate list for phase 2 */
    5333        21789 :     tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
    5334        21789 : }
    5335              : 
    5336              : /*
    5337              :  * ATRewriteCatalogs
    5338              :  *
    5339              :  * Traffic cop for ALTER TABLE Phase 2 operations.  Subcommands are
    5340              :  * dispatched in a "safe" execution order (designed to avoid unnecessary
    5341              :  * conflicts).
    5342              :  */
    5343              : static void
    5344        20362 : ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode,
    5345              :                   AlterTableUtilityContext *context)
    5346              : {
    5347              :     ListCell   *ltab;
    5348              : 
    5349              :     /*
    5350              :      * We process all the tables "in parallel", one pass at a time.  This is
    5351              :      * needed because we may have to propagate work from one table to another
    5352              :      * (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
    5353              :      * re-adding of the foreign key constraint to the other table).  Work can
    5354              :      * only be propagated into later passes, however.
    5355              :      */
    5356       255294 :     for (AlterTablePass pass = 0; pass < AT_NUM_PASSES; pass++)
    5357              :     {
    5358              :         /* Go through each table that needs to be processed */
    5359       483090 :         foreach(ltab, *wqueue)
    5360              :         {
    5361       248158 :             AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
    5362       248158 :             List       *subcmds = tab->subcmds[pass];
    5363              :             ListCell   *lcmd;
    5364              : 
    5365       248158 :             if (subcmds == NIL)
    5366       213926 :                 continue;
    5367              : 
    5368              :             /*
    5369              :              * Open the relation and store it in tab.  This allows subroutines
    5370              :              * close and reopen, if necessary.  Appropriate lock was obtained
    5371              :              * by phase 1, needn't get it again.
    5372              :              */
    5373        34232 :             tab->rel = relation_open(tab->relid, NoLock);
    5374              : 
    5375        68526 :             foreach(lcmd, subcmds)
    5376        36463 :                 ATExecCmd(wqueue, tab,
    5377        36463 :                           lfirst_node(AlterTableCmd, lcmd),
    5378              :                           lockmode, pass, context);
    5379              : 
    5380              :             /*
    5381              :              * After the ALTER TYPE or SET EXPRESSION pass, do cleanup work
    5382              :              * (this is not done in ATExecAlterColumnType since it should be
    5383              :              * done only once if multiple columns of a table are altered).
    5384              :              */
    5385        32063 :             if (pass == AT_PASS_ALTER_TYPE || pass == AT_PASS_SET_EXPRESSION)
    5386          866 :                 ATPostAlterTypeCleanup(wqueue, tab, lockmode);
    5387              : 
    5388        32063 :             if (tab->rel)
    5389              :             {
    5390        32063 :                 relation_close(tab->rel, NoLock);
    5391        32063 :                 tab->rel = NULL;
    5392              :             }
    5393              :         }
    5394              :     }
    5395              : 
    5396              :     /* Check to see if a toast table must be added. */
    5397        39362 :     foreach(ltab, *wqueue)
    5398              :     {
    5399        21169 :         AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
    5400              : 
    5401              :         /*
    5402              :          * If the table is source table of ATTACH PARTITION command, we did
    5403              :          * not modify anything about it that will change its toasting
    5404              :          * requirement, so no need to check.
    5405              :          */
    5406        21169 :         if (((tab->relkind == RELKIND_RELATION ||
    5407         4267 :               tab->relkind == RELKIND_PARTITIONED_TABLE) &&
    5408        19965 :              tab->partition_constraint == NULL) ||
    5409         2597 :             tab->relkind == RELKIND_MATVIEW)
    5410        18602 :             AlterTableCreateToastTable(tab->relid, (Datum) 0, lockmode);
    5411              :     }
    5412        18193 : }
    5413              : 
    5414              : /*
    5415              :  * ATExecCmd: dispatch a subcommand to appropriate execution routine
    5416              :  */
    5417              : static void
    5418        36463 : ATExecCmd(List **wqueue, AlteredTableInfo *tab,
    5419              :           AlterTableCmd *cmd, LOCKMODE lockmode, AlterTablePass cur_pass,
    5420              :           AlterTableUtilityContext *context)
    5421              : {
    5422        36463 :     ObjectAddress address = InvalidObjectAddress;
    5423        36463 :     Relation    rel = tab->rel;
    5424              : 
    5425        36463 :     switch (cmd->subtype)
    5426              :     {
    5427         1569 :         case AT_AddColumn:      /* ADD COLUMN */
    5428              :         case AT_AddColumnToView:    /* add column via CREATE OR REPLACE VIEW */
    5429         1569 :             address = ATExecAddColumn(wqueue, tab, rel, &cmd,
    5430         1569 :                                       cmd->recurse, false,
    5431              :                                       lockmode, cur_pass, context);
    5432         1401 :             break;
    5433          383 :         case AT_ColumnDefault:  /* ALTER COLUMN DEFAULT */
    5434          383 :             address = ATExecColumnDefault(rel, cmd->name, cmd->def, lockmode);
    5435          339 :             break;
    5436           53 :         case AT_CookedColumnDefault:    /* add a pre-cooked default */
    5437           53 :             address = ATExecCookedColumnDefault(rel, cmd->num, cmd->def);
    5438           53 :             break;
    5439          107 :         case AT_AddIdentity:
    5440          107 :             cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
    5441              :                                       cur_pass, context);
    5442              :             Assert(cmd != NULL);
    5443           99 :             address = ATExecAddIdentity(rel, cmd->name, cmd->def, lockmode, cmd->recurse, false);
    5444           63 :             break;
    5445           41 :         case AT_SetIdentity:
    5446           41 :             cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
    5447              :                                       cur_pass, context);
    5448              :             Assert(cmd != NULL);
    5449           41 :             address = ATExecSetIdentity(rel, cmd->name, cmd->def, lockmode, cmd->recurse, false);
    5450           25 :             break;
    5451           37 :         case AT_DropIdentity:
    5452           37 :             address = ATExecDropIdentity(rel, cmd->name, cmd->missing_ok, lockmode, cmd->recurse, false);
    5453           25 :             break;
    5454          177 :         case AT_DropNotNull:    /* ALTER COLUMN DROP NOT NULL */
    5455          177 :             address = ATExecDropNotNull(rel, cmd->name, cmd->recurse, lockmode);
    5456          109 :             break;
    5457          272 :         case AT_SetNotNull:     /* ALTER COLUMN SET NOT NULL */
    5458          272 :             address = ATExecSetNotNull(wqueue, rel, NULL, cmd->name,
    5459          272 :                                        cmd->recurse, false, lockmode);
    5460          252 :             break;
    5461          153 :         case AT_SetExpression:
    5462          153 :             address = ATExecSetExpression(tab, rel, cmd->name, cmd->def, lockmode);
    5463          141 :             break;
    5464           37 :         case AT_DropExpression:
    5465           37 :             address = ATExecDropExpression(rel, cmd->name, cmd->missing_ok, lockmode);
    5466           21 :             break;
    5467          107 :         case AT_SetStatistics:  /* ALTER COLUMN SET STATISTICS */
    5468          107 :             address = ATExecSetStatistics(rel, cmd->name, cmd->num, cmd->def, lockmode);
    5469           75 :             break;
    5470           17 :         case AT_SetOptions:     /* ALTER COLUMN SET ( options ) */
    5471           17 :             address = ATExecSetOptions(rel, cmd->name, cmd->def, false, lockmode);
    5472           17 :             break;
    5473            4 :         case AT_ResetOptions:   /* ALTER COLUMN RESET ( options ) */
    5474            4 :             address = ATExecSetOptions(rel, cmd->name, cmd->def, true, lockmode);
    5475            4 :             break;
    5476          173 :         case AT_SetStorage:     /* ALTER COLUMN SET STORAGE */
    5477          173 :             address = ATExecSetStorage(rel, cmd->name, cmd->def, lockmode);
    5478          165 :             break;
    5479           47 :         case AT_SetCompression: /* ALTER COLUMN SET COMPRESSION */
    5480           47 :             address = ATExecSetCompression(rel, cmd->name, cmd->def,
    5481              :                                            lockmode);
    5482           43 :             break;
    5483         1105 :         case AT_DropColumn:     /* DROP COLUMN */
    5484         1105 :             address = ATExecDropColumn(wqueue, rel, cmd->name,
    5485         1105 :                                        cmd->behavior, cmd->recurse, false,
    5486         1105 :                                        cmd->missing_ok, lockmode,
    5487              :                                        NULL);
    5488          977 :             break;
    5489          758 :         case AT_AddIndex:       /* ADD INDEX */
    5490          758 :             address = ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false,
    5491              :                                      lockmode);
    5492          645 :             break;
    5493          307 :         case AT_ReAddIndex:     /* ADD INDEX */
    5494          307 :             address = ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true,
    5495              :                                      lockmode);
    5496          307 :             break;
    5497           53 :         case AT_ReAddStatistics:    /* ADD STATISTICS */
    5498           53 :             address = ATExecAddStatistics(tab, rel, (CreateStatsStmt *) cmd->def,
    5499              :                                           true, lockmode);
    5500           53 :             break;
    5501        16866 :         case AT_AddConstraint:  /* ADD CONSTRAINT */
    5502              :             /* Transform the command only during initial examination */
    5503        16866 :             if (cur_pass == AT_PASS_ADD_CONSTR)
    5504         9489 :                 cmd = ATParseTransformCmd(wqueue, tab, rel, cmd,
    5505         9509 :                                           cmd->recurse, lockmode,
    5506              :                                           cur_pass, context);
    5507              :             /* Depending on constraint type, might be no more work to do now */
    5508        16846 :             if (cmd != NULL)
    5509              :                 address =
    5510         7357 :                     ATExecAddConstraint(wqueue, tab, rel,
    5511         7357 :                                         (Constraint *) cmd->def,
    5512         7357 :                                         cmd->recurse, false, lockmode);
    5513        16389 :             break;
    5514          249 :         case AT_ReAddConstraint:    /* Re-add pre-existing check constraint */
    5515              :             address =
    5516          249 :                 ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
    5517              :                                     true, true, lockmode);
    5518          241 :             break;
    5519            9 :         case AT_ReAddDomainConstraint:  /* Re-add pre-existing domain check
    5520              :                                          * constraint */
    5521              :             address =
    5522            9 :                 AlterDomainAddConstraint(((AlterDomainStmt *) cmd->def)->typeName,
    5523            9 :                                          ((AlterDomainStmt *) cmd->def)->def,
    5524              :                                          NULL);
    5525            5 :             break;
    5526           52 :         case AT_ReAddComment:   /* Re-add existing comment */
    5527           52 :             address = CommentObject((CommentStmt *) cmd->def);
    5528           52 :             break;
    5529         5933 :         case AT_AddIndexConstraint: /* ADD CONSTRAINT USING INDEX */
    5530         5933 :             address = ATExecAddIndexConstraint(tab, rel, (IndexStmt *) cmd->def,
    5531              :                                                lockmode);
    5532         5925 :             break;
    5533          284 :         case AT_AlterConstraint:    /* ALTER CONSTRAINT */
    5534          284 :             address = ATExecAlterConstraint(wqueue, rel,
    5535          284 :                                             castNode(ATAlterConstraint, cmd->def),
    5536          284 :                                             cmd->recurse, lockmode);
    5537          232 :             break;
    5538          275 :         case AT_ValidateConstraint: /* VALIDATE CONSTRAINT */
    5539          275 :             address = ATExecValidateConstraint(wqueue, rel, cmd->name, cmd->recurse,
    5540              :                                                false, lockmode);
    5541          271 :             break;
    5542          549 :         case AT_DropConstraint: /* DROP CONSTRAINT */
    5543          549 :             ATExecDropConstraint(rel, cmd->name, cmd->behavior,
    5544          549 :                                  cmd->recurse,
    5545          549 :                                  cmd->missing_ok, lockmode);
    5546          409 :             break;
    5547          781 :         case AT_AlterColumnType:    /* ALTER COLUMN TYPE */
    5548              :             /* parse transformation was done earlier */
    5549          781 :             address = ATExecAlterColumnType(tab, rel, cmd, lockmode);
    5550          753 :             break;
    5551           93 :         case AT_AlterColumnGenericOptions:  /* ALTER COLUMN OPTIONS */
    5552              :             address =
    5553           93 :                 ATExecAlterColumnGenericOptions(rel, cmd->name,
    5554           93 :                                                 (List *) cmd->def, lockmode);
    5555           89 :             break;
    5556         1124 :         case AT_ChangeOwner:    /* ALTER OWNER */
    5557         1121 :             ATExecChangeOwner(RelationGetRelid(rel),
    5558         1124 :                               get_rolespec_oid(cmd->newowner, false),
    5559              :                               false, lockmode);
    5560         1113 :             break;
    5561           39 :         case AT_ClusterOn:      /* CLUSTER ON */
    5562           39 :             address = ATExecClusterOn(rel, cmd->name, lockmode);
    5563           39 :             break;
    5564            8 :         case AT_DropCluster:    /* SET WITHOUT CLUSTER */
    5565            8 :             ATExecDropCluster(rel, lockmode);
    5566            8 :             break;
    5567           58 :         case AT_SetLogged:      /* SET LOGGED */
    5568              :         case AT_SetUnLogged:    /* SET UNLOGGED */
    5569           58 :             break;
    5570            4 :         case AT_DropOids:       /* SET WITHOUT OIDS */
    5571              :             /* nothing to do here, oid columns don't exist anymore */
    5572            4 :             break;
    5573           61 :         case AT_SetAccessMethod:    /* SET ACCESS METHOD */
    5574              : 
    5575              :             /*
    5576              :              * Only do this for partitioned tables, for which this is just a
    5577              :              * catalog change.  Tables with storage are handled by Phase 3.
    5578              :              */
    5579           61 :             if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE &&
    5580           33 :                 tab->chgAccessMethod)
    5581           29 :                 ATExecSetAccessMethodNoStorage(rel, tab->newAccessMethod);
    5582           61 :             break;
    5583          107 :         case AT_SetTableSpace:  /* SET TABLESPACE */
    5584              : 
    5585              :             /*
    5586              :              * Only do this for partitioned tables and indexes, for which this
    5587              :              * is just a catalog change.  Other relation types which have
    5588              :              * storage are handled by Phase 3.
    5589              :              */
    5590          107 :             if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
    5591           99 :                 rel->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
    5592           24 :                 ATExecSetTableSpaceNoStorage(rel, tab->newTableSpace);
    5593              : 
    5594          103 :             break;
    5595          622 :         case AT_SetRelOptions:  /* SET (...) */
    5596              :         case AT_ResetRelOptions:    /* RESET (...) */
    5597              :         case AT_ReplaceRelOptions:  /* replace entire option list */
    5598          622 :             ATExecSetRelOptions(rel, (List *) cmd->def, cmd->subtype, lockmode);
    5599          588 :             break;
    5600           65 :         case AT_EnableTrig:     /* ENABLE TRIGGER name */
    5601           65 :             ATExecEnableDisableTrigger(rel, cmd->name,
    5602              :                                        TRIGGER_FIRES_ON_ORIGIN, false,
    5603           65 :                                        cmd->recurse,
    5604              :                                        lockmode);
    5605           65 :             break;
    5606           27 :         case AT_EnableAlwaysTrig:   /* ENABLE ALWAYS TRIGGER name */
    5607           27 :             ATExecEnableDisableTrigger(rel, cmd->name,
    5608              :                                        TRIGGER_FIRES_ALWAYS, false,
    5609           27 :                                        cmd->recurse,
    5610              :                                        lockmode);
    5611           27 :             break;
    5612            8 :         case AT_EnableReplicaTrig:  /* ENABLE REPLICA TRIGGER name */
    5613            8 :             ATExecEnableDisableTrigger(rel, cmd->name,
    5614              :                                        TRIGGER_FIRES_ON_REPLICA, false,
    5615            8 :                                        cmd->recurse,
    5616              :                                        lockmode);
    5617            8 :             break;
    5618           75 :         case AT_DisableTrig:    /* DISABLE TRIGGER name */
    5619           75 :             ATExecEnableDisableTrigger(rel, cmd->name,
    5620              :                                        TRIGGER_DISABLED, false,
    5621           75 :                                        cmd->recurse,
    5622              :                                        lockmode);
    5623           75 :             break;
    5624            0 :         case AT_EnableTrigAll:  /* ENABLE TRIGGER ALL */
    5625            0 :             ATExecEnableDisableTrigger(rel, NULL,
    5626              :                                        TRIGGER_FIRES_ON_ORIGIN, false,
    5627            0 :                                        cmd->recurse,
    5628              :                                        lockmode);
    5629            0 :             break;
    5630            8 :         case AT_DisableTrigAll: /* DISABLE TRIGGER ALL */
    5631            8 :             ATExecEnableDisableTrigger(rel, NULL,
    5632              :                                        TRIGGER_DISABLED, false,
    5633            8 :                                        cmd->recurse,
    5634              :                                        lockmode);
    5635            8 :             break;
    5636            0 :         case AT_EnableTrigUser: /* ENABLE TRIGGER USER */
    5637            0 :             ATExecEnableDisableTrigger(rel, NULL,
    5638              :                                        TRIGGER_FIRES_ON_ORIGIN, true,
    5639            0 :                                        cmd->recurse,
    5640              :                                        lockmode);
    5641            0 :             break;
    5642            8 :         case AT_DisableTrigUser:    /* DISABLE TRIGGER USER */
    5643            8 :             ATExecEnableDisableTrigger(rel, NULL,
    5644              :                                        TRIGGER_DISABLED, true,
    5645            8 :                                        cmd->recurse,
    5646              :                                        lockmode);
    5647            8 :             break;
    5648              : 
    5649            5 :         case AT_EnableRule:     /* ENABLE RULE name */
    5650            5 :             ATExecEnableDisableRule(rel, cmd->name,
    5651              :                                     RULE_FIRES_ON_ORIGIN, lockmode);
    5652            5 :             break;
    5653            0 :         case AT_EnableAlwaysRule:   /* ENABLE ALWAYS RULE name */
    5654            0 :             ATExecEnableDisableRule(rel, cmd->name,
    5655              :                                     RULE_FIRES_ALWAYS, lockmode);
    5656            0 :             break;
    5657            4 :         case AT_EnableReplicaRule:  /* ENABLE REPLICA RULE name */
    5658            4 :             ATExecEnableDisableRule(rel, cmd->name,
    5659              :                                     RULE_FIRES_ON_REPLICA, lockmode);
    5660            4 :             break;
    5661           20 :         case AT_DisableRule:    /* DISABLE RULE name */
    5662           20 :             ATExecEnableDisableRule(rel, cmd->name,
    5663              :                                     RULE_DISABLED, lockmode);
    5664           20 :             break;
    5665              : 
    5666          289 :         case AT_AddInherit:
    5667          289 :             address = ATExecAddInherit(rel, (RangeVar *) cmd->def, lockmode);
    5668          209 :             break;
    5669           69 :         case AT_DropInherit:
    5670           69 :             address = ATExecDropInherit(rel, (RangeVar *) cmd->def, lockmode);
    5671           65 :             break;
    5672           42 :         case AT_AddOf:
    5673           42 :             address = ATExecAddOf(rel, (TypeName *) cmd->def, lockmode);
    5674           18 :             break;
    5675            4 :         case AT_DropOf:
    5676            4 :             ATExecDropOf(rel, lockmode);
    5677            4 :             break;
    5678          313 :         case AT_ReplicaIdentity:
    5679          313 :             ATExecReplicaIdentity(rel, (ReplicaIdentityStmt *) cmd->def, lockmode);
    5680          281 :             break;
    5681          236 :         case AT_EnableRowSecurity:
    5682          236 :             ATExecSetRowSecurity(rel, true);
    5683          236 :             break;
    5684            6 :         case AT_DisableRowSecurity:
    5685            6 :             ATExecSetRowSecurity(rel, false);
    5686            6 :             break;
    5687           70 :         case AT_ForceRowSecurity:
    5688           70 :             ATExecForceNoForceRowSecurity(rel, true);
    5689           70 :             break;
    5690           20 :         case AT_NoForceRowSecurity:
    5691           20 :             ATExecForceNoForceRowSecurity(rel, false);
    5692           20 :             break;
    5693           31 :         case AT_GenericOptions:
    5694           31 :             ATExecGenericOptions(rel, (List *) cmd->def);
    5695           30 :             break;
    5696         1857 :         case AT_AttachPartition:
    5697         1857 :             cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
    5698              :                                       cur_pass, context);
    5699              :             Assert(cmd != NULL);
    5700         1841 :             if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
    5701         1594 :                 address = ATExecAttachPartition(wqueue, rel, (PartitionCmd *) cmd->def,
    5702              :                                                 context);
    5703              :             else
    5704          247 :                 address = ATExecAttachPartitionIdx(wqueue, rel,
    5705          247 :                                                    ((PartitionCmd *) cmd->def)->name);
    5706         1577 :             break;
    5707          365 :         case AT_DetachPartition:
    5708          365 :             cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
    5709              :                                       cur_pass, context);
    5710              :             Assert(cmd != NULL);
    5711              :             /* ATPrepCmd ensures it must be a table */
    5712              :             Assert(rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
    5713          365 :             address = ATExecDetachPartition(wqueue, tab, rel,
    5714          365 :                                             ((PartitionCmd *) cmd->def)->name,
    5715          365 :                                             ((PartitionCmd *) cmd->def)->concurrent);
    5716          288 :             break;
    5717            7 :         case AT_DetachPartitionFinalize:
    5718            7 :             address = ATExecDetachPartitionFinalize(rel, ((PartitionCmd *) cmd->def)->name);
    5719            7 :             break;
    5720          172 :         case AT_MergePartitions:
    5721          172 :             cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
    5722              :                                       cur_pass, context);
    5723              :             Assert(cmd != NULL);
    5724              :             Assert(rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
    5725          116 :             ATExecMergePartitions(wqueue, tab, rel, (PartitionCmd *) cmd->def,
    5726              :                                   context);
    5727           88 :             break;
    5728          248 :         case AT_SplitPartition:
    5729          248 :             cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
    5730              :                                       cur_pass, context);
    5731              :             Assert(cmd != NULL);
    5732              :             Assert(rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
    5733          128 :             ATExecSplitPartition(wqueue, tab, rel, (PartitionCmd *) cmd->def,
    5734              :                                  context);
    5735          120 :             break;
    5736            0 :         default:                /* oops */
    5737            0 :             elog(ERROR, "unrecognized alter table type: %d",
    5738              :                  (int) cmd->subtype);
    5739              :             break;
    5740              :     }
    5741              : 
    5742              :     /*
    5743              :      * Report the subcommand to interested event triggers.
    5744              :      */
    5745        34294 :     if (cmd)
    5746        24805 :         EventTriggerCollectAlterTableSubcmd((Node *) cmd, address);
    5747              : 
    5748              :     /*
    5749              :      * Bump the command counter to ensure the next subcommand in the sequence
    5750              :      * can see the changes so far
    5751              :      */
    5752        34294 :     CommandCounterIncrement();
    5753        34294 : }
    5754              : 
    5755              : /*
    5756              :  * ATParseTransformCmd: perform parse transformation for one subcommand
    5757              :  *
    5758              :  * Returns the transformed subcommand tree, if there is one, else NULL.
    5759              :  *
    5760              :  * The parser may hand back additional AlterTableCmd(s) and/or other
    5761              :  * utility statements, either before or after the original subcommand.
    5762              :  * Other AlterTableCmds are scheduled into the appropriate slot of the
    5763              :  * AlteredTableInfo (they had better be for later passes than the current one).
    5764              :  * Utility statements that are supposed to happen before the AlterTableCmd
    5765              :  * are executed immediately.  Those that are supposed to happen afterwards
    5766              :  * are added to the tab->afterStmts list to be done at the very end.
    5767              :  */
    5768              : static AlterTableCmd *
    5769        14715 : ATParseTransformCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
    5770              :                     AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode,
    5771              :                     AlterTablePass cur_pass, AlterTableUtilityContext *context)
    5772              : {
    5773        14715 :     AlterTableCmd *newcmd = NULL;
    5774        14715 :     AlterTableStmt *atstmt = makeNode(AlterTableStmt);
    5775              :     List       *beforeStmts;
    5776              :     List       *afterStmts;
    5777              :     ListCell   *lc;
    5778              : 
    5779              :     /* Gin up an AlterTableStmt with just this subcommand and this table */
    5780        14715 :     atstmt->relation =
    5781        14715 :         makeRangeVar(get_namespace_name(RelationGetNamespace(rel)),
    5782        14715 :                      pstrdup(RelationGetRelationName(rel)),
    5783              :                      -1);
    5784        14715 :     atstmt->relation->inh = recurse;
    5785        14715 :     atstmt->cmds = list_make1(cmd);
    5786        14715 :     atstmt->objtype = OBJECT_TABLE; /* needn't be picky here */
    5787        14715 :     atstmt->missing_ok = false;
    5788              : 
    5789              :     /* Transform the AlterTableStmt */
    5790        14715 :     atstmt = transformAlterTableStmt(RelationGetRelid(rel),
    5791              :                                      atstmt,
    5792              :                                      context->queryString,
    5793              :                                      &beforeStmts,
    5794              :                                      &afterStmts);
    5795              : 
    5796              :     /* Execute any statements that should happen before these subcommand(s) */
    5797        14802 :     foreach(lc, beforeStmts)
    5798              :     {
    5799          315 :         Node       *stmt = (Node *) lfirst(lc);
    5800              : 
    5801          315 :         ProcessUtilityForAlterTable(stmt, context);
    5802          307 :         CommandCounterIncrement();
    5803              :     }
    5804              : 
    5805              :     /* Examine the transformed subcommands and schedule them appropriately */
    5806        33557 :     foreach(lc, atstmt->cmds)
    5807              :     {
    5808        19070 :         AlterTableCmd *cmd2 = lfirst_node(AlterTableCmd, lc);
    5809              :         AlterTablePass pass;
    5810              : 
    5811              :         /*
    5812              :          * This switch need only cover the subcommand types that can be added
    5813              :          * by parse_utilcmd.c; otherwise, we'll use the default strategy of
    5814              :          * executing the subcommand immediately, as a substitute for the
    5815              :          * original subcommand.  (Note, however, that this does cause
    5816              :          * AT_AddConstraint subcommands to be rescheduled into later passes,
    5817              :          * which is important for index and foreign key constraints.)
    5818              :          *
    5819              :          * We assume we needn't do any phase-1 checks for added subcommands.
    5820              :          */
    5821        19070 :         switch (cmd2->subtype)
    5822              :         {
    5823          774 :             case AT_AddIndex:
    5824          774 :                 pass = AT_PASS_ADD_INDEX;
    5825          774 :                 break;
    5826         5933 :             case AT_AddIndexConstraint:
    5827         5933 :                 pass = AT_PASS_ADD_INDEXCONSTR;
    5828         5933 :                 break;
    5829         7365 :             case AT_AddConstraint:
    5830              :                 /* Recursion occurs during execution phase */
    5831         7365 :                 if (recurse)
    5832         7328 :                     cmd2->recurse = true;
    5833         7365 :                 switch (castNode(Constraint, cmd2->def)->contype)
    5834              :                 {
    5835         5002 :                     case CONSTR_NOTNULL:
    5836         5002 :                         pass = AT_PASS_COL_ATTRS;
    5837         5002 :                         break;
    5838            0 :                     case CONSTR_PRIMARY:
    5839              :                     case CONSTR_UNIQUE:
    5840              :                     case CONSTR_EXCLUSION:
    5841            0 :                         pass = AT_PASS_ADD_INDEXCONSTR;
    5842            0 :                         break;
    5843         2363 :                     default:
    5844         2363 :                         pass = AT_PASS_ADD_OTHERCONSTR;
    5845         2363 :                         break;
    5846              :                 }
    5847         7365 :                 break;
    5848            0 :             case AT_AlterColumnGenericOptions:
    5849              :                 /* This command never recurses */
    5850              :                 /* No command-specific prep needed */
    5851            0 :                 pass = AT_PASS_MISC;
    5852            0 :                 break;
    5853         4998 :             default:
    5854         4998 :                 pass = cur_pass;
    5855         4998 :                 break;
    5856              :         }
    5857              : 
    5858        19070 :         if (pass < cur_pass)
    5859              :         {
    5860              :             /* Cannot schedule into a pass we already finished */
    5861            0 :             elog(ERROR, "ALTER TABLE scheduling failure: too late for pass %d",
    5862              :                  pass);
    5863              :         }
    5864        19070 :         else if (pass > cur_pass)
    5865              :         {
    5866              :             /* OK, queue it up for later */
    5867        14072 :             tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd2);
    5868              :         }
    5869              :         else
    5870              :         {
    5871              :             /*
    5872              :              * We should see at most one subcommand for the current pass,
    5873              :              * which is the transformed version of the original subcommand.
    5874              :              */
    5875         4998 :             if (newcmd == NULL && cmd->subtype == cmd2->subtype)
    5876              :             {
    5877              :                 /* Found the transformed version of our subcommand */
    5878         4998 :                 newcmd = cmd2;
    5879              :             }
    5880              :             else
    5881            0 :                 elog(ERROR, "ALTER TABLE scheduling failure: bogus item for pass %d",
    5882              :                      pass);
    5883              :         }
    5884              :     }
    5885              : 
    5886              :     /* Queue up any after-statements to happen at the end */
    5887        14487 :     tab->afterStmts = list_concat(tab->afterStmts, afterStmts);
    5888              : 
    5889        14487 :     return newcmd;
    5890              : }
    5891              : 
    5892              : /*
    5893              :  * ATRewriteTables: ALTER TABLE phase 3
    5894              :  */
    5895              : static void
    5896        18193 : ATRewriteTables(AlterTableStmt *parsetree, List **wqueue, LOCKMODE lockmode,
    5897              :                 AlterTableUtilityContext *context)
    5898              : {
    5899              :     ListCell   *ltab;
    5900              : 
    5901              :     /* Go through each table that needs to be checked or rewritten */
    5902        38972 :     foreach(ltab, *wqueue)
    5903              :     {
    5904        21093 :         AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
    5905              : 
    5906              :         /* Relations without storage may be ignored here */
    5907        21093 :         if (!RELKIND_HAS_STORAGE(tab->relkind))
    5908         4083 :             continue;
    5909              : 
    5910              :         /*
    5911              :          * If we change column data types, the operation has to be propagated
    5912              :          * to tables that use this table's rowtype as a column type.
    5913              :          * tab->newvals will also be non-NULL in the case where we're adding a
    5914              :          * column with a default.  We choose to forbid that case as well,
    5915              :          * since composite types might eventually support defaults.
    5916              :          *
    5917              :          * (Eventually we'll probably need to check for composite type
    5918              :          * dependencies even when we're just scanning the table without a
    5919              :          * rewrite, but at the moment a composite type does not enforce any
    5920              :          * constraints, so it's not necessary/appropriate to enforce them just
    5921              :          * during ALTER.)
    5922              :          */
    5923        17010 :         if (tab->newvals != NIL || tab->rewrite > 0)
    5924              :         {
    5925              :             Relation    rel;
    5926              : 
    5927         1272 :             rel = table_open(tab->relid, NoLock);
    5928         1272 :             find_composite_type_dependencies(rel->rd_rel->reltype, rel, NULL);
    5929         1236 :             table_close(rel, NoLock);
    5930              :         }
    5931              : 
    5932              :         /*
    5933              :          * We only need to rewrite the table if at least one column needs to
    5934              :          * be recomputed, or we are changing its persistence or access method.
    5935              :          *
    5936              :          * There are two reasons for requiring a rewrite when changing
    5937              :          * persistence: on one hand, we need to ensure that the buffers
    5938              :          * belonging to each of the two relations are marked with or without
    5939              :          * BM_PERMANENT properly.  On the other hand, since rewriting creates
    5940              :          * and assigns a new relfilenumber, we automatically create or drop an
    5941              :          * init fork for the relation as appropriate.
    5942              :          */
    5943        16974 :         if (tab->rewrite > 0 && tab->relkind != RELKIND_SEQUENCE)
    5944          708 :         {
    5945              :             /* Build a temporary relation and copy data */
    5946              :             Relation    OldHeap;
    5947              :             Oid         OIDNewHeap;
    5948              :             Oid         NewAccessMethod;
    5949              :             Oid         NewTableSpace;
    5950              :             char        persistence;
    5951              : 
    5952          757 :             OldHeap = table_open(tab->relid, NoLock);
    5953              : 
    5954              :             /*
    5955              :              * We don't support rewriting of system catalogs; there are too
    5956              :              * many corner cases and too little benefit.  In particular this
    5957              :              * is certainly not going to work for mapped catalogs.
    5958              :              */
    5959          757 :             if (IsSystemRelation(OldHeap))
    5960            0 :                 ereport(ERROR,
    5961              :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    5962              :                          errmsg("cannot rewrite system relation \"%s\"",
    5963              :                                 RelationGetRelationName(OldHeap))));
    5964              : 
    5965          757 :             if (RelationIsUsedAsCatalogTable(OldHeap))
    5966            1 :                 ereport(ERROR,
    5967              :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    5968              :                          errmsg("cannot rewrite table \"%s\" used as a catalog table",
    5969              :                                 RelationGetRelationName(OldHeap))));
    5970              : 
    5971              :             /*
    5972              :              * Don't allow rewrite on temp tables of other backends ... their
    5973              :              * local buffer manager is not going to cope.  (This is redundant
    5974              :              * with the check in CheckAlterTableIsSafe, but for safety we'll
    5975              :              * check here too.)
    5976              :              */
    5977          756 :             if (RELATION_IS_OTHER_TEMP(OldHeap))
    5978            0 :                 ereport(ERROR,
    5979              :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    5980              :                          errmsg("cannot rewrite temporary tables of other sessions")));
    5981              : 
    5982              :             /*
    5983              :              * Select destination tablespace (same as original unless user
    5984              :              * requested a change)
    5985              :              */
    5986          756 :             if (tab->newTableSpace)
    5987            0 :                 NewTableSpace = tab->newTableSpace;
    5988              :             else
    5989          756 :                 NewTableSpace = OldHeap->rd_rel->reltablespace;
    5990              : 
    5991              :             /*
    5992              :              * Select destination access method (same as original unless user
    5993              :              * requested a change)
    5994              :              */
    5995          756 :             if (tab->chgAccessMethod)
    5996           24 :                 NewAccessMethod = tab->newAccessMethod;
    5997              :             else
    5998          732 :                 NewAccessMethod = OldHeap->rd_rel->relam;
    5999              : 
    6000              :             /*
    6001              :              * Select persistence of transient table (same as original unless
    6002              :              * user requested a change)
    6003              :              */
    6004          756 :             persistence = tab->chgPersistence ?
    6005          722 :                 tab->newrelpersistence : OldHeap->rd_rel->relpersistence;
    6006              : 
    6007          756 :             table_close(OldHeap, NoLock);
    6008              : 
    6009              :             /*
    6010              :              * Fire off an Event Trigger now, before actually rewriting the
    6011              :              * table.
    6012              :              *
    6013              :              * We don't support Event Trigger for nested commands anywhere,
    6014              :              * here included, and parsetree is given NULL when coming from
    6015              :              * AlterTableInternal.
    6016              :              *
    6017              :              * And fire it only once.
    6018              :              */
    6019          756 :             if (parsetree)
    6020          756 :                 EventTriggerTableRewrite((Node *) parsetree,
    6021              :                                          tab->relid,
    6022              :                                          tab->rewrite);
    6023              : 
    6024              :             /*
    6025              :              * Create transient table that will receive the modified data.
    6026              :              *
    6027              :              * Ensure it is marked correctly as logged or unlogged.  We have
    6028              :              * to do this here so that buffers for the new relfilenumber will
    6029              :              * have the right persistence set, and at the same time ensure
    6030              :              * that the original filenumbers's buffers will get read in with
    6031              :              * the correct setting (i.e. the original one).  Otherwise a
    6032              :              * rollback after the rewrite would possibly result with buffers
    6033              :              * for the original filenumbers having the wrong persistence
    6034              :              * setting.
    6035              :              *
    6036              :              * NB: This relies on swap_relation_files() also swapping the
    6037              :              * persistence. That wouldn't work for pg_class, but that can't be
    6038              :              * unlogged anyway.
    6039              :              */
    6040          752 :             OIDNewHeap = make_new_heap(tab->relid, NewTableSpace, NewAccessMethod,
    6041              :                                        persistence, lockmode);
    6042              : 
    6043              :             /*
    6044              :              * Copy the heap data into the new table with the desired
    6045              :              * modifications, and test the current data within the table
    6046              :              * against new constraints generated by ALTER TABLE commands.
    6047              :              */
    6048          752 :             ATRewriteTable(tab, OIDNewHeap);
    6049              : 
    6050              :             /*
    6051              :              * Swap the physical files of the old and new heaps, then rebuild
    6052              :              * indexes and discard the old heap.  We can use RecentXmin for
    6053              :              * the table's new relfrozenxid because we rewrote all the tuples
    6054              :              * in ATRewriteTable, so no older Xid remains in the table.  Also,
    6055              :              * we never try to swap toast tables by content, since we have no
    6056              :              * interest in letting this code work on system catalogs.
    6057              :              */
    6058          712 :             finish_heap_swap(tab->relid, OIDNewHeap,
    6059              :                              false, false, true,
    6060          712 :                              !OidIsValid(tab->newTableSpace),
    6061              :                              RecentXmin,
    6062              :                              ReadNextMultiXactId(),
    6063              :                              persistence);
    6064              : 
    6065          708 :             InvokeObjectPostAlterHook(RelationRelationId, tab->relid, 0);
    6066              :         }
    6067        16217 :         else if (tab->rewrite > 0 && tab->relkind == RELKIND_SEQUENCE)
    6068              :         {
    6069           16 :             if (tab->chgPersistence)
    6070           16 :                 SequenceChangePersistence(tab->relid, tab->newrelpersistence);
    6071              :         }
    6072              :         else
    6073              :         {
    6074              :             /*
    6075              :              * If required, test the current data within the table against new
    6076              :              * constraints generated by ALTER TABLE commands, but don't
    6077              :              * rebuild data.
    6078              :              */
    6079        16201 :             if (tab->constraints != NIL || tab->verify_new_notnull ||
    6080        14149 :                 tab->partition_constraint != NULL)
    6081         3347 :                 ATRewriteTable(tab, InvalidOid);
    6082              : 
    6083              :             /*
    6084              :              * If we had SET TABLESPACE but no reason to reconstruct tuples,
    6085              :              * just do a block-by-block copy.
    6086              :              */
    6087        15972 :             if (tab->newTableSpace)
    6088           83 :                 ATExecSetTableSpace(tab->relid, tab->newTableSpace, lockmode);
    6089              :         }
    6090              : 
    6091              :         /*
    6092              :          * Also change persistence of owned sequences, so that it matches the
    6093              :          * table persistence.
    6094              :          */
    6095        16696 :         if (tab->chgPersistence)
    6096              :         {
    6097           50 :             List       *seqlist = getOwnedSequences(tab->relid);
    6098              :             ListCell   *lc;
    6099              : 
    6100           82 :             foreach(lc, seqlist)
    6101              :             {
    6102           32 :                 Oid         seq_relid = lfirst_oid(lc);
    6103              : 
    6104           32 :                 SequenceChangePersistence(seq_relid, tab->newrelpersistence);
    6105              :             }
    6106              :         }
    6107              :     }
    6108              : 
    6109              :     /*
    6110              :      * Foreign key constraints are checked in a final pass, since (a) it's
    6111              :      * generally best to examine each one separately, and (b) it's at least
    6112              :      * theoretically possible that we have changed both relations of the
    6113              :      * foreign key, and we'd better have finished both rewrites before we try
    6114              :      * to read the tables.
    6115              :      */
    6116        38429 :     foreach(ltab, *wqueue)
    6117              :     {
    6118        20617 :         AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
    6119        20617 :         Relation    rel = NULL;
    6120              :         ListCell   *lcon;
    6121              : 
    6122              :         /* Relations without storage may be ignored here too */
    6123        20617 :         if (!RELKIND_HAS_STORAGE(tab->relkind))
    6124         3990 :             continue;
    6125              : 
    6126        17888 :         foreach(lcon, tab->constraints)
    6127              :         {
    6128         1328 :             NewConstraint *con = lfirst(lcon);
    6129              : 
    6130         1328 :             if (con->contype == CONSTR_FOREIGN)
    6131              :             {
    6132          734 :                 Constraint *fkconstraint = (Constraint *) con->qual;
    6133              :                 Relation    refrel;
    6134              : 
    6135          734 :                 if (rel == NULL)
    6136              :                 {
    6137              :                     /* Long since locked, no need for another */
    6138          726 :                     rel = table_open(tab->relid, NoLock);
    6139              :                 }
    6140              : 
    6141          734 :                 refrel = table_open(con->refrelid, RowShareLock);
    6142              : 
    6143          734 :                 validateForeignKeyConstraint(fkconstraint->conname, rel, refrel,
    6144              :                                              con->refindid,
    6145              :                                              con->conid,
    6146          734 :                                              con->conwithperiod);
    6147              : 
    6148              :                 /*
    6149              :                  * No need to mark the constraint row as validated, we did
    6150              :                  * that when we inserted the row earlier.
    6151              :                  */
    6152              : 
    6153          667 :                 table_close(refrel, NoLock);
    6154              :             }
    6155              :         }
    6156              : 
    6157        16560 :         if (rel)
    6158          659 :             table_close(rel, NoLock);
    6159              :     }
    6160              : 
    6161              :     /* Finally, run any afterStmts that were queued up */
    6162        38335 :     foreach(ltab, *wqueue)
    6163              :     {
    6164        20523 :         AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
    6165              :         ListCell   *lc;
    6166              : 
    6167        20579 :         foreach(lc, tab->afterStmts)
    6168              :         {
    6169           56 :             Node       *stmt = (Node *) lfirst(lc);
    6170              : 
    6171           56 :             ProcessUtilityForAlterTable(stmt, context);
    6172           56 :             CommandCounterIncrement();
    6173              :         }
    6174              :     }
    6175        17812 : }
    6176              : 
    6177              : /*
    6178              :  * ATRewriteTable: scan or rewrite one table
    6179              :  *
    6180              :  * A rewrite is requested by passing a valid OIDNewHeap; in that case, caller
    6181              :  * must already hold AccessExclusiveLock on it.
    6182              :  */
    6183              : static void
    6184         4099 : ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap)
    6185              : {
    6186              :     Relation    oldrel;
    6187              :     Relation    newrel;
    6188              :     TupleDesc   oldTupDesc;
    6189              :     TupleDesc   newTupDesc;
    6190         4099 :     bool        needscan = false;
    6191              :     List       *notnull_attrs;
    6192              :     List       *notnull_virtual_attrs;
    6193              :     int         i;
    6194              :     ListCell   *l;
    6195              :     EState     *estate;
    6196              :     CommandId   mycid;
    6197              :     BulkInsertState bistate;
    6198              :     int         ti_options;
    6199         4099 :     ExprState  *partqualstate = NULL;
    6200              : 
    6201              :     /*
    6202              :      * Open the relation(s).  We have surely already locked the existing
    6203              :      * table.
    6204              :      */
    6205         4099 :     oldrel = table_open(tab->relid, NoLock);
    6206         4099 :     oldTupDesc = tab->oldDesc;
    6207         4099 :     newTupDesc = RelationGetDescr(oldrel);  /* includes all mods */
    6208              : 
    6209         4099 :     if (OidIsValid(OIDNewHeap))
    6210              :     {
    6211              :         Assert(CheckRelationOidLockedByMe(OIDNewHeap, AccessExclusiveLock,
    6212              :                                           false));
    6213          752 :         newrel = table_open(OIDNewHeap, NoLock);
    6214              :     }
    6215              :     else
    6216         3347 :         newrel = NULL;
    6217              : 
    6218              :     /*
    6219              :      * Prepare a BulkInsertState and options for table_tuple_insert.  The FSM
    6220              :      * is empty, so don't bother using it.
    6221              :      */
    6222         4099 :     if (newrel)
    6223              :     {
    6224          752 :         mycid = GetCurrentCommandId(true);
    6225          752 :         bistate = GetBulkInsertState();
    6226          752 :         ti_options = TABLE_INSERT_SKIP_FSM;
    6227              :     }
    6228              :     else
    6229              :     {
    6230              :         /* keep compiler quiet about using these uninitialized */
    6231         3347 :         mycid = 0;
    6232         3347 :         bistate = NULL;
    6233         3347 :         ti_options = 0;
    6234              :     }
    6235              : 
    6236              :     /*
    6237              :      * Generate the constraint and default execution states
    6238              :      */
    6239              : 
    6240         4099 :     estate = CreateExecutorState();
    6241              : 
    6242              :     /* Build the needed expression execution states */
    6243         5583 :     foreach(l, tab->constraints)
    6244              :     {
    6245         1484 :         NewConstraint *con = lfirst(l);
    6246              : 
    6247         1484 :         switch (con->contype)
    6248              :         {
    6249          746 :             case CONSTR_CHECK:
    6250          746 :                 needscan = true;
    6251          746 :                 con->qualstate = ExecPrepareExpr((Expr *) expand_generated_columns_in_expr(con->qual, oldrel, 1), estate);
    6252          746 :                 break;
    6253          738 :             case CONSTR_FOREIGN:
    6254              :                 /* Nothing to do here */
    6255          738 :                 break;
    6256            0 :             default:
    6257            0 :                 elog(ERROR, "unrecognized constraint type: %d",
    6258              :                      (int) con->contype);
    6259              :         }
    6260              :     }
    6261              : 
    6262              :     /* Build expression execution states for partition check quals */
    6263         4099 :     if (tab->partition_constraint)
    6264              :     {
    6265         1389 :         needscan = true;
    6266         1389 :         partqualstate = ExecPrepareExpr(tab->partition_constraint, estate);
    6267              :     }
    6268              : 
    6269         4897 :     foreach(l, tab->newvals)
    6270              :     {
    6271          798 :         NewColumnValue *ex = lfirst(l);
    6272              : 
    6273              :         /* expr already planned */
    6274          798 :         ex->exprstate = ExecInitExpr(ex->expr, NULL);
    6275              :     }
    6276              : 
    6277         4099 :     notnull_attrs = notnull_virtual_attrs = NIL;
    6278         4099 :     if (newrel || tab->verify_new_notnull)
    6279              :     {
    6280              :         /*
    6281              :          * If we are rebuilding the tuples OR if we added any new but not
    6282              :          * verified not-null constraints, check all *valid* not-null
    6283              :          * constraints. This is a bit of overkill but it minimizes risk of
    6284              :          * bugs.
    6285              :          *
    6286              :          * notnull_attrs does *not* collect attribute numbers for valid
    6287              :          * not-null constraints over virtual generated columns; instead, they
    6288              :          * are collected in notnull_virtual_attrs for verification elsewhere.
    6289              :          */
    6290         5318 :         for (i = 0; i < newTupDesc->natts; i++)
    6291              :         {
    6292         3885 :             CompactAttribute *attr = TupleDescCompactAttr(newTupDesc, i);
    6293              : 
    6294         3885 :             if (attr->attnullability == ATTNULLABLE_VALID &&
    6295         1392 :                 !attr->attisdropped)
    6296              :             {
    6297         1392 :                 Form_pg_attribute wholeatt = TupleDescAttr(newTupDesc, i);
    6298              : 
    6299         1392 :                 if (wholeatt->attgenerated != ATTRIBUTE_GENERATED_VIRTUAL)
    6300         1332 :                     notnull_attrs = lappend_int(notnull_attrs, wholeatt->attnum);
    6301              :                 else
    6302           60 :                     notnull_virtual_attrs = lappend_int(notnull_virtual_attrs,
    6303           60 :                                                         wholeatt->attnum);
    6304              :             }
    6305              :         }
    6306         1433 :         if (notnull_attrs || notnull_virtual_attrs)
    6307         1023 :             needscan = true;
    6308              :     }
    6309              : 
    6310         4099 :     if (newrel || needscan)
    6311              :     {
    6312              :         ExprContext *econtext;
    6313              :         TupleTableSlot *oldslot;
    6314              :         TupleTableSlot *newslot;
    6315              :         TableScanDesc scan;
    6316              :         MemoryContext oldCxt;
    6317         3491 :         List       *dropped_attrs = NIL;
    6318              :         ListCell   *lc;
    6319              :         Snapshot    snapshot;
    6320         3491 :         ResultRelInfo *rInfo = NULL;
    6321              : 
    6322              :         /*
    6323              :          * When adding or changing a virtual generated column with a not-null
    6324              :          * constraint, we need to evaluate whether the generation expression
    6325              :          * is null.  For that, we borrow ExecRelGenVirtualNotNull().  Here, we
    6326              :          * prepare a dummy ResultRelInfo.
    6327              :          */
    6328         3491 :         if (notnull_virtual_attrs != NIL)
    6329              :         {
    6330              :             MemoryContext oldcontext;
    6331              : 
    6332              :             Assert(newTupDesc->constr->has_generated_virtual);
    6333              :             Assert(newTupDesc->constr->has_not_null);
    6334           40 :             oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
    6335           40 :             rInfo = makeNode(ResultRelInfo);
    6336           40 :             InitResultRelInfo(rInfo,
    6337              :                               oldrel,
    6338              :                               0,    /* dummy rangetable index */
    6339              :                               NULL,
    6340              :                               estate->es_instrument);
    6341           40 :             MemoryContextSwitchTo(oldcontext);
    6342              :         }
    6343              : 
    6344         3491 :         if (newrel)
    6345          752 :             ereport(DEBUG1,
    6346              :                     (errmsg_internal("rewriting table \"%s\"",
    6347              :                                      RelationGetRelationName(oldrel))));
    6348              :         else
    6349         2739 :             ereport(DEBUG1,
    6350              :                     (errmsg_internal("verifying table \"%s\"",
    6351              :                                      RelationGetRelationName(oldrel))));
    6352              : 
    6353         3491 :         if (newrel)
    6354              :         {
    6355              :             /*
    6356              :              * All predicate locks on the tuples or pages are about to be made
    6357              :              * invalid, because we move tuples around.  Promote them to
    6358              :              * relation locks.
    6359              :              */
    6360          752 :             TransferPredicateLocksToHeapRelation(oldrel);
    6361              :         }
    6362              : 
    6363         3491 :         econtext = GetPerTupleExprContext(estate);
    6364              : 
    6365              :         /*
    6366              :          * Create necessary tuple slots. When rewriting, two slots are needed,
    6367              :          * otherwise one suffices. In the case where one slot suffices, we
    6368              :          * need to use the new tuple descriptor, otherwise some constraints
    6369              :          * can't be evaluated.  Note that even when the tuple layout is the
    6370              :          * same and no rewrite is required, the tupDescs might not be
    6371              :          * (consider ADD COLUMN without a default).
    6372              :          */
    6373         3491 :         if (tab->rewrite)
    6374              :         {
    6375              :             Assert(newrel != NULL);
    6376          752 :             oldslot = MakeSingleTupleTableSlot(oldTupDesc,
    6377              :                                                table_slot_callbacks(oldrel));
    6378          752 :             newslot = MakeSingleTupleTableSlot(newTupDesc,
    6379              :                                                table_slot_callbacks(newrel));
    6380              : 
    6381              :             /*
    6382              :              * Set all columns in the new slot to NULL initially, to ensure
    6383              :              * columns added as part of the rewrite are initialized to NULL.
    6384              :              * That is necessary as tab->newvals will not contain an
    6385              :              * expression for columns with a NULL default, e.g. when adding a
    6386              :              * column without a default together with a column with a default
    6387              :              * requiring an actual rewrite.
    6388              :              */
    6389          752 :             ExecStoreAllNullTuple(newslot);
    6390              :         }
    6391              :         else
    6392              :         {
    6393         2739 :             oldslot = MakeSingleTupleTableSlot(newTupDesc,
    6394              :                                                table_slot_callbacks(oldrel));
    6395         2739 :             newslot = NULL;
    6396              :         }
    6397              : 
    6398              :         /*
    6399              :          * Any attributes that are dropped according to the new tuple
    6400              :          * descriptor can be set to NULL. We precompute the list of dropped
    6401              :          * attributes to avoid needing to do so in the per-tuple loop.
    6402              :          */
    6403        12316 :         for (i = 0; i < newTupDesc->natts; i++)
    6404              :         {
    6405         8825 :             if (TupleDescAttr(newTupDesc, i)->attisdropped)
    6406          564 :                 dropped_attrs = lappend_int(dropped_attrs, i);
    6407              :         }
    6408              : 
    6409              :         /*
    6410              :          * Scan through the rows, generating a new row if needed and then
    6411              :          * checking all the constraints.
    6412              :          */
    6413         3491 :         snapshot = RegisterSnapshot(GetLatestSnapshot());
    6414         3491 :         scan = table_beginscan(oldrel, snapshot, 0, NULL);
    6415              : 
    6416              :         /*
    6417              :          * Switch to per-tuple memory context and reset it for each tuple
    6418              :          * produced, so we don't leak memory.
    6419              :          */
    6420         3491 :         oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
    6421              : 
    6422       489917 :         while (table_scan_getnextslot(scan, ForwardScanDirection, oldslot))
    6423              :         {
    6424              :             TupleTableSlot *insertslot;
    6425              : 
    6426       483204 :             if (tab->rewrite > 0)
    6427              :             {
    6428              :                 /* Extract data from old tuple */
    6429        66447 :                 slot_getallattrs(oldslot);
    6430        66447 :                 ExecClearTuple(newslot);
    6431              : 
    6432              :                 /* copy attributes */
    6433        66447 :                 memcpy(newslot->tts_values, oldslot->tts_values,
    6434        66447 :                        sizeof(Datum) * oldslot->tts_nvalid);
    6435        66447 :                 memcpy(newslot->tts_isnull, oldslot->tts_isnull,
    6436        66447 :                        sizeof(bool) * oldslot->tts_nvalid);
    6437              : 
    6438              :                 /* Set dropped attributes to null in new tuple */
    6439        66564 :                 foreach(lc, dropped_attrs)
    6440          117 :                     newslot->tts_isnull[lfirst_int(lc)] = true;
    6441              : 
    6442              :                 /*
    6443              :                  * Constraints and GENERATED expressions might reference the
    6444              :                  * tableoid column, so fill tts_tableOid with the desired
    6445              :                  * value.  (We must do this each time, because it gets
    6446              :                  * overwritten with newrel's OID during storing.)
    6447              :                  */
    6448        66447 :                 newslot->tts_tableOid = RelationGetRelid(oldrel);
    6449              : 
    6450              :                 /*
    6451              :                  * Process supplied expressions to replace selected columns.
    6452              :                  *
    6453              :                  * First, evaluate expressions whose inputs come from the old
    6454              :                  * tuple.
    6455              :                  */
    6456        66447 :                 econtext->ecxt_scantuple = oldslot;
    6457              : 
    6458       136850 :                 foreach(l, tab->newvals)
    6459              :                 {
    6460        70423 :                     NewColumnValue *ex = lfirst(l);
    6461              : 
    6462        70423 :                     if (ex->is_generated)
    6463          208 :                         continue;
    6464              : 
    6465        70215 :                     newslot->tts_values[ex->attnum - 1]
    6466        70195 :                         = ExecEvalExpr(ex->exprstate,
    6467              :                                        econtext,
    6468        70215 :                                        &newslot->tts_isnull[ex->attnum - 1]);
    6469              :                 }
    6470              : 
    6471        66427 :                 ExecStoreVirtualTuple(newslot);
    6472              : 
    6473              :                 /*
    6474              :                  * Now, evaluate any expressions whose inputs come from the
    6475              :                  * new tuple.  We assume these columns won't reference each
    6476              :                  * other, so that there's no ordering dependency.
    6477              :                  */
    6478        66427 :                 econtext->ecxt_scantuple = newslot;
    6479              : 
    6480       136830 :                 foreach(l, tab->newvals)
    6481              :                 {
    6482        70403 :                     NewColumnValue *ex = lfirst(l);
    6483              : 
    6484        70403 :                     if (!ex->is_generated)
    6485        70195 :                         continue;
    6486              : 
    6487          208 :                     newslot->tts_values[ex->attnum - 1]
    6488          208 :                         = ExecEvalExpr(ex->exprstate,
    6489              :                                        econtext,
    6490          208 :                                        &newslot->tts_isnull[ex->attnum - 1]);
    6491              :                 }
    6492              : 
    6493        66427 :                 insertslot = newslot;
    6494              :             }
    6495              :             else
    6496              :             {
    6497              :                 /*
    6498              :                  * If there's no rewrite, old and new table are guaranteed to
    6499              :                  * have the same AM, so we can just use the old slot to verify
    6500              :                  * new constraints etc.
    6501              :                  */
    6502       416757 :                 insertslot = oldslot;
    6503              :             }
    6504              : 
    6505              :             /* Now check any constraints on the possibly-changed tuple */
    6506       483184 :             econtext->ecxt_scantuple = insertslot;
    6507              : 
    6508      2577170 :             foreach_int(attn, notnull_attrs)
    6509              :             {
    6510      1610938 :                 if (slot_attisnull(insertslot, attn))
    6511              :                 {
    6512           68 :                     Form_pg_attribute attr = TupleDescAttr(newTupDesc, attn - 1);
    6513              : 
    6514           68 :                     ereport(ERROR,
    6515              :                             (errcode(ERRCODE_NOT_NULL_VIOLATION),
    6516              :                              errmsg("column \"%s\" of relation \"%s\" contains null values",
    6517              :                                     NameStr(attr->attname),
    6518              :                                     RelationGetRelationName(oldrel)),
    6519              :                              errtablecol(oldrel, attn)));
    6520              :                 }
    6521              :             }
    6522              : 
    6523       483116 :             if (notnull_virtual_attrs != NIL)
    6524              :             {
    6525              :                 AttrNumber  attnum;
    6526              : 
    6527           56 :                 attnum = ExecRelGenVirtualNotNull(rInfo, insertslot,
    6528              :                                                   estate,
    6529              :                                                   notnull_virtual_attrs);
    6530           56 :                 if (attnum != InvalidAttrNumber)
    6531              :                 {
    6532           20 :                     Form_pg_attribute attr = TupleDescAttr(newTupDesc, attnum - 1);
    6533              : 
    6534           20 :                     ereport(ERROR,
    6535              :                             errcode(ERRCODE_NOT_NULL_VIOLATION),
    6536              :                             errmsg("column \"%s\" of relation \"%s\" contains null values",
    6537              :                                    NameStr(attr->attname),
    6538              :                                    RelationGetRelationName(oldrel)),
    6539              :                             errtablecol(oldrel, attnum));
    6540              :                 }
    6541              :             }
    6542              : 
    6543       488309 :             foreach(l, tab->constraints)
    6544              :             {
    6545         5325 :                 NewConstraint *con = lfirst(l);
    6546              : 
    6547         5325 :                 switch (con->contype)
    6548              :                 {
    6549         5259 :                     case CONSTR_CHECK:
    6550         5259 :                         if (!ExecCheck(con->qualstate, econtext))
    6551          112 :                             ereport(ERROR,
    6552              :                                     (errcode(ERRCODE_CHECK_VIOLATION),
    6553              :                                      errmsg("check constraint \"%s\" of relation \"%s\" is violated by some row",
    6554              :                                             con->name,
    6555              :                                             RelationGetRelationName(oldrel)),
    6556              :                                      errtableconstraint(oldrel, con->name)));
    6557         5147 :                         break;
    6558           66 :                     case CONSTR_NOTNULL:
    6559              :                     case CONSTR_FOREIGN:
    6560              :                         /* Nothing to do here */
    6561           66 :                         break;
    6562            0 :                     default:
    6563            0 :                         elog(ERROR, "unrecognized constraint type: %d",
    6564              :                              (int) con->contype);
    6565              :                 }
    6566              :             }
    6567              : 
    6568       482984 :             if (partqualstate && !ExecCheck(partqualstate, econtext))
    6569              :             {
    6570           49 :                 if (tab->validate_default)
    6571           17 :                     ereport(ERROR,
    6572              :                             (errcode(ERRCODE_CHECK_VIOLATION),
    6573              :                              errmsg("updated partition constraint for default partition \"%s\" would be violated by some row",
    6574              :                                     RelationGetRelationName(oldrel)),
    6575              :                              errtable(oldrel)));
    6576              :                 else
    6577           32 :                     ereport(ERROR,
    6578              :                             (errcode(ERRCODE_CHECK_VIOLATION),
    6579              :                              errmsg("partition constraint of relation \"%s\" is violated by some row",
    6580              :                                     RelationGetRelationName(oldrel)),
    6581              :                              errtable(oldrel)));
    6582              :             }
    6583              : 
    6584              :             /* Write the tuple out to the new relation */
    6585       482935 :             if (newrel)
    6586        66407 :                 table_tuple_insert(newrel, insertslot, mycid,
    6587              :                                    ti_options, bistate);
    6588              : 
    6589       482935 :             ResetExprContext(econtext);
    6590              : 
    6591       482935 :             CHECK_FOR_INTERRUPTS();
    6592              :         }
    6593              : 
    6594         3222 :         MemoryContextSwitchTo(oldCxt);
    6595         3222 :         table_endscan(scan);
    6596         3222 :         UnregisterSnapshot(snapshot);
    6597              : 
    6598         3222 :         ExecDropSingleTupleTableSlot(oldslot);
    6599         3222 :         if (newslot)
    6600          712 :             ExecDropSingleTupleTableSlot(newslot);
    6601              :     }
    6602              : 
    6603         3830 :     FreeExecutorState(estate);
    6604              : 
    6605         3830 :     table_close(oldrel, NoLock);
    6606         3830 :     if (newrel)
    6607              :     {
    6608          712 :         FreeBulkInsertState(bistate);
    6609              : 
    6610          712 :         table_finish_bulk_insert(newrel, ti_options);
    6611              : 
    6612          712 :         table_close(newrel, NoLock);
    6613              :     }
    6614         3830 : }
    6615              : 
    6616              : /*
    6617              :  * ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
    6618              :  */
    6619              : static AlteredTableInfo *
    6620        27878 : ATGetQueueEntry(List **wqueue, Relation rel)
    6621              : {
    6622        27878 :     Oid         relid = RelationGetRelid(rel);
    6623              :     AlteredTableInfo *tab;
    6624              :     ListCell   *ltab;
    6625              : 
    6626        36154 :     foreach(ltab, *wqueue)
    6627              :     {
    6628        12003 :         tab = (AlteredTableInfo *) lfirst(ltab);
    6629        12003 :         if (tab->relid == relid)
    6630         3727 :             return tab;
    6631              :     }
    6632              : 
    6633              :     /*
    6634              :      * Not there, so add it.  Note that we make a copy of the relation's
    6635              :      * existing descriptor before anything interesting can happen to it.
    6636              :      */
    6637        24151 :     tab = palloc0_object(AlteredTableInfo);
    6638        24151 :     tab->relid = relid;
    6639        24151 :     tab->rel = NULL;         /* set later */
    6640        24151 :     tab->relkind = rel->rd_rel->relkind;
    6641        24151 :     tab->oldDesc = CreateTupleDescCopyConstr(RelationGetDescr(rel));
    6642        24151 :     tab->newAccessMethod = InvalidOid;
    6643        24151 :     tab->chgAccessMethod = false;
    6644        24151 :     tab->newTableSpace = InvalidOid;
    6645        24151 :     tab->newrelpersistence = RELPERSISTENCE_PERMANENT;
    6646        24151 :     tab->chgPersistence = false;
    6647              : 
    6648        24151 :     *wqueue = lappend(*wqueue, tab);
    6649              : 
    6650        24151 :     return tab;
    6651              : }
    6652              : 
    6653              : static const char *
    6654           73 : alter_table_type_to_string(AlterTableType cmdtype)
    6655              : {
    6656           73 :     switch (cmdtype)
    6657              :     {
    6658            0 :         case AT_AddColumn:
    6659              :         case AT_AddColumnToView:
    6660            0 :             return "ADD COLUMN";
    6661            0 :         case AT_ColumnDefault:
    6662              :         case AT_CookedColumnDefault:
    6663            0 :             return "ALTER COLUMN ... SET DEFAULT";
    6664            4 :         case AT_DropNotNull:
    6665            4 :             return "ALTER COLUMN ... DROP NOT NULL";
    6666            4 :         case AT_SetNotNull:
    6667            4 :             return "ALTER COLUMN ... SET NOT NULL";
    6668            0 :         case AT_SetExpression:
    6669            0 :             return "ALTER COLUMN ... SET EXPRESSION";
    6670            0 :         case AT_DropExpression:
    6671            0 :             return "ALTER COLUMN ... DROP EXPRESSION";
    6672            0 :         case AT_SetStatistics:
    6673            0 :             return "ALTER COLUMN ... SET STATISTICS";
    6674            8 :         case AT_SetOptions:
    6675            8 :             return "ALTER COLUMN ... SET";
    6676            0 :         case AT_ResetOptions:
    6677            0 :             return "ALTER COLUMN ... RESET";
    6678            0 :         case AT_SetStorage:
    6679            0 :             return "ALTER COLUMN ... SET STORAGE";
    6680            0 :         case AT_SetCompression:
    6681            0 :             return "ALTER COLUMN ... SET COMPRESSION";
    6682            4 :         case AT_DropColumn:
    6683            4 :             return "DROP COLUMN";
    6684            0 :         case AT_AddIndex:
    6685              :         case AT_ReAddIndex:
    6686            0 :             return NULL;        /* not real grammar */
    6687            0 :         case AT_AddConstraint:
    6688              :         case AT_ReAddConstraint:
    6689              :         case AT_ReAddDomainConstraint:
    6690              :         case AT_AddIndexConstraint:
    6691            0 :             return "ADD CONSTRAINT";
    6692            4 :         case AT_AlterConstraint:
    6693            4 :             return "ALTER CONSTRAINT";
    6694            0 :         case AT_ValidateConstraint:
    6695            0 :             return "VALIDATE CONSTRAINT";
    6696            0 :         case AT_DropConstraint:
    6697            0 :             return "DROP CONSTRAINT";
    6698            0 :         case AT_ReAddComment:
    6699            0 :             return NULL;        /* not real grammar */
    6700            0 :         case AT_AlterColumnType:
    6701            0 :             return "ALTER COLUMN ... SET DATA TYPE";
    6702            0 :         case AT_AlterColumnGenericOptions:
    6703            0 :             return "ALTER COLUMN ... OPTIONS";
    6704            0 :         case AT_ChangeOwner:
    6705            0 :             return "OWNER TO";
    6706            4 :         case AT_ClusterOn:
    6707            4 :             return "CLUSTER ON";
    6708            4 :         case AT_DropCluster:
    6709            4 :             return "SET WITHOUT CLUSTER";
    6710            0 :         case AT_SetAccessMethod:
    6711            0 :             return "SET ACCESS METHOD";
    6712            4 :         case AT_SetLogged:
    6713            4 :             return "SET LOGGED";
    6714            4 :         case AT_SetUnLogged:
    6715            4 :             return "SET UNLOGGED";
    6716            0 :         case AT_DropOids:
    6717            0 :             return "SET WITHOUT OIDS";
    6718            0 :         case AT_SetTableSpace:
    6719            0 :             return "SET TABLESPACE";
    6720            1 :         case AT_SetRelOptions:
    6721            1 :             return "SET";
    6722            0 :         case AT_ResetRelOptions:
    6723            0 :             return "RESET";
    6724            0 :         case AT_ReplaceRelOptions:
    6725            0 :             return NULL;        /* not real grammar */
    6726            0 :         case AT_EnableTrig:
    6727            0 :             return "ENABLE TRIGGER";
    6728            0 :         case AT_EnableAlwaysTrig:
    6729            0 :             return "ENABLE ALWAYS TRIGGER";
    6730            0 :         case AT_EnableReplicaTrig:
    6731            0 :             return "ENABLE REPLICA TRIGGER";
    6732            0 :         case AT_DisableTrig:
    6733            0 :             return "DISABLE TRIGGER";
    6734            0 :         case AT_EnableTrigAll:
    6735            0 :             return "ENABLE TRIGGER ALL";
    6736            0 :         case AT_DisableTrigAll:
    6737            0 :             return "DISABLE TRIGGER ALL";
    6738            0 :         case AT_EnableTrigUser:
    6739            0 :             return "ENABLE TRIGGER USER";
    6740            0 :         case AT_DisableTrigUser:
    6741            0 :             return "DISABLE TRIGGER USER";
    6742            0 :         case AT_EnableRule:
    6743            0 :             return "ENABLE RULE";
    6744            0 :         case AT_EnableAlwaysRule:
    6745            0 :             return "ENABLE ALWAYS RULE";
    6746            0 :         case AT_EnableReplicaRule:
    6747            0 :             return "ENABLE REPLICA RULE";
    6748            0 :         case AT_DisableRule:
    6749            0 :             return "DISABLE RULE";
    6750            4 :         case AT_AddInherit:
    6751            4 :             return "INHERIT";
    6752            4 :         case AT_DropInherit:
    6753            4 :             return "NO INHERIT";
    6754            0 :         case AT_AddOf:
    6755            0 :             return "OF";
    6756            0 :         case AT_DropOf:
    6757            0 :             return "NOT OF";
    6758            0 :         case AT_ReplicaIdentity:
    6759            0 :             return "REPLICA IDENTITY";
    6760            0 :         case AT_EnableRowSecurity:
    6761            0 :             return "ENABLE ROW SECURITY";
    6762            0 :         case AT_DisableRowSecurity:
    6763            0 :             return "DISABLE ROW SECURITY";
    6764            0 :         case AT_ForceRowSecurity:
    6765            0 :             return "FORCE ROW SECURITY";
    6766            0 :         case AT_NoForceRowSecurity:
    6767            0 :             return "NO FORCE ROW SECURITY";
    6768            0 :         case AT_GenericOptions:
    6769            0 :             return "OPTIONS";
    6770            4 :         case AT_AttachPartition:
    6771            4 :             return "ATTACH PARTITION";
    6772           12 :         case AT_DetachPartition:
    6773           12 :             return "DETACH PARTITION";
    6774            4 :         case AT_DetachPartitionFinalize:
    6775            4 :             return "DETACH PARTITION ... FINALIZE";
    6776            0 :         case AT_MergePartitions:
    6777            0 :             return "MERGE PARTITIONS";
    6778            4 :         case AT_SplitPartition:
    6779            4 :             return "SPLIT PARTITION";
    6780            0 :         case AT_AddIdentity:
    6781            0 :             return "ALTER COLUMN ... ADD IDENTITY";
    6782            0 :         case AT_SetIdentity:
    6783            0 :             return "ALTER COLUMN ... SET";
    6784            0 :         case AT_DropIdentity:
    6785            0 :             return "ALTER COLUMN ... DROP IDENTITY";
    6786            0 :         case AT_ReAddStatistics:
    6787            0 :             return NULL;        /* not real grammar */
    6788              :     }
    6789              : 
    6790            0 :     return NULL;
    6791              : }
    6792              : 
    6793              : /*
    6794              :  * ATSimplePermissions
    6795              :  *
    6796              :  * - Ensure that it is a relation (or possibly a view)
    6797              :  * - Ensure this user is the owner
    6798              :  * - Ensure that it is not a system table
    6799              :  */
    6800              : static void
    6801        24718 : ATSimplePermissions(AlterTableType cmdtype, Relation rel, int allowed_targets)
    6802              : {
    6803              :     int         actual_target;
    6804              : 
    6805        24718 :     switch (rel->rd_rel->relkind)
    6806              :     {
    6807        18989 :         case RELKIND_RELATION:
    6808        18989 :             actual_target = ATT_TABLE;
    6809        18989 :             break;
    6810         4253 :         case RELKIND_PARTITIONED_TABLE:
    6811         4253 :             actual_target = ATT_PARTITIONED_TABLE;
    6812         4253 :             break;
    6813          276 :         case RELKIND_VIEW:
    6814          276 :             actual_target = ATT_VIEW;
    6815          276 :             break;
    6816           30 :         case RELKIND_MATVIEW:
    6817           30 :             actual_target = ATT_MATVIEW;
    6818           30 :             break;
    6819          145 :         case RELKIND_INDEX:
    6820          145 :             actual_target = ATT_INDEX;
    6821          145 :             break;
    6822          275 :         case RELKIND_PARTITIONED_INDEX:
    6823          275 :             actual_target = ATT_PARTITIONED_INDEX;
    6824          275 :             break;
    6825          141 :         case RELKIND_COMPOSITE_TYPE:
    6826          141 :             actual_target = ATT_COMPOSITE_TYPE;
    6827          141 :             break;
    6828          592 :         case RELKIND_FOREIGN_TABLE:
    6829          592 :             actual_target = ATT_FOREIGN_TABLE;
    6830          592 :             break;
    6831           16 :         case RELKIND_SEQUENCE:
    6832           16 :             actual_target = ATT_SEQUENCE;
    6833           16 :             break;
    6834            1 :         default:
    6835            1 :             actual_target = 0;
    6836            1 :             break;
    6837              :     }
    6838              : 
    6839              :     /* Wrong target type? */
    6840        24718 :     if ((actual_target & allowed_targets) == 0)
    6841              :     {
    6842           73 :         const char *action_str = alter_table_type_to_string(cmdtype);
    6843              : 
    6844           73 :         if (action_str)
    6845           73 :             ereport(ERROR,
    6846              :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    6847              :             /* translator: %s is a group of some SQL keywords */
    6848              :                      errmsg("ALTER action %s cannot be performed on relation \"%s\"",
    6849              :                             action_str, RelationGetRelationName(rel)),
    6850              :                      errdetail_relkind_not_supported(rel->rd_rel->relkind)));
    6851              :         else
    6852              :             /* internal error? */
    6853            0 :             elog(ERROR, "invalid ALTER action attempted on relation \"%s\"",
    6854              :                  RelationGetRelationName(rel));
    6855              :     }
    6856              : 
    6857              :     /* Permissions checks */
    6858        24645 :     if (!object_ownercheck(RelationRelationId, RelationGetRelid(rel), GetUserId()))
    6859            8 :         aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(rel->rd_rel->relkind),
    6860            8 :                        RelationGetRelationName(rel));
    6861              : 
    6862        24637 :     if (!allowSystemTableMods && IsSystemRelation(rel))
    6863            0 :         ereport(ERROR,
    6864              :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
    6865              :                  errmsg("permission denied: \"%s\" is a system catalog",
    6866              :                         RelationGetRelationName(rel))));
    6867        24637 : }
    6868              : 
    6869              : /*
    6870              :  * ATSimpleRecursion
    6871              :  *
    6872              :  * Simple table recursion sufficient for most ALTER TABLE operations.
    6873              :  * All direct and indirect children are processed in an unspecified order.
    6874              :  * Note that if a child inherits from the original table via multiple
    6875              :  * inheritance paths, it will be visited just once.
    6876              :  */
    6877              : static void
    6878          897 : ATSimpleRecursion(List **wqueue, Relation rel,
    6879              :                   AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode,
    6880              :                   AlterTableUtilityContext *context)
    6881              : {
    6882              :     /*
    6883              :      * Propagate to children, if desired and if there are (or might be) any
    6884              :      * children.
    6885              :      */
    6886          897 :     if (recurse && rel->rd_rel->relhassubclass)
    6887              :     {
    6888           55 :         Oid         relid = RelationGetRelid(rel);
    6889              :         ListCell   *child;
    6890              :         List       *children;
    6891              : 
    6892           55 :         children = find_all_inheritors(relid, lockmode, NULL);
    6893              : 
    6894              :         /*
    6895              :          * find_all_inheritors does the recursive search of the inheritance
    6896              :          * hierarchy, so all we have to do is process all of the relids in the
    6897              :          * list that it returns.
    6898              :          */
    6899          240 :         foreach(child, children)
    6900              :         {
    6901          185 :             Oid         childrelid = lfirst_oid(child);
    6902              :             Relation    childrel;
    6903              : 
    6904          185 :             if (childrelid == relid)
    6905           55 :                 continue;
    6906              :             /* find_all_inheritors already got lock */
    6907          130 :             childrel = relation_open(childrelid, NoLock);
    6908          130 :             CheckAlterTableIsSafe(childrel);
    6909          130 :             ATPrepCmd(wqueue, childrel, cmd, false, true, lockmode, context);
    6910          130 :             relation_close(childrel, NoLock);
    6911              :         }
    6912              :     }
    6913          897 : }
    6914              : 
    6915              : /*
    6916              :  * Obtain list of partitions of the given table, locking them all at the given
    6917              :  * lockmode and ensuring that they all pass CheckAlterTableIsSafe.
    6918              :  *
    6919              :  * This function is a no-op if the given relation is not a partitioned table;
    6920              :  * in particular, nothing is done if it's a legacy inheritance parent.
    6921              :  */
    6922              : static void
    6923          553 : ATCheckPartitionsNotInUse(Relation rel, LOCKMODE lockmode)
    6924              : {
    6925          553 :     if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
    6926              :     {
    6927              :         List       *inh;
    6928              :         ListCell   *cell;
    6929              : 
    6930          121 :         inh = find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
    6931              :         /* first element is the parent rel; must ignore it */
    6932          398 :         for_each_from(cell, inh, 1)
    6933              :         {
    6934              :             Relation    childrel;
    6935              : 
    6936              :             /* find_all_inheritors already got lock */
    6937          281 :             childrel = table_open(lfirst_oid(cell), NoLock);
    6938          281 :             CheckAlterTableIsSafe(childrel);
    6939          277 :             table_close(childrel, NoLock);
    6940              :         }
    6941          117 :         list_free(inh);
    6942              :     }
    6943          549 : }
    6944              : 
    6945              : /*
    6946              :  * ATTypedTableRecursion
    6947              :  *
    6948              :  * Propagate ALTER TYPE operations to the typed tables of that type.
    6949              :  * Also check the RESTRICT/CASCADE behavior.  Given CASCADE, also permit
    6950              :  * recursion to inheritance children of the typed tables.
    6951              :  */
    6952              : static void
    6953          125 : ATTypedTableRecursion(List **wqueue, Relation rel, AlterTableCmd *cmd,
    6954              :                       LOCKMODE lockmode, AlterTableUtilityContext *context)
    6955              : {
    6956              :     ListCell   *child;
    6957              :     List       *children;
    6958              : 
    6959              :     Assert(rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
    6960              : 
    6961          125 :     children = find_typed_table_dependencies(rel->rd_rel->reltype,
    6962          125 :                                              RelationGetRelationName(rel),
    6963              :                                              cmd->behavior);
    6964              : 
    6965          133 :     foreach(child, children)
    6966              :     {
    6967           20 :         Oid         childrelid = lfirst_oid(child);
    6968              :         Relation    childrel;
    6969              : 
    6970           20 :         childrel = relation_open(childrelid, lockmode);
    6971           20 :         CheckAlterTableIsSafe(childrel);
    6972           20 :         ATPrepCmd(wqueue, childrel, cmd, true, true, lockmode, context);
    6973           20 :         relation_close(childrel, NoLock);
    6974              :     }
    6975          113 : }
    6976              : 
    6977              : 
    6978              : /*
    6979              :  * find_composite_type_dependencies
    6980              :  *
    6981              :  * Check to see if the type "typeOid" is being used as a column in some table
    6982              :  * (possibly nested several levels deep in composite types, arrays, etc!).
    6983              :  * Eventually, we'd like to propagate the check or rewrite operation
    6984              :  * into such tables, but for now, just error out if we find any.
    6985              :  *
    6986              :  * Caller should provide either the associated relation of a rowtype,
    6987              :  * or a type name (not both) for use in the error message, if any.
    6988              :  *
    6989              :  * Note that "typeOid" is not necessarily a composite type; it could also be
    6990              :  * another container type such as an array or range, or a domain over one of
    6991              :  * these things.  The name of this function is therefore somewhat historical,
    6992              :  * but it's not worth changing.
    6993              :  *
    6994              :  * We assume that functions and views depending on the type are not reasons
    6995              :  * to reject the ALTER.  (How safe is this really?)
    6996              :  */
    6997              : void
    6998         3243 : find_composite_type_dependencies(Oid typeOid, Relation origRelation,
    6999              :                                  const char *origTypeName)
    7000              : {
    7001              :     Relation    depRel;
    7002              :     ScanKeyData key[2];
    7003              :     SysScanDesc depScan;
    7004              :     HeapTuple   depTup;
    7005              : 
    7006              :     /* since this function recurses, it could be driven to stack overflow */
    7007         3243 :     check_stack_depth();
    7008              : 
    7009              :     /*
    7010              :      * We scan pg_depend to find those things that depend on the given type.
    7011              :      * (We assume we can ignore refobjsubid for a type.)
    7012              :      */
    7013         3243 :     depRel = table_open(DependRelationId, AccessShareLock);
    7014              : 
    7015         3243 :     ScanKeyInit(&key[0],
    7016              :                 Anum_pg_depend_refclassid,
    7017              :                 BTEqualStrategyNumber, F_OIDEQ,
    7018              :                 ObjectIdGetDatum(TypeRelationId));
    7019         3243 :     ScanKeyInit(&key[1],
    7020              :                 Anum_pg_depend_refobjid,
    7021              :                 BTEqualStrategyNumber, F_OIDEQ,
    7022              :                 ObjectIdGetDatum(typeOid));
    7023              : 
    7024         3243 :     depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
    7025              :                                  NULL, 2, key);
    7026              : 
    7027         4976 :     while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
    7028              :     {
    7029         1837 :         Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
    7030              :         Relation    rel;
    7031              :         TupleDesc   tupleDesc;
    7032              :         Form_pg_attribute att;
    7033              : 
    7034              :         /* Check for directly dependent types */
    7035         1837 :         if (pg_depend->classid == TypeRelationId)
    7036              :         {
    7037              :             /*
    7038              :              * This must be an array, domain, or range containing the given
    7039              :              * type, so recursively check for uses of this type.  Note that
    7040              :              * any error message will mention the original type not the
    7041              :              * container; this is intentional.
    7042              :              */
    7043         1567 :             find_composite_type_dependencies(pg_depend->objid,
    7044              :                                              origRelation, origTypeName);
    7045         1551 :             continue;
    7046              :         }
    7047              : 
    7048              :         /* Else, ignore dependees that aren't relations */
    7049          270 :         if (pg_depend->classid != RelationRelationId)
    7050           81 :             continue;
    7051              : 
    7052          189 :         rel = relation_open(pg_depend->objid, AccessShareLock);
    7053          189 :         tupleDesc = RelationGetDescr(rel);
    7054              : 
    7055              :         /*
    7056              :          * If objsubid identifies a specific column, refer to that in error
    7057              :          * messages.  Otherwise, search to see if there's a user column of the
    7058              :          * type.  (We assume system columns are never of interesting types.)
    7059              :          * The search is needed because an index containing an expression
    7060              :          * column of the target type will just be recorded as a whole-relation
    7061              :          * dependency.  If we do not find a column of the type, the dependency
    7062              :          * must indicate that the type is transiently referenced in an index
    7063              :          * expression but not stored on disk, which we assume is OK, just as
    7064              :          * we do for references in views.  (It could also be that the target
    7065              :          * type is embedded in some container type that is stored in an index
    7066              :          * column, but the previous recursion should catch such cases.)
    7067              :          */
    7068          189 :         if (pg_depend->objsubid > 0 && pg_depend->objsubid <= tupleDesc->natts)
    7069           84 :             att = TupleDescAttr(tupleDesc, pg_depend->objsubid - 1);
    7070              :         else
    7071              :         {
    7072          105 :             att = NULL;
    7073          270 :             for (int attno = 1; attno <= tupleDesc->natts; attno++)
    7074              :             {
    7075          169 :                 att = TupleDescAttr(tupleDesc, attno - 1);
    7076          169 :                 if (att->atttypid == typeOid && !att->attisdropped)
    7077            4 :                     break;
    7078          165 :                 att = NULL;
    7079              :             }
    7080          105 :             if (att == NULL)
    7081              :             {
    7082              :                 /* No such column, so assume OK */
    7083          101 :                 relation_close(rel, AccessShareLock);
    7084          101 :                 continue;
    7085              :             }
    7086              :         }
    7087              : 
    7088              :         /*
    7089              :          * We definitely should reject if the relation has storage.  If it's
    7090              :          * partitioned, then perhaps we don't have to reject: if there are
    7091              :          * partitions then we'll fail when we find one, else there is no
    7092              :          * stored data to worry about.  However, it's possible that the type
    7093              :          * change would affect conclusions about whether the type is sortable
    7094              :          * or hashable and thus (if it's a partitioning column) break the
    7095              :          * partitioning rule.  For now, reject for partitioned rels too.
    7096              :          */
    7097           88 :         if (RELKIND_HAS_STORAGE(rel->rd_rel->relkind) ||
    7098            0 :             RELKIND_HAS_PARTITIONS(rel->rd_rel->relkind))
    7099              :         {
    7100           88 :             if (origTypeName)
    7101           20 :                 ereport(ERROR,
    7102              :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    7103              :                          errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
    7104              :                                 origTypeName,
    7105              :                                 RelationGetRelationName(rel),
    7106              :                                 NameStr(att->attname))));
    7107           68 :             else if (origRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
    7108           12 :                 ereport(ERROR,
    7109              :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    7110              :                          errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
    7111              :                                 RelationGetRelationName(origRelation),
    7112              :                                 RelationGetRelationName(rel),
    7113              :                                 NameStr(att->attname))));
    7114           56 :             else if (origRelation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
    7115            4 :                 ereport(ERROR,
    7116              :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    7117              :                          errmsg("cannot alter foreign table \"%s\" because column \"%s.%s\" uses its row type",
    7118              :                                 RelationGetRelationName(origRelation),
    7119              :                                 RelationGetRelationName(rel),
    7120              :                                 NameStr(att->attname))));
    7121              :             else
    7122           52 :                 ereport(ERROR,
    7123              :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    7124              :                          errmsg("cannot alter table \"%s\" because column \"%s.%s\" uses its row type",
    7125              :                                 RelationGetRelationName(origRelation),
    7126              :                                 RelationGetRelationName(rel),
    7127              :                                 NameStr(att->attname))));
    7128              :         }
    7129            0 :         else if (OidIsValid(rel->rd_rel->reltype))
    7130              :         {
    7131              :             /*
    7132              :              * A view or composite type itself isn't a problem, but we must
    7133              :              * recursively check for indirect dependencies via its rowtype.
    7134              :              */
    7135            0 :             find_composite_type_dependencies(rel->rd_rel->reltype,
    7136              :                                              origRelation, origTypeName);
    7137              :         }
    7138              : 
    7139            0 :         relation_close(rel, AccessShareLock);
    7140              :     }
    7141              : 
    7142         3139 :     systable_endscan(depScan);
    7143              : 
    7144         3139 :     relation_close(depRel, AccessShareLock);
    7145         3139 : }
    7146              : 
    7147              : 
    7148              : /*
    7149              :  * find_typed_table_dependencies
    7150              :  *
    7151              :  * Check to see if a composite type is being used as the type of a
    7152              :  * typed table.  Abort if any are found and behavior is RESTRICT.
    7153              :  * Else return the list of tables.
    7154              :  */
    7155              : static List *
    7156          141 : find_typed_table_dependencies(Oid typeOid, const char *typeName, DropBehavior behavior)
    7157              : {
    7158              :     Relation    classRel;
    7159              :     ScanKeyData key[1];
    7160              :     TableScanDesc scan;
    7161              :     HeapTuple   tuple;
    7162          141 :     List       *result = NIL;
    7163              : 
    7164          141 :     classRel = table_open(RelationRelationId, AccessShareLock);
    7165              : 
    7166          141 :     ScanKeyInit(&key[0],
    7167              :                 Anum_pg_class_reloftype,
    7168              :                 BTEqualStrategyNumber, F_OIDEQ,
    7169              :                 ObjectIdGetDatum(typeOid));
    7170              : 
    7171          141 :     scan = table_beginscan_catalog(classRel, 1, key);
    7172              : 
    7173          165 :     while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
    7174              :     {
    7175           40 :         Form_pg_class classform = (Form_pg_class) GETSTRUCT(tuple);
    7176              : 
    7177           40 :         if (behavior == DROP_RESTRICT)
    7178           16 :             ereport(ERROR,
    7179              :                     (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
    7180              :                      errmsg("cannot alter type \"%s\" because it is the type of a typed table",
    7181              :                             typeName),
    7182              :                      errhint("Use ALTER ... CASCADE to alter the typed tables too.")));
    7183              :         else
    7184           24 :             result = lappend_oid(result, classform->oid);
    7185              :     }
    7186              : 
    7187          125 :     table_endscan(scan);
    7188          125 :     table_close(classRel, AccessShareLock);
    7189              : 
    7190          125 :     return result;
    7191              : }
    7192              : 
    7193              : 
    7194              : /*
    7195              :  * check_of_type
    7196              :  *
    7197              :  * Check whether a type is suitable for CREATE TABLE OF/ALTER TABLE OF.  If it
    7198              :  * isn't suitable, throw an error.  Currently, we require that the type
    7199              :  * originated with CREATE TYPE AS.  We could support any row type, but doing so
    7200              :  * would require handling a number of extra corner cases in the DDL commands.
    7201              :  * (Also, allowing domain-over-composite would open up a can of worms about
    7202              :  * whether and how the domain's constraints should apply to derived tables.)
    7203              :  */
    7204              : void
    7205          119 : check_of_type(HeapTuple typetuple)
    7206              : {
    7207          119 :     Form_pg_type typ = (Form_pg_type) GETSTRUCT(typetuple);
    7208          119 :     bool        typeOk = false;
    7209              : 
    7210          119 :     if (typ->typtype == TYPTYPE_COMPOSITE)
    7211              :     {
    7212              :         Relation    typeRelation;
    7213              : 
    7214              :         Assert(OidIsValid(typ->typrelid));
    7215          115 :         typeRelation = relation_open(typ->typrelid, AccessShareLock);
    7216          115 :         typeOk = (typeRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
    7217              : 
    7218              :         /*
    7219              :          * Close the parent rel, but keep our AccessShareLock on it until xact
    7220              :          * commit.  That will prevent someone else from deleting or ALTERing
    7221              :          * the type before the typed table creation/conversion commits.
    7222              :          */
    7223          115 :         relation_close(typeRelation, NoLock);
    7224              : 
    7225          115 :         if (!typeOk)
    7226            4 :             ereport(ERROR,
    7227              :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    7228              :                      errmsg("type %s is the row type of another table",
    7229              :                             format_type_be(typ->oid)),
    7230              :                      errdetail("A typed table must use a stand-alone composite type created with CREATE TYPE.")));
    7231              :     }
    7232              :     else
    7233            4 :         ereport(ERROR,
    7234              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    7235              :                  errmsg("type %s is not a composite type",
    7236              :                         format_type_be(typ->oid))));
    7237          111 : }
    7238              : 
    7239              : 
    7240              : /*
    7241              :  * ALTER TABLE ADD COLUMN
    7242              :  *
    7243              :  * Adds an additional attribute to a relation making the assumption that
    7244              :  * CHECK, NOT NULL, and FOREIGN KEY constraints will be removed from the
    7245              :  * AT_AddColumn AlterTableCmd by parse_utilcmd.c and added as independent
    7246              :  * AlterTableCmd's.
    7247              :  *
    7248              :  * ADD COLUMN cannot use the normal ALTER TABLE recursion mechanism, because we
    7249              :  * have to decide at runtime whether to recurse or not depending on whether we
    7250              :  * actually add a column or merely merge with an existing column.  (We can't
    7251              :  * check this in a static pre-pass because it won't handle multiple inheritance
    7252              :  * situations correctly.)
    7253              :  */
    7254              : static void
    7255         1581 : ATPrepAddColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
    7256              :                 bool is_view, AlterTableCmd *cmd, LOCKMODE lockmode,
    7257              :                 AlterTableUtilityContext *context)
    7258              : {
    7259         1581 :     if (rel->rd_rel->reloftype && !recursing)
    7260            4 :         ereport(ERROR,
    7261              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    7262              :                  errmsg("cannot add column to typed table")));
    7263              : 
    7264         1577 :     if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
    7265           38 :         ATTypedTableRecursion(wqueue, rel, cmd, lockmode, context);
    7266              : 
    7267         1573 :     if (recurse && !is_view)
    7268         1502 :         cmd->recurse = true;
    7269         1573 : }
    7270              : 
    7271              : /*
    7272              :  * Add a column to a table.  The return value is the address of the
    7273              :  * new column in the parent relation.
    7274              :  *
    7275              :  * cmd is pass-by-ref so that we can replace it with the parse-transformed
    7276              :  * copy (but that happens only after we check for IF NOT EXISTS).
    7277              :  */
    7278              : static ObjectAddress
    7279         2059 : ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel,
    7280              :                 AlterTableCmd **cmd, bool recurse, bool recursing,
    7281              :                 LOCKMODE lockmode, AlterTablePass cur_pass,
    7282              :                 AlterTableUtilityContext *context)
    7283              : {
    7284         2059 :     Oid         myrelid = RelationGetRelid(rel);
    7285         2059 :     ColumnDef  *colDef = castNode(ColumnDef, (*cmd)->def);
    7286         2059 :     bool        if_not_exists = (*cmd)->missing_ok;
    7287              :     Relation    pgclass,
    7288              :                 attrdesc;
    7289              :     HeapTuple   reltup;
    7290              :     Form_pg_class relform;
    7291              :     Form_pg_attribute attribute;
    7292              :     int         newattnum;
    7293              :     char        relkind;
    7294              :     Expr       *defval;
    7295              :     List       *children;
    7296              :     ListCell   *child;
    7297              :     AlterTableCmd *childcmd;
    7298              :     ObjectAddress address;
    7299              :     TupleDesc   tupdesc;
    7300              : 
    7301              :     /* since this function recurses, it could be driven to stack overflow */
    7302         2059 :     check_stack_depth();
    7303              : 
    7304              :     /* At top level, permission check was done in ATPrepCmd, else do it */
    7305         2059 :     if (recursing)
    7306          490 :         ATSimplePermissions((*cmd)->subtype, rel,
    7307              :                             ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
    7308              : 
    7309         2059 :     if (rel->rd_rel->relispartition && !recursing)
    7310            8 :         ereport(ERROR,
    7311              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    7312              :                  errmsg("cannot add column to a partition")));
    7313              : 
    7314         2051 :     attrdesc = table_open(AttributeRelationId, RowExclusiveLock);
    7315              : 
    7316              :     /*
    7317              :      * Are we adding the column to a recursion child?  If so, check whether to
    7318              :      * merge with an existing definition for the column.  If we do merge, we
    7319              :      * must not recurse.  Children will already have the column, and recursing
    7320              :      * into them would mess up attinhcount.
    7321              :      */
    7322         2051 :     if (colDef->inhcount > 0)
    7323              :     {
    7324              :         HeapTuple   tuple;
    7325              : 
    7326              :         /* Does child already have a column by this name? */
    7327          490 :         tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
    7328          490 :         if (HeapTupleIsValid(tuple))
    7329              :         {
    7330           40 :             Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
    7331              :             Oid         ctypeId;
    7332              :             int32       ctypmod;
    7333              :             Oid         ccollid;
    7334              : 
    7335              :             /* Child column must match on type, typmod, and collation */
    7336           40 :             typenameTypeIdAndMod(NULL, colDef->typeName, &ctypeId, &ctypmod);
    7337           40 :             if (ctypeId != childatt->atttypid ||
    7338           40 :                 ctypmod != childatt->atttypmod)
    7339            0 :                 ereport(ERROR,
    7340              :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    7341              :                          errmsg("child table \"%s\" has different type for column \"%s\"",
    7342              :                                 RelationGetRelationName(rel), colDef->colname)));
    7343           40 :             ccollid = GetColumnDefCollation(NULL, colDef, ctypeId);
    7344           40 :             if (ccollid != childatt->attcollation)
    7345            0 :                 ereport(ERROR,
    7346              :                         (errcode(ERRCODE_COLLATION_MISMATCH),
    7347              :                          errmsg("child table \"%s\" has different collation for column \"%s\"",
    7348              :                                 RelationGetRelationName(rel), colDef->colname),
    7349              :                          errdetail("\"%s\" versus \"%s\"",
    7350              :                                    get_collation_name(ccollid),
    7351              :                                    get_collation_name(childatt->attcollation))));
    7352              : 
    7353              :             /* Bump the existing child att's inhcount */
    7354           40 :             if (pg_add_s16_overflow(childatt->attinhcount, 1,
    7355              :                                     &childatt->attinhcount))
    7356            0 :                 ereport(ERROR,
    7357              :                         errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    7358              :                         errmsg("too many inheritance parents"));
    7359           40 :             CatalogTupleUpdate(attrdesc, &tuple->t_self, tuple);
    7360              : 
    7361           40 :             heap_freetuple(tuple);
    7362              : 
    7363              :             /* Inform the user about the merge */
    7364           40 :             ereport(NOTICE,
    7365              :                     (errmsg("merging definition of column \"%s\" for child \"%s\"",
    7366              :                             colDef->colname, RelationGetRelationName(rel))));
    7367              : 
    7368           40 :             table_close(attrdesc, RowExclusiveLock);
    7369              : 
    7370              :             /* Make the child column change visible */
    7371           40 :             CommandCounterIncrement();
    7372              : 
    7373           40 :             return InvalidObjectAddress;
    7374              :         }
    7375              :     }
    7376              : 
    7377              :     /* skip if the name already exists and if_not_exists is true */
    7378         2011 :     if (!check_for_column_name_collision(rel, colDef->colname, if_not_exists))
    7379              :     {
    7380           44 :         table_close(attrdesc, RowExclusiveLock);
    7381           44 :         return InvalidObjectAddress;
    7382              :     }
    7383              : 
    7384              :     /*
    7385              :      * Okay, we need to add the column, so go ahead and do parse
    7386              :      * transformation.  This can result in queueing up, or even immediately
    7387              :      * executing, subsidiary operations (such as creation of unique indexes);
    7388              :      * so we mustn't do it until we have made the if_not_exists check.
    7389              :      *
    7390              :      * When recursing, the command was already transformed and we needn't do
    7391              :      * so again.  Also, if context isn't given we can't transform.  (That
    7392              :      * currently happens only for AT_AddColumnToView; we expect that view.c
    7393              :      * passed us a ColumnDef that doesn't need work.)
    7394              :      */
    7395         1947 :     if (context != NULL && !recursing)
    7396              :     {
    7397         1476 :         *cmd = ATParseTransformCmd(wqueue, tab, rel, *cmd, recurse, lockmode,
    7398              :                                    cur_pass, context);
    7399              :         Assert(*cmd != NULL);
    7400         1472 :         colDef = castNode(ColumnDef, (*cmd)->def);
    7401              :     }
    7402              : 
    7403              :     /*
    7404              :      * Regular inheritance children are independent enough not to inherit the
    7405              :      * identity column from parent hence cannot recursively add identity
    7406              :      * column if the table has inheritance children.
    7407              :      *
    7408              :      * Partitions, on the other hand, are integral part of a partitioned table
    7409              :      * and inherit identity column.  Hence propagate identity column down the
    7410              :      * partition hierarchy.
    7411              :      */
    7412         1943 :     if (colDef->identity &&
    7413           36 :         recurse &&
    7414           68 :         rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE &&
    7415           32 :         find_inheritance_children(myrelid, NoLock) != NIL)
    7416            4 :         ereport(ERROR,
    7417              :                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    7418              :                  errmsg("cannot recursively add identity column to table that has child tables")));
    7419              : 
    7420         1939 :     pgclass = table_open(RelationRelationId, RowExclusiveLock);
    7421              : 
    7422         1939 :     reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
    7423         1939 :     if (!HeapTupleIsValid(reltup))
    7424            0 :         elog(ERROR, "cache lookup failed for relation %u", myrelid);
    7425         1939 :     relform = (Form_pg_class) GETSTRUCT(reltup);
    7426         1939 :     relkind = relform->relkind;
    7427              : 
    7428              :     /* Determine the new attribute's number */
    7429         1939 :     newattnum = relform->relnatts + 1;
    7430         1939 :     if (newattnum > MaxHeapAttributeNumber)
    7431            0 :         ereport(ERROR,
    7432              :                 (errcode(ERRCODE_TOO_MANY_COLUMNS),
    7433              :                  errmsg("tables can have at most %d columns",
    7434              :                         MaxHeapAttributeNumber)));
    7435              : 
    7436              :     /*
    7437              :      * Construct new attribute's pg_attribute entry.
    7438              :      */
    7439         1939 :     tupdesc = BuildDescForRelation(list_make1(colDef));
    7440              : 
    7441         1931 :     attribute = TupleDescAttr(tupdesc, 0);
    7442              : 
    7443              :     /* Fix up attribute number */
    7444         1931 :     attribute->attnum = newattnum;
    7445              : 
    7446              :     /* make sure datatype is legal for a column */
    7447         3862 :     CheckAttributeType(NameStr(attribute->attname), attribute->atttypid, attribute->attcollation,
    7448         1931 :                        list_make1_oid(rel->rd_rel->reltype),
    7449         1931 :                        (attribute->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL ? CHKATYPE_IS_VIRTUAL : 0));
    7450              : 
    7451         1903 :     InsertPgAttributeTuples(attrdesc, tupdesc, myrelid, NULL, NULL);
    7452              : 
    7453         1903 :     table_close(attrdesc, RowExclusiveLock);
    7454              : 
    7455              :     /*
    7456              :      * Update pg_class tuple as appropriate
    7457              :      */
    7458         1903 :     relform->relnatts = newattnum;
    7459              : 
    7460         1903 :     CatalogTupleUpdate(pgclass, &reltup->t_self, reltup);
    7461              : 
    7462         1903 :     heap_freetuple(reltup);
    7463              : 
    7464              :     /* Post creation hook for new attribute */
    7465         1903 :     InvokeObjectPostCreateHook(RelationRelationId, myrelid, newattnum);
    7466              : 
    7467         1903 :     table_close(pgclass, RowExclusiveLock);
    7468              : 
    7469              :     /* Make the attribute's catalog entry visible */
    7470         1903 :     CommandCounterIncrement();
    7471              : 
    7472              :     /*
    7473              :      * Store the DEFAULT, if any, in the catalogs
    7474              :      */
    7475         1903 :     if (colDef->raw_default)
    7476              :     {
    7477              :         RawColumnDefault *rawEnt;
    7478              : 
    7479          705 :         rawEnt = palloc_object(RawColumnDefault);
    7480          705 :         rawEnt->attnum = attribute->attnum;
    7481          705 :         rawEnt->raw_default = copyObject(colDef->raw_default);
    7482          705 :         rawEnt->generated = colDef->generated;
    7483              : 
    7484              :         /*
    7485              :          * This function is intended for CREATE TABLE, so it processes a
    7486              :          * _list_ of defaults, but we just do one.
    7487              :          */
    7488          705 :         AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
    7489              :                                   false, true, false, NULL);
    7490              : 
    7491              :         /* Make the additional catalog changes visible */
    7492          617 :         CommandCounterIncrement();
    7493              :     }
    7494              : 
    7495              :     /*
    7496              :      * Tell Phase 3 to fill in the default expression, if there is one.
    7497              :      *
    7498              :      * If there is no default, Phase 3 doesn't have to do anything, because
    7499              :      * that effectively means that the default is NULL.  The heap tuple access
    7500              :      * routines always check for attnum > # of attributes in tuple, and return
    7501              :      * NULL if so, so without any modification of the tuple data we will get
    7502              :      * the effect of NULL values in the new column.
    7503              :      *
    7504              :      * Note: we use build_column_default, and not just the cooked default
    7505              :      * returned by AddRelationNewConstraints, so that the right thing happens
    7506              :      * when a datatype's default applies.
    7507              :      *
    7508              :      * Note: it might seem that this should happen at the end of Phase 2, so
    7509              :      * that the effects of subsequent subcommands can be taken into account.
    7510              :      * It's intentional that we do it now, though.  The new column should be
    7511              :      * filled according to what is said in the ADD COLUMN subcommand, so that
    7512              :      * the effects are the same as if this subcommand had been run by itself
    7513              :      * and the later subcommands had been issued in new ALTER TABLE commands.
    7514              :      *
    7515              :      * We can skip this entirely for relations without storage, since Phase 3
    7516              :      * is certainly not going to touch them.
    7517              :      */
    7518         1815 :     if (RELKIND_HAS_STORAGE(relkind))
    7519              :     {
    7520              :         bool        has_domain_constraints;
    7521         1557 :         bool        has_missing = false;
    7522         1557 :         bool        has_volatile = false;
    7523              : 
    7524              :         /*
    7525              :          * For an identity column, we can't use build_column_default(),
    7526              :          * because the sequence ownership isn't set yet.  So do it manually.
    7527              :          */
    7528         1557 :         if (colDef->identity)
    7529              :         {
    7530           28 :             NextValueExpr *nve = makeNode(NextValueExpr);
    7531              : 
    7532           28 :             nve->seqid = RangeVarGetRelid(colDef->identitySequence, NoLock, false);
    7533           28 :             nve->typeId = attribute->atttypid;
    7534              : 
    7535           28 :             defval = (Expr *) nve;
    7536              :         }
    7537              :         else
    7538         1529 :             defval = (Expr *) build_column_default(rel, attribute->attnum);
    7539              : 
    7540              :         has_domain_constraints =
    7541         1557 :             DomainHasConstraints(attribute->atttypid, &has_volatile);
    7542              : 
    7543              :         /*
    7544              :          * If the domain has volatile constraints, we must do a table rewrite
    7545              :          * since the constraint result could differ per row and cannot be
    7546              :          * evaluated once and cached as a missing value.
    7547              :          */
    7548         1557 :         if (has_volatile)
    7549           12 :             tab->rewrite |= AT_REWRITE_DEFAULT_VAL;
    7550              : 
    7551              :         /* Build CoerceToDomain(NULL) expression if needed */
    7552         1557 :         if (!defval && has_domain_constraints)
    7553              :         {
    7554              :             Oid         baseTypeId;
    7555              :             int32       baseTypeMod;
    7556              :             Oid         baseTypeColl;
    7557              : 
    7558           12 :             baseTypeMod = attribute->atttypmod;
    7559           12 :             baseTypeId = getBaseTypeAndTypmod(attribute->atttypid, &baseTypeMod);
    7560           12 :             baseTypeColl = get_typcollation(baseTypeId);
    7561           12 :             defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod, baseTypeColl);
    7562           12 :             defval = (Expr *) coerce_to_target_type(NULL,
    7563              :                                                     (Node *) defval,
    7564              :                                                     baseTypeId,
    7565              :                                                     attribute->atttypid,
    7566              :                                                     attribute->atttypmod,
    7567              :                                                     COERCION_ASSIGNMENT,
    7568              :                                                     COERCE_IMPLICIT_CAST,
    7569              :                                                     -1);
    7570           12 :             if (defval == NULL) /* should not happen */
    7571            0 :                 elog(ERROR, "failed to coerce base type to domain");
    7572              :         }
    7573              : 
    7574         1557 :         if (defval)
    7575              :         {
    7576              :             NewColumnValue *newval;
    7577              : 
    7578              :             /* Prepare defval for execution, either here or in Phase 3 */
    7579          586 :             defval = expression_planner(defval);
    7580              : 
    7581              :             /* Add the new default to the newvals list */
    7582          586 :             newval = palloc0_object(NewColumnValue);
    7583          586 :             newval->attnum = attribute->attnum;
    7584          586 :             newval->expr = defval;
    7585          586 :             newval->is_generated = (colDef->generated != '\0');
    7586              : 
    7587          586 :             tab->newvals = lappend(tab->newvals, newval);
    7588              : 
    7589              :             /*
    7590              :              * Attempt to skip a complete table rewrite by storing the
    7591              :              * specified DEFAULT value outside of the heap.  This is only
    7592              :              * allowed for plain relations and non-generated columns, and the
    7593              :              * default expression can't be volatile (stable is OK), and the
    7594              :              * domain constraint expressions can't be volatile (stable is OK).
    7595              :              *
    7596              :              * Note that contain_volatile_functions considers CoerceToDomain
    7597              :              * immutable, so we rely on DomainHasConstraints (called above)
    7598              :              * rather than checking defval alone.
    7599              :              *
    7600              :              * For domains with non-volatile constraints, we evaluate the
    7601              :              * default using soft error handling: if the constraint check
    7602              :              * fails (e.g., CHECK(value > 10) with DEFAULT 8), we fall back to
    7603              :              * a table rewrite.  This preserves the historical behavior that
    7604              :              * such a failure is only raised when the table has rows.
    7605              :              */
    7606          586 :             if (rel->rd_rel->relkind == RELKIND_RELATION &&
    7607          586 :                 !colDef->generated &&
    7608          493 :                 !has_volatile &&
    7609          481 :                 !contain_volatile_functions((Node *) defval))
    7610          367 :             {
    7611              :                 EState     *estate;
    7612              :                 ExprState  *exprState;
    7613              :                 Datum       missingval;
    7614              :                 bool        missingIsNull;
    7615          367 :                 ErrorSaveContext escontext = {T_ErrorSaveContext};
    7616              : 
    7617              :                 /* Evaluate the default expression with soft errors */
    7618          367 :                 estate = CreateExecutorState();
    7619          367 :                 exprState = ExecPrepareExprWithContext(defval, estate,
    7620              :                                                        (Node *) &escontext);
    7621          367 :                 missingval = ExecEvalExpr(exprState,
    7622          367 :                                           GetPerTupleExprContext(estate),
    7623              :                                           &missingIsNull);
    7624              : 
    7625              :                 /*
    7626              :                  * If the domain constraint check failed (via errsave),
    7627              :                  * missingval is unreliable.  Fall back to a table rewrite;
    7628              :                  * Phase 3 will re-evaluate with hard errors, so the user gets
    7629              :                  * an error only if the table has rows.
    7630              :                  */
    7631          367 :                 if (escontext.error_occurred)
    7632              :                 {
    7633           24 :                     missingIsNull = true;
    7634           24 :                     tab->rewrite |= AT_REWRITE_DEFAULT_VAL;
    7635              :                 }
    7636              : 
    7637              :                 /* If it turns out NULL, nothing to do; else store it */
    7638          367 :                 if (!missingIsNull)
    7639              :                 {
    7640          343 :                     StoreAttrMissingVal(rel, attribute->attnum, missingval);
    7641              :                     /* Make the additional catalog change visible */
    7642          343 :                     CommandCounterIncrement();
    7643          343 :                     has_missing = true;
    7644              :                 }
    7645          367 :                 FreeExecutorState(estate);
    7646              :             }
    7647              :             else
    7648              :             {
    7649              :                 /*
    7650              :                  * Failed to use missing mode.  We have to do a table rewrite
    7651              :                  * to install the value --- unless it's a virtual generated
    7652              :                  * column.
    7653              :                  */
    7654          219 :                 if (colDef->generated != ATTRIBUTE_GENERATED_VIRTUAL)
    7655          150 :                     tab->rewrite |= AT_REWRITE_DEFAULT_VAL;
    7656              :             }
    7657              :         }
    7658              : 
    7659         1557 :         if (!has_missing)
    7660              :         {
    7661              :             /*
    7662              :              * If the new column is NOT NULL, and there is no missing value,
    7663              :              * tell Phase 3 it needs to check for NULLs.
    7664              :              */
    7665         1214 :             tab->verify_new_notnull |= colDef->is_not_null;
    7666              :         }
    7667              :     }
    7668              : 
    7669              :     /*
    7670              :      * Add needed dependency entries for the new column.
    7671              :      */
    7672         1815 :     add_column_datatype_dependency(myrelid, newattnum, attribute->atttypid);
    7673         1815 :     add_column_collation_dependency(myrelid, newattnum, attribute->attcollation);
    7674              : 
    7675              :     /*
    7676              :      * Propagate to children as appropriate.  Unlike most other ALTER
    7677              :      * routines, we have to do this one level of recursion at a time; we can't
    7678              :      * use find_all_inheritors to do it in one pass.
    7679              :      */
    7680              :     children =
    7681         1815 :         find_inheritance_children(RelationGetRelid(rel), lockmode);
    7682              : 
    7683              :     /*
    7684              :      * If we are told not to recurse, there had better not be any child
    7685              :      * tables; else the addition would put them out of step.
    7686              :      */
    7687         1815 :     if (children && !recurse)
    7688            8 :         ereport(ERROR,
    7689              :                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    7690              :                  errmsg("column must be added to child tables too")));
    7691              : 
    7692              :     /* Children should see column as singly inherited */
    7693         1807 :     if (!recursing)
    7694              :     {
    7695         1357 :         childcmd = copyObject(*cmd);
    7696         1357 :         colDef = castNode(ColumnDef, childcmd->def);
    7697         1357 :         colDef->inhcount = 1;
    7698         1357 :         colDef->is_local = false;
    7699              :     }
    7700              :     else
    7701          450 :         childcmd = *cmd;        /* no need to copy again */
    7702              : 
    7703         2297 :     foreach(child, children)
    7704              :     {
    7705          490 :         Oid         childrelid = lfirst_oid(child);
    7706              :         Relation    childrel;
    7707              :         AlteredTableInfo *childtab;
    7708              : 
    7709              :         /* find_inheritance_children already got lock */
    7710          490 :         childrel = table_open(childrelid, NoLock);
    7711          490 :         CheckAlterTableIsSafe(childrel);
    7712              : 
    7713              :         /* Find or create work queue entry for this table */
    7714          490 :         childtab = ATGetQueueEntry(wqueue, childrel);
    7715              : 
    7716              :         /* Recurse to child; return value is ignored */
    7717          490 :         ATExecAddColumn(wqueue, childtab, childrel,
    7718              :                         &childcmd, recurse, true,
    7719              :                         lockmode, cur_pass, context);
    7720              : 
    7721          490 :         table_close(childrel, NoLock);
    7722              :     }
    7723              : 
    7724         1807 :     ObjectAddressSubSet(address, RelationRelationId, myrelid, newattnum);
    7725         1807 :     return address;
    7726              : }
    7727              : 
    7728              : /*
    7729              :  * If a new or renamed column will collide with the name of an existing
    7730              :  * column and if_not_exists is false then error out, else do nothing.
    7731              :  */
    7732              : static bool
    7733         2309 : check_for_column_name_collision(Relation rel, const char *colname,
    7734              :                                 bool if_not_exists)
    7735              : {
    7736              :     HeapTuple   attTuple;
    7737              :     int         attnum;
    7738              : 
    7739              :     /*
    7740              :      * this test is deliberately not attisdropped-aware, since if one tries to
    7741              :      * add a column matching a dropped column name, it's gonna fail anyway.
    7742              :      */
    7743         2309 :     attTuple = SearchSysCache2(ATTNAME,
    7744              :                                ObjectIdGetDatum(RelationGetRelid(rel)),
    7745              :                                PointerGetDatum(colname));
    7746         2309 :     if (!HeapTupleIsValid(attTuple))
    7747         2237 :         return true;
    7748              : 
    7749           72 :     attnum = ((Form_pg_attribute) GETSTRUCT(attTuple))->attnum;
    7750           72 :     ReleaseSysCache(attTuple);
    7751              : 
    7752              :     /*
    7753              :      * We throw a different error message for conflicts with system column
    7754              :      * names, since they are normally not shown and the user might otherwise
    7755              :      * be confused about the reason for the conflict.
    7756              :      */
    7757           72 :     if (attnum <= 0)
    7758            8 :         ereport(ERROR,
    7759              :                 (errcode(ERRCODE_DUPLICATE_COLUMN),
    7760              :                  errmsg("column name \"%s\" conflicts with a system column name",
    7761              :                         colname)));
    7762              :     else
    7763              :     {
    7764           64 :         if (if_not_exists)
    7765              :         {
    7766           44 :             ereport(NOTICE,
    7767              :                     (errcode(ERRCODE_DUPLICATE_COLUMN),
    7768              :                      errmsg("column \"%s\" of relation \"%s\" already exists, skipping",
    7769              :                             colname, RelationGetRelationName(rel))));
    7770           44 :             return false;
    7771              :         }
    7772              : 
    7773           20 :         ereport(ERROR,
    7774              :                 (errcode(ERRCODE_DUPLICATE_COLUMN),
    7775              :                  errmsg("column \"%s\" of relation \"%s\" already exists",
    7776              :                         colname, RelationGetRelationName(rel))));
    7777              :     }
    7778              : 
    7779              :     return true;
    7780              : }
    7781              : 
    7782              : /*
    7783              :  * Install a column's dependency on its datatype.
    7784              :  */
    7785              : static void
    7786         2568 : add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
    7787              : {
    7788              :     ObjectAddress myself,
    7789              :                 referenced;
    7790              : 
    7791         2568 :     myself.classId = RelationRelationId;
    7792         2568 :     myself.objectId = relid;
    7793         2568 :     myself.objectSubId = attnum;
    7794         2568 :     referenced.classId = TypeRelationId;
    7795         2568 :     referenced.objectId = typid;
    7796         2568 :     referenced.objectSubId = 0;
    7797         2568 :     recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
    7798         2568 : }
    7799              : 
    7800              : /*
    7801              :  * Install a column's dependency on its collation.
    7802              :  */
    7803              : static void
    7804         2568 : add_column_collation_dependency(Oid relid, int32 attnum, Oid collid)
    7805              : {
    7806              :     ObjectAddress myself,
    7807              :                 referenced;
    7808              : 
    7809              :     /* We know the default collation is pinned, so don't bother recording it */
    7810         2568 :     if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
    7811              :     {
    7812           12 :         myself.classId = RelationRelationId;
    7813           12 :         myself.objectId = relid;
    7814           12 :         myself.objectSubId = attnum;
    7815           12 :         referenced.classId = CollationRelationId;
    7816           12 :         referenced.objectId = collid;
    7817           12 :         referenced.objectSubId = 0;
    7818           12 :         recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
    7819              :     }
    7820         2568 : }
    7821              : 
    7822              : /*
    7823              :  * ALTER TABLE ALTER COLUMN DROP NOT NULL
    7824              :  *
    7825              :  * Return the address of the modified column.  If the column was already
    7826              :  * nullable, InvalidObjectAddress is returned.
    7827              :  */
    7828              : static ObjectAddress
    7829          177 : ATExecDropNotNull(Relation rel, const char *colName, bool recurse,
    7830              :                   LOCKMODE lockmode)
    7831              : {
    7832              :     HeapTuple   tuple;
    7833              :     HeapTuple   conTup;
    7834              :     Form_pg_attribute attTup;
    7835              :     AttrNumber  attnum;
    7836              :     Relation    attr_rel;
    7837              :     ObjectAddress address;
    7838              : 
    7839              :     /*
    7840              :      * lookup the attribute
    7841              :      */
    7842          177 :     attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
    7843              : 
    7844          177 :     tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
    7845          177 :     if (!HeapTupleIsValid(tuple))
    7846           12 :         ereport(ERROR,
    7847              :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    7848              :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
    7849              :                         colName, RelationGetRelationName(rel))));
    7850          165 :     attTup = (Form_pg_attribute) GETSTRUCT(tuple);
    7851          165 :     attnum = attTup->attnum;
    7852          165 :     ObjectAddressSubSet(address, RelationRelationId,
    7853              :                         RelationGetRelid(rel), attnum);
    7854              : 
    7855              :     /* If the column is already nullable there's nothing to do. */
    7856          165 :     if (!attTup->attnotnull)
    7857              :     {
    7858            0 :         table_close(attr_rel, RowExclusiveLock);
    7859            0 :         return InvalidObjectAddress;
    7860              :     }
    7861              : 
    7862              :     /* Prevent them from altering a system attribute */
    7863          165 :     if (attnum <= 0)
    7864            0 :         ereport(ERROR,
    7865              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    7866              :                  errmsg("cannot alter system column \"%s\"",
    7867              :                         colName)));
    7868              : 
    7869          165 :     if (attTup->attidentity)
    7870           12 :         ereport(ERROR,
    7871              :                 (errcode(ERRCODE_SYNTAX_ERROR),
    7872              :                  errmsg("column \"%s\" of relation \"%s\" is an identity column",
    7873              :                         colName, RelationGetRelationName(rel))));
    7874              : 
    7875              :     /*
    7876              :      * If rel is partition, shouldn't drop NOT NULL if parent has the same.
    7877              :      */
    7878          153 :     if (rel->rd_rel->relispartition)
    7879              :     {
    7880            8 :         Oid         parentId = get_partition_parent(RelationGetRelid(rel), false);
    7881            8 :         Relation    parent = table_open(parentId, AccessShareLock);
    7882            8 :         TupleDesc   tupDesc = RelationGetDescr(parent);
    7883              :         AttrNumber  parent_attnum;
    7884              : 
    7885            8 :         parent_attnum = get_attnum(parentId, colName);
    7886            8 :         if (TupleDescAttr(tupDesc, parent_attnum - 1)->attnotnull)
    7887            8 :             ereport(ERROR,
    7888              :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    7889              :                      errmsg("column \"%s\" is marked NOT NULL in parent table",
    7890              :                             colName)));
    7891            0 :         table_close(parent, AccessShareLock);
    7892              :     }
    7893              : 
    7894              :     /*
    7895              :      * Find the constraint that makes this column NOT NULL, and drop it.
    7896              :      * dropconstraint_internal() resets attnotnull.
    7897              :      */
    7898          145 :     conTup = findNotNullConstraintAttnum(RelationGetRelid(rel), attnum);
    7899          145 :     if (conTup == NULL)
    7900            0 :         elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation \"%s\"",
    7901              :              colName, RelationGetRelationName(rel));
    7902              : 
    7903              :     /* The normal case: we have a pg_constraint row, remove it */
    7904          145 :     dropconstraint_internal(rel, conTup, DROP_RESTRICT, recurse, false,
    7905              :                             false, lockmode);
    7906          109 :     heap_freetuple(conTup);
    7907              : 
    7908          109 :     InvokeObjectPostAlterHook(RelationRelationId,
    7909              :                               RelationGetRelid(rel), attnum);
    7910              : 
    7911          109 :     table_close(attr_rel, RowExclusiveLock);
    7912              : 
    7913          109 :     return address;
    7914              : }
    7915              : 
    7916              : /*
    7917              :  * set_attnotnull
    7918              :  *      Helper to update/validate the pg_attribute status of a not-null
    7919              :  *      constraint
    7920              :  *
    7921              :  * pg_attribute.attnotnull is set true, if it isn't already.
    7922              :  * If queue_validation is true, also set up wqueue to validate the constraint.
    7923              :  * wqueue may be given as NULL when validation is not needed (e.g., on table
    7924              :  * creation).
    7925              :  */
    7926              : static void
    7927        15209 : set_attnotnull(List **wqueue, Relation rel, AttrNumber attnum,
    7928              :                bool is_valid, bool queue_validation)
    7929              : {
    7930              :     Form_pg_attribute attr;
    7931              :     CompactAttribute *thisatt;
    7932              : 
    7933              :     Assert(!queue_validation || wqueue);
    7934              : 
    7935        15209 :     CheckAlterTableIsSafe(rel);
    7936              : 
    7937              :     /*
    7938              :      * Exit quickly by testing attnotnull from the tupledesc's copy of the
    7939              :      * attribute.
    7940              :      */
    7941        15209 :     attr = TupleDescAttr(RelationGetDescr(rel), attnum - 1);
    7942        15209 :     if (attr->attisdropped)
    7943            0 :         return;
    7944              : 
    7945        15209 :     if (!attr->attnotnull)
    7946              :     {
    7947              :         Relation    attr_rel;
    7948              :         HeapTuple   tuple;
    7949              : 
    7950          975 :         attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
    7951              : 
    7952          975 :         tuple = SearchSysCacheCopyAttNum(RelationGetRelid(rel), attnum);
    7953          975 :         if (!HeapTupleIsValid(tuple))
    7954            0 :             elog(ERROR, "cache lookup failed for attribute %d of relation %u",
    7955              :                  attnum, RelationGetRelid(rel));
    7956              : 
    7957          975 :         thisatt = TupleDescCompactAttr(RelationGetDescr(rel), attnum - 1);
    7958          975 :         thisatt->attnullability = ATTNULLABLE_VALID;
    7959              : 
    7960          975 :         attr = (Form_pg_attribute) GETSTRUCT(tuple);
    7961              : 
    7962          975 :         attr->attnotnull = true;
    7963          975 :         CatalogTupleUpdate(attr_rel, &tuple->t_self, tuple);
    7964              : 
    7965              :         /*
    7966              :          * If the nullness isn't already proven by validated constraints, have
    7967              :          * ALTER TABLE phase 3 test for it.
    7968              :          */
    7969          975 :         if (queue_validation && wqueue &&
    7970          812 :             !NotNullImpliedByRelConstraints(rel, attr))
    7971              :         {
    7972              :             AlteredTableInfo *tab;
    7973              : 
    7974          780 :             tab = ATGetQueueEntry(wqueue, rel);
    7975          780 :             tab->verify_new_notnull = true;
    7976              :         }
    7977              : 
    7978          975 :         CommandCounterIncrement();
    7979              : 
    7980          975 :         table_close(attr_rel, RowExclusiveLock);
    7981          975 :         heap_freetuple(tuple);
    7982              :     }
    7983              :     else
    7984              :     {
    7985        14234 :         CacheInvalidateRelcache(rel);
    7986              :     }
    7987              : }
    7988              : 
    7989              : /*
    7990              :  * ALTER TABLE ALTER COLUMN SET NOT NULL
    7991              :  *
    7992              :  * Add a not-null constraint to a single table and its children.  Returns
    7993              :  * the address of the constraint added to the parent relation, if one gets
    7994              :  * added, or InvalidObjectAddress otherwise.
    7995              :  *
    7996              :  * We must recurse to child tables during execution, rather than using
    7997              :  * ALTER TABLE's normal prep-time recursion.
    7998              :  */
    7999              : static ObjectAddress
    8000          469 : ATExecSetNotNull(List **wqueue, Relation rel, char *conName, char *colName,
    8001              :                  bool recurse, bool recursing, LOCKMODE lockmode)
    8002              : {
    8003              :     HeapTuple   tuple;
    8004              :     AttrNumber  attnum;
    8005              :     ObjectAddress address;
    8006              :     Constraint *constraint;
    8007              :     CookedConstraint *ccon;
    8008              :     List       *cooked;
    8009          469 :     bool        is_no_inherit = false;
    8010              : 
    8011              :     /* Guard against stack overflow due to overly deep inheritance tree. */
    8012          469 :     check_stack_depth();
    8013              : 
    8014              :     /* At top level, permission check was done in ATPrepCmd, else do it */
    8015          469 :     if (recursing)
    8016              :     {
    8017          197 :         ATSimplePermissions(AT_AddConstraint, rel,
    8018              :                             ATT_PARTITIONED_TABLE | ATT_TABLE | ATT_FOREIGN_TABLE);
    8019              :         Assert(conName != NULL);
    8020              :     }
    8021              : 
    8022          469 :     attnum = get_attnum(RelationGetRelid(rel), colName);
    8023          469 :     if (attnum == InvalidAttrNumber)
    8024           12 :         ereport(ERROR,
    8025              :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    8026              :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
    8027              :                         colName, RelationGetRelationName(rel))));
    8028              : 
    8029              :     /* Prevent them from altering a system attribute */
    8030          457 :     if (attnum <= 0)
    8031            0 :         ereport(ERROR,
    8032              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    8033              :                  errmsg("cannot alter system column \"%s\"",
    8034              :                         colName)));
    8035              : 
    8036              :     /* See if there's already a constraint */
    8037          457 :     tuple = findNotNullConstraintAttnum(RelationGetRelid(rel), attnum);
    8038          457 :     if (HeapTupleIsValid(tuple))
    8039              :     {
    8040          105 :         Form_pg_constraint conForm = (Form_pg_constraint) GETSTRUCT(tuple);
    8041          105 :         bool        changed = false;
    8042              : 
    8043              :         /*
    8044              :          * Don't let a NO INHERIT constraint be changed into inherit.
    8045              :          */
    8046          105 :         if (conForm->connoinherit && recurse)
    8047            8 :             ereport(ERROR,
    8048              :                     errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    8049              :                     errmsg("cannot change NO INHERIT status of NOT NULL constraint \"%s\" on relation \"%s\"",
    8050              :                            NameStr(conForm->conname),
    8051              :                            RelationGetRelationName(rel)));
    8052              : 
    8053              :         /*
    8054              :          * If we find an appropriate constraint, we're almost done, but just
    8055              :          * need to change some properties on it: if we're recursing, increment
    8056              :          * coninhcount; if not, set conislocal if not already set.
    8057              :          */
    8058           97 :         if (recursing)
    8059              :         {
    8060           68 :             if (pg_add_s16_overflow(conForm->coninhcount, 1,
    8061              :                                     &conForm->coninhcount))
    8062            0 :                 ereport(ERROR,
    8063              :                         errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    8064              :                         errmsg("too many inheritance parents"));
    8065           68 :             changed = true;
    8066              :         }
    8067           29 :         else if (!conForm->conislocal)
    8068              :         {
    8069            0 :             conForm->conislocal = true;
    8070            0 :             changed = true;
    8071              :         }
    8072           29 :         else if (!conForm->convalidated)
    8073              :         {
    8074              :             /*
    8075              :              * Flip attnotnull and convalidated, and also validate the
    8076              :              * constraint.
    8077              :              */
    8078           16 :             return ATExecValidateConstraint(wqueue, rel, NameStr(conForm->conname),
    8079              :                                             recurse, recursing, lockmode);
    8080              :         }
    8081              : 
    8082           81 :         if (changed)
    8083              :         {
    8084              :             Relation    constr_rel;
    8085              : 
    8086           68 :             constr_rel = table_open(ConstraintRelationId, RowExclusiveLock);
    8087              : 
    8088           68 :             CatalogTupleUpdate(constr_rel, &tuple->t_self, tuple);
    8089           68 :             ObjectAddressSet(address, ConstraintRelationId, conForm->oid);
    8090           68 :             table_close(constr_rel, RowExclusiveLock);
    8091              :         }
    8092              : 
    8093           81 :         if (changed)
    8094           68 :             return address;
    8095              :         else
    8096           13 :             return InvalidObjectAddress;
    8097              :     }
    8098              : 
    8099              :     /*
    8100              :      * If we're asked not to recurse, and children exist, raise an error for
    8101              :      * partitioned tables.  For inheritance, we act as if NO INHERIT had been
    8102              :      * specified.
    8103              :      */
    8104          372 :     if (!recurse &&
    8105           20 :         find_inheritance_children(RelationGetRelid(rel),
    8106              :                                   NoLock) != NIL)
    8107              :     {
    8108           12 :         if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
    8109            4 :             ereport(ERROR,
    8110              :                     errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    8111              :                     errmsg("constraint must be added to child tables too"),
    8112              :                     errhint("Do not specify the ONLY keyword."));
    8113              :         else
    8114            8 :             is_no_inherit = true;
    8115              :     }
    8116              : 
    8117              :     /*
    8118              :      * No constraint exists; we must add one.  First determine a name to use,
    8119              :      * if we haven't already.
    8120              :      */
    8121          348 :     if (!recursing)
    8122              :     {
    8123              :         Assert(conName == NULL);
    8124          223 :         conName = ChooseConstraintName(RelationGetRelationName(rel),
    8125              :                                        colName, "not_null",
    8126          223 :                                        RelationGetNamespace(rel),
    8127              :                                        NIL);
    8128              :     }
    8129              : 
    8130          348 :     constraint = makeNotNullConstraint(makeString(colName));
    8131          348 :     constraint->is_no_inherit = is_no_inherit;
    8132          348 :     constraint->conname = conName;
    8133              : 
    8134              :     /* and do it */
    8135          348 :     cooked = AddRelationNewConstraints(rel, NIL, list_make1(constraint),
    8136          348 :                                        false, !recursing, false, NULL);
    8137          348 :     ccon = linitial(cooked);
    8138          348 :     ObjectAddressSet(address, ConstraintRelationId, ccon->conoid);
    8139              : 
    8140              :     /* Mark pg_attribute.attnotnull for the column and queue validation */
    8141          348 :     set_attnotnull(wqueue, rel, attnum, true, true);
    8142              : 
    8143          348 :     InvokeObjectPostAlterHook(RelationRelationId,
    8144              :                               RelationGetRelid(rel), attnum);
    8145              : 
    8146              :     /*
    8147              :      * Recurse to propagate the constraint to children that don't have one.
    8148              :      */
    8149          348 :     if (recurse)
    8150              :     {
    8151              :         List       *children;
    8152              : 
    8153          332 :         children = find_inheritance_children(RelationGetRelid(rel),
    8154              :                                              lockmode);
    8155              : 
    8156          817 :         foreach_oid(childoid, children)
    8157              :         {
    8158          161 :             Relation    childrel = table_open(childoid, NoLock);
    8159              : 
    8160          161 :             CommandCounterIncrement();
    8161              : 
    8162          161 :             ATExecSetNotNull(wqueue, childrel, conName, colName,
    8163              :                              recurse, true, lockmode);
    8164          157 :             table_close(childrel, NoLock);
    8165              :         }
    8166              :     }
    8167              : 
    8168          344 :     return address;
    8169              : }
    8170              : 
    8171              : /*
    8172              :  * NotNullImpliedByRelConstraints
    8173              :  *      Does rel's existing constraints imply NOT NULL for the given attribute?
    8174              :  */
    8175              : static bool
    8176          812 : NotNullImpliedByRelConstraints(Relation rel, Form_pg_attribute attr)
    8177              : {
    8178          812 :     NullTest   *nnulltest = makeNode(NullTest);
    8179              : 
    8180         1624 :     nnulltest->arg = (Expr *) makeVar(1,
    8181          812 :                                       attr->attnum,
    8182              :                                       attr->atttypid,
    8183              :                                       attr->atttypmod,
    8184              :                                       attr->attcollation,
    8185              :                                       0);
    8186          812 :     nnulltest->nulltesttype = IS_NOT_NULL;
    8187              : 
    8188              :     /*
    8189              :      * argisrow = false is correct even for a composite column, because
    8190              :      * attnotnull does not represent a SQL-spec IS NOT NULL test in such a
    8191              :      * case, just IS DISTINCT FROM NULL.
    8192              :      */
    8193          812 :     nnulltest->argisrow = false;
    8194          812 :     nnulltest->location = -1;
    8195              : 
    8196          812 :     if (ConstraintImpliedByRelConstraint(rel, list_make1(nnulltest), NIL))
    8197              :     {
    8198           32 :         ereport(DEBUG1,
    8199              :                 (errmsg_internal("existing constraints on column \"%s.%s\" are sufficient to prove that it does not contain nulls",
    8200              :                                  RelationGetRelationName(rel), NameStr(attr->attname))));
    8201           32 :         return true;
    8202              :     }
    8203              : 
    8204          780 :     return false;
    8205              : }
    8206              : 
    8207              : /*
    8208              :  * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
    8209              :  *
    8210              :  * Return the address of the affected column.
    8211              :  */
    8212              : static ObjectAddress
    8213          383 : ATExecColumnDefault(Relation rel, const char *colName,
    8214              :                     Node *newDefault, LOCKMODE lockmode)
    8215              : {
    8216          383 :     TupleDesc   tupdesc = RelationGetDescr(rel);
    8217              :     AttrNumber  attnum;
    8218              :     ObjectAddress address;
    8219              : 
    8220              :     /*
    8221              :      * get the number of the attribute
    8222              :      */
    8223          383 :     attnum = get_attnum(RelationGetRelid(rel), colName);
    8224          383 :     if (attnum == InvalidAttrNumber)
    8225           20 :         ereport(ERROR,
    8226              :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    8227              :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
    8228              :                         colName, RelationGetRelationName(rel))));
    8229              : 
    8230              :     /* Prevent them from altering a system attribute */
    8231          363 :     if (attnum <= 0)
    8232            0 :         ereport(ERROR,
    8233              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    8234              :                  errmsg("cannot alter system column \"%s\"",
    8235              :                         colName)));
    8236              : 
    8237          363 :     if (TupleDescAttr(tupdesc, attnum - 1)->attidentity)
    8238           12 :         ereport(ERROR,
    8239              :                 (errcode(ERRCODE_SYNTAX_ERROR),
    8240              :                  errmsg("column \"%s\" of relation \"%s\" is an identity column",
    8241              :                         colName, RelationGetRelationName(rel)),
    8242              :         /* translator: %s is an SQL ALTER command */
    8243              :                  newDefault ? 0 : errhint("Use %s instead.",
    8244              :                                           "ALTER TABLE ... ALTER COLUMN ... DROP IDENTITY")));
    8245              : 
    8246          351 :     if (TupleDescAttr(tupdesc, attnum - 1)->attgenerated)
    8247            8 :         ereport(ERROR,
    8248              :                 (errcode(ERRCODE_SYNTAX_ERROR),
    8249              :                  errmsg("column \"%s\" of relation \"%s\" is a generated column",
    8250              :                         colName, RelationGetRelationName(rel)),
    8251              :                  newDefault ?
    8252              :         /* translator: %s is an SQL ALTER command */
    8253              :                  errhint("Use %s instead.", "ALTER TABLE ... ALTER COLUMN ... SET EXPRESSION") :
    8254              :                  (TupleDescAttr(tupdesc, attnum - 1)->attgenerated == ATTRIBUTE_GENERATED_STORED ?
    8255              :                   errhint("Use %s instead.", "ALTER TABLE ... ALTER COLUMN ... DROP EXPRESSION") : 0)));
    8256              : 
    8257              :     /*
    8258              :      * Remove any old default for the column.  We use RESTRICT here for
    8259              :      * safety, but at present we do not expect anything to depend on the
    8260              :      * default.
    8261              :      *
    8262              :      * We treat removing the existing default as an internal operation when it
    8263              :      * is preparatory to adding a new default, but as a user-initiated
    8264              :      * operation when the user asked for a drop.
    8265              :      */
    8266          343 :     RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false,
    8267              :                       newDefault != NULL);
    8268              : 
    8269          343 :     if (newDefault)
    8270              :     {
    8271              :         /* SET DEFAULT */
    8272              :         RawColumnDefault *rawEnt;
    8273              : 
    8274          227 :         rawEnt = palloc_object(RawColumnDefault);
    8275          227 :         rawEnt->attnum = attnum;
    8276          227 :         rawEnt->raw_default = newDefault;
    8277          227 :         rawEnt->generated = '\0';
    8278              : 
    8279              :         /*
    8280              :          * This function is intended for CREATE TABLE, so it processes a
    8281              :          * _list_ of defaults, but we just do one.
    8282              :          */
    8283          227 :         AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
    8284              :                                   false, true, false, NULL);
    8285              :     }
    8286              : 
    8287          339 :     ObjectAddressSubSet(address, RelationRelationId,
    8288              :                         RelationGetRelid(rel), attnum);
    8289          339 :     return address;
    8290              : }
    8291              : 
    8292              : /*
    8293              :  * Add a pre-cooked default expression.
    8294              :  *
    8295              :  * Return the address of the affected column.
    8296              :  */
    8297              : static ObjectAddress
    8298           53 : ATExecCookedColumnDefault(Relation rel, AttrNumber attnum,
    8299              :                           Node *newDefault)
    8300              : {
    8301              :     ObjectAddress address;
    8302              : 
    8303              :     /* We assume no checking is required */
    8304              : 
    8305              :     /*
    8306              :      * Remove any old default for the column.  We use RESTRICT here for
    8307              :      * safety, but at present we do not expect anything to depend on the
    8308              :      * default.  (In ordinary cases, there could not be a default in place
    8309              :      * anyway, but it's possible when combining LIKE with inheritance.)
    8310              :      */
    8311           53 :     RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false,
    8312              :                       true);
    8313              : 
    8314           53 :     (void) StoreAttrDefault(rel, attnum, newDefault, true);
    8315              : 
    8316           53 :     ObjectAddressSubSet(address, RelationRelationId,
    8317              :                         RelationGetRelid(rel), attnum);
    8318           53 :     return address;
    8319              : }
    8320              : 
    8321              : /*
    8322              :  * ALTER TABLE ALTER COLUMN ADD IDENTITY
    8323              :  *
    8324              :  * Return the address of the affected column.
    8325              :  */
    8326              : static ObjectAddress
    8327          103 : ATExecAddIdentity(Relation rel, const char *colName,
    8328              :                   Node *def, LOCKMODE lockmode, bool recurse, bool recursing)
    8329              : {
    8330              :     Relation    attrelation;
    8331              :     HeapTuple   tuple;
    8332              :     Form_pg_attribute attTup;
    8333              :     AttrNumber  attnum;
    8334              :     ObjectAddress address;
    8335          103 :     ColumnDef  *cdef = castNode(ColumnDef, def);
    8336              :     bool        ispartitioned;
    8337              : 
    8338          103 :     ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
    8339          103 :     if (ispartitioned && !recurse)
    8340            4 :         ereport(ERROR,
    8341              :                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    8342              :                  errmsg("cannot add identity to a column of only the partitioned table"),
    8343              :                  errhint("Do not specify the ONLY keyword.")));
    8344              : 
    8345           99 :     if (rel->rd_rel->relispartition && !recursing)
    8346            8 :         ereport(ERROR,
    8347              :                 errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    8348              :                 errmsg("cannot add identity to a column of a partition"));
    8349              : 
    8350           91 :     attrelation = table_open(AttributeRelationId, RowExclusiveLock);
    8351              : 
    8352           91 :     tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
    8353           91 :     if (!HeapTupleIsValid(tuple))
    8354            0 :         ereport(ERROR,
    8355              :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    8356              :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
    8357              :                         colName, RelationGetRelationName(rel))));
    8358           91 :     attTup = (Form_pg_attribute) GETSTRUCT(tuple);
    8359           91 :     attnum = attTup->attnum;
    8360              : 
    8361              :     /* Can't alter a system attribute */
    8362           91 :     if (attnum <= 0)
    8363            0 :         ereport(ERROR,
    8364              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    8365              :                  errmsg("cannot alter system column \"%s\"",
    8366              :                         colName)));
    8367              : 
    8368              :     /*
    8369              :      * Creating a column as identity implies NOT NULL, so adding the identity
    8370              :      * to an existing column that is not NOT NULL would create a state that
    8371              :      * cannot be reproduced without contortions.
    8372              :      */
    8373           91 :     if (!attTup->attnotnull)
    8374            4 :         ereport(ERROR,
    8375              :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    8376              :                  errmsg("column \"%s\" of relation \"%s\" must be declared NOT NULL before identity can be added",
    8377              :                         colName, RelationGetRelationName(rel))));
    8378              : 
    8379              :     /*
    8380              :      * On the other hand, if a not-null constraint exists, then verify that
    8381              :      * it's compatible.
    8382              :      */
    8383           87 :     if (attTup->attnotnull)
    8384              :     {
    8385              :         HeapTuple   contup;
    8386              :         Form_pg_constraint conForm;
    8387              : 
    8388           87 :         contup = findNotNullConstraintAttnum(RelationGetRelid(rel),
    8389              :                                              attnum);
    8390           87 :         if (!HeapTupleIsValid(contup))
    8391            0 :             elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation \"%s\"",
    8392              :                  colName, RelationGetRelationName(rel));
    8393              : 
    8394           87 :         conForm = (Form_pg_constraint) GETSTRUCT(contup);
    8395           87 :         if (!conForm->convalidated)
    8396            4 :             ereport(ERROR,
    8397              :                     errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    8398              :                     errmsg("incompatible NOT VALID constraint \"%s\" on relation \"%s\"",
    8399              :                            NameStr(conForm->conname), RelationGetRelationName(rel)),
    8400              :                     errhint("You might need to validate it using %s.",
    8401              :                             "ALTER TABLE ... VALIDATE CONSTRAINT"));
    8402              :     }
    8403              : 
    8404           83 :     if (attTup->attidentity)
    8405           12 :         ereport(ERROR,
    8406              :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    8407              :                  errmsg("column \"%s\" of relation \"%s\" is already an identity column",
    8408              :                         colName, RelationGetRelationName(rel))));
    8409              : 
    8410           71 :     if (attTup->atthasdef)
    8411            4 :         ereport(ERROR,
    8412              :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    8413              :                  errmsg("column \"%s\" of relation \"%s\" already has a default value",
    8414              :                         colName, RelationGetRelationName(rel))));
    8415              : 
    8416           67 :     attTup->attidentity = cdef->identity;
    8417           67 :     CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
    8418              : 
    8419           67 :     InvokeObjectPostAlterHook(RelationRelationId,
    8420              :                               RelationGetRelid(rel),
    8421              :                               attTup->attnum);
    8422           67 :     ObjectAddressSubSet(address, RelationRelationId,
    8423              :                         RelationGetRelid(rel), attnum);
    8424           67 :     heap_freetuple(tuple);
    8425              : 
    8426           67 :     table_close(attrelation, RowExclusiveLock);
    8427              : 
    8428              :     /*
    8429              :      * Recurse to propagate the identity column to partitions.  Identity is
    8430              :      * not inherited in regular inheritance children.
    8431              :      */
    8432           67 :     if (recurse && ispartitioned)
    8433              :     {
    8434              :         List       *children;
    8435              :         ListCell   *lc;
    8436              : 
    8437            6 :         children = find_inheritance_children(RelationGetRelid(rel), lockmode);
    8438              : 
    8439           10 :         foreach(lc, children)
    8440              :         {
    8441              :             Relation    childrel;
    8442              : 
    8443            4 :             childrel = table_open(lfirst_oid(lc), NoLock);
    8444            4 :             ATExecAddIdentity(childrel, colName, def, lockmode, recurse, true);
    8445            4 :             table_close(childrel, NoLock);
    8446              :         }
    8447              :     }
    8448              : 
    8449           67 :     return address;
    8450              : }
    8451              : 
    8452              : /*
    8453              :  * ALTER TABLE ALTER COLUMN SET { GENERATED or sequence options }
    8454              :  *
    8455              :  * Return the address of the affected column.
    8456              :  */
    8457              : static ObjectAddress
    8458           49 : ATExecSetIdentity(Relation rel, const char *colName, Node *def,
    8459              :                   LOCKMODE lockmode, bool recurse, bool recursing)
    8460              : {
    8461              :     ListCell   *option;
    8462           49 :     DefElem    *generatedEl = NULL;
    8463              :     HeapTuple   tuple;
    8464              :     Form_pg_attribute attTup;
    8465              :     AttrNumber  attnum;
    8466              :     Relation    attrelation;
    8467              :     ObjectAddress address;
    8468              :     bool        ispartitioned;
    8469              : 
    8470           49 :     ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
    8471           49 :     if (ispartitioned && !recurse)
    8472            4 :         ereport(ERROR,
    8473              :                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    8474              :                  errmsg("cannot change identity column of only the partitioned table"),
    8475              :                  errhint("Do not specify the ONLY keyword.")));
    8476              : 
    8477           45 :     if (rel->rd_rel->relispartition && !recursing)
    8478            8 :         ereport(ERROR,
    8479              :                 errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    8480              :                 errmsg("cannot change identity column of a partition"));
    8481              : 
    8482           66 :     foreach(option, castNode(List, def))
    8483              :     {
    8484           29 :         DefElem    *defel = lfirst_node(DefElem, option);
    8485              : 
    8486           29 :         if (strcmp(defel->defname, "generated") == 0)
    8487              :         {
    8488           29 :             if (generatedEl)
    8489            0 :                 ereport(ERROR,
    8490              :                         (errcode(ERRCODE_SYNTAX_ERROR),
    8491              :                          errmsg("conflicting or redundant options")));
    8492           29 :             generatedEl = defel;
    8493              :         }
    8494              :         else
    8495            0 :             elog(ERROR, "option \"%s\" not recognized",
    8496              :                  defel->defname);
    8497              :     }
    8498              : 
    8499              :     /*
    8500              :      * Even if there is nothing to change here, we run all the checks.  There
    8501              :      * will be a subsequent ALTER SEQUENCE that relies on everything being
    8502              :      * there.
    8503              :      */
    8504              : 
    8505           37 :     attrelation = table_open(AttributeRelationId, RowExclusiveLock);
    8506           37 :     tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
    8507           37 :     if (!HeapTupleIsValid(tuple))
    8508            0 :         ereport(ERROR,
    8509              :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    8510              :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
    8511              :                         colName, RelationGetRelationName(rel))));
    8512              : 
    8513           37 :     attTup = (Form_pg_attribute) GETSTRUCT(tuple);
    8514           37 :     attnum = attTup->attnum;
    8515              : 
    8516           37 :     if (attnum <= 0)
    8517            0 :         ereport(ERROR,
    8518              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    8519              :                  errmsg("cannot alter system column \"%s\"",
    8520              :                         colName)));
    8521              : 
    8522           37 :     if (!attTup->attidentity)
    8523            4 :         ereport(ERROR,
    8524              :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    8525              :                  errmsg("column \"%s\" of relation \"%s\" is not an identity column",
    8526              :                         colName, RelationGetRelationName(rel))));
    8527              : 
    8528           33 :     if (generatedEl)
    8529              :     {
    8530           29 :         attTup->attidentity = defGetInt32(generatedEl);
    8531           29 :         CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
    8532              : 
    8533           29 :         InvokeObjectPostAlterHook(RelationRelationId,
    8534              :                                   RelationGetRelid(rel),
    8535              :                                   attTup->attnum);
    8536           29 :         ObjectAddressSubSet(address, RelationRelationId,
    8537              :                             RelationGetRelid(rel), attnum);
    8538              :     }
    8539              :     else
    8540            4 :         address = InvalidObjectAddress;
    8541              : 
    8542           33 :     heap_freetuple(tuple);
    8543           33 :     table_close(attrelation, RowExclusiveLock);
    8544              : 
    8545              :     /*
    8546              :      * Recurse to propagate the identity change to partitions. Identity is not
    8547              :      * inherited in regular inheritance children.
    8548              :      */
    8549           33 :     if (generatedEl && recurse && ispartitioned)
    8550              :     {
    8551              :         List       *children;
    8552              :         ListCell   *lc;
    8553              : 
    8554            4 :         children = find_inheritance_children(RelationGetRelid(rel), lockmode);
    8555              : 
    8556           12 :         foreach(lc, children)
    8557              :         {
    8558              :             Relation    childrel;
    8559              : 
    8560            8 :             childrel = table_open(lfirst_oid(lc), NoLock);
    8561            8 :             ATExecSetIdentity(childrel, colName, def, lockmode, recurse, true);
    8562            8 :             table_close(childrel, NoLock);
    8563              :         }
    8564              :     }
    8565              : 
    8566           33 :     return address;
    8567              : }
    8568              : 
    8569              : /*
    8570              :  * ALTER TABLE ALTER COLUMN DROP IDENTITY
    8571              :  *
    8572              :  * Return the address of the affected column.
    8573              :  */
    8574              : static ObjectAddress
    8575           61 : ATExecDropIdentity(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode,
    8576              :                    bool recurse, bool recursing)
    8577              : {
    8578              :     HeapTuple   tuple;
    8579              :     Form_pg_attribute attTup;
    8580              :     AttrNumber  attnum;
    8581              :     Relation    attrelation;
    8582              :     ObjectAddress address;
    8583              :     Oid         seqid;
    8584              :     ObjectAddress seqaddress;
    8585              :     bool        ispartitioned;
    8586              : 
    8587           61 :     ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
    8588           61 :     if (ispartitioned && !recurse)
    8589            4 :         ereport(ERROR,
    8590              :                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    8591              :                  errmsg("cannot drop identity from a column of only the partitioned table"),
    8592              :                  errhint("Do not specify the ONLY keyword.")));
    8593              : 
    8594           57 :     if (rel->rd_rel->relispartition && !recursing)
    8595            4 :         ereport(ERROR,
    8596              :                 errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    8597              :                 errmsg("cannot drop identity from a column of a partition"));
    8598              : 
    8599           53 :     attrelation = table_open(AttributeRelationId, RowExclusiveLock);
    8600           53 :     tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
    8601           53 :     if (!HeapTupleIsValid(tuple))
    8602            0 :         ereport(ERROR,
    8603              :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    8604              :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
    8605              :                         colName, RelationGetRelationName(rel))));
    8606              : 
    8607           53 :     attTup = (Form_pg_attribute) GETSTRUCT(tuple);
    8608           53 :     attnum = attTup->attnum;
    8609              : 
    8610           53 :     if (attnum <= 0)
    8611            0 :         ereport(ERROR,
    8612              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    8613              :                  errmsg("cannot alter system column \"%s\"",
    8614              :                         colName)));
    8615              : 
    8616           53 :     if (!attTup->attidentity)
    8617              :     {
    8618            8 :         if (!missing_ok)
    8619            4 :             ereport(ERROR,
    8620              :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    8621              :                      errmsg("column \"%s\" of relation \"%s\" is not an identity column",
    8622              :                             colName, RelationGetRelationName(rel))));
    8623              :         else
    8624              :         {
    8625            4 :             ereport(NOTICE,
    8626              :                     (errmsg("column \"%s\" of relation \"%s\" is not an identity column, skipping",
    8627              :                             colName, RelationGetRelationName(rel))));
    8628            4 :             heap_freetuple(tuple);
    8629            4 :             table_close(attrelation, RowExclusiveLock);
    8630            4 :             return InvalidObjectAddress;
    8631              :         }
    8632              :     }
    8633              : 
    8634           45 :     attTup->attidentity = '\0';
    8635           45 :     CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
    8636              : 
    8637           45 :     InvokeObjectPostAlterHook(RelationRelationId,
    8638              :                               RelationGetRelid(rel),
    8639              :                               attTup->attnum);
    8640           45 :     ObjectAddressSubSet(address, RelationRelationId,
    8641              :                         RelationGetRelid(rel), attnum);
    8642           45 :     heap_freetuple(tuple);
    8643              : 
    8644           45 :     table_close(attrelation, RowExclusiveLock);
    8645              : 
    8646              :     /*
    8647              :      * Recurse to drop the identity from column in partitions.  Identity is
    8648              :      * not inherited in regular inheritance children so ignore them.
    8649              :      */
    8650           45 :     if (recurse && ispartitioned)
    8651              :     {
    8652              :         List       *children;
    8653              :         ListCell   *lc;
    8654              : 
    8655            4 :         children = find_inheritance_children(RelationGetRelid(rel), lockmode);
    8656              : 
    8657            8 :         foreach(lc, children)
    8658              :         {
    8659              :             Relation    childrel;
    8660              : 
    8661            4 :             childrel = table_open(lfirst_oid(lc), NoLock);
    8662            4 :             ATExecDropIdentity(childrel, colName, false, lockmode, recurse, true);
    8663            4 :             table_close(childrel, NoLock);
    8664              :         }
    8665              :     }
    8666              : 
    8667           45 :     if (!recursing)
    8668              :     {
    8669              :         /* drop the internal sequence */
    8670           21 :         seqid = getIdentitySequence(rel, attnum, false);
    8671           21 :         deleteDependencyRecordsForClass(RelationRelationId, seqid,
    8672              :                                         RelationRelationId, DEPENDENCY_INTERNAL);
    8673           21 :         CommandCounterIncrement();
    8674           21 :         seqaddress.classId = RelationRelationId;
    8675           21 :         seqaddress.objectId = seqid;
    8676           21 :         seqaddress.objectSubId = 0;
    8677           21 :         performDeletion(&seqaddress, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
    8678              :     }
    8679              : 
    8680           45 :     return address;
    8681              : }
    8682              : 
    8683              : /*
    8684              :  * ALTER TABLE ALTER COLUMN SET EXPRESSION
    8685              :  *
    8686              :  * Return the address of the affected column.
    8687              :  */
    8688              : static ObjectAddress
    8689          153 : ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName,
    8690              :                     Node *newExpr, LOCKMODE lockmode)
    8691              : {
    8692              :     HeapTuple   tuple;
    8693              :     Form_pg_attribute attTup;
    8694              :     AttrNumber  attnum;
    8695              :     char        attgenerated;
    8696              :     bool        rewrite;
    8697              :     Oid         attrdefoid;
    8698              :     ObjectAddress address;
    8699              :     Expr       *defval;
    8700              :     NewColumnValue *newval;
    8701              :     RawColumnDefault *rawEnt;
    8702              : 
    8703          153 :     tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
    8704          153 :     if (!HeapTupleIsValid(tuple))
    8705            0 :         ereport(ERROR,
    8706              :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    8707              :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
    8708              :                         colName, RelationGetRelationName(rel))));
    8709              : 
    8710          153 :     attTup = (Form_pg_attribute) GETSTRUCT(tuple);
    8711              : 
    8712          153 :     attnum = attTup->attnum;
    8713          153 :     if (attnum <= 0)
    8714            0 :         ereport(ERROR,
    8715              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    8716              :                  errmsg("cannot alter system column \"%s\"",
    8717              :                         colName)));
    8718              : 
    8719          153 :     attgenerated = attTup->attgenerated;
    8720          153 :     if (!attgenerated)
    8721            8 :         ereport(ERROR,
    8722              :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    8723              :                  errmsg("column \"%s\" of relation \"%s\" is not a generated column",
    8724              :                         colName, RelationGetRelationName(rel))));
    8725              : 
    8726          145 :     if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL && attTup->attnotnull)
    8727           16 :         tab->verify_new_notnull = true;
    8728              : 
    8729              :     /*
    8730              :      * We need to prevent this because a change of expression could affect a
    8731              :      * row filter and inject expressions that are not permitted in a row
    8732              :      * filter.  XXX We could try to have a more precise check to catch only
    8733              :      * publications with row filters, or even re-verify the row filter
    8734              :      * expressions.
    8735              :      */
    8736          221 :     if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL &&
    8737           76 :         GetRelationIncludedPublications(RelationGetRelid(rel)) != NIL)
    8738            4 :         ereport(ERROR,
    8739              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    8740              :                  errmsg("ALTER TABLE / SET EXPRESSION is not supported for virtual generated columns in tables that are part of a publication"),
    8741              :                  errdetail("Column \"%s\" of relation \"%s\" is a virtual generated column.",
    8742              :                            colName, RelationGetRelationName(rel))));
    8743              : 
    8744          141 :     rewrite = (attgenerated == ATTRIBUTE_GENERATED_STORED);
    8745              : 
    8746          141 :     ReleaseSysCache(tuple);
    8747              : 
    8748          141 :     if (rewrite)
    8749              :     {
    8750              :         /*
    8751              :          * Clear all the missing values if we're rewriting the table, since
    8752              :          * this renders them pointless.
    8753              :          */
    8754           69 :         RelationClearMissing(rel);
    8755              : 
    8756              :         /* make sure we don't conflict with later attribute modifications */
    8757           69 :         CommandCounterIncrement();
    8758              :     }
    8759              : 
    8760              :     /*
    8761              :      * Find everything that depends on the column (constraints, indexes, etc),
    8762              :      * and record enough information to let us recreate the objects.
    8763              :      */
    8764          141 :     RememberAllDependentForRebuilding(tab, AT_SetExpression, rel, attnum, colName);
    8765              : 
    8766              :     /*
    8767              :      * Drop the dependency records of the GENERATED expression, in particular
    8768              :      * its INTERNAL dependency on the column, which would otherwise cause
    8769              :      * dependency.c to refuse to perform the deletion.
    8770              :      */
    8771          141 :     attrdefoid = GetAttrDefaultOid(RelationGetRelid(rel), attnum);
    8772          141 :     if (!OidIsValid(attrdefoid))
    8773            0 :         elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
    8774              :              RelationGetRelid(rel), attnum);
    8775          141 :     (void) deleteDependencyRecordsFor(AttrDefaultRelationId, attrdefoid, false);
    8776              : 
    8777              :     /* Make above changes visible */
    8778          141 :     CommandCounterIncrement();
    8779              : 
    8780              :     /*
    8781              :      * Get rid of the GENERATED expression itself.  We use RESTRICT here for
    8782              :      * safety, but at present we do not expect anything to depend on the
    8783              :      * expression.
    8784              :      */
    8785          141 :     RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT,
    8786              :                       false, false);
    8787              : 
    8788              :     /* Prepare to store the new expression, in the catalogs */
    8789          141 :     rawEnt = palloc_object(RawColumnDefault);
    8790          141 :     rawEnt->attnum = attnum;
    8791          141 :     rawEnt->raw_default = newExpr;
    8792          141 :     rawEnt->generated = attgenerated;
    8793              : 
    8794              :     /* Store the generated expression */
    8795          141 :     AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
    8796              :                               false, true, false, NULL);
    8797              : 
    8798              :     /* Make above new expression visible */
    8799          141 :     CommandCounterIncrement();
    8800              : 
    8801          141 :     if (rewrite)
    8802              :     {
    8803              :         /* Prepare for table rewrite */
    8804           69 :         defval = (Expr *) build_column_default(rel, attnum);
    8805              : 
    8806           69 :         newval = palloc0_object(NewColumnValue);
    8807           69 :         newval->attnum = attnum;
    8808           69 :         newval->expr = expression_planner(defval);
    8809           69 :         newval->is_generated = true;
    8810              : 
    8811           69 :         tab->newvals = lappend(tab->newvals, newval);
    8812           69 :         tab->rewrite |= AT_REWRITE_DEFAULT_VAL;
    8813              :     }
    8814              : 
    8815              :     /* Drop any pg_statistic entry for the column */
    8816          141 :     RemoveStatistics(RelationGetRelid(rel), attnum);
    8817              : 
    8818          141 :     InvokeObjectPostAlterHook(RelationRelationId,
    8819              :                               RelationGetRelid(rel), attnum);
    8820              : 
    8821          141 :     ObjectAddressSubSet(address, RelationRelationId,
    8822              :                         RelationGetRelid(rel), attnum);
    8823          141 :     return address;
    8824              : }
    8825              : 
    8826              : /*
    8827              :  * ALTER TABLE ALTER COLUMN DROP EXPRESSION
    8828              :  */
    8829              : static void
    8830           57 : ATPrepDropExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode)
    8831              : {
    8832              :     /*
    8833              :      * Reject ONLY if there are child tables.  We could implement this, but it
    8834              :      * is a bit complicated.  GENERATED clauses must be attached to the column
    8835              :      * definition and cannot be added later like DEFAULT, so if a child table
    8836              :      * has a generation expression that the parent does not have, the child
    8837              :      * column will necessarily be an attislocal column.  So to implement ONLY
    8838              :      * here, we'd need extra code to update attislocal of the direct child
    8839              :      * tables, somewhat similar to how DROP COLUMN does it, so that the
    8840              :      * resulting state can be properly dumped and restored.
    8841              :      */
    8842           73 :     if (!recurse &&
    8843           16 :         find_inheritance_children(RelationGetRelid(rel), lockmode))
    8844            8 :         ereport(ERROR,
    8845              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    8846              :                  errmsg("ALTER TABLE / DROP EXPRESSION must be applied to child tables too")));
    8847              : 
    8848              :     /*
    8849              :      * Cannot drop generation expression from inherited columns.
    8850              :      */
    8851           49 :     if (!recursing)
    8852              :     {
    8853              :         HeapTuple   tuple;
    8854              :         Form_pg_attribute attTup;
    8855              : 
    8856           41 :         tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), cmd->name);
    8857           41 :         if (!HeapTupleIsValid(tuple))
    8858            0 :             ereport(ERROR,
    8859              :                     (errcode(ERRCODE_UNDEFINED_COLUMN),
    8860              :                      errmsg("column \"%s\" of relation \"%s\" does not exist",
    8861              :                             cmd->name, RelationGetRelationName(rel))));
    8862              : 
    8863           41 :         attTup = (Form_pg_attribute) GETSTRUCT(tuple);
    8864              : 
    8865           41 :         if (attTup->attinhcount > 0)
    8866            8 :             ereport(ERROR,
    8867              :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    8868              :                      errmsg("cannot drop generation expression from inherited column")));
    8869              :     }
    8870           41 : }
    8871              : 
    8872              : /*
    8873              :  * Return the address of the affected column.
    8874              :  */
    8875              : static ObjectAddress
    8876           37 : ATExecDropExpression(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode)
    8877              : {
    8878              :     HeapTuple   tuple;
    8879              :     Form_pg_attribute attTup;
    8880              :     AttrNumber  attnum;
    8881              :     Relation    attrelation;
    8882              :     Oid         attrdefoid;
    8883              :     ObjectAddress address;
    8884              : 
    8885           37 :     attrelation = table_open(AttributeRelationId, RowExclusiveLock);
    8886           37 :     tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
    8887           37 :     if (!HeapTupleIsValid(tuple))
    8888            0 :         ereport(ERROR,
    8889              :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    8890              :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
    8891              :                         colName, RelationGetRelationName(rel))));
    8892              : 
    8893           37 :     attTup = (Form_pg_attribute) GETSTRUCT(tuple);
    8894           37 :     attnum = attTup->attnum;
    8895              : 
    8896           37 :     if (attnum <= 0)
    8897            0 :         ereport(ERROR,
    8898              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    8899              :                  errmsg("cannot alter system column \"%s\"",
    8900              :                         colName)));
    8901              : 
    8902              :     /*
    8903              :      * TODO: This could be done, but it would need a table rewrite to
    8904              :      * materialize the generated values.  Note that for the time being, we
    8905              :      * still error with missing_ok, so that we don't silently leave the column
    8906              :      * as generated.
    8907              :      */
    8908           37 :     if (attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
    8909            8 :         ereport(ERROR,
    8910              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    8911              :                  errmsg("ALTER TABLE / DROP EXPRESSION is not supported for virtual generated columns"),
    8912              :                  errdetail("Column \"%s\" of relation \"%s\" is a virtual generated column.",
    8913              :                            colName, RelationGetRelationName(rel))));
    8914              : 
    8915           29 :     if (!attTup->attgenerated)
    8916              :     {
    8917           16 :         if (!missing_ok)
    8918            8 :             ereport(ERROR,
    8919              :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    8920              :                      errmsg("column \"%s\" of relation \"%s\" is not a generated column",
    8921              :                             colName, RelationGetRelationName(rel))));
    8922              :         else
    8923              :         {
    8924            8 :             ereport(NOTICE,
    8925              :                     (errmsg("column \"%s\" of relation \"%s\" is not a generated column, skipping",
    8926              :                             colName, RelationGetRelationName(rel))));
    8927            8 :             heap_freetuple(tuple);
    8928            8 :             table_close(attrelation, RowExclusiveLock);
    8929            8 :             return InvalidObjectAddress;
    8930              :         }
    8931              :     }
    8932              : 
    8933              :     /*
    8934              :      * Mark the column as no longer generated.  (The atthasdef flag needs to
    8935              :      * get cleared too, but RemoveAttrDefault will handle that.)
    8936              :      */
    8937           13 :     attTup->attgenerated = '\0';
    8938           13 :     CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
    8939              : 
    8940           13 :     InvokeObjectPostAlterHook(RelationRelationId,
    8941              :                               RelationGetRelid(rel),
    8942              :                               attnum);
    8943           13 :     heap_freetuple(tuple);
    8944              : 
    8945           13 :     table_close(attrelation, RowExclusiveLock);
    8946              : 
    8947              :     /*
    8948              :      * Drop the dependency records of the GENERATED expression, in particular
    8949              :      * its INTERNAL dependency on the column, which would otherwise cause
    8950              :      * dependency.c to refuse to perform the deletion.
    8951              :      */
    8952           13 :     attrdefoid = GetAttrDefaultOid(RelationGetRelid(rel), attnum);
    8953           13 :     if (!OidIsValid(attrdefoid))
    8954            0 :         elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
    8955              :              RelationGetRelid(rel), attnum);
    8956           13 :     (void) deleteDependencyRecordsFor(AttrDefaultRelationId, attrdefoid, false);
    8957              : 
    8958              :     /* Make above changes visible */
    8959           13 :     CommandCounterIncrement();
    8960              : 
    8961              :     /*
    8962              :      * Get rid of the GENERATED expression itself.  We use RESTRICT here for
    8963              :      * safety, but at present we do not expect anything to depend on the
    8964              :      * default.
    8965              :      */
    8966           13 :     RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT,
    8967              :                       false, false);
    8968              : 
    8969           13 :     ObjectAddressSubSet(address, RelationRelationId,
    8970              :                         RelationGetRelid(rel), attnum);
    8971           13 :     return address;
    8972              : }
    8973              : 
    8974              : /*
    8975              :  * ALTER TABLE ALTER COLUMN SET STATISTICS
    8976              :  *
    8977              :  * Return value is the address of the modified column
    8978              :  */
    8979              : static ObjectAddress
    8980          107 : ATExecSetStatistics(Relation rel, const char *colName, int16 colNum, Node *newValue, LOCKMODE lockmode)
    8981              : {
    8982          107 :     int         newtarget = 0;
    8983              :     bool        newtarget_default;
    8984              :     Relation    attrelation;
    8985              :     HeapTuple   tuple,
    8986              :                 newtuple;
    8987              :     Form_pg_attribute attrtuple;
    8988              :     AttrNumber  attnum;
    8989              :     ObjectAddress address;
    8990              :     Datum       repl_val[Natts_pg_attribute];
    8991              :     bool        repl_null[Natts_pg_attribute];
    8992              :     bool        repl_repl[Natts_pg_attribute];
    8993              : 
    8994              :     /*
    8995              :      * We allow referencing columns by numbers only for indexes, since table
    8996              :      * column numbers could contain gaps if columns are later dropped.
    8997              :      */
    8998          107 :     if (rel->rd_rel->relkind != RELKIND_INDEX &&
    8999           65 :         rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX &&
    9000              :         !colName)
    9001            0 :         ereport(ERROR,
    9002              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    9003              :                  errmsg("cannot refer to non-index column by number")));
    9004              : 
    9005              :     /* -1 was used in previous versions for the default setting */
    9006          107 :     if (newValue && intVal(newValue) != -1)
    9007              :     {
    9008           78 :         newtarget = intVal(newValue);
    9009           78 :         newtarget_default = false;
    9010              :     }
    9011              :     else
    9012           29 :         newtarget_default = true;
    9013              : 
    9014          107 :     if (!newtarget_default)
    9015              :     {
    9016              :         /*
    9017              :          * Limit target to a sane range
    9018              :          */
    9019           78 :         if (newtarget < 0)
    9020              :         {
    9021            0 :             ereport(ERROR,
    9022              :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    9023              :                      errmsg("statistics target %d is too low",
    9024              :                             newtarget)));
    9025              :         }
    9026           78 :         else if (newtarget > MAX_STATISTICS_TARGET)
    9027              :         {
    9028            0 :             newtarget = MAX_STATISTICS_TARGET;
    9029            0 :             ereport(WARNING,
    9030              :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    9031              :                      errmsg("lowering statistics target to %d",
    9032              :                             newtarget)));
    9033              :         }
    9034              :     }
    9035              : 
    9036          107 :     attrelation = table_open(AttributeRelationId, RowExclusiveLock);
    9037              : 
    9038          107 :     if (colName)
    9039              :     {
    9040           65 :         tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
    9041              : 
    9042           65 :         if (!HeapTupleIsValid(tuple))
    9043            8 :             ereport(ERROR,
    9044              :                     (errcode(ERRCODE_UNDEFINED_COLUMN),
    9045              :                      errmsg("column \"%s\" of relation \"%s\" does not exist",
    9046              :                             colName, RelationGetRelationName(rel))));
    9047              :     }
    9048              :     else
    9049              :     {
    9050           42 :         tuple = SearchSysCacheAttNum(RelationGetRelid(rel), colNum);
    9051              : 
    9052           42 :         if (!HeapTupleIsValid(tuple))
    9053            8 :             ereport(ERROR,
    9054              :                     (errcode(ERRCODE_UNDEFINED_COLUMN),
    9055              :                      errmsg("column number %d of relation \"%s\" does not exist",
    9056              :                             colNum, RelationGetRelationName(rel))));
    9057              :     }
    9058              : 
    9059           91 :     attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
    9060              : 
    9061           91 :     attnum = attrtuple->attnum;
    9062           91 :     if (attnum <= 0)
    9063            0 :         ereport(ERROR,
    9064              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    9065              :                  errmsg("cannot alter system column \"%s\"",
    9066              :                         colName)));
    9067              : 
    9068              :     /*
    9069              :      * Prevent this as long as the ANALYZE code skips virtual generated
    9070              :      * columns.
    9071              :      */
    9072           91 :     if (attrtuple->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
    9073            0 :         ereport(ERROR,
    9074              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    9075              :                  errmsg("cannot alter statistics on virtual generated column \"%s\"",
    9076              :                         colName)));
    9077              : 
    9078           91 :     if (rel->rd_rel->relkind == RELKIND_INDEX ||
    9079           57 :         rel->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
    9080              :     {
    9081           34 :         if (attnum > rel->rd_index->indnkeyatts)
    9082            4 :             ereport(ERROR,
    9083              :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    9084              :                      errmsg("cannot alter statistics on included column \"%s\" of index \"%s\"",
    9085              :                             NameStr(attrtuple->attname), RelationGetRelationName(rel))));
    9086           30 :         else if (rel->rd_index->indkey.values[attnum - 1] != 0)
    9087           12 :             ereport(ERROR,
    9088              :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    9089              :                      errmsg("cannot alter statistics on non-expression column \"%s\" of index \"%s\"",
    9090              :                             NameStr(attrtuple->attname), RelationGetRelationName(rel)),
    9091              :                      errhint("Alter statistics on table column instead.")));
    9092              :     }
    9093              : 
    9094              :     /* Build new tuple. */
    9095           75 :     memset(repl_null, false, sizeof(repl_null));
    9096           75 :     memset(repl_repl, false, sizeof(repl_repl));
    9097           75 :     if (!newtarget_default)
    9098           46 :         repl_val[Anum_pg_attribute_attstattarget - 1] = Int16GetDatum(newtarget);
    9099              :     else
    9100           29 :         repl_null[Anum_pg_attribute_attstattarget - 1] = true;
    9101           75 :     repl_repl[Anum_pg_attribute_attstattarget - 1] = true;
    9102           75 :     newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrelation),
    9103              :                                  repl_val, repl_null, repl_repl);
    9104           75 :     CatalogTupleUpdate(attrelation, &tuple->t_self, newtuple);
    9105              : 
    9106           75 :     InvokeObjectPostAlterHook(RelationRelationId,
    9107              :                               RelationGetRelid(rel),
    9108              :                               attrtuple->attnum);
    9109           75 :     ObjectAddressSubSet(address, RelationRelationId,
    9110              :                         RelationGetRelid(rel), attnum);
    9111              : 
    9112           75 :     heap_freetuple(newtuple);
    9113              : 
    9114           75 :     ReleaseSysCache(tuple);
    9115              : 
    9116           75 :     table_close(attrelation, RowExclusiveLock);
    9117              : 
    9118           75 :     return address;
    9119              : }
    9120              : 
    9121              : /*
    9122              :  * Return value is the address of the modified column
    9123              :  */
    9124              : static ObjectAddress
    9125           21 : ATExecSetOptions(Relation rel, const char *colName, Node *options,
    9126              :                  bool isReset, LOCKMODE lockmode)
    9127              : {
    9128              :     Relation    attrelation;
    9129              :     HeapTuple   tuple,
    9130              :                 newtuple;
    9131              :     Form_pg_attribute attrtuple;
    9132              :     AttrNumber  attnum;
    9133              :     Datum       datum,
    9134              :                 newOptions;
    9135              :     bool        isnull;
    9136              :     ObjectAddress address;
    9137              :     Datum       repl_val[Natts_pg_attribute];
    9138              :     bool        repl_null[Natts_pg_attribute];
    9139              :     bool        repl_repl[Natts_pg_attribute];
    9140              : 
    9141           21 :     attrelation = table_open(AttributeRelationId, RowExclusiveLock);
    9142              : 
    9143           21 :     tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
    9144              : 
    9145           21 :     if (!HeapTupleIsValid(tuple))
    9146            0 :         ereport(ERROR,
    9147              :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    9148              :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
    9149              :                         colName, RelationGetRelationName(rel))));
    9150           21 :     attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
    9151              : 
    9152           21 :     attnum = attrtuple->attnum;
    9153           21 :     if (attnum <= 0)
    9154            0 :         ereport(ERROR,
    9155              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    9156              :                  errmsg("cannot alter system column \"%s\"",
    9157              :                         colName)));
    9158              : 
    9159              :     /* Generate new proposed attoptions (text array) */
    9160           21 :     datum = SysCacheGetAttr(ATTNAME, tuple, Anum_pg_attribute_attoptions,
    9161              :                             &isnull);
    9162           21 :     newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
    9163              :                                      castNode(List, options), NULL, NULL,
    9164              :                                      false, isReset);
    9165              :     /* Validate new options */
    9166           21 :     (void) attribute_reloptions(newOptions, true);
    9167              : 
    9168              :     /* Build new tuple. */
    9169           21 :     memset(repl_null, false, sizeof(repl_null));
    9170           21 :     memset(repl_repl, false, sizeof(repl_repl));
    9171           21 :     if (newOptions != (Datum) 0)
    9172           21 :         repl_val[Anum_pg_attribute_attoptions - 1] = newOptions;
    9173              :     else
    9174            0 :         repl_null[Anum_pg_attribute_attoptions - 1] = true;
    9175           21 :     repl_repl[Anum_pg_attribute_attoptions - 1] = true;
    9176           21 :     newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrelation),
    9177              :                                  repl_val, repl_null, repl_repl);
    9178              : 
    9179              :     /* Update system catalog. */
    9180           21 :     CatalogTupleUpdate(attrelation, &newtuple->t_self, newtuple);
    9181              : 
    9182           21 :     InvokeObjectPostAlterHook(RelationRelationId,
    9183              :                               RelationGetRelid(rel),
    9184              :                               attrtuple->attnum);
    9185           21 :     ObjectAddressSubSet(address, RelationRelationId,
    9186              :                         RelationGetRelid(rel), attnum);
    9187              : 
    9188           21 :     heap_freetuple(newtuple);
    9189              : 
    9190           21 :     ReleaseSysCache(tuple);
    9191              : 
    9192           21 :     table_close(attrelation, RowExclusiveLock);
    9193              : 
    9194           21 :     return address;
    9195              : }
    9196              : 
    9197              : /*
    9198              :  * Helper function for ATExecSetStorage and ATExecSetCompression
    9199              :  *
    9200              :  * Set the attstorage and/or attcompression fields for index columns
    9201              :  * associated with the specified table column.
    9202              :  */
    9203              : static void
    9204          208 : SetIndexStorageProperties(Relation rel, Relation attrelation,
    9205              :                           AttrNumber attnum,
    9206              :                           bool setstorage, char newstorage,
    9207              :                           bool setcompression, char newcompression,
    9208              :                           LOCKMODE lockmode)
    9209              : {
    9210              :     ListCell   *lc;
    9211              : 
    9212          265 :     foreach(lc, RelationGetIndexList(rel))
    9213              :     {
    9214           57 :         Oid         indexoid = lfirst_oid(lc);
    9215              :         Relation    indrel;
    9216           57 :         AttrNumber  indattnum = 0;
    9217              :         HeapTuple   tuple;
    9218              : 
    9219           57 :         indrel = index_open(indexoid, lockmode);
    9220              : 
    9221           95 :         for (int i = 0; i < indrel->rd_index->indnatts; i++)
    9222              :         {
    9223           61 :             if (indrel->rd_index->indkey.values[i] == attnum)
    9224              :             {
    9225           23 :                 indattnum = i + 1;
    9226           23 :                 break;
    9227              :             }
    9228              :         }
    9229              : 
    9230           57 :         if (indattnum == 0)
    9231              :         {
    9232           34 :             index_close(indrel, lockmode);
    9233           34 :             continue;
    9234              :         }
    9235              : 
    9236           23 :         tuple = SearchSysCacheCopyAttNum(RelationGetRelid(indrel), indattnum);
    9237              : 
    9238           23 :         if (HeapTupleIsValid(tuple))
    9239              :         {
    9240           23 :             Form_pg_attribute attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
    9241              : 
    9242           23 :             if (setstorage)
    9243           15 :                 attrtuple->attstorage = newstorage;
    9244              : 
    9245           23 :             if (setcompression)
    9246            8 :                 attrtuple->attcompression = newcompression;
    9247              : 
    9248           23 :             CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
    9249              : 
    9250           23 :             InvokeObjectPostAlterHook(RelationRelationId,
    9251              :                                       RelationGetRelid(rel),
    9252              :                                       attrtuple->attnum);
    9253              : 
    9254           23 :             heap_freetuple(tuple);
    9255              :         }
    9256              : 
    9257           23 :         index_close(indrel, lockmode);
    9258              :     }
    9259          208 : }
    9260              : 
    9261              : /*
    9262              :  * ALTER TABLE ALTER COLUMN SET STORAGE
    9263              :  *
    9264              :  * Return value is the address of the modified column
    9265              :  */
    9266              : static ObjectAddress
    9267          173 : ATExecSetStorage(Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
    9268              : {
    9269              :     Relation    attrelation;
    9270              :     HeapTuple   tuple;
    9271              :     Form_pg_attribute attrtuple;
    9272              :     AttrNumber  attnum;
    9273              :     ObjectAddress address;
    9274              : 
    9275          173 :     attrelation = table_open(AttributeRelationId, RowExclusiveLock);
    9276              : 
    9277          173 :     tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
    9278              : 
    9279          173 :     if (!HeapTupleIsValid(tuple))
    9280            8 :         ereport(ERROR,
    9281              :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    9282              :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
    9283              :                         colName, RelationGetRelationName(rel))));
    9284          165 :     attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
    9285              : 
    9286          165 :     attnum = attrtuple->attnum;
    9287          165 :     if (attnum <= 0)
    9288            0 :         ereport(ERROR,
    9289              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    9290              :                  errmsg("cannot alter system column \"%s\"",
    9291              :                         colName)));
    9292              : 
    9293          165 :     attrtuple->attstorage = GetAttributeStorage(attrtuple->atttypid, strVal(newValue));
    9294              : 
    9295          165 :     CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
    9296              : 
    9297          165 :     InvokeObjectPostAlterHook(RelationRelationId,
    9298              :                               RelationGetRelid(rel),
    9299              :                               attrtuple->attnum);
    9300              : 
    9301              :     /*
    9302              :      * Apply the change to indexes as well (only for simple index columns,
    9303              :      * matching behavior of index.c ConstructTupleDescriptor()).
    9304              :      */
    9305          165 :     SetIndexStorageProperties(rel, attrelation, attnum,
    9306          165 :                               true, attrtuple->attstorage,
    9307              :                               false, 0,
    9308              :                               lockmode);
    9309              : 
    9310          165 :     heap_freetuple(tuple);
    9311              : 
    9312          165 :     table_close(attrelation, RowExclusiveLock);
    9313              : 
    9314          165 :     ObjectAddressSubSet(address, RelationRelationId,
    9315              :                         RelationGetRelid(rel), attnum);
    9316          165 :     return address;
    9317              : }
    9318              : 
    9319              : 
    9320              : /*
    9321              :  * ALTER TABLE DROP COLUMN
    9322              :  *
    9323              :  * DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
    9324              :  * because we have to decide at runtime whether to recurse or not depending
    9325              :  * on whether attinhcount goes to zero or not.  (We can't check this in a
    9326              :  * static pre-pass because it won't handle multiple inheritance situations
    9327              :  * correctly.)
    9328              :  */
    9329              : static void
    9330         1113 : ATPrepDropColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
    9331              :                  AlterTableCmd *cmd, LOCKMODE lockmode,
    9332              :                  AlterTableUtilityContext *context)
    9333              : {
    9334         1113 :     if (rel->rd_rel->reloftype && !recursing)
    9335            4 :         ereport(ERROR,
    9336              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    9337              :                  errmsg("cannot drop column from typed table")));
    9338              : 
    9339         1109 :     if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
    9340           54 :         ATTypedTableRecursion(wqueue, rel, cmd, lockmode, context);
    9341              : 
    9342         1105 :     if (recurse)
    9343          947 :         cmd->recurse = true;
    9344         1105 : }
    9345              : 
    9346              : /*
    9347              :  * Drops column 'colName' from relation 'rel' and returns the address of the
    9348              :  * dropped column.  The column is also dropped (or marked as no longer
    9349              :  * inherited from relation) from the relation's inheritance children, if any.
    9350              :  *
    9351              :  * In the recursive invocations for inheritance child relations, instead of
    9352              :  * dropping the column directly (if to be dropped at all), its object address
    9353              :  * is added to 'addrs', which must be non-NULL in such invocations.  All
    9354              :  * columns are dropped at the same time after all the children have been
    9355              :  * checked recursively.
    9356              :  */
    9357              : static ObjectAddress
    9358         1478 : ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
    9359              :                  DropBehavior behavior,
    9360              :                  bool recurse, bool recursing,
    9361              :                  bool missing_ok, LOCKMODE lockmode,
    9362              :                  ObjectAddresses *addrs)
    9363              : {
    9364              :     HeapTuple   tuple;
    9365              :     Form_pg_attribute targetatt;
    9366              :     AttrNumber  attnum;
    9367              :     List       *children;
    9368              :     ObjectAddress object;
    9369              :     bool        is_expr;
    9370              : 
    9371              :     /* At top level, permission check was done in ATPrepCmd, else do it */
    9372         1478 :     if (recursing)
    9373          373 :         ATSimplePermissions(AT_DropColumn, rel,
    9374              :                             ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
    9375              : 
    9376              :     /* Initialize addrs on the first invocation */
    9377              :     Assert(!recursing || addrs != NULL);
    9378              : 
    9379              :     /* since this function recurses, it could be driven to stack overflow */
    9380         1478 :     check_stack_depth();
    9381              : 
    9382         1478 :     if (!recursing)
    9383         1105 :         addrs = new_object_addresses();
    9384              : 
    9385              :     /*
    9386              :      * get the number of the attribute
    9387              :      */
    9388         1478 :     tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
    9389         1478 :     if (!HeapTupleIsValid(tuple))
    9390              :     {
    9391           40 :         if (!missing_ok)
    9392              :         {
    9393           24 :             ereport(ERROR,
    9394              :                     (errcode(ERRCODE_UNDEFINED_COLUMN),
    9395              :                      errmsg("column \"%s\" of relation \"%s\" does not exist",
    9396              :                             colName, RelationGetRelationName(rel))));
    9397              :         }
    9398              :         else
    9399              :         {
    9400           16 :             ereport(NOTICE,
    9401              :                     (errmsg("column \"%s\" of relation \"%s\" does not exist, skipping",
    9402              :                             colName, RelationGetRelationName(rel))));
    9403           16 :             return InvalidObjectAddress;
    9404              :         }
    9405              :     }
    9406         1438 :     targetatt = (Form_pg_attribute) GETSTRUCT(tuple);
    9407              : 
    9408         1438 :     attnum = targetatt->attnum;
    9409              : 
    9410              :     /* Can't drop a system attribute */
    9411         1438 :     if (attnum <= 0)
    9412            4 :         ereport(ERROR,
    9413              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    9414              :                  errmsg("cannot drop system column \"%s\"",
    9415              :                         colName)));
    9416              : 
    9417              :     /*
    9418              :      * Don't drop inherited columns, unless recursing (presumably from a drop
    9419              :      * of the parent column)
    9420              :      */
    9421         1434 :     if (targetatt->attinhcount > 0 && !recursing)
    9422           32 :         ereport(ERROR,
    9423              :                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    9424              :                  errmsg("cannot drop inherited column \"%s\"",
    9425              :                         colName)));
    9426              : 
    9427              :     /*
    9428              :      * Don't drop columns used in the partition key, either.  (If we let this
    9429              :      * go through, the key column's dependencies would cause a cascaded drop
    9430              :      * of the whole table, which is surely not what the user expected.)
    9431              :      */
    9432         1402 :     if (has_partition_attrs(rel,
    9433              :                             bms_make_singleton(attnum - FirstLowInvalidHeapAttributeNumber),
    9434              :                             &is_expr))
    9435           20 :         ereport(ERROR,
    9436              :                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    9437              :                  errmsg("cannot drop column \"%s\" because it is part of the partition key of relation \"%s\"",
    9438              :                         colName, RelationGetRelationName(rel))));
    9439              : 
    9440         1382 :     ReleaseSysCache(tuple);
    9441              : 
    9442              :     /*
    9443              :      * Propagate to children as appropriate.  Unlike most other ALTER
    9444              :      * routines, we have to do this one level of recursion at a time; we can't
    9445              :      * use find_all_inheritors to do it in one pass.
    9446              :      */
    9447              :     children =
    9448         1382 :         find_inheritance_children(RelationGetRelid(rel), lockmode);
    9449              : 
    9450         1382 :     if (children)
    9451              :     {
    9452              :         Relation    attr_rel;
    9453              :         ListCell   *child;
    9454              : 
    9455              :         /*
    9456              :          * In case of a partitioned table, the column must be dropped from the
    9457              :          * partitions as well.
    9458              :          */
    9459          204 :         if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && !recurse)
    9460            4 :             ereport(ERROR,
    9461              :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    9462              :                      errmsg("cannot drop column from only the partitioned table when partitions exist"),
    9463              :                      errhint("Do not specify the ONLY keyword.")));
    9464              : 
    9465          200 :         attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
    9466          593 :         foreach(child, children)
    9467              :         {
    9468          397 :             Oid         childrelid = lfirst_oid(child);
    9469              :             Relation    childrel;
    9470              :             Form_pg_attribute childatt;
    9471              : 
    9472              :             /* find_inheritance_children already got lock */
    9473          397 :             childrel = table_open(childrelid, NoLock);
    9474          397 :             CheckAlterTableIsSafe(childrel);
    9475              : 
    9476          397 :             tuple = SearchSysCacheCopyAttName(childrelid, colName);
    9477          397 :             if (!HeapTupleIsValid(tuple))   /* shouldn't happen */
    9478            0 :                 elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
    9479              :                      colName, childrelid);
    9480          397 :             childatt = (Form_pg_attribute) GETSTRUCT(tuple);
    9481              : 
    9482          397 :             if (childatt->attinhcount <= 0) /* shouldn't happen */
    9483            0 :                 elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
    9484              :                      childrelid, colName);
    9485              : 
    9486          397 :             if (recurse)
    9487              :             {
    9488              :                 /*
    9489              :                  * If the child column has other definition sources, just
    9490              :                  * decrement its inheritance count; if not, recurse to delete
    9491              :                  * it.
    9492              :                  */
    9493          381 :                 if (childatt->attinhcount == 1 && !childatt->attislocal)
    9494              :                 {
    9495              :                     /* Time to delete this child column, too */
    9496          373 :                     ATExecDropColumn(wqueue, childrel, colName,
    9497              :                                      behavior, true, true,
    9498              :                                      false, lockmode, addrs);
    9499              :                 }
    9500              :                 else
    9501              :                 {
    9502              :                     /* Child column must survive my deletion */
    9503            8 :                     childatt->attinhcount--;
    9504              : 
    9505            8 :                     CatalogTupleUpdate(attr_rel, &tuple->t_self, tuple);
    9506              : 
    9507              :                     /* Make update visible */
    9508            8 :                     CommandCounterIncrement();
    9509              :                 }
    9510              :             }
    9511              :             else
    9512              :             {
    9513              :                 /*
    9514              :                  * If we were told to drop ONLY in this table (no recursion),
    9515              :                  * we need to mark the inheritors' attributes as locally
    9516              :                  * defined rather than inherited.
    9517              :                  */
    9518           16 :                 childatt->attinhcount--;
    9519           16 :                 childatt->attislocal = true;
    9520              : 
    9521           16 :                 CatalogTupleUpdate(attr_rel, &tuple->t_self, tuple);
    9522              : 
    9523              :                 /* Make update visible */
    9524           16 :                 CommandCounterIncrement();
    9525              :             }
    9526              : 
    9527          393 :             heap_freetuple(tuple);
    9528              : 
    9529          393 :             table_close(childrel, NoLock);
    9530              :         }
    9531          196 :         table_close(attr_rel, RowExclusiveLock);
    9532              :     }
    9533              : 
    9534              :     /* Add object to delete */
    9535         1374 :     object.classId = RelationRelationId;
    9536         1374 :     object.objectId = RelationGetRelid(rel);
    9537         1374 :     object.objectSubId = attnum;
    9538         1374 :     add_exact_object_address(&object, addrs);
    9539              : 
    9540         1374 :     if (!recursing)
    9541              :     {
    9542              :         /* Recursion has ended, drop everything that was collected */
    9543         1005 :         performMultipleDeletions(addrs, behavior, 0);
    9544          961 :         free_object_addresses(addrs);
    9545              :     }
    9546              : 
    9547         1330 :     return object;
    9548              : }
    9549              : 
    9550              : /*
    9551              :  * Prepare to add a primary key on a table, by adding not-null constraints
    9552              :  * on all columns.
    9553              :  *
    9554              :  * The not-null constraints for a primary key must cover the whole inheritance
    9555              :  * hierarchy (failing to ensure that leads to funny corner cases).  For the
    9556              :  * normal case where we're asked to recurse, this routine checks if the
    9557              :  * not-null constraints exist already, and if not queues a requirement for
    9558              :  * them to be created by phase 2.
    9559              :  *
    9560              :  * For the case where we're asked not to recurse, we verify that a not-null
    9561              :  * constraint exists on each column of each (direct) child table, throwing an
    9562              :  * error if not.  Not throwing an error would also work, because a not-null
    9563              :  * constraint would be created anyway, but it'd cause a silent scan of the
    9564              :  * child table to verify absence of nulls.  We prefer to let the user know so
    9565              :  * that they can add the constraint manually without having to hold
    9566              :  * AccessExclusiveLock while at it.
    9567              :  *
    9568              :  * However, it's also important that we do not acquire locks on children if
    9569              :  * the not-null constraints already exist on the parent, to avoid risking
    9570              :  * deadlocks during parallel pg_restore of PKs on partitioned tables.
    9571              :  */
    9572              : static void
    9573         9529 : ATPrepAddPrimaryKey(List **wqueue, Relation rel, AlterTableCmd *cmd,
    9574              :                     bool recurse, LOCKMODE lockmode,
    9575              :                     AlterTableUtilityContext *context)
    9576              : {
    9577              :     Constraint *pkconstr;
    9578         9529 :     List       *children = NIL;
    9579         9529 :     bool        got_children = false;
    9580              : 
    9581         9529 :     pkconstr = castNode(Constraint, cmd->def);
    9582         9529 :     if (pkconstr->contype != CONSTR_PRIMARY)
    9583         5677 :         return;
    9584              : 
    9585              :     /* Verify that columns are not-null, or request that they be made so */
    9586         8309 :     foreach_node(String, column, pkconstr->keys)
    9587              :     {
    9588              :         AlterTableCmd *newcmd;
    9589              :         Constraint *nnconstr;
    9590              :         HeapTuple   tuple;
    9591              : 
    9592              :         /*
    9593              :          * First check if a suitable constraint exists.  If it does, we don't
    9594              :          * need to request another one.  We do need to bail out if it's not
    9595              :          * valid, though.
    9596              :          */
    9597          645 :         tuple = findNotNullConstraint(RelationGetRelid(rel), strVal(column));
    9598          645 :         if (tuple != NULL)
    9599              :         {
    9600          318 :             verifyNotNullPKCompatible(tuple, strVal(column));
    9601              : 
    9602              :             /* All good with this one; don't request another */
    9603          310 :             heap_freetuple(tuple);
    9604          310 :             continue;
    9605              :         }
    9606          327 :         else if (!recurse)
    9607              :         {
    9608              :             /*
    9609              :              * No constraint on this column.  Asked not to recurse, we won't
    9610              :              * create one here, but verify that all children have one.
    9611              :              */
    9612           24 :             if (!got_children)
    9613              :             {
    9614           24 :                 children = find_inheritance_children(RelationGetRelid(rel),
    9615              :                                                      lockmode);
    9616              :                 /* only search for children on the first time through */
    9617           24 :                 got_children = true;
    9618              :             }
    9619              : 
    9620           48 :             foreach_oid(childrelid, children)
    9621              :             {
    9622              :                 HeapTuple   tup;
    9623              : 
    9624           24 :                 tup = findNotNullConstraint(childrelid, strVal(column));
    9625           24 :                 if (!tup)
    9626            4 :                     ereport(ERROR,
    9627              :                             errmsg("column \"%s\" of table \"%s\" is not marked NOT NULL",
    9628              :                                    strVal(column), get_rel_name(childrelid)));
    9629              :                 /* verify it's good enough */
    9630           20 :                 verifyNotNullPKCompatible(tup, strVal(column));
    9631              :             }
    9632              :         }
    9633              : 
    9634              :         /* This column is not already not-null, so add it to the queue */
    9635          315 :         nnconstr = makeNotNullConstraint(column);
    9636              : 
    9637          315 :         newcmd = makeNode(AlterTableCmd);
    9638          315 :         newcmd->subtype = AT_AddConstraint;
    9639              :         /* note we force recurse=true here; see above */
    9640          315 :         newcmd->recurse = true;
    9641          315 :         newcmd->def = (Node *) nnconstr;
    9642              : 
    9643          315 :         ATPrepCmd(wqueue, rel, newcmd, true, false, lockmode, context);
    9644              :     }
    9645              : }
    9646              : 
    9647              : /*
    9648              :  * Verify whether the given not-null constraint is compatible with a
    9649              :  * primary key.  If not, an error is thrown.
    9650              :  */
    9651              : static void
    9652          338 : verifyNotNullPKCompatible(HeapTuple tuple, const char *colname)
    9653              : {
    9654          338 :     Form_pg_constraint conForm = (Form_pg_constraint) GETSTRUCT(tuple);
    9655              : 
    9656          338 :     if (conForm->contype != CONSTRAINT_NOTNULL)
    9657            0 :         elog(ERROR, "constraint %u is not a not-null constraint", conForm->oid);
    9658              : 
    9659              :     /* a NO INHERIT constraint is no good */
    9660          338 :     if (conForm->connoinherit)
    9661            8 :         ereport(ERROR,
    9662              :                 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    9663              :                 errmsg("cannot create primary key on column \"%s\"", colname),
    9664              :         /*- translator: fourth %s is a constraint characteristic such as NOT VALID */
    9665              :                 errdetail("The constraint \"%s\" on column \"%s\" of table \"%s\", marked %s, is incompatible with a primary key.",
    9666              :                           NameStr(conForm->conname), colname,
    9667              :                           get_rel_name(conForm->conrelid), "NO INHERIT"),
    9668              :                 errhint("You might need to make the existing constraint inheritable using %s.",
    9669              :                         "ALTER TABLE ... ALTER CONSTRAINT ... INHERIT"));
    9670              : 
    9671              :     /* an unvalidated constraint is no good */
    9672          330 :     if (!conForm->convalidated)
    9673            8 :         ereport(ERROR,
    9674              :                 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    9675              :                 errmsg("cannot create primary key on column \"%s\"", colname),
    9676              :         /*- translator: fourth %s is a constraint characteristic such as NOT VALID */
    9677              :                 errdetail("The constraint \"%s\" on column \"%s\" of table \"%s\", marked %s, is incompatible with a primary key.",
    9678              :                           NameStr(conForm->conname), colname,
    9679              :                           get_rel_name(conForm->conrelid), "NOT VALID"),
    9680              :                 errhint("You might need to validate it using %s.",
    9681              :                         "ALTER TABLE ... VALIDATE CONSTRAINT"));
    9682          322 : }
    9683              : 
    9684              : /*
    9685              :  * ALTER TABLE ADD INDEX
    9686              :  *
    9687              :  * There is no such command in the grammar, but parse_utilcmd.c converts
    9688              :  * UNIQUE and PRIMARY KEY constraints into AT_AddIndex subcommands.  This lets
    9689              :  * us schedule creation of the index at the appropriate time during ALTER.
    9690              :  *
    9691              :  * Return value is the address of the new index.
    9692              :  */
    9693              : static ObjectAddress
    9694         1065 : ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
    9695              :                IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode)
    9696              : {
    9697              :     bool        check_rights;
    9698              :     bool        skip_build;
    9699              :     bool        quiet;
    9700              :     ObjectAddress address;
    9701              : 
    9702              :     Assert(IsA(stmt, IndexStmt));
    9703              :     Assert(!stmt->concurrent);
    9704              : 
    9705              :     /* The IndexStmt has already been through transformIndexStmt */
    9706              :     Assert(stmt->transformed);
    9707              : 
    9708              :     /* suppress schema rights check when rebuilding existing index */
    9709         1065 :     check_rights = !is_rebuild;
    9710              :     /* skip index build if phase 3 will do it or we're reusing an old one */
    9711         1065 :     skip_build = tab->rewrite > 0 || RelFileNumberIsValid(stmt->oldNumber);
    9712              :     /* suppress notices when rebuilding existing index */
    9713         1065 :     quiet = is_rebuild;
    9714              : 
    9715         1065 :     address = DefineIndex(NULL,
    9716              :                           RelationGetRelid(rel),
    9717              :                           stmt,
    9718              :                           InvalidOid,   /* no predefined OID */
    9719              :                           InvalidOid,   /* no parent index */
    9720              :                           InvalidOid,   /* no parent constraint */
    9721              :                           -1,   /* total_parts unknown */
    9722              :                           true, /* is_alter_table */
    9723              :                           check_rights,
    9724              :                           false,    /* check_not_in_use - we did it already */
    9725              :                           skip_build,
    9726              :                           quiet);
    9727              : 
    9728              :     /*
    9729              :      * If TryReuseIndex() stashed a relfilenumber for us, we used it for the
    9730              :      * new index instead of building from scratch.  Restore associated fields.
    9731              :      * This may store InvalidSubTransactionId in both fields, in which case
    9732              :      * relcache.c will assume it can rebuild the relcache entry.  Hence, do
    9733              :      * this after the CCI that made catalog rows visible to any rebuild.  The
    9734              :      * DROP of the old edition of this index will have scheduled the storage
    9735              :      * for deletion at commit, so cancel that pending deletion.
    9736              :      */
    9737          952 :     if (RelFileNumberIsValid(stmt->oldNumber))
    9738              :     {
    9739           49 :         Relation    irel = index_open(address.objectId, NoLock);
    9740              : 
    9741           49 :         irel->rd_createSubid = stmt->oldCreateSubid;
    9742           49 :         irel->rd_firstRelfilelocatorSubid = stmt->oldFirstRelfilelocatorSubid;
    9743           49 :         RelationPreserveStorage(irel->rd_locator, true);
    9744           49 :         index_close(irel, NoLock);
    9745              :     }
    9746              : 
    9747          952 :     return address;
    9748              : }
    9749              : 
    9750              : /*
    9751              :  * ALTER TABLE ADD STATISTICS
    9752              :  *
    9753              :  * This is no such command in the grammar, but we use this internally to add
    9754              :  * AT_ReAddStatistics subcommands to rebuild extended statistics after a table
    9755              :  * column type change.
    9756              :  */
    9757              : static ObjectAddress
    9758           53 : ATExecAddStatistics(AlteredTableInfo *tab, Relation rel,
    9759              :                     CreateStatsStmt *stmt, bool is_rebuild, LOCKMODE lockmode)
    9760              : {
    9761              :     ObjectAddress address;
    9762              : 
    9763              :     Assert(IsA(stmt, CreateStatsStmt));
    9764              : 
    9765              :     /* The CreateStatsStmt has already been through transformStatsStmt */
    9766              :     Assert(stmt->transformed);
    9767              : 
    9768           53 :     address = CreateStatistics(stmt, !is_rebuild);
    9769              : 
    9770           53 :     return address;
    9771              : }
    9772              : 
    9773              : /*
    9774              :  * ALTER TABLE ADD CONSTRAINT USING INDEX
    9775              :  *
    9776              :  * Returns the address of the new constraint.
    9777              :  */
    9778              : static ObjectAddress
    9779         5933 : ATExecAddIndexConstraint(AlteredTableInfo *tab, Relation rel,
    9780              :                          IndexStmt *stmt, LOCKMODE lockmode)
    9781              : {
    9782         5933 :     Oid         index_oid = stmt->indexOid;
    9783              :     Relation    indexRel;
    9784              :     char       *indexName;
    9785              :     IndexInfo  *indexInfo;
    9786              :     char       *constraintName;
    9787              :     char        constraintType;
    9788              :     ObjectAddress address;
    9789              :     bits16      flags;
    9790              : 
    9791              :     Assert(IsA(stmt, IndexStmt));
    9792              :     Assert(OidIsValid(index_oid));
    9793              :     Assert(stmt->isconstraint);
    9794              : 
    9795              :     /*
    9796              :      * Doing this on partitioned tables is not a simple feature to implement,
    9797              :      * so let's punt for now.
    9798              :      */
    9799         5933 :     if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
    9800            4 :         ereport(ERROR,
    9801              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    9802              :                  errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX is not supported on partitioned tables")));
    9803              : 
    9804         5929 :     indexRel = index_open(index_oid, AccessShareLock);
    9805              : 
    9806         5929 :     indexName = pstrdup(RelationGetRelationName(indexRel));
    9807              : 
    9808         5929 :     indexInfo = BuildIndexInfo(indexRel);
    9809              : 
    9810              :     /* this should have been checked at parse time */
    9811         5929 :     if (!indexInfo->ii_Unique)
    9812            0 :         elog(ERROR, "index \"%s\" is not unique", indexName);
    9813              : 
    9814              :     /*
    9815              :      * Determine name to assign to constraint.  We require a constraint to
    9816              :      * have the same name as the underlying index; therefore, use the index's
    9817              :      * existing name as the default constraint name, and if the user
    9818              :      * explicitly gives some other name for the constraint, rename the index
    9819              :      * to match.
    9820              :      */
    9821         5929 :     constraintName = stmt->idxname;
    9822         5929 :     if (constraintName == NULL)
    9823         5912 :         constraintName = indexName;
    9824           17 :     else if (strcmp(constraintName, indexName) != 0)
    9825              :     {
    9826           13 :         ereport(NOTICE,
    9827              :                 (errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX will rename index \"%s\" to \"%s\"",
    9828              :                         indexName, constraintName)));
    9829           13 :         RenameRelationInternal(index_oid, constraintName, false, true);
    9830              :     }
    9831              : 
    9832              :     /* Extra checks needed if making primary key */
    9833         5929 :     if (stmt->primary)
    9834         3319 :         index_check_primary_key(rel, indexInfo, true, stmt);
    9835              : 
    9836              :     /* Note we currently don't support EXCLUSION constraints here */
    9837         5925 :     if (stmt->primary)
    9838         3315 :         constraintType = CONSTRAINT_PRIMARY;
    9839              :     else
    9840         2610 :         constraintType = CONSTRAINT_UNIQUE;
    9841              : 
    9842              :     /* Create the catalog entries for the constraint */
    9843         5925 :     flags = INDEX_CONSTR_CREATE_UPDATE_INDEX |
    9844              :         INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS |
    9845        11850 :         (stmt->initdeferred ? INDEX_CONSTR_CREATE_INIT_DEFERRED : 0) |
    9846         5925 :         (stmt->deferrable ? INDEX_CONSTR_CREATE_DEFERRABLE : 0) |
    9847         5925 :         (stmt->primary ? INDEX_CONSTR_CREATE_MARK_AS_PRIMARY : 0);
    9848              : 
    9849         5925 :     address = index_constraint_create(rel,
    9850              :                                       index_oid,
    9851              :                                       InvalidOid,
    9852              :                                       indexInfo,
    9853              :                                       constraintName,
    9854              :                                       constraintType,
    9855              :                                       flags,
    9856              :                                       allowSystemTableMods,
    9857              :                                       false);   /* is_internal */
    9858              : 
    9859         5925 :     index_close(indexRel, NoLock);
    9860              : 
    9861         5925 :     return address;
    9862              : }
    9863              : 
    9864              : /*
    9865              :  * ALTER TABLE ADD CONSTRAINT
    9866              :  *
    9867              :  * Return value is the address of the new constraint; if no constraint was
    9868              :  * added, InvalidObjectAddress is returned.
    9869              :  */
    9870              : static ObjectAddress
    9871         7606 : ATExecAddConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
    9872              :                     Constraint *newConstraint, bool recurse, bool is_readd,
    9873              :                     LOCKMODE lockmode)
    9874              : {
    9875         7606 :     ObjectAddress address = InvalidObjectAddress;
    9876              : 
    9877              :     Assert(IsA(newConstraint, Constraint));
    9878              : 
    9879              :     /*
    9880              :      * Currently, we only expect to see CONSTR_CHECK, CONSTR_NOTNULL and
    9881              :      * CONSTR_FOREIGN nodes arriving here (see the preprocessing done in
    9882              :      * parse_utilcmd.c).
    9883              :      */
    9884         7606 :     switch (newConstraint->contype)
    9885              :     {
    9886         5867 :         case CONSTR_CHECK:
    9887              :         case CONSTR_NOTNULL:
    9888              :             address =
    9889         5867 :                 ATAddCheckNNConstraint(wqueue, tab, rel,
    9890              :                                        newConstraint, recurse, false, is_readd,
    9891              :                                        lockmode);
    9892         5767 :             break;
    9893              : 
    9894         1739 :         case CONSTR_FOREIGN:
    9895              : 
    9896              :             /*
    9897              :              * Assign or validate constraint name
    9898              :              */
    9899         1739 :             if (newConstraint->conname)
    9900              :             {
    9901          748 :                 if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
    9902              :                                          RelationGetRelid(rel),
    9903          748 :                                          newConstraint->conname))
    9904            0 :                     ereport(ERROR,
    9905              :                             (errcode(ERRCODE_DUPLICATE_OBJECT),
    9906              :                              errmsg("constraint \"%s\" for relation \"%s\" already exists",
    9907              :                                     newConstraint->conname,
    9908              :                                     RelationGetRelationName(rel))));
    9909              :             }
    9910              :             else
    9911          991 :                 newConstraint->conname =
    9912          991 :                     ChooseConstraintName(RelationGetRelationName(rel),
    9913          991 :                                          ChooseForeignKeyConstraintNameAddition(newConstraint->fk_attrs),
    9914              :                                          "fkey",
    9915          991 :                                          RelationGetNamespace(rel),
    9916              :                                          NIL);
    9917              : 
    9918         1739 :             address = ATAddForeignKeyConstraint(wqueue, tab, rel,
    9919              :                                                 newConstraint,
    9920              :                                                 recurse, false,
    9921              :                                                 lockmode);
    9922         1374 :             break;
    9923              : 
    9924            0 :         default:
    9925            0 :             elog(ERROR, "unrecognized constraint type: %d",
    9926              :                  (int) newConstraint->contype);
    9927              :     }
    9928              : 
    9929         7141 :     return address;
    9930              : }
    9931              : 
    9932              : /*
    9933              :  * Generate the column-name portion of the constraint name for a new foreign
    9934              :  * key given the list of column names that reference the referenced
    9935              :  * table.  This will be passed to ChooseConstraintName along with the parent
    9936              :  * table name and the "fkey" suffix.
    9937              :  *
    9938              :  * We know that less than NAMEDATALEN characters will actually be used, so we
    9939              :  * can truncate the result once we've generated that many.
    9940              :  *
    9941              :  * XXX see also ChooseExtendedStatisticNameAddition and
    9942              :  * ChooseIndexNameAddition.
    9943              :  */
    9944              : static char *
    9945          991 : ChooseForeignKeyConstraintNameAddition(List *colnames)
    9946              : {
    9947              :     char        buf[NAMEDATALEN * 2];
    9948          991 :     int         buflen = 0;
    9949              :     ListCell   *lc;
    9950              : 
    9951          991 :     buf[0] = '\0';
    9952         2260 :     foreach(lc, colnames)
    9953              :     {
    9954         1269 :         const char *name = strVal(lfirst(lc));
    9955              : 
    9956         1269 :         if (buflen > 0)
    9957          278 :             buf[buflen++] = '_';    /* insert _ between names */
    9958              : 
    9959              :         /*
    9960              :          * At this point we have buflen <= NAMEDATALEN.  name should be less
    9961              :          * than NAMEDATALEN already, but use strlcpy for paranoia.
    9962              :          */
    9963         1269 :         strlcpy(buf + buflen, name, NAMEDATALEN);
    9964         1269 :         buflen += strlen(buf + buflen);
    9965         1269 :         if (buflen >= NAMEDATALEN)
    9966            0 :             break;
    9967              :     }
    9968          991 :     return pstrdup(buf);
    9969              : }
    9970              : 
    9971              : /*
    9972              :  * Add a check or not-null constraint to a single table and its children.
    9973              :  * Returns the address of the constraint added to the parent relation,
    9974              :  * if one gets added, or InvalidObjectAddress otherwise.
    9975              :  *
    9976              :  * Subroutine for ATExecAddConstraint.
    9977              :  *
    9978              :  * We must recurse to child tables during execution, rather than using
    9979              :  * ALTER TABLE's normal prep-time recursion.  The reason is that all the
    9980              :  * constraints *must* be given the same name, else they won't be seen as
    9981              :  * related later.  If the user didn't explicitly specify a name, then
    9982              :  * AddRelationNewConstraints would normally assign different names to the
    9983              :  * child constraints.  To fix that, we must capture the name assigned at
    9984              :  * the parent table and pass that down.
    9985              :  */
    9986              : static ObjectAddress
    9987         6518 : ATAddCheckNNConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
    9988              :                        Constraint *constr, bool recurse, bool recursing,
    9989              :                        bool is_readd, LOCKMODE lockmode)
    9990              : {
    9991              :     List       *newcons;
    9992              :     ListCell   *lcon;
    9993              :     List       *children;
    9994              :     ListCell   *child;
    9995         6518 :     ObjectAddress address = InvalidObjectAddress;
    9996              : 
    9997              :     /* Guard against stack overflow due to overly deep inheritance tree. */
    9998         6518 :     check_stack_depth();
    9999              : 
   10000              :     /* At top level, permission check was done in ATPrepCmd, else do it */
   10001         6518 :     if (recursing)
   10002          651 :         ATSimplePermissions(AT_AddConstraint, rel,
   10003              :                             ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
   10004              : 
   10005              :     /*
   10006              :      * Call AddRelationNewConstraints to do the work, making sure it works on
   10007              :      * a copy of the Constraint so transformExpr can't modify the original. It
   10008              :      * returns a list of cooked constraints.
   10009              :      *
   10010              :      * If the constraint ends up getting merged with a pre-existing one, it's
   10011              :      * omitted from the returned list, which is what we want: we do not need
   10012              :      * to do any validation work.  That can only happen at child tables,
   10013              :      * though, since we disallow merging at the top level.
   10014              :      */
   10015         6518 :     newcons = AddRelationNewConstraints(rel, NIL,
   10016         6518 :                                         list_make1(copyObject(constr)),
   10017         6518 :                                         recursing || is_readd,  /* allow_merge */
   10018              :                                         !recursing, /* is_local */
   10019              :                                         is_readd,   /* is_internal */
   10020        13036 :                                         NULL);  /* queryString not available
   10021              :                                                  * here */
   10022              : 
   10023              :     /* we don't expect more than one constraint here */
   10024              :     Assert(list_length(newcons) <= 1);
   10025              : 
   10026              :     /* Add each to-be-validated constraint to Phase 3's queue */
   10027        12714 :     foreach(lcon, newcons)
   10028              :     {
   10029         6292 :         CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
   10030              : 
   10031         6292 :         if (!ccon->skip_validation && ccon->contype != CONSTR_NOTNULL)
   10032              :         {
   10033              :             NewConstraint *newcon;
   10034              : 
   10035          743 :             newcon = palloc0_object(NewConstraint);
   10036          743 :             newcon->name = ccon->name;
   10037          743 :             newcon->contype = ccon->contype;
   10038          743 :             newcon->qual = ccon->expr;
   10039              : 
   10040          743 :             tab->constraints = lappend(tab->constraints, newcon);
   10041              :         }
   10042              : 
   10043              :         /* Save the actually assigned name if it was defaulted */
   10044         6292 :         if (constr->conname == NULL)
   10045         4942 :             constr->conname = ccon->name;
   10046              : 
   10047              :         /*
   10048              :          * If adding a valid not-null constraint, set the pg_attribute flag
   10049              :          * and tell phase 3 to verify existing rows, if needed.  For an
   10050              :          * invalid constraint, just set attnotnull, without queueing
   10051              :          * verification.
   10052              :          */
   10053         6292 :         if (constr->contype == CONSTR_NOTNULL)
   10054         5244 :             set_attnotnull(wqueue, rel, ccon->attnum,
   10055         5244 :                            !constr->skip_validation,
   10056         5244 :                            !constr->skip_validation);
   10057              : 
   10058         6292 :         ObjectAddressSet(address, ConstraintRelationId, ccon->conoid);
   10059              :     }
   10060              : 
   10061              :     /* At this point we must have a locked-down name to use */
   10062              :     Assert(newcons == NIL || constr->conname != NULL);
   10063              : 
   10064              :     /* Advance command counter in case same table is visited multiple times */
   10065         6422 :     CommandCounterIncrement();
   10066              : 
   10067              :     /*
   10068              :      * If the constraint got merged with an existing constraint, we're done.
   10069              :      * We mustn't recurse to child tables in this case, because they've
   10070              :      * already got the constraint, and visiting them again would lead to an
   10071              :      * incorrect value for coninhcount.
   10072              :      */
   10073         6422 :     if (newcons == NIL)
   10074          130 :         return address;
   10075              : 
   10076              :     /*
   10077              :      * If adding a NO INHERIT constraint, no need to find our children.
   10078              :      */
   10079         6292 :     if (constr->is_no_inherit)
   10080           56 :         return address;
   10081              : 
   10082              :     /*
   10083              :      * Propagate to children as appropriate.  Unlike most other ALTER
   10084              :      * routines, we have to do this one level of recursion at a time; we can't
   10085              :      * use find_all_inheritors to do it in one pass.
   10086              :      */
   10087              :     children =
   10088         6236 :         find_inheritance_children(RelationGetRelid(rel), lockmode);
   10089              : 
   10090              :     /*
   10091              :      * Check if ONLY was specified with ALTER TABLE.  If so, allow the
   10092              :      * constraint creation only if there are no children currently. Error out
   10093              :      * otherwise.
   10094              :      */
   10095         6236 :     if (!recurse && children != NIL)
   10096            4 :         ereport(ERROR,
   10097              :                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   10098              :                  errmsg("constraint must be added to child tables too")));
   10099              : 
   10100              :     /*
   10101              :      * Recurse to create the constraint on each child.
   10102              :      */
   10103         6863 :     foreach(child, children)
   10104              :     {
   10105          651 :         Oid         childrelid = lfirst_oid(child);
   10106              :         Relation    childrel;
   10107              :         AlteredTableInfo *childtab;
   10108              : 
   10109              :         /* find_inheritance_children already got lock */
   10110          651 :         childrel = table_open(childrelid, NoLock);
   10111          651 :         CheckAlterTableIsSafe(childrel);
   10112              : 
   10113              :         /* Find or create work queue entry for this table */
   10114          651 :         childtab = ATGetQueueEntry(wqueue, childrel);
   10115              : 
   10116              :         /* Recurse to this child */
   10117          651 :         ATAddCheckNNConstraint(wqueue, childtab, childrel,
   10118              :                                constr, recurse, true, is_readd, lockmode);
   10119              : 
   10120          631 :         table_close(childrel, NoLock);
   10121              :     }
   10122              : 
   10123         6212 :     return address;
   10124              : }
   10125              : 
   10126              : /*
   10127              :  * Add a foreign-key constraint to a single table; return the new constraint's
   10128              :  * address.
   10129              :  *
   10130              :  * Subroutine for ATExecAddConstraint.  Must already hold exclusive
   10131              :  * lock on the rel, and have done appropriate validity checks for it.
   10132              :  * We do permissions checks here, however.
   10133              :  *
   10134              :  * When the referenced or referencing tables (or both) are partitioned,
   10135              :  * multiple pg_constraint rows are required -- one for each partitioned table
   10136              :  * and each partition on each side (fortunately, not one for every combination
   10137              :  * thereof).  We also need action triggers on each leaf partition on the
   10138              :  * referenced side, and check triggers on each leaf partition on the
   10139              :  * referencing side.
   10140              :  */
   10141              : static ObjectAddress
   10142         1739 : ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
   10143              :                           Constraint *fkconstraint,
   10144              :                           bool recurse, bool recursing, LOCKMODE lockmode)
   10145              : {
   10146              :     Relation    pkrel;
   10147         1739 :     int16       pkattnum[INDEX_MAX_KEYS] = {0};
   10148         1739 :     int16       fkattnum[INDEX_MAX_KEYS] = {0};
   10149         1739 :     Oid         pktypoid[INDEX_MAX_KEYS] = {0};
   10150         1739 :     Oid         fktypoid[INDEX_MAX_KEYS] = {0};
   10151         1739 :     Oid         pkcolloid[INDEX_MAX_KEYS] = {0};
   10152         1739 :     Oid         fkcolloid[INDEX_MAX_KEYS] = {0};
   10153         1739 :     Oid         opclasses[INDEX_MAX_KEYS] = {0};
   10154         1739 :     Oid         pfeqoperators[INDEX_MAX_KEYS] = {0};
   10155         1739 :     Oid         ppeqoperators[INDEX_MAX_KEYS] = {0};
   10156         1739 :     Oid         ffeqoperators[INDEX_MAX_KEYS] = {0};
   10157         1739 :     int16       fkdelsetcols[INDEX_MAX_KEYS] = {0};
   10158              :     bool        with_period;
   10159              :     bool        pk_has_without_overlaps;
   10160              :     int         i;
   10161              :     int         numfks,
   10162              :                 numpks,
   10163              :                 numfkdelsetcols;
   10164              :     Oid         indexOid;
   10165              :     bool        old_check_ok;
   10166              :     ObjectAddress address;
   10167         1739 :     ListCell   *old_pfeqop_item = list_head(fkconstraint->old_conpfeqop);
   10168              : 
   10169              :     /*
   10170              :      * Grab ShareRowExclusiveLock on the pk table, so that someone doesn't
   10171              :      * delete rows out from under us.
   10172              :      */
   10173         1739 :     if (OidIsValid(fkconstraint->old_pktable_oid))
   10174           48 :         pkrel = table_open(fkconstraint->old_pktable_oid, ShareRowExclusiveLock);
   10175              :     else
   10176         1691 :         pkrel = table_openrv(fkconstraint->pktable, ShareRowExclusiveLock);
   10177              : 
   10178              :     /*
   10179              :      * Validity checks (permission checks wait till we have the column
   10180              :      * numbers)
   10181              :      */
   10182         1735 :     if (!recurse && rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
   10183            4 :         ereport(ERROR,
   10184              :                 errcode(ERRCODE_WRONG_OBJECT_TYPE),
   10185              :                 errmsg("cannot use ONLY for foreign key on partitioned table \"%s\" referencing relation \"%s\"",
   10186              :                        RelationGetRelationName(rel),
   10187              :                        RelationGetRelationName(pkrel)));
   10188              : 
   10189         1731 :     if (pkrel->rd_rel->relkind != RELKIND_RELATION &&
   10190          236 :         pkrel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
   10191            0 :         ereport(ERROR,
   10192              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   10193              :                  errmsg("referenced relation \"%s\" is not a table",
   10194              :                         RelationGetRelationName(pkrel))));
   10195              : 
   10196         1731 :     if (!allowSystemTableMods && IsSystemRelation(pkrel))
   10197            1 :         ereport(ERROR,
   10198              :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
   10199              :                  errmsg("permission denied: \"%s\" is a system catalog",
   10200              :                         RelationGetRelationName(pkrel))));
   10201              : 
   10202              :     /*
   10203              :      * References from permanent or unlogged tables to temp tables, and from
   10204              :      * permanent tables to unlogged tables, are disallowed because the
   10205              :      * referenced data can vanish out from under us.  References from temp
   10206              :      * tables to any other table type are also disallowed, because other
   10207              :      * backends might need to run the RI triggers on the perm table, but they
   10208              :      * can't reliably see tuples in the local buffers of other backends.
   10209              :      */
   10210         1730 :     switch (rel->rd_rel->relpersistence)
   10211              :     {
   10212         1537 :         case RELPERSISTENCE_PERMANENT:
   10213         1537 :             if (!RelationIsPermanent(pkrel))
   10214            0 :                 ereport(ERROR,
   10215              :                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   10216              :                          errmsg("constraints on permanent tables may reference only permanent tables")));
   10217         1537 :             break;
   10218            8 :         case RELPERSISTENCE_UNLOGGED:
   10219            8 :             if (!RelationIsPermanent(pkrel)
   10220            8 :                 && pkrel->rd_rel->relpersistence != RELPERSISTENCE_UNLOGGED)
   10221            0 :                 ereport(ERROR,
   10222              :                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   10223              :                          errmsg("constraints on unlogged tables may reference only permanent or unlogged tables")));
   10224            8 :             break;
   10225          185 :         case RELPERSISTENCE_TEMP:
   10226          185 :             if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
   10227            0 :                 ereport(ERROR,
   10228              :                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   10229              :                          errmsg("constraints on temporary tables may reference only temporary tables")));
   10230          185 :             if (!pkrel->rd_islocaltemp || !rel->rd_islocaltemp)
   10231            0 :                 ereport(ERROR,
   10232              :                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   10233              :                          errmsg("constraints on temporary tables must involve temporary tables of this session")));
   10234          185 :             break;
   10235              :     }
   10236              : 
   10237              :     /*
   10238              :      * Look up the referencing attributes to make sure they exist, and record
   10239              :      * their attnums and type and collation OIDs.
   10240              :      */
   10241         1730 :     numfks = transformColumnNameList(RelationGetRelid(rel),
   10242              :                                      fkconstraint->fk_attrs,
   10243              :                                      fkattnum, fktypoid, fkcolloid);
   10244         1710 :     with_period = fkconstraint->fk_with_period || fkconstraint->pk_with_period;
   10245         1710 :     if (with_period && !fkconstraint->fk_with_period)
   10246           16 :         ereport(ERROR,
   10247              :                 errcode(ERRCODE_INVALID_FOREIGN_KEY),
   10248              :                 errmsg("foreign key uses PERIOD on the referenced table but not the referencing table"));
   10249              : 
   10250         1694 :     numfkdelsetcols = transformColumnNameList(RelationGetRelid(rel),
   10251              :                                               fkconstraint->fk_del_set_cols,
   10252              :                                               fkdelsetcols, NULL, NULL);
   10253         1690 :     numfkdelsetcols = validateFkOnDeleteSetColumns(numfks, fkattnum,
   10254              :                                                    numfkdelsetcols,
   10255              :                                                    fkdelsetcols,
   10256              :                                                    fkconstraint->fk_del_set_cols);
   10257              : 
   10258              :     /*
   10259              :      * If the attribute list for the referenced table was omitted, lookup the
   10260              :      * definition of the primary key and use it.  Otherwise, validate the
   10261              :      * supplied attribute list.  In either case, discover the index OID and
   10262              :      * index opclasses, and the attnums and type and collation OIDs of the
   10263              :      * attributes.
   10264              :      */
   10265         1686 :     if (fkconstraint->pk_attrs == NIL)
   10266              :     {
   10267          811 :         numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
   10268              :                                             &fkconstraint->pk_attrs,
   10269              :                                             pkattnum, pktypoid, pkcolloid,
   10270              :                                             opclasses, &pk_has_without_overlaps);
   10271              : 
   10272              :         /* If the primary key uses WITHOUT OVERLAPS, the fk must use PERIOD */
   10273          811 :         if (pk_has_without_overlaps && !fkconstraint->fk_with_period)
   10274           16 :             ereport(ERROR,
   10275              :                     errcode(ERRCODE_INVALID_FOREIGN_KEY),
   10276              :                     errmsg("foreign key uses PERIOD on the referenced table but not the referencing table"));
   10277              :     }
   10278              :     else
   10279              :     {
   10280          875 :         numpks = transformColumnNameList(RelationGetRelid(pkrel),
   10281              :                                          fkconstraint->pk_attrs,
   10282              :                                          pkattnum, pktypoid, pkcolloid);
   10283              : 
   10284              :         /* Since we got pk_attrs, one should be a period. */
   10285          855 :         if (with_period && !fkconstraint->pk_with_period)
   10286           16 :             ereport(ERROR,
   10287              :                     errcode(ERRCODE_INVALID_FOREIGN_KEY),
   10288              :                     errmsg("foreign key uses PERIOD on the referencing table but not the referenced table"));
   10289              : 
   10290              :         /* Look for an index matching the column list */
   10291          839 :         indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
   10292              :                                            with_period, opclasses, &pk_has_without_overlaps);
   10293              :     }
   10294              : 
   10295              :     /*
   10296              :      * If the referenced primary key has WITHOUT OVERLAPS, the foreign key
   10297              :      * must use PERIOD.
   10298              :      */
   10299         1610 :     if (pk_has_without_overlaps && !with_period)
   10300            8 :         ereport(ERROR,
   10301              :                 errcode(ERRCODE_INVALID_FOREIGN_KEY),
   10302              :                 errmsg("foreign key must use PERIOD when referencing a primary key using WITHOUT OVERLAPS"));
   10303              : 
   10304              :     /*
   10305              :      * Now we can check permissions.
   10306              :      */
   10307         1602 :     checkFkeyPermissions(pkrel, pkattnum, numpks);
   10308              : 
   10309              :     /*
   10310              :      * Check some things for generated columns.
   10311              :      */
   10312         3769 :     for (i = 0; i < numfks; i++)
   10313              :     {
   10314         2187 :         char        attgenerated = TupleDescAttr(RelationGetDescr(rel), fkattnum[i] - 1)->attgenerated;
   10315              : 
   10316         2187 :         if (attgenerated)
   10317              :         {
   10318              :             /*
   10319              :              * Check restrictions on UPDATE/DELETE actions, per SQL standard
   10320              :              */
   10321           32 :             if (fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETNULL ||
   10322           32 :                 fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETDEFAULT ||
   10323           32 :                 fkconstraint->fk_upd_action == FKCONSTR_ACTION_CASCADE)
   10324            8 :                 ereport(ERROR,
   10325              :                         (errcode(ERRCODE_SYNTAX_ERROR),
   10326              :                          errmsg("invalid %s action for foreign key constraint containing generated column",
   10327              :                                 "ON UPDATE")));
   10328           24 :             if (fkconstraint->fk_del_action == FKCONSTR_ACTION_SETNULL ||
   10329           16 :                 fkconstraint->fk_del_action == FKCONSTR_ACTION_SETDEFAULT)
   10330            8 :                 ereport(ERROR,
   10331              :                         (errcode(ERRCODE_SYNTAX_ERROR),
   10332              :                          errmsg("invalid %s action for foreign key constraint containing generated column",
   10333              :                                 "ON DELETE")));
   10334              :         }
   10335              : 
   10336              :         /*
   10337              :          * FKs on virtual columns are not supported.  This would require
   10338              :          * various additional support in ri_triggers.c, including special
   10339              :          * handling in ri_NullCheck(), ri_KeysEqual(),
   10340              :          * RI_FKey_fk_upd_check_required() (since all virtual columns appear
   10341              :          * as NULL there).  Also not really practical as long as you can't
   10342              :          * index virtual columns.
   10343              :          */
   10344         2171 :         if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
   10345            4 :             ereport(ERROR,
   10346              :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   10347              :                      errmsg("foreign key constraints on virtual generated columns are not supported")));
   10348              :     }
   10349              : 
   10350              :     /*
   10351              :      * Some actions are currently unsupported for foreign keys using PERIOD.
   10352              :      */
   10353         1582 :     if (fkconstraint->fk_with_period)
   10354              :     {
   10355          178 :         if (fkconstraint->fk_upd_action == FKCONSTR_ACTION_RESTRICT ||
   10356          170 :             fkconstraint->fk_upd_action == FKCONSTR_ACTION_CASCADE ||
   10357          158 :             fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETNULL ||
   10358          146 :             fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETDEFAULT)
   10359           44 :             ereport(ERROR,
   10360              :                     errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   10361              :                     errmsg("unsupported %s action for foreign key constraint using PERIOD",
   10362              :                            "ON UPDATE"));
   10363              : 
   10364          134 :         if (fkconstraint->fk_del_action == FKCONSTR_ACTION_RESTRICT ||
   10365          130 :             fkconstraint->fk_del_action == FKCONSTR_ACTION_CASCADE ||
   10366          130 :             fkconstraint->fk_del_action == FKCONSTR_ACTION_SETNULL ||
   10367          130 :             fkconstraint->fk_del_action == FKCONSTR_ACTION_SETDEFAULT)
   10368            4 :             ereport(ERROR,
   10369              :                     errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   10370              :                     errmsg("unsupported %s action for foreign key constraint using PERIOD",
   10371              :                            "ON DELETE"));
   10372              :     }
   10373              : 
   10374              :     /*
   10375              :      * Look up the equality operators to use in the constraint.
   10376              :      *
   10377              :      * Note that we have to be careful about the difference between the actual
   10378              :      * PK column type and the opclass' declared input type, which might be
   10379              :      * only binary-compatible with it.  The declared opcintype is the right
   10380              :      * thing to probe pg_amop with.
   10381              :      */
   10382         1534 :     if (numfks != numpks)
   10383            0 :         ereport(ERROR,
   10384              :                 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
   10385              :                  errmsg("number of referencing and referenced columns for foreign key disagree")));
   10386              : 
   10387              :     /*
   10388              :      * On the strength of a previous constraint, we might avoid scanning
   10389              :      * tables to validate this one.  See below.
   10390              :      */
   10391         1534 :     old_check_ok = (fkconstraint->old_conpfeqop != NIL);
   10392              :     Assert(!old_check_ok || numfks == list_length(fkconstraint->old_conpfeqop));
   10393              : 
   10394         3349 :     for (i = 0; i < numpks; i++)
   10395              :     {
   10396         1975 :         Oid         pktype = pktypoid[i];
   10397         1975 :         Oid         fktype = fktypoid[i];
   10398              :         Oid         fktyped;
   10399         1975 :         Oid         pkcoll = pkcolloid[i];
   10400         1975 :         Oid         fkcoll = fkcolloid[i];
   10401              :         HeapTuple   cla_ht;
   10402              :         Form_pg_opclass cla_tup;
   10403              :         Oid         amid;
   10404              :         Oid         opfamily;
   10405              :         Oid         opcintype;
   10406              :         bool        for_overlaps;
   10407              :         CompareType cmptype;
   10408              :         Oid         pfeqop;
   10409              :         Oid         ppeqop;
   10410              :         Oid         ffeqop;
   10411              :         int16       eqstrategy;
   10412              :         Oid         pfeqop_right;
   10413              : 
   10414              :         /* We need several fields out of the pg_opclass entry */
   10415         1975 :         cla_ht = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclasses[i]));
   10416         1975 :         if (!HeapTupleIsValid(cla_ht))
   10417            0 :             elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
   10418         1975 :         cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
   10419         1975 :         amid = cla_tup->opcmethod;
   10420         1975 :         opfamily = cla_tup->opcfamily;
   10421         1975 :         opcintype = cla_tup->opcintype;
   10422         1975 :         ReleaseSysCache(cla_ht);
   10423              : 
   10424              :         /*
   10425              :          * Get strategy number from index AM.
   10426              :          *
   10427              :          * For a normal foreign-key constraint, this should not fail, since we
   10428              :          * already checked that the index is unique and should therefore have
   10429              :          * appropriate equal operators.  For a period foreign key, this could
   10430              :          * fail if we selected a non-matching exclusion constraint earlier.
   10431              :          * (XXX Maybe we should do these lookups earlier so we don't end up
   10432              :          * doing that.)
   10433              :          */
   10434         1975 :         for_overlaps = with_period && i == numpks - 1;
   10435         1975 :         cmptype = for_overlaps ? COMPARE_OVERLAP : COMPARE_EQ;
   10436         1975 :         eqstrategy = IndexAmTranslateCompareType(cmptype, amid, opfamily, true);
   10437         1975 :         if (eqstrategy == InvalidStrategy)
   10438            0 :             ereport(ERROR,
   10439              :                     errcode(ERRCODE_UNDEFINED_OBJECT),
   10440              :                     for_overlaps
   10441              :                     ? errmsg("could not identify an overlaps operator for foreign key")
   10442              :                     : errmsg("could not identify an equality operator for foreign key"),
   10443              :                     errdetail("Could not translate compare type %d for operator family \"%s\" of access method \"%s\".",
   10444              :                               cmptype, get_opfamily_name(opfamily, false), get_am_name(amid)));
   10445              : 
   10446              :         /*
   10447              :          * There had better be a primary equality operator for the index.
   10448              :          * We'll use it for PK = PK comparisons.
   10449              :          */
   10450         1975 :         ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
   10451              :                                      eqstrategy);
   10452              : 
   10453         1975 :         if (!OidIsValid(ppeqop))
   10454            0 :             elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
   10455              :                  eqstrategy, opcintype, opcintype, opfamily);
   10456              : 
   10457              :         /*
   10458              :          * Are there equality operators that take exactly the FK type? Assume
   10459              :          * we should look through any domain here.
   10460              :          */
   10461         1975 :         fktyped = getBaseType(fktype);
   10462              : 
   10463         1975 :         pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
   10464              :                                      eqstrategy);
   10465         1975 :         if (OidIsValid(pfeqop))
   10466              :         {
   10467         1526 :             pfeqop_right = fktyped;
   10468         1526 :             ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
   10469              :                                          eqstrategy);
   10470              :         }
   10471              :         else
   10472              :         {
   10473              :             /* keep compiler quiet */
   10474          449 :             pfeqop_right = InvalidOid;
   10475          449 :             ffeqop = InvalidOid;
   10476              :         }
   10477              : 
   10478         1975 :         if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
   10479              :         {
   10480              :             /*
   10481              :              * Otherwise, look for an implicit cast from the FK type to the
   10482              :              * opcintype, and if found, use the primary equality operator.
   10483              :              * This is a bit tricky because opcintype might be a polymorphic
   10484              :              * type such as ANYARRAY or ANYENUM; so what we have to test is
   10485              :              * whether the two actual column types can be concurrently cast to
   10486              :              * that type.  (Otherwise, we'd fail to reject combinations such
   10487              :              * as int[] and point[].)
   10488              :              */
   10489              :             Oid         input_typeids[2];
   10490              :             Oid         target_typeids[2];
   10491              : 
   10492          449 :             input_typeids[0] = pktype;
   10493          449 :             input_typeids[1] = fktype;
   10494          449 :             target_typeids[0] = opcintype;
   10495          449 :             target_typeids[1] = opcintype;
   10496          449 :             if (can_coerce_type(2, input_typeids, target_typeids,
   10497              :                                 COERCION_IMPLICIT))
   10498              :             {
   10499          297 :                 pfeqop = ffeqop = ppeqop;
   10500          297 :                 pfeqop_right = opcintype;
   10501              :             }
   10502              :         }
   10503              : 
   10504         1975 :         if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
   10505          152 :             ereport(ERROR,
   10506              :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
   10507              :                      errmsg("foreign key constraint \"%s\" cannot be implemented",
   10508              :                             fkconstraint->conname),
   10509              :                      errdetail("Key columns \"%s\" of the referencing table and \"%s\" of the referenced table "
   10510              :                                "are of incompatible types: %s and %s.",
   10511              :                                strVal(list_nth(fkconstraint->fk_attrs, i)),
   10512              :                                strVal(list_nth(fkconstraint->pk_attrs, i)),
   10513              :                                format_type_be(fktype),
   10514              :                                format_type_be(pktype))));
   10515              : 
   10516              :         /*
   10517              :          * This shouldn't be possible, but better check to make sure we have a
   10518              :          * consistent state for the check below.
   10519              :          */
   10520         1823 :         if ((OidIsValid(pkcoll) && !OidIsValid(fkcoll)) || (!OidIsValid(pkcoll) && OidIsValid(fkcoll)))
   10521            0 :             elog(ERROR, "key columns are not both collatable");
   10522              : 
   10523         1823 :         if (OidIsValid(pkcoll) && OidIsValid(fkcoll))
   10524              :         {
   10525              :             bool        pkcolldet;
   10526              :             bool        fkcolldet;
   10527              : 
   10528           69 :             pkcolldet = get_collation_isdeterministic(pkcoll);
   10529           69 :             fkcolldet = get_collation_isdeterministic(fkcoll);
   10530              : 
   10531              :             /*
   10532              :              * SQL requires that both collations are the same.  This is
   10533              :              * because we need a consistent notion of equality on both
   10534              :              * columns.  We relax this by allowing different collations if
   10535              :              * they are both deterministic.  (This is also for backward
   10536              :              * compatibility, because PostgreSQL has always allowed this.)
   10537              :              */
   10538           69 :             if ((!pkcolldet || !fkcolldet) && pkcoll != fkcoll)
   10539            8 :                 ereport(ERROR,
   10540              :                         (errcode(ERRCODE_COLLATION_MISMATCH),
   10541              :                          errmsg("foreign key constraint \"%s\" cannot be implemented", fkconstraint->conname),
   10542              :                          errdetail("Key columns \"%s\" of the referencing table and \"%s\" of the referenced table "
   10543              :                                    "have incompatible collations: \"%s\" and \"%s\".  "
   10544              :                                    "If either collation is nondeterministic, then both collations have to be the same.",
   10545              :                                    strVal(list_nth(fkconstraint->fk_attrs, i)),
   10546              :                                    strVal(list_nth(fkconstraint->pk_attrs, i)),
   10547              :                                    get_collation_name(fkcoll),
   10548              :                                    get_collation_name(pkcoll))));
   10549              :         }
   10550              : 
   10551         1815 :         if (old_check_ok)
   10552              :         {
   10553              :             /*
   10554              :              * When a pfeqop changes, revalidate the constraint.  We could
   10555              :              * permit intra-opfamily changes, but that adds subtle complexity
   10556              :              * without any concrete benefit for core types.  We need not
   10557              :              * assess ppeqop or ffeqop, which RI_Initial_Check() does not use.
   10558              :              */
   10559            4 :             old_check_ok = (pfeqop == lfirst_oid(old_pfeqop_item));
   10560            4 :             old_pfeqop_item = lnext(fkconstraint->old_conpfeqop,
   10561              :                                     old_pfeqop_item);
   10562              :         }
   10563         1815 :         if (old_check_ok)
   10564              :         {
   10565              :             Oid         old_fktype;
   10566              :             Oid         new_fktype;
   10567              :             CoercionPathType old_pathtype;
   10568              :             CoercionPathType new_pathtype;
   10569              :             Oid         old_castfunc;
   10570              :             Oid         new_castfunc;
   10571              :             Oid         old_fkcoll;
   10572              :             Oid         new_fkcoll;
   10573            4 :             Form_pg_attribute attr = TupleDescAttr(tab->oldDesc,
   10574            4 :                                                    fkattnum[i] - 1);
   10575              : 
   10576              :             /*
   10577              :              * Identify coercion pathways from each of the old and new FK-side
   10578              :              * column types to the right (foreign) operand type of the pfeqop.
   10579              :              * We may assume that pg_constraint.conkey is not changing.
   10580              :              */
   10581            4 :             old_fktype = attr->atttypid;
   10582            4 :             new_fktype = fktype;
   10583            4 :             old_pathtype = findFkeyCast(pfeqop_right, old_fktype,
   10584              :                                         &old_castfunc);
   10585            4 :             new_pathtype = findFkeyCast(pfeqop_right, new_fktype,
   10586              :                                         &new_castfunc);
   10587              : 
   10588            4 :             old_fkcoll = attr->attcollation;
   10589            4 :             new_fkcoll = fkcoll;
   10590              : 
   10591              :             /*
   10592              :              * Upon a change to the cast from the FK column to its pfeqop
   10593              :              * operand, revalidate the constraint.  For this evaluation, a
   10594              :              * binary coercion cast is equivalent to no cast at all.  While
   10595              :              * type implementors should design implicit casts with an eye
   10596              :              * toward consistency of operations like equality, we cannot
   10597              :              * assume here that they have done so.
   10598              :              *
   10599              :              * A function with a polymorphic argument could change behavior
   10600              :              * arbitrarily in response to get_fn_expr_argtype().  Therefore,
   10601              :              * when the cast destination is polymorphic, we only avoid
   10602              :              * revalidation if the input type has not changed at all.  Given
   10603              :              * just the core data types and operator classes, this requirement
   10604              :              * prevents no would-be optimizations.
   10605              :              *
   10606              :              * If the cast converts from a base type to a domain thereon, then
   10607              :              * that domain type must be the opcintype of the unique index.
   10608              :              * Necessarily, the primary key column must then be of the domain
   10609              :              * type.  Since the constraint was previously valid, all values on
   10610              :              * the foreign side necessarily exist on the primary side and in
   10611              :              * turn conform to the domain.  Consequently, we need not treat
   10612              :              * domains specially here.
   10613              :              *
   10614              :              * If the collation changes, revalidation is required, unless both
   10615              :              * collations are deterministic, because those share the same
   10616              :              * notion of equality (because texteq reduces to bitwise
   10617              :              * equality).
   10618              :              *
   10619              :              * We need not directly consider the PK type.  It's necessarily
   10620              :              * binary coercible to the opcintype of the unique index column,
   10621              :              * and ri_triggers.c will only deal with PK datums in terms of
   10622              :              * that opcintype.  Changing the opcintype also changes pfeqop.
   10623              :              */
   10624            4 :             old_check_ok = (new_pathtype == old_pathtype &&
   10625            4 :                             new_castfunc == old_castfunc &&
   10626            4 :                             (!IsPolymorphicType(pfeqop_right) ||
   10627            8 :                              new_fktype == old_fktype) &&
   10628            0 :                             (new_fkcoll == old_fkcoll ||
   10629            0 :                              (get_collation_isdeterministic(old_fkcoll) && get_collation_isdeterministic(new_fkcoll))));
   10630              :         }
   10631              : 
   10632         1815 :         pfeqoperators[i] = pfeqop;
   10633         1815 :         ppeqoperators[i] = ppeqop;
   10634         1815 :         ffeqoperators[i] = ffeqop;
   10635              :     }
   10636              : 
   10637              :     /*
   10638              :      * For FKs with PERIOD we need additional operators to check whether the
   10639              :      * referencing row's range is contained by the aggregated ranges of the
   10640              :      * referenced row(s). For rangetypes and multirangetypes this is
   10641              :      * fk.periodatt <@ range_agg(pk.periodatt). Those are the only types we
   10642              :      * support for now. FKs will look these up at "runtime", but we should
   10643              :      * make sure the lookup works here, even if we don't use the values.
   10644              :      */
   10645         1374 :     if (with_period)
   10646              :     {
   10647              :         Oid         periodoperoid;
   10648              :         Oid         aggedperiodoperoid;
   10649              :         Oid         intersectoperoid;
   10650              : 
   10651          118 :         FindFKPeriodOpers(opclasses[numpks - 1], &periodoperoid, &aggedperiodoperoid,
   10652              :                           &intersectoperoid);
   10653              :     }
   10654              : 
   10655              :     /* First, create the constraint catalog entry itself. */
   10656         1374 :     address = addFkConstraint(addFkBothSides,
   10657              :                               fkconstraint->conname, fkconstraint, rel, pkrel,
   10658              :                               indexOid,
   10659              :                               InvalidOid,   /* no parent constraint */
   10660              :                               numfks,
   10661              :                               pkattnum,
   10662              :                               fkattnum,
   10663              :                               pfeqoperators,
   10664              :                               ppeqoperators,
   10665              :                               ffeqoperators,
   10666              :                               numfkdelsetcols,
   10667              :                               fkdelsetcols,
   10668              :                               false,
   10669              :                               with_period);
   10670              : 
   10671              :     /* Next process the action triggers at the referenced side and recurse */
   10672         1374 :     addFkRecurseReferenced(fkconstraint, rel, pkrel,
   10673              :                            indexOid,
   10674              :                            address.objectId,
   10675              :                            numfks,
   10676              :                            pkattnum,
   10677              :                            fkattnum,
   10678              :                            pfeqoperators,
   10679              :                            ppeqoperators,
   10680              :                            ffeqoperators,
   10681              :                            numfkdelsetcols,
   10682              :                            fkdelsetcols,
   10683              :                            old_check_ok,
   10684              :                            InvalidOid, InvalidOid,
   10685              :                            with_period);
   10686              : 
   10687              :     /* Lastly create the check triggers at the referencing side and recurse */
   10688         1374 :     addFkRecurseReferencing(wqueue, fkconstraint, rel, pkrel,
   10689              :                             indexOid,
   10690              :                             address.objectId,
   10691              :                             numfks,
   10692              :                             pkattnum,
   10693              :                             fkattnum,
   10694              :                             pfeqoperators,
   10695              :                             ppeqoperators,
   10696              :                             ffeqoperators,
   10697              :                             numfkdelsetcols,
   10698              :                             fkdelsetcols,
   10699              :                             old_check_ok,
   10700              :                             lockmode,
   10701              :                             InvalidOid, InvalidOid,
   10702              :                             with_period);
   10703              : 
   10704              :     /*
   10705              :      * Done.  Close pk table, but keep lock until we've committed.
   10706              :      */
   10707         1374 :     table_close(pkrel, NoLock);
   10708              : 
   10709         1374 :     return address;
   10710              : }
   10711              : 
   10712              : /*
   10713              :  * validateFkOnDeleteSetColumns
   10714              :  *      Verifies that columns used in ON DELETE SET NULL/DEFAULT (...)
   10715              :  *      column lists are valid.
   10716              :  *
   10717              :  * If there are duplicates in the fksetcolsattnums[] array, this silently
   10718              :  * removes the dups.  The new count of numfksetcols is returned.
   10719              :  */
   10720              : static int
   10721         1690 : validateFkOnDeleteSetColumns(int numfks, const int16 *fkattnums,
   10722              :                              int numfksetcols, int16 *fksetcolsattnums,
   10723              :                              List *fksetcols)
   10724              : {
   10725         1690 :     int         numcolsout = 0;
   10726              : 
   10727         1710 :     for (int i = 0; i < numfksetcols; i++)
   10728              :     {
   10729           24 :         int16       setcol_attnum = fksetcolsattnums[i];
   10730           24 :         bool        seen = false;
   10731              : 
   10732              :         /* Make sure it's in fkattnums[] */
   10733           44 :         for (int j = 0; j < numfks; j++)
   10734              :         {
   10735           40 :             if (fkattnums[j] == setcol_attnum)
   10736              :             {
   10737           20 :                 seen = true;
   10738           20 :                 break;
   10739              :             }
   10740              :         }
   10741              : 
   10742           24 :         if (!seen)
   10743              :         {
   10744            4 :             char       *col = strVal(list_nth(fksetcols, i));
   10745              : 
   10746            4 :             ereport(ERROR,
   10747              :                     (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
   10748              :                      errmsg("column \"%s\" referenced in ON DELETE SET action must be part of foreign key", col)));
   10749              :         }
   10750              : 
   10751              :         /* Now check for dups */
   10752           20 :         seen = false;
   10753           20 :         for (int j = 0; j < numcolsout; j++)
   10754              :         {
   10755            4 :             if (fksetcolsattnums[j] == setcol_attnum)
   10756              :             {
   10757            4 :                 seen = true;
   10758            4 :                 break;
   10759              :             }
   10760              :         }
   10761           20 :         if (!seen)
   10762           16 :             fksetcolsattnums[numcolsout++] = setcol_attnum;
   10763              :     }
   10764         1686 :     return numcolsout;
   10765              : }
   10766              : 
   10767              : /*
   10768              :  * addFkConstraint
   10769              :  *      Install pg_constraint entries to implement a foreign key constraint.
   10770              :  *      Caller must separately invoke addFkRecurseReferenced and
   10771              :  *      addFkRecurseReferencing, as appropriate, to install pg_trigger entries
   10772              :  *      and (for partitioned tables) recurse to partitions.
   10773              :  *
   10774              :  * fkside: the side of the FK (or both) to create.  Caller should
   10775              :  *      call addFkRecurseReferenced if this is addFkReferencedSide,
   10776              :  *      addFkRecurseReferencing if it's addFkReferencingSide, or both if it's
   10777              :  *      addFkBothSides.
   10778              :  * constraintname: the base name for the constraint being added,
   10779              :  *      copied to fkconstraint->conname if the latter is not set
   10780              :  * fkconstraint: the constraint being added
   10781              :  * rel: the root referencing relation
   10782              :  * pkrel: the referenced relation; might be a partition, if recursing
   10783              :  * indexOid: the OID of the index (on pkrel) implementing this constraint
   10784              :  * parentConstr: the OID of a parent constraint; InvalidOid if this is a
   10785              :  *      top-level constraint
   10786              :  * numfks: the number of columns in the foreign key
   10787              :  * pkattnum: the attnum array of referenced attributes
   10788              :  * fkattnum: the attnum array of referencing attributes
   10789              :  * pf/pp/ffeqoperators: OID array of operators between columns
   10790              :  * numfkdelsetcols: the number of columns in the ON DELETE SET NULL/DEFAULT
   10791              :  *      (...) clause
   10792              :  * fkdelsetcols: the attnum array of the columns in the ON DELETE SET
   10793              :  *      NULL/DEFAULT clause
   10794              :  * with_period: true if this is a temporal FK
   10795              :  */
   10796              : static ObjectAddress
   10797         2741 : addFkConstraint(addFkConstraintSides fkside,
   10798              :                 char *constraintname, Constraint *fkconstraint,
   10799              :                 Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr,
   10800              :                 int numfks, int16 *pkattnum,
   10801              :                 int16 *fkattnum, Oid *pfeqoperators, Oid *ppeqoperators,
   10802              :                 Oid *ffeqoperators, int numfkdelsetcols, int16 *fkdelsetcols,
   10803              :                 bool is_internal, bool with_period)
   10804              : {
   10805              :     ObjectAddress address;
   10806              :     Oid         constrOid;
   10807              :     char       *conname;
   10808              :     bool        conislocal;
   10809              :     int16       coninhcount;
   10810              :     bool        connoinherit;
   10811              : 
   10812              :     /*
   10813              :      * Verify relkind for each referenced partition.  At the top level, this
   10814              :      * is redundant with a previous check, but we need it when recursing.
   10815              :      */
   10816         2741 :     if (pkrel->rd_rel->relkind != RELKIND_RELATION &&
   10817          589 :         pkrel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
   10818            0 :         ereport(ERROR,
   10819              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   10820              :                  errmsg("referenced relation \"%s\" is not a table",
   10821              :                         RelationGetRelationName(pkrel))));
   10822              : 
   10823              :     /*
   10824              :      * Caller supplies us with a constraint name; however, it may be used in
   10825              :      * this partition, so come up with a different one in that case.  Unless
   10826              :      * truncation to NAMEDATALEN dictates otherwise, the new name will be the
   10827              :      * supplied name with an underscore and digit(s) appended.
   10828              :      */
   10829         2741 :     if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
   10830              :                              RelationGetRelid(rel),
   10831              :                              constraintname))
   10832          811 :         conname = ChooseConstraintName(constraintname,
   10833              :                                        NULL,
   10834              :                                        "",
   10835          811 :                                        RelationGetNamespace(rel), NIL);
   10836              :     else
   10837         1930 :         conname = constraintname;
   10838              : 
   10839         2741 :     if (fkconstraint->conname == NULL)
   10840          319 :         fkconstraint->conname = pstrdup(conname);
   10841              : 
   10842         2741 :     if (OidIsValid(parentConstr))
   10843              :     {
   10844         1367 :         conislocal = false;
   10845         1367 :         coninhcount = 1;
   10846         1367 :         connoinherit = false;
   10847              :     }
   10848              :     else
   10849              :     {
   10850         1374 :         conislocal = true;
   10851         1374 :         coninhcount = 0;
   10852              : 
   10853              :         /*
   10854              :          * always inherit for partitioned tables, never for legacy inheritance
   10855              :          */
   10856         1374 :         connoinherit = rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE;
   10857              :     }
   10858              : 
   10859              :     /*
   10860              :      * Record the FK constraint in pg_constraint.
   10861              :      */
   10862         2741 :     constrOid = CreateConstraintEntry(conname,
   10863         2741 :                                       RelationGetNamespace(rel),
   10864              :                                       CONSTRAINT_FOREIGN,
   10865         2741 :                                       fkconstraint->deferrable,
   10866         2741 :                                       fkconstraint->initdeferred,
   10867         2741 :                                       fkconstraint->is_enforced,
   10868         2741 :                                       fkconstraint->initially_valid,
   10869              :                                       parentConstr,
   10870              :                                       RelationGetRelid(rel),
   10871              :                                       fkattnum,
   10872              :                                       numfks,
   10873              :                                       numfks,
   10874              :                                       InvalidOid,   /* not a domain constraint */
   10875              :                                       indexOid,
   10876              :                                       RelationGetRelid(pkrel),
   10877              :                                       pkattnum,
   10878              :                                       pfeqoperators,
   10879              :                                       ppeqoperators,
   10880              :                                       ffeqoperators,
   10881              :                                       numfks,
   10882         2741 :                                       fkconstraint->fk_upd_action,
   10883         2741 :                                       fkconstraint->fk_del_action,
   10884              :                                       fkdelsetcols,
   10885              :                                       numfkdelsetcols,
   10886         2741 :                                       fkconstraint->fk_matchtype,
   10887              :                                       NULL, /* no exclusion constraint */
   10888              :                                       NULL, /* no check constraint */
   10889              :                                       NULL,
   10890              :                                       conislocal,   /* islocal */
   10891              :                                       coninhcount,  /* inhcount */
   10892              :                                       connoinherit, /* conNoInherit */
   10893              :                                       with_period,  /* conPeriod */
   10894              :                                       is_internal); /* is_internal */
   10895              : 
   10896         2741 :     ObjectAddressSet(address, ConstraintRelationId, constrOid);
   10897              : 
   10898              :     /*
   10899              :      * In partitioning cases, create the dependency entries for this
   10900              :      * constraint.  (For non-partitioned cases, relevant entries were created
   10901              :      * by CreateConstraintEntry.)
   10902              :      *
   10903              :      * On the referenced side, we need the constraint to have an internal
   10904              :      * dependency on its parent constraint; this means that this constraint
   10905              :      * cannot be dropped on its own -- only through the parent constraint. It
   10906              :      * also means the containing partition cannot be dropped on its own, but
   10907              :      * it can be detached, at which point this dependency is removed (after
   10908              :      * verifying that no rows are referenced via this FK.)
   10909              :      *
   10910              :      * When processing the referencing side, we link the constraint via the
   10911              :      * special partitioning dependencies: the parent constraint is the primary
   10912              :      * dependent, and the partition on which the foreign key exists is the
   10913              :      * secondary dependency.  That way, this constraint is dropped if either
   10914              :      * of these objects is.
   10915              :      *
   10916              :      * Note that this is only necessary for the subsidiary pg_constraint rows
   10917              :      * in partitions; the topmost row doesn't need any of this.
   10918              :      */
   10919         2741 :     if (OidIsValid(parentConstr))
   10920              :     {
   10921              :         ObjectAddress referenced;
   10922              : 
   10923         1367 :         ObjectAddressSet(referenced, ConstraintRelationId, parentConstr);
   10924              : 
   10925              :         Assert(fkside != addFkBothSides);
   10926         1367 :         if (fkside == addFkReferencedSide)
   10927          807 :             recordDependencyOn(&address, &referenced, DEPENDENCY_INTERNAL);
   10928              :         else
   10929              :         {
   10930          560 :             recordDependencyOn(&address, &referenced, DEPENDENCY_PARTITION_PRI);
   10931          560 :             ObjectAddressSet(referenced, RelationRelationId, RelationGetRelid(rel));
   10932          560 :             recordDependencyOn(&address, &referenced, DEPENDENCY_PARTITION_SEC);
   10933              :         }
   10934              :     }
   10935              : 
   10936              :     /* make new constraint visible, in case we add more */
   10937         2741 :     CommandCounterIncrement();
   10938              : 
   10939         2741 :     return address;
   10940              : }
   10941              : 
   10942              : /*
   10943              :  * addFkRecurseReferenced
   10944              :  *      Recursive helper for the referenced side of foreign key creation,
   10945              :  *      which creates the action triggers and recurses
   10946              :  *
   10947              :  * If the referenced relation is a plain relation, create the necessary action
   10948              :  * triggers that implement the constraint.  If the referenced relation is a
   10949              :  * partitioned table, then we create a pg_constraint row referencing the parent
   10950              :  * of the referencing side for it and recurse on this routine for each
   10951              :  * partition.
   10952              :  *
   10953              :  * fkconstraint: the constraint being added
   10954              :  * rel: the root referencing relation
   10955              :  * pkrel: the referenced relation; might be a partition, if recursing
   10956              :  * indexOid: the OID of the index (on pkrel) implementing this constraint
   10957              :  * parentConstr: the OID of a parent constraint; InvalidOid if this is a
   10958              :  *      top-level constraint
   10959              :  * numfks: the number of columns in the foreign key
   10960              :  * pkattnum: the attnum array of referenced attributes
   10961              :  * fkattnum: the attnum array of referencing attributes
   10962              :  * numfkdelsetcols: the number of columns in the ON DELETE SET
   10963              :  *      NULL/DEFAULT (...) clause
   10964              :  * fkdelsetcols: the attnum array of the columns in the ON DELETE SET
   10965              :  *      NULL/DEFAULT clause
   10966              :  * pf/pp/ffeqoperators: OID array of operators between columns
   10967              :  * old_check_ok: true if this constraint replaces an existing one that
   10968              :  *      was already validated (thus this one doesn't need validation)
   10969              :  * parentDelTrigger and parentUpdTrigger: when recursively called on a
   10970              :  *      partition, the OIDs of the parent action triggers for DELETE and
   10971              :  *      UPDATE respectively.
   10972              :  * with_period: true if this is a temporal FK
   10973              :  */
   10974              : static void
   10975         2253 : addFkRecurseReferenced(Constraint *fkconstraint, Relation rel,
   10976              :                        Relation pkrel, Oid indexOid, Oid parentConstr,
   10977              :                        int numfks,
   10978              :                        int16 *pkattnum, int16 *fkattnum, Oid *pfeqoperators,
   10979              :                        Oid *ppeqoperators, Oid *ffeqoperators,
   10980              :                        int numfkdelsetcols, int16 *fkdelsetcols,
   10981              :                        bool old_check_ok,
   10982              :                        Oid parentDelTrigger, Oid parentUpdTrigger,
   10983              :                        bool with_period)
   10984              : {
   10985         2253 :     Oid         deleteTriggerOid = InvalidOid,
   10986         2253 :                 updateTriggerOid = InvalidOid;
   10987              : 
   10988              :     Assert(CheckRelationLockedByMe(pkrel, ShareRowExclusiveLock, true));
   10989              :     Assert(CheckRelationLockedByMe(rel, ShareRowExclusiveLock, true));
   10990              : 
   10991              :     /*
   10992              :      * Create action triggers to enforce the constraint, or skip them if the
   10993              :      * constraint is NOT ENFORCED.
   10994              :      */
   10995         2253 :     if (fkconstraint->is_enforced)
   10996         2205 :         createForeignKeyActionTriggers(RelationGetRelid(rel),
   10997              :                                        RelationGetRelid(pkrel),
   10998              :                                        fkconstraint,
   10999              :                                        parentConstr, indexOid,
   11000              :                                        parentDelTrigger, parentUpdTrigger,
   11001              :                                        &deleteTriggerOid, &updateTriggerOid);
   11002              : 
   11003              :     /*
   11004              :      * If the referenced table is partitioned, recurse on ourselves to handle
   11005              :      * each partition.  We need one pg_constraint row created for each
   11006              :      * partition in addition to the pg_constraint row for the parent table.
   11007              :      */
   11008         2253 :     if (pkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
   11009              :     {
   11010          373 :         PartitionDesc pd = RelationGetPartitionDesc(pkrel, true);
   11011              : 
   11012         1004 :         for (int i = 0; i < pd->nparts; i++)
   11013              :         {
   11014              :             Relation    partRel;
   11015              :             AttrMap    *map;
   11016              :             AttrNumber *mapped_pkattnum;
   11017              :             Oid         partIndexId;
   11018              :             ObjectAddress address;
   11019              : 
   11020              :             /* XXX would it be better to acquire these locks beforehand? */
   11021          631 :             partRel = table_open(pd->oids[i], ShareRowExclusiveLock);
   11022              : 
   11023              :             /*
   11024              :              * Map the attribute numbers in the referenced side of the FK
   11025              :              * definition to match the partition's column layout.
   11026              :              */
   11027          631 :             map = build_attrmap_by_name_if_req(RelationGetDescr(partRel),
   11028              :                                                RelationGetDescr(pkrel),
   11029              :                                                false);
   11030          631 :             if (map)
   11031              :             {
   11032           89 :                 mapped_pkattnum = palloc_array(AttrNumber, numfks);
   11033          186 :                 for (int j = 0; j < numfks; j++)
   11034           97 :                     mapped_pkattnum[j] = map->attnums[pkattnum[j] - 1];
   11035              :             }
   11036              :             else
   11037          542 :                 mapped_pkattnum = pkattnum;
   11038              : 
   11039              :             /* Determine the index to use at this level */
   11040          631 :             partIndexId = index_get_partition(partRel, indexOid);
   11041          631 :             if (!OidIsValid(partIndexId))
   11042            0 :                 elog(ERROR, "index for %u not found in partition %s",
   11043              :                      indexOid, RelationGetRelationName(partRel));
   11044              : 
   11045              :             /* Create entry at this level ... */
   11046          631 :             address = addFkConstraint(addFkReferencedSide,
   11047              :                                       fkconstraint->conname, fkconstraint, rel,
   11048              :                                       partRel, partIndexId, parentConstr,
   11049              :                                       numfks, mapped_pkattnum,
   11050              :                                       fkattnum, pfeqoperators, ppeqoperators,
   11051              :                                       ffeqoperators, numfkdelsetcols,
   11052              :                                       fkdelsetcols, true, with_period);
   11053              :             /* ... and recurse to our children */
   11054          631 :             addFkRecurseReferenced(fkconstraint, rel, partRel,
   11055              :                                    partIndexId, address.objectId, numfks,
   11056              :                                    mapped_pkattnum, fkattnum,
   11057              :                                    pfeqoperators, ppeqoperators, ffeqoperators,
   11058              :                                    numfkdelsetcols, fkdelsetcols,
   11059              :                                    old_check_ok,
   11060              :                                    deleteTriggerOid, updateTriggerOid,
   11061              :                                    with_period);
   11062              : 
   11063              :             /* Done -- clean up (but keep the lock) */
   11064          631 :             table_close(partRel, NoLock);
   11065          631 :             if (map)
   11066              :             {
   11067           89 :                 pfree(mapped_pkattnum);
   11068           89 :                 free_attrmap(map);
   11069              :             }
   11070              :         }
   11071              :     }
   11072         2253 : }
   11073              : 
   11074              : /*
   11075              :  * addFkRecurseReferencing
   11076              :  *      Recursive helper for the referencing side of foreign key creation,
   11077              :  *      which creates the check triggers and recurses
   11078              :  *
   11079              :  * If the referencing relation is a plain relation, create the necessary check
   11080              :  * triggers that implement the constraint, and set up for Phase 3 constraint
   11081              :  * verification.  If the referencing relation is a partitioned table, then
   11082              :  * we create a pg_constraint row for it and recurse on this routine for each
   11083              :  * partition.
   11084              :  *
   11085              :  * We assume that the referenced relation is locked against concurrent
   11086              :  * deletions.  If it's a partitioned relation, every partition must be so
   11087              :  * locked.
   11088              :  *
   11089              :  * wqueue: the ALTER TABLE work queue; NULL when not running as part
   11090              :  *      of an ALTER TABLE sequence.
   11091              :  * fkconstraint: the constraint being added
   11092              :  * rel: the referencing relation; might be a partition, if recursing
   11093              :  * pkrel: the root referenced relation
   11094              :  * indexOid: the OID of the index (on pkrel) implementing this constraint
   11095              :  * parentConstr: the OID of the parent constraint (there is always one)
   11096              :  * numfks: the number of columns in the foreign key
   11097              :  * pkattnum: the attnum array of referenced attributes
   11098              :  * fkattnum: the attnum array of referencing attributes
   11099              :  * pf/pp/ffeqoperators: OID array of operators between columns
   11100              :  * numfkdelsetcols: the number of columns in the ON DELETE SET NULL/DEFAULT
   11101              :  *      (...) clause
   11102              :  * fkdelsetcols: the attnum array of the columns in the ON DELETE SET
   11103              :  *      NULL/DEFAULT clause
   11104              :  * old_check_ok: true if this constraint replaces an existing one that
   11105              :  *      was already validated (thus this one doesn't need validation)
   11106              :  * lockmode: the lockmode to acquire on partitions when recursing
   11107              :  * parentInsTrigger and parentUpdTrigger: when being recursively called on
   11108              :  *      a partition, the OIDs of the parent check triggers for INSERT and
   11109              :  *      UPDATE respectively.
   11110              :  * with_period: true if this is a temporal FK
   11111              :  */
   11112              : static void
   11113         1934 : addFkRecurseReferencing(List **wqueue, Constraint *fkconstraint, Relation rel,
   11114              :                         Relation pkrel, Oid indexOid, Oid parentConstr,
   11115              :                         int numfks, int16 *pkattnum, int16 *fkattnum,
   11116              :                         Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators,
   11117              :                         int numfkdelsetcols, int16 *fkdelsetcols,
   11118              :                         bool old_check_ok, LOCKMODE lockmode,
   11119              :                         Oid parentInsTrigger, Oid parentUpdTrigger,
   11120              :                         bool with_period)
   11121              : {
   11122         1934 :     Oid         insertTriggerOid = InvalidOid,
   11123         1934 :                 updateTriggerOid = InvalidOid;
   11124              : 
   11125              :     Assert(OidIsValid(parentConstr));
   11126              :     Assert(CheckRelationLockedByMe(rel, ShareRowExclusiveLock, true));
   11127              :     Assert(CheckRelationLockedByMe(pkrel, ShareRowExclusiveLock, true));
   11128              : 
   11129         1934 :     if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
   11130            0 :         ereport(ERROR,
   11131              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   11132              :                  errmsg("foreign key constraints are not supported on foreign tables")));
   11133              : 
   11134              :     /*
   11135              :      * Add check triggers if the constraint is ENFORCED, and if needed,
   11136              :      * schedule them to be checked in Phase 3.
   11137              :      *
   11138              :      * If the relation is partitioned, drill down to do it to its partitions.
   11139              :      */
   11140         1934 :     if (fkconstraint->is_enforced)
   11141         1902 :         createForeignKeyCheckTriggers(RelationGetRelid(rel),
   11142              :                                       RelationGetRelid(pkrel),
   11143              :                                       fkconstraint,
   11144              :                                       parentConstr,
   11145              :                                       indexOid,
   11146              :                                       parentInsTrigger, parentUpdTrigger,
   11147              :                                       &insertTriggerOid, &updateTriggerOid);
   11148              : 
   11149         1934 :     if (rel->rd_rel->relkind == RELKIND_RELATION)
   11150              :     {
   11151              :         /*
   11152              :          * Tell Phase 3 to check that the constraint is satisfied by existing
   11153              :          * rows. We can skip this during table creation, when constraint is
   11154              :          * specified as NOT ENFORCED, or when requested explicitly by
   11155              :          * specifying NOT VALID in an ADD FOREIGN KEY command, and when we're
   11156              :          * recreating a constraint following a SET DATA TYPE operation that
   11157              :          * did not impugn its validity.
   11158              :          */
   11159         1611 :         if (wqueue && !old_check_ok && !fkconstraint->skip_validation &&
   11160          509 :             fkconstraint->is_enforced)
   11161              :         {
   11162              :             NewConstraint *newcon;
   11163              :             AlteredTableInfo *tab;
   11164              : 
   11165          509 :             tab = ATGetQueueEntry(wqueue, rel);
   11166              : 
   11167          509 :             newcon = palloc0_object(NewConstraint);
   11168          509 :             newcon->name = get_constraint_name(parentConstr);
   11169          509 :             newcon->contype = CONSTR_FOREIGN;
   11170          509 :             newcon->refrelid = RelationGetRelid(pkrel);
   11171          509 :             newcon->refindid = indexOid;
   11172          509 :             newcon->conid = parentConstr;
   11173          509 :             newcon->conwithperiod = fkconstraint->fk_with_period;
   11174          509 :             newcon->qual = (Node *) fkconstraint;
   11175              : 
   11176          509 :             tab->constraints = lappend(tab->constraints, newcon);
   11177              :         }
   11178              :     }
   11179          323 :     else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
   11180              :     {
   11181          323 :         PartitionDesc pd = RelationGetPartitionDesc(rel, true);
   11182              :         Relation    trigrel;
   11183              : 
   11184              :         /*
   11185              :          * Triggers of the foreign keys will be manipulated a bunch of times
   11186              :          * in the loop below.  To avoid repeatedly opening/closing the trigger
   11187              :          * catalog relation, we open it here and pass it to the subroutines
   11188              :          * called below.
   11189              :          */
   11190          323 :         trigrel = table_open(TriggerRelationId, RowExclusiveLock);
   11191              : 
   11192              :         /*
   11193              :          * Recurse to take appropriate action on each partition; either we
   11194              :          * find an existing constraint to reparent to ours, or we create a new
   11195              :          * one.
   11196              :          */
   11197          572 :         for (int i = 0; i < pd->nparts; i++)
   11198              :         {
   11199          253 :             Relation    partition = table_open(pd->oids[i], lockmode);
   11200              :             List       *partFKs;
   11201              :             AttrMap    *attmap;
   11202              :             AttrNumber  mapped_fkattnum[INDEX_MAX_KEYS];
   11203              :             bool        attached;
   11204              :             ObjectAddress address;
   11205              : 
   11206          253 :             CheckAlterTableIsSafe(partition);
   11207              : 
   11208          249 :             attmap = build_attrmap_by_name(RelationGetDescr(partition),
   11209              :                                            RelationGetDescr(rel),
   11210              :                                            false);
   11211          642 :             for (int j = 0; j < numfks; j++)
   11212          393 :                 mapped_fkattnum[j] = attmap->attnums[fkattnum[j] - 1];
   11213              : 
   11214              :             /* Check whether an existing constraint can be repurposed */
   11215          249 :             partFKs = copyObject(RelationGetFKeyList(partition));
   11216          249 :             attached = false;
   11217          509 :             foreach_node(ForeignKeyCacheInfo, fk, partFKs)
   11218              :             {
   11219           19 :                 if (tryAttachPartitionForeignKey(wqueue,
   11220              :                                                  fk,
   11221              :                                                  partition,
   11222              :                                                  parentConstr,
   11223              :                                                  numfks,
   11224              :                                                  mapped_fkattnum,
   11225              :                                                  pkattnum,
   11226              :                                                  pfeqoperators,
   11227              :                                                  insertTriggerOid,
   11228              :                                                  updateTriggerOid,
   11229              :                                                  trigrel))
   11230              :                 {
   11231            8 :                     attached = true;
   11232            8 :                     break;
   11233              :                 }
   11234              :             }
   11235          249 :             if (attached)
   11236              :             {
   11237            8 :                 table_close(partition, NoLock);
   11238            8 :                 continue;
   11239              :             }
   11240              : 
   11241              :             /*
   11242              :              * No luck finding a good constraint to reuse; create our own.
   11243              :              */
   11244          241 :             address = addFkConstraint(addFkReferencingSide,
   11245              :                                       fkconstraint->conname, fkconstraint,
   11246              :                                       partition, pkrel, indexOid, parentConstr,
   11247              :                                       numfks, pkattnum,
   11248              :                                       mapped_fkattnum, pfeqoperators,
   11249              :                                       ppeqoperators, ffeqoperators,
   11250              :                                       numfkdelsetcols, fkdelsetcols, true,
   11251              :                                       with_period);
   11252              : 
   11253              :             /* call ourselves to finalize the creation and we're done */
   11254          241 :             addFkRecurseReferencing(wqueue, fkconstraint, partition, pkrel,
   11255              :                                     indexOid,
   11256              :                                     address.objectId,
   11257              :                                     numfks,
   11258              :                                     pkattnum,
   11259              :                                     mapped_fkattnum,
   11260              :                                     pfeqoperators,
   11261              :                                     ppeqoperators,
   11262              :                                     ffeqoperators,
   11263              :                                     numfkdelsetcols,
   11264              :                                     fkdelsetcols,
   11265              :                                     old_check_ok,
   11266              :                                     lockmode,
   11267              :                                     insertTriggerOid,
   11268              :                                     updateTriggerOid,
   11269              :                                     with_period);
   11270              : 
   11271          241 :             table_close(partition, NoLock);
   11272              :         }
   11273              : 
   11274          319 :         table_close(trigrel, RowExclusiveLock);
   11275              :     }
   11276         1930 : }
   11277              : 
   11278              : /*
   11279              :  * CloneForeignKeyConstraints
   11280              :  *      Clone foreign keys from a partitioned table to a newly acquired
   11281              :  *      partition.
   11282              :  *
   11283              :  * partitionRel is a partition of parentRel, so we can be certain that it has
   11284              :  * the same columns with the same datatypes.  The columns may be in different
   11285              :  * order, though.
   11286              :  *
   11287              :  * wqueue must be passed to set up phase 3 constraint checking, unless the
   11288              :  * referencing-side partition is known to be empty (such as in CREATE TABLE /
   11289              :  * PARTITION OF).
   11290              :  */
   11291              : static void
   11292         7641 : CloneForeignKeyConstraints(List **wqueue, Relation parentRel,
   11293              :                            Relation partitionRel)
   11294              : {
   11295              :     /* This only works for declarative partitioning */
   11296              :     Assert(parentRel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
   11297              : 
   11298              :     /*
   11299              :      * First, clone constraints where the parent is on the referencing side.
   11300              :      */
   11301         7641 :     CloneFkReferencing(wqueue, parentRel, partitionRel);
   11302              : 
   11303              :     /*
   11304              :      * Clone constraints for which the parent is on the referenced side.
   11305              :      */
   11306         7629 :     CloneFkReferenced(parentRel, partitionRel);
   11307         7629 : }
   11308              : 
   11309              : /*
   11310              :  * CloneFkReferenced
   11311              :  *      Subroutine for CloneForeignKeyConstraints
   11312              :  *
   11313              :  * Find all the FKs that have the parent relation on the referenced side;
   11314              :  * clone those constraints to the given partition.  This is to be called
   11315              :  * when the partition is being created or attached.
   11316              :  *
   11317              :  * This recurses to partitions, if the relation being attached is partitioned.
   11318              :  * Recursion is done by calling addFkRecurseReferenced.
   11319              :  */
   11320              : static void
   11321         7629 : CloneFkReferenced(Relation parentRel, Relation partitionRel)
   11322              : {
   11323              :     Relation    pg_constraint;
   11324              :     AttrMap    *attmap;
   11325              :     ListCell   *cell;
   11326              :     SysScanDesc scan;
   11327              :     ScanKeyData key[2];
   11328              :     HeapTuple   tuple;
   11329         7629 :     List       *clone = NIL;
   11330              :     Relation    trigrel;
   11331              : 
   11332              :     /*
   11333              :      * Search for any constraints where this partition's parent is in the
   11334              :      * referenced side.  However, we must not clone any constraint whose
   11335              :      * parent constraint is also going to be cloned, to avoid duplicates.  So
   11336              :      * do it in two steps: first construct the list of constraints to clone,
   11337              :      * then go over that list cloning those whose parents are not in the list.
   11338              :      * (We must not rely on the parent being seen first, since the catalog
   11339              :      * scan could return children first.)
   11340              :      */
   11341         7629 :     pg_constraint = table_open(ConstraintRelationId, RowShareLock);
   11342         7629 :     ScanKeyInit(&key[0],
   11343              :                 Anum_pg_constraint_confrelid, BTEqualStrategyNumber,
   11344              :                 F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(parentRel)));
   11345         7629 :     ScanKeyInit(&key[1],
   11346              :                 Anum_pg_constraint_contype, BTEqualStrategyNumber,
   11347              :                 F_CHAREQ, CharGetDatum(CONSTRAINT_FOREIGN));
   11348              :     /* This is a seqscan, as we don't have a usable index ... */
   11349         7629 :     scan = systable_beginscan(pg_constraint, InvalidOid, true,
   11350              :                               NULL, 2, key);
   11351         7953 :     while ((tuple = systable_getnext(scan)) != NULL)
   11352              :     {
   11353          324 :         Form_pg_constraint constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
   11354              : 
   11355          324 :         clone = lappend_oid(clone, constrForm->oid);
   11356              :     }
   11357         7629 :     systable_endscan(scan);
   11358         7629 :     table_close(pg_constraint, RowShareLock);
   11359              : 
   11360              :     /*
   11361              :      * Triggers of the foreign keys will be manipulated a bunch of times in
   11362              :      * the loop below.  To avoid repeatedly opening/closing the trigger
   11363              :      * catalog relation, we open it here and pass it to the subroutines called
   11364              :      * below.
   11365              :      */
   11366         7629 :     trigrel = table_open(TriggerRelationId, RowExclusiveLock);
   11367              : 
   11368         7629 :     attmap = build_attrmap_by_name(RelationGetDescr(partitionRel),
   11369              :                                    RelationGetDescr(parentRel),
   11370              :                                    false);
   11371         7953 :     foreach(cell, clone)
   11372              :     {
   11373          324 :         Oid         constrOid = lfirst_oid(cell);
   11374              :         Form_pg_constraint constrForm;
   11375              :         Relation    fkRel;
   11376              :         Oid         indexOid;
   11377              :         Oid         partIndexId;
   11378              :         int         numfks;
   11379              :         AttrNumber  conkey[INDEX_MAX_KEYS];
   11380              :         AttrNumber  mapped_confkey[INDEX_MAX_KEYS];
   11381              :         AttrNumber  confkey[INDEX_MAX_KEYS];
   11382              :         Oid         conpfeqop[INDEX_MAX_KEYS];
   11383              :         Oid         conppeqop[INDEX_MAX_KEYS];
   11384              :         Oid         conffeqop[INDEX_MAX_KEYS];
   11385              :         int         numfkdelsetcols;
   11386              :         AttrNumber  confdelsetcols[INDEX_MAX_KEYS];
   11387              :         Constraint *fkconstraint;
   11388              :         ObjectAddress address;
   11389          324 :         Oid         deleteTriggerOid = InvalidOid,
   11390          324 :                     updateTriggerOid = InvalidOid;
   11391              : 
   11392          324 :         tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
   11393          324 :         if (!HeapTupleIsValid(tuple))
   11394            0 :             elog(ERROR, "cache lookup failed for constraint %u", constrOid);
   11395          324 :         constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
   11396              : 
   11397              :         /*
   11398              :          * As explained above: don't try to clone a constraint for which we're
   11399              :          * going to clone the parent.
   11400              :          */
   11401          324 :         if (list_member_oid(clone, constrForm->conparentid))
   11402              :         {
   11403          148 :             ReleaseSysCache(tuple);
   11404          148 :             continue;
   11405              :         }
   11406              : 
   11407              :         /* We need the same lock level that CreateTrigger will acquire */
   11408          176 :         fkRel = table_open(constrForm->conrelid, ShareRowExclusiveLock);
   11409              : 
   11410          176 :         indexOid = constrForm->conindid;
   11411          176 :         DeconstructFkConstraintRow(tuple,
   11412              :                                    &numfks,
   11413              :                                    conkey,
   11414              :                                    confkey,
   11415              :                                    conpfeqop,
   11416              :                                    conppeqop,
   11417              :                                    conffeqop,
   11418              :                                    &numfkdelsetcols,
   11419              :                                    confdelsetcols);
   11420              : 
   11421          380 :         for (int i = 0; i < numfks; i++)
   11422          204 :             mapped_confkey[i] = attmap->attnums[confkey[i] - 1];
   11423              : 
   11424          176 :         fkconstraint = makeNode(Constraint);
   11425          176 :         fkconstraint->contype = CONSTRAINT_FOREIGN;
   11426          176 :         fkconstraint->conname = NameStr(constrForm->conname);
   11427          176 :         fkconstraint->deferrable = constrForm->condeferrable;
   11428          176 :         fkconstraint->initdeferred = constrForm->condeferred;
   11429          176 :         fkconstraint->location = -1;
   11430          176 :         fkconstraint->pktable = NULL;
   11431              :         /* ->fk_attrs determined below */
   11432          176 :         fkconstraint->pk_attrs = NIL;
   11433          176 :         fkconstraint->fk_matchtype = constrForm->confmatchtype;
   11434          176 :         fkconstraint->fk_upd_action = constrForm->confupdtype;
   11435          176 :         fkconstraint->fk_del_action = constrForm->confdeltype;
   11436          176 :         fkconstraint->fk_del_set_cols = NIL;
   11437          176 :         fkconstraint->old_conpfeqop = NIL;
   11438          176 :         fkconstraint->old_pktable_oid = InvalidOid;
   11439          176 :         fkconstraint->is_enforced = constrForm->conenforced;
   11440          176 :         fkconstraint->skip_validation = false;
   11441          176 :         fkconstraint->initially_valid = constrForm->convalidated;
   11442              : 
   11443              :         /* set up colnames that are used to generate the constraint name */
   11444          380 :         for (int i = 0; i < numfks; i++)
   11445              :         {
   11446              :             Form_pg_attribute att;
   11447              : 
   11448          204 :             att = TupleDescAttr(RelationGetDescr(fkRel),
   11449          204 :                                 conkey[i] - 1);
   11450          204 :             fkconstraint->fk_attrs = lappend(fkconstraint->fk_attrs,
   11451          204 :                                              makeString(NameStr(att->attname)));
   11452              :         }
   11453              : 
   11454              :         /*
   11455              :          * Add the new foreign key constraint pointing to the new partition.
   11456              :          * Because this new partition appears in the referenced side of the
   11457              :          * constraint, we don't need to set up for Phase 3 check.
   11458              :          */
   11459          176 :         partIndexId = index_get_partition(partitionRel, indexOid);
   11460          176 :         if (!OidIsValid(partIndexId))
   11461            0 :             elog(ERROR, "index for %u not found in partition %s",
   11462              :                  indexOid, RelationGetRelationName(partitionRel));
   11463              : 
   11464              :         /*
   11465              :          * Get the "action" triggers belonging to the constraint to pass as
   11466              :          * parent OIDs for similar triggers that will be created on the
   11467              :          * partition in addFkRecurseReferenced().
   11468              :          */
   11469          176 :         if (constrForm->conenforced)
   11470          172 :             GetForeignKeyActionTriggers(trigrel, constrOid,
   11471              :                                         constrForm->confrelid, constrForm->conrelid,
   11472              :                                         &deleteTriggerOid, &updateTriggerOid);
   11473              : 
   11474              :         /* Add this constraint ... */
   11475          176 :         address = addFkConstraint(addFkReferencedSide,
   11476              :                                   fkconstraint->conname, fkconstraint, fkRel,
   11477              :                                   partitionRel, partIndexId, constrOid,
   11478              :                                   numfks, mapped_confkey,
   11479              :                                   conkey, conpfeqop, conppeqop, conffeqop,
   11480              :                                   numfkdelsetcols, confdelsetcols, false,
   11481          176 :                                   constrForm->conperiod);
   11482              :         /* ... and recurse */
   11483          176 :         addFkRecurseReferenced(fkconstraint,
   11484              :                                fkRel,
   11485              :                                partitionRel,
   11486              :                                partIndexId,
   11487              :                                address.objectId,
   11488              :                                numfks,
   11489              :                                mapped_confkey,
   11490              :                                conkey,
   11491              :                                conpfeqop,
   11492              :                                conppeqop,
   11493              :                                conffeqop,
   11494              :                                numfkdelsetcols,
   11495              :                                confdelsetcols,
   11496              :                                true,
   11497              :                                deleteTriggerOid,
   11498              :                                updateTriggerOid,
   11499          176 :                                constrForm->conperiod);
   11500              : 
   11501          176 :         table_close(fkRel, NoLock);
   11502          176 :         ReleaseSysCache(tuple);
   11503              :     }
   11504              : 
   11505         7629 :     table_close(trigrel, RowExclusiveLock);
   11506         7629 : }
   11507              : 
   11508              : /*
   11509              :  * CloneFkReferencing
   11510              :  *      Subroutine for CloneForeignKeyConstraints
   11511              :  *
   11512              :  * For each FK constraint of the parent relation in the given list, find an
   11513              :  * equivalent constraint in its partition relation that can be reparented;
   11514              :  * if one cannot be found, create a new constraint in the partition as its
   11515              :  * child.
   11516              :  *
   11517              :  * If wqueue is given, it is used to set up phase-3 verification for each
   11518              :  * cloned constraint; omit it if such verification is not needed
   11519              :  * (example: the partition is being created anew).
   11520              :  */
   11521              : static void
   11522         7641 : CloneFkReferencing(List **wqueue, Relation parentRel, Relation partRel)
   11523              : {
   11524              :     AttrMap    *attmap;
   11525              :     List       *partFKs;
   11526         7641 :     List       *clone = NIL;
   11527              :     ListCell   *cell;
   11528              :     Relation    trigrel;
   11529              : 
   11530              :     /* obtain a list of constraints that we need to clone */
   11531         8572 :     foreach(cell, RelationGetFKeyList(parentRel))
   11532              :     {
   11533          935 :         ForeignKeyCacheInfo *fk = lfirst(cell);
   11534              : 
   11535              :         /*
   11536              :          * Refuse to attach a table as partition that this partitioned table
   11537              :          * already has a foreign key to.  This isn't useful schema, which is
   11538              :          * proven by the fact that there have been no user complaints that
   11539              :          * it's already impossible to achieve this in the opposite direction,
   11540              :          * i.e., creating a foreign key that references a partition.  This
   11541              :          * restriction allows us to dodge some complexities around
   11542              :          * pg_constraint and pg_trigger row creations that would be needed
   11543              :          * during ATTACH/DETACH for this kind of relationship.
   11544              :          */
   11545          935 :         if (fk->confrelid == RelationGetRelid(partRel))
   11546            4 :             ereport(ERROR,
   11547              :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   11548              :                      errmsg("cannot attach table \"%s\" as a partition because it is referenced by foreign key \"%s\"",
   11549              :                             RelationGetRelationName(partRel),
   11550              :                             get_constraint_name(fk->conoid))));
   11551              : 
   11552          931 :         clone = lappend_oid(clone, fk->conoid);
   11553              :     }
   11554              : 
   11555              :     /*
   11556              :      * Silently do nothing if there's nothing to do.  In particular, this
   11557              :      * avoids throwing a spurious error for foreign tables.
   11558              :      */
   11559         7637 :     if (clone == NIL)
   11560         7246 :         return;
   11561              : 
   11562          391 :     if (partRel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
   11563            0 :         ereport(ERROR,
   11564              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   11565              :                  errmsg("foreign key constraints are not supported on foreign tables")));
   11566              : 
   11567              :     /*
   11568              :      * Triggers of the foreign keys will be manipulated a bunch of times in
   11569              :      * the loop below.  To avoid repeatedly opening/closing the trigger
   11570              :      * catalog relation, we open it here and pass it to the subroutines called
   11571              :      * below.
   11572              :      */
   11573          391 :     trigrel = table_open(TriggerRelationId, RowExclusiveLock);
   11574              : 
   11575              :     /*
   11576              :      * The constraint key may differ, if the columns in the partition are
   11577              :      * different.  This map is used to convert them.
   11578              :      */
   11579          391 :     attmap = build_attrmap_by_name(RelationGetDescr(partRel),
   11580              :                                    RelationGetDescr(parentRel),
   11581              :                                    false);
   11582              : 
   11583          391 :     partFKs = copyObject(RelationGetFKeyList(partRel));
   11584              : 
   11585         1314 :     foreach(cell, clone)
   11586              :     {
   11587          931 :         Oid         parentConstrOid = lfirst_oid(cell);
   11588              :         Form_pg_constraint constrForm;
   11589              :         Relation    pkrel;
   11590              :         HeapTuple   tuple;
   11591              :         int         numfks;
   11592              :         AttrNumber  conkey[INDEX_MAX_KEYS];
   11593              :         AttrNumber  mapped_conkey[INDEX_MAX_KEYS];
   11594              :         AttrNumber  confkey[INDEX_MAX_KEYS];
   11595              :         Oid         conpfeqop[INDEX_MAX_KEYS];
   11596              :         Oid         conppeqop[INDEX_MAX_KEYS];
   11597              :         Oid         conffeqop[INDEX_MAX_KEYS];
   11598              :         int         numfkdelsetcols;
   11599              :         AttrNumber  confdelsetcols[INDEX_MAX_KEYS];
   11600              :         Constraint *fkconstraint;
   11601              :         bool        attached;
   11602              :         Oid         indexOid;
   11603              :         ObjectAddress address;
   11604              :         ListCell   *lc;
   11605          931 :         Oid         insertTriggerOid = InvalidOid,
   11606          931 :                     updateTriggerOid = InvalidOid;
   11607              :         bool        with_period;
   11608              : 
   11609          931 :         tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(parentConstrOid));
   11610          931 :         if (!HeapTupleIsValid(tuple))
   11611            0 :             elog(ERROR, "cache lookup failed for constraint %u",
   11612              :                  parentConstrOid);
   11613          931 :         constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
   11614              : 
   11615              :         /* Don't clone constraints whose parents are being cloned */
   11616          931 :         if (list_member_oid(clone, constrForm->conparentid))
   11617              :         {
   11618          508 :             ReleaseSysCache(tuple);
   11619          608 :             continue;
   11620              :         }
   11621              : 
   11622              :         /*
   11623              :          * Need to prevent concurrent deletions.  If pkrel is a partitioned
   11624              :          * relation, that means to lock all partitions.
   11625              :          */
   11626          423 :         pkrel = table_open(constrForm->confrelid, ShareRowExclusiveLock);
   11627          423 :         if (pkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
   11628          176 :             (void) find_all_inheritors(RelationGetRelid(pkrel),
   11629              :                                        ShareRowExclusiveLock, NULL);
   11630              : 
   11631          423 :         DeconstructFkConstraintRow(tuple, &numfks, conkey, confkey,
   11632              :                                    conpfeqop, conppeqop, conffeqop,
   11633              :                                    &numfkdelsetcols, confdelsetcols);
   11634         1002 :         for (int i = 0; i < numfks; i++)
   11635          579 :             mapped_conkey[i] = attmap->attnums[conkey[i] - 1];
   11636              : 
   11637              :         /*
   11638              :          * Get the "check" triggers belonging to the constraint, if it is
   11639              :          * ENFORCED, to pass as parent OIDs for similar triggers that will be
   11640              :          * created on the partition in addFkRecurseReferencing().  They are
   11641              :          * also passed to tryAttachPartitionForeignKey() below to simply
   11642              :          * assign as parents to the partition's existing "check" triggers,
   11643              :          * that is, if the corresponding constraints is deemed attachable to
   11644              :          * the parent constraint.
   11645              :          */
   11646          423 :         if (constrForm->conenforced)
   11647          415 :             GetForeignKeyCheckTriggers(trigrel, constrForm->oid,
   11648              :                                        constrForm->confrelid, constrForm->conrelid,
   11649              :                                        &insertTriggerOid, &updateTriggerOid);
   11650              : 
   11651              :         /*
   11652              :          * Before creating a new constraint, see whether any existing FKs are
   11653              :          * fit for the purpose.  If one is, attach the parent constraint to
   11654              :          * it, and don't clone anything.  This way we avoid the expensive
   11655              :          * verification step and don't end up with a duplicate FK, and we
   11656              :          * don't need to recurse to partitions for this constraint.
   11657              :          */
   11658          423 :         attached = false;
   11659          483 :         foreach(lc, partFKs)
   11660              :         {
   11661          164 :             ForeignKeyCacheInfo *fk = lfirst_node(ForeignKeyCacheInfo, lc);
   11662              : 
   11663          164 :             if (tryAttachPartitionForeignKey(wqueue,
   11664              :                                              fk,
   11665              :                                              partRel,
   11666              :                                              parentConstrOid,
   11667              :                                              numfks,
   11668              :                                              mapped_conkey,
   11669              :                                              confkey,
   11670              :                                              conpfeqop,
   11671              :                                              insertTriggerOid,
   11672              :                                              updateTriggerOid,
   11673              :                                              trigrel))
   11674              :             {
   11675          100 :                 attached = true;
   11676          100 :                 table_close(pkrel, NoLock);
   11677          100 :                 break;
   11678              :             }
   11679              :         }
   11680          419 :         if (attached)
   11681              :         {
   11682          100 :             ReleaseSysCache(tuple);
   11683          100 :             continue;
   11684              :         }
   11685              : 
   11686              :         /* No dice.  Set up to create our own constraint */
   11687          319 :         fkconstraint = makeNode(Constraint);
   11688          319 :         fkconstraint->contype = CONSTRAINT_FOREIGN;
   11689              :         /* ->conname determined below */
   11690          319 :         fkconstraint->deferrable = constrForm->condeferrable;
   11691          319 :         fkconstraint->initdeferred = constrForm->condeferred;
   11692          319 :         fkconstraint->location = -1;
   11693          319 :         fkconstraint->pktable = NULL;
   11694              :         /* ->fk_attrs determined below */
   11695          319 :         fkconstraint->pk_attrs = NIL;
   11696          319 :         fkconstraint->fk_matchtype = constrForm->confmatchtype;
   11697          319 :         fkconstraint->fk_upd_action = constrForm->confupdtype;
   11698          319 :         fkconstraint->fk_del_action = constrForm->confdeltype;
   11699          319 :         fkconstraint->fk_del_set_cols = NIL;
   11700          319 :         fkconstraint->old_conpfeqop = NIL;
   11701          319 :         fkconstraint->old_pktable_oid = InvalidOid;
   11702          319 :         fkconstraint->is_enforced = constrForm->conenforced;
   11703          319 :         fkconstraint->skip_validation = false;
   11704          319 :         fkconstraint->initially_valid = constrForm->convalidated;
   11705          718 :         for (int i = 0; i < numfks; i++)
   11706              :         {
   11707              :             Form_pg_attribute att;
   11708              : 
   11709          399 :             att = TupleDescAttr(RelationGetDescr(partRel),
   11710          399 :                                 mapped_conkey[i] - 1);
   11711          399 :             fkconstraint->fk_attrs = lappend(fkconstraint->fk_attrs,
   11712          399 :                                              makeString(NameStr(att->attname)));
   11713              :         }
   11714              : 
   11715          319 :         indexOid = constrForm->conindid;
   11716          319 :         with_period = constrForm->conperiod;
   11717              : 
   11718              :         /* Create the pg_constraint entry at this level */
   11719          319 :         address = addFkConstraint(addFkReferencingSide,
   11720          319 :                                   NameStr(constrForm->conname), fkconstraint,
   11721              :                                   partRel, pkrel, indexOid, parentConstrOid,
   11722              :                                   numfks, confkey,
   11723              :                                   mapped_conkey, conpfeqop,
   11724              :                                   conppeqop, conffeqop,
   11725              :                                   numfkdelsetcols, confdelsetcols,
   11726              :                                   false, with_period);
   11727              : 
   11728              :         /* Done with the cloned constraint's tuple */
   11729          319 :         ReleaseSysCache(tuple);
   11730              : 
   11731              :         /* Create the check triggers, and recurse to partitions, if any */
   11732          319 :         addFkRecurseReferencing(wqueue,
   11733              :                                 fkconstraint,
   11734              :                                 partRel,
   11735              :                                 pkrel,
   11736              :                                 indexOid,
   11737              :                                 address.objectId,
   11738              :                                 numfks,
   11739              :                                 confkey,
   11740              :                                 mapped_conkey,
   11741              :                                 conpfeqop,
   11742              :                                 conppeqop,
   11743              :                                 conffeqop,
   11744              :                                 numfkdelsetcols,
   11745              :                                 confdelsetcols,
   11746              :                                 false,  /* no old check exists */
   11747              :                                 AccessExclusiveLock,
   11748              :                                 insertTriggerOid,
   11749              :                                 updateTriggerOid,
   11750              :                                 with_period);
   11751          315 :         table_close(pkrel, NoLock);
   11752              :     }
   11753              : 
   11754          383 :     table_close(trigrel, RowExclusiveLock);
   11755              : }
   11756              : 
   11757              : /*
   11758              :  * When the parent of a partition receives [the referencing side of] a foreign
   11759              :  * key, we must propagate that foreign key to the partition.  However, the
   11760              :  * partition might already have an equivalent foreign key; this routine
   11761              :  * compares the given ForeignKeyCacheInfo (in the partition) to the FK defined
   11762              :  * by the other parameters.  If they are equivalent, create the link between
   11763              :  * the two constraints and return true.
   11764              :  *
   11765              :  * If the given FK does not match the one defined by rest of the params,
   11766              :  * return false.
   11767              :  */
   11768              : static bool
   11769          183 : tryAttachPartitionForeignKey(List **wqueue,
   11770              :                              ForeignKeyCacheInfo *fk,
   11771              :                              Relation partition,
   11772              :                              Oid parentConstrOid,
   11773              :                              int numfks,
   11774              :                              AttrNumber *mapped_conkey,
   11775              :                              AttrNumber *confkey,
   11776              :                              Oid *conpfeqop,
   11777              :                              Oid parentInsTrigger,
   11778              :                              Oid parentUpdTrigger,
   11779              :                              Relation trigrel)
   11780              : {
   11781              :     HeapTuple   parentConstrTup;
   11782              :     Form_pg_constraint parentConstr;
   11783              :     HeapTuple   partcontup;
   11784              :     Form_pg_constraint partConstr;
   11785              : 
   11786          183 :     parentConstrTup = SearchSysCache1(CONSTROID,
   11787              :                                       ObjectIdGetDatum(parentConstrOid));
   11788          183 :     if (!HeapTupleIsValid(parentConstrTup))
   11789            0 :         elog(ERROR, "cache lookup failed for constraint %u", parentConstrOid);
   11790          183 :     parentConstr = (Form_pg_constraint) GETSTRUCT(parentConstrTup);
   11791              : 
   11792              :     /*
   11793              :      * Do some quick & easy initial checks.  If any of these fail, we cannot
   11794              :      * use this constraint.
   11795              :      */
   11796          183 :     if (fk->confrelid != parentConstr->confrelid || fk->nkeys != numfks)
   11797              :     {
   11798            0 :         ReleaseSysCache(parentConstrTup);
   11799            0 :         return false;
   11800              :     }
   11801          505 :     for (int i = 0; i < numfks; i++)
   11802              :     {
   11803          324 :         if (fk->conkey[i] != mapped_conkey[i] ||
   11804          322 :             fk->confkey[i] != confkey[i] ||
   11805          322 :             fk->conpfeqop[i] != conpfeqop[i])
   11806              :         {
   11807            2 :             ReleaseSysCache(parentConstrTup);
   11808            2 :             return false;
   11809              :         }
   11810              :     }
   11811              : 
   11812              :     /* Looks good so far; perform more extensive checks. */
   11813          181 :     partcontup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(fk->conoid));
   11814          181 :     if (!HeapTupleIsValid(partcontup))
   11815            0 :         elog(ERROR, "cache lookup failed for constraint %u", fk->conoid);
   11816          181 :     partConstr = (Form_pg_constraint) GETSTRUCT(partcontup);
   11817              : 
   11818              :     /*
   11819              :      * An error should be raised if the constraint enforceability is
   11820              :      * different. Returning false without raising an error, as we do for other
   11821              :      * attributes, could lead to a duplicate constraint with the same
   11822              :      * enforceability as the parent. While this may be acceptable, it may not
   11823              :      * be ideal. Therefore, it's better to raise an error and allow the user
   11824              :      * to correct the enforceability before proceeding.
   11825              :      */
   11826          181 :     if (partConstr->conenforced != parentConstr->conenforced)
   11827            4 :         ereport(ERROR,
   11828              :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
   11829              :                  errmsg("constraint \"%s\" enforceability conflicts with constraint \"%s\" on relation \"%s\"",
   11830              :                         NameStr(parentConstr->conname),
   11831              :                         NameStr(partConstr->conname),
   11832              :                         RelationGetRelationName(partition))));
   11833              : 
   11834          177 :     if (OidIsValid(partConstr->conparentid) ||
   11835          158 :         partConstr->condeferrable != parentConstr->condeferrable ||
   11836          140 :         partConstr->condeferred != parentConstr->condeferred ||
   11837          140 :         partConstr->confupdtype != parentConstr->confupdtype ||
   11838          117 :         partConstr->confdeltype != parentConstr->confdeltype ||
   11839          117 :         partConstr->confmatchtype != parentConstr->confmatchtype)
   11840              :     {
   11841           69 :         ReleaseSysCache(parentConstrTup);
   11842           69 :         ReleaseSysCache(partcontup);
   11843           69 :         return false;
   11844              :     }
   11845              : 
   11846          108 :     ReleaseSysCache(parentConstrTup);
   11847          108 :     ReleaseSysCache(partcontup);
   11848              : 
   11849              :     /* Looks good!  Attach this constraint. */
   11850          108 :     AttachPartitionForeignKey(wqueue, partition, fk->conoid,
   11851              :                               parentConstrOid, parentInsTrigger,
   11852              :                               parentUpdTrigger, trigrel);
   11853              : 
   11854          108 :     return true;
   11855              : }
   11856              : 
   11857              : /*
   11858              :  * AttachPartitionForeignKey
   11859              :  *
   11860              :  * The subroutine for tryAttachPartitionForeignKey performs the final tasks of
   11861              :  * attaching the constraint, removing redundant triggers and entries from
   11862              :  * pg_constraint, and setting the constraint's parent.
   11863              :  */
   11864              : static void
   11865          108 : AttachPartitionForeignKey(List **wqueue,
   11866              :                           Relation partition,
   11867              :                           Oid partConstrOid,
   11868              :                           Oid parentConstrOid,
   11869              :                           Oid parentInsTrigger,
   11870              :                           Oid parentUpdTrigger,
   11871              :                           Relation trigrel)
   11872              : {
   11873              :     HeapTuple   parentConstrTup;
   11874              :     Form_pg_constraint parentConstr;
   11875              :     HeapTuple   partcontup;
   11876              :     Form_pg_constraint partConstr;
   11877              :     bool        queueValidation;
   11878              :     Oid         partConstrFrelid;
   11879              :     Oid         partConstrRelid;
   11880              :     bool        parentConstrIsEnforced;
   11881              : 
   11882              :     /* Fetch the parent constraint tuple */
   11883          108 :     parentConstrTup = SearchSysCache1(CONSTROID,
   11884              :                                       ObjectIdGetDatum(parentConstrOid));
   11885          108 :     if (!HeapTupleIsValid(parentConstrTup))
   11886            0 :         elog(ERROR, "cache lookup failed for constraint %u", parentConstrOid);
   11887          108 :     parentConstr = (Form_pg_constraint) GETSTRUCT(parentConstrTup);
   11888          108 :     parentConstrIsEnforced = parentConstr->conenforced;
   11889              : 
   11890              :     /* Fetch the child constraint tuple */
   11891          108 :     partcontup = SearchSysCache1(CONSTROID,
   11892              :                                  ObjectIdGetDatum(partConstrOid));
   11893          108 :     if (!HeapTupleIsValid(partcontup))
   11894            0 :         elog(ERROR, "cache lookup failed for constraint %u", partConstrOid);
   11895          108 :     partConstr = (Form_pg_constraint) GETSTRUCT(partcontup);
   11896          108 :     partConstrFrelid = partConstr->confrelid;
   11897          108 :     partConstrRelid = partConstr->conrelid;
   11898              : 
   11899              :     /*
   11900              :      * If the referenced table is partitioned, then the partition we're
   11901              :      * attaching now has extra pg_constraint rows and action triggers that are
   11902              :      * no longer needed.  Remove those.
   11903              :      */
   11904          108 :     if (get_rel_relkind(partConstrFrelid) == RELKIND_PARTITIONED_TABLE)
   11905              :     {
   11906           24 :         Relation    pg_constraint = table_open(ConstraintRelationId, RowShareLock);
   11907              : 
   11908           24 :         RemoveInheritedConstraint(pg_constraint, trigrel, partConstrOid,
   11909              :                                   partConstrRelid);
   11910              : 
   11911           24 :         table_close(pg_constraint, RowShareLock);
   11912              :     }
   11913              : 
   11914              :     /*
   11915              :      * Will we need to validate this constraint?   A valid parent constraint
   11916              :      * implies that all child constraints have been validated, so if this one
   11917              :      * isn't, we must trigger phase 3 validation.
   11918              :      */
   11919          108 :     queueValidation = parentConstr->convalidated && !partConstr->convalidated;
   11920              : 
   11921          108 :     ReleaseSysCache(partcontup);
   11922          108 :     ReleaseSysCache(parentConstrTup);
   11923              : 
   11924              :     /*
   11925              :      * The action triggers in the new partition become redundant -- the parent
   11926              :      * table already has equivalent ones, and those will be able to reach the
   11927              :      * partition.  Remove the ones in the partition.  We identify them because
   11928              :      * they have our constraint OID, as well as being on the referenced rel.
   11929              :      */
   11930          108 :     DropForeignKeyConstraintTriggers(trigrel, partConstrOid, partConstrFrelid,
   11931              :                                      partConstrRelid);
   11932              : 
   11933          108 :     ConstraintSetParentConstraint(partConstrOid, parentConstrOid,
   11934              :                                   RelationGetRelid(partition));
   11935              : 
   11936              :     /*
   11937              :      * Like the constraint, attach partition's "check" triggers to the
   11938              :      * corresponding parent triggers if the constraint is ENFORCED. NOT
   11939              :      * ENFORCED constraints do not have these triggers.
   11940              :      */
   11941          108 :     if (parentConstrIsEnforced)
   11942              :     {
   11943              :         Oid         insertTriggerOid,
   11944              :                     updateTriggerOid;
   11945              : 
   11946          100 :         GetForeignKeyCheckTriggers(trigrel,
   11947              :                                    partConstrOid, partConstrFrelid, partConstrRelid,
   11948              :                                    &insertTriggerOid, &updateTriggerOid);
   11949              :         Assert(OidIsValid(insertTriggerOid) && OidIsValid(parentInsTrigger));
   11950          100 :         TriggerSetParentTrigger(trigrel, insertTriggerOid, parentInsTrigger,
   11951              :                                 RelationGetRelid(partition));
   11952              :         Assert(OidIsValid(updateTriggerOid) && OidIsValid(parentUpdTrigger));
   11953          100 :         TriggerSetParentTrigger(trigrel, updateTriggerOid, parentUpdTrigger,
   11954              :                                 RelationGetRelid(partition));
   11955              :     }
   11956              : 
   11957              :     /*
   11958              :      * We updated this pg_constraint row above to set its parent; validating
   11959              :      * it will cause its convalidated flag to change, so we need CCI here.  In
   11960              :      * addition, we need it unconditionally for the rare case where the parent
   11961              :      * table has *two* identical constraints; when reaching this function for
   11962              :      * the second one, we must have made our changes visible, otherwise we
   11963              :      * would try to attach both to this one.
   11964              :      */
   11965          108 :     CommandCounterIncrement();
   11966              : 
   11967              :     /* If validation is needed, put it in the queue now. */
   11968          108 :     if (queueValidation)
   11969              :     {
   11970              :         Relation    conrel;
   11971              :         Oid         confrelid;
   11972              : 
   11973           12 :         conrel = table_open(ConstraintRelationId, RowExclusiveLock);
   11974              : 
   11975           12 :         partcontup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(partConstrOid));
   11976           12 :         if (!HeapTupleIsValid(partcontup))
   11977            0 :             elog(ERROR, "cache lookup failed for constraint %u", partConstrOid);
   11978              : 
   11979           12 :         confrelid = ((Form_pg_constraint) GETSTRUCT(partcontup))->confrelid;
   11980              : 
   11981              :         /* Use the same lock as for AT_ValidateConstraint */
   11982           12 :         QueueFKConstraintValidation(wqueue, conrel, partition, confrelid,
   11983              :                                     partcontup, ShareUpdateExclusiveLock);
   11984           12 :         ReleaseSysCache(partcontup);
   11985           12 :         table_close(conrel, RowExclusiveLock);
   11986              :     }
   11987          108 : }
   11988              : 
   11989              : /*
   11990              :  * RemoveInheritedConstraint
   11991              :  *
   11992              :  * Removes the constraint and its associated trigger from the specified
   11993              :  * relation, which inherited the given constraint.
   11994              :  */
   11995              : static void
   11996           24 : RemoveInheritedConstraint(Relation conrel, Relation trigrel, Oid conoid,
   11997              :                           Oid conrelid)
   11998              : {
   11999              :     ObjectAddresses *objs;
   12000              :     HeapTuple   consttup;
   12001              :     ScanKeyData key;
   12002              :     SysScanDesc scan;
   12003              :     HeapTuple   trigtup;
   12004              : 
   12005           24 :     ScanKeyInit(&key,
   12006              :                 Anum_pg_constraint_conrelid,
   12007              :                 BTEqualStrategyNumber, F_OIDEQ,
   12008              :                 ObjectIdGetDatum(conrelid));
   12009              : 
   12010           24 :     scan = systable_beginscan(conrel,
   12011              :                               ConstraintRelidTypidNameIndexId,
   12012              :                               true, NULL, 1, &key);
   12013           24 :     objs = new_object_addresses();
   12014          216 :     while ((consttup = systable_getnext(scan)) != NULL)
   12015              :     {
   12016          192 :         Form_pg_constraint conform = (Form_pg_constraint) GETSTRUCT(consttup);
   12017              : 
   12018          192 :         if (conform->conparentid != conoid)
   12019          140 :             continue;
   12020              :         else
   12021              :         {
   12022              :             ObjectAddress addr;
   12023              :             SysScanDesc scan2;
   12024              :             ScanKeyData key2;
   12025              :             int         n PG_USED_FOR_ASSERTS_ONLY;
   12026              : 
   12027           52 :             ObjectAddressSet(addr, ConstraintRelationId, conform->oid);
   12028           52 :             add_exact_object_address(&addr, objs);
   12029              : 
   12030              :             /*
   12031              :              * First we must delete the dependency record that binds the
   12032              :              * constraint records together.
   12033              :              */
   12034           52 :             n = deleteDependencyRecordsForSpecific(ConstraintRelationId,
   12035              :                                                    conform->oid,
   12036              :                                                    DEPENDENCY_INTERNAL,
   12037              :                                                    ConstraintRelationId,
   12038              :                                                    conoid);
   12039              :             Assert(n == 1);     /* actually only one is expected */
   12040              : 
   12041              :             /*
   12042              :              * Now search for the triggers for this constraint and set them up
   12043              :              * for deletion too
   12044              :              */
   12045           52 :             ScanKeyInit(&key2,
   12046              :                         Anum_pg_trigger_tgconstraint,
   12047              :                         BTEqualStrategyNumber, F_OIDEQ,
   12048              :                         ObjectIdGetDatum(conform->oid));
   12049           52 :             scan2 = systable_beginscan(trigrel, TriggerConstraintIndexId,
   12050              :                                        true, NULL, 1, &key2);
   12051          156 :             while ((trigtup = systable_getnext(scan2)) != NULL)
   12052              :             {
   12053          104 :                 ObjectAddressSet(addr, TriggerRelationId,
   12054              :                                  ((Form_pg_trigger) GETSTRUCT(trigtup))->oid);
   12055          104 :                 add_exact_object_address(&addr, objs);
   12056              :             }
   12057           52 :             systable_endscan(scan2);
   12058              :         }
   12059              :     }
   12060              :     /* make the dependency deletions visible */
   12061           24 :     CommandCounterIncrement();
   12062           24 :     performMultipleDeletions(objs, DROP_RESTRICT,
   12063              :                              PERFORM_DELETION_INTERNAL);
   12064           24 :     systable_endscan(scan);
   12065           24 : }
   12066              : 
   12067              : /*
   12068              :  * DropForeignKeyConstraintTriggers
   12069              :  *
   12070              :  * The subroutine for tryAttachPartitionForeignKey handles the deletion of
   12071              :  * action triggers for the foreign key constraint.
   12072              :  *
   12073              :  * If valid confrelid and conrelid values are not provided, the respective
   12074              :  * trigger check will be skipped, and the trigger will be considered for
   12075              :  * removal.
   12076              :  */
   12077              : static void
   12078          156 : DropForeignKeyConstraintTriggers(Relation trigrel, Oid conoid, Oid confrelid,
   12079              :                                  Oid conrelid)
   12080              : {
   12081              :     ScanKeyData key;
   12082              :     SysScanDesc scan;
   12083              :     HeapTuple   trigtup;
   12084              : 
   12085          156 :     ScanKeyInit(&key,
   12086              :                 Anum_pg_trigger_tgconstraint,
   12087              :                 BTEqualStrategyNumber, F_OIDEQ,
   12088              :                 ObjectIdGetDatum(conoid));
   12089          156 :     scan = systable_beginscan(trigrel, TriggerConstraintIndexId, true,
   12090              :                               NULL, 1, &key);
   12091          676 :     while ((trigtup = systable_getnext(scan)) != NULL)
   12092              :     {
   12093          520 :         Form_pg_trigger trgform = (Form_pg_trigger) GETSTRUCT(trigtup);
   12094              :         ObjectAddress trigger;
   12095              : 
   12096              :         /* Invalid if trigger is not for a referential integrity constraint */
   12097          520 :         if (!OidIsValid(trgform->tgconstrrelid))
   12098          200 :             continue;
   12099          520 :         if (OidIsValid(conrelid) && trgform->tgconstrrelid != conrelid)
   12100          200 :             continue;
   12101          320 :         if (OidIsValid(confrelid) && trgform->tgrelid != confrelid)
   12102            0 :             continue;
   12103              : 
   12104              :         /* We should be dropping trigger related to foreign key constraint */
   12105              :         Assert(trgform->tgfoid == F_RI_FKEY_CHECK_INS ||
   12106              :                trgform->tgfoid == F_RI_FKEY_CHECK_UPD ||
   12107              :                trgform->tgfoid == F_RI_FKEY_CASCADE_DEL ||
   12108              :                trgform->tgfoid == F_RI_FKEY_CASCADE_UPD ||
   12109              :                trgform->tgfoid == F_RI_FKEY_RESTRICT_DEL ||
   12110              :                trgform->tgfoid == F_RI_FKEY_RESTRICT_UPD ||
   12111              :                trgform->tgfoid == F_RI_FKEY_SETNULL_DEL ||
   12112              :                trgform->tgfoid == F_RI_FKEY_SETNULL_UPD ||
   12113              :                trgform->tgfoid == F_RI_FKEY_SETDEFAULT_DEL ||
   12114              :                trgform->tgfoid == F_RI_FKEY_SETDEFAULT_UPD ||
   12115              :                trgform->tgfoid == F_RI_FKEY_NOACTION_DEL ||
   12116              :                trgform->tgfoid == F_RI_FKEY_NOACTION_UPD);
   12117              : 
   12118              :         /*
   12119              :          * The constraint is originally set up to contain this trigger as an
   12120              :          * implementation object, so there's a dependency record that links
   12121              :          * the two; however, since the trigger is no longer needed, we remove
   12122              :          * the dependency link in order to be able to drop the trigger while
   12123              :          * keeping the constraint intact.
   12124              :          */
   12125          320 :         deleteDependencyRecordsFor(TriggerRelationId,
   12126              :                                    trgform->oid,
   12127              :                                    false);
   12128              :         /* make dependency deletion visible to performDeletion */
   12129          320 :         CommandCounterIncrement();
   12130          320 :         ObjectAddressSet(trigger, TriggerRelationId,
   12131              :                          trgform->oid);
   12132          320 :         performDeletion(&trigger, DROP_RESTRICT, 0);
   12133              :         /* make trigger drop visible, in case the loop iterates */
   12134          320 :         CommandCounterIncrement();
   12135              :     }
   12136              : 
   12137          156 :     systable_endscan(scan);
   12138          156 : }
   12139              : 
   12140              : /*
   12141              :  * GetForeignKeyActionTriggers
   12142              :  *      Returns delete and update "action" triggers of the given relation
   12143              :  *      belonging to the given constraint
   12144              :  */
   12145              : static void
   12146          172 : GetForeignKeyActionTriggers(Relation trigrel,
   12147              :                             Oid conoid, Oid confrelid, Oid conrelid,
   12148              :                             Oid *deleteTriggerOid,
   12149              :                             Oid *updateTriggerOid)
   12150              : {
   12151              :     ScanKeyData key;
   12152              :     SysScanDesc scan;
   12153              :     HeapTuple   trigtup;
   12154              : 
   12155          172 :     *deleteTriggerOid = *updateTriggerOid = InvalidOid;
   12156          172 :     ScanKeyInit(&key,
   12157              :                 Anum_pg_trigger_tgconstraint,
   12158              :                 BTEqualStrategyNumber, F_OIDEQ,
   12159              :                 ObjectIdGetDatum(conoid));
   12160              : 
   12161          172 :     scan = systable_beginscan(trigrel, TriggerConstraintIndexId, true,
   12162              :                               NULL, 1, &key);
   12163          356 :     while ((trigtup = systable_getnext(scan)) != NULL)
   12164              :     {
   12165          356 :         Form_pg_trigger trgform = (Form_pg_trigger) GETSTRUCT(trigtup);
   12166              : 
   12167          356 :         if (trgform->tgconstrrelid != conrelid)
   12168           12 :             continue;
   12169          344 :         if (trgform->tgrelid != confrelid)
   12170            0 :             continue;
   12171              :         /* Only ever look at "action" triggers on the PK side. */
   12172          344 :         if (RI_FKey_trigger_type(trgform->tgfoid) != RI_TRIGGER_PK)
   12173            0 :             continue;
   12174          344 :         if (TRIGGER_FOR_DELETE(trgform->tgtype))
   12175              :         {
   12176              :             Assert(*deleteTriggerOid == InvalidOid);
   12177          172 :             *deleteTriggerOid = trgform->oid;
   12178              :         }
   12179          172 :         else if (TRIGGER_FOR_UPDATE(trgform->tgtype))
   12180              :         {
   12181              :             Assert(*updateTriggerOid == InvalidOid);
   12182          172 :             *updateTriggerOid = trgform->oid;
   12183              :         }
   12184              : #ifndef USE_ASSERT_CHECKING
   12185              :         /* In an assert-enabled build, continue looking to find duplicates */
   12186          344 :         if (OidIsValid(*deleteTriggerOid) && OidIsValid(*updateTriggerOid))
   12187          172 :             break;
   12188              : #endif
   12189              :     }
   12190              : 
   12191          172 :     if (!OidIsValid(*deleteTriggerOid))
   12192            0 :         elog(ERROR, "could not find ON DELETE action trigger of foreign key constraint %u",
   12193              :              conoid);
   12194          172 :     if (!OidIsValid(*updateTriggerOid))
   12195            0 :         elog(ERROR, "could not find ON UPDATE action trigger of foreign key constraint %u",
   12196              :              conoid);
   12197              : 
   12198          172 :     systable_endscan(scan);
   12199          172 : }
   12200              : 
   12201              : /*
   12202              :  * GetForeignKeyCheckTriggers
   12203              :  *      Returns insert and update "check" triggers of the given relation
   12204              :  *      belonging to the given constraint
   12205              :  */
   12206              : static void
   12207          587 : GetForeignKeyCheckTriggers(Relation trigrel,
   12208              :                            Oid conoid, Oid confrelid, Oid conrelid,
   12209              :                            Oid *insertTriggerOid,
   12210              :                            Oid *updateTriggerOid)
   12211              : {
   12212              :     ScanKeyData key;
   12213              :     SysScanDesc scan;
   12214              :     HeapTuple   trigtup;
   12215              : 
   12216          587 :     *insertTriggerOid = *updateTriggerOid = InvalidOid;
   12217          587 :     ScanKeyInit(&key,
   12218              :                 Anum_pg_trigger_tgconstraint,
   12219              :                 BTEqualStrategyNumber, F_OIDEQ,
   12220              :                 ObjectIdGetDatum(conoid));
   12221              : 
   12222          587 :     scan = systable_beginscan(trigrel, TriggerConstraintIndexId, true,
   12223              :                               NULL, 1, &key);
   12224         1914 :     while ((trigtup = systable_getnext(scan)) != NULL)
   12225              :     {
   12226         1914 :         Form_pg_trigger trgform = (Form_pg_trigger) GETSTRUCT(trigtup);
   12227              : 
   12228         1914 :         if (trgform->tgconstrrelid != confrelid)
   12229          668 :             continue;
   12230         1246 :         if (trgform->tgrelid != conrelid)
   12231            0 :             continue;
   12232              :         /* Only ever look at "check" triggers on the FK side. */
   12233         1246 :         if (RI_FKey_trigger_type(trgform->tgfoid) != RI_TRIGGER_FK)
   12234           72 :             continue;
   12235         1174 :         if (TRIGGER_FOR_INSERT(trgform->tgtype))
   12236              :         {
   12237              :             Assert(*insertTriggerOid == InvalidOid);
   12238          587 :             *insertTriggerOid = trgform->oid;
   12239              :         }
   12240          587 :         else if (TRIGGER_FOR_UPDATE(trgform->tgtype))
   12241              :         {
   12242              :             Assert(*updateTriggerOid == InvalidOid);
   12243          587 :             *updateTriggerOid = trgform->oid;
   12244              :         }
   12245              : #ifndef USE_ASSERT_CHECKING
   12246              :         /* In an assert-enabled build, continue looking to find duplicates. */
   12247         1174 :         if (OidIsValid(*insertTriggerOid) && OidIsValid(*updateTriggerOid))
   12248          587 :             break;
   12249              : #endif
   12250              :     }
   12251              : 
   12252          587 :     if (!OidIsValid(*insertTriggerOid))
   12253            0 :         elog(ERROR, "could not find ON INSERT check triggers of foreign key constraint %u",
   12254              :              conoid);
   12255          587 :     if (!OidIsValid(*updateTriggerOid))
   12256            0 :         elog(ERROR, "could not find ON UPDATE check triggers of foreign key constraint %u",
   12257              :              conoid);
   12258              : 
   12259          587 :     systable_endscan(scan);
   12260          587 : }
   12261              : 
   12262              : /*
   12263              :  * ALTER TABLE ALTER CONSTRAINT
   12264              :  *
   12265              :  * Update the attributes of a constraint.
   12266              :  *
   12267              :  * Currently works for Foreign Key, Check, and not null constraints.
   12268              :  *
   12269              :  * If the constraint is modified, returns its address; otherwise, return
   12270              :  * InvalidObjectAddress.
   12271              :  */
   12272              : static ObjectAddress
   12273          284 : ATExecAlterConstraint(List **wqueue, Relation rel, ATAlterConstraint *cmdcon,
   12274              :                       bool recurse, LOCKMODE lockmode)
   12275              : {
   12276              :     Relation    conrel;
   12277              :     Relation    tgrel;
   12278              :     SysScanDesc scan;
   12279              :     ScanKeyData skey[3];
   12280              :     HeapTuple   contuple;
   12281              :     Form_pg_constraint currcon;
   12282              :     ObjectAddress address;
   12283              : 
   12284              :     /*
   12285              :      * Disallow altering ONLY a partitioned table, as it would make no sense.
   12286              :      * This is okay for legacy inheritance.
   12287              :      */
   12288          284 :     if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && !recurse)
   12289            0 :         ereport(ERROR,
   12290              :                 errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   12291              :                 errmsg("constraint must be altered in child tables too"),
   12292              :                 errhint("Do not specify the ONLY keyword."));
   12293              : 
   12294              : 
   12295          284 :     conrel = table_open(ConstraintRelationId, RowExclusiveLock);
   12296          284 :     tgrel = table_open(TriggerRelationId, RowExclusiveLock);
   12297              : 
   12298              :     /*
   12299              :      * Find and check the target constraint
   12300              :      */
   12301          284 :     ScanKeyInit(&skey[0],
   12302              :                 Anum_pg_constraint_conrelid,
   12303              :                 BTEqualStrategyNumber, F_OIDEQ,
   12304              :                 ObjectIdGetDatum(RelationGetRelid(rel)));
   12305          284 :     ScanKeyInit(&skey[1],
   12306              :                 Anum_pg_constraint_contypid,
   12307              :                 BTEqualStrategyNumber, F_OIDEQ,
   12308              :                 ObjectIdGetDatum(InvalidOid));
   12309          284 :     ScanKeyInit(&skey[2],
   12310              :                 Anum_pg_constraint_conname,
   12311              :                 BTEqualStrategyNumber, F_NAMEEQ,
   12312          284 :                 CStringGetDatum(cmdcon->conname));
   12313          284 :     scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
   12314              :                               true, NULL, 3, skey);
   12315              : 
   12316              :     /* There can be at most one matching row */
   12317          284 :     if (!HeapTupleIsValid(contuple = systable_getnext(scan)))
   12318            4 :         ereport(ERROR,
   12319              :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
   12320              :                  errmsg("constraint \"%s\" of relation \"%s\" does not exist",
   12321              :                         cmdcon->conname, RelationGetRelationName(rel))));
   12322              : 
   12323          280 :     currcon = (Form_pg_constraint) GETSTRUCT(contuple);
   12324          280 :     if (cmdcon->alterDeferrability && currcon->contype != CONSTRAINT_FOREIGN)
   12325            0 :         ereport(ERROR,
   12326              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   12327              :                  errmsg("constraint \"%s\" of relation \"%s\" is not a foreign key constraint",
   12328              :                         cmdcon->conname, RelationGetRelationName(rel))));
   12329          280 :     if (cmdcon->alterEnforceability &&
   12330          148 :         (currcon->contype != CONSTRAINT_FOREIGN && currcon->contype != CONSTRAINT_CHECK))
   12331            8 :         ereport(ERROR,
   12332              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   12333              :                  errmsg("cannot alter enforceability of constraint \"%s\" of relation \"%s\"",
   12334              :                         cmdcon->conname, RelationGetRelationName(rel)),
   12335              :                  errhint("Only foreign key and check constraints can change enforceability.")));
   12336          272 :     if (cmdcon->alterInheritability &&
   12337           60 :         currcon->contype != CONSTRAINT_NOTNULL)
   12338           16 :         ereport(ERROR,
   12339              :                 errcode(ERRCODE_WRONG_OBJECT_TYPE),
   12340              :                 errmsg("constraint \"%s\" of relation \"%s\" is not a not-null constraint",
   12341              :                        cmdcon->conname, RelationGetRelationName(rel)));
   12342              : 
   12343              :     /* Refuse to modify inheritability of inherited constraints */
   12344          256 :     if (cmdcon->alterInheritability &&
   12345           44 :         cmdcon->noinherit && currcon->coninhcount > 0)
   12346            4 :         ereport(ERROR,
   12347              :                 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
   12348              :                 errmsg("cannot alter inherited constraint \"%s\" on relation \"%s\"",
   12349              :                        NameStr(currcon->conname),
   12350              :                        RelationGetRelationName(rel)));
   12351              : 
   12352              :     /*
   12353              :      * If it's not the topmost constraint, raise an error.
   12354              :      *
   12355              :      * Altering a non-topmost constraint leaves some triggers untouched, since
   12356              :      * they are not directly connected to this constraint; also, pg_dump would
   12357              :      * ignore the deferrability status of the individual constraint, since it
   12358              :      * only dumps topmost constraints.  Avoid these problems by refusing this
   12359              :      * operation and telling the user to alter the parent constraint instead.
   12360              :      */
   12361          252 :     if (OidIsValid(currcon->conparentid))
   12362              :     {
   12363              :         HeapTuple   tp;
   12364            8 :         Oid         parent = currcon->conparentid;
   12365            8 :         char       *ancestorname = NULL;
   12366            8 :         char       *ancestortable = NULL;
   12367              : 
   12368              :         /* Loop to find the topmost constraint */
   12369           16 :         while (HeapTupleIsValid(tp = SearchSysCache1(CONSTROID, ObjectIdGetDatum(parent))))
   12370              :         {
   12371           16 :             Form_pg_constraint contup = (Form_pg_constraint) GETSTRUCT(tp);
   12372              : 
   12373              :             /* If no parent, this is the constraint we want */
   12374           16 :             if (!OidIsValid(contup->conparentid))
   12375              :             {
   12376            8 :                 ancestorname = pstrdup(NameStr(contup->conname));
   12377            8 :                 ancestortable = get_rel_name(contup->conrelid);
   12378            8 :                 ReleaseSysCache(tp);
   12379            8 :                 break;
   12380              :             }
   12381              : 
   12382            8 :             parent = contup->conparentid;
   12383            8 :             ReleaseSysCache(tp);
   12384              :         }
   12385              : 
   12386            8 :         ereport(ERROR,
   12387              :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
   12388              :                  errmsg("cannot alter constraint \"%s\" on relation \"%s\"",
   12389              :                         cmdcon->conname, RelationGetRelationName(rel)),
   12390              :                  ancestorname && ancestortable ?
   12391              :                  errdetail("Constraint \"%s\" is derived from constraint \"%s\" of relation \"%s\".",
   12392              :                            cmdcon->conname, ancestorname, ancestortable) : 0,
   12393              :                  errhint("You may alter the constraint it derives from instead.")));
   12394              :     }
   12395              : 
   12396          244 :     address = InvalidObjectAddress;
   12397              : 
   12398              :     /*
   12399              :      * Do the actual catalog work, and recurse if necessary.
   12400              :      */
   12401          244 :     if (ATExecAlterConstraintInternal(wqueue, cmdcon, conrel, tgrel, rel,
   12402              :                                       contuple, recurse, lockmode))
   12403          224 :         ObjectAddressSet(address, ConstraintRelationId, currcon->oid);
   12404              : 
   12405          232 :     systable_endscan(scan);
   12406              : 
   12407          232 :     table_close(tgrel, RowExclusiveLock);
   12408          232 :     table_close(conrel, RowExclusiveLock);
   12409              : 
   12410          232 :     return address;
   12411              : }
   12412              : 
   12413              : /*
   12414              :  * A subroutine of ATExecAlterConstraint that calls the respective routines for
   12415              :  * altering constraint's enforceability, deferrability or inheritability.
   12416              :  */
   12417              : static bool
   12418          244 : ATExecAlterConstraintInternal(List **wqueue, ATAlterConstraint *cmdcon,
   12419              :                               Relation conrel, Relation tgrel, Relation rel,
   12420              :                               HeapTuple contuple, bool recurse,
   12421              :                               LOCKMODE lockmode)
   12422              : {
   12423              :     Form_pg_constraint currcon;
   12424          244 :     bool        changed = false;
   12425          244 :     List       *otherrelids = NIL;
   12426              : 
   12427          244 :     currcon = (Form_pg_constraint) GETSTRUCT(contuple);
   12428              : 
   12429              :     /*
   12430              :      * Do the catalog work for the enforceability or deferrability change,
   12431              :      * recurse if necessary.
   12432              :      *
   12433              :      * Note that even if deferrability is requested to be altered along with
   12434              :      * enforceability, we don't need to explicitly update multiple entries in
   12435              :      * pg_trigger related to deferrability.
   12436              :      *
   12437              :      * Modifying foreign key enforceability involves either creating or
   12438              :      * dropping the trigger, during which the deferrability setting will be
   12439              :      * adjusted automatically.
   12440              :      */
   12441          244 :     if (cmdcon->alterEnforceability)
   12442              :     {
   12443          140 :         if (currcon->contype == CONSTRAINT_FOREIGN)
   12444           52 :             changed = ATExecAlterFKConstrEnforceability(wqueue, cmdcon, conrel, tgrel,
   12445              :                                                         currcon->conrelid,
   12446              :                                                         currcon->confrelid,
   12447              :                                                         contuple, lockmode,
   12448              :                                                         InvalidOid, InvalidOid,
   12449              :                                                         InvalidOid, InvalidOid);
   12450           88 :         else if (currcon->contype == CONSTRAINT_CHECK)
   12451           88 :             changed = ATExecAlterCheckConstrEnforceability(wqueue, cmdcon, conrel,
   12452              :                                                            contuple, recurse, false,
   12453              :                                                            lockmode);
   12454              :     }
   12455          168 :     else if (cmdcon->alterDeferrability &&
   12456           64 :              ATExecAlterConstrDeferrability(wqueue, cmdcon, conrel, tgrel, rel,
   12457              :                                             contuple, recurse, &otherrelids,
   12458              :                                             lockmode))
   12459              :     {
   12460              :         /*
   12461              :          * AlterConstrUpdateConstraintEntry already invalidated relcache for
   12462              :          * the relations having the constraint itself; here we also invalidate
   12463              :          * for relations that have any triggers that are part of the
   12464              :          * constraint.
   12465              :          */
   12466          204 :         foreach_oid(relid, otherrelids)
   12467           76 :             CacheInvalidateRelcacheByRelid(relid);
   12468              : 
   12469           64 :         changed = true;
   12470              :     }
   12471              : 
   12472              :     /*
   12473              :      * Do the catalog work for the inheritability change.
   12474              :      */
   12475          272 :     if (cmdcon->alterInheritability &&
   12476           40 :         ATExecAlterConstrInheritability(wqueue, cmdcon, conrel, rel, contuple,
   12477              :                                         lockmode))
   12478           36 :         changed = true;
   12479              : 
   12480          232 :     return changed;
   12481              : }
   12482              : 
   12483              : /*
   12484              :  * Returns true if the foreign key constraint's enforceability is altered.
   12485              :  *
   12486              :  * Depending on whether the constraint is being set to ENFORCED or NOT
   12487              :  * ENFORCED, it creates or drops the trigger accordingly.
   12488              :  *
   12489              :  * Note that we must recurse even when trying to change a constraint to not
   12490              :  * enforced if it is already not enforced, in case descendant constraints
   12491              :  * might be enforced and need to be changed to not enforced. Conversely, we
   12492              :  * should do nothing if a constraint is being set to enforced and is already
   12493              :  * enforced, as descendant constraints cannot be different in that case.
   12494              :  */
   12495              : static bool
   12496          120 : ATExecAlterFKConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon,
   12497              :                                   Relation conrel, Relation tgrel,
   12498              :                                   Oid fkrelid, Oid pkrelid,
   12499              :                                   HeapTuple contuple, LOCKMODE lockmode,
   12500              :                                   Oid ReferencedParentDelTrigger,
   12501              :                                   Oid ReferencedParentUpdTrigger,
   12502              :                                   Oid ReferencingParentInsTrigger,
   12503              :                                   Oid ReferencingParentUpdTrigger)
   12504              : {
   12505              :     Form_pg_constraint currcon;
   12506              :     Oid         conoid;
   12507              :     Relation    rel;
   12508          120 :     bool        changed = false;
   12509              : 
   12510              :     /* Since this function recurses, it could be driven to stack overflow */
   12511          120 :     check_stack_depth();
   12512              : 
   12513              :     Assert(cmdcon->alterEnforceability);
   12514              : 
   12515          120 :     currcon = (Form_pg_constraint) GETSTRUCT(contuple);
   12516          120 :     conoid = currcon->oid;
   12517              : 
   12518              :     /* Should be foreign key constraint */
   12519              :     Assert(currcon->contype == CONSTRAINT_FOREIGN);
   12520              : 
   12521          120 :     rel = table_open(currcon->conrelid, lockmode);
   12522              : 
   12523          120 :     if (currcon->conenforced != cmdcon->is_enforced)
   12524              :     {
   12525          116 :         AlterConstrUpdateConstraintEntry(cmdcon, conrel, contuple);
   12526          116 :         changed = true;
   12527              :     }
   12528              : 
   12529              :     /* Drop triggers */
   12530          120 :     if (!cmdcon->is_enforced)
   12531              :     {
   12532              :         /*
   12533              :          * When setting a constraint to NOT ENFORCED, the constraint triggers
   12534              :          * need to be dropped. Therefore, we must process the child relations
   12535              :          * first, followed by the parent, to account for dependencies.
   12536              :          */
   12537           84 :         if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
   12538           36 :             get_rel_relkind(currcon->confrelid) == RELKIND_PARTITIONED_TABLE)
   12539           12 :             AlterFKConstrEnforceabilityRecurse(wqueue, cmdcon, conrel, tgrel,
   12540              :                                                fkrelid, pkrelid, contuple,
   12541              :                                                lockmode, InvalidOid, InvalidOid,
   12542              :                                                InvalidOid, InvalidOid);
   12543              : 
   12544              :         /* Drop all the triggers */
   12545           48 :         DropForeignKeyConstraintTriggers(tgrel, conoid, InvalidOid, InvalidOid);
   12546              :     }
   12547           72 :     else if (changed)           /* Create triggers */
   12548              :     {
   12549           72 :         Oid         ReferencedDelTriggerOid = InvalidOid,
   12550           72 :                     ReferencedUpdTriggerOid = InvalidOid,
   12551           72 :                     ReferencingInsTriggerOid = InvalidOid,
   12552           72 :                     ReferencingUpdTriggerOid = InvalidOid;
   12553              : 
   12554              :         /* Prepare the minimal information required for trigger creation. */
   12555           72 :         Constraint *fkconstraint = makeNode(Constraint);
   12556              : 
   12557           72 :         fkconstraint->conname = pstrdup(NameStr(currcon->conname));
   12558           72 :         fkconstraint->fk_matchtype = currcon->confmatchtype;
   12559           72 :         fkconstraint->fk_upd_action = currcon->confupdtype;
   12560           72 :         fkconstraint->fk_del_action = currcon->confdeltype;
   12561              : 
   12562              :         /* Create referenced triggers */
   12563           72 :         if (currcon->conrelid == fkrelid)
   12564           44 :             createForeignKeyActionTriggers(currcon->conrelid,
   12565              :                                            currcon->confrelid,
   12566              :                                            fkconstraint,
   12567              :                                            conoid,
   12568              :                                            currcon->conindid,
   12569              :                                            ReferencedParentDelTrigger,
   12570              :                                            ReferencedParentUpdTrigger,
   12571              :                                            &ReferencedDelTriggerOid,
   12572              :                                            &ReferencedUpdTriggerOid);
   12573              : 
   12574              :         /* Create referencing triggers */
   12575           72 :         if (currcon->confrelid == pkrelid)
   12576           60 :             createForeignKeyCheckTriggers(currcon->conrelid,
   12577              :                                           pkrelid,
   12578              :                                           fkconstraint,
   12579              :                                           conoid,
   12580              :                                           currcon->conindid,
   12581              :                                           ReferencingParentInsTrigger,
   12582              :                                           ReferencingParentUpdTrigger,
   12583              :                                           &ReferencingInsTriggerOid,
   12584              :                                           &ReferencingUpdTriggerOid);
   12585              : 
   12586              :         /*
   12587              :          * Tell Phase 3 to check that the constraint is satisfied by existing
   12588              :          * rows.  Only applies to leaf partitions, and (for constraints that
   12589              :          * reference a partitioned table) only if this is not one of the
   12590              :          * pg_constraint rows that exist solely to support action triggers.
   12591              :          */
   12592           72 :         if (rel->rd_rel->relkind == RELKIND_RELATION &&
   12593           60 :             currcon->confrelid == pkrelid)
   12594              :         {
   12595              :             AlteredTableInfo *tab;
   12596              :             NewConstraint *newcon;
   12597              : 
   12598           48 :             newcon = palloc0_object(NewConstraint);
   12599           48 :             newcon->name = fkconstraint->conname;
   12600           48 :             newcon->contype = CONSTR_FOREIGN;
   12601           48 :             newcon->refrelid = currcon->confrelid;
   12602           48 :             newcon->refindid = currcon->conindid;
   12603           48 :             newcon->conid = currcon->oid;
   12604           48 :             newcon->qual = (Node *) fkconstraint;
   12605              : 
   12606              :             /* Find or create work queue entry for this table */
   12607           48 :             tab = ATGetQueueEntry(wqueue, rel);
   12608           48 :             tab->constraints = lappend(tab->constraints, newcon);
   12609              :         }
   12610              : 
   12611              :         /*
   12612              :          * If the table at either end of the constraint is partitioned, we
   12613              :          * need to recurse and create triggers for each constraint that is a
   12614              :          * child of this one.
   12615              :          */
   12616          132 :         if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
   12617           60 :             get_rel_relkind(currcon->confrelid) == RELKIND_PARTITIONED_TABLE)
   12618           20 :             AlterFKConstrEnforceabilityRecurse(wqueue, cmdcon, conrel, tgrel,
   12619              :                                                fkrelid, pkrelid, contuple,
   12620              :                                                lockmode,
   12621              :                                                ReferencedDelTriggerOid,
   12622              :                                                ReferencedUpdTriggerOid,
   12623              :                                                ReferencingInsTriggerOid,
   12624              :                                                ReferencingUpdTriggerOid);
   12625              :     }
   12626              : 
   12627          120 :     table_close(rel, NoLock);
   12628              : 
   12629          120 :     return changed;
   12630              : }
   12631              : 
   12632              : /*
   12633              :  * Returns true if the CHECK constraint's enforceability is altered.
   12634              :  */
   12635              : static bool
   12636          236 : ATExecAlterCheckConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon,
   12637              :                                      Relation conrel, HeapTuple contuple,
   12638              :                                      bool recurse, bool recursing, LOCKMODE lockmode)
   12639              : {
   12640              :     Form_pg_constraint currcon;
   12641              :     Relation    rel;
   12642          236 :     bool        changed = false;
   12643          236 :     List       *children = NIL;
   12644              : 
   12645              :     /* Since this function recurses, it could be driven to stack overflow */
   12646          236 :     check_stack_depth();
   12647              : 
   12648              :     Assert(cmdcon->alterEnforceability);
   12649              : 
   12650          236 :     currcon = (Form_pg_constraint) GETSTRUCT(contuple);
   12651              : 
   12652              :     Assert(currcon->contype == CONSTRAINT_CHECK);
   12653              : 
   12654              :     /*
   12655              :      * Parent relation already locked by caller, children will be locked by
   12656              :      * find_all_inheritors. So NoLock is fine here.
   12657              :      */
   12658          236 :     rel = table_open(currcon->conrelid, NoLock);
   12659              : 
   12660          236 :     if (currcon->conenforced != cmdcon->is_enforced)
   12661              :     {
   12662          196 :         AlterConstrUpdateConstraintEntry(cmdcon, conrel, contuple);
   12663          196 :         changed = true;
   12664              :     }
   12665              : 
   12666              :     /*
   12667              :      * Note that we must recurse even when trying to change a check constraint
   12668              :      * to not enforced if it is already not enforced, in case descendant
   12669              :      * constraints might be enforced and need to be changed to not enforced.
   12670              :      * Conversely, we should do nothing if a constraint is being set to
   12671              :      * enforced and is already enforced, as descendant constraints cannot be
   12672              :      * different in that case.
   12673              :      */
   12674          236 :     if (!cmdcon->is_enforced || changed)
   12675              :     {
   12676              :         /*
   12677              :          * If we're recursing, the parent has already done this, so skip it.
   12678              :          * Also, if the constraint is a NO INHERIT constraint, we shouldn't
   12679              :          * try to look for it in the children.
   12680              :          */
   12681          220 :         if (!recursing && !currcon->connoinherit)
   12682           84 :             children = find_all_inheritors(RelationGetRelid(rel),
   12683              :                                            lockmode, NULL);
   12684              : 
   12685          664 :         foreach_oid(childoid, children)
   12686              :         {
   12687          240 :             if (childoid == RelationGetRelid(rel))
   12688           84 :                 continue;
   12689              : 
   12690              :             /*
   12691              :              * If we are told not to recurse, there had better not be any
   12692              :              * child tables, because we can't change constraint enforceability
   12693              :              * on the parent unless we have changed enforceability for all
   12694              :              * child.
   12695              :              */
   12696          156 :             if (!recurse)
   12697            8 :                 ereport(ERROR,
   12698              :                         errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   12699              :                         errmsg("constraint must be altered on child tables too"),
   12700              :                         errhint("Do not specify the ONLY keyword."));
   12701              : 
   12702          148 :             AlterCheckConstrEnforceabilityRecurse(wqueue, cmdcon, conrel,
   12703              :                                                   childoid, false, true,
   12704              :                                                   lockmode);
   12705              :         }
   12706              :     }
   12707              : 
   12708              :     /*
   12709              :      * Tell Phase 3 to check that the constraint is satisfied by existing
   12710              :      * rows. We only need do this when altering the constraint from NOT
   12711              :      * ENFORCED to ENFORCED.
   12712              :      */
   12713          228 :     if (rel->rd_rel->relkind == RELKIND_RELATION &&
   12714          180 :         !currcon->conenforced &&
   12715          128 :         cmdcon->is_enforced)
   12716              :     {
   12717              :         AlteredTableInfo *tab;
   12718              :         NewConstraint *newcon;
   12719              :         Datum       val;
   12720              :         char       *conbin;
   12721              : 
   12722          116 :         newcon = palloc0_object(NewConstraint);
   12723          116 :         newcon->name = pstrdup(NameStr(currcon->conname));
   12724          116 :         newcon->contype = CONSTR_CHECK;
   12725              : 
   12726          116 :         val = SysCacheGetAttrNotNull(CONSTROID, contuple,
   12727              :                                      Anum_pg_constraint_conbin);
   12728          116 :         conbin = TextDatumGetCString(val);
   12729          116 :         newcon->qual = expand_generated_columns_in_expr(stringToNode(conbin), rel, 1);
   12730              : 
   12731              :         /* Find or create work queue entry for this table */
   12732          116 :         tab = ATGetQueueEntry(wqueue, rel);
   12733          116 :         tab->constraints = lappend(tab->constraints, newcon);
   12734              :     }
   12735              : 
   12736          228 :     table_close(rel, NoLock);
   12737              : 
   12738          228 :     return changed;
   12739              : }
   12740              : 
   12741              : /*
   12742              :  * Invokes ATExecAlterCheckConstrEnforceability for each CHECK constraint that
   12743              :  * is a child of the specified constraint.
   12744              :  *
   12745              :  * We rely on the parent and child tables having identical CHECK constraint
   12746              :  * names to retrieve the child's pg_constraint tuple.
   12747              :  *
   12748              :  * The arguments to this function have the same meaning as the arguments to
   12749              :  * ATExecAlterCheckConstrEnforceability.
   12750              :  */
   12751              : static void
   12752          148 : AlterCheckConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
   12753              :                                       Relation conrel, Oid conrelid,
   12754              :                                       bool recurse, bool recursing,
   12755              :                                       LOCKMODE lockmode)
   12756              : {
   12757              :     SysScanDesc pscan;
   12758              :     HeapTuple   childtup;
   12759              :     ScanKeyData skey[3];
   12760              : 
   12761          148 :     ScanKeyInit(&skey[0],
   12762              :                 Anum_pg_constraint_conrelid,
   12763              :                 BTEqualStrategyNumber, F_OIDEQ,
   12764              :                 ObjectIdGetDatum(conrelid));
   12765          148 :     ScanKeyInit(&skey[1],
   12766              :                 Anum_pg_constraint_contypid,
   12767              :                 BTEqualStrategyNumber, F_OIDEQ,
   12768              :                 ObjectIdGetDatum(InvalidOid));
   12769          148 :     ScanKeyInit(&skey[2],
   12770              :                 Anum_pg_constraint_conname,
   12771              :                 BTEqualStrategyNumber, F_NAMEEQ,
   12772          148 :                 CStringGetDatum(cmdcon->conname));
   12773              : 
   12774          148 :     pscan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId, true,
   12775              :                                NULL, 3, skey);
   12776              : 
   12777          148 :     if (!HeapTupleIsValid(childtup = systable_getnext(pscan)))
   12778            0 :         ereport(ERROR,
   12779              :                 errcode(ERRCODE_UNDEFINED_OBJECT),
   12780              :                 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
   12781              :                        cmdcon->conname, get_rel_name(conrelid)));
   12782              : 
   12783          148 :     ATExecAlterCheckConstrEnforceability(wqueue, cmdcon, conrel, childtup,
   12784              :                                          recurse, recursing, lockmode);
   12785              : 
   12786          148 :     systable_endscan(pscan);
   12787          148 : }
   12788              : 
   12789              : /*
   12790              :  * Returns true if the constraint's deferrability is altered.
   12791              :  *
   12792              :  * *otherrelids is appended OIDs of relations containing affected triggers.
   12793              :  *
   12794              :  * Note that we must recurse even when the values are correct, in case
   12795              :  * indirect descendants have had their constraints altered locally.
   12796              :  * (This could be avoided if we forbade altering constraints in partitions
   12797              :  * but existing releases don't do that.)
   12798              :  */
   12799              : static bool
   12800          108 : ATExecAlterConstrDeferrability(List **wqueue, ATAlterConstraint *cmdcon,
   12801              :                                Relation conrel, Relation tgrel, Relation rel,
   12802              :                                HeapTuple contuple, bool recurse,
   12803              :                                List **otherrelids, LOCKMODE lockmode)
   12804              : {
   12805              :     Form_pg_constraint currcon;
   12806              :     Oid         refrelid;
   12807          108 :     bool        changed = false;
   12808              : 
   12809              :     /* since this function recurses, it could be driven to stack overflow */
   12810          108 :     check_stack_depth();
   12811              : 
   12812              :     Assert(cmdcon->alterDeferrability);
   12813              : 
   12814          108 :     currcon = (Form_pg_constraint) GETSTRUCT(contuple);
   12815          108 :     refrelid = currcon->confrelid;
   12816              : 
   12817              :     /* Should be foreign key constraint */
   12818              :     Assert(currcon->contype == CONSTRAINT_FOREIGN);
   12819              : 
   12820              :     /*
   12821              :      * If called to modify a constraint that's already in the desired state,
   12822              :      * silently do nothing.
   12823              :      */
   12824          108 :     if (currcon->condeferrable != cmdcon->deferrable ||
   12825            4 :         currcon->condeferred != cmdcon->initdeferred)
   12826              :     {
   12827          108 :         AlterConstrUpdateConstraintEntry(cmdcon, conrel, contuple);
   12828          108 :         changed = true;
   12829              : 
   12830              :         /*
   12831              :          * Now we need to update the multiple entries in pg_trigger that
   12832              :          * implement the constraint.
   12833              :          */
   12834          108 :         AlterConstrTriggerDeferrability(currcon->oid, tgrel, rel,
   12835          108 :                                         cmdcon->deferrable,
   12836          108 :                                         cmdcon->initdeferred, otherrelids);
   12837              :     }
   12838              : 
   12839              :     /*
   12840              :      * If the table at either end of the constraint is partitioned, we need to
   12841              :      * handle every constraint that is a child of this one.
   12842              :      */
   12843          108 :     if (recurse && changed &&
   12844          200 :         (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
   12845           92 :          get_rel_relkind(refrelid) == RELKIND_PARTITIONED_TABLE))
   12846           28 :         AlterConstrDeferrabilityRecurse(wqueue, cmdcon, conrel, tgrel, rel,
   12847              :                                         contuple, recurse, otherrelids,
   12848              :                                         lockmode);
   12849              : 
   12850          108 :     return changed;
   12851              : }
   12852              : 
   12853              : /*
   12854              :  * Returns true if the constraint's inheritability is altered.
   12855              :  */
   12856              : static bool
   12857           40 : ATExecAlterConstrInheritability(List **wqueue, ATAlterConstraint *cmdcon,
   12858              :                                 Relation conrel, Relation rel,
   12859              :                                 HeapTuple contuple, LOCKMODE lockmode)
   12860              : {
   12861              :     Form_pg_constraint currcon;
   12862              :     AttrNumber  colNum;
   12863              :     char       *colName;
   12864              :     List       *children;
   12865              : 
   12866              :     Assert(cmdcon->alterInheritability);
   12867              : 
   12868           40 :     currcon = (Form_pg_constraint) GETSTRUCT(contuple);
   12869              : 
   12870              :     /* The current implementation only works for NOT NULL constraints */
   12871              :     Assert(currcon->contype == CONSTRAINT_NOTNULL);
   12872              : 
   12873              :     /*
   12874              :      * If called to modify a constraint that's already in the desired state,
   12875              :      * silently do nothing.
   12876              :      */
   12877           40 :     if (cmdcon->noinherit == currcon->connoinherit)
   12878            0 :         return false;
   12879              : 
   12880           40 :     AlterConstrUpdateConstraintEntry(cmdcon, conrel, contuple);
   12881           40 :     CommandCounterIncrement();
   12882              : 
   12883              :     /* Fetch the column number and name */
   12884           40 :     colNum = extractNotNullColumn(contuple);
   12885           40 :     colName = get_attname(currcon->conrelid, colNum, false);
   12886              : 
   12887              :     /*
   12888              :      * Propagate the change to children.  For this subcommand type we don't
   12889              :      * recursively affect children, just the immediate level.
   12890              :      */
   12891           40 :     children = find_inheritance_children(RelationGetRelid(rel),
   12892              :                                          lockmode);
   12893          128 :     foreach_oid(childoid, children)
   12894              :     {
   12895              :         ObjectAddress addr;
   12896              : 
   12897           56 :         if (cmdcon->noinherit)
   12898              :         {
   12899              :             HeapTuple   childtup;
   12900              :             Form_pg_constraint childcon;
   12901              : 
   12902           20 :             childtup = findNotNullConstraint(childoid, colName);
   12903           20 :             if (!childtup)
   12904            0 :                 elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation %u",
   12905              :                      colName, childoid);
   12906           20 :             childcon = (Form_pg_constraint) GETSTRUCT(childtup);
   12907              :             Assert(childcon->coninhcount > 0);
   12908           20 :             childcon->coninhcount--;
   12909           20 :             childcon->conislocal = true;
   12910           20 :             CatalogTupleUpdate(conrel, &childtup->t_self, childtup);
   12911           20 :             heap_freetuple(childtup);
   12912              :         }
   12913              :         else
   12914              :         {
   12915           36 :             Relation    childrel = table_open(childoid, NoLock);
   12916              : 
   12917           36 :             addr = ATExecSetNotNull(wqueue, childrel, NameStr(currcon->conname),
   12918              :                                     colName, true, true, lockmode);
   12919           32 :             if (OidIsValid(addr.objectId))
   12920           32 :                 CommandCounterIncrement();
   12921           32 :             table_close(childrel, NoLock);
   12922              :         }
   12923              :     }
   12924              : 
   12925           36 :     return true;
   12926              : }
   12927              : 
   12928              : /*
   12929              :  * A subroutine of ATExecAlterConstrDeferrability that updated constraint
   12930              :  * trigger's deferrability.
   12931              :  *
   12932              :  * The arguments to this function have the same meaning as the arguments to
   12933              :  * ATExecAlterConstrDeferrability.
   12934              :  */
   12935              : static void
   12936          108 : AlterConstrTriggerDeferrability(Oid conoid, Relation tgrel, Relation rel,
   12937              :                                 bool deferrable, bool initdeferred,
   12938              :                                 List **otherrelids)
   12939              : {
   12940              :     HeapTuple   tgtuple;
   12941              :     ScanKeyData tgkey;
   12942              :     SysScanDesc tgscan;
   12943              : 
   12944          108 :     ScanKeyInit(&tgkey,
   12945              :                 Anum_pg_trigger_tgconstraint,
   12946              :                 BTEqualStrategyNumber, F_OIDEQ,
   12947              :                 ObjectIdGetDatum(conoid));
   12948          108 :     tgscan = systable_beginscan(tgrel, TriggerConstraintIndexId, true,
   12949              :                                 NULL, 1, &tgkey);
   12950          420 :     while (HeapTupleIsValid(tgtuple = systable_getnext(tgscan)))
   12951              :     {
   12952          312 :         Form_pg_trigger tgform = (Form_pg_trigger) GETSTRUCT(tgtuple);
   12953              :         Form_pg_trigger copy_tg;
   12954              :         HeapTuple   tgCopyTuple;
   12955              : 
   12956              :         /*
   12957              :          * Remember OIDs of other relation(s) involved in FK constraint.
   12958              :          * (Note: it's likely that we could skip forcing a relcache inval for
   12959              :          * other rels that don't have a trigger whose properties change, but
   12960              :          * let's be conservative.)
   12961              :          */
   12962          312 :         if (tgform->tgrelid != RelationGetRelid(rel))
   12963          152 :             *otherrelids = list_append_unique_oid(*otherrelids,
   12964              :                                                   tgform->tgrelid);
   12965              : 
   12966              :         /*
   12967              :          * Update enable status and deferrability of RI_FKey_noaction_del,
   12968              :          * RI_FKey_noaction_upd, RI_FKey_check_ins and RI_FKey_check_upd
   12969              :          * triggers, but not others; see createForeignKeyActionTriggers and
   12970              :          * CreateFKCheckTrigger.
   12971              :          */
   12972          312 :         if (tgform->tgfoid != F_RI_FKEY_NOACTION_DEL &&
   12973          248 :             tgform->tgfoid != F_RI_FKEY_NOACTION_UPD &&
   12974          172 :             tgform->tgfoid != F_RI_FKEY_CHECK_INS &&
   12975           92 :             tgform->tgfoid != F_RI_FKEY_CHECK_UPD)
   12976           12 :             continue;
   12977              : 
   12978          300 :         tgCopyTuple = heap_copytuple(tgtuple);
   12979          300 :         copy_tg = (Form_pg_trigger) GETSTRUCT(tgCopyTuple);
   12980              : 
   12981          300 :         copy_tg->tgdeferrable = deferrable;
   12982          300 :         copy_tg->tginitdeferred = initdeferred;
   12983          300 :         CatalogTupleUpdate(tgrel, &tgCopyTuple->t_self, tgCopyTuple);
   12984              : 
   12985          300 :         InvokeObjectPostAlterHook(TriggerRelationId, tgform->oid, 0);
   12986              : 
   12987          300 :         heap_freetuple(tgCopyTuple);
   12988              :     }
   12989              : 
   12990          108 :     systable_endscan(tgscan);
   12991          108 : }
   12992              : 
   12993              : /*
   12994              :  * Invokes ATExecAlterFKConstrEnforceability for each foreign key constraint
   12995              :  * that is a child of the specified constraint.
   12996              :  *
   12997              :  * Note that this doesn't handle recursion the normal way, viz. by scanning the
   12998              :  * list of child relations and recursing; instead it uses the conparentid
   12999              :  * relationships.  This may need to be reconsidered.
   13000              :  *
   13001              :  * The arguments to this function have the same meaning as the arguments to
   13002              :  * ATExecAlterFKConstrEnforceability.
   13003              :  */
   13004              : static void
   13005           32 : AlterFKConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
   13006              :                                    Relation conrel, Relation tgrel,
   13007              :                                    Oid fkrelid, Oid pkrelid,
   13008              :                                    HeapTuple contuple, LOCKMODE lockmode,
   13009              :                                    Oid ReferencedParentDelTrigger,
   13010              :                                    Oid ReferencedParentUpdTrigger,
   13011              :                                    Oid ReferencingParentInsTrigger,
   13012              :                                    Oid ReferencingParentUpdTrigger)
   13013              : {
   13014              :     Form_pg_constraint currcon;
   13015              :     Oid         conoid;
   13016              :     ScanKeyData pkey;
   13017              :     SysScanDesc pscan;
   13018              :     HeapTuple   childtup;
   13019              : 
   13020           32 :     currcon = (Form_pg_constraint) GETSTRUCT(contuple);
   13021           32 :     conoid = currcon->oid;
   13022              : 
   13023           32 :     ScanKeyInit(&pkey,
   13024              :                 Anum_pg_constraint_conparentid,
   13025              :                 BTEqualStrategyNumber, F_OIDEQ,
   13026              :                 ObjectIdGetDatum(conoid));
   13027              : 
   13028           32 :     pscan = systable_beginscan(conrel, ConstraintParentIndexId,
   13029              :                                true, NULL, 1, &pkey);
   13030              : 
   13031          100 :     while (HeapTupleIsValid(childtup = systable_getnext(pscan)))
   13032           68 :         ATExecAlterFKConstrEnforceability(wqueue, cmdcon, conrel, tgrel, fkrelid,
   13033              :                                           pkrelid, childtup, lockmode,
   13034              :                                           ReferencedParentDelTrigger,
   13035              :                                           ReferencedParentUpdTrigger,
   13036              :                                           ReferencingParentInsTrigger,
   13037              :                                           ReferencingParentUpdTrigger);
   13038              : 
   13039           32 :     systable_endscan(pscan);
   13040           32 : }
   13041              : 
   13042              : /*
   13043              :  * Invokes ATExecAlterConstrDeferrability for each constraint that is a child of
   13044              :  * the specified constraint.
   13045              :  *
   13046              :  * Note that this doesn't handle recursion the normal way, viz. by scanning the
   13047              :  * list of child relations and recursing; instead it uses the conparentid
   13048              :  * relationships.  This may need to be reconsidered.
   13049              :  *
   13050              :  * The arguments to this function have the same meaning as the arguments to
   13051              :  * ATExecAlterConstrDeferrability.
   13052              :  */
   13053              : static void
   13054           28 : AlterConstrDeferrabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
   13055              :                                 Relation conrel, Relation tgrel, Relation rel,
   13056              :                                 HeapTuple contuple, bool recurse,
   13057              :                                 List **otherrelids, LOCKMODE lockmode)
   13058              : {
   13059              :     Form_pg_constraint currcon;
   13060              :     Oid         conoid;
   13061              :     ScanKeyData pkey;
   13062              :     SysScanDesc pscan;
   13063              :     HeapTuple   childtup;
   13064              : 
   13065           28 :     currcon = (Form_pg_constraint) GETSTRUCT(contuple);
   13066           28 :     conoid = currcon->oid;
   13067              : 
   13068           28 :     ScanKeyInit(&pkey,
   13069              :                 Anum_pg_constraint_conparentid,
   13070              :                 BTEqualStrategyNumber, F_OIDEQ,
   13071              :                 ObjectIdGetDatum(conoid));
   13072              : 
   13073           28 :     pscan = systable_beginscan(conrel, ConstraintParentIndexId,
   13074              :                                true, NULL, 1, &pkey);
   13075              : 
   13076           72 :     while (HeapTupleIsValid(childtup = systable_getnext(pscan)))
   13077              :     {
   13078           44 :         Form_pg_constraint childcon = (Form_pg_constraint) GETSTRUCT(childtup);
   13079              :         Relation    childrel;
   13080              : 
   13081           44 :         childrel = table_open(childcon->conrelid, lockmode);
   13082              : 
   13083           44 :         ATExecAlterConstrDeferrability(wqueue, cmdcon, conrel, tgrel, childrel,
   13084              :                                        childtup, recurse, otherrelids, lockmode);
   13085           44 :         table_close(childrel, NoLock);
   13086              :     }
   13087              : 
   13088           28 :     systable_endscan(pscan);
   13089           28 : }
   13090              : 
   13091              : /*
   13092              :  * Update the constraint entry for the given ATAlterConstraint command, and
   13093              :  * invoke the appropriate hooks.
   13094              :  */
   13095              : static void
   13096          460 : AlterConstrUpdateConstraintEntry(ATAlterConstraint *cmdcon, Relation conrel,
   13097              :                                  HeapTuple contuple)
   13098              : {
   13099              :     HeapTuple   copyTuple;
   13100              :     Form_pg_constraint copy_con;
   13101              : 
   13102              :     Assert(cmdcon->alterEnforceability || cmdcon->alterDeferrability ||
   13103              :            cmdcon->alterInheritability);
   13104              : 
   13105          460 :     copyTuple = heap_copytuple(contuple);
   13106          460 :     copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
   13107              : 
   13108          460 :     if (cmdcon->alterEnforceability)
   13109              :     {
   13110          312 :         copy_con->conenforced = cmdcon->is_enforced;
   13111              : 
   13112              :         /*
   13113              :          * NB: The convalidated status is irrelevant when the constraint is
   13114              :          * set to NOT ENFORCED, but for consistency, it should still be set
   13115              :          * appropriately. Similarly, if the constraint is later changed to
   13116              :          * ENFORCED, validation will be performed during phase 3, so it makes
   13117              :          * sense to mark it as valid in that case.
   13118              :          */
   13119          312 :         copy_con->convalidated = cmdcon->is_enforced;
   13120              :     }
   13121          460 :     if (cmdcon->alterDeferrability)
   13122              :     {
   13123          112 :         copy_con->condeferrable = cmdcon->deferrable;
   13124          112 :         copy_con->condeferred = cmdcon->initdeferred;
   13125              :     }
   13126          460 :     if (cmdcon->alterInheritability)
   13127           40 :         copy_con->connoinherit = cmdcon->noinherit;
   13128              : 
   13129          460 :     CatalogTupleUpdate(conrel, &copyTuple->t_self, copyTuple);
   13130          460 :     InvokeObjectPostAlterHook(ConstraintRelationId, copy_con->oid, 0);
   13131              : 
   13132              :     /* Make new constraint flags visible to others */
   13133          460 :     CacheInvalidateRelcacheByRelid(copy_con->conrelid);
   13134              : 
   13135          460 :     heap_freetuple(copyTuple);
   13136          460 : }
   13137              : 
   13138              : /*
   13139              :  * ALTER TABLE VALIDATE CONSTRAINT
   13140              :  *
   13141              :  * XXX The reason we handle recursion here rather than at Phase 1 is because
   13142              :  * there's no good way to skip recursing when handling foreign keys: there is
   13143              :  * no need to lock children in that case, yet we wouldn't be able to avoid
   13144              :  * doing so at that level.
   13145              :  *
   13146              :  * Return value is the address of the validated constraint.  If the constraint
   13147              :  * was already validated, InvalidObjectAddress is returned.
   13148              :  */
   13149              : static ObjectAddress
   13150          347 : ATExecValidateConstraint(List **wqueue, Relation rel, char *constrName,
   13151              :                          bool recurse, bool recursing, LOCKMODE lockmode)
   13152              : {
   13153              :     Relation    conrel;
   13154              :     SysScanDesc scan;
   13155              :     ScanKeyData skey[3];
   13156              :     HeapTuple   tuple;
   13157              :     Form_pg_constraint con;
   13158              :     ObjectAddress address;
   13159              : 
   13160          347 :     conrel = table_open(ConstraintRelationId, RowExclusiveLock);
   13161              : 
   13162              :     /*
   13163              :      * Find and check the target constraint
   13164              :      */
   13165          347 :     ScanKeyInit(&skey[0],
   13166              :                 Anum_pg_constraint_conrelid,
   13167              :                 BTEqualStrategyNumber, F_OIDEQ,
   13168              :                 ObjectIdGetDatum(RelationGetRelid(rel)));
   13169          347 :     ScanKeyInit(&skey[1],
   13170              :                 Anum_pg_constraint_contypid,
   13171              :                 BTEqualStrategyNumber, F_OIDEQ,
   13172              :                 ObjectIdGetDatum(InvalidOid));
   13173          347 :     ScanKeyInit(&skey[2],
   13174              :                 Anum_pg_constraint_conname,
   13175              :                 BTEqualStrategyNumber, F_NAMEEQ,
   13176              :                 CStringGetDatum(constrName));
   13177          347 :     scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
   13178              :                               true, NULL, 3, skey);
   13179              : 
   13180              :     /* There can be at most one matching row */
   13181          347 :     if (!HeapTupleIsValid(tuple = systable_getnext(scan)))
   13182            0 :         ereport(ERROR,
   13183              :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
   13184              :                  errmsg("constraint \"%s\" of relation \"%s\" does not exist",
   13185              :                         constrName, RelationGetRelationName(rel))));
   13186              : 
   13187          347 :     con = (Form_pg_constraint) GETSTRUCT(tuple);
   13188          347 :     if (con->contype != CONSTRAINT_FOREIGN &&
   13189          170 :         con->contype != CONSTRAINT_CHECK &&
   13190           74 :         con->contype != CONSTRAINT_NOTNULL)
   13191            0 :         ereport(ERROR,
   13192              :                 errcode(ERRCODE_WRONG_OBJECT_TYPE),
   13193              :                 errmsg("cannot validate constraint \"%s\" of relation \"%s\"",
   13194              :                        constrName, RelationGetRelationName(rel)),
   13195              :                 errdetail("This operation is not supported for this type of constraint."));
   13196              : 
   13197          347 :     if (!con->conenforced)
   13198            4 :         ereport(ERROR,
   13199              :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
   13200              :                  errmsg("cannot validate NOT ENFORCED constraint")));
   13201              : 
   13202          343 :     if (!con->convalidated)
   13203              :     {
   13204          331 :         if (con->contype == CONSTRAINT_FOREIGN)
   13205              :         {
   13206          173 :             QueueFKConstraintValidation(wqueue, conrel, rel, con->confrelid,
   13207              :                                         tuple, lockmode);
   13208              :         }
   13209          158 :         else if (con->contype == CONSTRAINT_CHECK)
   13210              :         {
   13211           84 :             QueueCheckConstraintValidation(wqueue, conrel, rel, constrName,
   13212              :                                            tuple, recurse, recursing, lockmode);
   13213              :         }
   13214           74 :         else if (con->contype == CONSTRAINT_NOTNULL)
   13215              :         {
   13216           74 :             QueueNNConstraintValidation(wqueue, conrel, rel,
   13217              :                                         tuple, recurse, recursing, lockmode);
   13218              :         }
   13219              : 
   13220          331 :         ObjectAddressSet(address, ConstraintRelationId, con->oid);
   13221              :     }
   13222              :     else
   13223           12 :         address = InvalidObjectAddress; /* already validated */
   13224              : 
   13225          343 :     systable_endscan(scan);
   13226              : 
   13227          343 :     table_close(conrel, RowExclusiveLock);
   13228              : 
   13229          343 :     return address;
   13230              : }
   13231              : 
   13232              : /*
   13233              :  * QueueFKConstraintValidation
   13234              :  *
   13235              :  * Add an entry to the wqueue to validate the given foreign key constraint in
   13236              :  * Phase 3 and update the convalidated field in the pg_constraint catalog
   13237              :  * for the specified relation and all its children.
   13238              :  */
   13239              : static void
   13240          225 : QueueFKConstraintValidation(List **wqueue, Relation conrel, Relation fkrel,
   13241              :                             Oid pkrelid, HeapTuple contuple, LOCKMODE lockmode)
   13242              : {
   13243              :     Form_pg_constraint con;
   13244              :     AlteredTableInfo *tab;
   13245              :     HeapTuple   copyTuple;
   13246              :     Form_pg_constraint copy_con;
   13247              : 
   13248          225 :     con = (Form_pg_constraint) GETSTRUCT(contuple);
   13249              :     Assert(con->contype == CONSTRAINT_FOREIGN);
   13250              :     Assert(!con->convalidated);
   13251              : 
   13252              :     /*
   13253              :      * Add the validation to phase 3's queue; not needed for partitioned
   13254              :      * tables themselves, only for their partitions.
   13255              :      *
   13256              :      * When the referenced table (pkrelid) is partitioned, the referencing
   13257              :      * table (fkrel) has one pg_constraint row pointing to each partition
   13258              :      * thereof.  These rows are there only to support action triggers and no
   13259              :      * table scan is needed, therefore skip this for them as well.
   13260              :      */
   13261          225 :     if (fkrel->rd_rel->relkind == RELKIND_RELATION &&
   13262          193 :         con->confrelid == pkrelid)
   13263              :     {
   13264              :         NewConstraint *newcon;
   13265              :         Constraint *fkconstraint;
   13266              : 
   13267              :         /* Queue validation for phase 3 */
   13268          181 :         fkconstraint = makeNode(Constraint);
   13269              :         /* for now this is all we need */
   13270          181 :         fkconstraint->conname = pstrdup(NameStr(con->conname));
   13271              : 
   13272          181 :         newcon = palloc0_object(NewConstraint);
   13273          181 :         newcon->name = fkconstraint->conname;
   13274          181 :         newcon->contype = CONSTR_FOREIGN;
   13275          181 :         newcon->refrelid = con->confrelid;
   13276          181 :         newcon->refindid = con->conindid;
   13277          181 :         newcon->conid = con->oid;
   13278          181 :         newcon->qual = (Node *) fkconstraint;
   13279              : 
   13280              :         /* Find or create work queue entry for this table */
   13281          181 :         tab = ATGetQueueEntry(wqueue, fkrel);
   13282          181 :         tab->constraints = lappend(tab->constraints, newcon);
   13283              :     }
   13284              : 
   13285              :     /*
   13286              :      * If the table at either end of the constraint is partitioned, we need to
   13287              :      * recurse and handle every unvalidated constraint that is a child of this
   13288              :      * constraint.
   13289              :      */
   13290          418 :     if (fkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
   13291          193 :         get_rel_relkind(con->confrelid) == RELKIND_PARTITIONED_TABLE)
   13292              :     {
   13293              :         ScanKeyData pkey;
   13294              :         SysScanDesc pscan;
   13295              :         HeapTuple   childtup;
   13296              : 
   13297           52 :         ScanKeyInit(&pkey,
   13298              :                     Anum_pg_constraint_conparentid,
   13299              :                     BTEqualStrategyNumber, F_OIDEQ,
   13300              :                     ObjectIdGetDatum(con->oid));
   13301              : 
   13302           52 :         pscan = systable_beginscan(conrel, ConstraintParentIndexId,
   13303              :                                    true, NULL, 1, &pkey);
   13304              : 
   13305          104 :         while (HeapTupleIsValid(childtup = systable_getnext(pscan)))
   13306              :         {
   13307              :             Form_pg_constraint childcon;
   13308              :             Relation    childrel;
   13309              : 
   13310           52 :             childcon = (Form_pg_constraint) GETSTRUCT(childtup);
   13311              : 
   13312              :             /*
   13313              :              * If the child constraint has already been validated, no further
   13314              :              * action is required for it or its descendants, as they are all
   13315              :              * valid.
   13316              :              */
   13317           52 :             if (childcon->convalidated)
   13318           12 :                 continue;
   13319              : 
   13320           40 :             childrel = table_open(childcon->conrelid, lockmode);
   13321              : 
   13322              :             /*
   13323              :              * NB: Note that pkrelid should be passed as-is during recursion,
   13324              :              * as it is required to identify the root referenced table.
   13325              :              */
   13326           40 :             QueueFKConstraintValidation(wqueue, conrel, childrel, pkrelid,
   13327              :                                         childtup, lockmode);
   13328           40 :             table_close(childrel, NoLock);
   13329              :         }
   13330              : 
   13331           52 :         systable_endscan(pscan);
   13332              :     }
   13333              : 
   13334              :     /*
   13335              :      * Now mark the pg_constraint row as validated (even if we didn't check,
   13336              :      * notably the ones for partitions on the referenced side).
   13337              :      *
   13338              :      * We rely on transaction abort to roll back this change if phase 3
   13339              :      * ultimately finds violating rows.  This is a bit ugly.
   13340              :      */
   13341          225 :     copyTuple = heap_copytuple(contuple);
   13342          225 :     copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
   13343          225 :     copy_con->convalidated = true;
   13344          225 :     CatalogTupleUpdate(conrel, &copyTuple->t_self, copyTuple);
   13345              : 
   13346          225 :     InvokeObjectPostAlterHook(ConstraintRelationId, con->oid, 0);
   13347              : 
   13348          225 :     heap_freetuple(copyTuple);
   13349          225 : }
   13350              : 
   13351              : /*
   13352              :  * QueueCheckConstraintValidation
   13353              :  *
   13354              :  * Add an entry to the wqueue to validate the given check constraint in Phase 3
   13355              :  * and update the convalidated field in the pg_constraint catalog for the
   13356              :  * specified relation and all its inheriting children.
   13357              :  */
   13358              : static void
   13359           84 : QueueCheckConstraintValidation(List **wqueue, Relation conrel, Relation rel,
   13360              :                                char *constrName, HeapTuple contuple,
   13361              :                                bool recurse, bool recursing, LOCKMODE lockmode)
   13362              : {
   13363              :     Form_pg_constraint con;
   13364              :     AlteredTableInfo *tab;
   13365              :     HeapTuple   copyTuple;
   13366              :     Form_pg_constraint copy_con;
   13367              : 
   13368           84 :     List       *children = NIL;
   13369              :     ListCell   *child;
   13370              :     NewConstraint *newcon;
   13371              :     Datum       val;
   13372              :     char       *conbin;
   13373              : 
   13374           84 :     con = (Form_pg_constraint) GETSTRUCT(contuple);
   13375              :     Assert(con->contype == CONSTRAINT_CHECK);
   13376              : 
   13377              :     /*
   13378              :      * If we're recursing, the parent has already done this, so skip it. Also,
   13379              :      * if the constraint is a NO INHERIT constraint, we shouldn't try to look
   13380              :      * for it in the children.
   13381              :      */
   13382           84 :     if (!recursing && !con->connoinherit)
   13383           48 :         children = find_all_inheritors(RelationGetRelid(rel),
   13384              :                                        lockmode, NULL);
   13385              : 
   13386              :     /*
   13387              :      * For CHECK constraints, we must ensure that we only mark the constraint
   13388              :      * as validated on the parent if it's already validated on the children.
   13389              :      *
   13390              :      * We recurse before validating on the parent, to reduce risk of
   13391              :      * deadlocks.
   13392              :      */
   13393          164 :     foreach(child, children)
   13394              :     {
   13395           80 :         Oid         childoid = lfirst_oid(child);
   13396              :         Relation    childrel;
   13397              : 
   13398           80 :         if (childoid == RelationGetRelid(rel))
   13399           48 :             continue;
   13400              : 
   13401              :         /*
   13402              :          * If we are told not to recurse, there had better not be any child
   13403              :          * tables, because we can't mark the constraint on the parent valid
   13404              :          * unless it is valid for all child tables.
   13405              :          */
   13406           32 :         if (!recurse)
   13407            0 :             ereport(ERROR,
   13408              :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   13409              :                      errmsg("constraint must be validated on child tables too")));
   13410              : 
   13411              :         /* find_all_inheritors already got lock */
   13412           32 :         childrel = table_open(childoid, NoLock);
   13413              : 
   13414           32 :         ATExecValidateConstraint(wqueue, childrel, constrName, false,
   13415              :                                  true, lockmode);
   13416           32 :         table_close(childrel, NoLock);
   13417              :     }
   13418              : 
   13419              :     /* Queue validation for phase 3 */
   13420           84 :     newcon = palloc0_object(NewConstraint);
   13421           84 :     newcon->name = constrName;
   13422           84 :     newcon->contype = CONSTR_CHECK;
   13423           84 :     newcon->refrelid = InvalidOid;
   13424           84 :     newcon->refindid = InvalidOid;
   13425           84 :     newcon->conid = con->oid;
   13426              : 
   13427           84 :     val = SysCacheGetAttrNotNull(CONSTROID, contuple,
   13428              :                                  Anum_pg_constraint_conbin);
   13429           84 :     conbin = TextDatumGetCString(val);
   13430           84 :     newcon->qual = expand_generated_columns_in_expr(stringToNode(conbin), rel, 1);
   13431              : 
   13432              :     /* Find or create work queue entry for this table */
   13433           84 :     tab = ATGetQueueEntry(wqueue, rel);
   13434           84 :     tab->constraints = lappend(tab->constraints, newcon);
   13435              : 
   13436              :     /*
   13437              :      * Invalidate relcache so that others see the new validated constraint.
   13438              :      */
   13439           84 :     CacheInvalidateRelcache(rel);
   13440              : 
   13441              :     /*
   13442              :      * Now update the catalog, while we have the door open.
   13443              :      */
   13444           84 :     copyTuple = heap_copytuple(contuple);
   13445           84 :     copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
   13446           84 :     copy_con->convalidated = true;
   13447           84 :     CatalogTupleUpdate(conrel, &copyTuple->t_self, copyTuple);
   13448              : 
   13449           84 :     InvokeObjectPostAlterHook(ConstraintRelationId, con->oid, 0);
   13450              : 
   13451           84 :     heap_freetuple(copyTuple);
   13452           84 : }
   13453              : 
   13454              : /*
   13455              :  * QueueNNConstraintValidation
   13456              :  *
   13457              :  * Add an entry to the wqueue to validate the given not-null constraint in
   13458              :  * Phase 3 and update the convalidated field in the pg_constraint catalog for
   13459              :  * the specified relation and all its inheriting children.
   13460              :  */
   13461              : static void
   13462           74 : QueueNNConstraintValidation(List **wqueue, Relation conrel, Relation rel,
   13463              :                             HeapTuple contuple, bool recurse, bool recursing,
   13464              :                             LOCKMODE lockmode)
   13465              : {
   13466              :     Form_pg_constraint con;
   13467              :     AlteredTableInfo *tab;
   13468              :     HeapTuple   copyTuple;
   13469              :     Form_pg_constraint copy_con;
   13470           74 :     List       *children = NIL;
   13471              :     AttrNumber  attnum;
   13472              :     char       *colname;
   13473              : 
   13474           74 :     con = (Form_pg_constraint) GETSTRUCT(contuple);
   13475              :     Assert(con->contype == CONSTRAINT_NOTNULL);
   13476              : 
   13477           74 :     attnum = extractNotNullColumn(contuple);
   13478              : 
   13479              :     /*
   13480              :      * If we're recursing, we've already done this for parent, so skip it.
   13481              :      * Also, if the constraint is a NO INHERIT constraint, we shouldn't try to
   13482              :      * look for it in the children.
   13483              :      *
   13484              :      * We recurse before validating on the parent, to reduce risk of
   13485              :      * deadlocks.
   13486              :      */
   13487           74 :     if (!recursing && !con->connoinherit)
   13488           50 :         children = find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
   13489              : 
   13490           74 :     colname = get_attname(RelationGetRelid(rel), attnum, false);
   13491          250 :     foreach_oid(childoid, children)
   13492              :     {
   13493              :         Relation    childrel;
   13494              :         HeapTuple   contup;
   13495              :         Form_pg_constraint childcon;
   13496              :         char       *conname;
   13497              : 
   13498          102 :         if (childoid == RelationGetRelid(rel))
   13499           50 :             continue;
   13500              : 
   13501              :         /*
   13502              :          * If we are told not to recurse, there had better not be any child
   13503              :          * tables, because we can't mark the constraint on the parent valid
   13504              :          * unless it is valid for all child tables.
   13505              :          */
   13506           52 :         if (!recurse)
   13507            0 :             ereport(ERROR,
   13508              :                     errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   13509              :                     errmsg("constraint must be validated on child tables too"));
   13510              : 
   13511              :         /*
   13512              :          * The column on child might have a different attnum, so search by
   13513              :          * column name.
   13514              :          */
   13515           52 :         contup = findNotNullConstraint(childoid, colname);
   13516           52 :         if (!contup)
   13517            0 :             elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation \"%s\"",
   13518              :                  colname, get_rel_name(childoid));
   13519           52 :         childcon = (Form_pg_constraint) GETSTRUCT(contup);
   13520           52 :         if (childcon->convalidated)
   13521           28 :             continue;
   13522              : 
   13523              :         /* find_all_inheritors already got lock */
   13524           24 :         childrel = table_open(childoid, NoLock);
   13525           24 :         conname = pstrdup(NameStr(childcon->conname));
   13526              : 
   13527              :         /* XXX improve ATExecValidateConstraint API to avoid double search */
   13528           24 :         ATExecValidateConstraint(wqueue, childrel, conname,
   13529              :                                  false, true, lockmode);
   13530           24 :         table_close(childrel, NoLock);
   13531              :     }
   13532              : 
   13533              :     /* Set attnotnull appropriately without queueing another validation */
   13534           74 :     set_attnotnull(NULL, rel, attnum, true, false);
   13535              : 
   13536           74 :     tab = ATGetQueueEntry(wqueue, rel);
   13537           74 :     tab->verify_new_notnull = true;
   13538              : 
   13539              :     /*
   13540              :      * Invalidate relcache so that others see the new validated constraint.
   13541              :      */
   13542           74 :     CacheInvalidateRelcache(rel);
   13543              : 
   13544              :     /*
   13545              :      * Now update the catalogs, while we have the door open.
   13546              :      */
   13547           74 :     copyTuple = heap_copytuple(contuple);
   13548           74 :     copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
   13549           74 :     copy_con->convalidated = true;
   13550           74 :     CatalogTupleUpdate(conrel, &copyTuple->t_self, copyTuple);
   13551              : 
   13552           74 :     InvokeObjectPostAlterHook(ConstraintRelationId, con->oid, 0);
   13553              : 
   13554           74 :     heap_freetuple(copyTuple);
   13555           74 : }
   13556              : 
   13557              : /*
   13558              :  * transformColumnNameList - transform list of column names
   13559              :  *
   13560              :  * Lookup each name and return its attnum and, optionally, type and collation
   13561              :  * OIDs
   13562              :  *
   13563              :  * Note: the name of this function suggests that it's general-purpose,
   13564              :  * but actually it's only used to look up names appearing in foreign-key
   13565              :  * clauses.  The error messages would need work to use it in other cases,
   13566              :  * and perhaps the validity checks as well.
   13567              :  */
   13568              : static int
   13569         4299 : transformColumnNameList(Oid relId, List *colList,
   13570              :                         int16 *attnums, Oid *atttypids, Oid *attcollids)
   13571              : {
   13572              :     ListCell   *l;
   13573              :     int         attnum;
   13574              : 
   13575         4299 :     attnum = 0;
   13576         7858 :     foreach(l, colList)
   13577              :     {
   13578         3603 :         char       *attname = strVal(lfirst(l));
   13579              :         HeapTuple   atttuple;
   13580              :         Form_pg_attribute attform;
   13581              : 
   13582         3603 :         atttuple = SearchSysCacheAttName(relId, attname);
   13583         3603 :         if (!HeapTupleIsValid(atttuple))
   13584           36 :             ereport(ERROR,
   13585              :                     (errcode(ERRCODE_UNDEFINED_COLUMN),
   13586              :                      errmsg("column \"%s\" referenced in foreign key constraint does not exist",
   13587              :                             attname)));
   13588         3567 :         attform = (Form_pg_attribute) GETSTRUCT(atttuple);
   13589         3567 :         if (attform->attnum < 0)
   13590            8 :             ereport(ERROR,
   13591              :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   13592              :                      errmsg("system columns cannot be used in foreign keys")));
   13593         3559 :         if (attnum >= INDEX_MAX_KEYS)
   13594            0 :             ereport(ERROR,
   13595              :                     (errcode(ERRCODE_TOO_MANY_COLUMNS),
   13596              :                      errmsg("cannot have more than %d keys in a foreign key",
   13597              :                             INDEX_MAX_KEYS)));
   13598         3559 :         attnums[attnum] = attform->attnum;
   13599         3559 :         if (atttypids != NULL)
   13600         3535 :             atttypids[attnum] = attform->atttypid;
   13601         3559 :         if (attcollids != NULL)
   13602         3535 :             attcollids[attnum] = attform->attcollation;
   13603         3559 :         ReleaseSysCache(atttuple);
   13604         3559 :         attnum++;
   13605              :     }
   13606              : 
   13607         4255 :     return attnum;
   13608              : }
   13609              : 
   13610              : /*
   13611              :  * transformFkeyGetPrimaryKey -
   13612              :  *
   13613              :  *  Look up the names, attnums, types, and collations of the primary key attributes
   13614              :  *  for the pkrel.  Also return the index OID and index opclasses of the
   13615              :  *  index supporting the primary key.  Also return whether the index has
   13616              :  *  WITHOUT OVERLAPS.
   13617              :  *
   13618              :  *  All parameters except pkrel are output parameters.  Also, the function
   13619              :  *  return value is the number of attributes in the primary key.
   13620              :  *
   13621              :  *  Used when the column list in the REFERENCES specification is omitted.
   13622              :  */
   13623              : static int
   13624          811 : transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
   13625              :                            List **attnamelist,
   13626              :                            int16 *attnums, Oid *atttypids, Oid *attcollids,
   13627              :                            Oid *opclasses, bool *pk_has_without_overlaps)
   13628              : {
   13629              :     List       *indexoidlist;
   13630              :     ListCell   *indexoidscan;
   13631          811 :     HeapTuple   indexTuple = NULL;
   13632          811 :     Form_pg_index indexStruct = NULL;
   13633              :     Datum       indclassDatum;
   13634              :     oidvector  *indclass;
   13635              :     int         i;
   13636              : 
   13637              :     /*
   13638              :      * Get the list of index OIDs for the table from the relcache, and look up
   13639              :      * each one in the pg_index syscache until we find one marked primary key
   13640              :      * (hopefully there isn't more than one such).  Insist it's valid, too.
   13641              :      */
   13642          811 :     *indexOid = InvalidOid;
   13643              : 
   13644          811 :     indexoidlist = RelationGetIndexList(pkrel);
   13645              : 
   13646          815 :     foreach(indexoidscan, indexoidlist)
   13647              :     {
   13648          815 :         Oid         indexoid = lfirst_oid(indexoidscan);
   13649              : 
   13650          815 :         indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
   13651          815 :         if (!HeapTupleIsValid(indexTuple))
   13652            0 :             elog(ERROR, "cache lookup failed for index %u", indexoid);
   13653          815 :         indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
   13654          815 :         if (indexStruct->indisprimary && indexStruct->indisvalid)
   13655              :         {
   13656              :             /*
   13657              :              * Refuse to use a deferrable primary key.  This is per SQL spec,
   13658              :              * and there would be a lot of interesting semantic problems if we
   13659              :              * tried to allow it.
   13660              :              */
   13661          811 :             if (!indexStruct->indimmediate)
   13662            0 :                 ereport(ERROR,
   13663              :                         (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
   13664              :                          errmsg("cannot use a deferrable primary key for referenced table \"%s\"",
   13665              :                                 RelationGetRelationName(pkrel))));
   13666              : 
   13667          811 :             *indexOid = indexoid;
   13668          811 :             break;
   13669              :         }
   13670            4 :         ReleaseSysCache(indexTuple);
   13671              :     }
   13672              : 
   13673          811 :     list_free(indexoidlist);
   13674              : 
   13675              :     /*
   13676              :      * Check that we found it
   13677              :      */
   13678          811 :     if (!OidIsValid(*indexOid))
   13679            0 :         ereport(ERROR,
   13680              :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
   13681              :                  errmsg("there is no primary key for referenced table \"%s\"",
   13682              :                         RelationGetRelationName(pkrel))));
   13683              : 
   13684              :     /* Must get indclass the hard way */
   13685          811 :     indclassDatum = SysCacheGetAttrNotNull(INDEXRELID, indexTuple,
   13686              :                                            Anum_pg_index_indclass);
   13687          811 :     indclass = (oidvector *) DatumGetPointer(indclassDatum);
   13688              : 
   13689              :     /*
   13690              :      * Now build the list of PK attributes from the indkey definition (we
   13691              :      * assume a primary key cannot have expressional elements)
   13692              :      */
   13693          811 :     *attnamelist = NIL;
   13694         1934 :     for (i = 0; i < indexStruct->indnkeyatts; i++)
   13695              :     {
   13696         1123 :         int         pkattno = indexStruct->indkey.values[i];
   13697              : 
   13698         1123 :         attnums[i] = pkattno;
   13699         1123 :         atttypids[i] = attnumTypeId(pkrel, pkattno);
   13700         1123 :         attcollids[i] = attnumCollationId(pkrel, pkattno);
   13701         1123 :         opclasses[i] = indclass->values[i];
   13702         1123 :         *attnamelist = lappend(*attnamelist,
   13703         1123 :                                makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
   13704              :     }
   13705              : 
   13706          811 :     *pk_has_without_overlaps = indexStruct->indisexclusion;
   13707              : 
   13708          811 :     ReleaseSysCache(indexTuple);
   13709              : 
   13710          811 :     return i;
   13711              : }
   13712              : 
   13713              : /*
   13714              :  * transformFkeyCheckAttrs -
   13715              :  *
   13716              :  *  Validate that the 'attnums' columns in the 'pkrel' relation are valid to
   13717              :  *  reference as part of a foreign key constraint.
   13718              :  *
   13719              :  *  Returns the OID of the unique index supporting the constraint and
   13720              :  *  populates the caller-provided 'opclasses' array with the opclasses
   13721              :  *  associated with the index columns.  Also sets whether the index
   13722              :  *  uses WITHOUT OVERLAPS.
   13723              :  *
   13724              :  *  Raises an ERROR on validation failure.
   13725              :  */
   13726              : static Oid
   13727          839 : transformFkeyCheckAttrs(Relation pkrel,
   13728              :                         int numattrs, int16 *attnums,
   13729              :                         bool with_period, Oid *opclasses,
   13730              :                         bool *pk_has_without_overlaps)
   13731              : {
   13732          839 :     Oid         indexoid = InvalidOid;
   13733          839 :     bool        found = false;
   13734          839 :     bool        found_deferrable = false;
   13735              :     List       *indexoidlist;
   13736              :     ListCell   *indexoidscan;
   13737              :     int         i,
   13738              :                 j;
   13739              : 
   13740              :     /*
   13741              :      * Reject duplicate appearances of columns in the referenced-columns list.
   13742              :      * Such a case is forbidden by the SQL standard, and even if we thought it
   13743              :      * useful to allow it, there would be ambiguity about how to match the
   13744              :      * list to unique indexes (in particular, it'd be unclear which index
   13745              :      * opclass goes with which FK column).
   13746              :      */
   13747         1959 :     for (i = 0; i < numattrs; i++)
   13748              :     {
   13749         1479 :         for (j = i + 1; j < numattrs; j++)
   13750              :         {
   13751          359 :             if (attnums[i] == attnums[j])
   13752           16 :                 ereport(ERROR,
   13753              :                         (errcode(ERRCODE_INVALID_FOREIGN_KEY),
   13754              :                          errmsg("foreign key referenced-columns list must not contain duplicates")));
   13755              :         }
   13756              :     }
   13757              : 
   13758              :     /*
   13759              :      * Get the list of index OIDs for the table from the relcache, and look up
   13760              :      * each one in the pg_index syscache, and match unique indexes to the list
   13761              :      * of attnums we are given.
   13762              :      */
   13763          823 :     indexoidlist = RelationGetIndexList(pkrel);
   13764              : 
   13765          942 :     foreach(indexoidscan, indexoidlist)
   13766              :     {
   13767              :         HeapTuple   indexTuple;
   13768              :         Form_pg_index indexStruct;
   13769              : 
   13770          934 :         indexoid = lfirst_oid(indexoidscan);
   13771          934 :         indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
   13772          934 :         if (!HeapTupleIsValid(indexTuple))
   13773            0 :             elog(ERROR, "cache lookup failed for index %u", indexoid);
   13774          934 :         indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
   13775              : 
   13776              :         /*
   13777              :          * Must have the right number of columns; must be unique (or if
   13778              :          * temporal then exclusion instead) and not a partial index; forget it
   13779              :          * if there are any expressions, too. Invalid indexes are out as well.
   13780              :          */
   13781          934 :         if (indexStruct->indnkeyatts == numattrs &&
   13782          853 :             (with_period ? indexStruct->indisexclusion : indexStruct->indisunique) &&
   13783         1706 :             indexStruct->indisvalid &&
   13784         1706 :             heap_attisnull(indexTuple, Anum_pg_index_indpred, NULL) &&
   13785          853 :             heap_attisnull(indexTuple, Anum_pg_index_indexprs, NULL))
   13786              :         {
   13787              :             Datum       indclassDatum;
   13788              :             oidvector  *indclass;
   13789              : 
   13790              :             /* Must get indclass the hard way */
   13791          853 :             indclassDatum = SysCacheGetAttrNotNull(INDEXRELID, indexTuple,
   13792              :                                                    Anum_pg_index_indclass);
   13793          853 :             indclass = (oidvector *) DatumGetPointer(indclassDatum);
   13794              : 
   13795              :             /*
   13796              :              * The given attnum list may match the index columns in any order.
   13797              :              * Check for a match, and extract the appropriate opclasses while
   13798              :              * we're at it.
   13799              :              *
   13800              :              * We know that attnums[] is duplicate-free per the test at the
   13801              :              * start of this function, and we checked above that the number of
   13802              :              * index columns agrees, so if we find a match for each attnums[]
   13803              :              * entry then we must have a one-to-one match in some order.
   13804              :              */
   13805         1965 :             for (i = 0; i < numattrs; i++)
   13806              :             {
   13807         1150 :                 found = false;
   13808         1531 :                 for (j = 0; j < numattrs; j++)
   13809              :                 {
   13810         1493 :                     if (attnums[i] == indexStruct->indkey.values[j])
   13811              :                     {
   13812         1112 :                         opclasses[i] = indclass->values[j];
   13813         1112 :                         found = true;
   13814         1112 :                         break;
   13815              :                     }
   13816              :                 }
   13817         1150 :                 if (!found)
   13818           38 :                     break;
   13819              :             }
   13820              :             /* The last attribute in the index must be the PERIOD FK part */
   13821          853 :             if (found && with_period)
   13822              :             {
   13823           80 :                 int16       periodattnum = attnums[numattrs - 1];
   13824              : 
   13825           80 :                 found = (periodattnum == indexStruct->indkey.values[numattrs - 1]);
   13826              :             }
   13827              : 
   13828              :             /*
   13829              :              * Refuse to use a deferrable unique/primary key.  This is per SQL
   13830              :              * spec, and there would be a lot of interesting semantic problems
   13831              :              * if we tried to allow it.
   13832              :              */
   13833          853 :             if (found && !indexStruct->indimmediate)
   13834              :             {
   13835              :                 /*
   13836              :                  * Remember that we found an otherwise matching index, so that
   13837              :                  * we can generate a more appropriate error message.
   13838              :                  */
   13839            0 :                 found_deferrable = true;
   13840            0 :                 found = false;
   13841              :             }
   13842              : 
   13843              :             /* We need to know whether the index has WITHOUT OVERLAPS */
   13844          853 :             if (found)
   13845          815 :                 *pk_has_without_overlaps = indexStruct->indisexclusion;
   13846              :         }
   13847          934 :         ReleaseSysCache(indexTuple);
   13848          934 :         if (found)
   13849          815 :             break;
   13850              :     }
   13851              : 
   13852          823 :     if (!found)
   13853              :     {
   13854            8 :         if (found_deferrable)
   13855            0 :             ereport(ERROR,
   13856              :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
   13857              :                      errmsg("cannot use a deferrable unique constraint for referenced table \"%s\"",
   13858              :                             RelationGetRelationName(pkrel))));
   13859              :         else
   13860            8 :             ereport(ERROR,
   13861              :                     (errcode(ERRCODE_INVALID_FOREIGN_KEY),
   13862              :                      errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
   13863              :                             RelationGetRelationName(pkrel))));
   13864              :     }
   13865              : 
   13866          815 :     list_free(indexoidlist);
   13867              : 
   13868          815 :     return indexoid;
   13869              : }
   13870              : 
   13871              : /*
   13872              :  * findFkeyCast -
   13873              :  *
   13874              :  *  Wrapper around find_coercion_pathway() for ATAddForeignKeyConstraint().
   13875              :  *  Caller has equal regard for binary coercibility and for an exact match.
   13876              : */
   13877              : static CoercionPathType
   13878            8 : findFkeyCast(Oid targetTypeId, Oid sourceTypeId, Oid *funcid)
   13879              : {
   13880              :     CoercionPathType ret;
   13881              : 
   13882            8 :     if (targetTypeId == sourceTypeId)
   13883              :     {
   13884            8 :         ret = COERCION_PATH_RELABELTYPE;
   13885            8 :         *funcid = InvalidOid;
   13886              :     }
   13887              :     else
   13888              :     {
   13889            0 :         ret = find_coercion_pathway(targetTypeId, sourceTypeId,
   13890              :                                     COERCION_IMPLICIT, funcid);
   13891            0 :         if (ret == COERCION_PATH_NONE)
   13892              :             /* A previously-relied-upon cast is now gone. */
   13893            0 :             elog(ERROR, "could not find cast from %u to %u",
   13894              :                  sourceTypeId, targetTypeId);
   13895              :     }
   13896              : 
   13897            8 :     return ret;
   13898              : }
   13899              : 
   13900              : /*
   13901              :  * Permissions checks on the referenced table for ADD FOREIGN KEY
   13902              :  *
   13903              :  * Note: we have already checked that the user owns the referencing table,
   13904              :  * else we'd have failed much earlier; no additional checks are needed for it.
   13905              :  */
   13906              : static void
   13907         1602 : checkFkeyPermissions(Relation rel, int16 *attnums, int natts)
   13908              : {
   13909         1602 :     Oid         roleid = GetUserId();
   13910              :     AclResult   aclresult;
   13911              :     int         i;
   13912              : 
   13913              :     /* Okay if we have relation-level REFERENCES permission */
   13914         1602 :     aclresult = pg_class_aclcheck(RelationGetRelid(rel), roleid,
   13915              :                                   ACL_REFERENCES);
   13916         1602 :     if (aclresult == ACLCHECK_OK)
   13917         1602 :         return;
   13918              :     /* Else we must have REFERENCES on each column */
   13919            0 :     for (i = 0; i < natts; i++)
   13920              :     {
   13921            0 :         aclresult = pg_attribute_aclcheck(RelationGetRelid(rel), attnums[i],
   13922              :                                           roleid, ACL_REFERENCES);
   13923            0 :         if (aclresult != ACLCHECK_OK)
   13924            0 :             aclcheck_error(aclresult, get_relkind_objtype(rel->rd_rel->relkind),
   13925            0 :                            RelationGetRelationName(rel));
   13926              :     }
   13927              : }
   13928              : 
   13929              : /*
   13930              :  * Scan the existing rows in a table to verify they meet a proposed FK
   13931              :  * constraint.
   13932              :  *
   13933              :  * Caller must have opened and locked both relations appropriately.
   13934              :  */
   13935              : static void
   13936          734 : validateForeignKeyConstraint(char *conname,
   13937              :                              Relation rel,
   13938              :                              Relation pkrel,
   13939              :                              Oid pkindOid,
   13940              :                              Oid constraintOid,
   13941              :                              bool hasperiod)
   13942              : {
   13943              :     TupleTableSlot *slot;
   13944              :     TableScanDesc scan;
   13945          734 :     Trigger     trig = {0};
   13946              :     Snapshot    snapshot;
   13947              :     MemoryContext oldcxt;
   13948              :     MemoryContext perTupCxt;
   13949              : 
   13950          734 :     ereport(DEBUG1,
   13951              :             (errmsg_internal("validating foreign key constraint \"%s\"", conname)));
   13952              : 
   13953              :     /*
   13954              :      * Build a trigger call structure; we'll need it either way.
   13955              :      */
   13956          734 :     trig.tgoid = InvalidOid;
   13957          734 :     trig.tgname = conname;
   13958          734 :     trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
   13959          734 :     trig.tgisinternal = true;
   13960          734 :     trig.tgconstrrelid = RelationGetRelid(pkrel);
   13961          734 :     trig.tgconstrindid = pkindOid;
   13962          734 :     trig.tgconstraint = constraintOid;
   13963          734 :     trig.tgdeferrable = false;
   13964          734 :     trig.tginitdeferred = false;
   13965              :     /* we needn't fill in remaining fields */
   13966              : 
   13967              :     /*
   13968              :      * See if we can do it with a single LEFT JOIN query.  A false result
   13969              :      * indicates we must proceed with the fire-the-trigger method. We can't do
   13970              :      * a LEFT JOIN for temporal FKs yet, but we can once we support temporal
   13971              :      * left joins.
   13972              :      */
   13973          734 :     if (!hasperiod && RI_Initial_Check(&trig, rel, pkrel))
   13974          608 :         return;
   13975              : 
   13976              :     /*
   13977              :      * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
   13978              :      * if that tuple had just been inserted.  If any of those fail, it should
   13979              :      * ereport(ERROR) and that's that.
   13980              :      */
   13981           71 :     snapshot = RegisterSnapshot(GetLatestSnapshot());
   13982           71 :     slot = table_slot_create(rel, NULL);
   13983           71 :     scan = table_beginscan(rel, snapshot, 0, NULL);
   13984              : 
   13985           71 :     perTupCxt = AllocSetContextCreate(CurrentMemoryContext,
   13986              :                                       "validateForeignKeyConstraint",
   13987              :                                       ALLOCSET_SMALL_SIZES);
   13988           71 :     oldcxt = MemoryContextSwitchTo(perTupCxt);
   13989              : 
   13990          127 :     while (table_scan_getnextslot(scan, ForwardScanDirection, slot))
   13991              :     {
   13992           68 :         LOCAL_FCINFO(fcinfo, 0);
   13993           68 :         TriggerData trigdata = {0};
   13994              : 
   13995           68 :         CHECK_FOR_INTERRUPTS();
   13996              : 
   13997              :         /*
   13998              :          * Make a call to the trigger function
   13999              :          *
   14000              :          * No parameters are passed, but we do set a context
   14001              :          */
   14002          340 :         MemSet(fcinfo, 0, SizeForFunctionCallInfo(0));
   14003              : 
   14004              :         /*
   14005              :          * We assume RI_FKey_check_ins won't look at flinfo...
   14006              :          */
   14007           68 :         trigdata.type = T_TriggerData;
   14008           68 :         trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
   14009           68 :         trigdata.tg_relation = rel;
   14010           68 :         trigdata.tg_trigtuple = ExecFetchSlotHeapTuple(slot, false, NULL);
   14011           68 :         trigdata.tg_trigslot = slot;
   14012           68 :         trigdata.tg_trigger = &trig;
   14013              : 
   14014           68 :         fcinfo->context = (Node *) &trigdata;
   14015              : 
   14016           68 :         RI_FKey_check_ins(fcinfo);
   14017              : 
   14018           56 :         MemoryContextReset(perTupCxt);
   14019              :     }
   14020              : 
   14021           59 :     MemoryContextSwitchTo(oldcxt);
   14022           59 :     MemoryContextDelete(perTupCxt);
   14023           59 :     table_endscan(scan);
   14024           59 :     UnregisterSnapshot(snapshot);
   14025           59 :     ExecDropSingleTupleTableSlot(slot);
   14026              : }
   14027              : 
   14028              : /*
   14029              :  * CreateFKCheckTrigger
   14030              :  *      Creates the insert (on_insert=true) or update "check" trigger that
   14031              :  *      implements a given foreign key
   14032              :  *
   14033              :  * Returns the OID of the so created trigger.
   14034              :  */
   14035              : static Oid
   14036         3924 : CreateFKCheckTrigger(Oid myRelOid, Oid refRelOid, Constraint *fkconstraint,
   14037              :                      Oid constraintOid, Oid indexOid, Oid parentTrigOid,
   14038              :                      bool on_insert)
   14039              : {
   14040              :     ObjectAddress trigAddress;
   14041              :     CreateTrigStmt *fk_trigger;
   14042              : 
   14043              :     /*
   14044              :      * Note: for a self-referential FK (referencing and referenced tables are
   14045              :      * the same), it is important that the ON UPDATE action fires before the
   14046              :      * CHECK action, since both triggers will fire on the same row during an
   14047              :      * UPDATE event; otherwise the CHECK trigger will be checking a non-final
   14048              :      * state of the row.  Triggers fire in name order, so we ensure this by
   14049              :      * using names like "RI_ConstraintTrigger_a_NNNN" for the action triggers
   14050              :      * and "RI_ConstraintTrigger_c_NNNN" for the check triggers.
   14051              :      */
   14052         3924 :     fk_trigger = makeNode(CreateTrigStmt);
   14053         3924 :     fk_trigger->replace = false;
   14054         3924 :     fk_trigger->isconstraint = true;
   14055         3924 :     fk_trigger->trigname = "RI_ConstraintTrigger_c";
   14056         3924 :     fk_trigger->relation = NULL;
   14057              : 
   14058              :     /* Either ON INSERT or ON UPDATE */
   14059         3924 :     if (on_insert)
   14060              :     {
   14061         1962 :         fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
   14062         1962 :         fk_trigger->events = TRIGGER_TYPE_INSERT;
   14063              :     }
   14064              :     else
   14065              :     {
   14066         1962 :         fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
   14067         1962 :         fk_trigger->events = TRIGGER_TYPE_UPDATE;
   14068              :     }
   14069              : 
   14070         3924 :     fk_trigger->args = NIL;
   14071         3924 :     fk_trigger->row = true;
   14072         3924 :     fk_trigger->timing = TRIGGER_TYPE_AFTER;
   14073         3924 :     fk_trigger->columns = NIL;
   14074         3924 :     fk_trigger->whenClause = NULL;
   14075         3924 :     fk_trigger->transitionRels = NIL;
   14076         3924 :     fk_trigger->deferrable = fkconstraint->deferrable;
   14077         3924 :     fk_trigger->initdeferred = fkconstraint->initdeferred;
   14078         3924 :     fk_trigger->constrrel = NULL;
   14079              : 
   14080         3924 :     trigAddress = CreateTrigger(fk_trigger, NULL, myRelOid, refRelOid,
   14081              :                                 constraintOid, indexOid, InvalidOid,
   14082              :                                 parentTrigOid, NULL, true, false);
   14083              : 
   14084              :     /* Make changes-so-far visible */
   14085         3924 :     CommandCounterIncrement();
   14086              : 
   14087         3924 :     return trigAddress.objectId;
   14088              : }
   14089              : 
   14090              : /*
   14091              :  * createForeignKeyActionTriggers
   14092              :  *      Create the referenced-side "action" triggers that implement a foreign
   14093              :  *      key.
   14094              :  *
   14095              :  * Returns the OIDs of the so created triggers in *deleteTrigOid and
   14096              :  * *updateTrigOid.
   14097              :  */
   14098              : static void
   14099         2249 : createForeignKeyActionTriggers(Oid myRelOid, Oid refRelOid, Constraint *fkconstraint,
   14100              :                                Oid constraintOid, Oid indexOid,
   14101              :                                Oid parentDelTrigger, Oid parentUpdTrigger,
   14102              :                                Oid *deleteTrigOid, Oid *updateTrigOid)
   14103              : {
   14104              :     CreateTrigStmt *fk_trigger;
   14105              :     ObjectAddress trigAddress;
   14106              : 
   14107              :     /*
   14108              :      * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
   14109              :      * DELETE action on the referenced table.
   14110              :      */
   14111         2249 :     fk_trigger = makeNode(CreateTrigStmt);
   14112         2249 :     fk_trigger->replace = false;
   14113         2249 :     fk_trigger->isconstraint = true;
   14114         2249 :     fk_trigger->trigname = "RI_ConstraintTrigger_a";
   14115         2249 :     fk_trigger->relation = NULL;
   14116         2249 :     fk_trigger->args = NIL;
   14117         2249 :     fk_trigger->row = true;
   14118         2249 :     fk_trigger->timing = TRIGGER_TYPE_AFTER;
   14119         2249 :     fk_trigger->events = TRIGGER_TYPE_DELETE;
   14120         2249 :     fk_trigger->columns = NIL;
   14121         2249 :     fk_trigger->whenClause = NULL;
   14122         2249 :     fk_trigger->transitionRels = NIL;
   14123         2249 :     fk_trigger->constrrel = NULL;
   14124              : 
   14125         2249 :     switch (fkconstraint->fk_del_action)
   14126              :     {
   14127         1820 :         case FKCONSTR_ACTION_NOACTION:
   14128         1820 :             fk_trigger->deferrable = fkconstraint->deferrable;
   14129         1820 :             fk_trigger->initdeferred = fkconstraint->initdeferred;
   14130         1820 :             fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
   14131         1820 :             break;
   14132           20 :         case FKCONSTR_ACTION_RESTRICT:
   14133           20 :             fk_trigger->deferrable = false;
   14134           20 :             fk_trigger->initdeferred = false;
   14135           20 :             fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
   14136           20 :             break;
   14137          306 :         case FKCONSTR_ACTION_CASCADE:
   14138          306 :             fk_trigger->deferrable = false;
   14139          306 :             fk_trigger->initdeferred = false;
   14140          306 :             fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
   14141          306 :             break;
   14142           63 :         case FKCONSTR_ACTION_SETNULL:
   14143           63 :             fk_trigger->deferrable = false;
   14144           63 :             fk_trigger->initdeferred = false;
   14145           63 :             fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
   14146           63 :             break;
   14147           40 :         case FKCONSTR_ACTION_SETDEFAULT:
   14148           40 :             fk_trigger->deferrable = false;
   14149           40 :             fk_trigger->initdeferred = false;
   14150           40 :             fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
   14151           40 :             break;
   14152            0 :         default:
   14153            0 :             elog(ERROR, "unrecognized FK action type: %d",
   14154              :                  (int) fkconstraint->fk_del_action);
   14155              :             break;
   14156              :     }
   14157              : 
   14158         2249 :     trigAddress = CreateTrigger(fk_trigger, NULL, refRelOid, myRelOid,
   14159              :                                 constraintOid, indexOid, InvalidOid,
   14160              :                                 parentDelTrigger, NULL, true, false);
   14161         2249 :     if (deleteTrigOid)
   14162         2249 :         *deleteTrigOid = trigAddress.objectId;
   14163              : 
   14164              :     /* Make changes-so-far visible */
   14165         2249 :     CommandCounterIncrement();
   14166              : 
   14167              :     /*
   14168              :      * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
   14169              :      * UPDATE action on the referenced table.
   14170              :      */
   14171         2249 :     fk_trigger = makeNode(CreateTrigStmt);
   14172         2249 :     fk_trigger->replace = false;
   14173         2249 :     fk_trigger->isconstraint = true;
   14174         2249 :     fk_trigger->trigname = "RI_ConstraintTrigger_a";
   14175         2249 :     fk_trigger->relation = NULL;
   14176         2249 :     fk_trigger->args = NIL;
   14177         2249 :     fk_trigger->row = true;
   14178         2249 :     fk_trigger->timing = TRIGGER_TYPE_AFTER;
   14179         2249 :     fk_trigger->events = TRIGGER_TYPE_UPDATE;
   14180         2249 :     fk_trigger->columns = NIL;
   14181         2249 :     fk_trigger->whenClause = NULL;
   14182         2249 :     fk_trigger->transitionRels = NIL;
   14183         2249 :     fk_trigger->constrrel = NULL;
   14184              : 
   14185         2249 :     switch (fkconstraint->fk_upd_action)
   14186              :     {
   14187         1945 :         case FKCONSTR_ACTION_NOACTION:
   14188         1945 :             fk_trigger->deferrable = fkconstraint->deferrable;
   14189         1945 :             fk_trigger->initdeferred = fkconstraint->initdeferred;
   14190         1945 :             fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
   14191         1945 :             break;
   14192           24 :         case FKCONSTR_ACTION_RESTRICT:
   14193           24 :             fk_trigger->deferrable = false;
   14194           24 :             fk_trigger->initdeferred = false;
   14195           24 :             fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
   14196           24 :             break;
   14197          211 :         case FKCONSTR_ACTION_CASCADE:
   14198          211 :             fk_trigger->deferrable = false;
   14199          211 :             fk_trigger->initdeferred = false;
   14200          211 :             fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
   14201          211 :             break;
   14202           41 :         case FKCONSTR_ACTION_SETNULL:
   14203           41 :             fk_trigger->deferrable = false;
   14204           41 :             fk_trigger->initdeferred = false;
   14205           41 :             fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
   14206           41 :             break;
   14207           28 :         case FKCONSTR_ACTION_SETDEFAULT:
   14208           28 :             fk_trigger->deferrable = false;
   14209           28 :             fk_trigger->initdeferred = false;
   14210           28 :             fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
   14211           28 :             break;
   14212            0 :         default:
   14213            0 :             elog(ERROR, "unrecognized FK action type: %d",
   14214              :                  (int) fkconstraint->fk_upd_action);
   14215              :             break;
   14216              :     }
   14217              : 
   14218         2249 :     trigAddress = CreateTrigger(fk_trigger, NULL, refRelOid, myRelOid,
   14219              :                                 constraintOid, indexOid, InvalidOid,
   14220              :                                 parentUpdTrigger, NULL, true, false);
   14221         2249 :     if (updateTrigOid)
   14222         2249 :         *updateTrigOid = trigAddress.objectId;
   14223         2249 : }
   14224              : 
   14225              : /*
   14226              :  * createForeignKeyCheckTriggers
   14227              :  *      Create the referencing-side "check" triggers that implement a foreign
   14228              :  *      key.
   14229              :  *
   14230              :  * Returns the OIDs of the so created triggers in *insertTrigOid and
   14231              :  * *updateTrigOid.
   14232              :  */
   14233              : static void
   14234         1962 : createForeignKeyCheckTriggers(Oid myRelOid, Oid refRelOid,
   14235              :                               Constraint *fkconstraint, Oid constraintOid,
   14236              :                               Oid indexOid,
   14237              :                               Oid parentInsTrigger, Oid parentUpdTrigger,
   14238              :                               Oid *insertTrigOid, Oid *updateTrigOid)
   14239              : {
   14240         1962 :     *insertTrigOid = CreateFKCheckTrigger(myRelOid, refRelOid, fkconstraint,
   14241              :                                           constraintOid, indexOid,
   14242              :                                           parentInsTrigger, true);
   14243         1962 :     *updateTrigOid = CreateFKCheckTrigger(myRelOid, refRelOid, fkconstraint,
   14244              :                                           constraintOid, indexOid,
   14245              :                                           parentUpdTrigger, false);
   14246         1962 : }
   14247              : 
   14248              : /*
   14249              :  * ALTER TABLE DROP CONSTRAINT
   14250              :  *
   14251              :  * Like DROP COLUMN, we can't use the normal ALTER TABLE recursion mechanism.
   14252              :  */
   14253              : static void
   14254          549 : ATExecDropConstraint(Relation rel, const char *constrName,
   14255              :                      DropBehavior behavior, bool recurse,
   14256              :                      bool missing_ok, LOCKMODE lockmode)
   14257              : {
   14258              :     Relation    conrel;
   14259              :     SysScanDesc scan;
   14260              :     ScanKeyData skey[3];
   14261              :     HeapTuple   tuple;
   14262          549 :     bool        found = false;
   14263              : 
   14264          549 :     conrel = table_open(ConstraintRelationId, RowExclusiveLock);
   14265              : 
   14266              :     /*
   14267              :      * Find and drop the target constraint
   14268              :      */
   14269          549 :     ScanKeyInit(&skey[0],
   14270              :                 Anum_pg_constraint_conrelid,
   14271              :                 BTEqualStrategyNumber, F_OIDEQ,
   14272              :                 ObjectIdGetDatum(RelationGetRelid(rel)));
   14273          549 :     ScanKeyInit(&skey[1],
   14274              :                 Anum_pg_constraint_contypid,
   14275              :                 BTEqualStrategyNumber, F_OIDEQ,
   14276              :                 ObjectIdGetDatum(InvalidOid));
   14277          549 :     ScanKeyInit(&skey[2],
   14278              :                 Anum_pg_constraint_conname,
   14279              :                 BTEqualStrategyNumber, F_NAMEEQ,
   14280              :                 CStringGetDatum(constrName));
   14281          549 :     scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
   14282              :                               true, NULL, 3, skey);
   14283              : 
   14284              :     /* There can be at most one matching row */
   14285          549 :     if (HeapTupleIsValid(tuple = systable_getnext(scan)))
   14286              :     {
   14287          525 :         dropconstraint_internal(rel, tuple, behavior, recurse, false,
   14288              :                                 missing_ok, lockmode);
   14289          401 :         found = true;
   14290              :     }
   14291              : 
   14292          425 :     systable_endscan(scan);
   14293              : 
   14294          425 :     if (!found)
   14295              :     {
   14296           24 :         if (!missing_ok)
   14297           16 :             ereport(ERROR,
   14298              :                     errcode(ERRCODE_UNDEFINED_OBJECT),
   14299              :                     errmsg("constraint \"%s\" of relation \"%s\" does not exist",
   14300              :                            constrName, RelationGetRelationName(rel)));
   14301              :         else
   14302            8 :             ereport(NOTICE,
   14303              :                     errmsg("constraint \"%s\" of relation \"%s\" does not exist, skipping",
   14304              :                            constrName, RelationGetRelationName(rel)));
   14305              :     }
   14306              : 
   14307          409 :     table_close(conrel, RowExclusiveLock);
   14308          409 : }
   14309              : 
   14310              : /*
   14311              :  * Remove a constraint, using its pg_constraint tuple
   14312              :  *
   14313              :  * Implementation for ALTER TABLE DROP CONSTRAINT and ALTER TABLE ALTER COLUMN
   14314              :  * DROP NOT NULL.
   14315              :  *
   14316              :  * Returns the address of the constraint being removed.
   14317              :  */
   14318              : static ObjectAddress
   14319          829 : dropconstraint_internal(Relation rel, HeapTuple constraintTup, DropBehavior behavior,
   14320              :                         bool recurse, bool recursing, bool missing_ok,
   14321              :                         LOCKMODE lockmode)
   14322              : {
   14323              :     Relation    conrel;
   14324              :     Form_pg_constraint con;
   14325              :     ObjectAddress conobj;
   14326              :     List       *children;
   14327          829 :     bool        is_no_inherit_constraint = false;
   14328              :     char       *constrName;
   14329          829 :     char       *colname = NULL;
   14330              : 
   14331              :     /* Guard against stack overflow due to overly deep inheritance tree. */
   14332          829 :     check_stack_depth();
   14333              : 
   14334              :     /* At top level, permission check was done in ATPrepCmd, else do it */
   14335          829 :     if (recursing)
   14336          159 :         ATSimplePermissions(AT_DropConstraint, rel,
   14337              :                             ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
   14338              : 
   14339          825 :     conrel = table_open(ConstraintRelationId, RowExclusiveLock);
   14340              : 
   14341          825 :     con = (Form_pg_constraint) GETSTRUCT(constraintTup);
   14342          825 :     constrName = NameStr(con->conname);
   14343              : 
   14344              :     /* Don't allow drop of inherited constraints */
   14345          825 :     if (con->coninhcount > 0 && !recursing)
   14346          104 :         ereport(ERROR,
   14347              :                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   14348              :                  errmsg("cannot drop inherited constraint \"%s\" of relation \"%s\"",
   14349              :                         constrName, RelationGetRelationName(rel))));
   14350              : 
   14351              :     /*
   14352              :      * Reset pg_constraint.attnotnull, if this is a not-null constraint.
   14353              :      *
   14354              :      * While doing that, we're in a good position to disallow dropping a not-
   14355              :      * null constraint underneath a primary key, a replica identity index, or
   14356              :      * a generated identity column.
   14357              :      */
   14358          721 :     if (con->contype == CONSTRAINT_NOTNULL)
   14359              :     {
   14360          207 :         Relation    attrel = table_open(AttributeRelationId, RowExclusiveLock);
   14361          207 :         AttrNumber  attnum = extractNotNullColumn(constraintTup);
   14362              :         Bitmapset  *pkattrs;
   14363              :         Bitmapset  *irattrs;
   14364              :         HeapTuple   atttup;
   14365              :         Form_pg_attribute attForm;
   14366              : 
   14367              :         /* save column name for recursion step */
   14368          207 :         colname = get_attname(RelationGetRelid(rel), attnum, false);
   14369              : 
   14370              :         /*
   14371              :          * Disallow if it's in the primary key.  For partitioned tables we
   14372              :          * cannot rely solely on RelationGetIndexAttrBitmap, because it'll
   14373              :          * return NULL if the primary key is invalid; but we still need to
   14374              :          * protect not-null constraints under such a constraint, so check the
   14375              :          * slow way.
   14376              :          */
   14377          207 :         pkattrs = RelationGetIndexAttrBitmap(rel, INDEX_ATTR_BITMAP_PRIMARY_KEY);
   14378              : 
   14379          207 :         if (pkattrs == NULL &&
   14380          183 :             rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
   14381              :         {
   14382           12 :             Oid         pkindex = RelationGetPrimaryKeyIndex(rel, true);
   14383              : 
   14384           12 :             if (OidIsValid(pkindex))
   14385              :             {
   14386            0 :                 Relation    pk = relation_open(pkindex, AccessShareLock);
   14387              : 
   14388            0 :                 pkattrs = NULL;
   14389            0 :                 for (int i = 0; i < pk->rd_index->indnkeyatts; i++)
   14390            0 :                     pkattrs = bms_add_member(pkattrs, pk->rd_index->indkey.values[i]);
   14391              : 
   14392            0 :                 relation_close(pk, AccessShareLock);
   14393              :             }
   14394              :         }
   14395              : 
   14396          231 :         if (pkattrs &&
   14397           24 :             bms_is_member(attnum - FirstLowInvalidHeapAttributeNumber, pkattrs))
   14398           16 :             ereport(ERROR,
   14399              :                     errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   14400              :                     errmsg("column \"%s\" is in a primary key",
   14401              :                            get_attname(RelationGetRelid(rel), attnum, false)));
   14402              : 
   14403              :         /* Disallow if it's in the replica identity */
   14404          191 :         irattrs = RelationGetIndexAttrBitmap(rel, INDEX_ATTR_BITMAP_IDENTITY_KEY);
   14405          191 :         if (bms_is_member(attnum - FirstLowInvalidHeapAttributeNumber, irattrs))
   14406            8 :             ereport(ERROR,
   14407              :                     errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   14408              :                     errmsg("column \"%s\" is in index used as replica identity",
   14409              :                            get_attname(RelationGetRelid(rel), attnum, false)));
   14410              : 
   14411              :         /* Disallow if it's a GENERATED AS IDENTITY column */
   14412          183 :         atttup = SearchSysCacheCopyAttNum(RelationGetRelid(rel), attnum);
   14413          183 :         if (!HeapTupleIsValid(atttup))
   14414            0 :             elog(ERROR, "cache lookup failed for attribute %d of relation %u",
   14415              :                  attnum, RelationGetRelid(rel));
   14416          183 :         attForm = (Form_pg_attribute) GETSTRUCT(atttup);
   14417          183 :         if (attForm->attidentity != '\0')
   14418            0 :             ereport(ERROR,
   14419              :                     errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
   14420              :                     errmsg("column \"%s\" of relation \"%s\" is an identity column",
   14421              :                            get_attname(RelationGetRelid(rel), attnum,
   14422              :                                        false),
   14423              :                            RelationGetRelationName(rel)));
   14424              : 
   14425              :         /* All good -- reset attnotnull if needed */
   14426          183 :         if (attForm->attnotnull)
   14427              :         {
   14428          183 :             attForm->attnotnull = false;
   14429          183 :             CatalogTupleUpdate(attrel, &atttup->t_self, atttup);
   14430              :         }
   14431              : 
   14432          183 :         table_close(attrel, RowExclusiveLock);
   14433              :     }
   14434              : 
   14435          697 :     is_no_inherit_constraint = con->connoinherit;
   14436              : 
   14437              :     /*
   14438              :      * If it's a foreign-key constraint, we'd better lock the referenced table
   14439              :      * and check that that's not in use, just as we've already done for the
   14440              :      * constrained table (else we might, eg, be dropping a trigger that has
   14441              :      * unfired events).  But we can/must skip that in the self-referential
   14442              :      * case.
   14443              :      */
   14444          697 :     if (con->contype == CONSTRAINT_FOREIGN &&
   14445          112 :         con->confrelid != RelationGetRelid(rel))
   14446              :     {
   14447              :         Relation    frel;
   14448              : 
   14449              :         /* Must match lock taken by RemoveTriggerById: */
   14450          112 :         frel = table_open(con->confrelid, AccessExclusiveLock);
   14451          112 :         CheckAlterTableIsSafe(frel);
   14452          108 :         table_close(frel, NoLock);
   14453              :     }
   14454              : 
   14455              :     /*
   14456              :      * Perform the actual constraint deletion
   14457              :      */
   14458          693 :     ObjectAddressSet(conobj, ConstraintRelationId, con->oid);
   14459          693 :     performDeletion(&conobj, behavior, 0);
   14460              : 
   14461              :     /*
   14462              :      * For partitioned tables, non-CHECK, non-NOT-NULL inherited constraints
   14463              :      * are dropped via the dependency mechanism, so we're done here.
   14464              :      */
   14465          669 :     if (con->contype != CONSTRAINT_CHECK &&
   14466          416 :         con->contype != CONSTRAINT_NOTNULL &&
   14467          233 :         rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
   14468              :     {
   14469           52 :         table_close(conrel, RowExclusiveLock);
   14470           52 :         return conobj;
   14471              :     }
   14472              : 
   14473              :     /*
   14474              :      * Propagate to children as appropriate.  Unlike most other ALTER
   14475              :      * routines, we have to do this one level of recursion at a time; we can't
   14476              :      * use find_all_inheritors to do it in one pass.
   14477              :      */
   14478          617 :     if (!is_no_inherit_constraint)
   14479          428 :         children = find_inheritance_children(RelationGetRelid(rel), lockmode);
   14480              :     else
   14481          189 :         children = NIL;
   14482              : 
   14483         1509 :     foreach_oid(childrelid, children)
   14484              :     {
   14485              :         Relation    childrel;
   14486              :         HeapTuple   tuple;
   14487              :         Form_pg_constraint childcon;
   14488              : 
   14489              :         /* find_inheritance_children already got lock */
   14490          283 :         childrel = table_open(childrelid, NoLock);
   14491          283 :         CheckAlterTableIsSafe(childrel);
   14492              : 
   14493              :         /*
   14494              :          * We search for not-null constraints by column name, and others by
   14495              :          * constraint name.
   14496              :          */
   14497          283 :         if (con->contype == CONSTRAINT_NOTNULL)
   14498              :         {
   14499           98 :             tuple = findNotNullConstraint(childrelid, colname);
   14500           98 :             if (!HeapTupleIsValid(tuple))
   14501            0 :                 elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation %u",
   14502              :                      colname, RelationGetRelid(childrel));
   14503              :         }
   14504              :         else
   14505              :         {
   14506              :             SysScanDesc scan;
   14507              :             ScanKeyData skey[3];
   14508              : 
   14509          185 :             ScanKeyInit(&skey[0],
   14510              :                         Anum_pg_constraint_conrelid,
   14511              :                         BTEqualStrategyNumber, F_OIDEQ,
   14512              :                         ObjectIdGetDatum(childrelid));
   14513          185 :             ScanKeyInit(&skey[1],
   14514              :                         Anum_pg_constraint_contypid,
   14515              :                         BTEqualStrategyNumber, F_OIDEQ,
   14516              :                         ObjectIdGetDatum(InvalidOid));
   14517          185 :             ScanKeyInit(&skey[2],
   14518              :                         Anum_pg_constraint_conname,
   14519              :                         BTEqualStrategyNumber, F_NAMEEQ,
   14520              :                         CStringGetDatum(constrName));
   14521          185 :             scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
   14522              :                                       true, NULL, 3, skey);
   14523              :             /* There can only be one, so no need to loop */
   14524          185 :             tuple = systable_getnext(scan);
   14525          185 :             if (!HeapTupleIsValid(tuple))
   14526            0 :                 ereport(ERROR,
   14527              :                         (errcode(ERRCODE_UNDEFINED_OBJECT),
   14528              :                          errmsg("constraint \"%s\" of relation \"%s\" does not exist",
   14529              :                                 constrName,
   14530              :                                 RelationGetRelationName(childrel))));
   14531          185 :             tuple = heap_copytuple(tuple);
   14532          185 :             systable_endscan(scan);
   14533              :         }
   14534              : 
   14535          283 :         childcon = (Form_pg_constraint) GETSTRUCT(tuple);
   14536              : 
   14537              :         /* Right now only CHECK and not-null constraints can be inherited */
   14538          283 :         if (childcon->contype != CONSTRAINT_CHECK &&
   14539           98 :             childcon->contype != CONSTRAINT_NOTNULL)
   14540            0 :             elog(ERROR, "inherited constraint is not a CHECK or not-null constraint");
   14541              : 
   14542          283 :         if (childcon->coninhcount <= 0) /* shouldn't happen */
   14543            0 :             elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
   14544              :                  childrelid, NameStr(childcon->conname));
   14545              : 
   14546          283 :         if (recurse)
   14547              :         {
   14548              :             /*
   14549              :              * If the child constraint has other definition sources, just
   14550              :              * decrement its inheritance count; if not, recurse to delete it.
   14551              :              */
   14552          215 :             if (childcon->coninhcount == 1 && !childcon->conislocal)
   14553              :             {
   14554              :                 /* Time to delete this child constraint, too */
   14555          159 :                 dropconstraint_internal(childrel, tuple, behavior,
   14556              :                                         recurse, true, missing_ok,
   14557              :                                         lockmode);
   14558              :             }
   14559              :             else
   14560              :             {
   14561              :                 /* Child constraint must survive my deletion */
   14562           56 :                 childcon->coninhcount--;
   14563           56 :                 CatalogTupleUpdate(conrel, &tuple->t_self, tuple);
   14564              : 
   14565              :                 /* Make update visible */
   14566           56 :                 CommandCounterIncrement();
   14567              :             }
   14568              :         }
   14569              :         else
   14570              :         {
   14571              :             /*
   14572              :              * If we were told to drop ONLY in this table (no recursion) and
   14573              :              * there are no further parents for this constraint, we need to
   14574              :              * mark the inheritors' constraints as locally defined rather than
   14575              :              * inherited.
   14576              :              */
   14577           68 :             childcon->coninhcount--;
   14578           68 :             if (childcon->coninhcount == 0)
   14579           68 :                 childcon->conislocal = true;
   14580              : 
   14581           68 :             CatalogTupleUpdate(conrel, &tuple->t_self, tuple);
   14582              : 
   14583              :             /* Make update visible */
   14584           68 :             CommandCounterIncrement();
   14585              :         }
   14586              : 
   14587          279 :         heap_freetuple(tuple);
   14588              : 
   14589          279 :         table_close(childrel, NoLock);
   14590              :     }
   14591              : 
   14592          613 :     table_close(conrel, RowExclusiveLock);
   14593              : 
   14594          613 :     return conobj;
   14595              : }
   14596              : 
   14597              : /*
   14598              :  * ALTER COLUMN TYPE
   14599              :  *
   14600              :  * Unlike other subcommand types, we do parse transformation for ALTER COLUMN
   14601              :  * TYPE during phase 1 --- the AlterTableCmd passed in here is already
   14602              :  * transformed (and must be, because we rely on some transformed fields).
   14603              :  *
   14604              :  * The point of this is that the execution of all ALTER COLUMN TYPEs for a
   14605              :  * table will be done "in parallel" during phase 3, so all the USING
   14606              :  * expressions should be parsed assuming the original column types.  Also,
   14607              :  * this allows a USING expression to refer to a field that will be dropped.
   14608              :  *
   14609              :  * To make this work safely, AT_PASS_DROP then AT_PASS_ALTER_TYPE must be
   14610              :  * the first two execution steps in phase 2; they must not see the effects
   14611              :  * of any other subcommand types, since the USING expressions are parsed
   14612              :  * against the unmodified table's state.
   14613              :  */
   14614              : static void
   14615          936 : ATPrepAlterColumnType(List **wqueue,
   14616              :                       AlteredTableInfo *tab, Relation rel,
   14617              :                       bool recurse, bool recursing,
   14618              :                       AlterTableCmd *cmd, LOCKMODE lockmode,
   14619              :                       AlterTableUtilityContext *context)
   14620              : {
   14621          936 :     char       *colName = cmd->name;
   14622          936 :     ColumnDef  *def = (ColumnDef *) cmd->def;
   14623          936 :     TypeName   *typeName = def->typeName;
   14624          936 :     Node       *transform = def->cooked_default;
   14625              :     HeapTuple   tuple;
   14626              :     Form_pg_attribute attTup;
   14627              :     AttrNumber  attnum;
   14628              :     Oid         targettype;
   14629              :     int32       targettypmod;
   14630              :     Oid         targetcollid;
   14631              :     NewColumnValue *newval;
   14632          936 :     ParseState *pstate = make_parsestate(NULL);
   14633              :     AclResult   aclresult;
   14634              :     bool        is_expr;
   14635              : 
   14636          936 :     pstate->p_sourcetext = context->queryString;
   14637              : 
   14638          936 :     if (rel->rd_rel->reloftype && !recursing)
   14639            4 :         ereport(ERROR,
   14640              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   14641              :                  errmsg("cannot alter column type of typed table"),
   14642              :                  parser_errposition(pstate, def->location)));
   14643              : 
   14644              :     /* lookup the attribute so we can check inheritance status */
   14645          932 :     tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
   14646          932 :     if (!HeapTupleIsValid(tuple))
   14647            0 :         ereport(ERROR,
   14648              :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
   14649              :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
   14650              :                         colName, RelationGetRelationName(rel)),
   14651              :                  parser_errposition(pstate, def->location)));
   14652          932 :     attTup = (Form_pg_attribute) GETSTRUCT(tuple);
   14653          932 :     attnum = attTup->attnum;
   14654              : 
   14655              :     /* Can't alter a system attribute */
   14656          932 :     if (attnum <= 0)
   14657            4 :         ereport(ERROR,
   14658              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   14659              :                  errmsg("cannot alter system column \"%s\"", colName),
   14660              :                  parser_errposition(pstate, def->location)));
   14661              : 
   14662              :     /*
   14663              :      * Cannot specify USING when altering type of a generated column, because
   14664              :      * that would violate the generation expression.
   14665              :      */
   14666          928 :     if (attTup->attgenerated && def->cooked_default)
   14667            8 :         ereport(ERROR,
   14668              :                 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
   14669              :                  errmsg("cannot specify USING when altering type of generated column"),
   14670              :                  errdetail("Column \"%s\" is a generated column.", colName),
   14671              :                  parser_errposition(pstate, def->location)));
   14672              : 
   14673              :     /*
   14674              :      * Don't alter inherited columns.  At outer level, there had better not be
   14675              :      * any inherited definition; when recursing, we assume this was checked at
   14676              :      * the parent level (see below).
   14677              :      */
   14678          920 :     if (attTup->attinhcount > 0 && !recursing)
   14679            4 :         ereport(ERROR,
   14680              :                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   14681              :                  errmsg("cannot alter inherited column \"%s\"", colName),
   14682              :                  parser_errposition(pstate, def->location)));
   14683              : 
   14684              :     /* Don't alter columns used in the partition key */
   14685          916 :     if (has_partition_attrs(rel,
   14686              :                             bms_make_singleton(attnum - FirstLowInvalidHeapAttributeNumber),
   14687              :                             &is_expr))
   14688           12 :         ereport(ERROR,
   14689              :                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   14690              :                  errmsg("cannot alter column \"%s\" because it is part of the partition key of relation \"%s\"",
   14691              :                         colName, RelationGetRelationName(rel)),
   14692              :                  parser_errposition(pstate, def->location)));
   14693              : 
   14694              :     /* Look up the target type */
   14695          904 :     typenameTypeIdAndMod(pstate, typeName, &targettype, &targettypmod);
   14696              : 
   14697          900 :     aclresult = object_aclcheck(TypeRelationId, targettype, GetUserId(), ACL_USAGE);
   14698          900 :     if (aclresult != ACLCHECK_OK)
   14699            8 :         aclcheck_error_type(aclresult, targettype);
   14700              : 
   14701              :     /* And the collation */
   14702          892 :     targetcollid = GetColumnDefCollation(pstate, def, targettype);
   14703              : 
   14704              :     /* make sure datatype is legal for a column */
   14705         1776 :     CheckAttributeType(colName, targettype, targetcollid,
   14706          888 :                        list_make1_oid(rel->rd_rel->reltype),
   14707          888 :                        (attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL ? CHKATYPE_IS_VIRTUAL : 0));
   14708              : 
   14709          880 :     if (attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
   14710              :     {
   14711              :         /* do nothing */
   14712              :     }
   14713          856 :     else if (tab->relkind == RELKIND_RELATION ||
   14714          133 :              tab->relkind == RELKIND_PARTITIONED_TABLE)
   14715              :     {
   14716              :         /*
   14717              :          * Set up an expression to transform the old data value to the new
   14718              :          * type. If a USING option was given, use the expression as
   14719              :          * transformed by transformAlterTableStmt, else just take the old
   14720              :          * value and try to coerce it.  We do this first so that type
   14721              :          * incompatibility can be detected before we waste effort, and because
   14722              :          * we need the expression to be parsed against the original table row
   14723              :          * type.
   14724              :          */
   14725          767 :         if (!transform)
   14726              :         {
   14727          616 :             transform = (Node *) makeVar(1, attnum,
   14728              :                                          attTup->atttypid, attTup->atttypmod,
   14729              :                                          attTup->attcollation,
   14730              :                                          0);
   14731              :         }
   14732              : 
   14733          767 :         transform = coerce_to_target_type(pstate,
   14734              :                                           transform, exprType(transform),
   14735              :                                           targettype, targettypmod,
   14736              :                                           COERCION_ASSIGNMENT,
   14737              :                                           COERCE_IMPLICIT_CAST,
   14738              :                                           -1);
   14739          767 :         if (transform == NULL)
   14740              :         {
   14741              :             /* error text depends on whether USING was specified or not */
   14742           15 :             if (def->cooked_default != NULL)
   14743            4 :                 ereport(ERROR,
   14744              :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
   14745              :                          errmsg("result of USING clause for column \"%s\""
   14746              :                                 " cannot be cast automatically to type %s",
   14747              :                                 colName, format_type_be(targettype)),
   14748              :                          errhint("You might need to add an explicit cast.")));
   14749              :             else
   14750           11 :                 ereport(ERROR,
   14751              :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
   14752              :                          errmsg("column \"%s\" cannot be cast automatically to type %s",
   14753              :                                 colName, format_type_be(targettype)),
   14754              :                          !attTup->attgenerated ?
   14755              :                 /* translator: USING is SQL, don't translate it */
   14756              :                          errhint("You might need to specify \"USING %s::%s\".",
   14757              :                                  quote_identifier(colName),
   14758              :                                  format_type_with_typemod(targettype,
   14759              :                                                           targettypmod)) : 0));
   14760              :         }
   14761              : 
   14762              :         /* Fix collations after all else */
   14763          752 :         assign_expr_collations(pstate, transform);
   14764              : 
   14765              :         /* Expand virtual generated columns in the expr. */
   14766          752 :         transform = expand_generated_columns_in_expr(transform, rel, 1);
   14767              : 
   14768              :         /* Plan the expr now so we can accurately assess the need to rewrite. */
   14769          752 :         transform = (Node *) expression_planner((Expr *) transform);
   14770              : 
   14771              :         /*
   14772              :          * Add a work queue item to make ATRewriteTable update the column
   14773              :          * contents.
   14774              :          */
   14775          752 :         newval = palloc0_object(NewColumnValue);
   14776          752 :         newval->attnum = attnum;
   14777          752 :         newval->expr = (Expr *) transform;
   14778          752 :         newval->is_generated = false;
   14779              : 
   14780          752 :         tab->newvals = lappend(tab->newvals, newval);
   14781         1372 :         if (ATColumnChangeRequiresRewrite(transform, attnum))
   14782          620 :             tab->rewrite |= AT_REWRITE_COLUMN_REWRITE;
   14783              :     }
   14784           89 :     else if (transform)
   14785            8 :         ereport(ERROR,
   14786              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   14787              :                  errmsg("\"%s\" is not a table",
   14788              :                         RelationGetRelationName(rel))));
   14789              : 
   14790          857 :     if (!RELKIND_HAS_STORAGE(tab->relkind) || attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
   14791              :     {
   14792              :         /*
   14793              :          * For relations or columns without storage, do this check now.
   14794              :          * Regular tables will check it later when the table is being
   14795              :          * rewritten.
   14796              :          */
   14797          149 :         find_composite_type_dependencies(rel->rd_rel->reltype, rel, NULL);
   14798              :     }
   14799              : 
   14800          825 :     ReleaseSysCache(tuple);
   14801              : 
   14802              :     /*
   14803              :      * Recurse manually by queueing a new command for each child, if
   14804              :      * necessary. We cannot apply ATSimpleRecursion here because we need to
   14805              :      * remap attribute numbers in the USING expression, if any.
   14806              :      *
   14807              :      * If we are told not to recurse, there had better not be any child
   14808              :      * tables; else the alter would put them out of step.
   14809              :      */
   14810          825 :     if (recurse)
   14811              :     {
   14812          654 :         Oid         relid = RelationGetRelid(rel);
   14813              :         List       *child_oids,
   14814              :                    *child_numparents;
   14815              :         ListCell   *lo,
   14816              :                    *li;
   14817              : 
   14818          654 :         child_oids = find_all_inheritors(relid, lockmode,
   14819              :                                          &child_numparents);
   14820              : 
   14821              :         /*
   14822              :          * find_all_inheritors does the recursive search of the inheritance
   14823              :          * hierarchy, so all we have to do is process all of the relids in the
   14824              :          * list that it returns.
   14825              :          */
   14826         1446 :         forboth(lo, child_oids, li, child_numparents)
   14827              :         {
   14828          808 :             Oid         childrelid = lfirst_oid(lo);
   14829          808 :             int         numparents = lfirst_int(li);
   14830              :             Relation    childrel;
   14831              :             HeapTuple   childtuple;
   14832              :             Form_pg_attribute childattTup;
   14833              : 
   14834          808 :             if (childrelid == relid)
   14835          654 :                 continue;
   14836              : 
   14837              :             /* find_all_inheritors already got lock */
   14838          154 :             childrel = relation_open(childrelid, NoLock);
   14839          154 :             CheckAlterTableIsSafe(childrel);
   14840              : 
   14841              :             /*
   14842              :              * Verify that the child doesn't have any inherited definitions of
   14843              :              * this column that came from outside this inheritance hierarchy.
   14844              :              * (renameatt makes a similar test, though in a different way
   14845              :              * because of its different recursion mechanism.)
   14846              :              */
   14847          154 :             childtuple = SearchSysCacheAttName(RelationGetRelid(childrel),
   14848              :                                                colName);
   14849          154 :             if (!HeapTupleIsValid(childtuple))
   14850            0 :                 ereport(ERROR,
   14851              :                         (errcode(ERRCODE_UNDEFINED_COLUMN),
   14852              :                          errmsg("column \"%s\" of relation \"%s\" does not exist",
   14853              :                                 colName, RelationGetRelationName(childrel))));
   14854          154 :             childattTup = (Form_pg_attribute) GETSTRUCT(childtuple);
   14855              : 
   14856          154 :             if (childattTup->attinhcount > numparents)
   14857            4 :                 ereport(ERROR,
   14858              :                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   14859              :                          errmsg("cannot alter inherited column \"%s\" of relation \"%s\"",
   14860              :                                 colName, RelationGetRelationName(childrel))));
   14861              : 
   14862          150 :             ReleaseSysCache(childtuple);
   14863              : 
   14864              :             /*
   14865              :              * Remap the attribute numbers.  If no USING expression was
   14866              :              * specified, there is no need for this step.
   14867              :              */
   14868          150 :             if (def->cooked_default)
   14869              :             {
   14870              :                 AttrMap    *attmap;
   14871              :                 bool        found_whole_row;
   14872              : 
   14873              :                 /* create a copy to scribble on */
   14874           52 :                 cmd = copyObject(cmd);
   14875              : 
   14876           52 :                 attmap = build_attrmap_by_name(RelationGetDescr(childrel),
   14877              :                                                RelationGetDescr(rel),
   14878              :                                                false);
   14879          104 :                 ((ColumnDef *) cmd->def)->cooked_default =
   14880           52 :                     map_variable_attnos(def->cooked_default,
   14881              :                                         1, 0,
   14882              :                                         attmap,
   14883              :                                         InvalidOid, &found_whole_row);
   14884           52 :                 if (found_whole_row)
   14885            4 :                     ereport(ERROR,
   14886              :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   14887              :                              errmsg("cannot convert whole-row table reference"),
   14888              :                              errdetail("USING expression contains a whole-row table reference.")));
   14889           48 :                 pfree(attmap);
   14890              :             }
   14891          146 :             ATPrepCmd(wqueue, childrel, cmd, false, true, lockmode, context);
   14892          138 :             relation_close(childrel, NoLock);
   14893              :         }
   14894              :     }
   14895          204 :     else if (!recursing &&
   14896           33 :              find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL)
   14897            0 :         ereport(ERROR,
   14898              :                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   14899              :                  errmsg("type of inherited column \"%s\" must be changed in child tables too",
   14900              :                         colName)));
   14901              : 
   14902          809 :     if (tab->relkind == RELKIND_COMPOSITE_TYPE)
   14903           33 :         ATTypedTableRecursion(wqueue, rel, cmd, lockmode, context);
   14904          805 : }
   14905              : 
   14906              : /*
   14907              :  * When the data type of a column is changed, a rewrite might not be required
   14908              :  * if the new type is sufficiently identical to the old one, and the USING
   14909              :  * clause isn't trying to insert some other value.  It's safe to skip the
   14910              :  * rewrite in these cases:
   14911              :  *
   14912              :  * - the old type is binary coercible to the new type
   14913              :  * - the new type is an unconstrained domain over the old type
   14914              :  * - {NEW,OLD} or {OLD,NEW} is {timestamptz,timestamp} and the timezone is UTC
   14915              :  *
   14916              :  * In the case of a constrained domain, we could get by with scanning the
   14917              :  * table and checking the constraint rather than actually rewriting it, but we
   14918              :  * don't currently try to do that.
   14919              :  */
   14920              : static bool
   14921          752 : ATColumnChangeRequiresRewrite(Node *expr, AttrNumber varattno)
   14922              : {
   14923              :     Assert(expr != NULL);
   14924              : 
   14925              :     for (;;)
   14926              :     {
   14927              :         /* only one varno, so no need to check that */
   14928          828 :         if (IsA(expr, Var) && ((Var *) expr)->varattno == varattno)
   14929          132 :             return false;
   14930          696 :         else if (IsA(expr, RelabelType))
   14931           68 :             expr = (Node *) ((RelabelType *) expr)->arg;
   14932          628 :         else if (IsA(expr, CoerceToDomain))
   14933              :         {
   14934            0 :             CoerceToDomain *d = (CoerceToDomain *) expr;
   14935              : 
   14936            0 :             if (DomainHasConstraints(d->resulttype, NULL))
   14937            0 :                 return true;
   14938            0 :             expr = (Node *) d->arg;
   14939              :         }
   14940          628 :         else if (IsA(expr, FuncExpr))
   14941              :         {
   14942          495 :             FuncExpr   *f = (FuncExpr *) expr;
   14943              : 
   14944          495 :             switch (f->funcid)
   14945              :             {
   14946           12 :                 case F_TIMESTAMPTZ_TIMESTAMP:
   14947              :                 case F_TIMESTAMP_TIMESTAMPTZ:
   14948           12 :                     if (TimestampTimestampTzRequiresRewrite())
   14949            4 :                         return true;
   14950              :                     else
   14951            8 :                         expr = linitial(f->args);
   14952            8 :                     break;
   14953          483 :                 default:
   14954          483 :                     return true;
   14955              :             }
   14956              :         }
   14957              :         else
   14958          133 :             return true;
   14959              :     }
   14960              : }
   14961              : 
   14962              : /*
   14963              :  * ALTER COLUMN .. SET DATA TYPE
   14964              :  *
   14965              :  * Return the address of the modified column.
   14966              :  */
   14967              : static ObjectAddress
   14968          781 : ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
   14969              :                       AlterTableCmd *cmd, LOCKMODE lockmode)
   14970              : {
   14971          781 :     char       *colName = cmd->name;
   14972          781 :     ColumnDef  *def = (ColumnDef *) cmd->def;
   14973          781 :     TypeName   *typeName = def->typeName;
   14974              :     HeapTuple   heapTup;
   14975              :     Form_pg_attribute attTup,
   14976              :                 attOldTup;
   14977              :     AttrNumber  attnum;
   14978              :     HeapTuple   typeTuple;
   14979              :     Form_pg_type tform;
   14980              :     Oid         targettype;
   14981              :     int32       targettypmod;
   14982              :     Oid         targetcollid;
   14983              :     Node       *defaultexpr;
   14984              :     Relation    attrelation;
   14985              :     Relation    depRel;
   14986              :     ScanKeyData key[3];
   14987              :     SysScanDesc scan;
   14988              :     HeapTuple   depTup;
   14989              :     ObjectAddress address;
   14990              : 
   14991              :     /*
   14992              :      * Clear all the missing values if we're rewriting the table, since this
   14993              :      * renders them pointless.
   14994              :      */
   14995          781 :     if (tab->rewrite)
   14996              :     {
   14997              :         Relation    newrel;
   14998              : 
   14999          580 :         newrel = table_open(RelationGetRelid(rel), NoLock);
   15000          580 :         RelationClearMissing(newrel);
   15001          580 :         relation_close(newrel, NoLock);
   15002              :         /* make sure we don't conflict with later attribute modifications */
   15003          580 :         CommandCounterIncrement();
   15004              :     }
   15005              : 
   15006          781 :     attrelation = table_open(AttributeRelationId, RowExclusiveLock);
   15007              : 
   15008              :     /* Look up the target column */
   15009          781 :     heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
   15010          781 :     if (!HeapTupleIsValid(heapTup)) /* shouldn't happen */
   15011            0 :         ereport(ERROR,
   15012              :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
   15013              :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
   15014              :                         colName, RelationGetRelationName(rel))));
   15015          781 :     attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
   15016          781 :     attnum = attTup->attnum;
   15017          781 :     attOldTup = TupleDescAttr(tab->oldDesc, attnum - 1);
   15018              : 
   15019              :     /* Check for multiple ALTER TYPE on same column --- can't cope */
   15020          781 :     if (attTup->atttypid != attOldTup->atttypid ||
   15021          781 :         attTup->atttypmod != attOldTup->atttypmod)
   15022            0 :         ereport(ERROR,
   15023              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   15024              :                  errmsg("cannot alter type of column \"%s\" twice",
   15025              :                         colName)));
   15026              : 
   15027              :     /* Look up the target type (should not fail, since prep found it) */
   15028          781 :     typeTuple = typenameType(NULL, typeName, &targettypmod);
   15029          781 :     tform = (Form_pg_type) GETSTRUCT(typeTuple);
   15030          781 :     targettype = tform->oid;
   15031              :     /* And the collation */
   15032          781 :     targetcollid = GetColumnDefCollation(NULL, def, targettype);
   15033              : 
   15034              :     /*
   15035              :      * If there is a default expression for the column, get it and ensure we
   15036              :      * can coerce it to the new datatype.  (We must do this before changing
   15037              :      * the column type, because build_column_default itself will try to
   15038              :      * coerce, and will not issue the error message we want if it fails.)
   15039              :      *
   15040              :      * We remove any implicit coercion steps at the top level of the old
   15041              :      * default expression; this has been agreed to satisfy the principle of
   15042              :      * least surprise.  (The conversion to the new column type should act like
   15043              :      * it started from what the user sees as the stored expression, and the
   15044              :      * implicit coercions aren't going to be shown.)
   15045              :      */
   15046          781 :     if (attTup->atthasdef)
   15047              :     {
   15048           60 :         defaultexpr = build_column_default(rel, attnum);
   15049              :         Assert(defaultexpr);
   15050           60 :         defaultexpr = strip_implicit_coercions(defaultexpr);
   15051           60 :         defaultexpr = coerce_to_target_type(NULL,   /* no UNKNOWN params */
   15052              :                                             defaultexpr, exprType(defaultexpr),
   15053              :                                             targettype, targettypmod,
   15054              :                                             COERCION_ASSIGNMENT,
   15055              :                                             COERCE_IMPLICIT_CAST,
   15056              :                                             -1);
   15057           60 :         if (defaultexpr == NULL)
   15058              :         {
   15059            4 :             if (attTup->attgenerated)
   15060            0 :                 ereport(ERROR,
   15061              :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
   15062              :                          errmsg("generation expression for column \"%s\" cannot be cast automatically to type %s",
   15063              :                                 colName, format_type_be(targettype))));
   15064              :             else
   15065            4 :                 ereport(ERROR,
   15066              :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
   15067              :                          errmsg("default for column \"%s\" cannot be cast automatically to type %s",
   15068              :                                 colName, format_type_be(targettype))));
   15069              :         }
   15070              :     }
   15071              :     else
   15072          721 :         defaultexpr = NULL;
   15073              : 
   15074              :     /*
   15075              :      * Find everything that depends on the column (constraints, indexes, etc),
   15076              :      * and record enough information to let us recreate the objects.
   15077              :      *
   15078              :      * The actual recreation does not happen here, but only after we have
   15079              :      * performed all the individual ALTER TYPE operations.  We have to save
   15080              :      * the info before executing ALTER TYPE, though, else the deparser will
   15081              :      * get confused.
   15082              :      */
   15083          777 :     RememberAllDependentForRebuilding(tab, AT_AlterColumnType, rel, attnum, colName);
   15084              : 
   15085              :     /*
   15086              :      * Now scan for dependencies of this column on other things.  The only
   15087              :      * things we should find are the dependency on the column datatype and
   15088              :      * possibly a collation dependency.  Those can be removed.
   15089              :      */
   15090          753 :     depRel = table_open(DependRelationId, RowExclusiveLock);
   15091              : 
   15092          753 :     ScanKeyInit(&key[0],
   15093              :                 Anum_pg_depend_classid,
   15094              :                 BTEqualStrategyNumber, F_OIDEQ,
   15095              :                 ObjectIdGetDatum(RelationRelationId));
   15096          753 :     ScanKeyInit(&key[1],
   15097              :                 Anum_pg_depend_objid,
   15098              :                 BTEqualStrategyNumber, F_OIDEQ,
   15099              :                 ObjectIdGetDatum(RelationGetRelid(rel)));
   15100          753 :     ScanKeyInit(&key[2],
   15101              :                 Anum_pg_depend_objsubid,
   15102              :                 BTEqualStrategyNumber, F_INT4EQ,
   15103              :                 Int32GetDatum((int32) attnum));
   15104              : 
   15105          753 :     scan = systable_beginscan(depRel, DependDependerIndexId, true,
   15106              :                               NULL, 3, key);
   15107              : 
   15108          755 :     while (HeapTupleIsValid(depTup = systable_getnext(scan)))
   15109              :     {
   15110            2 :         Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
   15111              :         ObjectAddress foundObject;
   15112              : 
   15113            2 :         foundObject.classId = foundDep->refclassid;
   15114            2 :         foundObject.objectId = foundDep->refobjid;
   15115            2 :         foundObject.objectSubId = foundDep->refobjsubid;
   15116              : 
   15117            2 :         if (foundDep->deptype != DEPENDENCY_NORMAL)
   15118            0 :             elog(ERROR, "found unexpected dependency type '%c'",
   15119              :                  foundDep->deptype);
   15120            2 :         if (!(foundDep->refclassid == TypeRelationId &&
   15121            2 :               foundDep->refobjid == attTup->atttypid) &&
   15122            0 :             !(foundDep->refclassid == CollationRelationId &&
   15123            0 :               foundDep->refobjid == attTup->attcollation))
   15124            0 :             elog(ERROR, "found unexpected dependency for column: %s",
   15125              :                  getObjectDescription(&foundObject, false));
   15126              : 
   15127            2 :         CatalogTupleDelete(depRel, &depTup->t_self);
   15128              :     }
   15129              : 
   15130          753 :     systable_endscan(scan);
   15131              : 
   15132          753 :     table_close(depRel, RowExclusiveLock);
   15133              : 
   15134              :     /*
   15135              :      * Here we go --- change the recorded column type and collation.  (Note
   15136              :      * heapTup is a copy of the syscache entry, so okay to scribble on.) First
   15137              :      * fix up the missing value if any.
   15138              :      */
   15139          753 :     if (attTup->atthasmissing)
   15140              :     {
   15141              :         Datum       missingval;
   15142              :         bool        missingNull;
   15143              : 
   15144              :         /* if rewrite is true the missing value should already be cleared */
   15145              :         Assert(tab->rewrite == 0);
   15146              : 
   15147              :         /* Get the missing value datum */
   15148            4 :         missingval = heap_getattr(heapTup,
   15149              :                                   Anum_pg_attribute_attmissingval,
   15150              :                                   attrelation->rd_att,
   15151              :                                   &missingNull);
   15152              : 
   15153              :         /* if it's a null array there is nothing to do */
   15154              : 
   15155            4 :         if (!missingNull)
   15156              :         {
   15157              :             /*
   15158              :              * Get the datum out of the array and repack it in a new array
   15159              :              * built with the new type data. We assume that since the table
   15160              :              * doesn't need rewriting, the actual Datum doesn't need to be
   15161              :              * changed, only the array metadata.
   15162              :              */
   15163              : 
   15164            4 :             int         one = 1;
   15165              :             bool        isNull;
   15166            4 :             Datum       valuesAtt[Natts_pg_attribute] = {0};
   15167            4 :             bool        nullsAtt[Natts_pg_attribute] = {0};
   15168            4 :             bool        replacesAtt[Natts_pg_attribute] = {0};
   15169              :             HeapTuple   newTup;
   15170              : 
   15171            8 :             missingval = array_get_element(missingval,
   15172              :                                            1,
   15173              :                                            &one,
   15174              :                                            0,
   15175            4 :                                            attTup->attlen,
   15176            4 :                                            attTup->attbyval,
   15177            4 :                                            attTup->attalign,
   15178              :                                            &isNull);
   15179            4 :             missingval = PointerGetDatum(construct_array(&missingval,
   15180              :                                                          1,
   15181              :                                                          targettype,
   15182            4 :                                                          tform->typlen,
   15183            4 :                                                          tform->typbyval,
   15184            4 :                                                          tform->typalign));
   15185              : 
   15186            4 :             valuesAtt[Anum_pg_attribute_attmissingval - 1] = missingval;
   15187            4 :             replacesAtt[Anum_pg_attribute_attmissingval - 1] = true;
   15188            4 :             nullsAtt[Anum_pg_attribute_attmissingval - 1] = false;
   15189              : 
   15190            4 :             newTup = heap_modify_tuple(heapTup, RelationGetDescr(attrelation),
   15191              :                                        valuesAtt, nullsAtt, replacesAtt);
   15192            4 :             heap_freetuple(heapTup);
   15193            4 :             heapTup = newTup;
   15194            4 :             attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
   15195              :         }
   15196              :     }
   15197              : 
   15198          753 :     attTup->atttypid = targettype;
   15199          753 :     attTup->atttypmod = targettypmod;
   15200          753 :     attTup->attcollation = targetcollid;
   15201          753 :     if (list_length(typeName->arrayBounds) > PG_INT16_MAX)
   15202            0 :         ereport(ERROR,
   15203              :                 errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
   15204              :                 errmsg("too many array dimensions"));
   15205          753 :     attTup->attndims = list_length(typeName->arrayBounds);
   15206          753 :     attTup->attlen = tform->typlen;
   15207          753 :     attTup->attbyval = tform->typbyval;
   15208          753 :     attTup->attalign = tform->typalign;
   15209          753 :     attTup->attstorage = tform->typstorage;
   15210          753 :     attTup->attcompression = InvalidCompressionMethod;
   15211              : 
   15212          753 :     ReleaseSysCache(typeTuple);
   15213              : 
   15214          753 :     CatalogTupleUpdate(attrelation, &heapTup->t_self, heapTup);
   15215              : 
   15216          753 :     table_close(attrelation, RowExclusiveLock);
   15217              : 
   15218              :     /* Install dependencies on new datatype and collation */
   15219          753 :     add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
   15220          753 :     add_column_collation_dependency(RelationGetRelid(rel), attnum, targetcollid);
   15221              : 
   15222              :     /*
   15223              :      * Drop any pg_statistic entry for the column, since it's now wrong type
   15224              :      */
   15225          753 :     RemoveStatistics(RelationGetRelid(rel), attnum);
   15226              : 
   15227          753 :     InvokeObjectPostAlterHook(RelationRelationId,
   15228              :                               RelationGetRelid(rel), attnum);
   15229              : 
   15230              :     /*
   15231              :      * Update the default, if present, by brute force --- remove and re-add
   15232              :      * the default.  Probably unsafe to take shortcuts, since the new version
   15233              :      * may well have additional dependencies.  (It's okay to do this now,
   15234              :      * rather than after other ALTER TYPE commands, since the default won't
   15235              :      * depend on other column types.)
   15236              :      */
   15237          753 :     if (defaultexpr)
   15238              :     {
   15239              :         /*
   15240              :          * If it's a GENERATED default, drop its dependency records, in
   15241              :          * particular its INTERNAL dependency on the column, which would
   15242              :          * otherwise cause dependency.c to refuse to perform the deletion.
   15243              :          */
   15244           56 :         if (attTup->attgenerated)
   15245              :         {
   15246           24 :             Oid         attrdefoid = GetAttrDefaultOid(RelationGetRelid(rel), attnum);
   15247              : 
   15248           24 :             if (!OidIsValid(attrdefoid))
   15249            0 :                 elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
   15250              :                      RelationGetRelid(rel), attnum);
   15251           24 :             (void) deleteDependencyRecordsFor(AttrDefaultRelationId, attrdefoid, false);
   15252              :         }
   15253              : 
   15254              :         /*
   15255              :          * Make updates-so-far visible, particularly the new pg_attribute row
   15256              :          * which will be updated again.
   15257              :          */
   15258           56 :         CommandCounterIncrement();
   15259              : 
   15260              :         /*
   15261              :          * We use RESTRICT here for safety, but at present we do not expect
   15262              :          * anything to depend on the default.
   15263              :          */
   15264           56 :         RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true,
   15265              :                           true);
   15266              : 
   15267           56 :         (void) StoreAttrDefault(rel, attnum, defaultexpr, true);
   15268              :     }
   15269              : 
   15270          753 :     ObjectAddressSubSet(address, RelationRelationId,
   15271              :                         RelationGetRelid(rel), attnum);
   15272              : 
   15273              :     /* Cleanup */
   15274          753 :     heap_freetuple(heapTup);
   15275              : 
   15276          753 :     return address;
   15277              : }
   15278              : 
   15279              : /*
   15280              :  * Subroutine for ATExecAlterColumnType and ATExecSetExpression: Find everything
   15281              :  * that depends on the column (constraints, indexes, etc), and record enough
   15282              :  * information to let us recreate the objects.
   15283              :  */
   15284              : static void
   15285          918 : RememberAllDependentForRebuilding(AlteredTableInfo *tab, AlterTableType subtype,
   15286              :                                   Relation rel, AttrNumber attnum, const char *colName)
   15287              : {
   15288              :     Relation    depRel;
   15289              :     ScanKeyData key[3];
   15290              :     SysScanDesc scan;
   15291              :     HeapTuple   depTup;
   15292              : 
   15293              :     Assert(subtype == AT_AlterColumnType || subtype == AT_SetExpression);
   15294              : 
   15295          918 :     depRel = table_open(DependRelationId, RowExclusiveLock);
   15296              : 
   15297          918 :     ScanKeyInit(&key[0],
   15298              :                 Anum_pg_depend_refclassid,
   15299              :                 BTEqualStrategyNumber, F_OIDEQ,
   15300              :                 ObjectIdGetDatum(RelationRelationId));
   15301          918 :     ScanKeyInit(&key[1],
   15302              :                 Anum_pg_depend_refobjid,
   15303              :                 BTEqualStrategyNumber, F_OIDEQ,
   15304              :                 ObjectIdGetDatum(RelationGetRelid(rel)));
   15305          918 :     ScanKeyInit(&key[2],
   15306              :                 Anum_pg_depend_refobjsubid,
   15307              :                 BTEqualStrategyNumber, F_INT4EQ,
   15308              :                 Int32GetDatum((int32) attnum));
   15309              : 
   15310          918 :     scan = systable_beginscan(depRel, DependReferenceIndexId, true,
   15311              :                               NULL, 3, key);
   15312              : 
   15313         1861 :     while (HeapTupleIsValid(depTup = systable_getnext(scan)))
   15314              :     {
   15315          967 :         Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
   15316              :         ObjectAddress foundObject;
   15317              : 
   15318          967 :         foundObject.classId = foundDep->classid;
   15319          967 :         foundObject.objectId = foundDep->objid;
   15320          967 :         foundObject.objectSubId = foundDep->objsubid;
   15321              : 
   15322          967 :         switch (foundObject.classId)
   15323              :         {
   15324          193 :             case RelationRelationId:
   15325              :                 {
   15326          193 :                     char        relKind = get_rel_relkind(foundObject.objectId);
   15327              : 
   15328          193 :                     if (relKind == RELKIND_INDEX ||
   15329              :                         relKind == RELKIND_PARTITIONED_INDEX)
   15330              :                     {
   15331              :                         Assert(foundObject.objectSubId == 0);
   15332          168 :                         RememberIndexForRebuilding(foundObject.objectId, tab);
   15333              :                     }
   15334           25 :                     else if (relKind == RELKIND_SEQUENCE)
   15335              :                     {
   15336              :                         /*
   15337              :                          * This must be a SERIAL column's sequence.  We need
   15338              :                          * not do anything to it.
   15339              :                          */
   15340              :                         Assert(foundObject.objectSubId == 0);
   15341              :                     }
   15342              :                     else
   15343              :                     {
   15344              :                         /* Not expecting any other direct dependencies... */
   15345            0 :                         elog(ERROR, "unexpected object depending on column: %s",
   15346              :                              getObjectDescription(&foundObject, false));
   15347              :                     }
   15348          193 :                     break;
   15349              :                 }
   15350              : 
   15351          500 :             case ConstraintRelationId:
   15352              :                 Assert(foundObject.objectSubId == 0);
   15353          500 :                 RememberConstraintForRebuilding(foundObject.objectId, tab);
   15354          500 :                 break;
   15355              : 
   15356            0 :             case ProcedureRelationId:
   15357              : 
   15358              :                 /*
   15359              :                  * A new-style SQL function can depend on a column, if that
   15360              :                  * column is referenced in the parsed function body.  Ideally
   15361              :                  * we'd automatically update the function by deparsing and
   15362              :                  * reparsing it, but that's risky and might well fail anyhow.
   15363              :                  * FIXME someday.
   15364              :                  *
   15365              :                  * This is only a problem for AT_AlterColumnType, not
   15366              :                  * AT_SetExpression.
   15367              :                  */
   15368            0 :                 if (subtype == AT_AlterColumnType)
   15369            0 :                     ereport(ERROR,
   15370              :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   15371              :                              errmsg("cannot alter type of a column used by a function or procedure"),
   15372              :                              errdetail("%s depends on column \"%s\"",
   15373              :                                        getObjectDescription(&foundObject, false),
   15374              :                                        colName)));
   15375            0 :                 break;
   15376              : 
   15377            8 :             case RewriteRelationId:
   15378              : 
   15379              :                 /*
   15380              :                  * View/rule bodies have pretty much the same issues as
   15381              :                  * function bodies.  FIXME someday.
   15382              :                  */
   15383            8 :                 if (subtype == AT_AlterColumnType)
   15384            8 :                     ereport(ERROR,
   15385              :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   15386              :                              errmsg("cannot alter type of a column used by a view or rule"),
   15387              :                              errdetail("%s depends on column \"%s\"",
   15388              :                                        getObjectDescription(&foundObject, false),
   15389              :                                        colName)));
   15390            0 :                 break;
   15391              : 
   15392            0 :             case TriggerRelationId:
   15393              : 
   15394              :                 /*
   15395              :                  * A trigger can depend on a column because the column is
   15396              :                  * specified as an update target, or because the column is
   15397              :                  * used in the trigger's WHEN condition.  The first case would
   15398              :                  * not require any extra work, but the second case would
   15399              :                  * require updating the WHEN expression, which has the same
   15400              :                  * issues as above.  Since we can't easily tell which case
   15401              :                  * applies, we punt for both.  FIXME someday.
   15402              :                  */
   15403            0 :                 if (subtype == AT_AlterColumnType)
   15404            0 :                     ereport(ERROR,
   15405              :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   15406              :                              errmsg("cannot alter type of a column used in a trigger definition"),
   15407              :                              errdetail("%s depends on column \"%s\"",
   15408              :                                        getObjectDescription(&foundObject, false),
   15409              :                                        colName)));
   15410            0 :                 break;
   15411              : 
   15412            0 :             case PolicyRelationId:
   15413              : 
   15414              :                 /*
   15415              :                  * A policy can depend on a column because the column is
   15416              :                  * specified in the policy's USING or WITH CHECK qual
   15417              :                  * expressions.  It might be possible to rewrite and recheck
   15418              :                  * the policy expression, but punt for now.  It's certainly
   15419              :                  * easy enough to remove and recreate the policy; still, FIXME
   15420              :                  * someday.
   15421              :                  */
   15422            0 :                 if (subtype == AT_AlterColumnType)
   15423            0 :                     ereport(ERROR,
   15424              :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   15425              :                              errmsg("cannot alter type of a column used in a policy definition"),
   15426              :                              errdetail("%s depends on column \"%s\"",
   15427              :                                        getObjectDescription(&foundObject, false),
   15428              :                                        colName)));
   15429            0 :                 break;
   15430              : 
   15431          213 :             case AttrDefaultRelationId:
   15432              :                 {
   15433          213 :                     ObjectAddress col = GetAttrDefaultColumnAddress(foundObject.objectId);
   15434              : 
   15435          410 :                     if (col.objectId == RelationGetRelid(rel) &&
   15436          213 :                         col.objectSubId == attnum)
   15437              :                     {
   15438              :                         /*
   15439              :                          * Ignore the column's own default expression.  The
   15440              :                          * caller deals with it.
   15441              :                          */
   15442              :                     }
   15443              :                     else
   15444              :                     {
   15445              :                         /*
   15446              :                          * This must be a reference from the expression of a
   15447              :                          * generated column elsewhere in the same table.
   15448              :                          * Changing the type/generated expression of a column
   15449              :                          * that is used by a generated column is not allowed
   15450              :                          * by SQL standard, so just punt for now.  It might be
   15451              :                          * doable with some thinking and effort.
   15452              :                          */
   15453           16 :                         if (subtype == AT_AlterColumnType)
   15454           16 :                             ereport(ERROR,
   15455              :                                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   15456              :                                      errmsg("cannot alter type of a column used by a generated column"),
   15457              :                                      errdetail("Column \"%s\" is used by generated column \"%s\".",
   15458              :                                                colName,
   15459              :                                                get_attname(col.objectId,
   15460              :                                                            col.objectSubId,
   15461              :                                                            false))));
   15462              :                     }
   15463          197 :                     break;
   15464              :                 }
   15465              : 
   15466           53 :             case StatisticExtRelationId:
   15467              : 
   15468              :                 /*
   15469              :                  * Give the extended-stats machinery a chance to fix anything
   15470              :                  * that this column type change would break.
   15471              :                  */
   15472           53 :                 RememberStatisticsForRebuilding(foundObject.objectId, tab);
   15473           53 :                 break;
   15474              : 
   15475            0 :             case PublicationRelRelationId:
   15476              : 
   15477              :                 /*
   15478              :                  * Column reference in a PUBLICATION ... FOR TABLE ... WHERE
   15479              :                  * clause.  Same issues as above.  FIXME someday.
   15480              :                  */
   15481            0 :                 if (subtype == AT_AlterColumnType)
   15482            0 :                     ereport(ERROR,
   15483              :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   15484              :                              errmsg("cannot alter type of a column used by a publication WHERE clause"),
   15485              :                              errdetail("%s depends on column \"%s\"",
   15486              :                                        getObjectDescription(&foundObject, false),
   15487              :                                        colName)));
   15488            0 :                 break;
   15489              : 
   15490            0 :             default:
   15491              : 
   15492              :                 /*
   15493              :                  * We don't expect any other sorts of objects to depend on a
   15494              :                  * column.
   15495              :                  */
   15496            0 :                 elog(ERROR, "unexpected object depending on column: %s",
   15497              :                      getObjectDescription(&foundObject, false));
   15498              :                 break;
   15499              :         }
   15500              :     }
   15501              : 
   15502          894 :     systable_endscan(scan);
   15503          894 :     table_close(depRel, NoLock);
   15504          894 : }
   15505              : 
   15506              : /*
   15507              :  * Subroutine for ATExecAlterColumnType: remember that a replica identity
   15508              :  * needs to be reset.
   15509              :  */
   15510              : static void
   15511          307 : RememberReplicaIdentityForRebuilding(Oid indoid, AlteredTableInfo *tab)
   15512              : {
   15513          307 :     if (!get_index_isreplident(indoid))
   15514          295 :         return;
   15515              : 
   15516           12 :     if (tab->replicaIdentityIndex)
   15517            0 :         elog(ERROR, "relation %u has multiple indexes marked as replica identity", tab->relid);
   15518              : 
   15519           12 :     tab->replicaIdentityIndex = get_rel_name(indoid);
   15520              : }
   15521              : 
   15522              : /*
   15523              :  * Subroutine for ATExecAlterColumnType: remember any clustered index.
   15524              :  */
   15525              : static void
   15526          307 : RememberClusterOnForRebuilding(Oid indoid, AlteredTableInfo *tab)
   15527              : {
   15528          307 :     if (!get_index_isclustered(indoid))
   15529          295 :         return;
   15530              : 
   15531           12 :     if (tab->clusterOnIndex)
   15532            0 :         elog(ERROR, "relation %u has multiple clustered indexes", tab->relid);
   15533              : 
   15534           12 :     tab->clusterOnIndex = get_rel_name(indoid);
   15535              : }
   15536              : 
   15537              : /*
   15538              :  * Subroutine for ATExecAlterColumnType: remember that a constraint needs
   15539              :  * to be rebuilt (which we might already know).
   15540              :  */
   15541              : static void
   15542          508 : RememberConstraintForRebuilding(Oid conoid, AlteredTableInfo *tab)
   15543              : {
   15544              :     /*
   15545              :      * This de-duplication check is critical for two independent reasons: we
   15546              :      * mustn't try to recreate the same constraint twice, and if a constraint
   15547              :      * depends on more than one column whose type is to be altered, we must
   15548              :      * capture its definition string before applying any of the column type
   15549              :      * changes.  ruleutils.c will get confused if we ask again later.
   15550              :      */
   15551          508 :     if (!list_member_oid(tab->changedConstraintOids, conoid))
   15552              :     {
   15553              :         /* OK, capture the constraint's existing definition string */
   15554          436 :         char       *defstring = pg_get_constraintdef_command(conoid);
   15555              :         Oid         indoid;
   15556              : 
   15557              :         /*
   15558              :          * It is critical to create not-null constraints ahead of primary key
   15559              :          * indexes; otherwise, the not-null constraint would be created by the
   15560              :          * primary key, and the constraint name would be wrong.
   15561              :          */
   15562          436 :         if (get_constraint_type(conoid) == CONSTRAINT_NOTNULL)
   15563              :         {
   15564          147 :             tab->changedConstraintOids = lcons_oid(conoid,
   15565              :                                                    tab->changedConstraintOids);
   15566          147 :             tab->changedConstraintDefs = lcons(defstring,
   15567              :                                                tab->changedConstraintDefs);
   15568              :         }
   15569              :         else
   15570              :         {
   15571              : 
   15572          289 :             tab->changedConstraintOids = lappend_oid(tab->changedConstraintOids,
   15573              :                                                      conoid);
   15574          289 :             tab->changedConstraintDefs = lappend(tab->changedConstraintDefs,
   15575              :                                                  defstring);
   15576              :         }
   15577              : 
   15578              :         /*
   15579              :          * For the index of a constraint, if any, remember if it is used for
   15580              :          * the table's replica identity or if it is a clustered index, so that
   15581              :          * ATPostAlterTypeCleanup() can queue up commands necessary to restore
   15582              :          * those properties.
   15583              :          */
   15584          436 :         indoid = get_constraint_index(conoid);
   15585          436 :         if (OidIsValid(indoid))
   15586              :         {
   15587          152 :             RememberReplicaIdentityForRebuilding(indoid, tab);
   15588          152 :             RememberClusterOnForRebuilding(indoid, tab);
   15589              :         }
   15590              :     }
   15591          508 : }
   15592              : 
   15593              : /*
   15594              :  * Subroutine for ATExecAlterColumnType: remember that an index needs
   15595              :  * to be rebuilt (which we might already know).
   15596              :  */
   15597              : static void
   15598          168 : RememberIndexForRebuilding(Oid indoid, AlteredTableInfo *tab)
   15599              : {
   15600              :     /*
   15601              :      * This de-duplication check is critical for two independent reasons: we
   15602              :      * mustn't try to recreate the same index twice, and if an index depends
   15603              :      * on more than one column whose type is to be altered, we must capture
   15604              :      * its definition string before applying any of the column type changes.
   15605              :      * ruleutils.c will get confused if we ask again later.
   15606              :      */
   15607          168 :     if (!list_member_oid(tab->changedIndexOids, indoid))
   15608              :     {
   15609              :         /*
   15610              :          * Before adding it as an index-to-rebuild, we'd better see if it
   15611              :          * belongs to a constraint, and if so rebuild the constraint instead.
   15612              :          * Typically this check fails, because constraint indexes normally
   15613              :          * have only dependencies on their constraint.  But it's possible for
   15614              :          * such an index to also have direct dependencies on table columns,
   15615              :          * for example with a partial exclusion constraint.
   15616              :          */
   15617          163 :         Oid         conoid = get_index_constraint(indoid);
   15618              : 
   15619          163 :         if (OidIsValid(conoid))
   15620              :         {
   15621            8 :             RememberConstraintForRebuilding(conoid, tab);
   15622              :         }
   15623              :         else
   15624              :         {
   15625              :             /* OK, capture the index's existing definition string */
   15626          155 :             char       *defstring = pg_get_indexdef_string(indoid);
   15627              : 
   15628          155 :             tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
   15629              :                                                 indoid);
   15630          155 :             tab->changedIndexDefs = lappend(tab->changedIndexDefs,
   15631              :                                             defstring);
   15632              : 
   15633              :             /*
   15634              :              * Remember if this index is used for the table's replica identity
   15635              :              * or if it is a clustered index, so that ATPostAlterTypeCleanup()
   15636              :              * can queue up commands necessary to restore those properties.
   15637              :              */
   15638          155 :             RememberReplicaIdentityForRebuilding(indoid, tab);
   15639          155 :             RememberClusterOnForRebuilding(indoid, tab);
   15640              :         }
   15641              :     }
   15642          168 : }
   15643              : 
   15644              : /*
   15645              :  * Subroutine for ATExecAlterColumnType: remember that a statistics object
   15646              :  * needs to be rebuilt (which we might already know).
   15647              :  */
   15648              : static void
   15649           53 : RememberStatisticsForRebuilding(Oid stxoid, AlteredTableInfo *tab)
   15650              : {
   15651              :     /*
   15652              :      * This de-duplication check is critical for two independent reasons: we
   15653              :      * mustn't try to recreate the same statistics object twice, and if the
   15654              :      * statistics object depends on more than one column whose type is to be
   15655              :      * altered, we must capture its definition string before applying any of
   15656              :      * the type changes. ruleutils.c will get confused if we ask again later.
   15657              :      */
   15658           53 :     if (!list_member_oid(tab->changedStatisticsOids, stxoid))
   15659              :     {
   15660              :         /* OK, capture the statistics object's existing definition string */
   15661           53 :         char       *defstring = pg_get_statisticsobjdef_string(stxoid);
   15662              : 
   15663           53 :         tab->changedStatisticsOids = lappend_oid(tab->changedStatisticsOids,
   15664              :                                                  stxoid);
   15665           53 :         tab->changedStatisticsDefs = lappend(tab->changedStatisticsDefs,
   15666              :                                              defstring);
   15667              :     }
   15668           53 : }
   15669              : 
   15670              : /*
   15671              :  * Cleanup after we've finished all the ALTER TYPE or SET EXPRESSION
   15672              :  * operations for a particular relation.  We have to drop and recreate all the
   15673              :  * indexes and constraints that depend on the altered columns.  We do the
   15674              :  * actual dropping here, but re-creation is managed by adding work queue
   15675              :  * entries to do those steps later.
   15676              :  */
   15677              : static void
   15678          866 : ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab, LOCKMODE lockmode)
   15679              : {
   15680              :     ObjectAddress obj;
   15681              :     ObjectAddresses *objects;
   15682              :     ListCell   *def_item;
   15683              :     ListCell   *oid_item;
   15684              : 
   15685              :     /*
   15686              :      * Collect all the constraints and indexes to drop so we can process them
   15687              :      * in a single call.  That way we don't have to worry about dependencies
   15688              :      * among them.
   15689              :      */
   15690          866 :     objects = new_object_addresses();
   15691              : 
   15692              :     /*
   15693              :      * Re-parse the index and constraint definitions, and attach them to the
   15694              :      * appropriate work queue entries.  We do this before dropping because in
   15695              :      * the case of a constraint on another table, we might not yet have
   15696              :      * exclusive lock on the table the constraint is attached to, and we need
   15697              :      * to get that before reparsing/dropping.  (That's possible at least for
   15698              :      * FOREIGN KEY, CHECK, and EXCLUSION constraints; in non-FK cases it
   15699              :      * requires a dependency on the target table's composite type in the other
   15700              :      * table's constraint expressions.)
   15701              :      *
   15702              :      * We can't rely on the output of deparsing to tell us which relation to
   15703              :      * operate on, because concurrent activity might have made the name
   15704              :      * resolve differently.  Instead, we've got to use the OID of the
   15705              :      * constraint or index we're processing to figure out which relation to
   15706              :      * operate on.
   15707              :      */
   15708         1302 :     forboth(oid_item, tab->changedConstraintOids,
   15709              :             def_item, tab->changedConstraintDefs)
   15710              :     {
   15711          436 :         Oid         oldId = lfirst_oid(oid_item);
   15712              :         HeapTuple   tup;
   15713              :         Form_pg_constraint con;
   15714              :         Oid         relid;
   15715              :         Oid         confrelid;
   15716              :         bool        conislocal;
   15717              : 
   15718          436 :         tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(oldId));
   15719          436 :         if (!HeapTupleIsValid(tup)) /* should not happen */
   15720            0 :             elog(ERROR, "cache lookup failed for constraint %u", oldId);
   15721          436 :         con = (Form_pg_constraint) GETSTRUCT(tup);
   15722          436 :         if (OidIsValid(con->conrelid))
   15723          427 :             relid = con->conrelid;
   15724              :         else
   15725              :         {
   15726              :             /* must be a domain constraint */
   15727            9 :             relid = get_typ_typrelid(getBaseType(con->contypid));
   15728            9 :             if (!OidIsValid(relid))
   15729            0 :                 elog(ERROR, "could not identify relation associated with constraint %u", oldId);
   15730              :         }
   15731          436 :         confrelid = con->confrelid;
   15732          436 :         conislocal = con->conislocal;
   15733          436 :         ReleaseSysCache(tup);
   15734              : 
   15735          436 :         ObjectAddressSet(obj, ConstraintRelationId, oldId);
   15736          436 :         add_exact_object_address(&obj, objects);
   15737              : 
   15738              :         /*
   15739              :          * If the constraint is inherited (only), we don't want to inject a
   15740              :          * new definition here; it'll get recreated when
   15741              :          * ATAddCheckNNConstraint recurses from adding the parent table's
   15742              :          * constraint.  But we had to carry the info this far so that we can
   15743              :          * drop the constraint below.
   15744              :          */
   15745          436 :         if (!conislocal)
   15746           26 :             continue;
   15747              : 
   15748              :         /*
   15749              :          * When rebuilding another table's constraint that references the
   15750              :          * table we're modifying, we might not yet have any lock on the other
   15751              :          * table, so get one now.  We'll need AccessExclusiveLock for the DROP
   15752              :          * CONSTRAINT step, so there's no value in asking for anything weaker.
   15753              :          */
   15754          410 :         if (relid != tab->relid)
   15755           36 :             LockRelationOid(relid, AccessExclusiveLock);
   15756              : 
   15757          410 :         ATPostAlterTypeParse(oldId, relid, confrelid,
   15758          410 :                              (char *) lfirst(def_item),
   15759          410 :                              wqueue, lockmode, tab->rewrite);
   15760              :     }
   15761         1021 :     forboth(oid_item, tab->changedIndexOids,
   15762              :             def_item, tab->changedIndexDefs)
   15763              :     {
   15764          155 :         Oid         oldId = lfirst_oid(oid_item);
   15765              :         Oid         relid;
   15766              : 
   15767          155 :         relid = IndexGetRelation(oldId, false);
   15768              : 
   15769              :         /*
   15770              :          * As above, make sure we have lock on the index's table if it's not
   15771              :          * the same table.
   15772              :          */
   15773          155 :         if (relid != tab->relid)
   15774           12 :             LockRelationOid(relid, AccessExclusiveLock);
   15775              : 
   15776          155 :         ATPostAlterTypeParse(oldId, relid, InvalidOid,
   15777          155 :                              (char *) lfirst(def_item),
   15778          155 :                              wqueue, lockmode, tab->rewrite);
   15779              : 
   15780          155 :         ObjectAddressSet(obj, RelationRelationId, oldId);
   15781          155 :         add_exact_object_address(&obj, objects);
   15782              :     }
   15783              : 
   15784              :     /* add dependencies for new statistics */
   15785          919 :     forboth(oid_item, tab->changedStatisticsOids,
   15786              :             def_item, tab->changedStatisticsDefs)
   15787              :     {
   15788           53 :         Oid         oldId = lfirst_oid(oid_item);
   15789              :         Oid         relid;
   15790              : 
   15791           53 :         relid = StatisticsGetRelation(oldId, false);
   15792              : 
   15793              :         /*
   15794              :          * As above, make sure we have lock on the statistics object's table
   15795              :          * if it's not the same table.  However, we take
   15796              :          * ShareUpdateExclusiveLock here, aligning with the lock level used in
   15797              :          * CreateStatistics and RemoveStatisticsById.
   15798              :          *
   15799              :          * CAUTION: this should be done after all cases that grab
   15800              :          * AccessExclusiveLock, else we risk causing deadlock due to needing
   15801              :          * to promote our table lock.
   15802              :          */
   15803           53 :         if (relid != tab->relid)
   15804           12 :             LockRelationOid(relid, ShareUpdateExclusiveLock);
   15805              : 
   15806           53 :         ATPostAlterTypeParse(oldId, relid, InvalidOid,
   15807           53 :                              (char *) lfirst(def_item),
   15808           53 :                              wqueue, lockmode, tab->rewrite);
   15809              : 
   15810           53 :         ObjectAddressSet(obj, StatisticExtRelationId, oldId);
   15811           53 :         add_exact_object_address(&obj, objects);
   15812              :     }
   15813              : 
   15814              :     /*
   15815              :      * Queue up command to restore replica identity index marking
   15816              :      */
   15817          866 :     if (tab->replicaIdentityIndex)
   15818              :     {
   15819           12 :         AlterTableCmd *cmd = makeNode(AlterTableCmd);
   15820           12 :         ReplicaIdentityStmt *subcmd = makeNode(ReplicaIdentityStmt);
   15821              : 
   15822           12 :         subcmd->identity_type = REPLICA_IDENTITY_INDEX;
   15823           12 :         subcmd->name = tab->replicaIdentityIndex;
   15824           12 :         cmd->subtype = AT_ReplicaIdentity;
   15825           12 :         cmd->def = (Node *) subcmd;
   15826              : 
   15827              :         /* do it after indexes and constraints */
   15828           12 :         tab->subcmds[AT_PASS_OLD_CONSTR] =
   15829           12 :             lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
   15830              :     }
   15831              : 
   15832              :     /*
   15833              :      * Queue up command to restore marking of index used for cluster.
   15834              :      */
   15835          866 :     if (tab->clusterOnIndex)
   15836              :     {
   15837           12 :         AlterTableCmd *cmd = makeNode(AlterTableCmd);
   15838              : 
   15839           12 :         cmd->subtype = AT_ClusterOn;
   15840           12 :         cmd->name = tab->clusterOnIndex;
   15841              : 
   15842              :         /* do it after indexes and constraints */
   15843           12 :         tab->subcmds[AT_PASS_OLD_CONSTR] =
   15844           12 :             lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
   15845              :     }
   15846              : 
   15847              :     /*
   15848              :      * It should be okay to use DROP_RESTRICT here, since nothing else should
   15849              :      * be depending on these objects.
   15850              :      */
   15851          866 :     performMultipleDeletions(objects, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
   15852              : 
   15853          866 :     free_object_addresses(objects);
   15854              : 
   15855              :     /*
   15856              :      * The objects will get recreated during subsequent passes over the work
   15857              :      * queue.
   15858              :      */
   15859          866 : }
   15860              : 
   15861              : /*
   15862              :  * Parse the previously-saved definition string for a constraint, index or
   15863              :  * statistics object against the newly-established column data type(s), and
   15864              :  * queue up the resulting command parsetrees for execution.
   15865              :  *
   15866              :  * This might fail if, for example, you have a WHERE clause that uses an
   15867              :  * operator that's not available for the new column type.
   15868              :  */
   15869              : static void
   15870          618 : ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
   15871              :                      List **wqueue, LOCKMODE lockmode, bool rewrite)
   15872              : {
   15873              :     List       *raw_parsetree_list;
   15874              :     List       *querytree_list;
   15875              :     ListCell   *list_item;
   15876              :     Relation    rel;
   15877              : 
   15878              :     /*
   15879              :      * We expect that we will get only ALTER TABLE and CREATE INDEX
   15880              :      * statements. Hence, there is no need to pass them through
   15881              :      * parse_analyze_*() or the rewriter, but instead we need to pass them
   15882              :      * through parse_utilcmd.c to make them ready for execution.
   15883              :      */
   15884          618 :     raw_parsetree_list = raw_parser(cmd, RAW_PARSE_DEFAULT);
   15885          618 :     querytree_list = NIL;
   15886         1236 :     foreach(list_item, raw_parsetree_list)
   15887              :     {
   15888          618 :         RawStmt    *rs = lfirst_node(RawStmt, list_item);
   15889          618 :         Node       *stmt = rs->stmt;
   15890              : 
   15891          618 :         if (IsA(stmt, IndexStmt))
   15892          155 :             querytree_list = lappend(querytree_list,
   15893          155 :                                      transformIndexStmt(oldRelId,
   15894              :                                                         (IndexStmt *) stmt,
   15895              :                                                         cmd));
   15896          463 :         else if (IsA(stmt, AlterTableStmt))
   15897              :         {
   15898              :             List       *beforeStmts;
   15899              :             List       *afterStmts;
   15900              : 
   15901          401 :             stmt = (Node *) transformAlterTableStmt(oldRelId,
   15902              :                                                     (AlterTableStmt *) stmt,
   15903              :                                                     cmd,
   15904              :                                                     &beforeStmts,
   15905              :                                                     &afterStmts);
   15906          401 :             querytree_list = list_concat(querytree_list, beforeStmts);
   15907          401 :             querytree_list = lappend(querytree_list, stmt);
   15908          401 :             querytree_list = list_concat(querytree_list, afterStmts);
   15909              :         }
   15910           62 :         else if (IsA(stmt, CreateStatsStmt))
   15911           53 :             querytree_list = lappend(querytree_list,
   15912           53 :                                      transformStatsStmt(oldRelId,
   15913              :                                                         (CreateStatsStmt *) stmt,
   15914              :                                                         cmd));
   15915              :         else
   15916            9 :             querytree_list = lappend(querytree_list, stmt);
   15917              :     }
   15918              : 
   15919              :     /* Caller should already have acquired whatever lock we need. */
   15920          618 :     rel = relation_open(oldRelId, NoLock);
   15921              : 
   15922              :     /*
   15923              :      * Attach each generated command to the proper place in the work queue.
   15924              :      * Note this could result in creation of entirely new work-queue entries.
   15925              :      *
   15926              :      * Also note that we have to tweak the command subtypes, because it turns
   15927              :      * out that re-creation of indexes and constraints has to act a bit
   15928              :      * differently from initial creation.
   15929              :      */
   15930         1236 :     foreach(list_item, querytree_list)
   15931              :     {
   15932          618 :         Node       *stm = (Node *) lfirst(list_item);
   15933              :         AlteredTableInfo *tab;
   15934              : 
   15935          618 :         tab = ATGetQueueEntry(wqueue, rel);
   15936              : 
   15937          618 :         if (IsA(stm, IndexStmt))
   15938              :         {
   15939          155 :             IndexStmt  *stmt = (IndexStmt *) stm;
   15940              :             AlterTableCmd *newcmd;
   15941              : 
   15942          155 :             if (!rewrite)
   15943           41 :                 TryReuseIndex(oldId, stmt);
   15944          155 :             stmt->reset_default_tblspc = true;
   15945              :             /* keep the index's comment */
   15946          155 :             stmt->idxcomment = GetComment(oldId, RelationRelationId, 0);
   15947              : 
   15948          155 :             newcmd = makeNode(AlterTableCmd);
   15949          155 :             newcmd->subtype = AT_ReAddIndex;
   15950          155 :             newcmd->def = (Node *) stmt;
   15951          155 :             tab->subcmds[AT_PASS_OLD_INDEX] =
   15952          155 :                 lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
   15953              :         }
   15954          463 :         else if (IsA(stm, AlterTableStmt))
   15955              :         {
   15956          401 :             AlterTableStmt *stmt = (AlterTableStmt *) stm;
   15957              :             ListCell   *lcmd;
   15958              : 
   15959          802 :             foreach(lcmd, stmt->cmds)
   15960              :             {
   15961          401 :                 AlterTableCmd *cmd = lfirst_node(AlterTableCmd, lcmd);
   15962              : 
   15963          401 :                 if (cmd->subtype == AT_AddIndex)
   15964              :                 {
   15965              :                     IndexStmt  *indstmt;
   15966              :                     Oid         indoid;
   15967              : 
   15968          152 :                     indstmt = castNode(IndexStmt, cmd->def);
   15969          152 :                     indoid = get_constraint_index(oldId);
   15970              : 
   15971          152 :                     if (!rewrite)
   15972           32 :                         TryReuseIndex(indoid, indstmt);
   15973              :                     /* keep any comment on the index */
   15974          152 :                     indstmt->idxcomment = GetComment(indoid,
   15975              :                                                      RelationRelationId, 0);
   15976          152 :                     indstmt->reset_default_tblspc = true;
   15977              : 
   15978          152 :                     cmd->subtype = AT_ReAddIndex;
   15979          152 :                     tab->subcmds[AT_PASS_OLD_INDEX] =
   15980          152 :                         lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
   15981              : 
   15982              :                     /* recreate any comment on the constraint */
   15983          152 :                     RebuildConstraintComment(tab,
   15984              :                                              AT_PASS_OLD_INDEX,
   15985              :                                              oldId,
   15986              :                                              rel,
   15987              :                                              NIL,
   15988          152 :                                              indstmt->idxname);
   15989              :                 }
   15990          249 :                 else if (cmd->subtype == AT_AddConstraint)
   15991              :                 {
   15992          249 :                     Constraint *con = castNode(Constraint, cmd->def);
   15993              : 
   15994          249 :                     con->old_pktable_oid = refRelId;
   15995              :                     /* rewriting neither side of a FK */
   15996          249 :                     if (con->contype == CONSTR_FOREIGN &&
   15997           48 :                         !rewrite && tab->rewrite == 0)
   15998            4 :                         TryReuseForeignKey(oldId, con);
   15999          249 :                     con->reset_default_tblspc = true;
   16000          249 :                     cmd->subtype = AT_ReAddConstraint;
   16001          249 :                     tab->subcmds[AT_PASS_OLD_CONSTR] =
   16002          249 :                         lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
   16003              : 
   16004              :                     /*
   16005              :                      * Recreate any comment on the constraint.  If we have
   16006              :                      * recreated a primary key, then transformTableConstraint
   16007              :                      * has added an unnamed not-null constraint here; skip
   16008              :                      * this in that case.
   16009              :                      */
   16010          249 :                     if (con->conname)
   16011          249 :                         RebuildConstraintComment(tab,
   16012              :                                                  AT_PASS_OLD_CONSTR,
   16013              :                                                  oldId,
   16014              :                                                  rel,
   16015              :                                                  NIL,
   16016          249 :                                                  con->conname);
   16017              :                     else
   16018              :                         Assert(con->contype == CONSTR_NOTNULL);
   16019              :                 }
   16020              :                 else
   16021            0 :                     elog(ERROR, "unexpected statement subtype: %d",
   16022              :                          (int) cmd->subtype);
   16023              :             }
   16024              :         }
   16025           62 :         else if (IsA(stm, AlterDomainStmt))
   16026              :         {
   16027            9 :             AlterDomainStmt *stmt = (AlterDomainStmt *) stm;
   16028              : 
   16029            9 :             if (stmt->subtype == AD_AddConstraint)
   16030              :             {
   16031            9 :                 Constraint *con = castNode(Constraint, stmt->def);
   16032            9 :                 AlterTableCmd *cmd = makeNode(AlterTableCmd);
   16033              : 
   16034            9 :                 cmd->subtype = AT_ReAddDomainConstraint;
   16035            9 :                 cmd->def = (Node *) stmt;
   16036            9 :                 tab->subcmds[AT_PASS_OLD_CONSTR] =
   16037            9 :                     lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
   16038              : 
   16039              :                 /* recreate any comment on the constraint */
   16040            9 :                 RebuildConstraintComment(tab,
   16041              :                                          AT_PASS_OLD_CONSTR,
   16042              :                                          oldId,
   16043              :                                          NULL,
   16044              :                                          stmt->typeName,
   16045            9 :                                          con->conname);
   16046              :             }
   16047              :             else
   16048            0 :                 elog(ERROR, "unexpected statement subtype: %d",
   16049              :                      (int) stmt->subtype);
   16050              :         }
   16051           53 :         else if (IsA(stm, CreateStatsStmt))
   16052              :         {
   16053           53 :             CreateStatsStmt *stmt = (CreateStatsStmt *) stm;
   16054              :             AlterTableCmd *newcmd;
   16055              : 
   16056              :             /* keep the statistics object's comment */
   16057           53 :             stmt->stxcomment = GetComment(oldId, StatisticExtRelationId, 0);
   16058              : 
   16059           53 :             newcmd = makeNode(AlterTableCmd);
   16060           53 :             newcmd->subtype = AT_ReAddStatistics;
   16061           53 :             newcmd->def = (Node *) stmt;
   16062           53 :             tab->subcmds[AT_PASS_MISC] =
   16063           53 :                 lappend(tab->subcmds[AT_PASS_MISC], newcmd);
   16064              :         }
   16065              :         else
   16066            0 :             elog(ERROR, "unexpected statement type: %d",
   16067              :                  (int) nodeTag(stm));
   16068              :     }
   16069              : 
   16070          618 :     relation_close(rel, NoLock);
   16071          618 : }
   16072              : 
   16073              : /*
   16074              :  * Subroutine for ATPostAlterTypeParse() to recreate any existing comment
   16075              :  * for a table or domain constraint that is being rebuilt.
   16076              :  *
   16077              :  * objid is the OID of the constraint.
   16078              :  * Pass "rel" for a table constraint, or "domname" (domain's qualified name
   16079              :  * as a string list) for a domain constraint.
   16080              :  * (We could dig that info, as well as the conname, out of the pg_constraint
   16081              :  * entry; but callers already have them so might as well pass them.)
   16082              :  */
   16083              : static void
   16084          410 : RebuildConstraintComment(AlteredTableInfo *tab, AlterTablePass pass, Oid objid,
   16085              :                          Relation rel, List *domname,
   16086              :                          const char *conname)
   16087              : {
   16088              :     CommentStmt *cmd;
   16089              :     char       *comment_str;
   16090              :     AlterTableCmd *newcmd;
   16091              : 
   16092              :     /* Look for comment for object wanted, and leave if none */
   16093          410 :     comment_str = GetComment(objid, ConstraintRelationId, 0);
   16094          410 :     if (comment_str == NULL)
   16095          350 :         return;
   16096              : 
   16097              :     /* Build CommentStmt node, copying all input data for safety */
   16098           60 :     cmd = makeNode(CommentStmt);
   16099           60 :     if (rel)
   16100              :     {
   16101           52 :         cmd->objtype = OBJECT_TABCONSTRAINT;
   16102           52 :         cmd->object = (Node *)
   16103           52 :             list_make3(makeString(get_namespace_name(RelationGetNamespace(rel))),
   16104              :                        makeString(pstrdup(RelationGetRelationName(rel))),
   16105              :                        makeString(pstrdup(conname)));
   16106              :     }
   16107              :     else
   16108              :     {
   16109            8 :         cmd->objtype = OBJECT_DOMCONSTRAINT;
   16110            8 :         cmd->object = (Node *)
   16111            8 :             list_make2(makeTypeNameFromNameList(copyObject(domname)),
   16112              :                        makeString(pstrdup(conname)));
   16113              :     }
   16114           60 :     cmd->comment = comment_str;
   16115              : 
   16116              :     /* Append it to list of commands */
   16117           60 :     newcmd = makeNode(AlterTableCmd);
   16118           60 :     newcmd->subtype = AT_ReAddComment;
   16119           60 :     newcmd->def = (Node *) cmd;
   16120           60 :     tab->subcmds[pass] = lappend(tab->subcmds[pass], newcmd);
   16121              : }
   16122              : 
   16123              : /*
   16124              :  * Subroutine for ATPostAlterTypeParse().  Calls out to CheckIndexCompatible()
   16125              :  * for the real analysis, then mutates the IndexStmt based on that verdict.
   16126              :  */
   16127              : static void
   16128           73 : TryReuseIndex(Oid oldId, IndexStmt *stmt)
   16129              : {
   16130           73 :     if (CheckIndexCompatible(oldId,
   16131           73 :                              stmt->accessMethod,
   16132           73 :                              stmt->indexParams,
   16133           73 :                              stmt->excludeOpNames,
   16134           73 :                              stmt->iswithoutoverlaps))
   16135              :     {
   16136           69 :         Relation    irel = index_open(oldId, NoLock);
   16137              : 
   16138              :         /* If it's a partitioned index, there is no storage to share. */
   16139           69 :         if (irel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
   16140              :         {
   16141           49 :             stmt->oldNumber = irel->rd_locator.relNumber;
   16142           49 :             stmt->oldCreateSubid = irel->rd_createSubid;
   16143           49 :             stmt->oldFirstRelfilelocatorSubid = irel->rd_firstRelfilelocatorSubid;
   16144              :         }
   16145           69 :         index_close(irel, NoLock);
   16146              :     }
   16147           73 : }
   16148              : 
   16149              : /*
   16150              :  * Subroutine for ATPostAlterTypeParse().
   16151              :  *
   16152              :  * Stash the old P-F equality operator into the Constraint node, for possible
   16153              :  * use by ATAddForeignKeyConstraint() in determining whether revalidation of
   16154              :  * this constraint can be skipped.
   16155              :  */
   16156              : static void
   16157            4 : TryReuseForeignKey(Oid oldId, Constraint *con)
   16158              : {
   16159              :     HeapTuple   tup;
   16160              :     Datum       adatum;
   16161              :     ArrayType  *arr;
   16162              :     Oid        *rawarr;
   16163              :     int         numkeys;
   16164              :     int         i;
   16165              : 
   16166              :     Assert(con->contype == CONSTR_FOREIGN);
   16167              :     Assert(con->old_conpfeqop == NIL);   /* already prepared this node */
   16168              : 
   16169            4 :     tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(oldId));
   16170            4 :     if (!HeapTupleIsValid(tup)) /* should not happen */
   16171            0 :         elog(ERROR, "cache lookup failed for constraint %u", oldId);
   16172              : 
   16173            4 :     adatum = SysCacheGetAttrNotNull(CONSTROID, tup,
   16174              :                                     Anum_pg_constraint_conpfeqop);
   16175            4 :     arr = DatumGetArrayTypeP(adatum);   /* ensure not toasted */
   16176            4 :     numkeys = ARR_DIMS(arr)[0];
   16177              :     /* test follows the one in ri_FetchConstraintInfo() */
   16178            4 :     if (ARR_NDIM(arr) != 1 ||
   16179            4 :         ARR_HASNULL(arr) ||
   16180            4 :         ARR_ELEMTYPE(arr) != OIDOID)
   16181            0 :         elog(ERROR, "conpfeqop is not a 1-D Oid array");
   16182            4 :     rawarr = (Oid *) ARR_DATA_PTR(arr);
   16183              : 
   16184              :     /* stash a List of the operator Oids in our Constraint node */
   16185            8 :     for (i = 0; i < numkeys; i++)
   16186            4 :         con->old_conpfeqop = lappend_oid(con->old_conpfeqop, rawarr[i]);
   16187              : 
   16188            4 :     ReleaseSysCache(tup);
   16189            4 : }
   16190              : 
   16191              : /*
   16192              :  * ALTER COLUMN .. OPTIONS ( ... )
   16193              :  *
   16194              :  * Returns the address of the modified column
   16195              :  */
   16196              : static ObjectAddress
   16197           93 : ATExecAlterColumnGenericOptions(Relation rel,
   16198              :                                 const char *colName,
   16199              :                                 List *options,
   16200              :                                 LOCKMODE lockmode)
   16201              : {
   16202              :     Relation    ftrel;
   16203              :     Relation    attrel;
   16204              :     ForeignServer *server;
   16205              :     ForeignDataWrapper *fdw;
   16206              :     HeapTuple   tuple;
   16207              :     HeapTuple   newtuple;
   16208              :     bool        isnull;
   16209              :     Datum       repl_val[Natts_pg_attribute];
   16210              :     bool        repl_null[Natts_pg_attribute];
   16211              :     bool        repl_repl[Natts_pg_attribute];
   16212              :     Datum       datum;
   16213              :     Form_pg_foreign_table fttableform;
   16214              :     Form_pg_attribute atttableform;
   16215              :     AttrNumber  attnum;
   16216              :     ObjectAddress address;
   16217              : 
   16218           93 :     if (options == NIL)
   16219            0 :         return InvalidObjectAddress;
   16220              : 
   16221              :     /* First, determine FDW validator associated to the foreign table. */
   16222           93 :     ftrel = table_open(ForeignTableRelationId, AccessShareLock);
   16223           93 :     tuple = SearchSysCache1(FOREIGNTABLEREL, ObjectIdGetDatum(rel->rd_id));
   16224           93 :     if (!HeapTupleIsValid(tuple))
   16225            0 :         ereport(ERROR,
   16226              :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
   16227              :                  errmsg("foreign table \"%s\" does not exist",
   16228              :                         RelationGetRelationName(rel))));
   16229           93 :     fttableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
   16230           93 :     server = GetForeignServer(fttableform->ftserver);
   16231           93 :     fdw = GetForeignDataWrapper(server->fdwid);
   16232              : 
   16233           93 :     table_close(ftrel, AccessShareLock);
   16234           93 :     ReleaseSysCache(tuple);
   16235              : 
   16236           93 :     attrel = table_open(AttributeRelationId, RowExclusiveLock);
   16237           93 :     tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
   16238           93 :     if (!HeapTupleIsValid(tuple))
   16239            0 :         ereport(ERROR,
   16240              :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
   16241              :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
   16242              :                         colName, RelationGetRelationName(rel))));
   16243              : 
   16244              :     /* Prevent them from altering a system attribute */
   16245           93 :     atttableform = (Form_pg_attribute) GETSTRUCT(tuple);
   16246           93 :     attnum = atttableform->attnum;
   16247           93 :     if (attnum <= 0)
   16248            4 :         ereport(ERROR,
   16249              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   16250              :                  errmsg("cannot alter system column \"%s\"", colName)));
   16251              : 
   16252              : 
   16253              :     /* Initialize buffers for new tuple values */
   16254           89 :     memset(repl_val, 0, sizeof(repl_val));
   16255           89 :     memset(repl_null, false, sizeof(repl_null));
   16256           89 :     memset(repl_repl, false, sizeof(repl_repl));
   16257              : 
   16258              :     /* Extract the current options */
   16259           89 :     datum = SysCacheGetAttr(ATTNAME,
   16260              :                             tuple,
   16261              :                             Anum_pg_attribute_attfdwoptions,
   16262              :                             &isnull);
   16263           89 :     if (isnull)
   16264           83 :         datum = PointerGetDatum(NULL);
   16265              : 
   16266              :     /* Transform the options */
   16267           89 :     datum = transformGenericOptions(AttributeRelationId,
   16268              :                                     datum,
   16269              :                                     options,
   16270              :                                     fdw->fdwvalidator);
   16271              : 
   16272           89 :     if (DatumGetPointer(datum) != NULL)
   16273           89 :         repl_val[Anum_pg_attribute_attfdwoptions - 1] = datum;
   16274              :     else
   16275            0 :         repl_null[Anum_pg_attribute_attfdwoptions - 1] = true;
   16276              : 
   16277           89 :     repl_repl[Anum_pg_attribute_attfdwoptions - 1] = true;
   16278              : 
   16279              :     /* Everything looks good - update the tuple */
   16280              : 
   16281           89 :     newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrel),
   16282              :                                  repl_val, repl_null, repl_repl);
   16283              : 
   16284           89 :     CatalogTupleUpdate(attrel, &newtuple->t_self, newtuple);
   16285              : 
   16286           89 :     InvokeObjectPostAlterHook(RelationRelationId,
   16287              :                               RelationGetRelid(rel),
   16288              :                               atttableform->attnum);
   16289           89 :     ObjectAddressSubSet(address, RelationRelationId,
   16290              :                         RelationGetRelid(rel), attnum);
   16291              : 
   16292           89 :     ReleaseSysCache(tuple);
   16293              : 
   16294           89 :     table_close(attrel, RowExclusiveLock);
   16295              : 
   16296           89 :     heap_freetuple(newtuple);
   16297              : 
   16298           89 :     return address;
   16299              : }
   16300              : 
   16301              : /*
   16302              :  * ALTER TABLE OWNER
   16303              :  *
   16304              :  * recursing is true if we are recursing from a table to its indexes,
   16305              :  * sequences, or toast table.  We don't allow the ownership of those things to
   16306              :  * be changed separately from the parent table.  Also, we can skip permission
   16307              :  * checks (this is necessary not just an optimization, else we'd fail to
   16308              :  * handle toast tables properly).
   16309              :  *
   16310              :  * recursing is also true if ALTER TYPE OWNER is calling us to fix up a
   16311              :  * free-standing composite type.
   16312              :  */
   16313              : void
   16314         1312 : ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
   16315              : {
   16316              :     Relation    target_rel;
   16317              :     Relation    class_rel;
   16318              :     HeapTuple   tuple;
   16319              :     Form_pg_class tuple_class;
   16320              : 
   16321              :     /*
   16322              :      * Get exclusive lock till end of transaction on the target table. Use
   16323              :      * relation_open so that we can work on indexes and sequences.
   16324              :      */
   16325         1312 :     target_rel = relation_open(relationOid, lockmode);
   16326              : 
   16327              :     /* Get its pg_class tuple, too */
   16328         1312 :     class_rel = table_open(RelationRelationId, RowExclusiveLock);
   16329              : 
   16330         1312 :     tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relationOid));
   16331         1312 :     if (!HeapTupleIsValid(tuple))
   16332            0 :         elog(ERROR, "cache lookup failed for relation %u", relationOid);
   16333         1312 :     tuple_class = (Form_pg_class) GETSTRUCT(tuple);
   16334              : 
   16335              :     /* Can we change the ownership of this tuple? */
   16336         1312 :     switch (tuple_class->relkind)
   16337              :     {
   16338         1121 :         case RELKIND_RELATION:
   16339              :         case RELKIND_VIEW:
   16340              :         case RELKIND_MATVIEW:
   16341              :         case RELKIND_FOREIGN_TABLE:
   16342              :         case RELKIND_PARTITIONED_TABLE:
   16343              :         case RELKIND_PROPGRAPH:
   16344              :             /* ok to change owner */
   16345         1121 :             break;
   16346           74 :         case RELKIND_INDEX:
   16347           74 :             if (!recursing)
   16348              :             {
   16349              :                 /*
   16350              :                  * Because ALTER INDEX OWNER used to be allowed, and in fact
   16351              :                  * is generated by old versions of pg_dump, we give a warning
   16352              :                  * and do nothing rather than erroring out.  Also, to avoid
   16353              :                  * unnecessary chatter while restoring those old dumps, say
   16354              :                  * nothing at all if the command would be a no-op anyway.
   16355              :                  */
   16356            0 :                 if (tuple_class->relowner != newOwnerId)
   16357            0 :                     ereport(WARNING,
   16358              :                             (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   16359              :                              errmsg("cannot change owner of index \"%s\"",
   16360              :                                     NameStr(tuple_class->relname)),
   16361              :                              errhint("Change the ownership of the index's table instead.")));
   16362              :                 /* quick hack to exit via the no-op path */
   16363            0 :                 newOwnerId = tuple_class->relowner;
   16364              :             }
   16365           74 :             break;
   16366           12 :         case RELKIND_PARTITIONED_INDEX:
   16367           12 :             if (recursing)
   16368           12 :                 break;
   16369            0 :             ereport(ERROR,
   16370              :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   16371              :                      errmsg("cannot change owner of index \"%s\"",
   16372              :                             NameStr(tuple_class->relname)),
   16373              :                      errhint("Change the ownership of the index's table instead.")));
   16374              :             break;
   16375           65 :         case RELKIND_SEQUENCE:
   16376           65 :             if (!recursing &&
   16377           35 :                 tuple_class->relowner != newOwnerId)
   16378              :             {
   16379              :                 /* if it's an owned sequence, disallow changing it by itself */
   16380              :                 Oid         tableId;
   16381              :                 int32       colId;
   16382              : 
   16383            0 :                 if (sequenceIsOwned(relationOid, DEPENDENCY_AUTO, &tableId, &colId) ||
   16384            0 :                     sequenceIsOwned(relationOid, DEPENDENCY_INTERNAL, &tableId, &colId))
   16385            0 :                     ereport(ERROR,
   16386              :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   16387              :                              errmsg("cannot change owner of sequence \"%s\"",
   16388              :                                     NameStr(tuple_class->relname)),
   16389              :                              errdetail("Sequence \"%s\" is linked to table \"%s\".",
   16390              :                                        NameStr(tuple_class->relname),
   16391              :                                        get_rel_name(tableId))));
   16392              :             }
   16393           65 :             break;
   16394            5 :         case RELKIND_COMPOSITE_TYPE:
   16395            5 :             if (recursing)
   16396            5 :                 break;
   16397            0 :             ereport(ERROR,
   16398              :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   16399              :                      errmsg("\"%s\" is a composite type",
   16400              :                             NameStr(tuple_class->relname)),
   16401              :             /* translator: %s is an SQL ALTER command */
   16402              :                      errhint("Use %s instead.",
   16403              :                              "ALTER TYPE")));
   16404              :             break;
   16405           35 :         case RELKIND_TOASTVALUE:
   16406           35 :             if (recursing)
   16407           35 :                 break;
   16408              :             pg_fallthrough;
   16409              :         default:
   16410            0 :             ereport(ERROR,
   16411              :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   16412              :                      errmsg("cannot change owner of relation \"%s\"",
   16413              :                             NameStr(tuple_class->relname)),
   16414              :                      errdetail_relkind_not_supported(tuple_class->relkind)));
   16415              :     }
   16416              : 
   16417              :     /*
   16418              :      * If the new owner is the same as the existing owner, consider the
   16419              :      * command to have succeeded.  This is for dump restoration purposes.
   16420              :      */
   16421         1312 :     if (tuple_class->relowner != newOwnerId)
   16422              :     {
   16423              :         Datum       repl_val[Natts_pg_class];
   16424              :         bool        repl_null[Natts_pg_class];
   16425              :         bool        repl_repl[Natts_pg_class];
   16426              :         Acl        *newAcl;
   16427              :         Datum       aclDatum;
   16428              :         bool        isNull;
   16429              :         HeapTuple   newtuple;
   16430              : 
   16431              :         /* skip permission checks when recursing to index or toast table */
   16432          388 :         if (!recursing)
   16433              :         {
   16434              :             /* Superusers can always do it */
   16435          206 :             if (!superuser())
   16436              :             {
   16437           28 :                 Oid         namespaceOid = tuple_class->relnamespace;
   16438              :                 AclResult   aclresult;
   16439              : 
   16440              :                 /* Otherwise, must be owner of the existing object */
   16441           28 :                 if (!object_ownercheck(RelationRelationId, relationOid, GetUserId()))
   16442            0 :                     aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relationOid)),
   16443            0 :                                    RelationGetRelationName(target_rel));
   16444              : 
   16445              :                 /* Must be able to become new owner */
   16446           28 :                 check_can_set_role(GetUserId(), newOwnerId);
   16447              : 
   16448              :                 /* New owner must have CREATE privilege on namespace */
   16449           20 :                 aclresult = object_aclcheck(NamespaceRelationId, namespaceOid, newOwnerId,
   16450              :                                             ACL_CREATE);
   16451           20 :                 if (aclresult != ACLCHECK_OK)
   16452            0 :                     aclcheck_error(aclresult, OBJECT_SCHEMA,
   16453            0 :                                    get_namespace_name(namespaceOid));
   16454              :             }
   16455              :         }
   16456              : 
   16457          380 :         memset(repl_null, false, sizeof(repl_null));
   16458          380 :         memset(repl_repl, false, sizeof(repl_repl));
   16459              : 
   16460          380 :         repl_repl[Anum_pg_class_relowner - 1] = true;
   16461          380 :         repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
   16462              : 
   16463              :         /*
   16464              :          * Determine the modified ACL for the new owner.  This is only
   16465              :          * necessary when the ACL is non-null.
   16466              :          */
   16467          380 :         aclDatum = SysCacheGetAttr(RELOID, tuple,
   16468              :                                    Anum_pg_class_relacl,
   16469              :                                    &isNull);
   16470          380 :         if (!isNull)
   16471              :         {
   16472           52 :             newAcl = aclnewowner(DatumGetAclP(aclDatum),
   16473              :                                  tuple_class->relowner, newOwnerId);
   16474           52 :             repl_repl[Anum_pg_class_relacl - 1] = true;
   16475           52 :             repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
   16476              :         }
   16477              : 
   16478          380 :         newtuple = heap_modify_tuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
   16479              : 
   16480          380 :         CatalogTupleUpdate(class_rel, &newtuple->t_self, newtuple);
   16481              : 
   16482          380 :         heap_freetuple(newtuple);
   16483              : 
   16484              :         /*
   16485              :          * We must similarly update any per-column ACLs to reflect the new
   16486              :          * owner; for neatness reasons that's split out as a subroutine.
   16487              :          */
   16488          380 :         change_owner_fix_column_acls(relationOid,
   16489              :                                      tuple_class->relowner,
   16490              :                                      newOwnerId);
   16491              : 
   16492              :         /*
   16493              :          * Update owner dependency reference, if any.  A composite type has
   16494              :          * none, because it's tracked for the pg_type entry instead of here;
   16495              :          * indexes and TOAST tables don't have their own entries either.
   16496              :          */
   16497          380 :         if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
   16498          375 :             tuple_class->relkind != RELKIND_INDEX &&
   16499          301 :             tuple_class->relkind != RELKIND_PARTITIONED_INDEX &&
   16500          289 :             tuple_class->relkind != RELKIND_TOASTVALUE)
   16501          254 :             changeDependencyOnOwner(RelationRelationId, relationOid,
   16502              :                                     newOwnerId);
   16503              : 
   16504              :         /*
   16505              :          * Also change the ownership of the table's row type, if it has one
   16506              :          */
   16507          380 :         if (OidIsValid(tuple_class->reltype))
   16508          238 :             AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId);
   16509              : 
   16510              :         /*
   16511              :          * If we are operating on a table or materialized view, also change
   16512              :          * the ownership of any indexes and sequences that belong to the
   16513              :          * relation, as well as its toast table (if it has one).
   16514              :          */
   16515          380 :         if (tuple_class->relkind == RELKIND_RELATION ||
   16516          201 :             tuple_class->relkind == RELKIND_PARTITIONED_TABLE ||
   16517          165 :             tuple_class->relkind == RELKIND_MATVIEW ||
   16518          165 :             tuple_class->relkind == RELKIND_TOASTVALUE)
   16519              :         {
   16520              :             List       *index_oid_list;
   16521              :             ListCell   *i;
   16522              : 
   16523              :             /* Find all the indexes belonging to this relation */
   16524          250 :             index_oid_list = RelationGetIndexList(target_rel);
   16525              : 
   16526              :             /* For each index, recursively change its ownership */
   16527          336 :             foreach(i, index_oid_list)
   16528           86 :                 ATExecChangeOwner(lfirst_oid(i), newOwnerId, true, lockmode);
   16529              : 
   16530          250 :             list_free(index_oid_list);
   16531              :         }
   16532              : 
   16533              :         /* If it has a toast table, recurse to change its ownership */
   16534          380 :         if (tuple_class->reltoastrelid != InvalidOid)
   16535           35 :             ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
   16536              :                               true, lockmode);
   16537              : 
   16538              :         /* If it has dependent sequences, recurse to change them too */
   16539          380 :         change_owner_recurse_to_sequences(relationOid, newOwnerId, lockmode);
   16540              :     }
   16541              : 
   16542         1304 :     InvokeObjectPostAlterHook(RelationRelationId, relationOid, 0);
   16543              : 
   16544         1304 :     ReleaseSysCache(tuple);
   16545         1304 :     table_close(class_rel, RowExclusiveLock);
   16546         1304 :     relation_close(target_rel, NoLock);
   16547         1304 : }
   16548              : 
   16549              : /*
   16550              :  * change_owner_fix_column_acls
   16551              :  *
   16552              :  * Helper function for ATExecChangeOwner.  Scan the columns of the table
   16553              :  * and fix any non-null column ACLs to reflect the new owner.
   16554              :  */
   16555              : static void
   16556          380 : change_owner_fix_column_acls(Oid relationOid, Oid oldOwnerId, Oid newOwnerId)
   16557              : {
   16558              :     Relation    attRelation;
   16559              :     SysScanDesc scan;
   16560              :     ScanKeyData key[1];
   16561              :     HeapTuple   attributeTuple;
   16562              : 
   16563          380 :     attRelation = table_open(AttributeRelationId, RowExclusiveLock);
   16564          380 :     ScanKeyInit(&key[0],
   16565              :                 Anum_pg_attribute_attrelid,
   16566              :                 BTEqualStrategyNumber, F_OIDEQ,
   16567              :                 ObjectIdGetDatum(relationOid));
   16568          380 :     scan = systable_beginscan(attRelation, AttributeRelidNumIndexId,
   16569              :                               true, NULL, 1, key);
   16570         2731 :     while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
   16571              :     {
   16572         2351 :         Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
   16573              :         Datum       repl_val[Natts_pg_attribute];
   16574              :         bool        repl_null[Natts_pg_attribute];
   16575              :         bool        repl_repl[Natts_pg_attribute];
   16576              :         Acl        *newAcl;
   16577              :         Datum       aclDatum;
   16578              :         bool        isNull;
   16579              :         HeapTuple   newtuple;
   16580              : 
   16581              :         /* Ignore dropped columns */
   16582         2351 :         if (att->attisdropped)
   16583         2350 :             continue;
   16584              : 
   16585         2351 :         aclDatum = heap_getattr(attributeTuple,
   16586              :                                 Anum_pg_attribute_attacl,
   16587              :                                 RelationGetDescr(attRelation),
   16588              :                                 &isNull);
   16589              :         /* Null ACLs do not require changes */
   16590         2351 :         if (isNull)
   16591         2350 :             continue;
   16592              : 
   16593            1 :         memset(repl_null, false, sizeof(repl_null));
   16594            1 :         memset(repl_repl, false, sizeof(repl_repl));
   16595              : 
   16596            1 :         newAcl = aclnewowner(DatumGetAclP(aclDatum),
   16597              :                              oldOwnerId, newOwnerId);
   16598            1 :         repl_repl[Anum_pg_attribute_attacl - 1] = true;
   16599            1 :         repl_val[Anum_pg_attribute_attacl - 1] = PointerGetDatum(newAcl);
   16600              : 
   16601            1 :         newtuple = heap_modify_tuple(attributeTuple,
   16602              :                                      RelationGetDescr(attRelation),
   16603              :                                      repl_val, repl_null, repl_repl);
   16604              : 
   16605            1 :         CatalogTupleUpdate(attRelation, &newtuple->t_self, newtuple);
   16606              : 
   16607            1 :         heap_freetuple(newtuple);
   16608              :     }
   16609          380 :     systable_endscan(scan);
   16610          380 :     table_close(attRelation, RowExclusiveLock);
   16611          380 : }
   16612              : 
   16613              : /*
   16614              :  * change_owner_recurse_to_sequences
   16615              :  *
   16616              :  * Helper function for ATExecChangeOwner.  Examines pg_depend searching
   16617              :  * for sequences that are dependent on serial columns, and changes their
   16618              :  * ownership.
   16619              :  */
   16620              : static void
   16621          380 : change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId, LOCKMODE lockmode)
   16622              : {
   16623              :     Relation    depRel;
   16624              :     SysScanDesc scan;
   16625              :     ScanKeyData key[2];
   16626              :     HeapTuple   tup;
   16627              : 
   16628              :     /*
   16629              :      * SERIAL sequences are those having an auto dependency on one of the
   16630              :      * table's columns (we don't care *which* column, exactly).
   16631              :      */
   16632          380 :     depRel = table_open(DependRelationId, AccessShareLock);
   16633              : 
   16634          380 :     ScanKeyInit(&key[0],
   16635              :                 Anum_pg_depend_refclassid,
   16636              :                 BTEqualStrategyNumber, F_OIDEQ,
   16637              :                 ObjectIdGetDatum(RelationRelationId));
   16638          380 :     ScanKeyInit(&key[1],
   16639              :                 Anum_pg_depend_refobjid,
   16640              :                 BTEqualStrategyNumber, F_OIDEQ,
   16641              :                 ObjectIdGetDatum(relationOid));
   16642              :     /* we leave refobjsubid unspecified */
   16643              : 
   16644          380 :     scan = systable_beginscan(depRel, DependReferenceIndexId, true,
   16645              :                               NULL, 2, key);
   16646              : 
   16647         1216 :     while (HeapTupleIsValid(tup = systable_getnext(scan)))
   16648              :     {
   16649          836 :         Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
   16650              :         Relation    seqRel;
   16651              : 
   16652              :         /* skip dependencies other than auto dependencies on columns */
   16653          836 :         if (depForm->refobjsubid == 0 ||
   16654          342 :             depForm->classid != RelationRelationId ||
   16655          106 :             depForm->objsubid != 0 ||
   16656          106 :             !(depForm->deptype == DEPENDENCY_AUTO || depForm->deptype == DEPENDENCY_INTERNAL))
   16657          730 :             continue;
   16658              : 
   16659              :         /* Use relation_open just in case it's an index */
   16660          106 :         seqRel = relation_open(depForm->objid, lockmode);
   16661              : 
   16662              :         /* skip non-sequence relations */
   16663          106 :         if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
   16664              :         {
   16665              :             /* No need to keep the lock */
   16666           89 :             relation_close(seqRel, lockmode);
   16667           89 :             continue;
   16668              :         }
   16669              : 
   16670              :         /* We don't need to close the sequence while we alter it. */
   16671           17 :         ATExecChangeOwner(depForm->objid, newOwnerId, true, lockmode);
   16672              : 
   16673              :         /* Now we can close it.  Keep the lock till end of transaction. */
   16674           17 :         relation_close(seqRel, NoLock);
   16675              :     }
   16676              : 
   16677          380 :     systable_endscan(scan);
   16678              : 
   16679          380 :     relation_close(depRel, AccessShareLock);
   16680          380 : }
   16681              : 
   16682              : /*
   16683              :  * ALTER TABLE CLUSTER ON
   16684              :  *
   16685              :  * The only thing we have to do is to change the indisclustered bits.
   16686              :  *
   16687              :  * Return the address of the new clustering index.
   16688              :  */
   16689              : static ObjectAddress
   16690           39 : ATExecClusterOn(Relation rel, const char *indexName, LOCKMODE lockmode)
   16691              : {
   16692              :     Oid         indexOid;
   16693              :     ObjectAddress address;
   16694              : 
   16695           39 :     indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
   16696              : 
   16697           39 :     if (!OidIsValid(indexOid))
   16698            0 :         ereport(ERROR,
   16699              :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
   16700              :                  errmsg("index \"%s\" for table \"%s\" does not exist",
   16701              :                         indexName, RelationGetRelationName(rel))));
   16702              : 
   16703              :     /* Check index is valid to cluster on */
   16704           39 :     check_index_is_clusterable(rel, indexOid, lockmode);
   16705              : 
   16706              :     /* And do the work */
   16707           39 :     mark_index_clustered(rel, indexOid, false);
   16708              : 
   16709           39 :     ObjectAddressSet(address,
   16710              :                      RelationRelationId, indexOid);
   16711              : 
   16712           39 :     return address;
   16713              : }
   16714              : 
   16715              : /*
   16716              :  * ALTER TABLE SET WITHOUT CLUSTER
   16717              :  *
   16718              :  * We have to find any indexes on the table that have indisclustered bit
   16719              :  * set and turn it off.
   16720              :  */
   16721              : static void
   16722            8 : ATExecDropCluster(Relation rel, LOCKMODE lockmode)
   16723              : {
   16724            8 :     mark_index_clustered(rel, InvalidOid, false);
   16725            8 : }
   16726              : 
   16727              : /*
   16728              :  * Preparation phase for SET ACCESS METHOD
   16729              :  *
   16730              :  * Check that the access method exists and determine whether a change is
   16731              :  * actually needed.
   16732              :  */
   16733              : static void
   16734           73 : ATPrepSetAccessMethod(AlteredTableInfo *tab, Relation rel, const char *amname)
   16735              : {
   16736              :     Oid         amoid;
   16737              : 
   16738              :     /*
   16739              :      * Look up the access method name and check that it differs from the
   16740              :      * table's current AM.  If DEFAULT was specified for a partitioned table
   16741              :      * (amname is NULL), set it to InvalidOid to reset the catalogued AM.
   16742              :      */
   16743           73 :     if (amname != NULL)
   16744           49 :         amoid = get_table_am_oid(amname, false);
   16745           24 :     else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
   16746           12 :         amoid = InvalidOid;
   16747              :     else
   16748           12 :         amoid = get_table_am_oid(default_table_access_method, false);
   16749              : 
   16750              :     /* if it's a match, phase 3 doesn't need to do anything */
   16751           73 :     if (rel->rd_rel->relam == amoid)
   16752            8 :         return;
   16753              : 
   16754              :     /* Save info for Phase 3 to do the real work */
   16755           65 :     tab->rewrite |= AT_REWRITE_ACCESS_METHOD;
   16756           65 :     tab->newAccessMethod = amoid;
   16757           65 :     tab->chgAccessMethod = true;
   16758              : }
   16759              : 
   16760              : /*
   16761              :  * Special handling of ALTER TABLE SET ACCESS METHOD for relations with no
   16762              :  * storage that have an interest in preserving AM.
   16763              :  *
   16764              :  * Since these have no storage, setting the access method is a catalog only
   16765              :  * operation.
   16766              :  */
   16767              : static void
   16768           29 : ATExecSetAccessMethodNoStorage(Relation rel, Oid newAccessMethodId)
   16769              : {
   16770              :     Relation    pg_class;
   16771              :     Oid         oldAccessMethodId;
   16772              :     HeapTuple   tuple;
   16773              :     Form_pg_class rd_rel;
   16774           29 :     Oid         reloid = RelationGetRelid(rel);
   16775              : 
   16776              :     /*
   16777              :      * Shouldn't be called on relations having storage; these are processed in
   16778              :      * phase 3.
   16779              :      */
   16780              :     Assert(!RELKIND_HAS_STORAGE(rel->rd_rel->relkind));
   16781              : 
   16782              :     /* Get a modifiable copy of the relation's pg_class row. */
   16783           29 :     pg_class = table_open(RelationRelationId, RowExclusiveLock);
   16784              : 
   16785           29 :     tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(reloid));
   16786           29 :     if (!HeapTupleIsValid(tuple))
   16787            0 :         elog(ERROR, "cache lookup failed for relation %u", reloid);
   16788           29 :     rd_rel = (Form_pg_class) GETSTRUCT(tuple);
   16789              : 
   16790              :     /* Update the pg_class row. */
   16791           29 :     oldAccessMethodId = rd_rel->relam;
   16792           29 :     rd_rel->relam = newAccessMethodId;
   16793              : 
   16794              :     /* Leave if no update required */
   16795           29 :     if (rd_rel->relam == oldAccessMethodId)
   16796              :     {
   16797            0 :         heap_freetuple(tuple);
   16798            0 :         table_close(pg_class, RowExclusiveLock);
   16799            0 :         return;
   16800              :     }
   16801              : 
   16802           29 :     CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
   16803              : 
   16804              :     /*
   16805              :      * Update the dependency on the new access method.  No dependency is added
   16806              :      * if the new access method is InvalidOid (default case).  Be very careful
   16807              :      * that this has to compare the previous value stored in pg_class with the
   16808              :      * new one.
   16809              :      */
   16810           29 :     if (!OidIsValid(oldAccessMethodId) && OidIsValid(rd_rel->relam))
   16811           13 :     {
   16812              :         ObjectAddress relobj,
   16813              :                     referenced;
   16814              : 
   16815              :         /*
   16816              :          * New access method is defined and there was no dependency
   16817              :          * previously, so record a new one.
   16818              :          */
   16819           13 :         ObjectAddressSet(relobj, RelationRelationId, reloid);
   16820           13 :         ObjectAddressSet(referenced, AccessMethodRelationId, rd_rel->relam);
   16821           13 :         recordDependencyOn(&relobj, &referenced, DEPENDENCY_NORMAL);
   16822              :     }
   16823           16 :     else if (OidIsValid(oldAccessMethodId) &&
   16824           16 :              !OidIsValid(rd_rel->relam))
   16825              :     {
   16826              :         /*
   16827              :          * There was an access method defined, and no new one, so just remove
   16828              :          * the existing dependency.
   16829              :          */
   16830            8 :         deleteDependencyRecordsForClass(RelationRelationId, reloid,
   16831              :                                         AccessMethodRelationId,
   16832              :                                         DEPENDENCY_NORMAL);
   16833              :     }
   16834              :     else
   16835              :     {
   16836              :         Assert(OidIsValid(oldAccessMethodId) &&
   16837              :                OidIsValid(rd_rel->relam));
   16838              : 
   16839              :         /* Both are valid, so update the dependency */
   16840            8 :         changeDependencyFor(RelationRelationId, reloid,
   16841              :                             AccessMethodRelationId,
   16842              :                             oldAccessMethodId, rd_rel->relam);
   16843              :     }
   16844              : 
   16845              :     /* make the relam and dependency changes visible */
   16846           29 :     CommandCounterIncrement();
   16847              : 
   16848           29 :     InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
   16849              : 
   16850           29 :     heap_freetuple(tuple);
   16851           29 :     table_close(pg_class, RowExclusiveLock);
   16852              : }
   16853              : 
   16854              : /*
   16855              :  * ALTER TABLE SET TABLESPACE
   16856              :  */
   16857              : static void
   16858          107 : ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, const char *tablespacename, LOCKMODE lockmode)
   16859              : {
   16860              :     Oid         tablespaceId;
   16861              : 
   16862              :     /* Check that the tablespace exists */
   16863          107 :     tablespaceId = get_tablespace_oid(tablespacename, false);
   16864              : 
   16865              :     /* Check permissions except when moving to database's default */
   16866          107 :     if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
   16867              :     {
   16868              :         AclResult   aclresult;
   16869              : 
   16870           42 :         aclresult = object_aclcheck(TableSpaceRelationId, tablespaceId, GetUserId(), ACL_CREATE);
   16871           42 :         if (aclresult != ACLCHECK_OK)
   16872            0 :             aclcheck_error(aclresult, OBJECT_TABLESPACE, tablespacename);
   16873              :     }
   16874              : 
   16875              :     /* Save info for Phase 3 to do the real work */
   16876          107 :     if (OidIsValid(tab->newTableSpace))
   16877            0 :         ereport(ERROR,
   16878              :                 (errcode(ERRCODE_SYNTAX_ERROR),
   16879              :                  errmsg("cannot have multiple SET TABLESPACE subcommands")));
   16880              : 
   16881          107 :     tab->newTableSpace = tablespaceId;
   16882          107 : }
   16883              : 
   16884              : /*
   16885              :  * Set, reset, or replace reloptions.
   16886              :  */
   16887              : static void
   16888          622 : ATExecSetRelOptions(Relation rel, List *defList, AlterTableType operation,
   16889              :                     LOCKMODE lockmode)
   16890              : {
   16891              :     Oid         relid;
   16892              :     Relation    pgclass;
   16893              :     HeapTuple   tuple;
   16894              :     HeapTuple   newtuple;
   16895              :     Datum       datum;
   16896              :     Datum       newOptions;
   16897              :     Datum       repl_val[Natts_pg_class];
   16898              :     bool        repl_null[Natts_pg_class];
   16899              :     bool        repl_repl[Natts_pg_class];
   16900          622 :     const char *const validnsps[] = HEAP_RELOPT_NAMESPACES;
   16901              : 
   16902          622 :     if (defList == NIL && operation != AT_ReplaceRelOptions)
   16903            0 :         return;                 /* nothing to do */
   16904              : 
   16905          622 :     pgclass = table_open(RelationRelationId, RowExclusiveLock);
   16906              : 
   16907              :     /* Fetch heap tuple */
   16908          622 :     relid = RelationGetRelid(rel);
   16909          622 :     tuple = SearchSysCacheLocked1(RELOID, ObjectIdGetDatum(relid));
   16910          622 :     if (!HeapTupleIsValid(tuple))
   16911            0 :         elog(ERROR, "cache lookup failed for relation %u", relid);
   16912              : 
   16913          622 :     if (operation == AT_ReplaceRelOptions)
   16914              :     {
   16915              :         /*
   16916              :          * If we're supposed to replace the reloptions list, we just pretend
   16917              :          * there were none before.
   16918              :          */
   16919          133 :         datum = (Datum) 0;
   16920              :     }
   16921              :     else
   16922              :     {
   16923              :         bool        isnull;
   16924              : 
   16925              :         /* Get the old reloptions */
   16926          489 :         datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
   16927              :                                 &isnull);
   16928          489 :         if (isnull)
   16929          304 :             datum = (Datum) 0;
   16930              :     }
   16931              : 
   16932              :     /* Generate new proposed reloptions (text array) */
   16933          622 :     newOptions = transformRelOptions(datum, defList, NULL, validnsps, false,
   16934              :                                      operation == AT_ResetRelOptions);
   16935              : 
   16936              :     /* Validate */
   16937          618 :     switch (rel->rd_rel->relkind)
   16938              :     {
   16939          342 :         case RELKIND_RELATION:
   16940              :         case RELKIND_MATVIEW:
   16941          342 :             (void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
   16942          342 :             break;
   16943            4 :         case RELKIND_PARTITIONED_TABLE:
   16944            4 :             (void) partitioned_table_reloptions(newOptions, true);
   16945            0 :             break;
   16946          201 :         case RELKIND_VIEW:
   16947          201 :             (void) view_reloptions(newOptions, true);
   16948          189 :             break;
   16949           71 :         case RELKIND_INDEX:
   16950              :         case RELKIND_PARTITIONED_INDEX:
   16951           71 :             (void) index_reloptions(rel->rd_indam->amoptions, newOptions, true);
   16952           57 :             break;
   16953            0 :         case RELKIND_TOASTVALUE:
   16954              :             /* fall through to error -- shouldn't ever get here */
   16955              :         default:
   16956            0 :             ereport(ERROR,
   16957              :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   16958              :                      errmsg("cannot set options for relation \"%s\"",
   16959              :                             RelationGetRelationName(rel)),
   16960              :                      errdetail_relkind_not_supported(rel->rd_rel->relkind)));
   16961              :             break;
   16962              :     }
   16963              : 
   16964              :     /* Special-case validation of view options */
   16965          588 :     if (rel->rd_rel->relkind == RELKIND_VIEW)
   16966              :     {
   16967          189 :         Query      *view_query = get_view_query(rel);
   16968          189 :         List       *view_options = untransformRelOptions(newOptions);
   16969              :         ListCell   *cell;
   16970          189 :         bool        check_option = false;
   16971              : 
   16972          257 :         foreach(cell, view_options)
   16973              :         {
   16974           68 :             DefElem    *defel = (DefElem *) lfirst(cell);
   16975              : 
   16976           68 :             if (strcmp(defel->defname, "check_option") == 0)
   16977           16 :                 check_option = true;
   16978              :         }
   16979              : 
   16980              :         /*
   16981              :          * If the check option is specified, look to see if the view is
   16982              :          * actually auto-updatable or not.
   16983              :          */
   16984          189 :         if (check_option)
   16985              :         {
   16986              :             const char *view_updatable_error =
   16987           16 :                 view_query_is_auto_updatable(view_query, true);
   16988              : 
   16989           16 :             if (view_updatable_error)
   16990            0 :                 ereport(ERROR,
   16991              :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   16992              :                          errmsg("WITH CHECK OPTION is supported only on automatically updatable views"),
   16993              :                          errhint("%s", _(view_updatable_error))));
   16994              :         }
   16995              :     }
   16996              : 
   16997              :     /*
   16998              :      * All we need do here is update the pg_class row; the new options will be
   16999              :      * propagated into relcaches during post-commit cache inval.
   17000              :      */
   17001          588 :     memset(repl_val, 0, sizeof(repl_val));
   17002          588 :     memset(repl_null, false, sizeof(repl_null));
   17003          588 :     memset(repl_repl, false, sizeof(repl_repl));
   17004              : 
   17005          588 :     if (newOptions != (Datum) 0)
   17006          390 :         repl_val[Anum_pg_class_reloptions - 1] = newOptions;
   17007              :     else
   17008          198 :         repl_null[Anum_pg_class_reloptions - 1] = true;
   17009              : 
   17010          588 :     repl_repl[Anum_pg_class_reloptions - 1] = true;
   17011              : 
   17012          588 :     newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
   17013              :                                  repl_val, repl_null, repl_repl);
   17014              : 
   17015          588 :     CatalogTupleUpdate(pgclass, &newtuple->t_self, newtuple);
   17016          588 :     UnlockTuple(pgclass, &tuple->t_self, InplaceUpdateTupleLock);
   17017              : 
   17018          588 :     InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
   17019              : 
   17020          588 :     heap_freetuple(newtuple);
   17021              : 
   17022          588 :     ReleaseSysCache(tuple);
   17023              : 
   17024              :     /* repeat the whole exercise for the toast table, if there's one */
   17025          588 :     if (OidIsValid(rel->rd_rel->reltoastrelid))
   17026              :     {
   17027              :         Relation    toastrel;
   17028          180 :         Oid         toastid = rel->rd_rel->reltoastrelid;
   17029              : 
   17030          180 :         toastrel = table_open(toastid, lockmode);
   17031              : 
   17032              :         /* Fetch heap tuple */
   17033          180 :         tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(toastid));
   17034          180 :         if (!HeapTupleIsValid(tuple))
   17035            0 :             elog(ERROR, "cache lookup failed for relation %u", toastid);
   17036              : 
   17037          180 :         if (operation == AT_ReplaceRelOptions)
   17038              :         {
   17039              :             /*
   17040              :              * If we're supposed to replace the reloptions list, we just
   17041              :              * pretend there were none before.
   17042              :              */
   17043            0 :             datum = (Datum) 0;
   17044              :         }
   17045              :         else
   17046              :         {
   17047              :             bool        isnull;
   17048              : 
   17049              :             /* Get the old reloptions */
   17050          180 :             datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
   17051              :                                     &isnull);
   17052          180 :             if (isnull)
   17053          156 :                 datum = (Datum) 0;
   17054              :         }
   17055              : 
   17056          180 :         newOptions = transformRelOptions(datum, defList, "toast", validnsps,
   17057              :                                          false, operation == AT_ResetRelOptions);
   17058              : 
   17059          180 :         (void) heap_reloptions(RELKIND_TOASTVALUE, newOptions, true);
   17060              : 
   17061          180 :         memset(repl_val, 0, sizeof(repl_val));
   17062          180 :         memset(repl_null, false, sizeof(repl_null));
   17063          180 :         memset(repl_repl, false, sizeof(repl_repl));
   17064              : 
   17065          180 :         if (newOptions != (Datum) 0)
   17066           28 :             repl_val[Anum_pg_class_reloptions - 1] = newOptions;
   17067              :         else
   17068          152 :             repl_null[Anum_pg_class_reloptions - 1] = true;
   17069              : 
   17070          180 :         repl_repl[Anum_pg_class_reloptions - 1] = true;
   17071              : 
   17072          180 :         newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
   17073              :                                      repl_val, repl_null, repl_repl);
   17074              : 
   17075          180 :         CatalogTupleUpdate(pgclass, &newtuple->t_self, newtuple);
   17076              : 
   17077          180 :         InvokeObjectPostAlterHookArg(RelationRelationId,
   17078              :                                      RelationGetRelid(toastrel), 0,
   17079              :                                      InvalidOid, true);
   17080              : 
   17081          180 :         heap_freetuple(newtuple);
   17082              : 
   17083          180 :         ReleaseSysCache(tuple);
   17084              : 
   17085          180 :         table_close(toastrel, NoLock);
   17086              :     }
   17087              : 
   17088          588 :     table_close(pgclass, RowExclusiveLock);
   17089              : }
   17090              : 
   17091              : /*
   17092              :  * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
   17093              :  * rewriting to be done, so we just want to copy the data as fast as possible.
   17094              :  */
   17095              : static void
   17096          109 : ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode)
   17097              : {
   17098              :     Relation    rel;
   17099              :     Oid         reltoastrelid;
   17100              :     RelFileNumber newrelfilenumber;
   17101              :     RelFileLocator newrlocator;
   17102          109 :     List       *reltoastidxids = NIL;
   17103              :     ListCell   *lc;
   17104              : 
   17105              :     /*
   17106              :      * Need lock here in case we are recursing to toast table or index
   17107              :      */
   17108          109 :     rel = relation_open(tableOid, lockmode);
   17109              : 
   17110              :     /* Check first if relation can be moved to new tablespace */
   17111          109 :     if (!CheckRelationTableSpaceMove(rel, newTableSpace))
   17112              :     {
   17113            5 :         InvokeObjectPostAlterHook(RelationRelationId,
   17114              :                                   RelationGetRelid(rel), 0);
   17115            5 :         relation_close(rel, NoLock);
   17116            5 :         return;
   17117              :     }
   17118              : 
   17119          104 :     reltoastrelid = rel->rd_rel->reltoastrelid;
   17120              :     /* Fetch the list of indexes on toast relation if necessary */
   17121          104 :     if (OidIsValid(reltoastrelid))
   17122              :     {
   17123           13 :         Relation    toastRel = relation_open(reltoastrelid, lockmode);
   17124              : 
   17125           13 :         reltoastidxids = RelationGetIndexList(toastRel);
   17126           13 :         relation_close(toastRel, lockmode);
   17127              :     }
   17128              : 
   17129              :     /*
   17130              :      * Relfilenumbers are not unique in databases across tablespaces, so we
   17131              :      * need to allocate a new one in the new tablespace.
   17132              :      */
   17133          104 :     newrelfilenumber = GetNewRelFileNumber(newTableSpace, NULL,
   17134          104 :                                            rel->rd_rel->relpersistence);
   17135              : 
   17136              :     /* Open old and new relation */
   17137          104 :     newrlocator = rel->rd_locator;
   17138          104 :     newrlocator.relNumber = newrelfilenumber;
   17139          104 :     newrlocator.spcOid = newTableSpace;
   17140              : 
   17141              :     /* hand off to AM to actually create new rel storage and copy the data */
   17142          104 :     if (rel->rd_rel->relkind == RELKIND_INDEX)
   17143              :     {
   17144           41 :         index_copy_data(rel, newrlocator);
   17145              :     }
   17146              :     else
   17147              :     {
   17148              :         Assert(RELKIND_HAS_TABLE_AM(rel->rd_rel->relkind));
   17149           63 :         table_relation_copy_data(rel, &newrlocator);
   17150              :     }
   17151              : 
   17152              :     /*
   17153              :      * Update the pg_class row.
   17154              :      *
   17155              :      * NB: This wouldn't work if ATExecSetTableSpace() were allowed to be
   17156              :      * executed on pg_class or its indexes (the above copy wouldn't contain
   17157              :      * the updated pg_class entry), but that's forbidden with
   17158              :      * CheckRelationTableSpaceMove().
   17159              :      */
   17160          104 :     SetRelationTableSpace(rel, newTableSpace, newrelfilenumber);
   17161              : 
   17162          104 :     InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
   17163              : 
   17164          104 :     RelationAssumeNewRelfilelocator(rel);
   17165              : 
   17166          104 :     relation_close(rel, NoLock);
   17167              : 
   17168              :     /* Make sure the reltablespace change is visible */
   17169          104 :     CommandCounterIncrement();
   17170              : 
   17171              :     /* Move associated toast relation and/or indexes, too */
   17172          104 :     if (OidIsValid(reltoastrelid))
   17173           13 :         ATExecSetTableSpace(reltoastrelid, newTableSpace, lockmode);
   17174          117 :     foreach(lc, reltoastidxids)
   17175           13 :         ATExecSetTableSpace(lfirst_oid(lc), newTableSpace, lockmode);
   17176              : 
   17177              :     /* Clean up */
   17178          104 :     list_free(reltoastidxids);
   17179              : }
   17180              : 
   17181              : /*
   17182              :  * Special handling of ALTER TABLE SET TABLESPACE for relations with no
   17183              :  * storage that have an interest in preserving tablespace.
   17184              :  *
   17185              :  * Since these have no storage the tablespace can be updated with a simple
   17186              :  * metadata only operation to update the tablespace.
   17187              :  */
   17188              : static void
   17189           24 : ATExecSetTableSpaceNoStorage(Relation rel, Oid newTableSpace)
   17190              : {
   17191              :     /*
   17192              :      * Shouldn't be called on relations having storage; these are processed in
   17193              :      * phase 3.
   17194              :      */
   17195              :     Assert(!RELKIND_HAS_STORAGE(rel->rd_rel->relkind));
   17196              : 
   17197              :     /* check if relation can be moved to its new tablespace */
   17198           24 :     if (!CheckRelationTableSpaceMove(rel, newTableSpace))
   17199              :     {
   17200            0 :         InvokeObjectPostAlterHook(RelationRelationId,
   17201              :                                   RelationGetRelid(rel),
   17202              :                                   0);
   17203            0 :         return;
   17204              :     }
   17205              : 
   17206              :     /* Update can be done, so change reltablespace */
   17207           20 :     SetRelationTableSpace(rel, newTableSpace, InvalidOid);
   17208              : 
   17209           20 :     InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
   17210              : 
   17211              :     /* Make sure the reltablespace change is visible */
   17212           20 :     CommandCounterIncrement();
   17213              : }
   17214              : 
   17215              : /*
   17216              :  * Alter Table ALL ... SET TABLESPACE
   17217              :  *
   17218              :  * Allows a user to move all objects of some type in a given tablespace in the
   17219              :  * current database to another tablespace.  Objects can be chosen based on the
   17220              :  * owner of the object also, to allow users to move only their objects.
   17221              :  * The user must have CREATE rights on the new tablespace, as usual.   The main
   17222              :  * permissions handling is done by the lower-level table move function.
   17223              :  *
   17224              :  * All to-be-moved objects are locked first. If NOWAIT is specified and the
   17225              :  * lock can't be acquired then we ereport(ERROR).
   17226              :  */
   17227              : Oid
   17228           20 : AlterTableMoveAll(AlterTableMoveAllStmt *stmt)
   17229              : {
   17230           20 :     List       *relations = NIL;
   17231              :     ListCell   *l;
   17232              :     ScanKeyData key[1];
   17233              :     Relation    rel;
   17234              :     TableScanDesc scan;
   17235              :     HeapTuple   tuple;
   17236              :     Oid         orig_tablespaceoid;
   17237              :     Oid         new_tablespaceoid;
   17238           20 :     List       *role_oids = roleSpecsToIds(stmt->roles);
   17239              : 
   17240              :     /* Ensure we were not asked to move something we can't */
   17241           20 :     if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
   17242            8 :         stmt->objtype != OBJECT_MATVIEW)
   17243            0 :         ereport(ERROR,
   17244              :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
   17245              :                  errmsg("only tables, indexes, and materialized views exist in tablespaces")));
   17246              : 
   17247              :     /* Get the orig and new tablespace OIDs */
   17248           20 :     orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
   17249           20 :     new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
   17250              : 
   17251              :     /* Can't move shared relations in to or out of pg_global */
   17252              :     /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
   17253           20 :     if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
   17254              :         new_tablespaceoid == GLOBALTABLESPACE_OID)
   17255            0 :         ereport(ERROR,
   17256              :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
   17257              :                  errmsg("cannot move relations in to or out of pg_global tablespace")));
   17258              : 
   17259              :     /*
   17260              :      * Must have CREATE rights on the new tablespace, unless it is the
   17261              :      * database default tablespace (which all users implicitly have CREATE
   17262              :      * rights on).
   17263              :      */
   17264           20 :     if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
   17265              :     {
   17266              :         AclResult   aclresult;
   17267              : 
   17268            0 :         aclresult = object_aclcheck(TableSpaceRelationId, new_tablespaceoid, GetUserId(),
   17269              :                                     ACL_CREATE);
   17270            0 :         if (aclresult != ACLCHECK_OK)
   17271            0 :             aclcheck_error(aclresult, OBJECT_TABLESPACE,
   17272            0 :                            get_tablespace_name(new_tablespaceoid));
   17273              :     }
   17274              : 
   17275              :     /*
   17276              :      * Now that the checks are done, check if we should set either to
   17277              :      * InvalidOid because it is our database's default tablespace.
   17278              :      */
   17279           20 :     if (orig_tablespaceoid == MyDatabaseTableSpace)
   17280            0 :         orig_tablespaceoid = InvalidOid;
   17281              : 
   17282           20 :     if (new_tablespaceoid == MyDatabaseTableSpace)
   17283           20 :         new_tablespaceoid = InvalidOid;
   17284              : 
   17285              :     /* no-op */
   17286           20 :     if (orig_tablespaceoid == new_tablespaceoid)
   17287            0 :         return new_tablespaceoid;
   17288              : 
   17289              :     /*
   17290              :      * Walk the list of objects in the tablespace and move them. This will
   17291              :      * only find objects in our database, of course.
   17292              :      */
   17293           20 :     ScanKeyInit(&key[0],
   17294              :                 Anum_pg_class_reltablespace,
   17295              :                 BTEqualStrategyNumber, F_OIDEQ,
   17296              :                 ObjectIdGetDatum(orig_tablespaceoid));
   17297              : 
   17298           20 :     rel = table_open(RelationRelationId, AccessShareLock);
   17299           20 :     scan = table_beginscan_catalog(rel, 1, key);
   17300           88 :     while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
   17301              :     {
   17302           68 :         Form_pg_class relForm = (Form_pg_class) GETSTRUCT(tuple);
   17303           68 :         Oid         relOid = relForm->oid;
   17304              : 
   17305              :         /*
   17306              :          * Do not move objects in pg_catalog as part of this, if an admin
   17307              :          * really wishes to do so, they can issue the individual ALTER
   17308              :          * commands directly.
   17309              :          *
   17310              :          * Also, explicitly avoid any shared tables, temp tables, or TOAST
   17311              :          * (TOAST will be moved with the main table).
   17312              :          */
   17313           68 :         if (IsCatalogNamespace(relForm->relnamespace) ||
   17314          136 :             relForm->relisshared ||
   17315          136 :             isAnyTempNamespace(relForm->relnamespace) ||
   17316           68 :             IsToastNamespace(relForm->relnamespace))
   17317            0 :             continue;
   17318              : 
   17319              :         /* Only move the object type requested */
   17320           68 :         if ((stmt->objtype == OBJECT_TABLE &&
   17321           40 :              relForm->relkind != RELKIND_RELATION &&
   17322           24 :              relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
   17323           44 :             (stmt->objtype == OBJECT_INDEX &&
   17324           24 :              relForm->relkind != RELKIND_INDEX &&
   17325            4 :              relForm->relkind != RELKIND_PARTITIONED_INDEX) ||
   17326           40 :             (stmt->objtype == OBJECT_MATVIEW &&
   17327            4 :              relForm->relkind != RELKIND_MATVIEW))
   17328           28 :             continue;
   17329              : 
   17330              :         /* Check if we are only moving objects owned by certain roles */
   17331           40 :         if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
   17332            0 :             continue;
   17333              : 
   17334              :         /*
   17335              :          * Handle permissions-checking here since we are locking the tables
   17336              :          * and also to avoid doing a bunch of work only to fail part-way. Note
   17337              :          * that permissions will also be checked by AlterTableInternal().
   17338              :          *
   17339              :          * Caller must be considered an owner on the table to move it.
   17340              :          */
   17341           40 :         if (!object_ownercheck(RelationRelationId, relOid, GetUserId()))
   17342            0 :             aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relOid)),
   17343            0 :                            NameStr(relForm->relname));
   17344              : 
   17345           40 :         if (stmt->nowait &&
   17346            0 :             !ConditionalLockRelationOid(relOid, AccessExclusiveLock))
   17347            0 :             ereport(ERROR,
   17348              :                     (errcode(ERRCODE_OBJECT_IN_USE),
   17349              :                      errmsg("aborting because lock on relation \"%s.%s\" is not available",
   17350              :                             get_namespace_name(relForm->relnamespace),
   17351              :                             NameStr(relForm->relname))));
   17352              :         else
   17353           40 :             LockRelationOid(relOid, AccessExclusiveLock);
   17354              : 
   17355              :         /* Add to our list of objects to move */
   17356           40 :         relations = lappend_oid(relations, relOid);
   17357              :     }
   17358              : 
   17359           20 :     table_endscan(scan);
   17360           20 :     table_close(rel, AccessShareLock);
   17361              : 
   17362           20 :     if (relations == NIL)
   17363            8 :         ereport(NOTICE,
   17364              :                 (errcode(ERRCODE_NO_DATA_FOUND),
   17365              :                  errmsg("no matching relations in tablespace \"%s\" found",
   17366              :                         orig_tablespaceoid == InvalidOid ? "(database default)" :
   17367              :                         get_tablespace_name(orig_tablespaceoid))));
   17368              : 
   17369              :     /* Everything is locked, loop through and move all of the relations. */
   17370           60 :     foreach(l, relations)
   17371              :     {
   17372           40 :         List       *cmds = NIL;
   17373           40 :         AlterTableCmd *cmd = makeNode(AlterTableCmd);
   17374              : 
   17375           40 :         cmd->subtype = AT_SetTableSpace;
   17376           40 :         cmd->name = stmt->new_tablespacename;
   17377              : 
   17378           40 :         cmds = lappend(cmds, cmd);
   17379              : 
   17380           40 :         EventTriggerAlterTableStart((Node *) stmt);
   17381              :         /* OID is set by AlterTableInternal */
   17382           40 :         AlterTableInternal(lfirst_oid(l), cmds, false);
   17383           40 :         EventTriggerAlterTableEnd();
   17384              :     }
   17385              : 
   17386           20 :     return new_tablespaceoid;
   17387              : }
   17388              : 
   17389              : static void
   17390           41 : index_copy_data(Relation rel, RelFileLocator newrlocator)
   17391              : {
   17392              :     SMgrRelation dstrel;
   17393              : 
   17394              :     /*
   17395              :      * Since we copy the file directly without looking at the shared buffers,
   17396              :      * we'd better first flush out any pages of the source relation that are
   17397              :      * in shared buffers.  We assume no new changes will be made while we are
   17398              :      * holding exclusive lock on the rel.
   17399              :      */
   17400           41 :     FlushRelationBuffers(rel);
   17401              : 
   17402              :     /*
   17403              :      * Create and copy all forks of the relation, and schedule unlinking of
   17404              :      * old physical files.
   17405              :      *
   17406              :      * NOTE: any conflict in relfilenumber value will be caught in
   17407              :      * RelationCreateStorage().
   17408              :      */
   17409           41 :     dstrel = RelationCreateStorage(newrlocator, rel->rd_rel->relpersistence, true);
   17410              : 
   17411              :     /* copy main fork */
   17412           41 :     RelationCopyStorage(RelationGetSmgr(rel), dstrel, MAIN_FORKNUM,
   17413           41 :                         rel->rd_rel->relpersistence);
   17414              : 
   17415              :     /* copy those extra forks that exist */
   17416           41 :     for (ForkNumber forkNum = MAIN_FORKNUM + 1;
   17417          164 :          forkNum <= MAX_FORKNUM; forkNum++)
   17418              :     {
   17419          123 :         if (smgrexists(RelationGetSmgr(rel), forkNum))
   17420              :         {
   17421            0 :             smgrcreate(dstrel, forkNum, false);
   17422              : 
   17423              :             /*
   17424              :              * WAL log creation if the relation is persistent, or this is the
   17425              :              * init fork of an unlogged relation.
   17426              :              */
   17427            0 :             if (RelationIsPermanent(rel) ||
   17428            0 :                 (rel->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED &&
   17429              :                  forkNum == INIT_FORKNUM))
   17430            0 :                 log_smgrcreate(&newrlocator, forkNum);
   17431            0 :             RelationCopyStorage(RelationGetSmgr(rel), dstrel, forkNum,
   17432            0 :                                 rel->rd_rel->relpersistence);
   17433              :         }
   17434              :     }
   17435              : 
   17436              :     /* drop old relation, and close new one */
   17437           41 :     RelationDropStorage(rel);
   17438           41 :     smgrclose(dstrel);
   17439           41 : }
   17440              : 
   17441              : /*
   17442              :  * ALTER TABLE ENABLE/DISABLE TRIGGER
   17443              :  *
   17444              :  * We just pass this off to trigger.c.
   17445              :  */
   17446              : static void
   17447          191 : ATExecEnableDisableTrigger(Relation rel, const char *trigname,
   17448              :                            char fires_when, bool skip_system, bool recurse,
   17449              :                            LOCKMODE lockmode)
   17450              : {
   17451          191 :     EnableDisableTrigger(rel, trigname, InvalidOid,
   17452              :                          fires_when, skip_system, recurse,
   17453              :                          lockmode);
   17454              : 
   17455          191 :     InvokeObjectPostAlterHook(RelationRelationId,
   17456              :                               RelationGetRelid(rel), 0);
   17457          191 : }
   17458              : 
   17459              : /*
   17460              :  * ALTER TABLE ENABLE/DISABLE RULE
   17461              :  *
   17462              :  * We just pass this off to rewriteDefine.c.
   17463              :  */
   17464              : static void
   17465           29 : ATExecEnableDisableRule(Relation rel, const char *rulename,
   17466              :                         char fires_when, LOCKMODE lockmode)
   17467              : {
   17468           29 :     EnableDisableRule(rel, rulename, fires_when);
   17469              : 
   17470           29 :     InvokeObjectPostAlterHook(RelationRelationId,
   17471              :                               RelationGetRelid(rel), 0);
   17472           29 : }
   17473              : 
   17474              : /*
   17475              :  * Preparation phase of [NO] INHERIT
   17476              :  *
   17477              :  * Check the relation defined as a child.
   17478              :  */
   17479              : static void
   17480          378 : ATPrepChangeInherit(Relation child_rel)
   17481              : {
   17482          378 :     if (child_rel->rd_rel->reloftype)
   17483            8 :         ereport(ERROR,
   17484              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   17485              :                  errmsg("cannot change inheritance of typed table")));
   17486              : 
   17487          370 :     if (child_rel->rd_rel->relispartition)
   17488           12 :         ereport(ERROR,
   17489              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   17490              :                  errmsg("cannot change inheritance of a partition")));
   17491          358 : }
   17492              : 
   17493              : /*
   17494              :  * ALTER TABLE INHERIT
   17495              :  *
   17496              :  * Return the address of the new parent relation.
   17497              :  */
   17498              : static ObjectAddress
   17499          289 : ATExecAddInherit(Relation child_rel, RangeVar *parent, LOCKMODE lockmode)
   17500              : {
   17501              :     Relation    parent_rel;
   17502              :     List       *children;
   17503              :     ObjectAddress address;
   17504              :     const char *trigger_name;
   17505              : 
   17506              :     /*
   17507              :      * A self-exclusive lock is needed here.  See the similar case in
   17508              :      * MergeAttributes() for a full explanation.
   17509              :      */
   17510          289 :     parent_rel = table_openrv(parent, ShareUpdateExclusiveLock);
   17511              : 
   17512              :     /*
   17513              :      * Must be owner of both parent and child -- child was checked by
   17514              :      * ATSimplePermissions call in ATPrepCmd
   17515              :      */
   17516          289 :     ATSimplePermissions(AT_AddInherit, parent_rel,
   17517              :                         ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
   17518              : 
   17519              :     /* Permanent rels cannot inherit from temporary ones */
   17520          289 :     if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
   17521            4 :         child_rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
   17522            0 :         ereport(ERROR,
   17523              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   17524              :                  errmsg("cannot inherit from temporary relation \"%s\"",
   17525              :                         RelationGetRelationName(parent_rel))));
   17526              : 
   17527              :     /* If parent rel is temp, it must belong to this session */
   17528          289 :     if (RELATION_IS_OTHER_TEMP(parent_rel))
   17529            0 :         ereport(ERROR,
   17530              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   17531              :                  errmsg("cannot inherit from temporary relation of another session")));
   17532              : 
   17533              :     /* Ditto for the child */
   17534          289 :     if (RELATION_IS_OTHER_TEMP(child_rel))
   17535            0 :         ereport(ERROR,
   17536              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   17537              :                  errmsg("cannot inherit to temporary relation of another session")));
   17538              : 
   17539              :     /* Prevent partitioned tables from becoming inheritance parents */
   17540          289 :     if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
   17541            4 :         ereport(ERROR,
   17542              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   17543              :                  errmsg("cannot inherit from partitioned table \"%s\"",
   17544              :                         parent->relname)));
   17545              : 
   17546              :     /* Likewise for partitions */
   17547          285 :     if (parent_rel->rd_rel->relispartition)
   17548            4 :         ereport(ERROR,
   17549              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   17550              :                  errmsg("cannot inherit from a partition")));
   17551              : 
   17552              :     /*
   17553              :      * Prevent circularity by seeing if proposed parent inherits from child.
   17554              :      * (In particular, this disallows making a rel inherit from itself.)
   17555              :      *
   17556              :      * This is not completely bulletproof because of race conditions: in
   17557              :      * multi-level inheritance trees, someone else could concurrently be
   17558              :      * making another inheritance link that closes the loop but does not join
   17559              :      * either of the rels we have locked.  Preventing that seems to require
   17560              :      * exclusive locks on the entire inheritance tree, which is a cure worse
   17561              :      * than the disease.  find_all_inheritors() will cope with circularity
   17562              :      * anyway, so don't sweat it too much.
   17563              :      *
   17564              :      * We use weakest lock we can on child's children, namely AccessShareLock.
   17565              :      */
   17566          281 :     children = find_all_inheritors(RelationGetRelid(child_rel),
   17567              :                                    AccessShareLock, NULL);
   17568              : 
   17569          281 :     if (list_member_oid(children, RelationGetRelid(parent_rel)))
   17570            8 :         ereport(ERROR,
   17571              :                 (errcode(ERRCODE_DUPLICATE_TABLE),
   17572              :                  errmsg("circular inheritance not allowed"),
   17573              :                  errdetail("\"%s\" is already a child of \"%s\".",
   17574              :                            parent->relname,
   17575              :                            RelationGetRelationName(child_rel))));
   17576              : 
   17577              :     /*
   17578              :      * If child_rel has row-level triggers with transition tables, we
   17579              :      * currently don't allow it to become an inheritance child.  See also
   17580              :      * prohibitions in ATExecAttachPartition() and CreateTrigger().
   17581              :      */
   17582          273 :     trigger_name = FindTriggerIncompatibleWithInheritance(child_rel->trigdesc);
   17583          273 :     if (trigger_name != NULL)
   17584            4 :         ereport(ERROR,
   17585              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   17586              :                  errmsg("trigger \"%s\" prevents table \"%s\" from becoming an inheritance child",
   17587              :                         trigger_name, RelationGetRelationName(child_rel)),
   17588              :                  errdetail("ROW triggers with transition tables are not supported in inheritance hierarchies.")));
   17589              : 
   17590              :     /* OK to create inheritance */
   17591          269 :     CreateInheritance(child_rel, parent_rel, false);
   17592              : 
   17593          209 :     ObjectAddressSet(address, RelationRelationId,
   17594              :                      RelationGetRelid(parent_rel));
   17595              : 
   17596              :     /* keep our lock on the parent relation until commit */
   17597          209 :     table_close(parent_rel, NoLock);
   17598              : 
   17599          209 :     return address;
   17600              : }
   17601              : 
   17602              : /*
   17603              :  * CreateInheritance
   17604              :  *      Catalog manipulation portion of creating inheritance between a child
   17605              :  *      table and a parent table.
   17606              :  *
   17607              :  * This verifies that all the columns and check constraints of the parent
   17608              :  * appear in the child and that they have the same data types and expressions.
   17609              :  *
   17610              :  * Common to ATExecAddInherit() and ATExecAttachPartition().
   17611              :  */
   17612              : static void
   17613         2175 : CreateInheritance(Relation child_rel, Relation parent_rel, bool ispartition)
   17614              : {
   17615              :     Relation    catalogRelation;
   17616              :     SysScanDesc scan;
   17617              :     ScanKeyData key;
   17618              :     HeapTuple   inheritsTuple;
   17619              :     int32       inhseqno;
   17620              : 
   17621              :     /* Note: get RowExclusiveLock because we will write pg_inherits below. */
   17622         2175 :     catalogRelation = table_open(InheritsRelationId, RowExclusiveLock);
   17623              : 
   17624              :     /*
   17625              :      * Check for duplicates in the list of parents, and determine the highest
   17626              :      * inhseqno already present; we'll use the next one for the new parent.
   17627              :      * Also, if proposed child is a partition, it cannot already be
   17628              :      * inheriting.
   17629              :      *
   17630              :      * Note: we do not reject the case where the child already inherits from
   17631              :      * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
   17632              :      */
   17633         2175 :     ScanKeyInit(&key,
   17634              :                 Anum_pg_inherits_inhrelid,
   17635              :                 BTEqualStrategyNumber, F_OIDEQ,
   17636              :                 ObjectIdGetDatum(RelationGetRelid(child_rel)));
   17637         2175 :     scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
   17638              :                               true, NULL, 1, &key);
   17639              : 
   17640              :     /* inhseqno sequences start at 1 */
   17641         2175 :     inhseqno = 0;
   17642         2218 :     while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
   17643              :     {
   17644           47 :         Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
   17645              : 
   17646           47 :         if (inh->inhparent == RelationGetRelid(parent_rel))
   17647            4 :             ereport(ERROR,
   17648              :                     (errcode(ERRCODE_DUPLICATE_TABLE),
   17649              :                      errmsg("relation \"%s\" would be inherited from more than once",
   17650              :                             RelationGetRelationName(parent_rel))));
   17651              : 
   17652           43 :         if (inh->inhseqno > inhseqno)
   17653           43 :             inhseqno = inh->inhseqno;
   17654              :     }
   17655         2171 :     systable_endscan(scan);
   17656              : 
   17657              :     /* Match up the columns and bump attinhcount as needed */
   17658         2171 :     MergeAttributesIntoExisting(child_rel, parent_rel, ispartition);
   17659              : 
   17660              :     /* Match up the constraints and bump coninhcount as needed */
   17661         2083 :     MergeConstraintsIntoExisting(child_rel, parent_rel);
   17662              : 
   17663              :     /*
   17664              :      * OK, it looks valid.  Make the catalog entries that show inheritance.
   17665              :      */
   17666         2043 :     StoreCatalogInheritance1(RelationGetRelid(child_rel),
   17667              :                              RelationGetRelid(parent_rel),
   17668              :                              inhseqno + 1,
   17669              :                              catalogRelation,
   17670         2043 :                              parent_rel->rd_rel->relkind ==
   17671              :                              RELKIND_PARTITIONED_TABLE);
   17672              : 
   17673              :     /* Now we're done with pg_inherits */
   17674         2043 :     table_close(catalogRelation, RowExclusiveLock);
   17675         2043 : }
   17676              : 
   17677              : /*
   17678              :  * Obtain the source-text form of the constraint expression for a check
   17679              :  * constraint, given its pg_constraint tuple
   17680              :  */
   17681              : static char *
   17682          272 : decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
   17683              : {
   17684              :     Form_pg_constraint con;
   17685              :     bool        isnull;
   17686              :     Datum       attr;
   17687              :     Datum       expr;
   17688              : 
   17689          272 :     con = (Form_pg_constraint) GETSTRUCT(contup);
   17690          272 :     attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
   17691          272 :     if (isnull)
   17692            0 :         elog(ERROR, "null conbin for constraint %u", con->oid);
   17693              : 
   17694          272 :     expr = DirectFunctionCall2(pg_get_expr, attr,
   17695              :                                ObjectIdGetDatum(con->conrelid));
   17696          272 :     return TextDatumGetCString(expr);
   17697              : }
   17698              : 
   17699              : /*
   17700              :  * Determine whether two check constraints are functionally equivalent
   17701              :  *
   17702              :  * The test we apply is to see whether they reverse-compile to the same
   17703              :  * source string.  This insulates us from issues like whether attributes
   17704              :  * have the same physical column numbers in parent and child relations.
   17705              :  *
   17706              :  * Note that we ignore enforceability as there are cases where constraints
   17707              :  * with differing enforceability are allowed.
   17708              :  */
   17709              : static bool
   17710          136 : constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc)
   17711              : {
   17712          136 :     Form_pg_constraint acon = (Form_pg_constraint) GETSTRUCT(a);
   17713          136 :     Form_pg_constraint bcon = (Form_pg_constraint) GETSTRUCT(b);
   17714              : 
   17715          136 :     if (acon->condeferrable != bcon->condeferrable ||
   17716          136 :         acon->condeferred != bcon->condeferred ||
   17717          136 :         strcmp(decompile_conbin(a, tupleDesc),
   17718          136 :                decompile_conbin(b, tupleDesc)) != 0)
   17719            4 :         return false;
   17720              :     else
   17721          132 :         return true;
   17722              : }
   17723              : 
   17724              : /*
   17725              :  * Check columns in child table match up with columns in parent, and increment
   17726              :  * their attinhcount.
   17727              :  *
   17728              :  * Called by CreateInheritance
   17729              :  *
   17730              :  * Currently all parent columns must be found in child. Missing columns are an
   17731              :  * error.  One day we might consider creating new columns like CREATE TABLE
   17732              :  * does.  However, that is widely unpopular --- in the common use case of
   17733              :  * partitioned tables it's a foot-gun.
   17734              :  *
   17735              :  * The data type must match exactly. If the parent column is NOT NULL then
   17736              :  * the child must be as well. Defaults are not compared, however.
   17737              :  */
   17738              : static void
   17739         2171 : MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition)
   17740              : {
   17741              :     Relation    attrrel;
   17742              :     TupleDesc   parent_desc;
   17743              : 
   17744         2171 :     attrrel = table_open(AttributeRelationId, RowExclusiveLock);
   17745         2171 :     parent_desc = RelationGetDescr(parent_rel);
   17746              : 
   17747         7159 :     for (AttrNumber parent_attno = 1; parent_attno <= parent_desc->natts; parent_attno++)
   17748              :     {
   17749         5076 :         Form_pg_attribute parent_att = TupleDescAttr(parent_desc, parent_attno - 1);
   17750         5076 :         char       *parent_attname = NameStr(parent_att->attname);
   17751              :         HeapTuple   tuple;
   17752              : 
   17753              :         /* Ignore dropped columns in the parent. */
   17754         5076 :         if (parent_att->attisdropped)
   17755          180 :             continue;
   17756              : 
   17757              :         /* Find same column in child (matching on column name). */
   17758         4896 :         tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel), parent_attname);
   17759         4896 :         if (HeapTupleIsValid(tuple))
   17760              :         {
   17761         4888 :             Form_pg_attribute child_att = (Form_pg_attribute) GETSTRUCT(tuple);
   17762              : 
   17763         4888 :             if (parent_att->atttypid != child_att->atttypid ||
   17764         4884 :                 parent_att->atttypmod != child_att->atttypmod)
   17765            8 :                 ereport(ERROR,
   17766              :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
   17767              :                          errmsg("child table \"%s\" has different type for column \"%s\"",
   17768              :                                 RelationGetRelationName(child_rel), parent_attname)));
   17769              : 
   17770         4880 :             if (parent_att->attcollation != child_att->attcollation)
   17771            4 :                 ereport(ERROR,
   17772              :                         (errcode(ERRCODE_COLLATION_MISMATCH),
   17773              :                          errmsg("child table \"%s\" has different collation for column \"%s\"",
   17774              :                                 RelationGetRelationName(child_rel), parent_attname)));
   17775              : 
   17776              :             /*
   17777              :              * If the parent has a not-null constraint that's not NO INHERIT,
   17778              :              * make sure the child has one too.
   17779              :              *
   17780              :              * Other constraints are checked elsewhere.
   17781              :              */
   17782         4876 :             if (parent_att->attnotnull && !child_att->attnotnull)
   17783              :             {
   17784              :                 HeapTuple   contup;
   17785              : 
   17786           32 :                 contup = findNotNullConstraintAttnum(RelationGetRelid(parent_rel),
   17787           32 :                                                      parent_att->attnum);
   17788           32 :                 if (HeapTupleIsValid(contup) &&
   17789           32 :                     !((Form_pg_constraint) GETSTRUCT(contup))->connoinherit)
   17790           20 :                     ereport(ERROR,
   17791              :                             errcode(ERRCODE_DATATYPE_MISMATCH),
   17792              :                             errmsg("column \"%s\" in child table \"%s\" must be marked NOT NULL",
   17793              :                                    parent_attname, RelationGetRelationName(child_rel)));
   17794              :             }
   17795              : 
   17796              :             /*
   17797              :              * Child column must be generated if and only if parent column is.
   17798              :              */
   17799         4856 :             if (parent_att->attgenerated && !child_att->attgenerated)
   17800           24 :                 ereport(ERROR,
   17801              :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
   17802              :                          errmsg("column \"%s\" in child table must be a generated column", parent_attname)));
   17803         4832 :             if (child_att->attgenerated && !parent_att->attgenerated)
   17804           16 :                 ereport(ERROR,
   17805              :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
   17806              :                          errmsg("column \"%s\" in child table must not be a generated column", parent_attname)));
   17807              : 
   17808         4816 :             if (parent_att->attgenerated && child_att->attgenerated && child_att->attgenerated != parent_att->attgenerated)
   17809            8 :                 ereport(ERROR,
   17810              :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
   17811              :                          errmsg("column \"%s\" inherits from generated column of different kind", parent_attname),
   17812              :                          errdetail("Parent column is %s, child column is %s.",
   17813              :                                    parent_att->attgenerated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL",
   17814              :                                    child_att->attgenerated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL")));
   17815              : 
   17816              :             /*
   17817              :              * Regular inheritance children are independent enough not to
   17818              :              * inherit identity columns.  But partitions are integral part of
   17819              :              * a partitioned table and inherit identity column.
   17820              :              */
   17821         4808 :             if (ispartition)
   17822         4331 :                 child_att->attidentity = parent_att->attidentity;
   17823              : 
   17824              :             /*
   17825              :              * OK, bump the child column's inheritance count.  (If we fail
   17826              :              * later on, this change will just roll back.)
   17827              :              */
   17828         4808 :             if (pg_add_s16_overflow(child_att->attinhcount, 1,
   17829              :                                     &child_att->attinhcount))
   17830            0 :                 ereport(ERROR,
   17831              :                         errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
   17832              :                         errmsg("too many inheritance parents"));
   17833              : 
   17834              :             /*
   17835              :              * In case of partitions, we must enforce that value of attislocal
   17836              :              * is same in all partitions. (Note: there are only inherited
   17837              :              * attributes in partitions)
   17838              :              */
   17839         4808 :             if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
   17840              :             {
   17841              :                 Assert(child_att->attinhcount == 1);
   17842         4331 :                 child_att->attislocal = false;
   17843              :             }
   17844              : 
   17845         4808 :             CatalogTupleUpdate(attrrel, &tuple->t_self, tuple);
   17846         4808 :             heap_freetuple(tuple);
   17847              :         }
   17848              :         else
   17849              :         {
   17850            8 :             ereport(ERROR,
   17851              :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
   17852              :                      errmsg("child table is missing column \"%s\"", parent_attname)));
   17853              :         }
   17854              :     }
   17855              : 
   17856         2083 :     table_close(attrrel, RowExclusiveLock);
   17857         2083 : }
   17858              : 
   17859              : /*
   17860              :  * Check constraints in child table match up with constraints in parent,
   17861              :  * and increment their coninhcount.
   17862              :  *
   17863              :  * Constraints that are marked ONLY in the parent are ignored.
   17864              :  *
   17865              :  * Called by CreateInheritance
   17866              :  *
   17867              :  * Currently all constraints in parent must be present in the child. One day we
   17868              :  * may consider adding new constraints like CREATE TABLE does.
   17869              :  *
   17870              :  * XXX This is O(N^2) which may be an issue with tables with hundreds of
   17871              :  * constraints. As long as tables have more like 10 constraints it shouldn't be
   17872              :  * a problem though. Even 100 constraints ought not be the end of the world.
   17873              :  *
   17874              :  * XXX See MergeWithExistingConstraint too if you change this code.
   17875              :  */
   17876              : static void
   17877         2083 : MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
   17878              : {
   17879              :     Relation    constraintrel;
   17880              :     SysScanDesc parent_scan;
   17881              :     ScanKeyData parent_key;
   17882              :     HeapTuple   parent_tuple;
   17883         2083 :     Oid         parent_relid = RelationGetRelid(parent_rel);
   17884              :     AttrMap    *attmap;
   17885              : 
   17886         2083 :     constraintrel = table_open(ConstraintRelationId, RowExclusiveLock);
   17887              : 
   17888              :     /* Outer loop scans through the parent's constraint definitions */
   17889         2083 :     ScanKeyInit(&parent_key,
   17890              :                 Anum_pg_constraint_conrelid,
   17891              :                 BTEqualStrategyNumber, F_OIDEQ,
   17892              :                 ObjectIdGetDatum(parent_relid));
   17893         2083 :     parent_scan = systable_beginscan(constraintrel, ConstraintRelidTypidNameIndexId,
   17894              :                                      true, NULL, 1, &parent_key);
   17895              : 
   17896         2083 :     attmap = build_attrmap_by_name(RelationGetDescr(parent_rel),
   17897              :                                    RelationGetDescr(child_rel),
   17898              :                                    true);
   17899              : 
   17900         3682 :     while (HeapTupleIsValid(parent_tuple = systable_getnext(parent_scan)))
   17901              :     {
   17902         1639 :         Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(parent_tuple);
   17903              :         SysScanDesc child_scan;
   17904              :         ScanKeyData child_key;
   17905              :         HeapTuple   child_tuple;
   17906              :         AttrNumber  parent_attno;
   17907         1639 :         bool        found = false;
   17908              : 
   17909         1639 :         if (parent_con->contype != CONSTRAINT_CHECK &&
   17910         1471 :             parent_con->contype != CONSTRAINT_NOTNULL)
   17911          762 :             continue;
   17912              : 
   17913              :         /* if the parent's constraint is marked NO INHERIT, it's not inherited */
   17914          909 :         if (parent_con->connoinherit)
   17915           32 :             continue;
   17916              : 
   17917          877 :         if (parent_con->contype == CONSTRAINT_NOTNULL)
   17918          725 :             parent_attno = extractNotNullColumn(parent_tuple);
   17919              :         else
   17920          152 :             parent_attno = InvalidAttrNumber;
   17921              : 
   17922              :         /* Search for a child constraint matching this one */
   17923          877 :         ScanKeyInit(&child_key,
   17924              :                     Anum_pg_constraint_conrelid,
   17925              :                     BTEqualStrategyNumber, F_OIDEQ,
   17926              :                     ObjectIdGetDatum(RelationGetRelid(child_rel)));
   17927          877 :         child_scan = systable_beginscan(constraintrel, ConstraintRelidTypidNameIndexId,
   17928              :                                         true, NULL, 1, &child_key);
   17929              : 
   17930         1402 :         while (HeapTupleIsValid(child_tuple = systable_getnext(child_scan)))
   17931              :         {
   17932         1386 :             Form_pg_constraint child_con = (Form_pg_constraint) GETSTRUCT(child_tuple);
   17933              :             HeapTuple   child_copy;
   17934              : 
   17935         1386 :             if (child_con->contype != parent_con->contype)
   17936          274 :                 continue;
   17937              : 
   17938              :             /*
   17939              :              * CHECK constraint are matched by constraint name, NOT NULL ones
   17940              :              * by attribute number.
   17941              :              */
   17942         1112 :             if (child_con->contype == CONSTRAINT_CHECK)
   17943              :             {
   17944          262 :                 if (strcmp(NameStr(parent_con->conname),
   17945          199 :                            NameStr(child_con->conname)) != 0)
   17946           63 :                     continue;
   17947              :             }
   17948          913 :             else if (child_con->contype == CONSTRAINT_NOTNULL)
   17949              :             {
   17950              :                 Form_pg_attribute parent_attr;
   17951              :                 Form_pg_attribute child_attr;
   17952              :                 AttrNumber  child_attno;
   17953              : 
   17954          913 :                 parent_attr = TupleDescAttr(parent_rel->rd_att, parent_attno - 1);
   17955          913 :                 child_attno = extractNotNullColumn(child_tuple);
   17956          913 :                 if (parent_attno != attmap->attnums[child_attno - 1])
   17957          188 :                     continue;
   17958              : 
   17959          725 :                 child_attr = TupleDescAttr(child_rel->rd_att, child_attno - 1);
   17960              :                 /* there shouldn't be constraints on dropped columns */
   17961          725 :                 if (parent_attr->attisdropped || child_attr->attisdropped)
   17962            0 :                     elog(ERROR, "found not-null constraint on dropped columns");
   17963              :             }
   17964              : 
   17965          861 :             if (child_con->contype == CONSTRAINT_CHECK &&
   17966          136 :                 !constraints_equivalent(parent_tuple, child_tuple, RelationGetDescr(constraintrel)))
   17967            4 :                 ereport(ERROR,
   17968              :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
   17969              :                          errmsg("child table \"%s\" has different definition for check constraint \"%s\"",
   17970              :                                 RelationGetRelationName(child_rel), NameStr(parent_con->conname))));
   17971              : 
   17972              :             /*
   17973              :              * If the child constraint is "no inherit" then cannot merge
   17974              :              */
   17975          857 :             if (child_con->connoinherit)
   17976            8 :                 ereport(ERROR,
   17977              :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
   17978              :                          errmsg("constraint \"%s\" conflicts with non-inherited constraint on child table \"%s\"",
   17979              :                                 NameStr(child_con->conname), RelationGetRelationName(child_rel))));
   17980              : 
   17981              :             /*
   17982              :              * If the child constraint is "not valid" then cannot merge with a
   17983              :              * valid parent constraint
   17984              :              */
   17985          849 :             if (parent_con->convalidated && child_con->conenforced &&
   17986          769 :                 !child_con->convalidated)
   17987            8 :                 ereport(ERROR,
   17988              :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
   17989              :                          errmsg("constraint \"%s\" conflicts with NOT VALID constraint on child table \"%s\"",
   17990              :                                 NameStr(child_con->conname), RelationGetRelationName(child_rel))));
   17991              : 
   17992              :             /*
   17993              :              * A NOT ENFORCED child constraint cannot be merged with an
   17994              :              * ENFORCED parent constraint. However, the reverse is allowed,
   17995              :              * where the child constraint is ENFORCED.
   17996              :              */
   17997          841 :             if (parent_con->conenforced && !child_con->conenforced)
   17998            4 :                 ereport(ERROR,
   17999              :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
   18000              :                          errmsg("constraint \"%s\" conflicts with NOT ENFORCED constraint on child table \"%s\"",
   18001              :                                 NameStr(child_con->conname), RelationGetRelationName(child_rel))));
   18002              : 
   18003              :             /*
   18004              :              * OK, bump the child constraint's inheritance count.  (If we fail
   18005              :              * later on, this change will just roll back.)
   18006              :              */
   18007          837 :             child_copy = heap_copytuple(child_tuple);
   18008          837 :             child_con = (Form_pg_constraint) GETSTRUCT(child_copy);
   18009              : 
   18010          837 :             if (pg_add_s16_overflow(child_con->coninhcount, 1,
   18011              :                                     &child_con->coninhcount))
   18012            0 :                 ereport(ERROR,
   18013              :                         errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
   18014              :                         errmsg("too many inheritance parents"));
   18015              : 
   18016              :             /*
   18017              :              * In case of partitions, an inherited constraint must be
   18018              :              * inherited only once since it cannot have multiple parents and
   18019              :              * it is never considered local.
   18020              :              */
   18021          837 :             if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
   18022              :             {
   18023              :                 Assert(child_con->coninhcount == 1);
   18024          746 :                 child_con->conislocal = false;
   18025              :             }
   18026              : 
   18027          837 :             CatalogTupleUpdate(constraintrel, &child_copy->t_self, child_copy);
   18028          837 :             heap_freetuple(child_copy);
   18029              : 
   18030          837 :             found = true;
   18031          837 :             break;
   18032              :         }
   18033              : 
   18034          853 :         systable_endscan(child_scan);
   18035              : 
   18036          853 :         if (!found)
   18037              :         {
   18038           16 :             if (parent_con->contype == CONSTRAINT_NOTNULL)
   18039            0 :                 ereport(ERROR,
   18040              :                         errcode(ERRCODE_DATATYPE_MISMATCH),
   18041              :                         errmsg("column \"%s\" in child table \"%s\" must be marked NOT NULL",
   18042              :                                get_attname(parent_relid,
   18043              :                                            extractNotNullColumn(parent_tuple),
   18044              :                                            false),
   18045              :                                RelationGetRelationName(child_rel)));
   18046              : 
   18047           16 :             ereport(ERROR,
   18048              :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
   18049              :                      errmsg("child table is missing constraint \"%s\"",
   18050              :                             NameStr(parent_con->conname))));
   18051              :         }
   18052              :     }
   18053              : 
   18054         2043 :     systable_endscan(parent_scan);
   18055         2043 :     table_close(constraintrel, RowExclusiveLock);
   18056         2043 : }
   18057              : 
   18058              : /*
   18059              :  * ALTER TABLE NO INHERIT
   18060              :  *
   18061              :  * Return value is the address of the relation that is no longer parent.
   18062              :  */
   18063              : static ObjectAddress
   18064           69 : ATExecDropInherit(Relation rel, RangeVar *parent, LOCKMODE lockmode)
   18065              : {
   18066              :     ObjectAddress address;
   18067              :     Relation    parent_rel;
   18068              : 
   18069              :     /*
   18070              :      * AccessShareLock on the parent is probably enough, seeing that DROP
   18071              :      * TABLE doesn't lock parent tables at all.  We need some lock since we'll
   18072              :      * be inspecting the parent's schema.
   18073              :      */
   18074           69 :     parent_rel = table_openrv(parent, AccessShareLock);
   18075              : 
   18076              :     /*
   18077              :      * We don't bother to check ownership of the parent table --- ownership of
   18078              :      * the child is presumed enough rights.
   18079              :      */
   18080              : 
   18081              :     /* Off to RemoveInheritance() where most of the work happens */
   18082           69 :     RemoveInheritance(rel, parent_rel, false);
   18083              : 
   18084           65 :     ObjectAddressSet(address, RelationRelationId,
   18085              :                      RelationGetRelid(parent_rel));
   18086              : 
   18087              :     /* keep our lock on the parent relation until commit */
   18088           65 :     table_close(parent_rel, NoLock);
   18089              : 
   18090           65 :     return address;
   18091              : }
   18092              : 
   18093              : /*
   18094              :  * MarkInheritDetached
   18095              :  *
   18096              :  * Set inhdetachpending for a partition, for ATExecDetachPartition
   18097              :  * in concurrent mode.  While at it, verify that no other partition is
   18098              :  * already pending detach.
   18099              :  */
   18100              : static void
   18101           75 : MarkInheritDetached(Relation child_rel, Relation parent_rel)
   18102              : {
   18103              :     Relation    catalogRelation;
   18104              :     SysScanDesc scan;
   18105              :     ScanKeyData key;
   18106              :     HeapTuple   inheritsTuple;
   18107           75 :     bool        found = false;
   18108              : 
   18109              :     Assert(parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
   18110              : 
   18111              :     /*
   18112              :      * Find pg_inherits entries by inhparent.  (We need to scan them all in
   18113              :      * order to verify that no other partition is pending detach.)
   18114              :      */
   18115           75 :     catalogRelation = table_open(InheritsRelationId, RowExclusiveLock);
   18116           75 :     ScanKeyInit(&key,
   18117              :                 Anum_pg_inherits_inhparent,
   18118              :                 BTEqualStrategyNumber, F_OIDEQ,
   18119              :                 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
   18120           75 :     scan = systable_beginscan(catalogRelation, InheritsParentIndexId,
   18121              :                               true, NULL, 1, &key);
   18122              : 
   18123          294 :     while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
   18124              :     {
   18125              :         Form_pg_inherits inhForm;
   18126              : 
   18127          145 :         inhForm = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
   18128          145 :         if (inhForm->inhdetachpending)
   18129            1 :             ereport(ERROR,
   18130              :                     errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
   18131              :                     errmsg("partition \"%s\" already pending detach in partitioned table \"%s.%s\"",
   18132              :                            get_rel_name(inhForm->inhrelid),
   18133              :                            get_namespace_name(parent_rel->rd_rel->relnamespace),
   18134              :                            RelationGetRelationName(parent_rel)),
   18135              :                     errhint("Use ALTER TABLE ... DETACH PARTITION ... FINALIZE to complete the pending detach operation."));
   18136              : 
   18137          144 :         if (inhForm->inhrelid == RelationGetRelid(child_rel))
   18138              :         {
   18139              :             HeapTuple   newtup;
   18140              : 
   18141           74 :             newtup = heap_copytuple(inheritsTuple);
   18142           74 :             ((Form_pg_inherits) GETSTRUCT(newtup))->inhdetachpending = true;
   18143              : 
   18144           74 :             CatalogTupleUpdate(catalogRelation,
   18145           74 :                                &inheritsTuple->t_self,
   18146              :                                newtup);
   18147           74 :             found = true;
   18148           74 :             heap_freetuple(newtup);
   18149              :             /* keep looking, to ensure we catch others pending detach */
   18150              :         }
   18151              :     }
   18152              : 
   18153              :     /* Done */
   18154           74 :     systable_endscan(scan);
   18155           74 :     table_close(catalogRelation, RowExclusiveLock);
   18156              : 
   18157           74 :     if (!found)
   18158            0 :         ereport(ERROR,
   18159              :                 (errcode(ERRCODE_UNDEFINED_TABLE),
   18160              :                  errmsg("relation \"%s\" is not a partition of relation \"%s\"",
   18161              :                         RelationGetRelationName(child_rel),
   18162              :                         RelationGetRelationName(parent_rel))));
   18163           74 : }
   18164              : 
   18165              : /*
   18166              :  * RemoveInheritance
   18167              :  *
   18168              :  * Drop a parent from the child's parents. This just adjusts the attinhcount
   18169              :  * and attislocal of the columns and removes the pg_inherit and pg_depend
   18170              :  * entries.  expect_detached is passed down to DeleteInheritsTuple, q.v..
   18171              :  *
   18172              :  * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
   18173              :  * up attislocal stays true, which means if a child is ever removed from a
   18174              :  * parent then its columns will never be automatically dropped which may
   18175              :  * surprise. But at least we'll never surprise by dropping columns someone
   18176              :  * isn't expecting to be dropped which would actually mean data loss.
   18177              :  *
   18178              :  * coninhcount and conislocal for inherited constraints are adjusted in
   18179              :  * exactly the same way.
   18180              :  *
   18181              :  * Common to ATExecDropInherit() and ATExecDetachPartition().
   18182              :  */
   18183              : static void
   18184          765 : RemoveInheritance(Relation child_rel, Relation parent_rel, bool expect_detached)
   18185              : {
   18186              :     Relation    catalogRelation;
   18187              :     SysScanDesc scan;
   18188              :     ScanKeyData key[3];
   18189              :     HeapTuple   attributeTuple,
   18190              :                 constraintTuple;
   18191              :     AttrMap    *attmap;
   18192              :     List       *connames;
   18193              :     List       *nncolumns;
   18194              :     bool        found;
   18195              :     bool        is_partitioning;
   18196              : 
   18197          765 :     is_partitioning = (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
   18198              : 
   18199          765 :     found = DeleteInheritsTuple(RelationGetRelid(child_rel),
   18200              :                                 RelationGetRelid(parent_rel),
   18201              :                                 expect_detached,
   18202          765 :                                 RelationGetRelationName(child_rel));
   18203          765 :     if (!found)
   18204              :     {
   18205           16 :         if (is_partitioning)
   18206           12 :             ereport(ERROR,
   18207              :                     (errcode(ERRCODE_UNDEFINED_TABLE),
   18208              :                      errmsg("relation \"%s\" is not a partition of relation \"%s\"",
   18209              :                             RelationGetRelationName(child_rel),
   18210              :                             RelationGetRelationName(parent_rel))));
   18211              :         else
   18212            4 :             ereport(ERROR,
   18213              :                     (errcode(ERRCODE_UNDEFINED_TABLE),
   18214              :                      errmsg("relation \"%s\" is not a parent of relation \"%s\"",
   18215              :                             RelationGetRelationName(parent_rel),
   18216              :                             RelationGetRelationName(child_rel))));
   18217              :     }
   18218              : 
   18219              :     /*
   18220              :      * Search through child columns looking for ones matching parent rel
   18221              :      */
   18222          749 :     catalogRelation = table_open(AttributeRelationId, RowExclusiveLock);
   18223          749 :     ScanKeyInit(&key[0],
   18224              :                 Anum_pg_attribute_attrelid,
   18225              :                 BTEqualStrategyNumber, F_OIDEQ,
   18226              :                 ObjectIdGetDatum(RelationGetRelid(child_rel)));
   18227          749 :     scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
   18228              :                               true, NULL, 1, key);
   18229         6933 :     while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
   18230              :     {
   18231         6184 :         Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
   18232              : 
   18233              :         /* Ignore if dropped or not inherited */
   18234         6184 :         if (att->attisdropped)
   18235           28 :             continue;
   18236         6156 :         if (att->attinhcount <= 0)
   18237         4522 :             continue;
   18238              : 
   18239         1634 :         if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
   18240         1634 :                                         NameStr(att->attname)))
   18241              :         {
   18242              :             /* Decrement inhcount and possibly set islocal to true */
   18243         1598 :             HeapTuple   copyTuple = heap_copytuple(attributeTuple);
   18244         1598 :             Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
   18245              : 
   18246         1598 :             copy_att->attinhcount--;
   18247         1598 :             if (copy_att->attinhcount == 0)
   18248         1578 :                 copy_att->attislocal = true;
   18249              : 
   18250         1598 :             CatalogTupleUpdate(catalogRelation, &copyTuple->t_self, copyTuple);
   18251         1598 :             heap_freetuple(copyTuple);
   18252              :         }
   18253              :     }
   18254          749 :     systable_endscan(scan);
   18255          749 :     table_close(catalogRelation, RowExclusiveLock);
   18256              : 
   18257              :     /*
   18258              :      * Likewise, find inherited check and not-null constraints and disinherit
   18259              :      * them. To do this, we first need a list of the names of the parent's
   18260              :      * check constraints.  (We cheat a bit by only checking for name matches,
   18261              :      * assuming that the expressions will match.)
   18262              :      *
   18263              :      * For NOT NULL columns, we store column numbers to match, mapping them in
   18264              :      * to the child rel's attribute numbers.
   18265              :      */
   18266          749 :     attmap = build_attrmap_by_name(RelationGetDescr(child_rel),
   18267              :                                    RelationGetDescr(parent_rel),
   18268              :                                    false);
   18269              : 
   18270          749 :     catalogRelation = table_open(ConstraintRelationId, RowExclusiveLock);
   18271          749 :     ScanKeyInit(&key[0],
   18272              :                 Anum_pg_constraint_conrelid,
   18273              :                 BTEqualStrategyNumber, F_OIDEQ,
   18274              :                 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
   18275          749 :     scan = systable_beginscan(catalogRelation, ConstraintRelidTypidNameIndexId,
   18276              :                               true, NULL, 1, key);
   18277              : 
   18278          749 :     connames = NIL;
   18279          749 :     nncolumns = NIL;
   18280              : 
   18281         1438 :     while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
   18282              :     {
   18283          689 :         Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
   18284              : 
   18285          689 :         if (con->connoinherit)
   18286          144 :             continue;
   18287              : 
   18288          545 :         if (con->contype == CONSTRAINT_CHECK)
   18289           76 :             connames = lappend(connames, pstrdup(NameStr(con->conname)));
   18290          545 :         if (con->contype == CONSTRAINT_NOTNULL)
   18291              :         {
   18292          249 :             AttrNumber  parent_attno = extractNotNullColumn(constraintTuple);
   18293              : 
   18294          249 :             nncolumns = lappend_int(nncolumns, attmap->attnums[parent_attno - 1]);
   18295              :         }
   18296              :     }
   18297              : 
   18298          749 :     systable_endscan(scan);
   18299              : 
   18300              :     /* Now scan the child's constraints to find matches */
   18301          749 :     ScanKeyInit(&key[0],
   18302              :                 Anum_pg_constraint_conrelid,
   18303              :                 BTEqualStrategyNumber, F_OIDEQ,
   18304              :                 ObjectIdGetDatum(RelationGetRelid(child_rel)));
   18305          749 :     scan = systable_beginscan(catalogRelation, ConstraintRelidTypidNameIndexId,
   18306              :                               true, NULL, 1, key);
   18307              : 
   18308         1434 :     while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
   18309              :     {
   18310          685 :         Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
   18311          685 :         bool        match = false;
   18312              : 
   18313              :         /*
   18314              :          * Match CHECK constraints by name, not-null constraints by column
   18315              :          * number, and ignore all others.
   18316              :          */
   18317          685 :         if (con->contype == CONSTRAINT_CHECK)
   18318              :         {
   18319          228 :             foreach_ptr(char, chkname, connames)
   18320              :             {
   18321           80 :                 if (con->contype == CONSTRAINT_CHECK &&
   18322           80 :                     strcmp(NameStr(con->conname), chkname) == 0)
   18323              :                 {
   18324           76 :                     match = true;
   18325           76 :                     connames = foreach_delete_current(connames, chkname);
   18326           76 :                     break;
   18327              :                 }
   18328              :             }
   18329              :         }
   18330          573 :         else if (con->contype == CONSTRAINT_NOTNULL)
   18331              :         {
   18332          289 :             AttrNumber  child_attno = extractNotNullColumn(constraintTuple);
   18333              : 
   18334          582 :             foreach_int(prevattno, nncolumns)
   18335              :             {
   18336          253 :                 if (prevattno == child_attno)
   18337              :                 {
   18338          249 :                     match = true;
   18339          249 :                     nncolumns = foreach_delete_current(nncolumns, prevattno);
   18340          249 :                     break;
   18341              :                 }
   18342              :             }
   18343              :         }
   18344              :         else
   18345          284 :             continue;
   18346              : 
   18347          401 :         if (match)
   18348              :         {
   18349              :             /* Decrement inhcount and possibly set islocal to true */
   18350          325 :             HeapTuple   copyTuple = heap_copytuple(constraintTuple);
   18351          325 :             Form_pg_constraint copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
   18352              : 
   18353          325 :             if (copy_con->coninhcount <= 0) /* shouldn't happen */
   18354            0 :                 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
   18355              :                      RelationGetRelid(child_rel), NameStr(copy_con->conname));
   18356              : 
   18357          325 :             copy_con->coninhcount--;
   18358          325 :             if (copy_con->coninhcount == 0)
   18359          313 :                 copy_con->conislocal = true;
   18360              : 
   18361          325 :             CatalogTupleUpdate(catalogRelation, &copyTuple->t_self, copyTuple);
   18362          325 :             heap_freetuple(copyTuple);
   18363              :         }
   18364              :     }
   18365              : 
   18366              :     /* We should have matched all constraints */
   18367          749 :     if (connames != NIL || nncolumns != NIL)
   18368            0 :         elog(ERROR, "%d unmatched constraints while removing inheritance from \"%s\" to \"%s\"",
   18369              :              list_length(connames) + list_length(nncolumns),
   18370              :              RelationGetRelationName(child_rel), RelationGetRelationName(parent_rel));
   18371              : 
   18372          749 :     systable_endscan(scan);
   18373          749 :     table_close(catalogRelation, RowExclusiveLock);
   18374              : 
   18375          749 :     drop_parent_dependency(RelationGetRelid(child_rel),
   18376              :                            RelationRelationId,
   18377              :                            RelationGetRelid(parent_rel),
   18378              :                            child_dependency_type(is_partitioning));
   18379              : 
   18380              :     /*
   18381              :      * Post alter hook of this inherits. Since object_access_hook doesn't take
   18382              :      * multiple object identifiers, we relay oid of parent relation using
   18383              :      * auxiliary_id argument.
   18384              :      */
   18385          749 :     InvokeObjectPostAlterHookArg(InheritsRelationId,
   18386              :                                  RelationGetRelid(child_rel), 0,
   18387              :                                  RelationGetRelid(parent_rel), false);
   18388          749 : }
   18389              : 
   18390              : /*
   18391              :  * Drop the dependency created by StoreCatalogInheritance1 (CREATE TABLE
   18392              :  * INHERITS/ALTER TABLE INHERIT -- refclassid will be RelationRelationId) or
   18393              :  * heap_create_with_catalog (CREATE TABLE OF/ALTER TABLE OF -- refclassid will
   18394              :  * be TypeRelationId).  There's no convenient way to do this, so go trawling
   18395              :  * through pg_depend.
   18396              :  */
   18397              : static void
   18398          757 : drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid,
   18399              :                        DependencyType deptype)
   18400              : {
   18401              :     Relation    catalogRelation;
   18402              :     SysScanDesc scan;
   18403              :     ScanKeyData key[3];
   18404              :     HeapTuple   depTuple;
   18405              : 
   18406          757 :     catalogRelation = table_open(DependRelationId, RowExclusiveLock);
   18407              : 
   18408          757 :     ScanKeyInit(&key[0],
   18409              :                 Anum_pg_depend_classid,
   18410              :                 BTEqualStrategyNumber, F_OIDEQ,
   18411              :                 ObjectIdGetDatum(RelationRelationId));
   18412          757 :     ScanKeyInit(&key[1],
   18413              :                 Anum_pg_depend_objid,
   18414              :                 BTEqualStrategyNumber, F_OIDEQ,
   18415              :                 ObjectIdGetDatum(relid));
   18416          757 :     ScanKeyInit(&key[2],
   18417              :                 Anum_pg_depend_objsubid,
   18418              :                 BTEqualStrategyNumber, F_INT4EQ,
   18419              :                 Int32GetDatum(0));
   18420              : 
   18421          757 :     scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
   18422              :                               NULL, 3, key);
   18423              : 
   18424         2324 :     while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
   18425              :     {
   18426         1567 :         Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
   18427              : 
   18428         1567 :         if (dep->refclassid == refclassid &&
   18429          785 :             dep->refobjid == refobjid &&
   18430          757 :             dep->refobjsubid == 0 &&
   18431          757 :             dep->deptype == deptype)
   18432          757 :             CatalogTupleDelete(catalogRelation, &depTuple->t_self);
   18433              :     }
   18434              : 
   18435          757 :     systable_endscan(scan);
   18436          757 :     table_close(catalogRelation, RowExclusiveLock);
   18437          757 : }
   18438              : 
   18439              : /*
   18440              :  * ALTER TABLE OF
   18441              :  *
   18442              :  * Attach a table to a composite type, as though it had been created with CREATE
   18443              :  * TABLE OF.  All attname, atttypid, atttypmod and attcollation must match.  The
   18444              :  * subject table must not have inheritance parents.  These restrictions ensure
   18445              :  * that you cannot create a configuration impossible with CREATE TABLE OF alone.
   18446              :  *
   18447              :  * The address of the type is returned.
   18448              :  */
   18449              : static ObjectAddress
   18450           42 : ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode)
   18451              : {
   18452           42 :     Oid         relid = RelationGetRelid(rel);
   18453              :     Type        typetuple;
   18454              :     Form_pg_type typeform;
   18455              :     Oid         typeid;
   18456              :     Relation    inheritsRelation,
   18457              :                 relationRelation;
   18458              :     SysScanDesc scan;
   18459              :     ScanKeyData key;
   18460              :     AttrNumber  table_attno,
   18461              :                 type_attno;
   18462              :     TupleDesc   typeTupleDesc,
   18463              :                 tableTupleDesc;
   18464              :     ObjectAddress tableobj,
   18465              :                 typeobj;
   18466              :     HeapTuple   classtuple;
   18467              : 
   18468              :     /* Validate the type. */
   18469           42 :     typetuple = typenameType(NULL, ofTypename, NULL);
   18470           42 :     check_of_type(typetuple);
   18471           42 :     typeform = (Form_pg_type) GETSTRUCT(typetuple);
   18472           42 :     typeid = typeform->oid;
   18473              : 
   18474              :     /* Fail if the table has any inheritance parents. */
   18475           42 :     inheritsRelation = table_open(InheritsRelationId, AccessShareLock);
   18476           42 :     ScanKeyInit(&key,
   18477              :                 Anum_pg_inherits_inhrelid,
   18478              :                 BTEqualStrategyNumber, F_OIDEQ,
   18479              :                 ObjectIdGetDatum(relid));
   18480           42 :     scan = systable_beginscan(inheritsRelation, InheritsRelidSeqnoIndexId,
   18481              :                               true, NULL, 1, &key);
   18482           42 :     if (HeapTupleIsValid(systable_getnext(scan)))
   18483            4 :         ereport(ERROR,
   18484              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   18485              :                  errmsg("typed tables cannot inherit")));
   18486           38 :     systable_endscan(scan);
   18487           38 :     table_close(inheritsRelation, AccessShareLock);
   18488              : 
   18489              :     /*
   18490              :      * Check the tuple descriptors for compatibility.  Unlike inheritance, we
   18491              :      * require that the order also match.  However, attnotnull need not match.
   18492              :      */
   18493           38 :     typeTupleDesc = lookup_rowtype_tupdesc(typeid, -1);
   18494           38 :     tableTupleDesc = RelationGetDescr(rel);
   18495           38 :     table_attno = 1;
   18496          121 :     for (type_attno = 1; type_attno <= typeTupleDesc->natts; type_attno++)
   18497              :     {
   18498              :         Form_pg_attribute type_attr,
   18499              :                     table_attr;
   18500              :         const char *type_attname,
   18501              :                    *table_attname;
   18502              : 
   18503              :         /* Get the next non-dropped type attribute. */
   18504           99 :         type_attr = TupleDescAttr(typeTupleDesc, type_attno - 1);
   18505           99 :         if (type_attr->attisdropped)
   18506           29 :             continue;
   18507           70 :         type_attname = NameStr(type_attr->attname);
   18508              : 
   18509              :         /* Get the next non-dropped table attribute. */
   18510              :         do
   18511              :         {
   18512           78 :             if (table_attno > tableTupleDesc->natts)
   18513            4 :                 ereport(ERROR,
   18514              :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
   18515              :                          errmsg("table is missing column \"%s\"",
   18516              :                                 type_attname)));
   18517           74 :             table_attr = TupleDescAttr(tableTupleDesc, table_attno - 1);
   18518           74 :             table_attno++;
   18519           74 :         } while (table_attr->attisdropped);
   18520           66 :         table_attname = NameStr(table_attr->attname);
   18521              : 
   18522              :         /* Compare name. */
   18523           66 :         if (strncmp(table_attname, type_attname, NAMEDATALEN) != 0)
   18524            4 :             ereport(ERROR,
   18525              :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
   18526              :                      errmsg("table has column \"%s\" where type requires \"%s\"",
   18527              :                             table_attname, type_attname)));
   18528              : 
   18529              :         /* Compare type. */
   18530           62 :         if (table_attr->atttypid != type_attr->atttypid ||
   18531           58 :             table_attr->atttypmod != type_attr->atttypmod ||
   18532           54 :             table_attr->attcollation != type_attr->attcollation)
   18533            8 :             ereport(ERROR,
   18534              :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
   18535              :                      errmsg("table \"%s\" has different type for column \"%s\"",
   18536              :                             RelationGetRelationName(rel), type_attname)));
   18537              :     }
   18538           22 :     ReleaseTupleDesc(typeTupleDesc);
   18539              : 
   18540              :     /* Any remaining columns at the end of the table had better be dropped. */
   18541           22 :     for (; table_attno <= tableTupleDesc->natts; table_attno++)
   18542              :     {
   18543            4 :         Form_pg_attribute table_attr = TupleDescAttr(tableTupleDesc,
   18544              :                                                      table_attno - 1);
   18545              : 
   18546            4 :         if (!table_attr->attisdropped)
   18547            4 :             ereport(ERROR,
   18548              :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
   18549              :                      errmsg("table has extra column \"%s\"",
   18550              :                             NameStr(table_attr->attname))));
   18551              :     }
   18552              : 
   18553              :     /* If the table was already typed, drop the existing dependency. */
   18554           18 :     if (rel->rd_rel->reloftype)
   18555            4 :         drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype,
   18556              :                                DEPENDENCY_NORMAL);
   18557              : 
   18558              :     /* Record a dependency on the new type. */
   18559           18 :     tableobj.classId = RelationRelationId;
   18560           18 :     tableobj.objectId = relid;
   18561           18 :     tableobj.objectSubId = 0;
   18562           18 :     typeobj.classId = TypeRelationId;
   18563           18 :     typeobj.objectId = typeid;
   18564           18 :     typeobj.objectSubId = 0;
   18565           18 :     recordDependencyOn(&tableobj, &typeobj, DEPENDENCY_NORMAL);
   18566              : 
   18567              :     /* Update pg_class.reloftype */
   18568           18 :     relationRelation = table_open(RelationRelationId, RowExclusiveLock);
   18569           18 :     classtuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
   18570           18 :     if (!HeapTupleIsValid(classtuple))
   18571            0 :         elog(ERROR, "cache lookup failed for relation %u", relid);
   18572           18 :     ((Form_pg_class) GETSTRUCT(classtuple))->reloftype = typeid;
   18573           18 :     CatalogTupleUpdate(relationRelation, &classtuple->t_self, classtuple);
   18574              : 
   18575           18 :     InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
   18576              : 
   18577           18 :     heap_freetuple(classtuple);
   18578           18 :     table_close(relationRelation, RowExclusiveLock);
   18579              : 
   18580           18 :     ReleaseSysCache(typetuple);
   18581              : 
   18582           18 :     return typeobj;
   18583              : }
   18584              : 
   18585              : /*
   18586              :  * ALTER TABLE NOT OF
   18587              :  *
   18588              :  * Detach a typed table from its originating type.  Just clear reloftype and
   18589              :  * remove the dependency.
   18590              :  */
   18591              : static void
   18592            4 : ATExecDropOf(Relation rel, LOCKMODE lockmode)
   18593              : {
   18594            4 :     Oid         relid = RelationGetRelid(rel);
   18595              :     Relation    relationRelation;
   18596              :     HeapTuple   tuple;
   18597              : 
   18598            4 :     if (!OidIsValid(rel->rd_rel->reloftype))
   18599            0 :         ereport(ERROR,
   18600              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   18601              :                  errmsg("\"%s\" is not a typed table",
   18602              :                         RelationGetRelationName(rel))));
   18603              : 
   18604              :     /*
   18605              :      * We don't bother to check ownership of the type --- ownership of the
   18606              :      * table is presumed enough rights.  No lock required on the type, either.
   18607              :      */
   18608              : 
   18609            4 :     drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype,
   18610              :                            DEPENDENCY_NORMAL);
   18611              : 
   18612              :     /* Clear pg_class.reloftype */
   18613            4 :     relationRelation = table_open(RelationRelationId, RowExclusiveLock);
   18614            4 :     tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
   18615            4 :     if (!HeapTupleIsValid(tuple))
   18616            0 :         elog(ERROR, "cache lookup failed for relation %u", relid);
   18617            4 :     ((Form_pg_class) GETSTRUCT(tuple))->reloftype = InvalidOid;
   18618            4 :     CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
   18619              : 
   18620            4 :     InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
   18621              : 
   18622            4 :     heap_freetuple(tuple);
   18623            4 :     table_close(relationRelation, RowExclusiveLock);
   18624            4 : }
   18625              : 
   18626              : /*
   18627              :  * relation_mark_replica_identity: Update a table's replica identity
   18628              :  *
   18629              :  * Iff ri_type = REPLICA_IDENTITY_INDEX, indexOid must be the Oid of a suitable
   18630              :  * index. Otherwise, it must be InvalidOid.
   18631              :  *
   18632              :  * Caller had better hold an exclusive lock on the relation, as the results
   18633              :  * of running two of these concurrently wouldn't be pretty.
   18634              :  */
   18635              : static void
   18636          281 : relation_mark_replica_identity(Relation rel, char ri_type, Oid indexOid,
   18637              :                                bool is_internal)
   18638              : {
   18639              :     Relation    pg_index;
   18640              :     Relation    pg_class;
   18641              :     HeapTuple   pg_class_tuple;
   18642              :     HeapTuple   pg_index_tuple;
   18643              :     Form_pg_class pg_class_form;
   18644              :     Form_pg_index pg_index_form;
   18645              :     ListCell   *index;
   18646              : 
   18647              :     /*
   18648              :      * Check whether relreplident has changed, and update it if so.
   18649              :      */
   18650          281 :     pg_class = table_open(RelationRelationId, RowExclusiveLock);
   18651          281 :     pg_class_tuple = SearchSysCacheCopy1(RELOID,
   18652              :                                          ObjectIdGetDatum(RelationGetRelid(rel)));
   18653          281 :     if (!HeapTupleIsValid(pg_class_tuple))
   18654            0 :         elog(ERROR, "cache lookup failed for relation \"%s\"",
   18655              :              RelationGetRelationName(rel));
   18656          281 :     pg_class_form = (Form_pg_class) GETSTRUCT(pg_class_tuple);
   18657          281 :     if (pg_class_form->relreplident != ri_type)
   18658              :     {
   18659          248 :         pg_class_form->relreplident = ri_type;
   18660          248 :         CatalogTupleUpdate(pg_class, &pg_class_tuple->t_self, pg_class_tuple);
   18661              :     }
   18662          281 :     table_close(pg_class, RowExclusiveLock);
   18663          281 :     heap_freetuple(pg_class_tuple);
   18664              : 
   18665              :     /*
   18666              :      * Update the per-index indisreplident flags correctly.
   18667              :      */
   18668          281 :     pg_index = table_open(IndexRelationId, RowExclusiveLock);
   18669          747 :     foreach(index, RelationGetIndexList(rel))
   18670              :     {
   18671          466 :         Oid         thisIndexOid = lfirst_oid(index);
   18672          466 :         bool        dirty = false;
   18673              : 
   18674          466 :         pg_index_tuple = SearchSysCacheCopy1(INDEXRELID,
   18675              :                                              ObjectIdGetDatum(thisIndexOid));
   18676          466 :         if (!HeapTupleIsValid(pg_index_tuple))
   18677            0 :             elog(ERROR, "cache lookup failed for index %u", thisIndexOid);
   18678          466 :         pg_index_form = (Form_pg_index) GETSTRUCT(pg_index_tuple);
   18679              : 
   18680          466 :         if (thisIndexOid == indexOid)
   18681              :         {
   18682              :             /* Set the bit if not already set. */
   18683          150 :             if (!pg_index_form->indisreplident)
   18684              :             {
   18685          138 :                 dirty = true;
   18686          138 :                 pg_index_form->indisreplident = true;
   18687              :             }
   18688              :         }
   18689              :         else
   18690              :         {
   18691              :             /* Unset the bit if set. */
   18692          316 :             if (pg_index_form->indisreplident)
   18693              :             {
   18694           34 :                 dirty = true;
   18695           34 :                 pg_index_form->indisreplident = false;
   18696              :             }
   18697              :         }
   18698              : 
   18699          466 :         if (dirty)
   18700              :         {
   18701          172 :             CatalogTupleUpdate(pg_index, &pg_index_tuple->t_self, pg_index_tuple);
   18702          172 :             InvokeObjectPostAlterHookArg(IndexRelationId, thisIndexOid, 0,
   18703              :                                          InvalidOid, is_internal);
   18704              : 
   18705              :             /*
   18706              :              * Invalidate the relcache for the table, so that after we commit
   18707              :              * all sessions will refresh the table's replica identity index
   18708              :              * before attempting any UPDATE or DELETE on the table.  (If we
   18709              :              * changed the table's pg_class row above, then a relcache inval
   18710              :              * is already queued due to that; but we might not have.)
   18711              :              */
   18712          172 :             CacheInvalidateRelcache(rel);
   18713              :         }
   18714          466 :         heap_freetuple(pg_index_tuple);
   18715              :     }
   18716              : 
   18717          281 :     table_close(pg_index, RowExclusiveLock);
   18718          281 : }
   18719              : 
   18720              : /*
   18721              :  * ALTER TABLE <name> REPLICA IDENTITY ...
   18722              :  */
   18723              : static void
   18724          313 : ATExecReplicaIdentity(Relation rel, ReplicaIdentityStmt *stmt, LOCKMODE lockmode)
   18725              : {
   18726              :     Oid         indexOid;
   18727              :     Relation    indexRel;
   18728              :     int         key;
   18729              : 
   18730          313 :     if (stmt->identity_type == REPLICA_IDENTITY_DEFAULT)
   18731              :     {
   18732            4 :         relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
   18733            4 :         return;
   18734              :     }
   18735          309 :     else if (stmt->identity_type == REPLICA_IDENTITY_FULL)
   18736              :     {
   18737           98 :         relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
   18738           98 :         return;
   18739              :     }
   18740          211 :     else if (stmt->identity_type == REPLICA_IDENTITY_NOTHING)
   18741              :     {
   18742           29 :         relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
   18743           29 :         return;
   18744              :     }
   18745          182 :     else if (stmt->identity_type == REPLICA_IDENTITY_INDEX)
   18746              :     {
   18747              :          /* fallthrough */ ;
   18748              :     }
   18749              :     else
   18750            0 :         elog(ERROR, "unexpected identity type %u", stmt->identity_type);
   18751              : 
   18752              :     /* Check that the index exists */
   18753          182 :     indexOid = get_relname_relid(stmt->name, rel->rd_rel->relnamespace);
   18754          182 :     if (!OidIsValid(indexOid))
   18755            0 :         ereport(ERROR,
   18756              :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
   18757              :                  errmsg("index \"%s\" for table \"%s\" does not exist",
   18758              :                         stmt->name, RelationGetRelationName(rel))));
   18759              : 
   18760          182 :     indexRel = index_open(indexOid, ShareLock);
   18761              : 
   18762              :     /* Check that the index is on the relation we're altering. */
   18763          182 :     if (indexRel->rd_index == NULL ||
   18764          182 :         indexRel->rd_index->indrelid != RelationGetRelid(rel))
   18765            4 :         ereport(ERROR,
   18766              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   18767              :                  errmsg("\"%s\" is not an index for table \"%s\"",
   18768              :                         RelationGetRelationName(indexRel),
   18769              :                         RelationGetRelationName(rel))));
   18770              : 
   18771              :     /*
   18772              :      * The AM must support uniqueness, and the index must in fact be unique.
   18773              :      * If we have a WITHOUT OVERLAPS constraint (identified by uniqueness +
   18774              :      * exclusion), we can use that too.
   18775              :      */
   18776          178 :     if ((!indexRel->rd_indam->amcanunique ||
   18777          166 :          !indexRel->rd_index->indisunique) &&
   18778           16 :         !(indexRel->rd_index->indisunique && indexRel->rd_index->indisexclusion))
   18779            8 :         ereport(ERROR,
   18780              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   18781              :                  errmsg("cannot use non-unique index \"%s\" as replica identity",
   18782              :                         RelationGetRelationName(indexRel))));
   18783              :     /* Deferred indexes are not guaranteed to be always unique. */
   18784          170 :     if (!indexRel->rd_index->indimmediate)
   18785            8 :         ereport(ERROR,
   18786              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   18787              :                  errmsg("cannot use non-immediate index \"%s\" as replica identity",
   18788              :                         RelationGetRelationName(indexRel))));
   18789              :     /* Expression indexes aren't supported. */
   18790          162 :     if (RelationGetIndexExpressions(indexRel) != NIL)
   18791            4 :         ereport(ERROR,
   18792              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   18793              :                  errmsg("cannot use expression index \"%s\" as replica identity",
   18794              :                         RelationGetRelationName(indexRel))));
   18795              :     /* Predicate indexes aren't supported. */
   18796          158 :     if (RelationGetIndexPredicate(indexRel) != NIL)
   18797            4 :         ereport(ERROR,
   18798              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   18799              :                  errmsg("cannot use partial index \"%s\" as replica identity",
   18800              :                         RelationGetRelationName(indexRel))));
   18801              : 
   18802              :     /* Check index for nullable columns. */
   18803          346 :     for (key = 0; key < IndexRelationGetNumberOfKeyAttributes(indexRel); key++)
   18804              :     {
   18805          196 :         int16       attno = indexRel->rd_index->indkey.values[key];
   18806              :         Form_pg_attribute attr;
   18807              : 
   18808              :         /*
   18809              :          * Reject any other system columns.  (Going forward, we'll disallow
   18810              :          * indexes containing such columns in the first place, but they might
   18811              :          * exist in older branches.)
   18812              :          */
   18813          196 :         if (attno <= 0)
   18814            0 :             ereport(ERROR,
   18815              :                     (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
   18816              :                      errmsg("index \"%s\" cannot be used as replica identity because column %d is a system column",
   18817              :                             RelationGetRelationName(indexRel), attno)));
   18818              : 
   18819          196 :         attr = TupleDescAttr(rel->rd_att, attno - 1);
   18820          196 :         if (!attr->attnotnull)
   18821            4 :             ereport(ERROR,
   18822              :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   18823              :                      errmsg("index \"%s\" cannot be used as replica identity because column \"%s\" is nullable",
   18824              :                             RelationGetRelationName(indexRel),
   18825              :                             NameStr(attr->attname))));
   18826              :     }
   18827              : 
   18828              :     /* This index is suitable for use as a replica identity. Mark it. */
   18829          150 :     relation_mark_replica_identity(rel, stmt->identity_type, indexOid, true);
   18830              : 
   18831          150 :     index_close(indexRel, NoLock);
   18832              : }
   18833              : 
   18834              : /*
   18835              :  * ALTER TABLE ENABLE/DISABLE ROW LEVEL SECURITY
   18836              :  */
   18837              : static void
   18838          242 : ATExecSetRowSecurity(Relation rel, bool rls)
   18839              : {
   18840              :     Relation    pg_class;
   18841              :     Oid         relid;
   18842              :     HeapTuple   tuple;
   18843              : 
   18844          242 :     relid = RelationGetRelid(rel);
   18845              : 
   18846              :     /* Pull the record for this relation and update it */
   18847          242 :     pg_class = table_open(RelationRelationId, RowExclusiveLock);
   18848              : 
   18849          242 :     tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
   18850              : 
   18851          242 :     if (!HeapTupleIsValid(tuple))
   18852            0 :         elog(ERROR, "cache lookup failed for relation %u", relid);
   18853              : 
   18854          242 :     ((Form_pg_class) GETSTRUCT(tuple))->relrowsecurity = rls;
   18855          242 :     CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
   18856              : 
   18857          242 :     InvokeObjectPostAlterHook(RelationRelationId,
   18858              :                               RelationGetRelid(rel), 0);
   18859              : 
   18860          242 :     table_close(pg_class, RowExclusiveLock);
   18861          242 :     heap_freetuple(tuple);
   18862          242 : }
   18863              : 
   18864              : /*
   18865              :  * ALTER TABLE FORCE/NO FORCE ROW LEVEL SECURITY
   18866              :  */
   18867              : static void
   18868           90 : ATExecForceNoForceRowSecurity(Relation rel, bool force_rls)
   18869              : {
   18870              :     Relation    pg_class;
   18871              :     Oid         relid;
   18872              :     HeapTuple   tuple;
   18873              : 
   18874           90 :     relid = RelationGetRelid(rel);
   18875              : 
   18876           90 :     pg_class = table_open(RelationRelationId, RowExclusiveLock);
   18877              : 
   18878           90 :     tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
   18879              : 
   18880           90 :     if (!HeapTupleIsValid(tuple))
   18881            0 :         elog(ERROR, "cache lookup failed for relation %u", relid);
   18882              : 
   18883           90 :     ((Form_pg_class) GETSTRUCT(tuple))->relforcerowsecurity = force_rls;
   18884           90 :     CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
   18885              : 
   18886           90 :     InvokeObjectPostAlterHook(RelationRelationId,
   18887              :                               RelationGetRelid(rel), 0);
   18888              : 
   18889           90 :     table_close(pg_class, RowExclusiveLock);
   18890           90 :     heap_freetuple(tuple);
   18891           90 : }
   18892              : 
   18893              : /*
   18894              :  * ALTER FOREIGN TABLE <name> OPTIONS (...)
   18895              :  */
   18896              : static void
   18897           31 : ATExecGenericOptions(Relation rel, List *options)
   18898              : {
   18899              :     Relation    ftrel;
   18900              :     ForeignServer *server;
   18901              :     ForeignDataWrapper *fdw;
   18902              :     HeapTuple   tuple;
   18903              :     bool        isnull;
   18904              :     Datum       repl_val[Natts_pg_foreign_table];
   18905              :     bool        repl_null[Natts_pg_foreign_table];
   18906              :     bool        repl_repl[Natts_pg_foreign_table];
   18907              :     Datum       datum;
   18908              :     Form_pg_foreign_table tableform;
   18909              : 
   18910           31 :     if (options == NIL)
   18911            0 :         return;
   18912              : 
   18913           31 :     ftrel = table_open(ForeignTableRelationId, RowExclusiveLock);
   18914              : 
   18915           31 :     tuple = SearchSysCacheCopy1(FOREIGNTABLEREL,
   18916              :                                 ObjectIdGetDatum(rel->rd_id));
   18917           31 :     if (!HeapTupleIsValid(tuple))
   18918            0 :         ereport(ERROR,
   18919              :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
   18920              :                  errmsg("foreign table \"%s\" does not exist",
   18921              :                         RelationGetRelationName(rel))));
   18922           31 :     tableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
   18923           31 :     server = GetForeignServer(tableform->ftserver);
   18924           31 :     fdw = GetForeignDataWrapper(server->fdwid);
   18925              : 
   18926           31 :     memset(repl_val, 0, sizeof(repl_val));
   18927           31 :     memset(repl_null, false, sizeof(repl_null));
   18928           31 :     memset(repl_repl, false, sizeof(repl_repl));
   18929              : 
   18930              :     /* Extract the current options */
   18931           31 :     datum = SysCacheGetAttr(FOREIGNTABLEREL,
   18932              :                             tuple,
   18933              :                             Anum_pg_foreign_table_ftoptions,
   18934              :                             &isnull);
   18935           31 :     if (isnull)
   18936            2 :         datum = PointerGetDatum(NULL);
   18937              : 
   18938              :     /* Transform the options */
   18939           31 :     datum = transformGenericOptions(ForeignTableRelationId,
   18940              :                                     datum,
   18941              :                                     options,
   18942              :                                     fdw->fdwvalidator);
   18943              : 
   18944           30 :     if (DatumGetPointer(datum) != NULL)
   18945           30 :         repl_val[Anum_pg_foreign_table_ftoptions - 1] = datum;
   18946              :     else
   18947            0 :         repl_null[Anum_pg_foreign_table_ftoptions - 1] = true;
   18948              : 
   18949           30 :     repl_repl[Anum_pg_foreign_table_ftoptions - 1] = true;
   18950              : 
   18951              :     /* Everything looks good - update the tuple */
   18952              : 
   18953           30 :     tuple = heap_modify_tuple(tuple, RelationGetDescr(ftrel),
   18954              :                               repl_val, repl_null, repl_repl);
   18955              : 
   18956           30 :     CatalogTupleUpdate(ftrel, &tuple->t_self, tuple);
   18957              : 
   18958              :     /*
   18959              :      * Invalidate relcache so that all sessions will refresh any cached plans
   18960              :      * that might depend on the old options.
   18961              :      */
   18962           30 :     CacheInvalidateRelcache(rel);
   18963              : 
   18964           30 :     InvokeObjectPostAlterHook(ForeignTableRelationId,
   18965              :                               RelationGetRelid(rel), 0);
   18966              : 
   18967           30 :     table_close(ftrel, RowExclusiveLock);
   18968              : 
   18969           30 :     heap_freetuple(tuple);
   18970              : }
   18971              : 
   18972              : /*
   18973              :  * ALTER TABLE ALTER COLUMN SET COMPRESSION
   18974              :  *
   18975              :  * Return value is the address of the modified column
   18976              :  */
   18977              : static ObjectAddress
   18978           47 : ATExecSetCompression(Relation rel,
   18979              :                      const char *column,
   18980              :                      Node *newValue,
   18981              :                      LOCKMODE lockmode)
   18982              : {
   18983              :     Relation    attrel;
   18984              :     HeapTuple   tuple;
   18985              :     Form_pg_attribute atttableform;
   18986              :     AttrNumber  attnum;
   18987              :     char       *compression;
   18988              :     char        cmethod;
   18989              :     ObjectAddress address;
   18990              : 
   18991           47 :     compression = strVal(newValue);
   18992              : 
   18993           47 :     attrel = table_open(AttributeRelationId, RowExclusiveLock);
   18994              : 
   18995              :     /* copy the cache entry so we can scribble on it below */
   18996           47 :     tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), column);
   18997           47 :     if (!HeapTupleIsValid(tuple))
   18998            0 :         ereport(ERROR,
   18999              :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
   19000              :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
   19001              :                         column, RelationGetRelationName(rel))));
   19002              : 
   19003              :     /* prevent them from altering a system attribute */
   19004           47 :     atttableform = (Form_pg_attribute) GETSTRUCT(tuple);
   19005           47 :     attnum = atttableform->attnum;
   19006           47 :     if (attnum <= 0)
   19007            0 :         ereport(ERROR,
   19008              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   19009              :                  errmsg("cannot alter system column \"%s\"", column)));
   19010              : 
   19011              :     /*
   19012              :      * Check that column type is compressible, then get the attribute
   19013              :      * compression method code
   19014              :      */
   19015           47 :     cmethod = GetAttributeCompression(atttableform->atttypid, compression);
   19016              : 
   19017              :     /* update pg_attribute entry */
   19018           43 :     atttableform->attcompression = cmethod;
   19019           43 :     CatalogTupleUpdate(attrel, &tuple->t_self, tuple);
   19020              : 
   19021           43 :     InvokeObjectPostAlterHook(RelationRelationId,
   19022              :                               RelationGetRelid(rel),
   19023              :                               attnum);
   19024              : 
   19025              :     /*
   19026              :      * Apply the change to indexes as well (only for simple index columns,
   19027              :      * matching behavior of index.c ConstructTupleDescriptor()).
   19028              :      */
   19029           43 :     SetIndexStorageProperties(rel, attrel, attnum,
   19030              :                               false, 0,
   19031              :                               true, cmethod,
   19032              :                               lockmode);
   19033              : 
   19034           43 :     heap_freetuple(tuple);
   19035              : 
   19036           43 :     table_close(attrel, RowExclusiveLock);
   19037              : 
   19038              :     /* make changes visible */
   19039           43 :     CommandCounterIncrement();
   19040              : 
   19041           43 :     ObjectAddressSubSet(address, RelationRelationId,
   19042              :                         RelationGetRelid(rel), attnum);
   19043           43 :     return address;
   19044              : }
   19045              : 
   19046              : 
   19047              : /*
   19048              :  * Preparation phase for SET LOGGED/UNLOGGED
   19049              :  *
   19050              :  * This verifies that we're not trying to change a temp table.  Also,
   19051              :  * existing foreign key constraints are checked to avoid ending up with
   19052              :  * permanent tables referencing unlogged tables.
   19053              :  */
   19054              : static void
   19055           66 : ATPrepChangePersistence(AlteredTableInfo *tab, Relation rel, bool toLogged)
   19056              : {
   19057              :     Relation    pg_constraint;
   19058              :     HeapTuple   tuple;
   19059              :     SysScanDesc scan;
   19060              :     ScanKeyData skey[1];
   19061              : 
   19062              :     /*
   19063              :      * Disallow changing status for a temp table.  Also verify whether we can
   19064              :      * get away with doing nothing; in such cases we don't need to run the
   19065              :      * checks below, either.
   19066              :      */
   19067           66 :     switch (rel->rd_rel->relpersistence)
   19068              :     {
   19069            0 :         case RELPERSISTENCE_TEMP:
   19070            0 :             ereport(ERROR,
   19071              :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   19072              :                      errmsg("cannot change logged status of table \"%s\" because it is temporary",
   19073              :                             RelationGetRelationName(rel)),
   19074              :                      errtable(rel)));
   19075              :             break;
   19076           37 :         case RELPERSISTENCE_PERMANENT:
   19077           37 :             if (toLogged)
   19078              :                 /* nothing to do */
   19079            8 :                 return;
   19080           33 :             break;
   19081           29 :         case RELPERSISTENCE_UNLOGGED:
   19082           29 :             if (!toLogged)
   19083              :                 /* nothing to do */
   19084            4 :                 return;
   19085           25 :             break;
   19086              :     }
   19087              : 
   19088              :     /*
   19089              :      * Check that the table is not part of any publication when changing to
   19090              :      * UNLOGGED, as UNLOGGED tables can't be published.
   19091              :      */
   19092           91 :     if (!toLogged &&
   19093           33 :         GetRelationIncludedPublications(RelationGetRelid(rel)) != NIL)
   19094            0 :         ereport(ERROR,
   19095              :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
   19096              :                  errmsg("cannot change table \"%s\" to unlogged because it is part of a publication",
   19097              :                         RelationGetRelationName(rel)),
   19098              :                  errdetail("Unlogged relations cannot be replicated.")));
   19099              : 
   19100              :     /*
   19101              :      * Check existing foreign key constraints to preserve the invariant that
   19102              :      * permanent tables cannot reference unlogged ones.  Self-referencing
   19103              :      * foreign keys can safely be ignored.
   19104              :      */
   19105           58 :     pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
   19106              : 
   19107              :     /*
   19108              :      * Scan conrelid if changing to permanent, else confrelid.  This also
   19109              :      * determines whether a useful index exists.
   19110              :      */
   19111           58 :     ScanKeyInit(&skey[0],
   19112              :                 toLogged ? Anum_pg_constraint_conrelid :
   19113              :                 Anum_pg_constraint_confrelid,
   19114              :                 BTEqualStrategyNumber, F_OIDEQ,
   19115              :                 ObjectIdGetDatum(RelationGetRelid(rel)));
   19116           58 :     scan = systable_beginscan(pg_constraint,
   19117              :                               toLogged ? ConstraintRelidTypidNameIndexId : InvalidOid,
   19118              :                               true, NULL, 1, skey);
   19119              : 
   19120           94 :     while (HeapTupleIsValid(tuple = systable_getnext(scan)))
   19121              :     {
   19122           44 :         Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
   19123              : 
   19124           44 :         if (con->contype == CONSTRAINT_FOREIGN)
   19125              :         {
   19126              :             Oid         foreignrelid;
   19127              :             Relation    foreignrel;
   19128              : 
   19129              :             /* the opposite end of what we used as scankey */
   19130           20 :             foreignrelid = toLogged ? con->confrelid : con->conrelid;
   19131              : 
   19132              :             /* ignore if self-referencing */
   19133           20 :             if (RelationGetRelid(rel) == foreignrelid)
   19134            8 :                 continue;
   19135              : 
   19136           12 :             foreignrel = relation_open(foreignrelid, AccessShareLock);
   19137              : 
   19138           12 :             if (toLogged)
   19139              :             {
   19140            4 :                 if (!RelationIsPermanent(foreignrel))
   19141            4 :                     ereport(ERROR,
   19142              :                             (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   19143              :                              errmsg("could not change table \"%s\" to logged because it references unlogged table \"%s\"",
   19144              :                                     RelationGetRelationName(rel),
   19145              :                                     RelationGetRelationName(foreignrel)),
   19146              :                              errtableconstraint(rel, NameStr(con->conname))));
   19147              :             }
   19148              :             else
   19149              :             {
   19150            8 :                 if (RelationIsPermanent(foreignrel))
   19151            4 :                     ereport(ERROR,
   19152              :                             (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   19153              :                              errmsg("could not change table \"%s\" to unlogged because it references logged table \"%s\"",
   19154              :                                     RelationGetRelationName(rel),
   19155              :                                     RelationGetRelationName(foreignrel)),
   19156              :                              errtableconstraint(rel, NameStr(con->conname))));
   19157              :             }
   19158              : 
   19159            4 :             relation_close(foreignrel, AccessShareLock);
   19160              :         }
   19161              :     }
   19162              : 
   19163           50 :     systable_endscan(scan);
   19164              : 
   19165           50 :     table_close(pg_constraint, AccessShareLock);
   19166              : 
   19167              :     /* force rewrite if necessary; see comment in ATRewriteTables */
   19168           50 :     tab->rewrite |= AT_REWRITE_ALTER_PERSISTENCE;
   19169           50 :     if (toLogged)
   19170           21 :         tab->newrelpersistence = RELPERSISTENCE_PERMANENT;
   19171              :     else
   19172           29 :         tab->newrelpersistence = RELPERSISTENCE_UNLOGGED;
   19173           50 :     tab->chgPersistence = true;
   19174              : }
   19175              : 
   19176              : /*
   19177              :  * Execute ALTER TABLE SET SCHEMA
   19178              :  */
   19179              : ObjectAddress
   19180           88 : AlterTableNamespace(AlterObjectSchemaStmt *stmt, Oid *oldschema)
   19181              : {
   19182              :     Relation    rel;
   19183              :     Oid         relid;
   19184              :     Oid         oldNspOid;
   19185              :     Oid         nspOid;
   19186              :     RangeVar   *newrv;
   19187              :     ObjectAddresses *objsMoved;
   19188              :     ObjectAddress myself;
   19189              : 
   19190           88 :     relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
   19191           88 :                                      stmt->missing_ok ? RVR_MISSING_OK : 0,
   19192              :                                      RangeVarCallbackForAlterRelation,
   19193              :                                      stmt);
   19194              : 
   19195           83 :     if (!OidIsValid(relid))
   19196              :     {
   19197           12 :         ereport(NOTICE,
   19198              :                 (errmsg("relation \"%s\" does not exist, skipping",
   19199              :                         stmt->relation->relname)));
   19200           12 :         return InvalidObjectAddress;
   19201              :     }
   19202              : 
   19203           71 :     rel = relation_open(relid, NoLock);
   19204              : 
   19205           71 :     oldNspOid = RelationGetNamespace(rel);
   19206              : 
   19207              :     /* If it's an owned sequence, disallow moving it by itself. */
   19208           71 :     if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
   19209              :     {
   19210              :         Oid         tableId;
   19211              :         int32       colId;
   19212              : 
   19213            6 :         if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
   19214            1 :             sequenceIsOwned(relid, DEPENDENCY_INTERNAL, &tableId, &colId))
   19215            4 :             ereport(ERROR,
   19216              :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   19217              :                      errmsg("cannot move an owned sequence into another schema"),
   19218              :                      errdetail("Sequence \"%s\" is linked to table \"%s\".",
   19219              :                                RelationGetRelationName(rel),
   19220              :                                get_rel_name(tableId))));
   19221              :     }
   19222              : 
   19223              :     /* Get and lock schema OID and check its permissions. */
   19224           67 :     newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
   19225           67 :     nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
   19226              : 
   19227              :     /* common checks on switching namespaces */
   19228           67 :     CheckSetNamespace(oldNspOid, nspOid);
   19229              : 
   19230           67 :     objsMoved = new_object_addresses();
   19231           67 :     AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
   19232           63 :     free_object_addresses(objsMoved);
   19233              : 
   19234           63 :     ObjectAddressSet(myself, RelationRelationId, relid);
   19235              : 
   19236           63 :     if (oldschema)
   19237           63 :         *oldschema = oldNspOid;
   19238              : 
   19239              :     /* close rel, but keep lock until commit */
   19240           63 :     relation_close(rel, NoLock);
   19241              : 
   19242           63 :     return myself;
   19243              : }
   19244              : 
   19245              : /*
   19246              :  * The guts of relocating a table or materialized view to another namespace:
   19247              :  * besides moving the relation itself, its dependent objects are relocated to
   19248              :  * the new schema.
   19249              :  */
   19250              : void
   19251           68 : AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid,
   19252              :                             ObjectAddresses *objsMoved)
   19253              : {
   19254              :     Relation    classRel;
   19255              : 
   19256              :     Assert(objsMoved != NULL);
   19257              : 
   19258              :     /* OK, modify the pg_class row and pg_depend entry */
   19259           68 :     classRel = table_open(RelationRelationId, RowExclusiveLock);
   19260              : 
   19261           68 :     AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
   19262              :                                    nspOid, true, objsMoved);
   19263              : 
   19264              :     /* Fix the table's row type too, if it has one */
   19265           64 :     if (OidIsValid(rel->rd_rel->reltype))
   19266           63 :         AlterTypeNamespaceInternal(rel->rd_rel->reltype, nspOid,
   19267              :                                    false,   /* isImplicitArray */
   19268              :                                    false,   /* ignoreDependent */
   19269              :                                    false,   /* errorOnTableType */
   19270              :                                    objsMoved);
   19271              : 
   19272              :     /* Fix other dependent stuff */
   19273           64 :     AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
   19274           64 :     AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
   19275              :                        objsMoved, AccessExclusiveLock);
   19276           64 :     AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
   19277              :                               false, objsMoved);
   19278              : 
   19279           64 :     table_close(classRel, RowExclusiveLock);
   19280           64 : }
   19281              : 
   19282              : /*
   19283              :  * The guts of relocating a relation to another namespace: fix the pg_class
   19284              :  * entry, and the pg_depend entry if any.  Caller must already have
   19285              :  * opened and write-locked pg_class.
   19286              :  */
   19287              : void
   19288          135 : AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
   19289              :                                Oid oldNspOid, Oid newNspOid,
   19290              :                                bool hasDependEntry,
   19291              :                                ObjectAddresses *objsMoved)
   19292              : {
   19293              :     HeapTuple   classTup;
   19294              :     Form_pg_class classForm;
   19295              :     ObjectAddress thisobj;
   19296          135 :     bool        already_done = false;
   19297              : 
   19298              :     /* no rel lock for relkind=c so use LOCKTAG_TUPLE */
   19299          135 :     classTup = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(relOid));
   19300          135 :     if (!HeapTupleIsValid(classTup))
   19301            0 :         elog(ERROR, "cache lookup failed for relation %u", relOid);
   19302          135 :     classForm = (Form_pg_class) GETSTRUCT(classTup);
   19303              : 
   19304              :     Assert(classForm->relnamespace == oldNspOid);
   19305              : 
   19306          135 :     thisobj.classId = RelationRelationId;
   19307          135 :     thisobj.objectId = relOid;
   19308          135 :     thisobj.objectSubId = 0;
   19309              : 
   19310              :     /*
   19311              :      * If the object has already been moved, don't move it again.  If it's
   19312              :      * already in the right place, don't move it, but still fire the object
   19313              :      * access hook.
   19314              :      */
   19315          135 :     already_done = object_address_present(&thisobj, objsMoved);
   19316          135 :     if (!already_done && oldNspOid != newNspOid)
   19317          103 :     {
   19318          107 :         ItemPointerData otid = classTup->t_self;
   19319              : 
   19320              :         /* check for duplicate name (more friendly than unique-index failure) */
   19321          107 :         if (get_relname_relid(NameStr(classForm->relname),
   19322              :                               newNspOid) != InvalidOid)
   19323            4 :             ereport(ERROR,
   19324              :                     (errcode(ERRCODE_DUPLICATE_TABLE),
   19325              :                      errmsg("relation \"%s\" already exists in schema \"%s\"",
   19326              :                             NameStr(classForm->relname),
   19327              :                             get_namespace_name(newNspOid))));
   19328              : 
   19329              :         /* classTup is a copy, so OK to scribble on */
   19330          103 :         classForm->relnamespace = newNspOid;
   19331              : 
   19332          103 :         CatalogTupleUpdate(classRel, &otid, classTup);
   19333          103 :         UnlockTuple(classRel, &otid, InplaceUpdateTupleLock);
   19334              : 
   19335              : 
   19336              :         /* Update dependency on schema if caller said so */
   19337          179 :         if (hasDependEntry &&
   19338           76 :             changeDependencyFor(RelationRelationId,
   19339              :                                 relOid,
   19340              :                                 NamespaceRelationId,
   19341              :                                 oldNspOid,
   19342              :                                 newNspOid) != 1)
   19343            0 :             elog(ERROR, "could not change schema dependency for relation \"%s\"",
   19344              :                  NameStr(classForm->relname));
   19345              :     }
   19346              :     else
   19347           28 :         UnlockTuple(classRel, &classTup->t_self, InplaceUpdateTupleLock);
   19348          131 :     if (!already_done)
   19349              :     {
   19350          131 :         add_exact_object_address(&thisobj, objsMoved);
   19351              : 
   19352          131 :         InvokeObjectPostAlterHook(RelationRelationId, relOid, 0);
   19353              :     }
   19354              : 
   19355          131 :     heap_freetuple(classTup);
   19356          131 : }
   19357              : 
   19358              : /*
   19359              :  * Move all indexes for the specified relation to another namespace.
   19360              :  *
   19361              :  * Note: we assume adequate permission checking was done by the caller,
   19362              :  * and that the caller has a suitable lock on the owning relation.
   19363              :  */
   19364              : static void
   19365           64 : AlterIndexNamespaces(Relation classRel, Relation rel,
   19366              :                      Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
   19367              : {
   19368              :     List       *indexList;
   19369              :     ListCell   *l;
   19370              : 
   19371           64 :     indexList = RelationGetIndexList(rel);
   19372              : 
   19373           94 :     foreach(l, indexList)
   19374              :     {
   19375           30 :         Oid         indexOid = lfirst_oid(l);
   19376              :         ObjectAddress thisobj;
   19377              : 
   19378           30 :         thisobj.classId = RelationRelationId;
   19379           30 :         thisobj.objectId = indexOid;
   19380           30 :         thisobj.objectSubId = 0;
   19381              : 
   19382              :         /*
   19383              :          * Note: currently, the index will not have its own dependency on the
   19384              :          * namespace, so we don't need to do changeDependencyFor(). There's no
   19385              :          * row type in pg_type, either.
   19386              :          *
   19387              :          * XXX this objsMoved test may be pointless -- surely we have a single
   19388              :          * dependency link from a relation to each index?
   19389              :          */
   19390           30 :         if (!object_address_present(&thisobj, objsMoved))
   19391              :         {
   19392           30 :             AlterRelationNamespaceInternal(classRel, indexOid,
   19393              :                                            oldNspOid, newNspOid,
   19394              :                                            false, objsMoved);
   19395           30 :             add_exact_object_address(&thisobj, objsMoved);
   19396              :         }
   19397              :     }
   19398              : 
   19399           64 :     list_free(indexList);
   19400           64 : }
   19401              : 
   19402              : /*
   19403              :  * Move all identity and SERIAL-column sequences of the specified relation to another
   19404              :  * namespace.
   19405              :  *
   19406              :  * Note: we assume adequate permission checking was done by the caller,
   19407              :  * and that the caller has a suitable lock on the owning relation.
   19408              :  */
   19409              : static void
   19410           64 : AlterSeqNamespaces(Relation classRel, Relation rel,
   19411              :                    Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved,
   19412              :                    LOCKMODE lockmode)
   19413              : {
   19414              :     Relation    depRel;
   19415              :     SysScanDesc scan;
   19416              :     ScanKeyData key[2];
   19417              :     HeapTuple   tup;
   19418              : 
   19419              :     /*
   19420              :      * SERIAL sequences are those having an auto dependency on one of the
   19421              :      * table's columns (we don't care *which* column, exactly).
   19422              :      */
   19423           64 :     depRel = table_open(DependRelationId, AccessShareLock);
   19424              : 
   19425           64 :     ScanKeyInit(&key[0],
   19426              :                 Anum_pg_depend_refclassid,
   19427              :                 BTEqualStrategyNumber, F_OIDEQ,
   19428              :                 ObjectIdGetDatum(RelationRelationId));
   19429           64 :     ScanKeyInit(&key[1],
   19430              :                 Anum_pg_depend_refobjid,
   19431              :                 BTEqualStrategyNumber, F_OIDEQ,
   19432              :                 ObjectIdGetDatum(RelationGetRelid(rel)));
   19433              :     /* we leave refobjsubid unspecified */
   19434              : 
   19435           64 :     scan = systable_beginscan(depRel, DependReferenceIndexId, true,
   19436              :                               NULL, 2, key);
   19437              : 
   19438          425 :     while (HeapTupleIsValid(tup = systable_getnext(scan)))
   19439              :     {
   19440          361 :         Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
   19441              :         Relation    seqRel;
   19442              : 
   19443              :         /* skip dependencies other than auto dependencies on columns */
   19444          361 :         if (depForm->refobjsubid == 0 ||
   19445          252 :             depForm->classid != RelationRelationId ||
   19446           28 :             depForm->objsubid != 0 ||
   19447           28 :             !(depForm->deptype == DEPENDENCY_AUTO || depForm->deptype == DEPENDENCY_INTERNAL))
   19448          333 :             continue;
   19449              : 
   19450              :         /* Use relation_open just in case it's an index */
   19451           28 :         seqRel = relation_open(depForm->objid, lockmode);
   19452              : 
   19453              :         /* skip non-sequence relations */
   19454           28 :         if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
   19455              :         {
   19456              :             /* No need to keep the lock */
   19457            0 :             relation_close(seqRel, lockmode);
   19458            0 :             continue;
   19459              :         }
   19460              : 
   19461              :         /* Fix the pg_class and pg_depend entries */
   19462           28 :         AlterRelationNamespaceInternal(classRel, depForm->objid,
   19463              :                                        oldNspOid, newNspOid,
   19464              :                                        true, objsMoved);
   19465              : 
   19466              :         /*
   19467              :          * Sequences used to have entries in pg_type, but no longer do.  If we
   19468              :          * ever re-instate that, we'll need to move the pg_type entry to the
   19469              :          * new namespace, too (using AlterTypeNamespaceInternal).
   19470              :          */
   19471              :         Assert(RelationGetForm(seqRel)->reltype == InvalidOid);
   19472              : 
   19473              :         /* Now we can close it.  Keep the lock till end of transaction. */
   19474           28 :         relation_close(seqRel, NoLock);
   19475              :     }
   19476              : 
   19477           64 :     systable_endscan(scan);
   19478              : 
   19479           64 :     relation_close(depRel, AccessShareLock);
   19480           64 : }
   19481              : 
   19482              : 
   19483              : /*
   19484              :  * This code supports
   19485              :  *  CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
   19486              :  *
   19487              :  * Because we only support this for TEMP tables, it's sufficient to remember
   19488              :  * the state in a backend-local data structure.
   19489              :  */
   19490              : 
   19491              : /*
   19492              :  * Register a newly-created relation's ON COMMIT action.
   19493              :  */
   19494              : void
   19495          120 : register_on_commit_action(Oid relid, OnCommitAction action)
   19496              : {
   19497              :     OnCommitItem *oc;
   19498              :     MemoryContext oldcxt;
   19499              : 
   19500              :     /*
   19501              :      * We needn't bother registering the relation unless there is an ON COMMIT
   19502              :      * action we need to take.
   19503              :      */
   19504          120 :     if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
   19505           16 :         return;
   19506              : 
   19507          104 :     oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
   19508              : 
   19509          104 :     oc = palloc_object(OnCommitItem);
   19510          104 :     oc->relid = relid;
   19511          104 :     oc->oncommit = action;
   19512          104 :     oc->creating_subid = GetCurrentSubTransactionId();
   19513          104 :     oc->deleting_subid = InvalidSubTransactionId;
   19514              : 
   19515              :     /*
   19516              :      * We use lcons() here so that ON COMMIT actions are processed in reverse
   19517              :      * order of registration.  That might not be essential but it seems
   19518              :      * reasonable.
   19519              :      */
   19520          104 :     on_commits = lcons(oc, on_commits);
   19521              : 
   19522          104 :     MemoryContextSwitchTo(oldcxt);
   19523              : }
   19524              : 
   19525              : /*
   19526              :  * Unregister any ON COMMIT action when a relation is deleted.
   19527              :  *
   19528              :  * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
   19529              :  */
   19530              : void
   19531        32218 : remove_on_commit_action(Oid relid)
   19532              : {
   19533              :     ListCell   *l;
   19534              : 
   19535        32331 :     foreach(l, on_commits)
   19536              :     {
   19537          205 :         OnCommitItem *oc = (OnCommitItem *) lfirst(l);
   19538              : 
   19539          205 :         if (oc->relid == relid)
   19540              :         {
   19541           92 :             oc->deleting_subid = GetCurrentSubTransactionId();
   19542           92 :             break;
   19543              :         }
   19544              :     }
   19545        32218 : }
   19546              : 
   19547              : /*
   19548              :  * Perform ON COMMIT actions.
   19549              :  *
   19550              :  * This is invoked just before actually committing, since it's possible
   19551              :  * to encounter errors.
   19552              :  */
   19553              : void
   19554       576933 : PreCommit_on_commit_actions(void)
   19555              : {
   19556              :     ListCell   *l;
   19557       576933 :     List       *oids_to_truncate = NIL;
   19558       576933 :     List       *oids_to_drop = NIL;
   19559              : 
   19560       577479 :     foreach(l, on_commits)
   19561              :     {
   19562          546 :         OnCommitItem *oc = (OnCommitItem *) lfirst(l);
   19563              : 
   19564              :         /* Ignore entry if already dropped in this xact */
   19565          546 :         if (oc->deleting_subid != InvalidSubTransactionId)
   19566           49 :             continue;
   19567              : 
   19568          497 :         switch (oc->oncommit)
   19569              :         {
   19570            0 :             case ONCOMMIT_NOOP:
   19571              :             case ONCOMMIT_PRESERVE_ROWS:
   19572              :                 /* Do nothing (there shouldn't be such entries, actually) */
   19573            0 :                 break;
   19574          462 :             case ONCOMMIT_DELETE_ROWS:
   19575              : 
   19576              :                 /*
   19577              :                  * If this transaction hasn't accessed any temporary
   19578              :                  * relations, we can skip truncating ON COMMIT DELETE ROWS
   19579              :                  * tables, as they must still be empty.
   19580              :                  */
   19581          462 :                 if ((MyXactFlags & XACT_FLAGS_ACCESSEDTEMPNAMESPACE))
   19582          298 :                     oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
   19583          462 :                 break;
   19584           35 :             case ONCOMMIT_DROP:
   19585           35 :                 oids_to_drop = lappend_oid(oids_to_drop, oc->relid);
   19586           35 :                 break;
   19587              :         }
   19588              :     }
   19589              : 
   19590              :     /*
   19591              :      * Truncate relations before dropping so that all dependencies between
   19592              :      * relations are removed after they are worked on.  Doing it like this
   19593              :      * might be a waste as it is possible that a relation being truncated will
   19594              :      * be dropped anyway due to its parent being dropped, but this makes the
   19595              :      * code more robust because of not having to re-check that the relation
   19596              :      * exists at truncation time.
   19597              :      */
   19598       576933 :     if (oids_to_truncate != NIL)
   19599          254 :         heap_truncate(oids_to_truncate);
   19600              : 
   19601       576929 :     if (oids_to_drop != NIL)
   19602              :     {
   19603           31 :         ObjectAddresses *targetObjects = new_object_addresses();
   19604              : 
   19605           66 :         foreach(l, oids_to_drop)
   19606              :         {
   19607              :             ObjectAddress object;
   19608              : 
   19609           35 :             object.classId = RelationRelationId;
   19610           35 :             object.objectId = lfirst_oid(l);
   19611           35 :             object.objectSubId = 0;
   19612              : 
   19613              :             Assert(!object_address_present(&object, targetObjects));
   19614              : 
   19615           35 :             add_exact_object_address(&object, targetObjects);
   19616              :         }
   19617              : 
   19618              :         /*
   19619              :          * Object deletion might involve toast table access (to clean up
   19620              :          * toasted catalog entries), so ensure we have a valid snapshot.
   19621              :          */
   19622           31 :         PushActiveSnapshot(GetTransactionSnapshot());
   19623              : 
   19624              :         /*
   19625              :          * Since this is an automatic drop, rather than one directly initiated
   19626              :          * by the user, we pass the PERFORM_DELETION_INTERNAL flag.
   19627              :          */
   19628           31 :         performMultipleDeletions(targetObjects, DROP_CASCADE,
   19629              :                                  PERFORM_DELETION_INTERNAL | PERFORM_DELETION_QUIETLY);
   19630              : 
   19631           31 :         PopActiveSnapshot();
   19632              : 
   19633              : #ifdef USE_ASSERT_CHECKING
   19634              : 
   19635              :         /*
   19636              :          * Note that table deletion will call remove_on_commit_action, so the
   19637              :          * entry should get marked as deleted.
   19638              :          */
   19639              :         foreach(l, on_commits)
   19640              :         {
   19641              :             OnCommitItem *oc = (OnCommitItem *) lfirst(l);
   19642              : 
   19643              :             if (oc->oncommit != ONCOMMIT_DROP)
   19644              :                 continue;
   19645              : 
   19646              :             Assert(oc->deleting_subid != InvalidSubTransactionId);
   19647              :         }
   19648              : #endif
   19649              :     }
   19650       576929 : }
   19651              : 
   19652              : /*
   19653              :  * Post-commit or post-abort cleanup for ON COMMIT management.
   19654              :  *
   19655              :  * All we do here is remove no-longer-needed OnCommitItem entries.
   19656              :  *
   19657              :  * During commit, remove entries that were deleted during this transaction;
   19658              :  * during abort, remove those created during this transaction.
   19659              :  */
   19660              : void
   19661       611215 : AtEOXact_on_commit_actions(bool isCommit)
   19662              : {
   19663              :     ListCell   *cur_item;
   19664              : 
   19665       611785 :     foreach(cur_item, on_commits)
   19666              :     {
   19667          570 :         OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
   19668              : 
   19669          642 :         if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
   19670           72 :             oc->creating_subid != InvalidSubTransactionId)
   19671              :         {
   19672              :             /* cur_item must be removed */
   19673          104 :             on_commits = foreach_delete_current(on_commits, cur_item);
   19674          104 :             pfree(oc);
   19675              :         }
   19676              :         else
   19677              :         {
   19678              :             /* cur_item must be preserved */
   19679          466 :             oc->creating_subid = InvalidSubTransactionId;
   19680          466 :             oc->deleting_subid = InvalidSubTransactionId;
   19681              :         }
   19682              :     }
   19683       611215 : }
   19684              : 
   19685              : /*
   19686              :  * Post-subcommit or post-subabort cleanup for ON COMMIT management.
   19687              :  *
   19688              :  * During subabort, we can immediately remove entries created during this
   19689              :  * subtransaction.  During subcommit, just relabel entries marked during
   19690              :  * this subtransaction as being the parent's responsibility.
   19691              :  */
   19692              : void
   19693        11785 : AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
   19694              :                               SubTransactionId parentSubid)
   19695              : {
   19696              :     ListCell   *cur_item;
   19697              : 
   19698        11785 :     foreach(cur_item, on_commits)
   19699              :     {
   19700            0 :         OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
   19701              : 
   19702            0 :         if (!isCommit && oc->creating_subid == mySubid)
   19703              :         {
   19704              :             /* cur_item must be removed */
   19705            0 :             on_commits = foreach_delete_current(on_commits, cur_item);
   19706            0 :             pfree(oc);
   19707              :         }
   19708              :         else
   19709              :         {
   19710              :             /* cur_item must be preserved */
   19711            0 :             if (oc->creating_subid == mySubid)
   19712            0 :                 oc->creating_subid = parentSubid;
   19713            0 :             if (oc->deleting_subid == mySubid)
   19714            0 :                 oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
   19715              :         }
   19716              :     }
   19717        11785 : }
   19718              : 
   19719              : /*
   19720              :  * This is intended as a callback for RangeVarGetRelidExtended().  It allows
   19721              :  * the relation to be locked only if (1) it's a plain or partitioned table,
   19722              :  * materialized view, or TOAST table and (2) the current user is the owner (or
   19723              :  * the superuser) or has been granted MAINTAIN.  This meets the
   19724              :  * permission-checking needs of CLUSTER, REINDEX TABLE, and REFRESH
   19725              :  * MATERIALIZED VIEW; we expose it here so that it can be used by all.
   19726              :  */
   19727              : void
   19728          681 : RangeVarCallbackMaintainsTable(const RangeVar *relation,
   19729              :                                Oid relId, Oid oldRelId, void *arg)
   19730              : {
   19731              :     char        relkind;
   19732              :     AclResult   aclresult;
   19733              : 
   19734              :     /* Nothing to do if the relation was not found. */
   19735          681 :     if (!OidIsValid(relId))
   19736            4 :         return;
   19737              : 
   19738              :     /*
   19739              :      * If the relation does exist, check whether it's an index.  But note that
   19740              :      * the relation might have been dropped between the time we did the name
   19741              :      * lookup and now.  In that case, there's nothing to do.
   19742              :      */
   19743          677 :     relkind = get_rel_relkind(relId);
   19744          677 :     if (!relkind)
   19745            0 :         return;
   19746          677 :     if (relkind != RELKIND_RELATION && relkind != RELKIND_TOASTVALUE &&
   19747          104 :         relkind != RELKIND_MATVIEW && relkind != RELKIND_PARTITIONED_TABLE)
   19748           18 :         ereport(ERROR,
   19749              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   19750              :                  errmsg("\"%s\" is not a table or materialized view", relation->relname)));
   19751              : 
   19752              :     /* Check permissions */
   19753          659 :     aclresult = pg_class_aclcheck(relId, GetUserId(), ACL_MAINTAIN);
   19754          659 :     if (aclresult != ACLCHECK_OK)
   19755           20 :         aclcheck_error(aclresult,
   19756           20 :                        get_relkind_objtype(get_rel_relkind(relId)),
   19757           20 :                        relation->relname);
   19758              : }
   19759              : 
   19760              : /*
   19761              :  * Callback to RangeVarGetRelidExtended() for TRUNCATE processing.
   19762              :  */
   19763              : static void
   19764         1409 : RangeVarCallbackForTruncate(const RangeVar *relation,
   19765              :                             Oid relId, Oid oldRelId, void *arg)
   19766              : {
   19767              :     HeapTuple   tuple;
   19768              : 
   19769              :     /* Nothing to do if the relation was not found. */
   19770         1409 :     if (!OidIsValid(relId))
   19771            0 :         return;
   19772              : 
   19773         1409 :     tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
   19774         1409 :     if (!HeapTupleIsValid(tuple))   /* should not happen */
   19775            0 :         elog(ERROR, "cache lookup failed for relation %u", relId);
   19776              : 
   19777         1409 :     truncate_check_rel(relId, (Form_pg_class) GETSTRUCT(tuple));
   19778         1406 :     truncate_check_perms(relId, (Form_pg_class) GETSTRUCT(tuple));
   19779              : 
   19780         1386 :     ReleaseSysCache(tuple);
   19781              : }
   19782              : 
   19783              : /*
   19784              :  * Callback for RangeVarGetRelidExtended().  Checks that the current user is
   19785              :  * the owner of the relation, or superuser.
   19786              :  */
   19787              : void
   19788        11488 : RangeVarCallbackOwnsRelation(const RangeVar *relation,
   19789              :                              Oid relId, Oid oldRelId, void *arg)
   19790              : {
   19791              :     HeapTuple   tuple;
   19792              : 
   19793              :     /* Nothing to do if the relation was not found. */
   19794        11488 :     if (!OidIsValid(relId))
   19795           17 :         return;
   19796              : 
   19797        11471 :     tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
   19798        11471 :     if (!HeapTupleIsValid(tuple))   /* should not happen */
   19799            0 :         elog(ERROR, "cache lookup failed for relation %u", relId);
   19800              : 
   19801        11471 :     if (!object_ownercheck(RelationRelationId, relId, GetUserId()))
   19802           16 :         aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relId)),
   19803           16 :                        relation->relname);
   19804              : 
   19805        22850 :     if (!allowSystemTableMods &&
   19806        11395 :         IsSystemClass(relId, (Form_pg_class) GETSTRUCT(tuple)))
   19807            1 :         ereport(ERROR,
   19808              :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
   19809              :                  errmsg("permission denied: \"%s\" is a system catalog",
   19810              :                         relation->relname)));
   19811              : 
   19812        11454 :     ReleaseSysCache(tuple);
   19813              : }
   19814              : 
   19815              : /*
   19816              :  * Common RangeVarGetRelid callback for rename, set schema, and alter table
   19817              :  * processing.
   19818              :  */
   19819              : static void
   19820        21726 : RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid,
   19821              :                                  void *arg)
   19822              : {
   19823        21726 :     Node       *stmt = (Node *) arg;
   19824              :     ObjectType  reltype;
   19825              :     HeapTuple   tuple;
   19826              :     Form_pg_class classform;
   19827              :     AclResult   aclresult;
   19828              :     char        relkind;
   19829              : 
   19830        21726 :     tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
   19831        21726 :     if (!HeapTupleIsValid(tuple))
   19832          161 :         return;                 /* concurrently dropped */
   19833        21565 :     classform = (Form_pg_class) GETSTRUCT(tuple);
   19834        21565 :     relkind = classform->relkind;
   19835              : 
   19836              :     /* Must own relation. */
   19837        21565 :     if (!object_ownercheck(RelationRelationId, relid, GetUserId()))
   19838           56 :         aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relid)), rv->relname);
   19839              : 
   19840              :     /* No system table modifications unless explicitly allowed. */
   19841        21509 :     if (!allowSystemTableMods && IsSystemClass(relid, classform))
   19842           18 :         ereport(ERROR,
   19843              :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
   19844              :                  errmsg("permission denied: \"%s\" is a system catalog",
   19845              :                         rv->relname)));
   19846              : 
   19847              :     /*
   19848              :      * Extract the specified relation type from the statement parse tree.
   19849              :      *
   19850              :      * Also, for ALTER .. RENAME, check permissions: the user must (still)
   19851              :      * have CREATE rights on the containing namespace.
   19852              :      */
   19853        21491 :     if (IsA(stmt, RenameStmt))
   19854              :     {
   19855          310 :         aclresult = object_aclcheck(NamespaceRelationId, classform->relnamespace,
   19856              :                                     GetUserId(), ACL_CREATE);
   19857          310 :         if (aclresult != ACLCHECK_OK)
   19858            0 :             aclcheck_error(aclresult, OBJECT_SCHEMA,
   19859            0 :                            get_namespace_name(classform->relnamespace));
   19860          310 :         reltype = ((RenameStmt *) stmt)->renameType;
   19861              :     }
   19862        21181 :     else if (IsA(stmt, AlterObjectSchemaStmt))
   19863           73 :         reltype = ((AlterObjectSchemaStmt *) stmt)->objectType;
   19864              : 
   19865        21108 :     else if (IsA(stmt, AlterTableStmt))
   19866        21108 :         reltype = ((AlterTableStmt *) stmt)->objtype;
   19867              :     else
   19868              :     {
   19869            0 :         elog(ERROR, "unrecognized node type: %d", (int) nodeTag(stmt));
   19870              :         reltype = OBJECT_TABLE; /* placate compiler */
   19871              :     }
   19872              : 
   19873              :     /*
   19874              :      * For compatibility with prior releases, we allow ALTER TABLE to be used
   19875              :      * with most other types of relations (but not composite types). We allow
   19876              :      * similar flexibility for ALTER INDEX in the case of RENAME, but not
   19877              :      * otherwise.  Otherwise, the user must select the correct form of the
   19878              :      * command for the relation at issue.
   19879              :      */
   19880        21491 :     if (reltype == OBJECT_SEQUENCE && relkind != RELKIND_SEQUENCE)
   19881            0 :         ereport(ERROR,
   19882              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   19883              :                  errmsg("\"%s\" is not a sequence", rv->relname)));
   19884              : 
   19885        21491 :     if (reltype == OBJECT_VIEW && relkind != RELKIND_VIEW)
   19886            0 :         ereport(ERROR,
   19887              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   19888              :                  errmsg("\"%s\" is not a view", rv->relname)));
   19889              : 
   19890        21491 :     if (reltype == OBJECT_MATVIEW && relkind != RELKIND_MATVIEW)
   19891            0 :         ereport(ERROR,
   19892              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   19893              :                  errmsg("\"%s\" is not a materialized view", rv->relname)));
   19894              : 
   19895        21491 :     if (reltype == OBJECT_FOREIGN_TABLE && relkind != RELKIND_FOREIGN_TABLE)
   19896            0 :         ereport(ERROR,
   19897              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   19898              :                  errmsg("\"%s\" is not a foreign table", rv->relname)));
   19899              : 
   19900        21491 :     if (reltype == OBJECT_TYPE && relkind != RELKIND_COMPOSITE_TYPE)
   19901            0 :         ereport(ERROR,
   19902              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   19903              :                  errmsg("\"%s\" is not a composite type", rv->relname)));
   19904              : 
   19905        21491 :     if (reltype == OBJECT_PROPGRAPH && relkind != RELKIND_PROPGRAPH)
   19906            0 :         ereport(ERROR,
   19907              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   19908              :                  errmsg("\"%s\" is not a property graph", rv->relname)));
   19909              : 
   19910        21491 :     if (reltype == OBJECT_INDEX && relkind != RELKIND_INDEX &&
   19911              :         relkind != RELKIND_PARTITIONED_INDEX
   19912           27 :         && !IsA(stmt, RenameStmt))
   19913            4 :         ereport(ERROR,
   19914              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   19915              :                  errmsg("\"%s\" is not an index", rv->relname)));
   19916              : 
   19917              :     /*
   19918              :      * Don't allow ALTER TABLE on composite types. We want people to use ALTER
   19919              :      * TYPE for that.
   19920              :      */
   19921        21487 :     if (reltype != OBJECT_TYPE && relkind == RELKIND_COMPOSITE_TYPE)
   19922            0 :         ereport(ERROR,
   19923              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   19924              :                  errmsg("\"%s\" is a composite type", rv->relname),
   19925              :         /* translator: %s is an SQL ALTER command */
   19926              :                  errhint("Use %s instead.",
   19927              :                          "ALTER TYPE")));
   19928              : 
   19929              :     /*
   19930              :      * Don't allow ALTER TABLE .. SET SCHEMA on relations that can't be moved
   19931              :      * to a different schema, such as indexes and TOAST tables.
   19932              :      */
   19933        21487 :     if (IsA(stmt, AlterObjectSchemaStmt))
   19934              :     {
   19935           73 :         if (relkind == RELKIND_INDEX || relkind == RELKIND_PARTITIONED_INDEX)
   19936            0 :             ereport(ERROR,
   19937              :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   19938              :                      errmsg("cannot change schema of index \"%s\"",
   19939              :                             rv->relname),
   19940              :                      errhint("Change the schema of the table instead.")));
   19941           73 :         else if (relkind == RELKIND_COMPOSITE_TYPE)
   19942            0 :             ereport(ERROR,
   19943              :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   19944              :                      errmsg("cannot change schema of composite type \"%s\"",
   19945              :                             rv->relname),
   19946              :             /* translator: %s is an SQL ALTER command */
   19947              :                      errhint("Use %s instead.",
   19948              :                              "ALTER TYPE")));
   19949           73 :         else if (relkind == RELKIND_TOASTVALUE)
   19950            0 :             ereport(ERROR,
   19951              :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   19952              :                      errmsg("cannot change schema of TOAST table \"%s\"",
   19953              :                             rv->relname),
   19954              :                      errhint("Change the schema of the table instead.")));
   19955              :     }
   19956              : 
   19957        21487 :     ReleaseSysCache(tuple);
   19958              : }
   19959              : 
   19960              : /*
   19961              :  * Transform any expressions present in the partition key
   19962              :  *
   19963              :  * Returns a transformed PartitionSpec.
   19964              :  */
   19965              : static PartitionSpec *
   19966         3538 : transformPartitionSpec(Relation rel, PartitionSpec *partspec)
   19967              : {
   19968              :     PartitionSpec *newspec;
   19969              :     ParseState *pstate;
   19970              :     ParseNamespaceItem *nsitem;
   19971              :     ListCell   *l;
   19972              : 
   19973         3538 :     newspec = makeNode(PartitionSpec);
   19974              : 
   19975         3538 :     newspec->strategy = partspec->strategy;
   19976         3538 :     newspec->partParams = NIL;
   19977         3538 :     newspec->location = partspec->location;
   19978              : 
   19979              :     /* Check valid number of columns for strategy */
   19980         5136 :     if (partspec->strategy == PARTITION_STRATEGY_LIST &&
   19981         1598 :         list_length(partspec->partParams) != 1)
   19982            4 :         ereport(ERROR,
   19983              :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
   19984              :                  errmsg("cannot use \"list\" partition strategy with more than one column")));
   19985              : 
   19986              :     /*
   19987              :      * Create a dummy ParseState and insert the target relation as its sole
   19988              :      * rangetable entry.  We need a ParseState for transformExpr.
   19989              :      */
   19990         3534 :     pstate = make_parsestate(NULL);
   19991         3534 :     nsitem = addRangeTableEntryForRelation(pstate, rel, AccessShareLock,
   19992              :                                            NULL, false, true);
   19993         3534 :     addNSItemToQuery(pstate, nsitem, true, true, true);
   19994              : 
   19995              :     /* take care of any partition expressions */
   19996         7370 :     foreach(l, partspec->partParams)
   19997              :     {
   19998         3852 :         PartitionElem *pelem = lfirst_node(PartitionElem, l);
   19999              : 
   20000         3852 :         if (pelem->expr)
   20001              :         {
   20002              :             /* Copy, to avoid scribbling on the input */
   20003          232 :             pelem = copyObject(pelem);
   20004              : 
   20005              :             /* Now do parse transformation of the expression */
   20006          232 :             pelem->expr = transformExpr(pstate, pelem->expr,
   20007              :                                         EXPR_KIND_PARTITION_EXPRESSION);
   20008              : 
   20009              :             /* we have to fix its collations too */
   20010          216 :             assign_expr_collations(pstate, pelem->expr);
   20011              :         }
   20012              : 
   20013         3836 :         newspec->partParams = lappend(newspec->partParams, pelem);
   20014              :     }
   20015              : 
   20016         3518 :     return newspec;
   20017              : }
   20018              : 
   20019              : /*
   20020              :  * Compute per-partition-column information from a list of PartitionElems.
   20021              :  * Expressions in the PartitionElems must be parse-analyzed already.
   20022              :  */
   20023              : static void
   20024         3518 : ComputePartitionAttrs(ParseState *pstate, Relation rel, List *partParams, AttrNumber *partattrs,
   20025              :                       List **partexprs, Oid *partopclass, Oid *partcollation,
   20026              :                       PartitionStrategy strategy)
   20027              : {
   20028              :     int         attn;
   20029              :     ListCell   *lc;
   20030              :     Oid         am_oid;
   20031              : 
   20032         3518 :     attn = 0;
   20033         7266 :     foreach(lc, partParams)
   20034              :     {
   20035         3836 :         PartitionElem *pelem = lfirst_node(PartitionElem, lc);
   20036              :         Oid         atttype;
   20037              :         Oid         attcollation;
   20038              : 
   20039         3836 :         if (pelem->name != NULL)
   20040              :         {
   20041              :             /* Simple attribute reference */
   20042              :             HeapTuple   atttuple;
   20043              :             Form_pg_attribute attform;
   20044              : 
   20045         3620 :             atttuple = SearchSysCacheAttName(RelationGetRelid(rel),
   20046         3620 :                                              pelem->name);
   20047         3620 :             if (!HeapTupleIsValid(atttuple))
   20048            8 :                 ereport(ERROR,
   20049              :                         (errcode(ERRCODE_UNDEFINED_COLUMN),
   20050              :                          errmsg("column \"%s\" named in partition key does not exist",
   20051              :                                 pelem->name),
   20052              :                          parser_errposition(pstate, pelem->location)));
   20053         3612 :             attform = (Form_pg_attribute) GETSTRUCT(atttuple);
   20054              : 
   20055         3612 :             if (attform->attnum <= 0)
   20056            4 :                 ereport(ERROR,
   20057              :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
   20058              :                          errmsg("cannot use system column \"%s\" in partition key",
   20059              :                                 pelem->name),
   20060              :                          parser_errposition(pstate, pelem->location)));
   20061              : 
   20062              :             /*
   20063              :              * Stored generated columns cannot work: They are computed after
   20064              :              * BEFORE triggers, but partition routing is done before all
   20065              :              * triggers.  Maybe virtual generated columns could be made to
   20066              :              * work, but then they would need to be handled as an expression
   20067              :              * below.
   20068              :              */
   20069         3608 :             if (attform->attgenerated)
   20070            8 :                 ereport(ERROR,
   20071              :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
   20072              :                          errmsg("cannot use generated column in partition key"),
   20073              :                          errdetail("Column \"%s\" is a generated column.",
   20074              :                                    pelem->name),
   20075              :                          parser_errposition(pstate, pelem->location)));
   20076              : 
   20077         3600 :             partattrs[attn] = attform->attnum;
   20078         3600 :             atttype = attform->atttypid;
   20079         3600 :             attcollation = attform->attcollation;
   20080         3600 :             ReleaseSysCache(atttuple);
   20081              :         }
   20082              :         else
   20083              :         {
   20084              :             /* Expression */
   20085          216 :             Node       *expr = pelem->expr;
   20086              :             char        partattname[16];
   20087          216 :             Bitmapset  *expr_attrs = NULL;
   20088              :             int         i;
   20089              : 
   20090              :             Assert(expr != NULL);
   20091          216 :             atttype = exprType(expr);
   20092          216 :             attcollation = exprCollation(expr);
   20093              : 
   20094              :             /*
   20095              :              * The expression must be of a storable type (e.g., not RECORD).
   20096              :              * The test is the same as for whether a table column is of a safe
   20097              :              * type (which is why we needn't check for the non-expression
   20098              :              * case).
   20099              :              */
   20100          216 :             snprintf(partattname, sizeof(partattname), "%d", attn + 1);
   20101          216 :             CheckAttributeType(partattname,
   20102              :                                atttype, attcollation,
   20103              :                                NIL, CHKATYPE_IS_PARTKEY);
   20104              : 
   20105              :             /*
   20106              :              * Strip any top-level COLLATE clause.  This ensures that we treat
   20107              :              * "x COLLATE y" and "(x COLLATE y)" alike.
   20108              :              */
   20109          208 :             while (IsA(expr, CollateExpr))
   20110            0 :                 expr = (Node *) ((CollateExpr *) expr)->arg;
   20111              : 
   20112              :             /*
   20113              :              * Examine all the columns in the partition key expression. When
   20114              :              * the whole-row reference is present, examine all the columns of
   20115              :              * the partitioned table.
   20116              :              */
   20117          208 :             pull_varattnos(expr, 1, &expr_attrs);
   20118          208 :             if (bms_is_member(0 - FirstLowInvalidHeapAttributeNumber, expr_attrs))
   20119              :             {
   20120           40 :                 expr_attrs = bms_add_range(expr_attrs,
   20121              :                                            1 - FirstLowInvalidHeapAttributeNumber,
   20122           20 :                                            RelationGetNumberOfAttributes(rel) - FirstLowInvalidHeapAttributeNumber);
   20123           20 :                 expr_attrs = bms_del_member(expr_attrs, 0 - FirstLowInvalidHeapAttributeNumber);
   20124              :             }
   20125              : 
   20126          208 :             i = -1;
   20127          457 :             while ((i = bms_next_member(expr_attrs, i)) >= 0)
   20128              :             {
   20129          281 :                 AttrNumber  attno = i + FirstLowInvalidHeapAttributeNumber;
   20130              : 
   20131              :                 Assert(attno != 0);
   20132              : 
   20133              :                 /*
   20134              :                  * Cannot allow system column references, since that would
   20135              :                  * make partition routing impossible: their values won't be
   20136              :                  * known yet when we need to do that.
   20137              :                  */
   20138          281 :                 if (attno < 0)
   20139            0 :                     ereport(ERROR,
   20140              :                             (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
   20141              :                              errmsg("partition key expressions cannot contain system column references")));
   20142              : 
   20143              :                 /*
   20144              :                  * Stored generated columns cannot work: They are computed
   20145              :                  * after BEFORE triggers, but partition routing is done before
   20146              :                  * all triggers.  Virtual generated columns could probably
   20147              :                  * work, but it would require more work elsewhere (for example
   20148              :                  * SET EXPRESSION would need to check whether the column is
   20149              :                  * used in partition keys).  Seems safer to prohibit for now.
   20150              :                  */
   20151          281 :                 if (TupleDescAttr(RelationGetDescr(rel), attno - 1)->attgenerated)
   20152           32 :                     ereport(ERROR,
   20153              :                             (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
   20154              :                              errmsg("cannot use generated column in partition key"),
   20155              :                              errdetail("Column \"%s\" is a generated column.",
   20156              :                                        get_attname(RelationGetRelid(rel), attno, false)),
   20157              :                              parser_errposition(pstate, pelem->location)));
   20158              :             }
   20159              : 
   20160          176 :             if (IsA(expr, Var) &&
   20161            8 :                 ((Var *) expr)->varattno > 0)
   20162              :             {
   20163              : 
   20164              :                 /*
   20165              :                  * User wrote "(column)" or "(column COLLATE something)".
   20166              :                  * Treat it like simple attribute anyway.
   20167              :                  */
   20168            4 :                 partattrs[attn] = ((Var *) expr)->varattno;
   20169              :             }
   20170              :             else
   20171              :             {
   20172          172 :                 partattrs[attn] = 0;    /* marks the column as expression */
   20173          172 :                 *partexprs = lappend(*partexprs, expr);
   20174              : 
   20175              :                 /*
   20176              :                  * transformPartitionSpec() should have already rejected
   20177              :                  * subqueries, aggregates, window functions, and SRFs, based
   20178              :                  * on the EXPR_KIND_ for partition expressions.
   20179              :                  */
   20180              : 
   20181              :                 /*
   20182              :                  * Preprocess the expression before checking for mutability.
   20183              :                  * This is essential for the reasons described in
   20184              :                  * contain_mutable_functions_after_planning.  However, we call
   20185              :                  * expression_planner for ourselves rather than using that
   20186              :                  * function, because if constant-folding reduces the
   20187              :                  * expression to a constant, we'd like to know that so we can
   20188              :                  * complain below.
   20189              :                  *
   20190              :                  * Like contain_mutable_functions_after_planning, assume that
   20191              :                  * expression_planner won't scribble on its input, so this
   20192              :                  * won't affect the partexprs entry we saved above.
   20193              :                  */
   20194          172 :                 expr = (Node *) expression_planner((Expr *) expr);
   20195              : 
   20196              :                 /*
   20197              :                  * Partition expressions cannot contain mutable functions,
   20198              :                  * because a given row must always map to the same partition
   20199              :                  * as long as there is no change in the partition boundary
   20200              :                  * structure.
   20201              :                  */
   20202          172 :                 if (contain_mutable_functions(expr))
   20203            4 :                     ereport(ERROR,
   20204              :                             (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
   20205              :                              errmsg("functions in partition key expression must be marked IMMUTABLE")));
   20206              : 
   20207              :                 /*
   20208              :                  * While it is not exactly *wrong* for a partition expression
   20209              :                  * to be a constant, it seems better to reject such keys.
   20210              :                  */
   20211          168 :                 if (IsA(expr, Const))
   20212            8 :                     ereport(ERROR,
   20213              :                             (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
   20214              :                              errmsg("cannot use constant expression as partition key")));
   20215              :             }
   20216              :         }
   20217              : 
   20218              :         /*
   20219              :          * Apply collation override if any
   20220              :          */
   20221         3764 :         if (pelem->collation)
   20222           36 :             attcollation = get_collation_oid(pelem->collation, false);
   20223              : 
   20224              :         /*
   20225              :          * Check we have a collation iff it's a collatable type.  The only
   20226              :          * expected failures here are (1) COLLATE applied to a noncollatable
   20227              :          * type, or (2) partition expression had an unresolved collation. But
   20228              :          * we might as well code this to be a complete consistency check.
   20229              :          */
   20230         3764 :         if (type_is_collatable(atttype))
   20231              :         {
   20232          436 :             if (!OidIsValid(attcollation))
   20233            0 :                 ereport(ERROR,
   20234              :                         (errcode(ERRCODE_INDETERMINATE_COLLATION),
   20235              :                          errmsg("could not determine which collation to use for partition expression"),
   20236              :                          errhint("Use the COLLATE clause to set the collation explicitly.")));
   20237              :         }
   20238              :         else
   20239              :         {
   20240         3328 :             if (OidIsValid(attcollation))
   20241            0 :                 ereport(ERROR,
   20242              :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
   20243              :                          errmsg("collations are not supported by type %s",
   20244              :                                 format_type_be(atttype))));
   20245              :         }
   20246              : 
   20247         3764 :         partcollation[attn] = attcollation;
   20248              : 
   20249              :         /*
   20250              :          * Identify the appropriate operator class.  For list and range
   20251              :          * partitioning, we use a btree operator class; hash partitioning uses
   20252              :          * a hash operator class.
   20253              :          */
   20254         3764 :         if (strategy == PARTITION_STRATEGY_HASH)
   20255          215 :             am_oid = HASH_AM_OID;
   20256              :         else
   20257         3549 :             am_oid = BTREE_AM_OID;
   20258              : 
   20259         3764 :         if (!pelem->opclass)
   20260              :         {
   20261         3672 :             partopclass[attn] = GetDefaultOpClass(atttype, am_oid);
   20262              : 
   20263         3672 :             if (!OidIsValid(partopclass[attn]))
   20264              :             {
   20265            8 :                 if (strategy == PARTITION_STRATEGY_HASH)
   20266            0 :                     ereport(ERROR,
   20267              :                             (errcode(ERRCODE_UNDEFINED_OBJECT),
   20268              :                              errmsg("data type %s has no default operator class for access method \"%s\"",
   20269              :                                     format_type_be(atttype), "hash"),
   20270              :                              errhint("You must specify a hash operator class or define a default hash operator class for the data type.")));
   20271              :                 else
   20272            8 :                     ereport(ERROR,
   20273              :                             (errcode(ERRCODE_UNDEFINED_OBJECT),
   20274              :                              errmsg("data type %s has no default operator class for access method \"%s\"",
   20275              :                                     format_type_be(atttype), "btree"),
   20276              :                              errhint("You must specify a btree operator class or define a default btree operator class for the data type.")));
   20277              :             }
   20278              :         }
   20279              :         else
   20280           92 :             partopclass[attn] = ResolveOpClass(pelem->opclass,
   20281              :                                                atttype,
   20282              :                                                am_oid == HASH_AM_OID ? "hash" : "btree",
   20283              :                                                am_oid);
   20284              : 
   20285         3748 :         attn++;
   20286              :     }
   20287         3430 : }
   20288              : 
   20289              : /*
   20290              :  * PartConstraintImpliedByRelConstraint
   20291              :  *      Do scanrel's existing constraints imply the partition constraint?
   20292              :  *
   20293              :  * "Existing constraints" include its check constraints and column-level
   20294              :  * not-null constraints.  partConstraint describes the partition constraint,
   20295              :  * in implicit-AND form.
   20296              :  */
   20297              : bool
   20298         2048 : PartConstraintImpliedByRelConstraint(Relation scanrel,
   20299              :                                      List *partConstraint)
   20300              : {
   20301         2048 :     List       *existConstraint = NIL;
   20302         2048 :     TupleConstr *constr = RelationGetDescr(scanrel)->constr;
   20303              :     int         i;
   20304              : 
   20305         2048 :     if (constr && constr->has_not_null)
   20306              :     {
   20307          534 :         int         natts = scanrel->rd_att->natts;
   20308              : 
   20309         1812 :         for (i = 1; i <= natts; i++)
   20310              :         {
   20311         1278 :             CompactAttribute *att = TupleDescCompactAttr(scanrel->rd_att, i - 1);
   20312              : 
   20313              :             /* invalid not-null constraint must be ignored here */
   20314         1278 :             if (att->attnullability == ATTNULLABLE_VALID && !att->attisdropped)
   20315              :             {
   20316          727 :                 Form_pg_attribute wholeatt = TupleDescAttr(scanrel->rd_att, i - 1);
   20317          727 :                 NullTest   *ntest = makeNode(NullTest);
   20318              : 
   20319          727 :                 ntest->arg = (Expr *) makeVar(1,
   20320              :                                               i,
   20321              :                                               wholeatt->atttypid,
   20322              :                                               wholeatt->atttypmod,
   20323              :                                               wholeatt->attcollation,
   20324              :                                               0);
   20325          727 :                 ntest->nulltesttype = IS_NOT_NULL;
   20326              : 
   20327              :                 /*
   20328              :                  * argisrow=false is correct even for a composite column,
   20329              :                  * because attnotnull does not represent a SQL-spec IS NOT
   20330              :                  * NULL test in such a case, just IS DISTINCT FROM NULL.
   20331              :                  */
   20332          727 :                 ntest->argisrow = false;
   20333          727 :                 ntest->location = -1;
   20334          727 :                 existConstraint = lappend(existConstraint, ntest);
   20335              :             }
   20336              :         }
   20337              :     }
   20338              : 
   20339         2048 :     return ConstraintImpliedByRelConstraint(scanrel, partConstraint, existConstraint);
   20340              : }
   20341              : 
   20342              : /*
   20343              :  * ConstraintImpliedByRelConstraint
   20344              :  *      Do scanrel's existing constraints imply the given constraint?
   20345              :  *
   20346              :  * testConstraint is the constraint to validate. provenConstraint is a
   20347              :  * caller-provided list of conditions which this function may assume
   20348              :  * to be true. Both provenConstraint and testConstraint must be in
   20349              :  * implicit-AND form, must only contain immutable clauses, and must
   20350              :  * contain only Vars with varno = 1.
   20351              :  */
   20352              : bool
   20353         2860 : ConstraintImpliedByRelConstraint(Relation scanrel, List *testConstraint, List *provenConstraint)
   20354              : {
   20355         2860 :     List       *existConstraint = list_copy(provenConstraint);
   20356         2860 :     TupleConstr *constr = RelationGetDescr(scanrel)->constr;
   20357              :     int         num_check,
   20358              :                 i;
   20359              : 
   20360         2860 :     num_check = (constr != NULL) ? constr->num_check : 0;
   20361         3196 :     for (i = 0; i < num_check; i++)
   20362              :     {
   20363              :         Node       *cexpr;
   20364              : 
   20365              :         /*
   20366              :          * If this constraint hasn't been fully validated yet, we must ignore
   20367              :          * it here.
   20368              :          */
   20369          336 :         if (!constr->check[i].ccvalid)
   20370           12 :             continue;
   20371              : 
   20372              :         /*
   20373              :          * NOT ENFORCED constraints are always marked as invalid, which should
   20374              :          * have been ignored.
   20375              :          */
   20376              :         Assert(constr->check[i].ccenforced);
   20377              : 
   20378          324 :         cexpr = stringToNode(constr->check[i].ccbin);
   20379              : 
   20380              :         /*
   20381              :          * Run each expression through const-simplification and
   20382              :          * canonicalization.  It is necessary, because we will be comparing it
   20383              :          * to similarly-processed partition constraint expressions, and may
   20384              :          * fail to detect valid matches without this.
   20385              :          */
   20386          324 :         cexpr = eval_const_expressions(NULL, cexpr);
   20387          324 :         cexpr = (Node *) canonicalize_qual((Expr *) cexpr, true);
   20388              : 
   20389          324 :         existConstraint = list_concat(existConstraint,
   20390          324 :                                       make_ands_implicit((Expr *) cexpr));
   20391              :     }
   20392              : 
   20393              :     /*
   20394              :      * Try to make the proof.  Since we are comparing CHECK constraints, we
   20395              :      * need to use weak implication, i.e., we assume existConstraint is
   20396              :      * not-false and try to prove the same for testConstraint.
   20397              :      *
   20398              :      * Note that predicate_implied_by assumes its first argument is known
   20399              :      * immutable.  That should always be true for both NOT NULL and partition
   20400              :      * constraints, so we don't test it here.
   20401              :      */
   20402         2860 :     return predicate_implied_by(testConstraint, existConstraint, true);
   20403              : }
   20404              : 
   20405              : /*
   20406              :  * QueuePartitionConstraintValidation
   20407              :  *
   20408              :  * Add an entry to wqueue to have the given partition constraint validated by
   20409              :  * Phase 3, for the given relation, and all its children.
   20410              :  *
   20411              :  * We first verify whether the given constraint is implied by pre-existing
   20412              :  * relation constraints; if it is, there's no need to scan the table to
   20413              :  * validate, so don't queue in that case.
   20414              :  */
   20415              : static void
   20416         1723 : QueuePartitionConstraintValidation(List **wqueue, Relation scanrel,
   20417              :                                    List *partConstraint,
   20418              :                                    bool validate_default)
   20419              : {
   20420              :     /*
   20421              :      * Based on the table's existing constraints, determine whether or not we
   20422              :      * may skip scanning the table.
   20423              :      */
   20424         1723 :     if (PartConstraintImpliedByRelConstraint(scanrel, partConstraint))
   20425              :     {
   20426           55 :         if (!validate_default)
   20427           41 :             ereport(DEBUG1,
   20428              :                     (errmsg_internal("partition constraint for table \"%s\" is implied by existing constraints",
   20429              :                                      RelationGetRelationName(scanrel))));
   20430              :         else
   20431           14 :             ereport(DEBUG1,
   20432              :                     (errmsg_internal("updated partition constraint for default partition \"%s\" is implied by existing constraints",
   20433              :                                      RelationGetRelationName(scanrel))));
   20434           55 :         return;
   20435              :     }
   20436              : 
   20437              :     /*
   20438              :      * Constraints proved insufficient. For plain relations, queue a
   20439              :      * validation item now; for partitioned tables, recurse to process each
   20440              :      * partition.
   20441              :      */
   20442         1668 :     if (scanrel->rd_rel->relkind == RELKIND_RELATION)
   20443              :     {
   20444              :         AlteredTableInfo *tab;
   20445              : 
   20446              :         /* Grab a work queue entry. */
   20447         1393 :         tab = ATGetQueueEntry(wqueue, scanrel);
   20448              :         Assert(tab->partition_constraint == NULL);
   20449         1393 :         tab->partition_constraint = (Expr *) linitial(partConstraint);
   20450         1393 :         tab->validate_default = validate_default;
   20451              :     }
   20452          275 :     else if (scanrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
   20453              :     {
   20454          244 :         PartitionDesc partdesc = RelationGetPartitionDesc(scanrel, true);
   20455              :         int         i;
   20456              : 
   20457          524 :         for (i = 0; i < partdesc->nparts; i++)
   20458              :         {
   20459              :             Relation    part_rel;
   20460              :             List       *thisPartConstraint;
   20461              : 
   20462              :             /*
   20463              :              * This is the minimum lock we need to prevent deadlocks.
   20464              :              */
   20465          280 :             part_rel = table_open(partdesc->oids[i], AccessExclusiveLock);
   20466              : 
   20467              :             /*
   20468              :              * Adjust the constraint for scanrel so that it matches this
   20469              :              * partition's attribute numbers.
   20470              :              */
   20471              :             thisPartConstraint =
   20472          280 :                 map_partition_varattnos(partConstraint, 1,
   20473              :                                         part_rel, scanrel);
   20474              : 
   20475          280 :             QueuePartitionConstraintValidation(wqueue, part_rel,
   20476              :                                                thisPartConstraint,
   20477              :                                                validate_default);
   20478          280 :             table_close(part_rel, NoLock);  /* keep lock till commit */
   20479              :         }
   20480              :     }
   20481              : }
   20482              : 
   20483              : /*
   20484              :  * attachPartitionTable: attach a new partition to the partitioned table
   20485              :  *
   20486              :  * wqueue: the ALTER TABLE work queue; can be NULL when not running as part
   20487              :  *   of an ALTER TABLE sequence.
   20488              :  * rel: partitioned relation;
   20489              :  * attachrel: relation of attached partition;
   20490              :  * bound: bounds of attached relation.
   20491              :  */
   20492              : static void
   20493         1906 : attachPartitionTable(List **wqueue, Relation rel, Relation attachrel, PartitionBoundSpec *bound)
   20494              : {
   20495              :     /*
   20496              :      * Create an inheritance; the relevant checks are performed inside the
   20497              :      * function.
   20498              :      */
   20499         1906 :     CreateInheritance(attachrel, rel, true);
   20500              : 
   20501              :     /* Update the pg_class entry. */
   20502         1834 :     StorePartitionBound(attachrel, rel, bound);
   20503              : 
   20504              :     /* Ensure there exists a correct set of indexes in the partition. */
   20505         1834 :     AttachPartitionEnsureIndexes(wqueue, rel, attachrel);
   20506              : 
   20507              :     /* and triggers */
   20508         1814 :     CloneRowTriggersToPartition(rel, attachrel);
   20509              : 
   20510              :     /*
   20511              :      * Clone foreign key constraints.  Callee is responsible for setting up
   20512              :      * for phase 3 constraint verification.
   20513              :      */
   20514         1810 :     CloneForeignKeyConstraints(wqueue, rel, attachrel);
   20515         1798 : }
   20516              : 
   20517              : /*
   20518              :  * ALTER TABLE <name> ATTACH PARTITION <partition-name> FOR VALUES
   20519              :  *
   20520              :  * Return the address of the newly attached partition.
   20521              :  */
   20522              : static ObjectAddress
   20523         1594 : ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd,
   20524              :                       AlterTableUtilityContext *context)
   20525              : {
   20526              :     Relation    attachrel,
   20527              :                 catalog;
   20528              :     List       *attachrel_children;
   20529              :     List       *partConstraint;
   20530              :     SysScanDesc scan;
   20531              :     ScanKeyData skey;
   20532              :     AttrNumber  attno;
   20533              :     int         natts;
   20534              :     TupleDesc   tupleDesc;
   20535              :     ObjectAddress address;
   20536              :     const char *trigger_name;
   20537              :     Oid         defaultPartOid;
   20538              :     List       *partBoundConstraint;
   20539         1594 :     List       *exceptpuboids = NIL;
   20540         1594 :     ParseState *pstate = make_parsestate(NULL);
   20541              : 
   20542         1594 :     pstate->p_sourcetext = context->queryString;
   20543              : 
   20544              :     /*
   20545              :      * We must lock the default partition if one exists, because attaching a
   20546              :      * new partition will change its partition constraint.
   20547              :      */
   20548              :     defaultPartOid =
   20549         1594 :         get_default_oid_from_partdesc(RelationGetPartitionDesc(rel, true));
   20550         1594 :     if (OidIsValid(defaultPartOid))
   20551          117 :         LockRelationOid(defaultPartOid, AccessExclusiveLock);
   20552              : 
   20553         1594 :     attachrel = table_openrv(cmd->name, AccessExclusiveLock);
   20554              : 
   20555              :     /*
   20556              :      * XXX I think it'd be a good idea to grab locks on all tables referenced
   20557              :      * by FKs at this point also.
   20558              :      */
   20559              : 
   20560              :     /*
   20561              :      * Must be owner of both parent and source table -- parent was checked by
   20562              :      * ATSimplePermissions call in ATPrepCmd
   20563              :      */
   20564         1590 :     ATSimplePermissions(AT_AttachPartition, attachrel,
   20565              :                         ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
   20566              : 
   20567              :     /* A partition can only have one parent */
   20568         1586 :     if (attachrel->rd_rel->relispartition)
   20569            4 :         ereport(ERROR,
   20570              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   20571              :                  errmsg("\"%s\" is already a partition",
   20572              :                         RelationGetRelationName(attachrel))));
   20573              : 
   20574         1582 :     if (OidIsValid(attachrel->rd_rel->reloftype))
   20575            4 :         ereport(ERROR,
   20576              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   20577              :                  errmsg("cannot attach a typed table as partition")));
   20578              : 
   20579              :     /*
   20580              :      * Disallow attaching a partition if the table is referenced in a
   20581              :      * publication EXCEPT clause. Changing the partition hierarchy could alter
   20582              :      * the effective publication membership.
   20583              :      */
   20584         1578 :     exceptpuboids = GetRelationExcludedPublications(RelationGetRelid(attachrel));
   20585         1578 :     if (exceptpuboids != NIL)
   20586              :     {
   20587            4 :         bool        first = true;
   20588              :         StringInfoData pubnames;
   20589              : 
   20590            4 :         initStringInfo(&pubnames);
   20591              : 
   20592           12 :         foreach_oid(pubid, exceptpuboids)
   20593              :         {
   20594            4 :             char       *pubname = get_publication_name(pubid, false);
   20595              : 
   20596            4 :             if (!first)
   20597              :             {
   20598              :                 /*
   20599              :                  * translator: This is a separator in a list of publication
   20600              :                  * names.
   20601              :                  */
   20602            0 :                 appendStringInfoString(&pubnames, _(", "));
   20603              :             }
   20604              : 
   20605            4 :             first = false;
   20606              : 
   20607            4 :             appendStringInfo(&pubnames, _("\"%s\""), pubname);
   20608              :         }
   20609              : 
   20610            4 :         ereport(ERROR,
   20611              :                 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
   20612              :                 errmsg_plural("cannot attach table \"%s\" as partition because it is referenced in publication %s EXCEPT clause",
   20613              :                               "cannot attach table \"%s\" as partition because it is referenced in publications %s EXCEPT clause",
   20614              :                               list_length(exceptpuboids),
   20615              :                               RelationGetRelationName(attachrel),
   20616              :                               pubnames.data),
   20617              :                 errdetail("The publication EXCEPT clause cannot contain tables that are partitions."),
   20618              :                 errhint("Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES."));
   20619              :     }
   20620              : 
   20621         1574 :     list_free(exceptpuboids);
   20622              : 
   20623              :     /*
   20624              :      * Table being attached should not already be part of inheritance; either
   20625              :      * as a child table...
   20626              :      */
   20627         1574 :     catalog = table_open(InheritsRelationId, AccessShareLock);
   20628         1574 :     ScanKeyInit(&skey,
   20629              :                 Anum_pg_inherits_inhrelid,
   20630              :                 BTEqualStrategyNumber, F_OIDEQ,
   20631              :                 ObjectIdGetDatum(RelationGetRelid(attachrel)));
   20632         1574 :     scan = systable_beginscan(catalog, InheritsRelidSeqnoIndexId, true,
   20633              :                               NULL, 1, &skey);
   20634         1574 :     if (HeapTupleIsValid(systable_getnext(scan)))
   20635            4 :         ereport(ERROR,
   20636              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   20637              :                  errmsg("cannot attach inheritance child as partition")));
   20638         1570 :     systable_endscan(scan);
   20639              : 
   20640              :     /* ...or as a parent table (except the case when it is partitioned) */
   20641         1570 :     ScanKeyInit(&skey,
   20642              :                 Anum_pg_inherits_inhparent,
   20643              :                 BTEqualStrategyNumber, F_OIDEQ,
   20644              :                 ObjectIdGetDatum(RelationGetRelid(attachrel)));
   20645         1570 :     scan = systable_beginscan(catalog, InheritsParentIndexId, true, NULL,
   20646              :                               1, &skey);
   20647         1570 :     if (HeapTupleIsValid(systable_getnext(scan)) &&
   20648          184 :         attachrel->rd_rel->relkind == RELKIND_RELATION)
   20649            4 :         ereport(ERROR,
   20650              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   20651              :                  errmsg("cannot attach inheritance parent as partition")));
   20652         1566 :     systable_endscan(scan);
   20653         1566 :     table_close(catalog, AccessShareLock);
   20654              : 
   20655              :     /*
   20656              :      * Prevent circularity by seeing if rel is a partition of attachrel. (In
   20657              :      * particular, this disallows making a rel a partition of itself.)
   20658              :      *
   20659              :      * We do that by checking if rel is a member of the list of attachrel's
   20660              :      * partitions provided the latter is partitioned at all.  We want to avoid
   20661              :      * having to construct this list again, so we request the strongest lock
   20662              :      * on all partitions.  We need the strongest lock, because we may decide
   20663              :      * to scan them if we find out that the table being attached (or its leaf
   20664              :      * partitions) may contain rows that violate the partition constraint. If
   20665              :      * the table has a constraint that would prevent such rows, which by
   20666              :      * definition is present in all the partitions, we need not scan the
   20667              :      * table, nor its partitions.  But we cannot risk a deadlock by taking a
   20668              :      * weaker lock now and the stronger one only when needed.
   20669              :      */
   20670         1566 :     attachrel_children = find_all_inheritors(RelationGetRelid(attachrel),
   20671              :                                              AccessExclusiveLock, NULL);
   20672         1566 :     if (list_member_oid(attachrel_children, RelationGetRelid(rel)))
   20673            8 :         ereport(ERROR,
   20674              :                 (errcode(ERRCODE_DUPLICATE_TABLE),
   20675              :                  errmsg("circular inheritance not allowed"),
   20676              :                  errdetail("\"%s\" is already a child of \"%s\".",
   20677              :                            RelationGetRelationName(rel),
   20678              :                            RelationGetRelationName(attachrel))));
   20679              : 
   20680              :     /* If the parent is permanent, so must be all of its partitions. */
   20681         1558 :     if (rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP &&
   20682         1530 :         attachrel->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
   20683            4 :         ereport(ERROR,
   20684              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   20685              :                  errmsg("cannot attach a temporary relation as partition of permanent relation \"%s\"",
   20686              :                         RelationGetRelationName(rel))));
   20687              : 
   20688              :     /* Temp parent cannot have a partition that is itself not a temp */
   20689         1554 :     if (rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
   20690           28 :         attachrel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
   20691           12 :         ereport(ERROR,
   20692              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   20693              :                  errmsg("cannot attach a permanent relation as partition of temporary relation \"%s\"",
   20694              :                         RelationGetRelationName(rel))));
   20695              : 
   20696              :     /* If the parent is temp, it must belong to this session */
   20697         1542 :     if (RELATION_IS_OTHER_TEMP(rel))
   20698            0 :         ereport(ERROR,
   20699              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   20700              :                  errmsg("cannot attach as partition of temporary relation of another session")));
   20701              : 
   20702              :     /* Ditto for the partition */
   20703         1542 :     if (RELATION_IS_OTHER_TEMP(attachrel))
   20704            0 :         ereport(ERROR,
   20705              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   20706              :                  errmsg("cannot attach temporary relation of another session as partition")));
   20707              : 
   20708              :     /*
   20709              :      * Check if attachrel has any identity columns or any columns that aren't
   20710              :      * in the parent.
   20711              :      */
   20712         1542 :     tupleDesc = RelationGetDescr(attachrel);
   20713         1542 :     natts = tupleDesc->natts;
   20714         5304 :     for (attno = 1; attno <= natts; attno++)
   20715              :     {
   20716         3790 :         Form_pg_attribute attribute = TupleDescAttr(tupleDesc, attno - 1);
   20717         3790 :         char       *attributeName = NameStr(attribute->attname);
   20718              : 
   20719              :         /* Ignore dropped */
   20720         3790 :         if (attribute->attisdropped)
   20721          388 :             continue;
   20722              : 
   20723         3402 :         if (attribute->attidentity)
   20724           16 :             ereport(ERROR,
   20725              :                     errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
   20726              :                     errmsg("table \"%s\" being attached contains an identity column \"%s\"",
   20727              :                            RelationGetRelationName(attachrel), attributeName),
   20728              :                     errdetail("The new partition may not contain an identity column."));
   20729              : 
   20730              :         /* Try to find the column in parent (matching on column name) */
   20731         3386 :         if (!SearchSysCacheExists2(ATTNAME,
   20732              :                                    ObjectIdGetDatum(RelationGetRelid(rel)),
   20733              :                                    CStringGetDatum(attributeName)))
   20734           12 :             ereport(ERROR,
   20735              :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
   20736              :                      errmsg("table \"%s\" contains column \"%s\" not found in parent \"%s\"",
   20737              :                             RelationGetRelationName(attachrel), attributeName,
   20738              :                             RelationGetRelationName(rel)),
   20739              :                      errdetail("The new partition may contain only the columns present in parent.")));
   20740              :     }
   20741              : 
   20742              :     /*
   20743              :      * If child_rel has row-level triggers with transition tables, we
   20744              :      * currently don't allow it to become a partition.  See also prohibitions
   20745              :      * in ATExecAddInherit() and CreateTrigger().
   20746              :      */
   20747         1514 :     trigger_name = FindTriggerIncompatibleWithInheritance(attachrel->trigdesc);
   20748         1514 :     if (trigger_name != NULL)
   20749            4 :         ereport(ERROR,
   20750              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   20751              :                  errmsg("trigger \"%s\" prevents table \"%s\" from becoming a partition",
   20752              :                         trigger_name, RelationGetRelationName(attachrel)),
   20753              :                  errdetail("ROW triggers with transition tables are not supported on partitions.")));
   20754              : 
   20755              :     /*
   20756              :      * Check that the new partition's bound is valid and does not overlap any
   20757              :      * of existing partitions of the parent - note that it does not return on
   20758              :      * error.
   20759              :      */
   20760         1510 :     check_new_partition_bound(RelationGetRelationName(attachrel), rel,
   20761              :                               cmd->bound, pstate);
   20762              : 
   20763         1486 :     attachPartitionTable(wqueue, rel, attachrel, cmd->bound);
   20764              : 
   20765              :     /*
   20766              :      * Generate a partition constraint from the partition bound specification.
   20767              :      * If the parent itself is a partition, make sure to include its
   20768              :      * constraint as well.
   20769              :      */
   20770         1378 :     partBoundConstraint = get_qual_from_partbound(rel, cmd->bound);
   20771              : 
   20772              :     /*
   20773              :      * Use list_concat_copy() to avoid modifying partBoundConstraint in place,
   20774              :      * since it's needed later to construct the constraint expression for
   20775              :      * validating against the default partition, if any.
   20776              :      */
   20777         1378 :     partConstraint = list_concat_copy(partBoundConstraint,
   20778         1378 :                                       RelationGetPartitionQual(rel));
   20779              : 
   20780              :     /* Skip validation if there are no constraints to validate. */
   20781         1378 :     if (partConstraint)
   20782              :     {
   20783              :         /*
   20784              :          * Run the partition quals through const-simplification similar to
   20785              :          * check constraints.  We skip canonicalize_qual, though, because
   20786              :          * partition quals should be in canonical form already.
   20787              :          */
   20788              :         partConstraint =
   20789         1350 :             (List *) eval_const_expressions(NULL,
   20790              :                                             (Node *) partConstraint);
   20791              : 
   20792              :         /* XXX this sure looks wrong */
   20793         1350 :         partConstraint = list_make1(make_ands_explicit(partConstraint));
   20794              : 
   20795              :         /*
   20796              :          * Adjust the generated constraint to match this partition's attribute
   20797              :          * numbers.
   20798              :          */
   20799         1350 :         partConstraint = map_partition_varattnos(partConstraint, 1, attachrel,
   20800              :                                                  rel);
   20801              : 
   20802              :         /* Validate partition constraints against the table being attached. */
   20803         1350 :         QueuePartitionConstraintValidation(wqueue, attachrel, partConstraint,
   20804              :                                            false);
   20805              :     }
   20806              : 
   20807              :     /*
   20808              :      * If we're attaching a partition other than the default partition and a
   20809              :      * default one exists, then that partition's partition constraint changes,
   20810              :      * so add an entry to the work queue to validate it, too.  (We must not do
   20811              :      * this when the partition being attached is the default one; we already
   20812              :      * did it above!)
   20813              :      */
   20814         1378 :     if (OidIsValid(defaultPartOid))
   20815              :     {
   20816              :         Relation    defaultrel;
   20817              :         List       *defPartConstraint;
   20818              : 
   20819              :         Assert(!cmd->bound->is_default);
   20820              : 
   20821              :         /* we already hold a lock on the default partition */
   20822           93 :         defaultrel = table_open(defaultPartOid, NoLock);
   20823              :         defPartConstraint =
   20824           93 :             get_proposed_default_constraint(partBoundConstraint);
   20825              : 
   20826              :         /*
   20827              :          * Map the Vars in the constraint expression from rel's attnos to
   20828              :          * defaultrel's.
   20829              :          */
   20830              :         defPartConstraint =
   20831           93 :             map_partition_varattnos(defPartConstraint,
   20832              :                                     1, defaultrel, rel);
   20833           93 :         QueuePartitionConstraintValidation(wqueue, defaultrel,
   20834              :                                            defPartConstraint, true);
   20835              : 
   20836              :         /* keep our lock until commit. */
   20837           93 :         table_close(defaultrel, NoLock);
   20838              :     }
   20839              : 
   20840         1378 :     ObjectAddressSet(address, RelationRelationId, RelationGetRelid(attachrel));
   20841              : 
   20842              :     /*
   20843              :      * If the partition we just attached is partitioned itself, invalidate
   20844              :      * relcache for all descendent partitions too to ensure that their
   20845              :      * rd_partcheck expression trees are rebuilt; partitions already locked at
   20846              :      * the beginning of this function.
   20847              :      */
   20848         1378 :     if (attachrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
   20849              :     {
   20850              :         ListCell   *l;
   20851              : 
   20852          711 :         foreach(l, attachrel_children)
   20853              :         {
   20854          482 :             CacheInvalidateRelcacheByRelid(lfirst_oid(l));
   20855              :         }
   20856              :     }
   20857              : 
   20858              :     /* keep our lock until commit */
   20859         1378 :     table_close(attachrel, NoLock);
   20860              : 
   20861         1378 :     return address;
   20862              : }
   20863              : 
   20864              : /*
   20865              :  * AttachPartitionEnsureIndexes
   20866              :  *      subroutine for ATExecAttachPartition to create/match indexes
   20867              :  *
   20868              :  * Enforce the indexing rule for partitioned tables during ALTER TABLE / ATTACH
   20869              :  * PARTITION: every partition must have an index attached to each index on the
   20870              :  * partitioned table.
   20871              :  */
   20872              : static void
   20873         1834 : AttachPartitionEnsureIndexes(List **wqueue, Relation rel, Relation attachrel)
   20874              : {
   20875              :     List       *idxes;
   20876              :     List       *attachRelIdxs;
   20877              :     Relation   *attachrelIdxRels;
   20878              :     IndexInfo **attachInfos;
   20879              :     ListCell   *cell;
   20880              :     MemoryContext cxt;
   20881              :     MemoryContext oldcxt;
   20882              : 
   20883         1834 :     cxt = AllocSetContextCreate(CurrentMemoryContext,
   20884              :                                 "AttachPartitionEnsureIndexes",
   20885              :                                 ALLOCSET_DEFAULT_SIZES);
   20886         1834 :     oldcxt = MemoryContextSwitchTo(cxt);
   20887              : 
   20888         1834 :     idxes = RelationGetIndexList(rel);
   20889         1834 :     attachRelIdxs = RelationGetIndexList(attachrel);
   20890         1834 :     attachrelIdxRels = palloc_array(Relation, list_length(attachRelIdxs));
   20891         1834 :     attachInfos = palloc_array(IndexInfo *, list_length(attachRelIdxs));
   20892              : 
   20893              :     /* Build arrays of all existing indexes and their IndexInfos */
   20894         3937 :     foreach_oid(cldIdxId, attachRelIdxs)
   20895              :     {
   20896          269 :         int         i = foreach_current_index(cldIdxId);
   20897              : 
   20898          269 :         attachrelIdxRels[i] = index_open(cldIdxId, AccessShareLock);
   20899          269 :         attachInfos[i] = BuildIndexInfo(attachrelIdxRels[i]);
   20900              :     }
   20901              : 
   20902              :     /*
   20903              :      * If we're attaching a foreign table, we must fail if any of the indexes
   20904              :      * is a constraint index; otherwise, there's nothing to do here.  Do this
   20905              :      * before starting work, to avoid wasting the effort of building a few
   20906              :      * non-unique indexes before coming across a unique one.
   20907              :      */
   20908         1834 :     if (attachrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
   20909              :     {
   20910           55 :         foreach(cell, idxes)
   20911              :         {
   20912           24 :             Oid         idx = lfirst_oid(cell);
   20913           24 :             Relation    idxRel = index_open(idx, AccessShareLock);
   20914              : 
   20915           24 :             if (idxRel->rd_index->indisunique ||
   20916           16 :                 idxRel->rd_index->indisprimary)
   20917            8 :                 ereport(ERROR,
   20918              :                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   20919              :                          errmsg("cannot attach foreign table \"%s\" as partition of partitioned table \"%s\"",
   20920              :                                 RelationGetRelationName(attachrel),
   20921              :                                 RelationGetRelationName(rel)),
   20922              :                          errdetail("Partitioned table \"%s\" contains unique indexes.",
   20923              :                                    RelationGetRelationName(rel))));
   20924           16 :             index_close(idxRel, AccessShareLock);
   20925              :         }
   20926              : 
   20927           31 :         goto out;
   20928              :     }
   20929              : 
   20930              :     /*
   20931              :      * For each index on the partitioned table, find a matching one in the
   20932              :      * partition-to-be; if one is not found, create one.
   20933              :      */
   20934         2260 :     foreach(cell, idxes)
   20935              :     {
   20936          477 :         Oid         idx = lfirst_oid(cell);
   20937          477 :         Relation    idxRel = index_open(idx, AccessShareLock);
   20938              :         IndexInfo  *info;
   20939              :         AttrMap    *attmap;
   20940          477 :         bool        found = false;
   20941              :         Oid         constraintOid;
   20942              : 
   20943              :         /*
   20944              :          * Ignore indexes in the partitioned table other than partitioned
   20945              :          * indexes.
   20946              :          */
   20947          477 :         if (idxRel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
   20948              :         {
   20949            0 :             index_close(idxRel, AccessShareLock);
   20950            0 :             continue;
   20951              :         }
   20952              : 
   20953              :         /* construct an indexinfo to compare existing indexes against */
   20954          477 :         info = BuildIndexInfo(idxRel);
   20955          477 :         attmap = build_attrmap_by_name(RelationGetDescr(attachrel),
   20956              :                                        RelationGetDescr(rel),
   20957              :                                        false);
   20958          477 :         constraintOid = get_relation_idx_constraint_oid(RelationGetRelid(rel), idx);
   20959              : 
   20960              :         /*
   20961              :          * Scan the list of existing indexes in the partition-to-be, and mark
   20962              :          * the first matching, valid, unattached one we find, if any, as
   20963              :          * partition of the parent index.  If we find one, we're done.
   20964              :          */
   20965          517 :         for (int i = 0; i < list_length(attachRelIdxs); i++)
   20966              :         {
   20967          197 :             Oid         cldIdxId = RelationGetRelid(attachrelIdxRels[i]);
   20968          197 :             Oid         cldConstrOid = InvalidOid;
   20969              : 
   20970              :             /* does this index have a parent?  if so, can't use it */
   20971          197 :             if (attachrelIdxRels[i]->rd_rel->relispartition)
   20972            8 :                 continue;
   20973              : 
   20974              :             /* If this index is invalid, can't use it */
   20975          189 :             if (!attachrelIdxRels[i]->rd_index->indisvalid)
   20976            4 :                 continue;
   20977              : 
   20978          185 :             if (CompareIndexInfo(attachInfos[i], info,
   20979          185 :                                  attachrelIdxRels[i]->rd_indcollation,
   20980          185 :                                  idxRel->rd_indcollation,
   20981          185 :                                  attachrelIdxRels[i]->rd_opfamily,
   20982          185 :                                  idxRel->rd_opfamily,
   20983              :                                  attmap))
   20984              :             {
   20985              :                 /*
   20986              :                  * If this index is being created in the parent because of a
   20987              :                  * constraint, then the child needs to have a constraint also,
   20988              :                  * so look for one.  If there is no such constraint, this
   20989              :                  * index is no good, so keep looking.
   20990              :                  */
   20991          161 :                 if (OidIsValid(constraintOid))
   20992              :                 {
   20993              :                     cldConstrOid =
   20994           96 :                         get_relation_idx_constraint_oid(RelationGetRelid(attachrel),
   20995              :                                                         cldIdxId);
   20996              :                     /* no dice */
   20997           96 :                     if (!OidIsValid(cldConstrOid))
   20998            4 :                         continue;
   20999              : 
   21000              :                     /* Ensure they're both the same type of constraint */
   21001          184 :                     if (get_constraint_type(constraintOid) !=
   21002           92 :                         get_constraint_type(cldConstrOid))
   21003            0 :                         continue;
   21004              :                 }
   21005              : 
   21006              :                 /* bingo. */
   21007          157 :                 IndexSetParentIndex(attachrelIdxRels[i], idx);
   21008          157 :                 if (OidIsValid(constraintOid))
   21009           92 :                     ConstraintSetParentConstraint(cldConstrOid, constraintOid,
   21010              :                                                   RelationGetRelid(attachrel));
   21011          157 :                 found = true;
   21012              : 
   21013          157 :                 CommandCounterIncrement();
   21014          157 :                 break;
   21015              :             }
   21016              :         }
   21017              : 
   21018              :         /*
   21019              :          * If no suitable index was found in the partition-to-be, create one
   21020              :          * now.  Note that if this is a PK, not-null constraints must already
   21021              :          * exist.
   21022              :          */
   21023          477 :         if (!found)
   21024              :         {
   21025              :             IndexStmt  *stmt;
   21026              :             Oid         conOid;
   21027              : 
   21028          320 :             stmt = generateClonedIndexStmt(NULL,
   21029              :                                            idxRel, attmap,
   21030              :                                            &conOid);
   21031          320 :             DefineIndex(NULL,
   21032              :                         RelationGetRelid(attachrel), stmt, InvalidOid,
   21033              :                         RelationGetRelid(idxRel),
   21034              :                         conOid,
   21035              :                         -1,
   21036              :                         true, false, false, false, false);
   21037              :         }
   21038              : 
   21039          465 :         index_close(idxRel, AccessShareLock);
   21040              :     }
   21041              : 
   21042         1814 : out:
   21043              :     /* Clean up. */
   21044         2075 :     for (int i = 0; i < list_length(attachRelIdxs); i++)
   21045          261 :         index_close(attachrelIdxRels[i], AccessShareLock);
   21046         1814 :     MemoryContextSwitchTo(oldcxt);
   21047         1814 :     MemoryContextDelete(cxt);
   21048         1814 : }
   21049              : 
   21050              : /*
   21051              :  * CloneRowTriggersToPartition
   21052              :  *      subroutine for ATExecAttachPartition/DefineRelation to create row
   21053              :  *      triggers on partitions
   21054              :  */
   21055              : static void
   21056         2130 : CloneRowTriggersToPartition(Relation parent, Relation partition)
   21057              : {
   21058              :     Relation    pg_trigger;
   21059              :     ScanKeyData key;
   21060              :     SysScanDesc scan;
   21061              :     HeapTuple   tuple;
   21062              :     MemoryContext perTupCxt;
   21063              : 
   21064         2130 :     ScanKeyInit(&key, Anum_pg_trigger_tgrelid, BTEqualStrategyNumber,
   21065              :                 F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(parent)));
   21066         2130 :     pg_trigger = table_open(TriggerRelationId, RowExclusiveLock);
   21067         2130 :     scan = systable_beginscan(pg_trigger, TriggerRelidNameIndexId,
   21068              :                               true, NULL, 1, &key);
   21069              : 
   21070         2130 :     perTupCxt = AllocSetContextCreate(CurrentMemoryContext,
   21071              :                                       "clone trig", ALLOCSET_SMALL_SIZES);
   21072              : 
   21073         3519 :     while (HeapTupleIsValid(tuple = systable_getnext(scan)))
   21074              :     {
   21075         1393 :         Form_pg_trigger trigForm = (Form_pg_trigger) GETSTRUCT(tuple);
   21076              :         CreateTrigStmt *trigStmt;
   21077         1393 :         Node       *qual = NULL;
   21078              :         Datum       value;
   21079              :         bool        isnull;
   21080         1393 :         List       *cols = NIL;
   21081         1393 :         List       *trigargs = NIL;
   21082              :         MemoryContext oldcxt;
   21083              : 
   21084              :         /*
   21085              :          * Ignore statement-level triggers; those are not cloned.
   21086              :          */
   21087         1393 :         if (!TRIGGER_FOR_ROW(trigForm->tgtype))
   21088         1262 :             continue;
   21089              : 
   21090              :         /*
   21091              :          * Don't clone internal triggers, because the constraint cloning code
   21092              :          * will.
   21093              :          */
   21094         1365 :         if (trigForm->tgisinternal)
   21095         1234 :             continue;
   21096              : 
   21097              :         /*
   21098              :          * Complain if we find an unexpected trigger type.
   21099              :          */
   21100          131 :         if (!TRIGGER_FOR_BEFORE(trigForm->tgtype) &&
   21101          107 :             !TRIGGER_FOR_AFTER(trigForm->tgtype))
   21102            0 :             elog(ERROR, "unexpected trigger \"%s\" found",
   21103              :                  NameStr(trigForm->tgname));
   21104              : 
   21105              :         /* Use short-lived context for CREATE TRIGGER */
   21106          131 :         oldcxt = MemoryContextSwitchTo(perTupCxt);
   21107              : 
   21108              :         /*
   21109              :          * If there is a WHEN clause, generate a 'cooked' version of it that's
   21110              :          * appropriate for the partition.
   21111              :          */
   21112          131 :         value = heap_getattr(tuple, Anum_pg_trigger_tgqual,
   21113              :                              RelationGetDescr(pg_trigger), &isnull);
   21114          131 :         if (!isnull)
   21115              :         {
   21116            4 :             qual = stringToNode(TextDatumGetCString(value));
   21117            4 :             qual = (Node *) map_partition_varattnos((List *) qual, PRS2_OLD_VARNO,
   21118              :                                                     partition, parent);
   21119            4 :             qual = (Node *) map_partition_varattnos((List *) qual, PRS2_NEW_VARNO,
   21120              :                                                     partition, parent);
   21121              :         }
   21122              : 
   21123              :         /*
   21124              :          * If there is a column list, transform it to a list of column names.
   21125              :          * Note we don't need to map this list in any way ...
   21126              :          */
   21127          131 :         if (trigForm->tgattr.dim1 > 0)
   21128              :         {
   21129              :             int         i;
   21130              : 
   21131            8 :             for (i = 0; i < trigForm->tgattr.dim1; i++)
   21132              :             {
   21133              :                 Form_pg_attribute col;
   21134              : 
   21135            4 :                 col = TupleDescAttr(parent->rd_att,
   21136            4 :                                     trigForm->tgattr.values[i] - 1);
   21137            4 :                 cols = lappend(cols,
   21138            4 :                                makeString(pstrdup(NameStr(col->attname))));
   21139              :             }
   21140              :         }
   21141              : 
   21142              :         /* Reconstruct trigger arguments list. */
   21143          131 :         if (trigForm->tgnargs > 0)
   21144              :         {
   21145              :             char       *p;
   21146              : 
   21147           36 :             value = heap_getattr(tuple, Anum_pg_trigger_tgargs,
   21148              :                                  RelationGetDescr(pg_trigger), &isnull);
   21149           36 :             if (isnull)
   21150            0 :                 elog(ERROR, "tgargs is null for trigger \"%s\" in partition \"%s\"",
   21151              :                      NameStr(trigForm->tgname), RelationGetRelationName(partition));
   21152              : 
   21153           36 :             p = (char *) VARDATA_ANY(DatumGetByteaPP(value));
   21154              : 
   21155           80 :             for (int i = 0; i < trigForm->tgnargs; i++)
   21156              :             {
   21157           44 :                 trigargs = lappend(trigargs, makeString(pstrdup(p)));
   21158           44 :                 p += strlen(p) + 1;
   21159              :             }
   21160              :         }
   21161              : 
   21162          131 :         trigStmt = makeNode(CreateTrigStmt);
   21163          131 :         trigStmt->replace = false;
   21164          131 :         trigStmt->isconstraint = OidIsValid(trigForm->tgconstraint);
   21165          131 :         trigStmt->trigname = NameStr(trigForm->tgname);
   21166          131 :         trigStmt->relation = NULL;
   21167          131 :         trigStmt->funcname = NULL;   /* passed separately */
   21168          131 :         trigStmt->args = trigargs;
   21169          131 :         trigStmt->row = true;
   21170          131 :         trigStmt->timing = trigForm->tgtype & TRIGGER_TYPE_TIMING_MASK;
   21171          131 :         trigStmt->events = trigForm->tgtype & TRIGGER_TYPE_EVENT_MASK;
   21172          131 :         trigStmt->columns = cols;
   21173          131 :         trigStmt->whenClause = NULL; /* passed separately */
   21174          131 :         trigStmt->transitionRels = NIL; /* not supported at present */
   21175          131 :         trigStmt->deferrable = trigForm->tgdeferrable;
   21176          131 :         trigStmt->initdeferred = trigForm->tginitdeferred;
   21177          131 :         trigStmt->constrrel = NULL; /* passed separately */
   21178              : 
   21179          131 :         CreateTriggerFiringOn(trigStmt, NULL, RelationGetRelid(partition),
   21180              :                               trigForm->tgconstrrelid, InvalidOid, InvalidOid,
   21181              :                               trigForm->tgfoid, trigForm->oid, qual,
   21182          131 :                               false, true, trigForm->tgenabled);
   21183              : 
   21184          127 :         MemoryContextSwitchTo(oldcxt);
   21185          127 :         MemoryContextReset(perTupCxt);
   21186              :     }
   21187              : 
   21188         2126 :     MemoryContextDelete(perTupCxt);
   21189              : 
   21190         2126 :     systable_endscan(scan);
   21191         2126 :     table_close(pg_trigger, RowExclusiveLock);
   21192         2126 : }
   21193              : 
   21194              : /*
   21195              :  * ALTER TABLE DETACH PARTITION
   21196              :  *
   21197              :  * Return the address of the relation that is no longer a partition of rel.
   21198              :  *
   21199              :  * If concurrent mode is requested, we run in two transactions.  A side-
   21200              :  * effect is that this command cannot run in a multi-part ALTER TABLE.
   21201              :  * Currently, that's enforced by the grammar.
   21202              :  *
   21203              :  * The strategy for concurrency is to first modify the partition's
   21204              :  * pg_inherit catalog row to make it visible to everyone that the
   21205              :  * partition is detached, lock the partition against writes, and commit
   21206              :  * the transaction; anyone who requests the partition descriptor from
   21207              :  * that point onwards has to ignore such a partition.  In a second
   21208              :  * transaction, we wait until all transactions that could have seen the
   21209              :  * partition as attached are gone, then we remove the rest of partition
   21210              :  * metadata (pg_inherits and pg_class.relpartbounds).
   21211              :  */
   21212              : static ObjectAddress
   21213          365 : ATExecDetachPartition(List **wqueue, AlteredTableInfo *tab, Relation rel,
   21214              :                       RangeVar *name, bool concurrent)
   21215              : {
   21216              :     Relation    partRel;
   21217              :     ObjectAddress address;
   21218              :     Oid         defaultPartOid;
   21219              : 
   21220              :     /*
   21221              :      * We must lock the default partition, because detaching this partition
   21222              :      * will change its partition constraint.
   21223              :      */
   21224              :     defaultPartOid =
   21225          365 :         get_default_oid_from_partdesc(RelationGetPartitionDesc(rel, true));
   21226          365 :     if (OidIsValid(defaultPartOid))
   21227              :     {
   21228              :         /*
   21229              :          * Concurrent detaching when a default partition exists is not
   21230              :          * supported. The main problem is that the default partition
   21231              :          * constraint would change.  And there's a definitional problem: what
   21232              :          * should happen to the tuples that are being inserted that belong to
   21233              :          * the partition being detached?  Putting them on the partition being
   21234              :          * detached would be wrong, since they'd become "lost" after the
   21235              :          * detaching completes but we cannot put them in the default partition
   21236              :          * either until we alter its partition constraint.
   21237              :          *
   21238              :          * I think we could solve this problem if we effected the constraint
   21239              :          * change before committing the first transaction.  But the lock would
   21240              :          * have to remain AEL and it would cause concurrent query planning to
   21241              :          * be blocked, so changing it that way would be even worse.
   21242              :          */
   21243           74 :         if (concurrent)
   21244            8 :             ereport(ERROR,
   21245              :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
   21246              :                      errmsg("cannot detach partitions concurrently when a default partition exists")));
   21247           66 :         LockRelationOid(defaultPartOid, AccessExclusiveLock);
   21248              :     }
   21249              : 
   21250              :     /*
   21251              :      * In concurrent mode, the partition is locked with share-update-exclusive
   21252              :      * in the first transaction.  This allows concurrent transactions to be
   21253              :      * doing DML to the partition.
   21254              :      */
   21255          357 :     partRel = table_openrv(name, concurrent ? ShareUpdateExclusiveLock :
   21256              :                            AccessExclusiveLock);
   21257              : 
   21258              :     /*
   21259              :      * Check inheritance conditions and either delete the pg_inherits row (in
   21260              :      * non-concurrent mode) or just set the inhdetachpending flag.
   21261              :      */
   21262          349 :     if (!concurrent)
   21263          274 :         RemoveInheritance(partRel, rel, false);
   21264              :     else
   21265           75 :         MarkInheritDetached(partRel, rel);
   21266              : 
   21267              :     /*
   21268              :      * Ensure that foreign keys still hold after this detach.  This keeps
   21269              :      * locks on the referencing tables, which prevents concurrent transactions
   21270              :      * from adding rows that we wouldn't see.  For this to work in concurrent
   21271              :      * mode, it is critical that the partition appears as no longer attached
   21272              :      * for the RI queries as soon as the first transaction commits.
   21273              :      */
   21274          336 :     ATDetachCheckNoForeignKeyRefs(partRel);
   21275              : 
   21276              :     /*
   21277              :      * Concurrent mode has to work harder; first we add a new constraint to
   21278              :      * the partition that matches the partition constraint.  Then we close our
   21279              :      * existing transaction, and in a new one wait for all processes to catch
   21280              :      * up on the catalog updates we've done so far; at that point we can
   21281              :      * complete the operation.
   21282              :      */
   21283          314 :     if (concurrent)
   21284              :     {
   21285              :         Oid         partrelid,
   21286              :                     parentrelid;
   21287              :         LOCKTAG     tag;
   21288              :         char       *parentrelname;
   21289              :         char       *partrelname;
   21290              : 
   21291              :         /*
   21292              :          * We're almost done now; the only traces that remain are the
   21293              :          * pg_inherits tuple and the partition's relpartbounds.  Before we can
   21294              :          * remove those, we need to wait until all transactions that know that
   21295              :          * this is a partition are gone.
   21296              :          */
   21297              : 
   21298              :         /*
   21299              :          * Remember relation OIDs to re-acquire them later; and relation names
   21300              :          * too, for error messages if something is dropped in between.
   21301              :          */
   21302           72 :         partrelid = RelationGetRelid(partRel);
   21303           72 :         parentrelid = RelationGetRelid(rel);
   21304           72 :         parentrelname = MemoryContextStrdup(PortalContext,
   21305           72 :                                             RelationGetRelationName(rel));
   21306           72 :         partrelname = MemoryContextStrdup(PortalContext,
   21307           72 :                                           RelationGetRelationName(partRel));
   21308              : 
   21309              :         /* Invalidate relcache entries for the parent -- must be before close */
   21310           72 :         CacheInvalidateRelcache(rel);
   21311              : 
   21312           72 :         table_close(partRel, NoLock);
   21313           72 :         table_close(rel, NoLock);
   21314           72 :         tab->rel = NULL;
   21315              : 
   21316              :         /* Make updated catalog entry visible */
   21317           72 :         PopActiveSnapshot();
   21318           72 :         CommitTransactionCommand();
   21319              : 
   21320           72 :         StartTransactionCommand();
   21321              : 
   21322              :         /*
   21323              :          * Now wait.  This ensures that all queries that were planned
   21324              :          * including the partition are finished before we remove the rest of
   21325              :          * catalog entries.  We don't need or indeed want to acquire this
   21326              :          * lock, though -- that would block later queries.
   21327              :          *
   21328              :          * We don't need to concern ourselves with waiting for a lock on the
   21329              :          * partition itself, since we will acquire AccessExclusiveLock below.
   21330              :          */
   21331           72 :         SET_LOCKTAG_RELATION(tag, MyDatabaseId, parentrelid);
   21332           72 :         WaitForLockersMultiple(list_make1(&tag), AccessExclusiveLock, false);
   21333              : 
   21334              :         /*
   21335              :          * Now acquire locks in both relations again.  Note they may have been
   21336              :          * removed in the meantime, so care is required.
   21337              :          */
   21338           47 :         rel = try_relation_open(parentrelid, ShareUpdateExclusiveLock);
   21339           47 :         partRel = try_relation_open(partrelid, AccessExclusiveLock);
   21340              : 
   21341              :         /* If the relations aren't there, something bad happened; bail out */
   21342           47 :         if (rel == NULL)
   21343              :         {
   21344            0 :             if (partRel != NULL)    /* shouldn't happen */
   21345            0 :                 elog(WARNING, "dangling partition \"%s\" remains, can't fix",
   21346              :                      partrelname);
   21347            0 :             ereport(ERROR,
   21348              :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
   21349              :                      errmsg("partitioned table \"%s\" was removed concurrently",
   21350              :                             parentrelname)));
   21351              :         }
   21352           47 :         if (partRel == NULL)
   21353            0 :             ereport(ERROR,
   21354              :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
   21355              :                      errmsg("partition \"%s\" was removed concurrently", partrelname)));
   21356              : 
   21357           47 :         tab->rel = rel;
   21358              :     }
   21359              : 
   21360              :     /*
   21361              :      * Detaching the partition might involve TOAST table access, so ensure we
   21362              :      * have a valid snapshot.
   21363              :      */
   21364          289 :     PushActiveSnapshot(GetTransactionSnapshot());
   21365              : 
   21366              :     /* Do the final part of detaching */
   21367          289 :     DetachPartitionFinalize(rel, partRel, concurrent, defaultPartOid);
   21368              : 
   21369          288 :     PopActiveSnapshot();
   21370              : 
   21371          288 :     ObjectAddressSet(address, RelationRelationId, RelationGetRelid(partRel));
   21372              : 
   21373              :     /* keep our lock until commit */
   21374          288 :     table_close(partRel, NoLock);
   21375              : 
   21376          288 :     return address;
   21377              : }
   21378              : 
   21379              : /*
   21380              :  * Second part of ALTER TABLE .. DETACH.
   21381              :  *
   21382              :  * This is separate so that it can be run independently when the second
   21383              :  * transaction of the concurrent algorithm fails (crash or abort).
   21384              :  */
   21385              : static void
   21386          664 : DetachPartitionFinalize(Relation rel, Relation partRel, bool concurrent,
   21387              :                         Oid defaultPartOid)
   21388              : {
   21389              :     Relation    classRel;
   21390              :     List       *fks;
   21391              :     ListCell   *cell;
   21392              :     List       *indexes;
   21393              :     Datum       new_val[Natts_pg_class];
   21394              :     bool        new_null[Natts_pg_class],
   21395              :                 new_repl[Natts_pg_class];
   21396              :     HeapTuple   tuple,
   21397              :                 newtuple;
   21398          664 :     Relation    trigrel = NULL;
   21399          664 :     List       *fkoids = NIL;
   21400              : 
   21401          664 :     if (concurrent)
   21402              :     {
   21403              :         /*
   21404              :          * We can remove the pg_inherits row now. (In the non-concurrent case,
   21405              :          * this was already done).
   21406              :          */
   21407           54 :         RemoveInheritance(partRel, rel, true);
   21408              :     }
   21409              : 
   21410              :     /* Drop any triggers that were cloned on creation/attach. */
   21411          664 :     DropClonedTriggersFromPartition(RelationGetRelid(partRel));
   21412              : 
   21413              :     /*
   21414              :      * Detach any foreign keys that are inherited.  This includes creating
   21415              :      * additional action triggers.
   21416              :      */
   21417          664 :     fks = copyObject(RelationGetFKeyList(partRel));
   21418          664 :     if (fks != NIL)
   21419           60 :         trigrel = table_open(TriggerRelationId, RowExclusiveLock);
   21420              : 
   21421              :     /*
   21422              :      * It's possible that the partition being detached has a foreign key that
   21423              :      * references a partitioned table.  When that happens, there are multiple
   21424              :      * pg_constraint rows for the partition: one points to the partitioned
   21425              :      * table itself, while the others point to each of its partitions.  Only
   21426              :      * the topmost one is to be considered here; the child constraints must be
   21427              :      * left alone, because conceptually those aren't coming from our parent
   21428              :      * partitioned table, but from this partition itself.
   21429              :      *
   21430              :      * We implement this by collecting all the constraint OIDs in a first scan
   21431              :      * of the FK array, and skipping in the loop below those constraints whose
   21432              :      * parents are listed here.
   21433              :      */
   21434         1444 :     foreach_node(ForeignKeyCacheInfo, fk, fks)
   21435          116 :         fkoids = lappend_oid(fkoids, fk->conoid);
   21436              : 
   21437          780 :     foreach(cell, fks)
   21438              :     {
   21439          116 :         ForeignKeyCacheInfo *fk = lfirst(cell);
   21440              :         HeapTuple   contup;
   21441              :         Form_pg_constraint conform;
   21442              : 
   21443          116 :         contup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(fk->conoid));
   21444          116 :         if (!HeapTupleIsValid(contup))
   21445            0 :             elog(ERROR, "cache lookup failed for constraint %u", fk->conoid);
   21446          116 :         conform = (Form_pg_constraint) GETSTRUCT(contup);
   21447              : 
   21448              :         /*
   21449              :          * Consider only inherited foreign keys, and only if their parents
   21450              :          * aren't in the list.
   21451              :          */
   21452          116 :         if (conform->contype != CONSTRAINT_FOREIGN ||
   21453          216 :             !OidIsValid(conform->conparentid) ||
   21454          100 :             list_member_oid(fkoids, conform->conparentid))
   21455              :         {
   21456           44 :             ReleaseSysCache(contup);
   21457           44 :             continue;
   21458              :         }
   21459              : 
   21460              :         /*
   21461              :          * The constraint on this table must be marked no longer a child of
   21462              :          * the parent's constraint, as do its check triggers.
   21463              :          */
   21464           72 :         ConstraintSetParentConstraint(fk->conoid, InvalidOid, InvalidOid);
   21465              : 
   21466              :         /*
   21467              :          * Also, look up the partition's "check" triggers corresponding to the
   21468              :          * ENFORCED constraint being detached and detach them from the parent
   21469              :          * triggers. NOT ENFORCED constraints do not have these triggers;
   21470              :          * therefore, this step is not needed.
   21471              :          */
   21472           72 :         if (fk->conenforced)
   21473              :         {
   21474              :             Oid         insertTriggerOid,
   21475              :                         updateTriggerOid;
   21476              : 
   21477           72 :             GetForeignKeyCheckTriggers(trigrel,
   21478              :                                        fk->conoid, fk->confrelid, fk->conrelid,
   21479              :                                        &insertTriggerOid, &updateTriggerOid);
   21480              :             Assert(OidIsValid(insertTriggerOid));
   21481           72 :             TriggerSetParentTrigger(trigrel, insertTriggerOid, InvalidOid,
   21482              :                                     RelationGetRelid(partRel));
   21483              :             Assert(OidIsValid(updateTriggerOid));
   21484           72 :             TriggerSetParentTrigger(trigrel, updateTriggerOid, InvalidOid,
   21485              :                                     RelationGetRelid(partRel));
   21486              :         }
   21487              : 
   21488              :         /*
   21489              :          * Lastly, create the action triggers on the referenced table, using
   21490              :          * addFkRecurseReferenced, which requires some elaborate setup (so put
   21491              :          * it in a separate block).  While at it, if the table is partitioned,
   21492              :          * that function will recurse to create the pg_constraint rows and
   21493              :          * action triggers for each partition.
   21494              :          *
   21495              :          * Note there's no need to do addFkConstraint() here, because the
   21496              :          * pg_constraint row already exists.
   21497              :          */
   21498              :         {
   21499              :             Constraint *fkconstraint;
   21500              :             int         numfks;
   21501              :             AttrNumber  conkey[INDEX_MAX_KEYS];
   21502              :             AttrNumber  confkey[INDEX_MAX_KEYS];
   21503              :             Oid         conpfeqop[INDEX_MAX_KEYS];
   21504              :             Oid         conppeqop[INDEX_MAX_KEYS];
   21505              :             Oid         conffeqop[INDEX_MAX_KEYS];
   21506              :             int         numfkdelsetcols;
   21507              :             AttrNumber  confdelsetcols[INDEX_MAX_KEYS];
   21508              :             Relation    refdRel;
   21509              : 
   21510           72 :             DeconstructFkConstraintRow(contup,
   21511              :                                        &numfks,
   21512              :                                        conkey,
   21513              :                                        confkey,
   21514              :                                        conpfeqop,
   21515              :                                        conppeqop,
   21516              :                                        conffeqop,
   21517              :                                        &numfkdelsetcols,
   21518              :                                        confdelsetcols);
   21519              : 
   21520              :             /* Create a synthetic node we'll use throughout */
   21521           72 :             fkconstraint = makeNode(Constraint);
   21522           72 :             fkconstraint->contype = CONSTRAINT_FOREIGN;
   21523           72 :             fkconstraint->conname = pstrdup(NameStr(conform->conname));
   21524           72 :             fkconstraint->deferrable = conform->condeferrable;
   21525           72 :             fkconstraint->initdeferred = conform->condeferred;
   21526           72 :             fkconstraint->is_enforced = conform->conenforced;
   21527           72 :             fkconstraint->skip_validation = true;
   21528           72 :             fkconstraint->initially_valid = conform->convalidated;
   21529              :             /* a few irrelevant fields omitted here */
   21530           72 :             fkconstraint->pktable = NULL;
   21531           72 :             fkconstraint->fk_attrs = NIL;
   21532           72 :             fkconstraint->pk_attrs = NIL;
   21533           72 :             fkconstraint->fk_matchtype = conform->confmatchtype;
   21534           72 :             fkconstraint->fk_upd_action = conform->confupdtype;
   21535           72 :             fkconstraint->fk_del_action = conform->confdeltype;
   21536           72 :             fkconstraint->fk_del_set_cols = NIL;
   21537           72 :             fkconstraint->old_conpfeqop = NIL;
   21538           72 :             fkconstraint->old_pktable_oid = InvalidOid;
   21539           72 :             fkconstraint->location = -1;
   21540              : 
   21541              :             /* set up colnames, used to generate the constraint name */
   21542          176 :             for (int i = 0; i < numfks; i++)
   21543              :             {
   21544              :                 Form_pg_attribute att;
   21545              : 
   21546          104 :                 att = TupleDescAttr(RelationGetDescr(partRel),
   21547          104 :                                     conkey[i] - 1);
   21548              : 
   21549          104 :                 fkconstraint->fk_attrs = lappend(fkconstraint->fk_attrs,
   21550          104 :                                                  makeString(NameStr(att->attname)));
   21551              :             }
   21552              : 
   21553           72 :             refdRel = table_open(fk->confrelid, ShareRowExclusiveLock);
   21554              : 
   21555           72 :             addFkRecurseReferenced(fkconstraint, partRel,
   21556              :                                    refdRel,
   21557              :                                    conform->conindid,
   21558              :                                    fk->conoid,
   21559              :                                    numfks,
   21560              :                                    confkey,
   21561              :                                    conkey,
   21562              :                                    conpfeqop,
   21563              :                                    conppeqop,
   21564              :                                    conffeqop,
   21565              :                                    numfkdelsetcols,
   21566              :                                    confdelsetcols,
   21567              :                                    true,
   21568              :                                    InvalidOid, InvalidOid,
   21569           72 :                                    conform->conperiod);
   21570           72 :             table_close(refdRel, NoLock);   /* keep lock till end of xact */
   21571              :         }
   21572              : 
   21573           72 :         ReleaseSysCache(contup);
   21574              :     }
   21575          664 :     list_free_deep(fks);
   21576          664 :     if (trigrel)
   21577           60 :         table_close(trigrel, RowExclusiveLock);
   21578              : 
   21579              :     /*
   21580              :      * Any sub-constraints that are in the referenced-side of a larger
   21581              :      * constraint have to be removed.  This partition is no longer part of the
   21582              :      * key space of the constraint.
   21583              :      */
   21584          719 :     foreach(cell, GetParentedForeignKeyRefs(partRel))
   21585              :     {
   21586           56 :         Oid         constrOid = lfirst_oid(cell);
   21587              :         ObjectAddress constraint;
   21588              : 
   21589           56 :         ConstraintSetParentConstraint(constrOid, InvalidOid, InvalidOid);
   21590           56 :         deleteDependencyRecordsForClass(ConstraintRelationId,
   21591              :                                         constrOid,
   21592              :                                         ConstraintRelationId,
   21593              :                                         DEPENDENCY_INTERNAL);
   21594           56 :         CommandCounterIncrement();
   21595              : 
   21596           56 :         ObjectAddressSet(constraint, ConstraintRelationId, constrOid);
   21597           56 :         performDeletion(&constraint, DROP_RESTRICT, 0);
   21598              :     }
   21599              : 
   21600              :     /* Now we can detach indexes */
   21601          663 :     indexes = RelationGetIndexList(partRel);
   21602          951 :     foreach(cell, indexes)
   21603              :     {
   21604          288 :         Oid         idxid = lfirst_oid(cell);
   21605              :         Oid         parentidx;
   21606              :         Relation    idx;
   21607              :         Oid         constrOid;
   21608              :         Oid         parentConstrOid;
   21609              : 
   21610          288 :         if (!has_superclass(idxid))
   21611            8 :             continue;
   21612              : 
   21613          280 :         parentidx = get_partition_parent(idxid, false);
   21614              :         Assert((IndexGetRelation(parentidx, false) == RelationGetRelid(rel)));
   21615              : 
   21616          280 :         idx = index_open(idxid, AccessExclusiveLock);
   21617          280 :         IndexSetParentIndex(idx, InvalidOid);
   21618              : 
   21619              :         /*
   21620              :          * If there's a constraint associated with the index, detach it too.
   21621              :          * Careful: it is possible for a constraint index in a partition to be
   21622              :          * the child of a non-constraint index, so verify whether the parent
   21623              :          * index does actually have a constraint.
   21624              :          */
   21625          280 :         constrOid = get_relation_idx_constraint_oid(RelationGetRelid(partRel),
   21626              :                                                     idxid);
   21627          280 :         parentConstrOid = get_relation_idx_constraint_oid(RelationGetRelid(rel),
   21628              :                                                           parentidx);
   21629          280 :         if (OidIsValid(parentConstrOid) && OidIsValid(constrOid))
   21630          127 :             ConstraintSetParentConstraint(constrOid, InvalidOid, InvalidOid);
   21631              : 
   21632          280 :         index_close(idx, NoLock);
   21633              :     }
   21634              : 
   21635              :     /* Update pg_class tuple */
   21636          663 :     classRel = table_open(RelationRelationId, RowExclusiveLock);
   21637          663 :     tuple = SearchSysCacheCopy1(RELOID,
   21638              :                                 ObjectIdGetDatum(RelationGetRelid(partRel)));
   21639          663 :     if (!HeapTupleIsValid(tuple))
   21640            0 :         elog(ERROR, "cache lookup failed for relation %u",
   21641              :              RelationGetRelid(partRel));
   21642              :     Assert(((Form_pg_class) GETSTRUCT(tuple))->relispartition);
   21643              : 
   21644              :     /* Clear relpartbound and reset relispartition */
   21645          663 :     memset(new_val, 0, sizeof(new_val));
   21646          663 :     memset(new_null, false, sizeof(new_null));
   21647          663 :     memset(new_repl, false, sizeof(new_repl));
   21648          663 :     new_val[Anum_pg_class_relpartbound - 1] = (Datum) 0;
   21649          663 :     new_null[Anum_pg_class_relpartbound - 1] = true;
   21650          663 :     new_repl[Anum_pg_class_relpartbound - 1] = true;
   21651          663 :     newtuple = heap_modify_tuple(tuple, RelationGetDescr(classRel),
   21652              :                                  new_val, new_null, new_repl);
   21653              : 
   21654          663 :     ((Form_pg_class) GETSTRUCT(newtuple))->relispartition = false;
   21655          663 :     CatalogTupleUpdate(classRel, &newtuple->t_self, newtuple);
   21656          663 :     heap_freetuple(newtuple);
   21657          663 :     table_close(classRel, RowExclusiveLock);
   21658              : 
   21659              :     /*
   21660              :      * Drop identity property from all identity columns of partition.
   21661              :      */
   21662         2145 :     for (int attno = 0; attno < RelationGetNumberOfAttributes(partRel); attno++)
   21663              :     {
   21664         1482 :         Form_pg_attribute attr = TupleDescAttr(partRel->rd_att, attno);
   21665              : 
   21666         1482 :         if (!attr->attisdropped && attr->attidentity)
   21667           20 :             ATExecDropIdentity(partRel, NameStr(attr->attname), false,
   21668              :                                AccessExclusiveLock, true, true);
   21669              :     }
   21670              : 
   21671          663 :     if (OidIsValid(defaultPartOid))
   21672              :     {
   21673              :         /*
   21674              :          * If the relation being detached is the default partition itself,
   21675              :          * remove it from the parent's pg_partitioned_table entry.
   21676              :          *
   21677              :          * If not, we must invalidate default partition's relcache entry, as
   21678              :          * in StorePartitionBound: its partition constraint depends on every
   21679              :          * other partition's partition constraint.
   21680              :          */
   21681          159 :         if (RelationGetRelid(partRel) == defaultPartOid)
   21682           29 :             update_default_partition_oid(RelationGetRelid(rel), InvalidOid);
   21683              :         else
   21684          130 :             CacheInvalidateRelcacheByRelid(defaultPartOid);
   21685              :     }
   21686              : 
   21687              :     /*
   21688              :      * Invalidate the parent's relcache so that the partition is no longer
   21689              :      * included in its partition descriptor.
   21690              :      */
   21691          663 :     CacheInvalidateRelcache(rel);
   21692              : 
   21693              :     /*
   21694              :      * If the partition we just detached is partitioned itself, invalidate
   21695              :      * relcache for all descendent partitions too to ensure that their
   21696              :      * rd_partcheck expression trees are rebuilt; must lock partitions before
   21697              :      * doing so, using the same lockmode as what partRel has been locked with
   21698              :      * by the caller.
   21699              :      */
   21700          663 :     if (partRel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
   21701              :     {
   21702              :         List       *children;
   21703              : 
   21704           41 :         children = find_all_inheritors(RelationGetRelid(partRel),
   21705              :                                        AccessExclusiveLock, NULL);
   21706          135 :         foreach(cell, children)
   21707              :         {
   21708           94 :             CacheInvalidateRelcacheByRelid(lfirst_oid(cell));
   21709              :         }
   21710              :     }
   21711          663 : }
   21712              : 
   21713              : /*
   21714              :  * ALTER TABLE ... DETACH PARTITION ... FINALIZE
   21715              :  *
   21716              :  * To use when a DETACH PARTITION command previously did not run to
   21717              :  * completion; this completes the detaching process.
   21718              :  */
   21719              : static ObjectAddress
   21720            7 : ATExecDetachPartitionFinalize(Relation rel, RangeVar *name)
   21721              : {
   21722              :     Relation    partRel;
   21723              :     ObjectAddress address;
   21724            7 :     Snapshot    snap = GetActiveSnapshot();
   21725              : 
   21726            7 :     partRel = table_openrv(name, AccessExclusiveLock);
   21727              : 
   21728              :     /*
   21729              :      * Wait until existing snapshots are gone.  This is important if the
   21730              :      * second transaction of DETACH PARTITION CONCURRENTLY is canceled: the
   21731              :      * user could immediately run DETACH FINALIZE without actually waiting for
   21732              :      * existing transactions.  We must not complete the detach action until
   21733              :      * all such queries are complete (otherwise we would present them with an
   21734              :      * inconsistent view of catalogs).
   21735              :      */
   21736            7 :     WaitForOlderSnapshots(snap->xmin, false);
   21737              : 
   21738            7 :     DetachPartitionFinalize(rel, partRel, true, InvalidOid);
   21739              : 
   21740            7 :     ObjectAddressSet(address, RelationRelationId, RelationGetRelid(partRel));
   21741              : 
   21742            7 :     table_close(partRel, NoLock);
   21743              : 
   21744            7 :     return address;
   21745              : }
   21746              : 
   21747              : /*
   21748              :  * DropClonedTriggersFromPartition
   21749              :  *      subroutine for ATExecDetachPartition to remove any triggers that were
   21750              :  *      cloned to the partition when it was created-as-partition or attached.
   21751              :  *      This undoes what CloneRowTriggersToPartition did.
   21752              :  */
   21753              : static void
   21754          664 : DropClonedTriggersFromPartition(Oid partitionId)
   21755              : {
   21756              :     ScanKeyData skey;
   21757              :     SysScanDesc scan;
   21758              :     HeapTuple   trigtup;
   21759              :     Relation    tgrel;
   21760              :     ObjectAddresses *objects;
   21761              : 
   21762          664 :     objects = new_object_addresses();
   21763              : 
   21764              :     /*
   21765              :      * Scan pg_trigger to search for all triggers on this rel.
   21766              :      */
   21767          664 :     ScanKeyInit(&skey, Anum_pg_trigger_tgrelid, BTEqualStrategyNumber,
   21768              :                 F_OIDEQ, ObjectIdGetDatum(partitionId));
   21769          664 :     tgrel = table_open(TriggerRelationId, RowExclusiveLock);
   21770          664 :     scan = systable_beginscan(tgrel, TriggerRelidNameIndexId,
   21771              :                               true, NULL, 1, &skey);
   21772         1000 :     while (HeapTupleIsValid(trigtup = systable_getnext(scan)))
   21773              :     {
   21774          336 :         Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(trigtup);
   21775              :         ObjectAddress trig;
   21776              : 
   21777              :         /* Ignore triggers that weren't cloned */
   21778          336 :         if (!OidIsValid(pg_trigger->tgparentid))
   21779          296 :             continue;
   21780              : 
   21781              :         /*
   21782              :          * Ignore internal triggers that are implementation objects of foreign
   21783              :          * keys, because these will be detached when the foreign keys
   21784              :          * themselves are.
   21785              :          */
   21786          280 :         if (OidIsValid(pg_trigger->tgconstrrelid))
   21787          240 :             continue;
   21788              : 
   21789              :         /*
   21790              :          * This is ugly, but necessary: remove the dependency markings on the
   21791              :          * trigger so that it can be removed.
   21792              :          */
   21793           40 :         deleteDependencyRecordsForClass(TriggerRelationId, pg_trigger->oid,
   21794              :                                         TriggerRelationId,
   21795              :                                         DEPENDENCY_PARTITION_PRI);
   21796           40 :         deleteDependencyRecordsForClass(TriggerRelationId, pg_trigger->oid,
   21797              :                                         RelationRelationId,
   21798              :                                         DEPENDENCY_PARTITION_SEC);
   21799              : 
   21800              :         /* remember this trigger to remove it below */
   21801           40 :         ObjectAddressSet(trig, TriggerRelationId, pg_trigger->oid);
   21802           40 :         add_exact_object_address(&trig, objects);
   21803              :     }
   21804              : 
   21805              :     /* make the dependency removal visible to the deletion below */
   21806          664 :     CommandCounterIncrement();
   21807          664 :     performMultipleDeletions(objects, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
   21808              : 
   21809              :     /* done */
   21810          664 :     free_object_addresses(objects);
   21811          664 :     systable_endscan(scan);
   21812          664 :     table_close(tgrel, RowExclusiveLock);
   21813          664 : }
   21814              : 
   21815              : /*
   21816              :  * Before acquiring lock on an index, acquire the same lock on the owning
   21817              :  * table.
   21818              :  */
   21819              : struct AttachIndexCallbackState
   21820              : {
   21821              :     Oid         partitionOid;
   21822              :     Oid         parentTblOid;
   21823              :     bool        lockedParentTbl;
   21824              : };
   21825              : 
   21826              : static void
   21827          254 : RangeVarCallbackForAttachIndex(const RangeVar *rv, Oid relOid, Oid oldRelOid,
   21828              :                                void *arg)
   21829              : {
   21830              :     struct AttachIndexCallbackState *state;
   21831              :     Form_pg_class classform;
   21832              :     HeapTuple   tuple;
   21833              : 
   21834          254 :     state = (struct AttachIndexCallbackState *) arg;
   21835              : 
   21836          254 :     if (!state->lockedParentTbl)
   21837              :     {
   21838          247 :         LockRelationOid(state->parentTblOid, AccessShareLock);
   21839          247 :         state->lockedParentTbl = true;
   21840              :     }
   21841              : 
   21842              :     /*
   21843              :      * If we previously locked some other heap, and the name we're looking up
   21844              :      * no longer refers to an index on that relation, release the now-useless
   21845              :      * lock.  XXX maybe we should do *after* we verify whether the index does
   21846              :      * not actually belong to the same relation ...
   21847              :      */
   21848          254 :     if (relOid != oldRelOid && OidIsValid(state->partitionOid))
   21849              :     {
   21850            0 :         UnlockRelationOid(state->partitionOid, AccessShareLock);
   21851            0 :         state->partitionOid = InvalidOid;
   21852              :     }
   21853              : 
   21854              :     /* Didn't find a relation, so no need for locking or permission checks. */
   21855          254 :     if (!OidIsValid(relOid))
   21856            4 :         return;
   21857              : 
   21858          250 :     tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid));
   21859          250 :     if (!HeapTupleIsValid(tuple))
   21860            0 :         return;                 /* concurrently dropped, so nothing to do */
   21861          250 :     classform = (Form_pg_class) GETSTRUCT(tuple);
   21862          250 :     if (classform->relkind != RELKIND_PARTITIONED_INDEX &&
   21863          193 :         classform->relkind != RELKIND_INDEX)
   21864            4 :         ereport(ERROR,
   21865              :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
   21866              :                  errmsg("\"%s\" is not an index", rv->relname)));
   21867          246 :     ReleaseSysCache(tuple);
   21868              : 
   21869              :     /*
   21870              :      * Since we need only examine the heap's tupledesc, an access share lock
   21871              :      * on it (preventing any DDL) is sufficient.
   21872              :      */
   21873          246 :     state->partitionOid = IndexGetRelation(relOid, false);
   21874          246 :     LockRelationOid(state->partitionOid, AccessShareLock);
   21875              : }
   21876              : 
   21877              : /*
   21878              :  * ALTER INDEX i1 ATTACH PARTITION i2
   21879              :  */
   21880              : static ObjectAddress
   21881          247 : ATExecAttachPartitionIdx(List **wqueue, Relation parentIdx, RangeVar *name)
   21882              : {
   21883              :     Relation    partIdx;
   21884              :     Relation    partTbl;
   21885              :     Relation    parentTbl;
   21886              :     ObjectAddress address;
   21887              :     Oid         partIdxId;
   21888              :     Oid         currParent;
   21889              :     struct AttachIndexCallbackState state;
   21890              : 
   21891              :     /*
   21892              :      * We need to obtain lock on the index 'name' to modify it, but we also
   21893              :      * need to read its owning table's tuple descriptor -- so we need to lock
   21894              :      * both.  To avoid deadlocks, obtain lock on the table before doing so on
   21895              :      * the index.  Furthermore, we need to examine the parent table of the
   21896              :      * partition, so lock that one too.
   21897              :      */
   21898          247 :     state.partitionOid = InvalidOid;
   21899          247 :     state.parentTblOid = parentIdx->rd_index->indrelid;
   21900          247 :     state.lockedParentTbl = false;
   21901              :     partIdxId =
   21902          247 :         RangeVarGetRelidExtended(name, AccessExclusiveLock, 0,
   21903              :                                  RangeVarCallbackForAttachIndex,
   21904              :                                  &state);
   21905              :     /* Not there? */
   21906          239 :     if (!OidIsValid(partIdxId))
   21907            0 :         ereport(ERROR,
   21908              :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
   21909              :                  errmsg("index \"%s\" does not exist", name->relname)));
   21910              : 
   21911              :     /* no deadlock risk: RangeVarGetRelidExtended already acquired the lock */
   21912          239 :     partIdx = relation_open(partIdxId, AccessExclusiveLock);
   21913              : 
   21914              :     /* we already hold locks on both tables, so this is safe: */
   21915          239 :     parentTbl = relation_open(parentIdx->rd_index->indrelid, AccessShareLock);
   21916          239 :     partTbl = relation_open(partIdx->rd_index->indrelid, NoLock);
   21917              : 
   21918          239 :     ObjectAddressSet(address, RelationRelationId, RelationGetRelid(partIdx));
   21919              : 
   21920              :     /* Silently do nothing if already in the right state */
   21921          478 :     currParent = partIdx->rd_rel->relispartition ?
   21922          239 :         get_partition_parent(partIdxId, false) : InvalidOid;
   21923          239 :     if (currParent != RelationGetRelid(parentIdx))
   21924              :     {
   21925              :         IndexInfo  *childInfo;
   21926              :         IndexInfo  *parentInfo;
   21927              :         AttrMap    *attmap;
   21928              :         bool        found;
   21929              :         int         i;
   21930              :         PartitionDesc partDesc;
   21931              :         Oid         constraintOid,
   21932          223 :                     cldConstrId = InvalidOid;
   21933              : 
   21934              :         /*
   21935              :          * If this partition already has an index attached, refuse the
   21936              :          * operation.
   21937              :          */
   21938          223 :         refuseDupeIndexAttach(parentIdx, partIdx, partTbl);
   21939              : 
   21940          219 :         if (OidIsValid(currParent))
   21941            0 :             ereport(ERROR,
   21942              :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
   21943              :                      errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
   21944              :                             RelationGetRelationName(partIdx),
   21945              :                             RelationGetRelationName(parentIdx)),
   21946              :                      errdetail("Index \"%s\" is already attached to another index.",
   21947              :                                RelationGetRelationName(partIdx))));
   21948              : 
   21949              :         /* Make sure it indexes a partition of the other index's table */
   21950          219 :         partDesc = RelationGetPartitionDesc(parentTbl, true);
   21951          219 :         found = false;
   21952          336 :         for (i = 0; i < partDesc->nparts; i++)
   21953              :         {
   21954          332 :             if (partDesc->oids[i] == state.partitionOid)
   21955              :             {
   21956          215 :                 found = true;
   21957          215 :                 break;
   21958              :             }
   21959              :         }
   21960          219 :         if (!found)
   21961            4 :             ereport(ERROR,
   21962              :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
   21963              :                      errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
   21964              :                             RelationGetRelationName(partIdx),
   21965              :                             RelationGetRelationName(parentIdx)),
   21966              :                      errdetail("Index \"%s\" is not an index on any partition of table \"%s\".",
   21967              :                                RelationGetRelationName(partIdx),
   21968              :                                RelationGetRelationName(parentTbl))));
   21969              : 
   21970              :         /* Ensure the indexes are compatible */
   21971          215 :         childInfo = BuildIndexInfo(partIdx);
   21972          215 :         parentInfo = BuildIndexInfo(parentIdx);
   21973          215 :         attmap = build_attrmap_by_name(RelationGetDescr(partTbl),
   21974              :                                        RelationGetDescr(parentTbl),
   21975              :                                        false);
   21976          215 :         if (!CompareIndexInfo(childInfo, parentInfo,
   21977          215 :                               partIdx->rd_indcollation,
   21978          215 :                               parentIdx->rd_indcollation,
   21979          215 :                               partIdx->rd_opfamily,
   21980          215 :                               parentIdx->rd_opfamily,
   21981              :                               attmap))
   21982           28 :             ereport(ERROR,
   21983              :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
   21984              :                      errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
   21985              :                             RelationGetRelationName(partIdx),
   21986              :                             RelationGetRelationName(parentIdx)),
   21987              :                      errdetail("The index definitions do not match.")));
   21988              : 
   21989              :         /*
   21990              :          * If there is a constraint in the parent, make sure there is one in
   21991              :          * the child too.
   21992              :          */
   21993          187 :         constraintOid = get_relation_idx_constraint_oid(RelationGetRelid(parentTbl),
   21994              :                                                         RelationGetRelid(parentIdx));
   21995              : 
   21996          187 :         if (OidIsValid(constraintOid))
   21997              :         {
   21998           71 :             cldConstrId = get_relation_idx_constraint_oid(RelationGetRelid(partTbl),
   21999              :                                                           partIdxId);
   22000           71 :             if (!OidIsValid(cldConstrId))
   22001            4 :                 ereport(ERROR,
   22002              :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
   22003              :                          errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
   22004              :                                 RelationGetRelationName(partIdx),
   22005              :                                 RelationGetRelationName(parentIdx)),
   22006              :                          errdetail("The index \"%s\" belongs to a constraint in table \"%s\" but no constraint exists for index \"%s\".",
   22007              :                                    RelationGetRelationName(parentIdx),
   22008              :                                    RelationGetRelationName(parentTbl),
   22009              :                                    RelationGetRelationName(partIdx))));
   22010              :         }
   22011              : 
   22012              :         /*
   22013              :          * If it's a primary key, make sure the columns in the partition are
   22014              :          * NOT NULL.
   22015              :          */
   22016          183 :         if (parentIdx->rd_index->indisprimary)
   22017           55 :             verifyPartitionIndexNotNull(childInfo, partTbl);
   22018              : 
   22019              :         /* All good -- do it */
   22020          183 :         IndexSetParentIndex(partIdx, RelationGetRelid(parentIdx));
   22021          183 :         if (OidIsValid(constraintOid))
   22022           67 :             ConstraintSetParentConstraint(cldConstrId, constraintOid,
   22023              :                                           RelationGetRelid(partTbl));
   22024              : 
   22025          183 :         free_attrmap(attmap);
   22026              : 
   22027          183 :         validatePartitionedIndex(parentIdx, parentTbl);
   22028              :     }
   22029              : 
   22030          199 :     relation_close(parentTbl, AccessShareLock);
   22031              :     /* keep these locks till commit */
   22032          199 :     relation_close(partTbl, NoLock);
   22033          199 :     relation_close(partIdx, NoLock);
   22034              : 
   22035          199 :     return address;
   22036              : }
   22037              : 
   22038              : /*
   22039              :  * Verify whether the given partition already contains an index attached
   22040              :  * to the given partitioned index.  If so, raise an error.
   22041              :  */
   22042              : static void
   22043          223 : refuseDupeIndexAttach(Relation parentIdx, Relation partIdx, Relation partitionTbl)
   22044              : {
   22045              :     Oid         existingIdx;
   22046              : 
   22047          223 :     existingIdx = index_get_partition(partitionTbl,
   22048              :                                       RelationGetRelid(parentIdx));
   22049          223 :     if (OidIsValid(existingIdx))
   22050            4 :         ereport(ERROR,
   22051              :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
   22052              :                  errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
   22053              :                         RelationGetRelationName(partIdx),
   22054              :                         RelationGetRelationName(parentIdx)),
   22055              :                  errdetail("Another index \"%s\" is already attached for partition \"%s\".",
   22056              :                            get_rel_name(existingIdx),
   22057              :                            RelationGetRelationName(partitionTbl))));
   22058          219 : }
   22059              : 
   22060              : /*
   22061              :  * Verify whether the set of attached partition indexes to a parent index on
   22062              :  * a partitioned table is complete.  If it is, mark the parent index valid.
   22063              :  *
   22064              :  * This should be called each time a partition index is attached.
   22065              :  */
   22066              : static void
   22067          211 : validatePartitionedIndex(Relation partedIdx, Relation partedTbl)
   22068              : {
   22069              :     Relation    inheritsRel;
   22070              :     SysScanDesc scan;
   22071              :     ScanKeyData key;
   22072          211 :     int         tuples = 0;
   22073              :     HeapTuple   inhTup;
   22074          211 :     bool        updated = false;
   22075              : 
   22076              :     Assert(partedIdx->rd_rel->relkind == RELKIND_PARTITIONED_INDEX);
   22077              : 
   22078              :     /*
   22079              :      * Scan pg_inherits for this parent index.  Count each valid index we find
   22080              :      * (verifying the pg_index entry for each), and if we reach the total
   22081              :      * amount we expect, we can mark this parent index as valid.
   22082              :      */
   22083          211 :     inheritsRel = table_open(InheritsRelationId, AccessShareLock);
   22084          211 :     ScanKeyInit(&key, Anum_pg_inherits_inhparent,
   22085              :                 BTEqualStrategyNumber, F_OIDEQ,
   22086              :                 ObjectIdGetDatum(RelationGetRelid(partedIdx)));
   22087          211 :     scan = systable_beginscan(inheritsRel, InheritsParentIndexId, true,
   22088              :                               NULL, 1, &key);
   22089          541 :     while ((inhTup = systable_getnext(scan)) != NULL)
   22090              :     {
   22091          330 :         Form_pg_inherits inhForm = (Form_pg_inherits) GETSTRUCT(inhTup);
   22092              :         HeapTuple   indTup;
   22093              :         Form_pg_index indexForm;
   22094              : 
   22095          330 :         indTup = SearchSysCache1(INDEXRELID,
   22096              :                                  ObjectIdGetDatum(inhForm->inhrelid));
   22097          330 :         if (!HeapTupleIsValid(indTup))
   22098            0 :             elog(ERROR, "cache lookup failed for index %u", inhForm->inhrelid);
   22099          330 :         indexForm = (Form_pg_index) GETSTRUCT(indTup);
   22100          330 :         if (indexForm->indisvalid)
   22101          292 :             tuples += 1;
   22102          330 :         ReleaseSysCache(indTup);
   22103              :     }
   22104              : 
   22105              :     /* Done with pg_inherits */
   22106          211 :     systable_endscan(scan);
   22107          211 :     table_close(inheritsRel, AccessShareLock);
   22108              : 
   22109              :     /*
   22110              :      * If we found as many inherited indexes as the partitioned table has
   22111              :      * partitions, we're good; update pg_index to set indisvalid.
   22112              :      */
   22113          211 :     if (tuples == RelationGetPartitionDesc(partedTbl, true)->nparts)
   22114              :     {
   22115              :         Relation    idxRel;
   22116              :         HeapTuple   indTup;
   22117              :         Form_pg_index indexForm;
   22118              : 
   22119          108 :         idxRel = table_open(IndexRelationId, RowExclusiveLock);
   22120          108 :         indTup = SearchSysCacheCopy1(INDEXRELID,
   22121              :                                      ObjectIdGetDatum(RelationGetRelid(partedIdx)));
   22122          108 :         if (!HeapTupleIsValid(indTup))
   22123            0 :             elog(ERROR, "cache lookup failed for index %u",
   22124              :                  RelationGetRelid(partedIdx));
   22125          108 :         indexForm = (Form_pg_index) GETSTRUCT(indTup);
   22126              : 
   22127          108 :         indexForm->indisvalid = true;
   22128          108 :         updated = true;
   22129              : 
   22130          108 :         CatalogTupleUpdate(idxRel, &indTup->t_self, indTup);
   22131              : 
   22132          108 :         table_close(idxRel, RowExclusiveLock);
   22133          108 :         heap_freetuple(indTup);
   22134              :     }
   22135              : 
   22136              :     /*
   22137              :      * If this index is in turn a partition of a larger index, validating it
   22138              :      * might cause the parent to become valid also.  Try that.
   22139              :      */
   22140          211 :     if (updated && partedIdx->rd_rel->relispartition)
   22141              :     {
   22142              :         Oid         parentIdxId,
   22143              :                     parentTblId;
   22144              :         Relation    parentIdx,
   22145              :                     parentTbl;
   22146              : 
   22147              :         /* make sure we see the validation we just did */
   22148           28 :         CommandCounterIncrement();
   22149              : 
   22150           28 :         parentIdxId = get_partition_parent(RelationGetRelid(partedIdx), false);
   22151           28 :         parentTblId = get_partition_parent(RelationGetRelid(partedTbl), false);
   22152           28 :         parentIdx = relation_open(parentIdxId, AccessExclusiveLock);
   22153           28 :         parentTbl = relation_open(parentTblId, AccessExclusiveLock);
   22154              :         Assert(!parentIdx->rd_index->indisvalid);
   22155              : 
   22156           28 :         validatePartitionedIndex(parentIdx, parentTbl);
   22157              : 
   22158           28 :         relation_close(parentIdx, AccessExclusiveLock);
   22159           28 :         relation_close(parentTbl, AccessExclusiveLock);
   22160              :     }
   22161          211 : }
   22162              : 
   22163              : /*
   22164              :  * When attaching an index as a partition of a partitioned index which is a
   22165              :  * primary key, verify that all the columns in the partition are marked NOT
   22166              :  * NULL.
   22167              :  */
   22168              : static void
   22169           55 : verifyPartitionIndexNotNull(IndexInfo *iinfo, Relation partition)
   22170              : {
   22171          111 :     for (int i = 0; i < iinfo->ii_NumIndexKeyAttrs; i++)
   22172              :     {
   22173           56 :         Form_pg_attribute att = TupleDescAttr(RelationGetDescr(partition),
   22174           56 :                                               iinfo->ii_IndexAttrNumbers[i] - 1);
   22175              : 
   22176           56 :         if (!att->attnotnull)
   22177            0 :             ereport(ERROR,
   22178              :                     errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   22179              :                     errmsg("invalid primary key definition"),
   22180              :                     errdetail("Column \"%s\" of relation \"%s\" is not marked NOT NULL.",
   22181              :                               NameStr(att->attname),
   22182              :                               RelationGetRelationName(partition)));
   22183              :     }
   22184           55 : }
   22185              : 
   22186              : /*
   22187              :  * Return an OID list of constraints that reference the given relation
   22188              :  * that are marked as having a parent constraints.
   22189              :  */
   22190              : static List *
   22191         1000 : GetParentedForeignKeyRefs(Relation partition)
   22192              : {
   22193              :     Relation    pg_constraint;
   22194              :     HeapTuple   tuple;
   22195              :     SysScanDesc scan;
   22196              :     ScanKeyData key[2];
   22197         1000 :     List       *constraints = NIL;
   22198              : 
   22199              :     /*
   22200              :      * If no indexes, or no columns are referenceable by FKs, we can avoid the
   22201              :      * scan.
   22202              :      */
   22203         1411 :     if (RelationGetIndexList(partition) == NIL ||
   22204          411 :         bms_is_empty(RelationGetIndexAttrBitmap(partition,
   22205              :                                                 INDEX_ATTR_BITMAP_KEY)))
   22206          757 :         return NIL;
   22207              : 
   22208              :     /* Search for constraints referencing this table */
   22209          243 :     pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
   22210          243 :     ScanKeyInit(&key[0],
   22211              :                 Anum_pg_constraint_confrelid, BTEqualStrategyNumber,
   22212              :                 F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(partition)));
   22213          243 :     ScanKeyInit(&key[1],
   22214              :                 Anum_pg_constraint_contype, BTEqualStrategyNumber,
   22215              :                 F_CHAREQ, CharGetDatum(CONSTRAINT_FOREIGN));
   22216              : 
   22217              :     /* XXX This is a seqscan, as we don't have a usable index */
   22218          243 :     scan = systable_beginscan(pg_constraint, InvalidOid, true, NULL, 2, key);
   22219          364 :     while ((tuple = systable_getnext(scan)) != NULL)
   22220              :     {
   22221          121 :         Form_pg_constraint constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
   22222              : 
   22223              :         /*
   22224              :          * We only need to process constraints that are part of larger ones.
   22225              :          */
   22226          121 :         if (!OidIsValid(constrForm->conparentid))
   22227            0 :             continue;
   22228              : 
   22229          121 :         constraints = lappend_oid(constraints, constrForm->oid);
   22230              :     }
   22231              : 
   22232          243 :     systable_endscan(scan);
   22233          243 :     table_close(pg_constraint, AccessShareLock);
   22234              : 
   22235          243 :     return constraints;
   22236              : }
   22237              : 
   22238              : /*
   22239              :  * During DETACH PARTITION, verify that any foreign keys pointing to the
   22240              :  * partitioned table would not become invalid.  An error is raised if any
   22241              :  * referenced values exist.
   22242              :  */
   22243              : static void
   22244          336 : ATDetachCheckNoForeignKeyRefs(Relation partition)
   22245              : {
   22246              :     List       *constraints;
   22247              :     ListCell   *cell;
   22248              : 
   22249          336 :     constraints = GetParentedForeignKeyRefs(partition);
   22250              : 
   22251          379 :     foreach(cell, constraints)
   22252              :     {
   22253           65 :         Oid         constrOid = lfirst_oid(cell);
   22254              :         HeapTuple   tuple;
   22255              :         Form_pg_constraint constrForm;
   22256              :         Relation    rel;
   22257           65 :         Trigger     trig = {0};
   22258              : 
   22259           65 :         tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
   22260           65 :         if (!HeapTupleIsValid(tuple))
   22261            0 :             elog(ERROR, "cache lookup failed for constraint %u", constrOid);
   22262           65 :         constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
   22263              : 
   22264              :         Assert(OidIsValid(constrForm->conparentid));
   22265              :         Assert(constrForm->confrelid == RelationGetRelid(partition));
   22266              : 
   22267              :         /* prevent data changes into the referencing table until commit */
   22268           65 :         rel = table_open(constrForm->conrelid, ShareLock);
   22269              : 
   22270           65 :         trig.tgoid = InvalidOid;
   22271           65 :         trig.tgname = NameStr(constrForm->conname);
   22272           65 :         trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
   22273           65 :         trig.tgisinternal = true;
   22274           65 :         trig.tgconstrrelid = RelationGetRelid(partition);
   22275           65 :         trig.tgconstrindid = constrForm->conindid;
   22276           65 :         trig.tgconstraint = constrForm->oid;
   22277           65 :         trig.tgdeferrable = false;
   22278           65 :         trig.tginitdeferred = false;
   22279              :         /* we needn't fill in remaining fields */
   22280              : 
   22281           65 :         RI_PartitionRemove_Check(&trig, rel, partition);
   22282              : 
   22283           43 :         ReleaseSysCache(tuple);
   22284              : 
   22285           43 :         table_close(rel, NoLock);
   22286              :     }
   22287          314 : }
   22288              : 
   22289              : /*
   22290              :  * resolve column compression specification to compression method.
   22291              :  */
   22292              : static char
   22293       156429 : GetAttributeCompression(Oid atttypid, const char *compression)
   22294              : {
   22295              :     char        cmethod;
   22296              : 
   22297       156429 :     if (compression == NULL || strcmp(compression, "default") == 0)
   22298       156292 :         return InvalidCompressionMethod;
   22299              : 
   22300              :     /*
   22301              :      * To specify a nondefault method, the column data type must be toastable.
   22302              :      * Note this says nothing about whether the column's attstorage setting
   22303              :      * permits compression; we intentionally allow attstorage and
   22304              :      * attcompression to be independent.  But with a non-toastable type,
   22305              :      * attstorage could not be set to a value that would permit compression.
   22306              :      *
   22307              :      * We don't actually need to enforce this, since nothing bad would happen
   22308              :      * if attcompression were non-default; it would never be consulted.  But
   22309              :      * it seems more user-friendly to complain about a certainly-useless
   22310              :      * attempt to set the property.
   22311              :      */
   22312          137 :     if (!TypeIsToastable(atttypid))
   22313            4 :         ereport(ERROR,
   22314              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   22315              :                  errmsg("column data type %s does not support compression",
   22316              :                         format_type_be(atttypid))));
   22317              : 
   22318          133 :     cmethod = CompressionNameToMethod(compression);
   22319          133 :     if (!CompressionMethodIsValid(cmethod))
   22320            8 :         ereport(ERROR,
   22321              :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
   22322              :                  errmsg("invalid compression method \"%s\"", compression)));
   22323              : 
   22324          125 :     return cmethod;
   22325              : }
   22326              : 
   22327              : /*
   22328              :  * resolve column storage specification
   22329              :  */
   22330              : static char
   22331          204 : GetAttributeStorage(Oid atttypid, const char *storagemode)
   22332              : {
   22333          204 :     char        cstorage = 0;
   22334              : 
   22335          204 :     if (pg_strcasecmp(storagemode, "plain") == 0)
   22336           37 :         cstorage = TYPSTORAGE_PLAIN;
   22337          167 :     else if (pg_strcasecmp(storagemode, "external") == 0)
   22338          104 :         cstorage = TYPSTORAGE_EXTERNAL;
   22339           63 :     else if (pg_strcasecmp(storagemode, "extended") == 0)
   22340           26 :         cstorage = TYPSTORAGE_EXTENDED;
   22341           37 :     else if (pg_strcasecmp(storagemode, "main") == 0)
   22342           33 :         cstorage = TYPSTORAGE_MAIN;
   22343            4 :     else if (pg_strcasecmp(storagemode, "default") == 0)
   22344            4 :         cstorage = get_typstorage(atttypid);
   22345              :     else
   22346            0 :         ereport(ERROR,
   22347              :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
   22348              :                  errmsg("invalid storage type \"%s\"",
   22349              :                         storagemode)));
   22350              : 
   22351              :     /*
   22352              :      * safety check: do not allow toasted storage modes unless column datatype
   22353              :      * is TOAST-aware.
   22354              :      */
   22355          204 :     if (!(cstorage == TYPSTORAGE_PLAIN || TypeIsToastable(atttypid)))
   22356            4 :         ereport(ERROR,
   22357              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   22358              :                  errmsg("column data type %s can only have storage PLAIN",
   22359              :                         format_type_be(atttypid))));
   22360              : 
   22361          200 :     return cstorage;
   22362              : }
   22363              : 
   22364              : /*
   22365              :  * buildExpressionExecutionStates: build the needed expression execution states
   22366              :  * for new partition (newPartRel) checks and initialize expressions for
   22367              :  * generated columns. All expressions should be created in "tab"
   22368              :  * (AlteredTableInfo structure).
   22369              :  */
   22370              : static void
   22371          420 : buildExpressionExecutionStates(AlteredTableInfo *tab, Relation newPartRel, EState *estate)
   22372              : {
   22373              :     /*
   22374              :      * Build the needed expression execution states. Here, we expect only NOT
   22375              :      * NULL and CHECK constraint.
   22376              :      */
   22377          856 :     foreach_ptr(NewConstraint, con, tab->constraints)
   22378              :     {
   22379           16 :         switch (con->contype)
   22380              :         {
   22381           16 :             case CONSTR_CHECK:
   22382              : 
   22383              :                 /*
   22384              :                  * We already expanded virtual expression in
   22385              :                  * createTableConstraints.
   22386              :                  */
   22387           16 :                 con->qualstate = ExecPrepareExpr((Expr *) con->qual, estate);
   22388           16 :                 break;
   22389            0 :             case CONSTR_NOTNULL:
   22390              :                 /* Nothing to do here. */
   22391            0 :                 break;
   22392            0 :             default:
   22393            0 :                 elog(ERROR, "unrecognized constraint type: %d",
   22394              :                      (int) con->contype);
   22395              :         }
   22396              :     }
   22397              : 
   22398              :     /* Expression already planned in createTableConstraints */
   22399          884 :     foreach_ptr(NewColumnValue, ex, tab->newvals)
   22400           44 :         ex->exprstate = ExecInitExpr((Expr *) ex->expr, NULL);
   22401          420 : }
   22402              : 
   22403              : /*
   22404              :  * evaluateGeneratedExpressionsAndCheckConstraints: evaluate any generated
   22405              :  * expressions for "tab" (AlteredTableInfo structure) whose inputs come from
   22406              :  * the new tuple (insertslot) of the new partition (newPartRel).
   22407              :  */
   22408              : static void
   22409          664 : evaluateGeneratedExpressionsAndCheckConstraints(AlteredTableInfo *tab,
   22410              :                                                 Relation newPartRel,
   22411              :                                                 TupleTableSlot *insertslot,
   22412              :                                                 ExprContext *econtext)
   22413              : {
   22414          664 :     econtext->ecxt_scantuple = insertslot;
   22415              : 
   22416         1392 :     foreach_ptr(NewColumnValue, ex, tab->newvals)
   22417              :     {
   22418           64 :         if (!ex->is_generated)
   22419            0 :             continue;
   22420              : 
   22421           64 :         insertslot->tts_values[ex->attnum - 1]
   22422           64 :             = ExecEvalExpr(ex->exprstate,
   22423              :                            econtext,
   22424           64 :                            &insertslot->tts_isnull[ex->attnum - 1]);
   22425              :     }
   22426              : 
   22427         1352 :     foreach_ptr(NewConstraint, con, tab->constraints)
   22428              :     {
   22429           24 :         switch (con->contype)
   22430              :         {
   22431           24 :             case CONSTR_CHECK:
   22432           24 :                 if (!ExecCheck(con->qualstate, econtext))
   22433            0 :                     ereport(ERROR,
   22434              :                             errcode(ERRCODE_CHECK_VIOLATION),
   22435              :                             errmsg("check constraint \"%s\" of relation \"%s\" is violated by some row",
   22436              :                                    con->name, RelationGetRelationName(newPartRel)),
   22437              :                             errtableconstraint(newPartRel, con->name));
   22438           24 :                 break;
   22439            0 :             case CONSTR_NOTNULL:
   22440              :             case CONSTR_FOREIGN:
   22441              :                 /* Nothing to do here */
   22442            0 :                 break;
   22443            0 :             default:
   22444            0 :                 elog(ERROR, "unrecognized constraint type: %d",
   22445              :                      (int) con->contype);
   22446              :         }
   22447              :     }
   22448          664 : }
   22449              : 
   22450              : /*
   22451              :  * getAttributesList: build a list of columns (ColumnDef) based on parent_rel
   22452              :  */
   22453              : static List *
   22454          440 : getAttributesList(Relation parent_rel)
   22455              : {
   22456              :     AttrNumber  parent_attno;
   22457              :     TupleDesc   modelDesc;
   22458          440 :     List       *colList = NIL;
   22459              : 
   22460          440 :     modelDesc = RelationGetDescr(parent_rel);
   22461              : 
   22462         1581 :     for (parent_attno = 1; parent_attno <= modelDesc->natts;
   22463         1141 :          parent_attno++)
   22464              :     {
   22465         1141 :         Form_pg_attribute attribute = TupleDescAttr(modelDesc,
   22466              :                                                     parent_attno - 1);
   22467              :         ColumnDef  *def;
   22468              : 
   22469              :         /* Ignore dropped columns in the parent. */
   22470         1141 :         if (attribute->attisdropped)
   22471            0 :             continue;
   22472              : 
   22473         1141 :         def = makeColumnDef(NameStr(attribute->attname), attribute->atttypid,
   22474              :                             attribute->atttypmod, attribute->attcollation);
   22475              : 
   22476         1141 :         def->is_not_null = attribute->attnotnull;
   22477              : 
   22478              :         /* Copy identity. */
   22479         1141 :         def->identity = attribute->attidentity;
   22480              : 
   22481              :         /* Copy attgenerated. */
   22482         1141 :         def->generated = attribute->attgenerated;
   22483              : 
   22484         1141 :         def->storage = attribute->attstorage;
   22485              : 
   22486              :         /* Likewise, copy compression. */
   22487         1141 :         if (CompressionMethodIsValid(attribute->attcompression))
   22488           12 :             def->compression =
   22489           12 :                 pstrdup(GetCompressionMethodName(attribute->attcompression));
   22490              :         else
   22491         1129 :             def->compression = NULL;
   22492              : 
   22493              :         /* Add to column list. */
   22494         1141 :         colList = lappend(colList, def);
   22495              :     }
   22496              : 
   22497          440 :     return colList;
   22498              : }
   22499              : 
   22500              : /*
   22501              :  * createTableConstraints:
   22502              :  * create check constraints, default values, and generated values for newRel
   22503              :  * based on parent_rel.  tab is pending-work queue for newRel, we may need it in
   22504              :  * MergePartitionsMoveRows.
   22505              :  */
   22506              : static void
   22507          420 : createTableConstraints(List **wqueue, AlteredTableInfo *tab,
   22508              :                        Relation parent_rel, Relation newRel)
   22509              : {
   22510              :     TupleDesc   tupleDesc;
   22511              :     TupleConstr *constr;
   22512              :     AttrMap    *attmap;
   22513              :     AttrNumber  parent_attno;
   22514              :     int         ccnum;
   22515          420 :     List       *constraints = NIL;
   22516          420 :     List       *cookedConstraints = NIL;
   22517              : 
   22518          420 :     tupleDesc = RelationGetDescr(parent_rel);
   22519          420 :     constr = tupleDesc->constr;
   22520              : 
   22521          420 :     if (!constr)
   22522          264 :         return;
   22523              : 
   22524              :     /*
   22525              :      * Construct a map from the parent relation's attnos to the child rel's.
   22526              :      * This re-checks type match, etc, although it shouldn't be possible to
   22527              :      * have a failure since both tables are locked.
   22528              :      */
   22529          156 :     attmap = build_attrmap_by_name(RelationGetDescr(newRel),
   22530              :                                    tupleDesc,
   22531              :                                    false);
   22532              : 
   22533              :     /* Cycle for default values. */
   22534          592 :     for (parent_attno = 1; parent_attno <= tupleDesc->natts; parent_attno++)
   22535              :     {
   22536          436 :         Form_pg_attribute attribute = TupleDescAttr(tupleDesc,
   22537              :                                                     parent_attno - 1);
   22538              : 
   22539              :         /* Ignore dropped columns in the parent. */
   22540          436 :         if (attribute->attisdropped)
   22541            0 :             continue;
   22542              : 
   22543              :         /* Copy the default, if present, and it should be copied. */
   22544          436 :         if (attribute->atthasdef)
   22545              :         {
   22546          100 :             Node       *this_default = NULL;
   22547              :             bool        found_whole_row;
   22548              :             AttrNumber  num;
   22549              :             Node       *def;
   22550              :             NewColumnValue *newval;
   22551              : 
   22552          100 :             if (attribute->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
   22553            4 :                 this_default = build_generation_expression(parent_rel, attribute->attnum);
   22554              :             else
   22555              :             {
   22556           96 :                 this_default = TupleDescGetDefault(tupleDesc, attribute->attnum);
   22557           96 :                 if (this_default == NULL)
   22558            0 :                     elog(ERROR, "default expression not found for attribute %d of relation \"%s\"",
   22559              :                          attribute->attnum, RelationGetRelationName(parent_rel));
   22560              :             }
   22561              : 
   22562          100 :             num = attmap->attnums[parent_attno - 1];
   22563          100 :             def = map_variable_attnos(this_default, 1, 0, attmap, InvalidOid, &found_whole_row);
   22564              : 
   22565          100 :             if (found_whole_row && attribute->attgenerated != '\0')
   22566            0 :                 elog(ERROR, "cannot convert whole-row table reference");
   22567              : 
   22568              :             /* Add a pre-cooked default expression. */
   22569          100 :             StoreAttrDefault(newRel, num, def, true);
   22570              : 
   22571              :             /*
   22572              :              * Stored generated column expressions in parent_rel might
   22573              :              * reference the tableoid.  newRel, parent_rel tableoid clear is
   22574              :              * not the same. If so, these stored generated columns require
   22575              :              * recomputation for newRel within MergePartitionsMoveRows.
   22576              :              */
   22577          100 :             if (attribute->attgenerated == ATTRIBUTE_GENERATED_STORED)
   22578              :             {
   22579           44 :                 newval = palloc0_object(NewColumnValue);
   22580           44 :                 newval->attnum = num;
   22581           44 :                 newval->expr = expression_planner((Expr *) def);
   22582           44 :                 newval->is_generated = (attribute->attgenerated != '\0');
   22583           44 :                 tab->newvals = lappend(tab->newvals, newval);
   22584              :             }
   22585              :         }
   22586              :     }
   22587              : 
   22588              :     /* Cycle for CHECK constraints. */
   22589          224 :     for (ccnum = 0; ccnum < constr->num_check; ccnum++)
   22590              :     {
   22591           68 :         char       *ccname = constr->check[ccnum].ccname;
   22592           68 :         char       *ccbin = constr->check[ccnum].ccbin;
   22593           68 :         bool        ccenforced = constr->check[ccnum].ccenforced;
   22594           68 :         bool        ccnoinherit = constr->check[ccnum].ccnoinherit;
   22595           68 :         bool        ccvalid = constr->check[ccnum].ccvalid;
   22596              :         Node       *ccbin_node;
   22597              :         bool        found_whole_row;
   22598              :         Constraint *constr;
   22599              : 
   22600              :         /*
   22601              :          * The partitioned table can not have a NO INHERIT check constraint
   22602              :          * (see StoreRelCheck function for details).
   22603              :          */
   22604              :         Assert(!ccnoinherit);
   22605              : 
   22606           68 :         ccbin_node = map_variable_attnos(stringToNode(ccbin),
   22607              :                                          1, 0,
   22608              :                                          attmap,
   22609              :                                          InvalidOid, &found_whole_row);
   22610              : 
   22611              :         /*
   22612              :          * For the moment we have to reject whole-row variables (as for CREATE
   22613              :          * TABLE LIKE and inheritances).
   22614              :          */
   22615           68 :         if (found_whole_row)
   22616            0 :             elog(ERROR, "Constraint \"%s\" contains a whole-row reference to table \"%s\".",
   22617              :                  ccname,
   22618              :                  RelationGetRelationName(parent_rel));
   22619              : 
   22620           68 :         constr = makeNode(Constraint);
   22621           68 :         constr->contype = CONSTR_CHECK;
   22622           68 :         constr->conname = pstrdup(ccname);
   22623           68 :         constr->deferrable = false;
   22624           68 :         constr->initdeferred = false;
   22625           68 :         constr->is_enforced = ccenforced;
   22626           68 :         constr->skip_validation = !ccvalid;
   22627           68 :         constr->initially_valid = ccvalid;
   22628           68 :         constr->is_no_inherit = ccnoinherit;
   22629           68 :         constr->raw_expr = NULL;
   22630           68 :         constr->cooked_expr = nodeToString(ccbin_node);
   22631           68 :         constr->location = -1;
   22632           68 :         constraints = lappend(constraints, constr);
   22633              :     }
   22634              : 
   22635              :     /* Install all CHECK constraints. */
   22636          156 :     cookedConstraints = AddRelationNewConstraints(newRel, NIL, constraints,
   22637              :                                                   false, true, true, NULL);
   22638              : 
   22639              :     /* Make the additional catalog changes visible. */
   22640          156 :     CommandCounterIncrement();
   22641              : 
   22642              :     /*
   22643              :      * parent_rel check constraint expression may reference tableoid, so later
   22644              :      * in MergePartitionsMoveRows, we need to evaluate the check constraint
   22645              :      * again for the newRel. We can check whether the check constraint
   22646              :      * contains a tableoid reference via pull_varattnos.
   22647              :      */
   22648          380 :     foreach_ptr(CookedConstraint, ccon, cookedConstraints)
   22649              :     {
   22650           68 :         if (!ccon->skip_validation)
   22651              :         {
   22652              :             Node       *qual;
   22653           44 :             Bitmapset  *attnums = NULL;
   22654              : 
   22655              :             Assert(ccon->contype == CONSTR_CHECK);
   22656           44 :             qual = expand_generated_columns_in_expr(ccon->expr, newRel, 1);
   22657           44 :             pull_varattnos(qual, 1, &attnums);
   22658              : 
   22659              :             /*
   22660              :              * Add a check only if it contains a tableoid
   22661              :              * (TableOidAttributeNumber).
   22662              :              */
   22663           44 :             if (bms_is_member(TableOidAttributeNumber - FirstLowInvalidHeapAttributeNumber,
   22664              :                               attnums))
   22665              :             {
   22666              :                 NewConstraint *newcon;
   22667              : 
   22668           16 :                 newcon = palloc0_object(NewConstraint);
   22669           16 :                 newcon->name = ccon->name;
   22670           16 :                 newcon->contype = CONSTR_CHECK;
   22671           16 :                 newcon->qual = qual;
   22672              : 
   22673           16 :                 tab->constraints = lappend(tab->constraints, newcon);
   22674              :             }
   22675              :         }
   22676              :     }
   22677              : 
   22678              :     /* Don't need the cookedConstraints anymore. */
   22679          156 :     list_free_deep(cookedConstraints);
   22680              : 
   22681              :     /* Reproduce not-null constraints. */
   22682          156 :     if (constr->has_not_null)
   22683              :     {
   22684              :         List       *nnconstraints;
   22685              : 
   22686              :         /*
   22687              :          * The "include_noinh" argument is false because a partitioned table
   22688              :          * can't have NO INHERIT constraint.
   22689              :          */
   22690          108 :         nnconstraints = RelationGetNotNullConstraints(RelationGetRelid(parent_rel),
   22691              :                                                       false, false);
   22692              : 
   22693              :         Assert(list_length(nnconstraints) > 0);
   22694              : 
   22695              :         /*
   22696              :          * We already set pg_attribute.attnotnull in createPartitionTable. No
   22697              :          * need call set_attnotnull again.
   22698              :          */
   22699          108 :         AddRelationNewConstraints(newRel, NIL, nnconstraints, false, true, true, NULL);
   22700              :     }
   22701              : }
   22702              : 
   22703              : /*
   22704              :  * createPartitionTable:
   22705              :  *
   22706              :  * Create a new partition (newPartName) for the partitioned table (parent_rel).
   22707              :  * ownerId is determined by the partition on which the operation is performed,
   22708              :  * so it is passed separately.  The new partition will inherit the access method
   22709              :  * and persistence type from the parent table.
   22710              :  *
   22711              :  * Returns the created relation (locked in AccessExclusiveLock mode).
   22712              :  */
   22713              : static Relation
   22714          440 : createPartitionTable(List **wqueue, RangeVar *newPartName,
   22715              :                      Relation parent_rel, Oid ownerId)
   22716              : {
   22717              :     Relation    newRel;
   22718              :     Oid         newRelId;
   22719              :     Oid         existingRelid;
   22720              :     TupleDesc   descriptor;
   22721          440 :     List       *colList = NIL;
   22722              :     Oid         relamId;
   22723              :     Oid         namespaceId;
   22724              :     AlteredTableInfo *new_partrel_tab;
   22725          440 :     Form_pg_class parent_relform = parent_rel->rd_rel;
   22726              : 
   22727              :     /* If the existing rel is temp, it must belong to this session. */
   22728          440 :     if (RELATION_IS_OTHER_TEMP(parent_rel))
   22729            0 :         ereport(ERROR,
   22730              :                 errcode(ERRCODE_WRONG_OBJECT_TYPE),
   22731              :                 errmsg("cannot create as partition of temporary relation of another session"));
   22732              : 
   22733              :     /* Look up inheritance ancestors and generate the relation schema. */
   22734          440 :     colList = getAttributesList(parent_rel);
   22735              : 
   22736              :     /* Create a tuple descriptor from the relation schema. */
   22737          440 :     descriptor = BuildDescForRelation(colList);
   22738              : 
   22739              :     /* Look up the access method for the new relation. */
   22740          440 :     relamId = (parent_relform->relam != InvalidOid) ? parent_relform->relam : HEAP_TABLE_AM_OID;
   22741              : 
   22742              :     /* Look up the namespace in which we are supposed to create the relation. */
   22743              :     namespaceId =
   22744          440 :         RangeVarGetAndCheckCreationNamespace(newPartName, NoLock, &existingRelid);
   22745          440 :     if (OidIsValid(existingRelid))
   22746            0 :         ereport(ERROR,
   22747              :                 errcode(ERRCODE_DUPLICATE_TABLE),
   22748              :                 errmsg("relation \"%s\" already exists", newPartName->relname));
   22749              : 
   22750              :     /*
   22751              :      * We intended to create the partition with the same persistence as the
   22752              :      * parent table, but we still need to recheck because that might be
   22753              :      * affected by the search_path.  If the parent is permanent, so must be
   22754              :      * all of its partitions.
   22755              :      */
   22756          440 :     if (parent_relform->relpersistence != RELPERSISTENCE_TEMP &&
   22757          404 :         newPartName->relpersistence == RELPERSISTENCE_TEMP)
   22758            8 :         ereport(ERROR,
   22759              :                 errcode(ERRCODE_WRONG_OBJECT_TYPE),
   22760              :                 errmsg("cannot create a temporary relation as partition of permanent relation \"%s\"",
   22761              :                        RelationGetRelationName(parent_rel)));
   22762              : 
   22763              :     /* Permanent rels cannot be partitions belonging to a temporary parent. */
   22764          432 :     if (newPartName->relpersistence != RELPERSISTENCE_TEMP &&
   22765          408 :         parent_relform->relpersistence == RELPERSISTENCE_TEMP)
   22766           12 :         ereport(ERROR,
   22767              :                 errcode(ERRCODE_WRONG_OBJECT_TYPE),
   22768              :                 errmsg("cannot create a permanent relation as partition of temporary relation \"%s\"",
   22769              :                        RelationGetRelationName(parent_rel)));
   22770              : 
   22771              :     /* Create the relation. */
   22772          420 :     newRelId = heap_create_with_catalog(newPartName->relname,
   22773              :                                         namespaceId,
   22774              :                                         parent_relform->reltablespace,
   22775              :                                         InvalidOid,
   22776              :                                         InvalidOid,
   22777              :                                         InvalidOid,
   22778              :                                         ownerId,
   22779              :                                         relamId,
   22780              :                                         descriptor,
   22781              :                                         NIL,
   22782              :                                         RELKIND_RELATION,
   22783          420 :                                         newPartName->relpersistence,
   22784              :                                         false,
   22785              :                                         false,
   22786              :                                         ONCOMMIT_NOOP,
   22787              :                                         (Datum) 0,
   22788              :                                         true,
   22789              :                                         allowSystemTableMods,
   22790              :                                         true,
   22791              :                                         InvalidOid,
   22792              :                                         NULL);
   22793              : 
   22794              :     /*
   22795              :      * We must bump the command counter to make the newly-created relation
   22796              :      * tuple visible for opening.
   22797              :      */
   22798          420 :     CommandCounterIncrement();
   22799              : 
   22800              :     /*
   22801              :      * Open the new partition with no lock, because we already have an
   22802              :      * AccessExclusiveLock placed there after creation.
   22803              :      */
   22804          420 :     newRel = table_open(newRelId, NoLock);
   22805              : 
   22806              :     /* Find or create a work queue entry for the newly created table. */
   22807          420 :     new_partrel_tab = ATGetQueueEntry(wqueue, newRel);
   22808              : 
   22809              :     /* Create constraints, default values, and generated values. */
   22810          420 :     createTableConstraints(wqueue, new_partrel_tab, parent_rel, newRel);
   22811              : 
   22812              :     /*
   22813              :      * Need to call CommandCounterIncrement, so a fresh relcache entry has
   22814              :      * newly installed constraint info.
   22815              :      */
   22816          420 :     CommandCounterIncrement();
   22817              : 
   22818          420 :     return newRel;
   22819              : }
   22820              : 
   22821              : /*
   22822              :  * MergePartitionsMoveRows: scan partitions to be merged (mergingPartitions)
   22823              :  * of the partitioned table and move rows into the new partition
   22824              :  * (newPartRel). We also verify check constraints against these rows.
   22825              :  */
   22826              : static void
   22827           88 : MergePartitionsMoveRows(List **wqueue, List *mergingPartitions, Relation newPartRel)
   22828              : {
   22829              :     CommandId   mycid;
   22830              :     EState     *estate;
   22831              :     AlteredTableInfo *tab;
   22832              :     ListCell   *ltab;
   22833              : 
   22834              :     /* The FSM is empty, so don't bother using it. */
   22835           88 :     int         ti_options = TABLE_INSERT_SKIP_FSM;
   22836              :     BulkInsertState bistate;    /* state of bulk inserts for partition */
   22837              :     TupleTableSlot *dstslot;
   22838              : 
   22839              :     /* Find the work queue entry for the new partition table: newPartRel. */
   22840           88 :     tab = ATGetQueueEntry(wqueue, newPartRel);
   22841              : 
   22842              :     /* Generate the constraint and default execution states. */
   22843           88 :     estate = CreateExecutorState();
   22844              : 
   22845           88 :     buildExpressionExecutionStates(tab, newPartRel, estate);
   22846              : 
   22847           88 :     mycid = GetCurrentCommandId(true);
   22848              : 
   22849              :     /* Prepare a BulkInsertState for table_tuple_insert. */
   22850           88 :     bistate = GetBulkInsertState();
   22851              : 
   22852              :     /* Create the necessary tuple slot. */
   22853           88 :     dstslot = table_slot_create(newPartRel, NULL);
   22854              : 
   22855          380 :     foreach_oid(merging_oid, mergingPartitions)
   22856              :     {
   22857              :         ExprContext *econtext;
   22858              :         TupleTableSlot *srcslot;
   22859              :         TupleConversionMap *tuple_map;
   22860              :         TableScanDesc scan;
   22861              :         MemoryContext oldCxt;
   22862              :         Snapshot    snapshot;
   22863              :         Relation    mergingPartition;
   22864              : 
   22865          204 :         econtext = GetPerTupleExprContext(estate);
   22866              : 
   22867              :         /*
   22868              :          * Partition is already locked in the transformPartitionCmdForMerge
   22869              :          * function.
   22870              :          */
   22871          204 :         mergingPartition = table_open(merging_oid, NoLock);
   22872              : 
   22873              :         /* Create a source tuple slot for the partition being merged. */
   22874          204 :         srcslot = table_slot_create(mergingPartition, NULL);
   22875              : 
   22876              :         /*
   22877              :          * Map computing for moving attributes of the merged partition to the
   22878              :          * new partition.
   22879              :          */
   22880          204 :         tuple_map = convert_tuples_by_name(RelationGetDescr(mergingPartition),
   22881              :                                            RelationGetDescr(newPartRel));
   22882              : 
   22883              :         /* Scan through the rows. */
   22884          204 :         snapshot = RegisterSnapshot(GetLatestSnapshot());
   22885          204 :         scan = table_beginscan(mergingPartition, snapshot, 0, NULL);
   22886              : 
   22887              :         /*
   22888              :          * Switch to per-tuple memory context and reset it for each tuple
   22889              :          * produced, so we don't leak memory.
   22890              :          */
   22891          204 :         oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
   22892              : 
   22893          445 :         while (table_scan_getnextslot(scan, ForwardScanDirection, srcslot))
   22894              :         {
   22895              :             TupleTableSlot *insertslot;
   22896              : 
   22897          241 :             CHECK_FOR_INTERRUPTS();
   22898              : 
   22899          241 :             if (tuple_map)
   22900              :             {
   22901              :                 /* Need to use a map to copy attributes. */
   22902           28 :                 insertslot = execute_attr_map_slot(tuple_map->attrMap, srcslot, dstslot);
   22903              :             }
   22904              :             else
   22905              :             {
   22906          213 :                 slot_getallattrs(srcslot);
   22907              : 
   22908              :                 /* Copy attributes directly. */
   22909          213 :                 insertslot = dstslot;
   22910              : 
   22911          213 :                 ExecClearTuple(insertslot);
   22912              : 
   22913          213 :                 memcpy(insertslot->tts_values, srcslot->tts_values,
   22914          213 :                        sizeof(Datum) * srcslot->tts_nvalid);
   22915          213 :                 memcpy(insertslot->tts_isnull, srcslot->tts_isnull,
   22916          213 :                        sizeof(bool) * srcslot->tts_nvalid);
   22917              : 
   22918          213 :                 ExecStoreVirtualTuple(insertslot);
   22919              :             }
   22920              : 
   22921              :             /*
   22922              :              * Constraints and GENERATED expressions might reference the
   22923              :              * tableoid column, so fill tts_tableOid with the desired value.
   22924              :              * (We must do this each time, because it gets overwritten with
   22925              :              * newrel's OID during storing.)
   22926              :              */
   22927          241 :             insertslot->tts_tableOid = RelationGetRelid(newPartRel);
   22928              : 
   22929              :             /*
   22930              :              * Now, evaluate any generated expressions whose inputs come from
   22931              :              * the new tuple.  We assume these columns won't reference each
   22932              :              * other, so that there's no ordering dependency.
   22933              :              */
   22934          241 :             evaluateGeneratedExpressionsAndCheckConstraints(tab, newPartRel,
   22935              :                                                             insertslot, econtext);
   22936              : 
   22937              :             /* Write the tuple out to the new relation. */
   22938          241 :             table_tuple_insert(newPartRel, insertslot, mycid,
   22939              :                                ti_options, bistate);
   22940              : 
   22941          241 :             ResetExprContext(econtext);
   22942              :         }
   22943              : 
   22944          204 :         MemoryContextSwitchTo(oldCxt);
   22945          204 :         table_endscan(scan);
   22946          204 :         UnregisterSnapshot(snapshot);
   22947              : 
   22948          204 :         if (tuple_map)
   22949           20 :             free_conversion_map(tuple_map);
   22950              : 
   22951          204 :         ExecDropSingleTupleTableSlot(srcslot);
   22952          204 :         table_close(mergingPartition, NoLock);
   22953              :     }
   22954              : 
   22955           88 :     FreeExecutorState(estate);
   22956           88 :     ExecDropSingleTupleTableSlot(dstslot);
   22957           88 :     FreeBulkInsertState(bistate);
   22958              : 
   22959           88 :     table_finish_bulk_insert(newPartRel, ti_options);
   22960              : 
   22961              :     /*
   22962              :      * We don't need to process this newPartRel since we already processed it
   22963              :      * here, so delete the ALTER TABLE queue for it.
   22964              :      */
   22965          176 :     foreach(ltab, *wqueue)
   22966              :     {
   22967          176 :         tab = (AlteredTableInfo *) lfirst(ltab);
   22968          176 :         if (tab->relid == RelationGetRelid(newPartRel))
   22969              :         {
   22970           88 :             *wqueue = list_delete_cell(*wqueue, ltab);
   22971           88 :             break;
   22972              :         }
   22973              :     }
   22974           88 : }
   22975              : 
   22976              : /*
   22977              :  * detachPartitionTable: detach partition "child_rel" from partitioned table
   22978              :  * "parent_rel" with default partition identifier "defaultPartOid"
   22979              :  */
   22980              : static void
   22981          368 : detachPartitionTable(Relation parent_rel, Relation child_rel, Oid defaultPartOid)
   22982              : {
   22983              :     /* Remove the pg_inherits row first. */
   22984          368 :     RemoveInheritance(child_rel, parent_rel, false);
   22985              : 
   22986              :     /*
   22987              :      * Detaching the partition might involve TOAST table access, so ensure we
   22988              :      * have a valid snapshot.
   22989              :      */
   22990          368 :     PushActiveSnapshot(GetTransactionSnapshot());
   22991              : 
   22992              :     /* Do the final part of detaching. */
   22993          368 :     DetachPartitionFinalize(parent_rel, child_rel, false, defaultPartOid);
   22994              : 
   22995          368 :     PopActiveSnapshot();
   22996          368 : }
   22997              : 
   22998              : /*
   22999              :  * ALTER TABLE <name> MERGE PARTITIONS <partition-list> INTO <partition-name>
   23000              :  */
   23001              : static void
   23002          116 : ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel,
   23003              :                       PartitionCmd *cmd, AlterTableUtilityContext *context)
   23004              : {
   23005              :     Relation    newPartRel;
   23006          116 :     List       *mergingPartitions = NIL;
   23007              :     Oid         defaultPartOid;
   23008              :     Oid         existingRelid;
   23009          116 :     Oid         ownerId = InvalidOid;
   23010              :     Oid         save_userid;
   23011              :     int         save_sec_context;
   23012              :     int         save_nestlevel;
   23013              : 
   23014              :     /*
   23015              :      * Check ownership of merged partitions - partitions with different owners
   23016              :      * cannot be merged. Also, collect the OIDs of these partitions during the
   23017              :      * check.
   23018              :      */
   23019          488 :     foreach_node(RangeVar, name, cmd->partlist)
   23020              :     {
   23021              :         Relation    mergingPartition;
   23022              : 
   23023              :         /*
   23024              :          * We are going to detach and remove this partition.  We already took
   23025              :          * AccessExclusiveLock lock on transformPartitionCmdForMerge, so here,
   23026              :          * NoLock is fine.
   23027              :          */
   23028          264 :         mergingPartition = table_openrv_extended(name, NoLock, false);
   23029              :         Assert(CheckRelationLockedByMe(mergingPartition, AccessExclusiveLock, false));
   23030              : 
   23031          264 :         if (OidIsValid(ownerId))
   23032              :         {
   23033              :             /* Do the partitions being merged have different owners? */
   23034          148 :             if (ownerId != mergingPartition->rd_rel->relowner)
   23035            4 :                 ereport(ERROR,
   23036              :                         errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   23037              :                         errmsg("partitions being merged have different owners"));
   23038              :         }
   23039              :         else
   23040          116 :             ownerId = mergingPartition->rd_rel->relowner;
   23041              : 
   23042              :         /* Store the next merging partition into the list. */
   23043          260 :         mergingPartitions = lappend_oid(mergingPartitions,
   23044              :                                         RelationGetRelid(mergingPartition));
   23045              : 
   23046          260 :         table_close(mergingPartition, NoLock);
   23047              :     }
   23048              : 
   23049              :     /* Look up the existing relation by the new partition name. */
   23050          112 :     RangeVarGetAndCheckCreationNamespace(cmd->name, NoLock, &existingRelid);
   23051              : 
   23052              :     /*
   23053              :      * Check if this name is already taken.  This helps us to detect the
   23054              :      * situation when one of the merging partitions has the same name as the
   23055              :      * new partition.  Otherwise, this would fail later on anyway, but
   23056              :      * catching this here allows us to emit a nicer error message.
   23057              :      */
   23058          112 :     if (OidIsValid(existingRelid))
   23059              :     {
   23060           17 :         if (list_member_oid(mergingPartitions, existingRelid))
   23061              :         {
   23062              :             /*
   23063              :              * The new partition has the same name as one of the merging
   23064              :              * partitions.
   23065              :              */
   23066              :             char        tmpRelName[NAMEDATALEN];
   23067              : 
   23068              :             /* Generate a temporary name. */
   23069           13 :             sprintf(tmpRelName, "merge-%u-%X-tmp", RelationGetRelid(rel), MyProcPid);
   23070              : 
   23071              :             /*
   23072              :              * Rename the existing partition with a temporary name, leaving it
   23073              :              * free for the new partition.  We don't need to care about this
   23074              :              * in the future because we're going to eventually drop the
   23075              :              * existing partition anyway.
   23076              :              */
   23077           13 :             RenameRelationInternal(existingRelid, tmpRelName, true, false);
   23078              : 
   23079              :             /*
   23080              :              * We must bump the command counter to make the new partition
   23081              :              * tuple visible for rename.
   23082              :              */
   23083           13 :             CommandCounterIncrement();
   23084              :         }
   23085              :         else
   23086              :         {
   23087            4 :             ereport(ERROR,
   23088              :                     errcode(ERRCODE_DUPLICATE_TABLE),
   23089              :                     errmsg("relation \"%s\" already exists", cmd->name->relname));
   23090              :         }
   23091              :     }
   23092              : 
   23093              :     defaultPartOid =
   23094          108 :         get_default_oid_from_partdesc(RelationGetPartitionDesc(rel, true));
   23095              : 
   23096              :     /* Detach all merging partitions. */
   23097          460 :     foreach_oid(mergingPartitionOid, mergingPartitions)
   23098              :     {
   23099              :         Relation    child_rel;
   23100              : 
   23101          244 :         child_rel = table_open(mergingPartitionOid, NoLock);
   23102              : 
   23103          244 :         detachPartitionTable(rel, child_rel, defaultPartOid);
   23104              : 
   23105          244 :         table_close(child_rel, NoLock);
   23106              :     }
   23107              : 
   23108              :     /*
   23109              :      * Perform a preliminary check to determine whether it's safe to drop all
   23110              :      * merging partitions before we actually do so later. After merging rows
   23111              :      * into the new partitions via MergePartitionsMoveRows, all old partitions
   23112              :      * need to be dropped. However, since the drop behavior is DROP_RESTRICT
   23113              :      * and the merge process (MergePartitionsMoveRows) can be time-consuming,
   23114              :      * performing an early check on the drop eligibility of old partitions is
   23115              :      * preferable.
   23116              :      */
   23117          448 :     foreach_oid(mergingPartitionOid, mergingPartitions)
   23118              :     {
   23119              :         ObjectAddress object;
   23120              : 
   23121              :         /* Get oid of the later to be dropped relation. */
   23122          240 :         object.objectId = mergingPartitionOid;
   23123          240 :         object.classId = RelationRelationId;
   23124          240 :         object.objectSubId = 0;
   23125              : 
   23126          240 :         performDeletionCheck(&object, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
   23127              :     }
   23128              : 
   23129              :     /*
   23130              :      * Create a table for the new partition, using the partitioned table as a
   23131              :      * model.
   23132              :      */
   23133              :     Assert(OidIsValid(ownerId));
   23134          104 :     newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId);
   23135              : 
   23136              :     /*
   23137              :      * Switch to the table owner's userid, so that any index functions are run
   23138              :      * as that user.  Also, lockdown security-restricted operations and
   23139              :      * arrange to make GUC variable changes local to this command.
   23140              :      *
   23141              :      * Need to do it after determining the namespace in the
   23142              :      * createPartitionTable() call.
   23143              :      */
   23144           88 :     GetUserIdAndSecContext(&save_userid, &save_sec_context);
   23145           88 :     SetUserIdAndSecContext(ownerId,
   23146              :                            save_sec_context | SECURITY_RESTRICTED_OPERATION);
   23147           88 :     save_nestlevel = NewGUCNestLevel();
   23148           88 :     RestrictSearchPath();
   23149              : 
   23150              :     /* Copy data from merged partitions to the new partition. */
   23151           88 :     MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel);
   23152              : 
   23153              :     /* Drop the current partitions before attaching the new one. */
   23154          380 :     foreach_oid(mergingPartitionOid, mergingPartitions)
   23155              :     {
   23156              :         ObjectAddress object;
   23157              : 
   23158          204 :         object.objectId = mergingPartitionOid;
   23159          204 :         object.classId = RelationRelationId;
   23160          204 :         object.objectSubId = 0;
   23161              : 
   23162          204 :         performDeletion(&object, DROP_RESTRICT, 0);
   23163              :     }
   23164              : 
   23165           88 :     list_free(mergingPartitions);
   23166              : 
   23167              :     /*
   23168              :      * Attach a new partition to the partitioned table. wqueue = NULL:
   23169              :      * verification for each cloned constraint is not needed.
   23170              :      */
   23171           88 :     attachPartitionTable(NULL, rel, newPartRel, cmd->bound);
   23172              : 
   23173              :     /* Keep the lock until commit. */
   23174           88 :     table_close(newPartRel, NoLock);
   23175              : 
   23176              :     /* Roll back any GUC changes executed by index functions. */
   23177           88 :     AtEOXact_GUC(false, save_nestlevel);
   23178              : 
   23179              :     /* Restore the userid and security context. */
   23180           88 :     SetUserIdAndSecContext(save_userid, save_sec_context);
   23181           88 : }
   23182              : 
   23183              : /*
   23184              :  * Struct with the context of the new partition for inserting rows from the
   23185              :  * split partition.
   23186              :  */
   23187              : typedef struct SplitPartitionContext
   23188              : {
   23189              :     ExprState  *partqualstate;  /* expression for checking a slot for a
   23190              :                                  * partition (NULL for DEFAULT partition) */
   23191              :     BulkInsertState bistate;    /* state of bulk inserts for partition */
   23192              :     TupleTableSlot *dstslot;    /* slot for inserting row into partition */
   23193              :     AlteredTableInfo *tab;      /* structure with generated column expressions
   23194              :                                  * and check constraint expressions. */
   23195              :     Relation    partRel;        /* relation for partition */
   23196              : } SplitPartitionContext;
   23197              : 
   23198              : /*
   23199              :  * createSplitPartitionContext: create context for partition and fill it
   23200              :  */
   23201              : static SplitPartitionContext *
   23202          332 : createSplitPartitionContext(Relation partRel)
   23203              : {
   23204              :     SplitPartitionContext *pc;
   23205              : 
   23206          332 :     pc = palloc0_object(SplitPartitionContext);
   23207          332 :     pc->partRel = partRel;
   23208              : 
   23209              :     /*
   23210              :      * Prepare a BulkInsertState for table_tuple_insert. The FSM is empty, so
   23211              :      * don't bother using it.
   23212              :      */
   23213          332 :     pc->bistate = GetBulkInsertState();
   23214              : 
   23215              :     /* Create a destination tuple slot for the new partition. */
   23216          332 :     pc->dstslot = table_slot_create(pc->partRel, NULL);
   23217              : 
   23218          332 :     return pc;
   23219              : }
   23220              : 
   23221              : /*
   23222              :  * deleteSplitPartitionContext: delete context for partition
   23223              :  */
   23224              : static void
   23225          332 : deleteSplitPartitionContext(SplitPartitionContext *pc, List **wqueue, int ti_options)
   23226              : {
   23227              :     ListCell   *ltab;
   23228              : 
   23229          332 :     ExecDropSingleTupleTableSlot(pc->dstslot);
   23230          332 :     FreeBulkInsertState(pc->bistate);
   23231              : 
   23232          332 :     table_finish_bulk_insert(pc->partRel, ti_options);
   23233              : 
   23234              :     /*
   23235              :      * We don't need to process this pc->partRel so delete the ALTER TABLE
   23236              :      * queue of it.
   23237              :      */
   23238          664 :     foreach(ltab, *wqueue)
   23239              :     {
   23240          664 :         AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
   23241              : 
   23242          664 :         if (tab->relid == RelationGetRelid(pc->partRel))
   23243              :         {
   23244          332 :             *wqueue = list_delete_cell(*wqueue, ltab);
   23245          332 :             break;
   23246              :         }
   23247              :     }
   23248              : 
   23249          332 :     pfree(pc);
   23250          332 : }
   23251              : 
   23252              : /*
   23253              :  * SplitPartitionMoveRows: scan split partition (splitRel) of partitioned table
   23254              :  * (rel) and move rows into new partitions.
   23255              :  *
   23256              :  * New partitions description:
   23257              :  * partlist: list of pointers to SinglePartitionSpec structures.  It contains
   23258              :  * the partition specification details for all new partitions.
   23259              :  * newPartRels: list of Relations, new partitions created in
   23260              :  * ATExecSplitPartition.
   23261              :  */
   23262              : static void
   23263          120 : SplitPartitionMoveRows(List **wqueue, Relation rel, Relation splitRel,
   23264              :                        List *partlist, List *newPartRels)
   23265              : {
   23266              :     /* The FSM is empty, so don't bother using it. */
   23267          120 :     int         ti_options = TABLE_INSERT_SKIP_FSM;
   23268              :     CommandId   mycid;
   23269              :     EState     *estate;
   23270              :     ListCell   *listptr,
   23271              :                *listptr2;
   23272              :     TupleTableSlot *srcslot;
   23273              :     ExprContext *econtext;
   23274              :     TableScanDesc scan;
   23275              :     Snapshot    snapshot;
   23276              :     MemoryContext oldCxt;
   23277          120 :     List       *partContexts = NIL;
   23278              :     TupleConversionMap *tuple_map;
   23279          120 :     SplitPartitionContext *defaultPartCtx = NULL,
   23280              :                *pc;
   23281              : 
   23282          120 :     mycid = GetCurrentCommandId(true);
   23283              : 
   23284          120 :     estate = CreateExecutorState();
   23285              : 
   23286          452 :     forboth(listptr, partlist, listptr2, newPartRels)
   23287              :     {
   23288          332 :         SinglePartitionSpec *sps = (SinglePartitionSpec *) lfirst(listptr);
   23289              : 
   23290          332 :         pc = createSplitPartitionContext((Relation) lfirst(listptr2));
   23291              : 
   23292              :         /* Find the work queue entry for the new partition table: newPartRel. */
   23293          332 :         pc->tab = ATGetQueueEntry(wqueue, pc->partRel);
   23294              : 
   23295          332 :         buildExpressionExecutionStates(pc->tab, pc->partRel, estate);
   23296              : 
   23297          332 :         if (sps->bound->is_default)
   23298              :         {
   23299              :             /*
   23300              :              * We should not create a structure to check the partition
   23301              :              * constraint for the new DEFAULT partition.
   23302              :              */
   23303           28 :             defaultPartCtx = pc;
   23304              :         }
   23305              :         else
   23306              :         {
   23307              :             List       *partConstraint;
   23308              : 
   23309              :             /* Build expression execution states for partition check quals. */
   23310          304 :             partConstraint = get_qual_from_partbound(rel, sps->bound);
   23311              :             partConstraint =
   23312          304 :                 (List *) eval_const_expressions(NULL,
   23313              :                                                 (Node *) partConstraint);
   23314              :             /* Make a boolean expression for ExecCheck(). */
   23315          304 :             partConstraint = list_make1(make_ands_explicit(partConstraint));
   23316              : 
   23317              :             /*
   23318              :              * Map the vars in the constraint expression from rel's attnos to
   23319              :              * splitRel's.
   23320              :              */
   23321          304 :             partConstraint = map_partition_varattnos(partConstraint,
   23322              :                                                      1, splitRel, rel);
   23323              : 
   23324          304 :             pc->partqualstate =
   23325          304 :                 ExecPrepareExpr((Expr *) linitial(partConstraint), estate);
   23326              :             Assert(pc->partqualstate != NULL);
   23327              :         }
   23328              : 
   23329              :         /* Store partition context into a list. */
   23330          332 :         partContexts = lappend(partContexts, pc);
   23331              :     }
   23332              : 
   23333          120 :     econtext = GetPerTupleExprContext(estate);
   23334              : 
   23335              :     /* Create the necessary tuple slot. */
   23336          120 :     srcslot = table_slot_create(splitRel, NULL);
   23337              : 
   23338              :     /*
   23339              :      * Map computing for moving attributes of the split partition to the new
   23340              :      * partition (for the first new partition, but other new partitions can
   23341              :      * use the same map).
   23342              :      */
   23343          120 :     pc = (SplitPartitionContext *) lfirst(list_head(partContexts));
   23344          120 :     tuple_map = convert_tuples_by_name(RelationGetDescr(splitRel),
   23345          120 :                                        RelationGetDescr(pc->partRel));
   23346              : 
   23347              :     /* Scan through the rows. */
   23348          120 :     snapshot = RegisterSnapshot(GetLatestSnapshot());
   23349          120 :     scan = table_beginscan(splitRel, snapshot, 0, NULL);
   23350              : 
   23351              :     /*
   23352              :      * Switch to per-tuple memory context and reset it for each tuple
   23353              :      * produced, so we don't leak memory.
   23354              :      */
   23355          120 :     oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
   23356              : 
   23357          543 :     while (table_scan_getnextslot(scan, ForwardScanDirection, srcslot))
   23358              :     {
   23359          423 :         bool        found = false;
   23360              :         TupleTableSlot *insertslot;
   23361              : 
   23362          423 :         CHECK_FOR_INTERRUPTS();
   23363              : 
   23364          423 :         econtext->ecxt_scantuple = srcslot;
   23365              : 
   23366              :         /* Search partition for the current slot, srcslot. */
   23367         1138 :         foreach(listptr, partContexts)
   23368              :         {
   23369         1062 :             pc = (SplitPartitionContext *) lfirst(listptr);
   23370              : 
   23371              :             /* skip DEFAULT partition */
   23372         1062 :             if (pc->partqualstate && ExecCheck(pc->partqualstate, econtext))
   23373              :             {
   23374          347 :                 found = true;
   23375          347 :                 break;
   23376              :             }
   23377              :         }
   23378          423 :         if (!found)
   23379              :         {
   23380              :             /* Use the DEFAULT partition if it exists. */
   23381           76 :             if (defaultPartCtx)
   23382           76 :                 pc = defaultPartCtx;
   23383              :             else
   23384            0 :                 ereport(ERROR,
   23385              :                         errcode(ERRCODE_CHECK_VIOLATION),
   23386              :                         errmsg("can not find partition for split partition row"),
   23387              :                         errtable(splitRel));
   23388              :         }
   23389              : 
   23390          423 :         if (tuple_map)
   23391              :         {
   23392              :             /* Need to use a map to copy attributes. */
   23393           16 :             insertslot = execute_attr_map_slot(tuple_map->attrMap, srcslot, pc->dstslot);
   23394              :         }
   23395              :         else
   23396              :         {
   23397              :             /* Extract data from the old tuple. */
   23398          407 :             slot_getallattrs(srcslot);
   23399              : 
   23400              :             /* Copy attributes directly. */
   23401          407 :             insertslot = pc->dstslot;
   23402              : 
   23403          407 :             ExecClearTuple(insertslot);
   23404              : 
   23405          407 :             memcpy(insertslot->tts_values, srcslot->tts_values,
   23406          407 :                    sizeof(Datum) * srcslot->tts_nvalid);
   23407          407 :             memcpy(insertslot->tts_isnull, srcslot->tts_isnull,
   23408          407 :                    sizeof(bool) * srcslot->tts_nvalid);
   23409              : 
   23410          407 :             ExecStoreVirtualTuple(insertslot);
   23411              :         }
   23412              : 
   23413              :         /*
   23414              :          * Constraints and GENERATED expressions might reference the tableoid
   23415              :          * column, so fill tts_tableOid with the desired value. (We must do
   23416              :          * this each time, because it gets overwritten with newrel's OID
   23417              :          * during storing.)
   23418              :          */
   23419          423 :         insertslot->tts_tableOid = RelationGetRelid(pc->partRel);
   23420              : 
   23421              :         /*
   23422              :          * Now, evaluate any generated expressions whose inputs come from the
   23423              :          * new tuple.  We assume these columns won't reference each other, so
   23424              :          * that there's no ordering dependency.
   23425              :          */
   23426          423 :         evaluateGeneratedExpressionsAndCheckConstraints(pc->tab, pc->partRel,
   23427              :                                                         insertslot, econtext);
   23428              : 
   23429              :         /* Write the tuple out to the new relation. */
   23430          423 :         table_tuple_insert(pc->partRel, insertslot, mycid,
   23431          423 :                            ti_options, pc->bistate);
   23432              : 
   23433          423 :         ResetExprContext(econtext);
   23434              :     }
   23435              : 
   23436          120 :     MemoryContextSwitchTo(oldCxt);
   23437              : 
   23438          120 :     table_endscan(scan);
   23439          120 :     UnregisterSnapshot(snapshot);
   23440              : 
   23441          120 :     if (tuple_map)
   23442            4 :         free_conversion_map(tuple_map);
   23443              : 
   23444          120 :     ExecDropSingleTupleTableSlot(srcslot);
   23445              : 
   23446          120 :     FreeExecutorState(estate);
   23447              : 
   23448          572 :     foreach_ptr(SplitPartitionContext, spc, partContexts)
   23449          332 :         deleteSplitPartitionContext(spc, wqueue, ti_options);
   23450          120 : }
   23451              : 
   23452              : /*
   23453              :  * ALTER TABLE <name> SPLIT PARTITION <partition-name> INTO <partition-list>
   23454              :  */
   23455              : static void
   23456          128 : ATExecSplitPartition(List **wqueue, AlteredTableInfo *tab, Relation rel,
   23457              :                      PartitionCmd *cmd, AlterTableUtilityContext *context)
   23458              : {
   23459              :     Relation    splitRel;
   23460              :     Oid         splitRelOid;
   23461              :     ListCell   *listptr,
   23462              :                *listptr2;
   23463          128 :     bool        isSameName = false;
   23464              :     char        tmpRelName[NAMEDATALEN];
   23465          128 :     List       *newPartRels = NIL;
   23466              :     ObjectAddress object;
   23467              :     Oid         defaultPartOid;
   23468              :     Oid         save_userid;
   23469              :     int         save_sec_context;
   23470              :     int         save_nestlevel;
   23471              : 
   23472          128 :     defaultPartOid = get_default_oid_from_partdesc(RelationGetPartitionDesc(rel, true));
   23473              : 
   23474              :     /*
   23475              :      * Partition is already locked in the transformPartitionCmdForSplit
   23476              :      * function.
   23477              :      */
   23478          128 :     splitRel = table_openrv(cmd->name, NoLock);
   23479              : 
   23480          128 :     splitRelOid = RelationGetRelid(splitRel);
   23481              : 
   23482              :     /* Check descriptions of new partitions. */
   23483          592 :     foreach_node(SinglePartitionSpec, sps, cmd->partlist)
   23484              :     {
   23485              :         Oid         existingRelid;
   23486              : 
   23487              :         /* Look up the existing relation by the new partition name. */
   23488          344 :         RangeVarGetAndCheckCreationNamespace(sps->name, NoLock, &existingRelid);
   23489              : 
   23490              :         /*
   23491              :          * This would fail later on anyway if the relation already exists. But
   23492              :          * by catching it here, we can emit a nicer error message.
   23493              :          */
   23494          344 :         if (existingRelid == splitRelOid && !isSameName)
   23495              :             /* One new partition can have the same name as a split partition. */
   23496           29 :             isSameName = true;
   23497          315 :         else if (OidIsValid(existingRelid))
   23498            4 :             ereport(ERROR,
   23499              :                     errcode(ERRCODE_DUPLICATE_TABLE),
   23500              :                     errmsg("relation \"%s\" already exists", sps->name->relname));
   23501              :     }
   23502              : 
   23503              :     /* Detach the split partition. */
   23504          124 :     detachPartitionTable(rel, splitRel, defaultPartOid);
   23505              : 
   23506              :     /*
   23507              :      * Perform a preliminary check to determine whether it's safe to drop the
   23508              :      * split partition before we actually do so later. After merging rows into
   23509              :      * the new partitions via SplitPartitionMoveRows, all old partitions need
   23510              :      * to be dropped. However, since the drop behavior is DROP_RESTRICT and
   23511              :      * the merge process (SplitPartitionMoveRows) can be time-consuming,
   23512              :      * performing an early check on the drop eligibility of old partitions is
   23513              :      * preferable.
   23514              :      */
   23515          124 :     object.objectId = splitRelOid;
   23516          124 :     object.classId = RelationRelationId;
   23517          124 :     object.objectSubId = 0;
   23518          124 :     performDeletionCheck(&object, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
   23519              : 
   23520              :     /*
   23521              :      * If a new partition has the same name as the split partition, then we
   23522              :      * should rename the split partition to reuse its name.
   23523              :      */
   23524          124 :     if (isSameName)
   23525              :     {
   23526              :         /*
   23527              :          * We must bump the command counter to make the split partition tuple
   23528              :          * visible for renaming.
   23529              :          */
   23530           29 :         CommandCounterIncrement();
   23531              :         /* Rename partition. */
   23532           29 :         sprintf(tmpRelName, "split-%u-%X-tmp", RelationGetRelid(rel), MyProcPid);
   23533           29 :         RenameRelationInternal(splitRelOid, tmpRelName, true, false);
   23534              : 
   23535              :         /*
   23536              :          * We must bump the command counter to make the split partition tuple
   23537              :          * visible after renaming.
   23538              :          */
   23539           29 :         CommandCounterIncrement();
   23540              :     }
   23541              : 
   23542              :     /* Create new partitions (like a split partition), without indexes. */
   23543          576 :     foreach_node(SinglePartitionSpec, sps, cmd->partlist)
   23544              :     {
   23545              :         Relation    newPartRel;
   23546              : 
   23547          336 :         newPartRel = createPartitionTable(wqueue, sps->name, rel,
   23548          336 :                                           splitRel->rd_rel->relowner);
   23549          332 :         newPartRels = lappend(newPartRels, newPartRel);
   23550              :     }
   23551              : 
   23552              :     /*
   23553              :      * Switch to the table owner's userid, so that any index functions are run
   23554              :      * as that user.  Also, lockdown security-restricted operations and
   23555              :      * arrange to make GUC variable changes local to this command.
   23556              :      *
   23557              :      * Need to do it after determining the namespace in the
   23558              :      * createPartitionTable() call.
   23559              :      */
   23560          120 :     GetUserIdAndSecContext(&save_userid, &save_sec_context);
   23561          120 :     SetUserIdAndSecContext(splitRel->rd_rel->relowner,
   23562              :                            save_sec_context | SECURITY_RESTRICTED_OPERATION);
   23563          120 :     save_nestlevel = NewGUCNestLevel();
   23564          120 :     RestrictSearchPath();
   23565              : 
   23566              :     /* Copy data from the split partition to the new partitions. */
   23567          120 :     SplitPartitionMoveRows(wqueue, rel, splitRel, cmd->partlist, newPartRels);
   23568              :     /* Keep the lock until commit. */
   23569          120 :     table_close(splitRel, NoLock);
   23570              : 
   23571              :     /* Attach new partitions to the partitioned table. */
   23572          452 :     forboth(listptr, cmd->partlist, listptr2, newPartRels)
   23573              :     {
   23574          332 :         SinglePartitionSpec *sps = (SinglePartitionSpec *) lfirst(listptr);
   23575          332 :         Relation    newPartRel = (Relation) lfirst(listptr2);
   23576              : 
   23577              :         /*
   23578              :          * wqueue = NULL: verification for each cloned constraint is not
   23579              :          * needed.
   23580              :          */
   23581          332 :         attachPartitionTable(NULL, rel, newPartRel, sps->bound);
   23582              :         /* Keep the lock until commit. */
   23583          332 :         table_close(newPartRel, NoLock);
   23584              :     }
   23585              : 
   23586              :     /* Drop the split partition. */
   23587          120 :     object.classId = RelationRelationId;
   23588          120 :     object.objectId = splitRelOid;
   23589          120 :     object.objectSubId = 0;
   23590              :     /* Probably DROP_CASCADE is not needed. */
   23591          120 :     performDeletion(&object, DROP_RESTRICT, 0);
   23592              : 
   23593              :     /* Roll back any GUC changes executed by index functions. */
   23594          120 :     AtEOXact_GUC(false, save_nestlevel);
   23595              : 
   23596              :     /* Restore the userid and security context. */
   23597          120 :     SetUserIdAndSecContext(save_userid, save_sec_context);
   23598          120 : }
        

Generated by: LCOV version 2.0-1