LCOV - code coverage report
Current view: top level - src/backend/parser - parse_utilcmd.c (source / functions) Hit Total Coverage
Test: PostgreSQL 15devel Lines: 1364 1531 89.1 %
Date: 2021-12-04 22:09:09 Functions: 29 29 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * parse_utilcmd.c
       4             :  *    Perform parse analysis work for various utility commands
       5             :  *
       6             :  * Formerly we did this work during parse_analyze() in analyze.c.  However
       7             :  * that is fairly unsafe in the presence of querytree caching, since any
       8             :  * database state that we depend on in making the transformations might be
       9             :  * obsolete by the time the utility command is executed; and utility commands
      10             :  * have no infrastructure for holding locks or rechecking plan validity.
      11             :  * Hence these functions are now called at the start of execution of their
      12             :  * respective utility commands.
      13             :  *
      14             :  *
      15             :  * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
      16             :  * Portions Copyright (c) 1994, Regents of the University of California
      17             :  *
      18             :  *  src/backend/parser/parse_utilcmd.c
      19             :  *
      20             :  *-------------------------------------------------------------------------
      21             :  */
      22             : 
      23             : #include "postgres.h"
      24             : 
      25             : #include "access/amapi.h"
      26             : #include "access/htup_details.h"
      27             : #include "access/relation.h"
      28             : #include "access/reloptions.h"
      29             : #include "access/table.h"
      30             : #include "access/toast_compression.h"
      31             : #include "catalog/dependency.h"
      32             : #include "catalog/heap.h"
      33             : #include "catalog/index.h"
      34             : #include "catalog/namespace.h"
      35             : #include "catalog/pg_am.h"
      36             : #include "catalog/pg_collation.h"
      37             : #include "catalog/pg_constraint.h"
      38             : #include "catalog/pg_opclass.h"
      39             : #include "catalog/pg_operator.h"
      40             : #include "catalog/pg_statistic_ext.h"
      41             : #include "catalog/pg_type.h"
      42             : #include "commands/comment.h"
      43             : #include "commands/defrem.h"
      44             : #include "commands/sequence.h"
      45             : #include "commands/tablecmds.h"
      46             : #include "commands/tablespace.h"
      47             : #include "miscadmin.h"
      48             : #include "nodes/makefuncs.h"
      49             : #include "nodes/nodeFuncs.h"
      50             : #include "optimizer/optimizer.h"
      51             : #include "parser/analyze.h"
      52             : #include "parser/parse_clause.h"
      53             : #include "parser/parse_coerce.h"
      54             : #include "parser/parse_collate.h"
      55             : #include "parser/parse_expr.h"
      56             : #include "parser/parse_relation.h"
      57             : #include "parser/parse_target.h"
      58             : #include "parser/parse_type.h"
      59             : #include "parser/parse_utilcmd.h"
      60             : #include "parser/parser.h"
      61             : #include "rewrite/rewriteManip.h"
      62             : #include "utils/acl.h"
      63             : #include "utils/builtins.h"
      64             : #include "utils/lsyscache.h"
      65             : #include "utils/partcache.h"
      66             : #include "utils/rel.h"
      67             : #include "utils/ruleutils.h"
      68             : #include "utils/syscache.h"
      69             : #include "utils/typcache.h"
      70             : 
      71             : 
      72             : /* State shared by transformCreateStmt and its subroutines */
      73             : typedef struct
      74             : {
      75             :     ParseState *pstate;         /* overall parser state */
      76             :     const char *stmtType;       /* "CREATE [FOREIGN] TABLE" or "ALTER TABLE" */
      77             :     RangeVar   *relation;       /* relation to create */
      78             :     Relation    rel;            /* opened/locked rel, if ALTER */
      79             :     List       *inhRelations;   /* relations to inherit from */
      80             :     bool        isforeign;      /* true if CREATE/ALTER FOREIGN TABLE */
      81             :     bool        isalter;        /* true if altering existing table */
      82             :     List       *columns;        /* ColumnDef items */
      83             :     List       *ckconstraints;  /* CHECK constraints */
      84             :     List       *fkconstraints;  /* FOREIGN KEY constraints */
      85             :     List       *ixconstraints;  /* index-creating constraints */
      86             :     List       *likeclauses;    /* LIKE clauses that need post-processing */
      87             :     List       *extstats;       /* cloned extended statistics */
      88             :     List       *blist;          /* "before list" of things to do before
      89             :                                  * creating the table */
      90             :     List       *alist;          /* "after list" of things to do after creating
      91             :                                  * the table */
      92             :     IndexStmt  *pkey;           /* PRIMARY KEY index, if any */
      93             :     bool        ispartitioned;  /* true if table is partitioned */
      94             :     PartitionBoundSpec *partbound;  /* transformed FOR VALUES */
      95             :     bool        ofType;         /* true if statement contains OF typename */
      96             : } CreateStmtContext;
      97             : 
      98             : /* State shared by transformCreateSchemaStmt and its subroutines */
      99             : typedef struct
     100             : {
     101             :     const char *stmtType;       /* "CREATE SCHEMA" or "ALTER SCHEMA" */
     102             :     char       *schemaname;     /* name of schema */
     103             :     RoleSpec   *authrole;       /* owner of schema */
     104             :     List       *sequences;      /* CREATE SEQUENCE items */
     105             :     List       *tables;         /* CREATE TABLE items */
     106             :     List       *views;          /* CREATE VIEW items */
     107             :     List       *indexes;        /* CREATE INDEX items */
     108             :     List       *triggers;       /* CREATE TRIGGER items */
     109             :     List       *grants;         /* GRANT items */
     110             : } CreateSchemaStmtContext;
     111             : 
     112             : 
     113             : static void transformColumnDefinition(CreateStmtContext *cxt,
     114             :                                       ColumnDef *column);
     115             : static void transformTableConstraint(CreateStmtContext *cxt,
     116             :                                      Constraint *constraint);
     117             : static void transformTableLikeClause(CreateStmtContext *cxt,
     118             :                                      TableLikeClause *table_like_clause);
     119             : static void transformOfType(CreateStmtContext *cxt,
     120             :                             TypeName *ofTypename);
     121             : static CreateStatsStmt *generateClonedExtStatsStmt(RangeVar *heapRel,
     122             :                                                    Oid heapRelid, Oid source_statsid);
     123             : static List *get_collation(Oid collation, Oid actual_datatype);
     124             : static List *get_opclass(Oid opclass, Oid actual_datatype);
     125             : static void transformIndexConstraints(CreateStmtContext *cxt);
     126             : static IndexStmt *transformIndexConstraint(Constraint *constraint,
     127             :                                            CreateStmtContext *cxt);
     128             : static void transformExtendedStatistics(CreateStmtContext *cxt);
     129             : static void transformFKConstraints(CreateStmtContext *cxt,
     130             :                                    bool skipValidation,
     131             :                                    bool isAddConstraint);
     132             : static void transformCheckConstraints(CreateStmtContext *cxt,
     133             :                                       bool skipValidation);
     134             : static void transformConstraintAttrs(CreateStmtContext *cxt,
     135             :                                      List *constraintList);
     136             : static void transformColumnType(CreateStmtContext *cxt, ColumnDef *column);
     137             : static void setSchemaName(char *context_schema, char **stmt_schema_name);
     138             : static void transformPartitionCmd(CreateStmtContext *cxt, PartitionCmd *cmd);
     139             : static List *transformPartitionRangeBounds(ParseState *pstate, List *blist,
     140             :                                            Relation parent);
     141             : static void validateInfiniteBounds(ParseState *pstate, List *blist);
     142             : static Const *transformPartitionBoundValue(ParseState *pstate, Node *con,
     143             :                                            const char *colName, Oid colType, int32 colTypmod,
     144             :                                            Oid partCollation);
     145             : 
     146             : 
     147             : /*
     148             :  * transformCreateStmt -
     149             :  *    parse analysis for CREATE TABLE
     150             :  *
     151             :  * Returns a List of utility commands to be done in sequence.  One of these
     152             :  * will be the transformed CreateStmt, but there may be additional actions
     153             :  * to be done before and after the actual DefineRelation() call.
     154             :  * In addition to normal utility commands such as AlterTableStmt and
     155             :  * IndexStmt, the result list may contain TableLikeClause(s), representing
     156             :  * the need to perform additional parse analysis after DefineRelation().
     157             :  *
     158             :  * SQL allows constraints to be scattered all over, so thumb through
     159             :  * the columns and collect all constraints into one place.
     160             :  * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
     161             :  * then expand those into multiple IndexStmt blocks.
     162             :  *    - thomas 1997-12-02
     163             :  */
     164             : List *
     165       24264 : transformCreateStmt(CreateStmt *stmt, const char *queryString)
     166             : {
     167             :     ParseState *pstate;
     168             :     CreateStmtContext cxt;
     169             :     List       *result;
     170             :     List       *save_alist;
     171             :     ListCell   *elements;
     172             :     Oid         namespaceid;
     173             :     Oid         existing_relid;
     174             :     ParseCallbackState pcbstate;
     175             : 
     176             :     /* Set up pstate */
     177       24264 :     pstate = make_parsestate(NULL);
     178       24264 :     pstate->p_sourcetext = queryString;
     179             : 
     180             :     /*
     181             :      * Look up the creation namespace.  This also checks permissions on the
     182             :      * target namespace, locks it against concurrent drops, checks for a
     183             :      * preexisting relation in that namespace with the same name, and updates
     184             :      * stmt->relation->relpersistence if the selected namespace is temporary.
     185             :      */
     186       24264 :     setup_parser_errposition_callback(&pcbstate, pstate,
     187       24264 :                                       stmt->relation->location);
     188             :     namespaceid =
     189       24264 :         RangeVarGetAndCheckCreationNamespace(stmt->relation, NoLock,
     190             :                                              &existing_relid);
     191       24256 :     cancel_parser_errposition_callback(&pcbstate);
     192             : 
     193             :     /*
     194             :      * If the relation already exists and the user specified "IF NOT EXISTS",
     195             :      * bail out with a NOTICE.
     196             :      */
     197       24256 :     if (stmt->if_not_exists && OidIsValid(existing_relid))
     198             :     {
     199           8 :         ereport(NOTICE,
     200             :                 (errcode(ERRCODE_DUPLICATE_TABLE),
     201             :                  errmsg("relation \"%s\" already exists, skipping",
     202             :                         stmt->relation->relname)));
     203           8 :         return NIL;
     204             :     }
     205             : 
     206             :     /*
     207             :      * If the target relation name isn't schema-qualified, make it so.  This
     208             :      * prevents some corner cases in which added-on rewritten commands might
     209             :      * think they should apply to other relations that have the same name and
     210             :      * are earlier in the search path.  But a local temp table is effectively
     211             :      * specified to be in pg_temp, so no need for anything extra in that case.
     212             :      */
     213       24248 :     if (stmt->relation->schemaname == NULL
     214       22002 :         && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
     215       20652 :         stmt->relation->schemaname = get_namespace_name(namespaceid);
     216             : 
     217             :     /* Set up CreateStmtContext */
     218       24248 :     cxt.pstate = pstate;
     219       24248 :     if (IsA(stmt, CreateForeignTableStmt))
     220             :     {
     221         358 :         cxt.stmtType = "CREATE FOREIGN TABLE";
     222         358 :         cxt.isforeign = true;
     223             :     }
     224             :     else
     225             :     {
     226       23890 :         cxt.stmtType = "CREATE TABLE";
     227       23890 :         cxt.isforeign = false;
     228             :     }
     229       24248 :     cxt.relation = stmt->relation;
     230       24248 :     cxt.rel = NULL;
     231       24248 :     cxt.inhRelations = stmt->inhRelations;
     232       24248 :     cxt.isalter = false;
     233       24248 :     cxt.columns = NIL;
     234       24248 :     cxt.ckconstraints = NIL;
     235       24248 :     cxt.fkconstraints = NIL;
     236       24248 :     cxt.ixconstraints = NIL;
     237       24248 :     cxt.likeclauses = NIL;
     238       24248 :     cxt.extstats = NIL;
     239       24248 :     cxt.blist = NIL;
     240       24248 :     cxt.alist = NIL;
     241       24248 :     cxt.pkey = NULL;
     242       24248 :     cxt.ispartitioned = stmt->partspec != NULL;
     243       24248 :     cxt.partbound = stmt->partbound;
     244       24248 :     cxt.ofType = (stmt->ofTypename != NULL);
     245             : 
     246             :     Assert(!stmt->ofTypename || !stmt->inhRelations); /* grammar enforces */
     247             : 
     248       24248 :     if (stmt->ofTypename)
     249          74 :         transformOfType(&cxt, stmt->ofTypename);
     250             : 
     251       24240 :     if (stmt->partspec)
     252             :     {
     253        2878 :         if (stmt->inhRelations && !stmt->partbound)
     254           4 :             ereport(ERROR,
     255             :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
     256             :                      errmsg("cannot create partitioned table as inheritance child")));
     257             :     }
     258             : 
     259             :     /*
     260             :      * Run through each primary element in the table creation clause. Separate
     261             :      * column defs from constraints, and do preliminary analysis.
     262             :      */
     263       75132 :     foreach(elements, stmt->tableElts)
     264             :     {
     265       50982 :         Node       *element = lfirst(elements);
     266             : 
     267       50982 :         switch (nodeTag(element))
     268             :         {
     269       49310 :             case T_ColumnDef:
     270       49310 :                 transformColumnDefinition(&cxt, (ColumnDef *) element);
     271       49244 :                 break;
     272             : 
     273        1222 :             case T_Constraint:
     274        1222 :                 transformTableConstraint(&cxt, (Constraint *) element);
     275        1210 :                 break;
     276             : 
     277         450 :             case T_TableLikeClause:
     278         450 :                 transformTableLikeClause(&cxt, (TableLikeClause *) element);
     279         442 :                 break;
     280             : 
     281           0 :             default:
     282           0 :                 elog(ERROR, "unrecognized node type: %d",
     283             :                      (int) nodeTag(element));
     284             :                 break;
     285             :         }
     286             :     }
     287             : 
     288             :     /*
     289             :      * Transfer anything we already have in cxt.alist into save_alist, to keep
     290             :      * it separate from the output of transformIndexConstraints.  (This may
     291             :      * not be necessary anymore, but we'll keep doing it to preserve the
     292             :      * historical order of execution of the alist commands.)
     293             :      */
     294       24150 :     save_alist = cxt.alist;
     295       24150 :     cxt.alist = NIL;
     296             : 
     297             :     Assert(stmt->constraints == NIL);
     298             : 
     299             :     /*
     300             :      * Postprocess constraints that give rise to index definitions.
     301             :      */
     302       24150 :     transformIndexConstraints(&cxt);
     303             : 
     304             :     /*
     305             :      * Re-consideration of LIKE clauses should happen after creation of
     306             :      * indexes, but before creation of foreign keys.  This order is critical
     307             :      * because a LIKE clause may attempt to create a primary key.  If there's
     308             :      * also a pkey in the main CREATE TABLE list, creation of that will not
     309             :      * check for a duplicate at runtime (since index_check_primary_key()
     310             :      * expects that we rejected dups here).  Creation of the LIKE-generated
     311             :      * pkey behaves like ALTER TABLE ADD, so it will check, but obviously that
     312             :      * only works if it happens second.  On the other hand, we want to make
     313             :      * pkeys before foreign key constraints, in case the user tries to make a
     314             :      * self-referential FK.
     315             :      */
     316       24150 :     cxt.alist = list_concat(cxt.alist, cxt.likeclauses);
     317             : 
     318             :     /*
     319             :      * Postprocess foreign-key constraints.
     320             :      */
     321       24150 :     transformFKConstraints(&cxt, true, false);
     322             : 
     323             :     /*
     324             :      * Postprocess check constraints.
     325             :      *
     326             :      * For regular tables all constraints can be marked valid immediately,
     327             :      * because the table is new therefore empty. Not so for foreign tables.
     328             :      */
     329       24150 :     transformCheckConstraints(&cxt, !cxt.isforeign);
     330             : 
     331             :     /*
     332             :      * Postprocess extended statistics.
     333             :      */
     334       24150 :     transformExtendedStatistics(&cxt);
     335             : 
     336             :     /*
     337             :      * Output results.
     338             :      */
     339       24150 :     stmt->tableElts = cxt.columns;
     340       24150 :     stmt->constraints = cxt.ckconstraints;
     341             : 
     342       24150 :     result = lappend(cxt.blist, stmt);
     343       24150 :     result = list_concat(result, cxt.alist);
     344       24150 :     result = list_concat(result, save_alist);
     345             : 
     346       24150 :     return result;
     347             : }
     348             : 
     349             : /*
     350             :  * generateSerialExtraStmts
     351             :  *      Generate CREATE SEQUENCE and ALTER SEQUENCE ... OWNED BY statements
     352             :  *      to create the sequence for a serial or identity column.
     353             :  *
     354             :  * This includes determining the name the sequence will have.  The caller
     355             :  * can ask to get back the name components by passing non-null pointers
     356             :  * for snamespace_p and sname_p.
     357             :  */
     358             : static void
     359         718 : generateSerialExtraStmts(CreateStmtContext *cxt, ColumnDef *column,
     360             :                          Oid seqtypid, List *seqoptions,
     361             :                          bool for_identity, bool col_exists,
     362             :                          char **snamespace_p, char **sname_p)
     363             : {
     364             :     ListCell   *option;
     365         718 :     DefElem    *nameEl = NULL;
     366             :     Oid         snamespaceid;
     367             :     char       *snamespace;
     368             :     char       *sname;
     369             :     CreateSeqStmt *seqstmt;
     370             :     AlterSeqStmt *altseqstmt;
     371             :     List       *attnamelist;
     372         718 :     int         nameEl_idx = -1;
     373             : 
     374             :     /*
     375             :      * Determine namespace and name to use for the sequence.
     376             :      *
     377             :      * First, check if a sequence name was passed in as an option.  This is
     378             :      * used by pg_dump.  Else, generate a name.
     379             :      *
     380             :      * Although we use ChooseRelationName, it's not guaranteed that the
     381             :      * selected sequence name won't conflict; given sufficiently long field
     382             :      * names, two different serial columns in the same table could be assigned
     383             :      * the same sequence name, and we'd not notice since we aren't creating
     384             :      * the sequence quite yet.  In practice this seems quite unlikely to be a
     385             :      * problem, especially since few people would need two serial columns in
     386             :      * one table.
     387             :      */
     388         922 :     foreach(option, seqoptions)
     389             :     {
     390         204 :         DefElem    *defel = lfirst_node(DefElem, option);
     391             : 
     392         204 :         if (strcmp(defel->defname, "sequence_name") == 0)
     393             :         {
     394          28 :             if (nameEl)
     395           0 :                 errorConflictingDefElem(defel, cxt->pstate);
     396          28 :             nameEl = defel;
     397          28 :             nameEl_idx = foreach_current_index(option);
     398             :         }
     399             :     }
     400             : 
     401         718 :     if (nameEl)
     402             :     {
     403          28 :         RangeVar   *rv = makeRangeVarFromNameList(castNode(List, nameEl->arg));
     404             : 
     405          28 :         snamespace = rv->schemaname;
     406          28 :         if (!snamespace)
     407             :         {
     408             :             /* Given unqualified SEQUENCE NAME, select namespace */
     409           0 :             if (cxt->rel)
     410           0 :                 snamespaceid = RelationGetNamespace(cxt->rel);
     411             :             else
     412           0 :                 snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
     413           0 :             snamespace = get_namespace_name(snamespaceid);
     414             :         }
     415          28 :         sname = rv->relname;
     416             :         /* Remove the SEQUENCE NAME item from seqoptions */
     417          28 :         seqoptions = list_delete_nth_cell(seqoptions, nameEl_idx);
     418             :     }
     419             :     else
     420             :     {
     421         690 :         if (cxt->rel)
     422          96 :             snamespaceid = RelationGetNamespace(cxt->rel);
     423             :         else
     424             :         {
     425         594 :             snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
     426         594 :             RangeVarAdjustRelationPersistence(cxt->relation, snamespaceid);
     427             :         }
     428         690 :         snamespace = get_namespace_name(snamespaceid);
     429         690 :         sname = ChooseRelationName(cxt->relation->relname,
     430         690 :                                    column->colname,
     431             :                                    "seq",
     432             :                                    snamespaceid,
     433             :                                    false);
     434             :     }
     435             : 
     436         718 :     ereport(DEBUG1,
     437             :             (errmsg_internal("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
     438             :                              cxt->stmtType, sname,
     439             :                              cxt->relation->relname, column->colname)));
     440             : 
     441             :     /*
     442             :      * Build a CREATE SEQUENCE command to create the sequence object, and add
     443             :      * it to the list of things to be done before this CREATE/ALTER TABLE.
     444             :      */
     445         718 :     seqstmt = makeNode(CreateSeqStmt);
     446         718 :     seqstmt->for_identity = for_identity;
     447         718 :     seqstmt->sequence = makeRangeVar(snamespace, sname, -1);
     448         718 :     seqstmt->options = seqoptions;
     449             : 
     450             :     /*
     451             :      * If a sequence data type was specified, add it to the options.  Prepend
     452             :      * to the list rather than append; in case a user supplied their own AS
     453             :      * clause, the "redundant options" error will point to their occurrence,
     454             :      * not our synthetic one.
     455             :      */
     456         718 :     if (seqtypid)
     457         714 :         seqstmt->options = lcons(makeDefElem("as",
     458         714 :                                              (Node *) makeTypeNameFromOid(seqtypid, -1),
     459             :                                              -1),
     460             :                                  seqstmt->options);
     461             : 
     462             :     /*
     463             :      * If this is ALTER ADD COLUMN, make sure the sequence will be owned by
     464             :      * the table's owner.  The current user might be someone else (perhaps a
     465             :      * superuser, or someone who's only a member of the owning role), but the
     466             :      * SEQUENCE OWNED BY mechanisms will bleat unless table and sequence have
     467             :      * exactly the same owning role.
     468             :      */
     469         718 :     if (cxt->rel)
     470         124 :         seqstmt->ownerId = cxt->rel->rd_rel->relowner;
     471             :     else
     472         594 :         seqstmt->ownerId = InvalidOid;
     473             : 
     474         718 :     cxt->blist = lappend(cxt->blist, seqstmt);
     475             : 
     476             :     /*
     477             :      * Store the identity sequence name that we decided on.  ALTER TABLE ...
     478             :      * ADD COLUMN ... IDENTITY needs this so that it can fill the new column
     479             :      * with values from the sequence, while the association of the sequence
     480             :      * with the table is not set until after the ALTER TABLE.
     481             :      */
     482         718 :     column->identitySequence = seqstmt->sequence;
     483             : 
     484             :     /*
     485             :      * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence as
     486             :      * owned by this column, and add it to the appropriate list of things to
     487             :      * be done along with this CREATE/ALTER TABLE.  In a CREATE or ALTER ADD
     488             :      * COLUMN, it must be done after the statement because we don't know the
     489             :      * column's attnum yet.  But if we do have the attnum (in AT_AddIdentity),
     490             :      * we can do the marking immediately, which improves some ALTER TABLE
     491             :      * behaviors.
     492             :      */
     493         718 :     altseqstmt = makeNode(AlterSeqStmt);
     494         718 :     altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
     495         718 :     attnamelist = list_make3(makeString(snamespace),
     496             :                              makeString(cxt->relation->relname),
     497             :                              makeString(column->colname));
     498         718 :     altseqstmt->options = list_make1(makeDefElem("owned_by",
     499             :                                                  (Node *) attnamelist, -1));
     500         718 :     altseqstmt->for_identity = for_identity;
     501             : 
     502         718 :     if (col_exists)
     503          76 :         cxt->blist = lappend(cxt->blist, altseqstmt);
     504             :     else
     505         642 :         cxt->alist = lappend(cxt->alist, altseqstmt);
     506             : 
     507         718 :     if (snamespace_p)
     508         518 :         *snamespace_p = snamespace;
     509         718 :     if (sname_p)
     510         518 :         *sname_p = sname;
     511         718 : }
     512             : 
     513             : /*
     514             :  * transformColumnDefinition -
     515             :  *      transform a single ColumnDef within CREATE TABLE
     516             :  *      Also used in ALTER TABLE ADD COLUMN
     517             :  */
     518             : static void
     519       50514 : transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
     520             : {
     521             :     bool        is_serial;
     522             :     bool        saw_nullable;
     523             :     bool        saw_default;
     524             :     bool        saw_identity;
     525             :     bool        saw_generated;
     526             :     ListCell   *clist;
     527             : 
     528       50514 :     cxt->columns = lappend(cxt->columns, column);
     529             : 
     530             :     /* Check for SERIAL pseudo-types */
     531       50514 :     is_serial = false;
     532       50514 :     if (column->typeName
     533       50390 :         && list_length(column->typeName->names) == 1
     534       26464 :         && !column->typeName->pct_type)
     535             :     {
     536       26464 :         char       *typname = strVal(linitial(column->typeName->names));
     537             : 
     538       26464 :         if (strcmp(typname, "smallserial") == 0 ||
     539       26458 :             strcmp(typname, "serial2") == 0)
     540             :         {
     541          10 :             is_serial = true;
     542          10 :             column->typeName->names = NIL;
     543          10 :             column->typeName->typeOid = INT2OID;
     544             :         }
     545       26454 :         else if (strcmp(typname, "serial") == 0 ||
     546       25960 :                  strcmp(typname, "serial4") == 0)
     547             :         {
     548         494 :             is_serial = true;
     549         494 :             column->typeName->names = NIL;
     550         494 :             column->typeName->typeOid = INT4OID;
     551             :         }
     552       25960 :         else if (strcmp(typname, "bigserial") == 0 ||
     553       25954 :                  strcmp(typname, "serial8") == 0)
     554             :         {
     555          14 :             is_serial = true;
     556          14 :             column->typeName->names = NIL;
     557          14 :             column->typeName->typeOid = INT8OID;
     558             :         }
     559             : 
     560             :         /*
     561             :          * We have to reject "serial[]" explicitly, because once we've set
     562             :          * typeid, LookupTypeName won't notice arrayBounds.  We don't need any
     563             :          * special coding for serial(typmod) though.
     564             :          */
     565       26464 :         if (is_serial && column->typeName->arrayBounds != NIL)
     566           0 :             ereport(ERROR,
     567             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     568             :                      errmsg("array of serial is not implemented"),
     569             :                      parser_errposition(cxt->pstate,
     570             :                                         column->typeName->location)));
     571             :     }
     572             : 
     573             :     /* Do necessary work on the column type declaration */
     574       50514 :     if (column->typeName)
     575       50390 :         transformColumnType(cxt, column);
     576             : 
     577             :     /* Special actions for SERIAL pseudo-types */
     578       50504 :     if (is_serial)
     579             :     {
     580             :         char       *snamespace;
     581             :         char       *sname;
     582             :         char       *qstring;
     583             :         A_Const    *snamenode;
     584             :         TypeCast   *castnode;
     585             :         FuncCall   *funccallnode;
     586             :         Constraint *constraint;
     587             : 
     588         518 :         generateSerialExtraStmts(cxt, column,
     589         518 :                                  column->typeName->typeOid, NIL,
     590             :                                  false, false,
     591             :                                  &snamespace, &sname);
     592             : 
     593             :         /*
     594             :          * Create appropriate constraints for SERIAL.  We do this in full,
     595             :          * rather than shortcutting, so that we will detect any conflicting
     596             :          * constraints the user wrote (like a different DEFAULT).
     597             :          *
     598             :          * Create an expression tree representing the function call
     599             :          * nextval('sequencename').  We cannot reduce the raw tree to cooked
     600             :          * form until after the sequence is created, but there's no need to do
     601             :          * so.
     602             :          */
     603         518 :         qstring = quote_qualified_identifier(snamespace, sname);
     604         518 :         snamenode = makeNode(A_Const);
     605         518 :         snamenode->val.node.type = T_String;
     606         518 :         snamenode->val.sval.val = qstring;
     607         518 :         snamenode->location = -1;
     608         518 :         castnode = makeNode(TypeCast);
     609         518 :         castnode->typeName = SystemTypeName("regclass");
     610         518 :         castnode->arg = (Node *) snamenode;
     611         518 :         castnode->location = -1;
     612         518 :         funccallnode = makeFuncCall(SystemFuncName("nextval"),
     613         518 :                                     list_make1(castnode),
     614             :                                     COERCE_EXPLICIT_CALL,
     615             :                                     -1);
     616         518 :         constraint = makeNode(Constraint);
     617         518 :         constraint->contype = CONSTR_DEFAULT;
     618         518 :         constraint->location = -1;
     619         518 :         constraint->raw_expr = (Node *) funccallnode;
     620         518 :         constraint->cooked_expr = NULL;
     621         518 :         column->constraints = lappend(column->constraints, constraint);
     622             : 
     623         518 :         constraint = makeNode(Constraint);
     624         518 :         constraint->contype = CONSTR_NOTNULL;
     625         518 :         constraint->location = -1;
     626         518 :         column->constraints = lappend(column->constraints, constraint);
     627             :     }
     628             : 
     629             :     /* Process column constraints, if any... */
     630       50504 :     transformConstraintAttrs(cxt, column->constraints);
     631             : 
     632       50504 :     saw_nullable = false;
     633       50504 :     saw_default = false;
     634       50504 :     saw_identity = false;
     635       50504 :     saw_generated = false;
     636             : 
     637       62542 :     foreach(clist, column->constraints)
     638             :     {
     639       12094 :         Constraint *constraint = lfirst_node(Constraint, clist);
     640             : 
     641       12094 :         switch (constraint->contype)
     642             :         {
     643          18 :             case CONSTR_NULL:
     644          18 :                 if (saw_nullable && column->is_not_null)
     645           4 :                     ereport(ERROR,
     646             :                             (errcode(ERRCODE_SYNTAX_ERROR),
     647             :                              errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
     648             :                                     column->colname, cxt->relation->relname),
     649             :                              parser_errposition(cxt->pstate,
     650             :                                                 constraint->location)));
     651          14 :                 column->is_not_null = false;
     652          14 :                 saw_nullable = true;
     653          14 :                 break;
     654             : 
     655        5158 :             case CONSTR_NOTNULL:
     656        5158 :                 if (saw_nullable && !column->is_not_null)
     657           0 :                     ereport(ERROR,
     658             :                             (errcode(ERRCODE_SYNTAX_ERROR),
     659             :                              errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
     660             :                                     column->colname, cxt->relation->relname),
     661             :                              parser_errposition(cxt->pstate,
     662             :                                                 constraint->location)));
     663        5158 :                 column->is_not_null = true;
     664        5158 :                 saw_nullable = true;
     665        5158 :                 break;
     666             : 
     667        1568 :             case CONSTR_DEFAULT:
     668        1568 :                 if (saw_default)
     669           0 :                     ereport(ERROR,
     670             :                             (errcode(ERRCODE_SYNTAX_ERROR),
     671             :                              errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
     672             :                                     column->colname, cxt->relation->relname),
     673             :                              parser_errposition(cxt->pstate,
     674             :                                                 constraint->location)));
     675        1568 :                 column->raw_default = constraint->raw_expr;
     676             :                 Assert(constraint->cooked_expr == NULL);
     677        1568 :                 saw_default = true;
     678        1568 :                 break;
     679             : 
     680         132 :             case CONSTR_IDENTITY:
     681             :                 {
     682             :                     Type        ctype;
     683             :                     Oid         typeOid;
     684             : 
     685         132 :                     if (cxt->ofType)
     686           4 :                         ereport(ERROR,
     687             :                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     688             :                                  errmsg("identity columns are not supported on typed tables")));
     689         128 :                     if (cxt->partbound)
     690           4 :                         ereport(ERROR,
     691             :                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     692             :                                  errmsg("identity columns are not supported on partitions")));
     693             : 
     694         124 :                     ctype = typenameType(cxt->pstate, column->typeName, NULL);
     695         124 :                     typeOid = ((Form_pg_type) GETSTRUCT(ctype))->oid;
     696         124 :                     ReleaseSysCache(ctype);
     697             : 
     698         124 :                     if (saw_identity)
     699           4 :                         ereport(ERROR,
     700             :                                 (errcode(ERRCODE_SYNTAX_ERROR),
     701             :                                  errmsg("multiple identity specifications for column \"%s\" of table \"%s\"",
     702             :                                         column->colname, cxt->relation->relname),
     703             :                                  parser_errposition(cxt->pstate,
     704             :                                                     constraint->location)));
     705             : 
     706         120 :                     generateSerialExtraStmts(cxt, column,
     707             :                                              typeOid, constraint->options,
     708             :                                              true, false,
     709             :                                              NULL, NULL);
     710             : 
     711         120 :                     column->identity = constraint->generated_when;
     712         120 :                     saw_identity = true;
     713             : 
     714             :                     /* An identity column is implicitly NOT NULL */
     715         120 :                     if (saw_nullable && !column->is_not_null)
     716           4 :                         ereport(ERROR,
     717             :                                 (errcode(ERRCODE_SYNTAX_ERROR),
     718             :                                  errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
     719             :                                         column->colname, cxt->relation->relname),
     720             :                                  parser_errposition(cxt->pstate,
     721             :                                                     constraint->location)));
     722         116 :                     column->is_not_null = true;
     723         116 :                     saw_nullable = true;
     724         116 :                     break;
     725             :                 }
     726             : 
     727         370 :             case CONSTR_GENERATED:
     728         370 :                 if (cxt->ofType)
     729           4 :                     ereport(ERROR,
     730             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     731             :                              errmsg("generated columns are not supported on typed tables")));
     732         366 :                 if (cxt->partbound)
     733           4 :                     ereport(ERROR,
     734             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     735             :                              errmsg("generated columns are not supported on partitions")));
     736             : 
     737         362 :                 if (saw_generated)
     738           4 :                     ereport(ERROR,
     739             :                             (errcode(ERRCODE_SYNTAX_ERROR),
     740             :                              errmsg("multiple generation clauses specified for column \"%s\" of table \"%s\"",
     741             :                                     column->colname, cxt->relation->relname),
     742             :                              parser_errposition(cxt->pstate,
     743             :                                                 constraint->location)));
     744         358 :                 column->generated = ATTRIBUTE_GENERATED_STORED;
     745         358 :                 column->raw_default = constraint->raw_expr;
     746             :                 Assert(constraint->cooked_expr == NULL);
     747         358 :                 saw_generated = true;
     748         358 :                 break;
     749             : 
     750         228 :             case CONSTR_CHECK:
     751         228 :                 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
     752         228 :                 break;
     753             : 
     754        3850 :             case CONSTR_PRIMARY:
     755        3850 :                 if (cxt->isforeign)
     756           4 :                     ereport(ERROR,
     757             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     758             :                              errmsg("primary key constraints are not supported on foreign tables"),
     759             :                              parser_errposition(cxt->pstate,
     760             :                                                 constraint->location)));
     761             :                 /* FALL THRU */
     762             : 
     763             :             case CONSTR_UNIQUE:
     764        4038 :                 if (cxt->isforeign)
     765           0 :                     ereport(ERROR,
     766             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     767             :                              errmsg("unique constraints are not supported on foreign tables"),
     768             :                              parser_errposition(cxt->pstate,
     769             :                                                 constraint->location)));
     770        4038 :                 if (constraint->keys == NIL)
     771        4038 :                     constraint->keys = list_make1(makeString(column->colname));
     772        4038 :                 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
     773        4038 :                 break;
     774             : 
     775           0 :             case CONSTR_EXCLUSION:
     776             :                 /* grammar does not allow EXCLUDE as a column constraint */
     777           0 :                 elog(ERROR, "column exclusion constraints are not supported");
     778             :                 break;
     779             : 
     780         500 :             case CONSTR_FOREIGN:
     781         500 :                 if (cxt->isforeign)
     782           4 :                     ereport(ERROR,
     783             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     784             :                              errmsg("foreign key constraints are not supported on foreign tables"),
     785             :                              parser_errposition(cxt->pstate,
     786             :                                                 constraint->location)));
     787             : 
     788             :                 /*
     789             :                  * Fill in the current attribute's name and throw it into the
     790             :                  * list of FK constraints to be processed later.
     791             :                  */
     792         496 :                 constraint->fk_attrs = list_make1(makeString(column->colname));
     793         496 :                 cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
     794         496 :                 break;
     795             : 
     796          78 :             case CONSTR_ATTR_DEFERRABLE:
     797             :             case CONSTR_ATTR_NOT_DEFERRABLE:
     798             :             case CONSTR_ATTR_DEFERRED:
     799             :             case CONSTR_ATTR_IMMEDIATE:
     800             :                 /* transformConstraintAttrs took care of these */
     801          78 :                 break;
     802             : 
     803           0 :             default:
     804           0 :                 elog(ERROR, "unrecognized constraint type: %d",
     805             :                      constraint->contype);
     806             :                 break;
     807             :         }
     808             : 
     809       12054 :         if (saw_default && saw_identity)
     810           8 :             ereport(ERROR,
     811             :                     (errcode(ERRCODE_SYNTAX_ERROR),
     812             :                      errmsg("both default and identity specified for column \"%s\" of table \"%s\"",
     813             :                             column->colname, cxt->relation->relname),
     814             :                      parser_errposition(cxt->pstate,
     815             :                                         constraint->location)));
     816             : 
     817       12046 :         if (saw_default && saw_generated)
     818           4 :             ereport(ERROR,
     819             :                     (errcode(ERRCODE_SYNTAX_ERROR),
     820             :                      errmsg("both default and generation expression specified for column \"%s\" of table \"%s\"",
     821             :                             column->colname, cxt->relation->relname),
     822             :                      parser_errposition(cxt->pstate,
     823             :                                         constraint->location)));
     824             : 
     825       12042 :         if (saw_identity && saw_generated)
     826           4 :             ereport(ERROR,
     827             :                     (errcode(ERRCODE_SYNTAX_ERROR),
     828             :                      errmsg("both identity and generation expression specified for column \"%s\" of table \"%s\"",
     829             :                             column->colname, cxt->relation->relname),
     830             :                      parser_errposition(cxt->pstate,
     831             :                                         constraint->location)));
     832             :     }
     833             : 
     834             :     /*
     835             :      * If needed, generate ALTER FOREIGN TABLE ALTER COLUMN statement to add
     836             :      * per-column foreign data wrapper options to this column after creation.
     837             :      */
     838       50448 :     if (column->fdwoptions != NIL)
     839             :     {
     840             :         AlterTableStmt *stmt;
     841             :         AlterTableCmd *cmd;
     842             : 
     843         142 :         cmd = makeNode(AlterTableCmd);
     844         142 :         cmd->subtype = AT_AlterColumnGenericOptions;
     845         142 :         cmd->name = column->colname;
     846         142 :         cmd->def = (Node *) column->fdwoptions;
     847         142 :         cmd->behavior = DROP_RESTRICT;
     848         142 :         cmd->missing_ok = false;
     849             : 
     850         142 :         stmt = makeNode(AlterTableStmt);
     851         142 :         stmt->relation = cxt->relation;
     852         142 :         stmt->cmds = NIL;
     853         142 :         stmt->objtype = OBJECT_FOREIGN_TABLE;
     854         142 :         stmt->cmds = lappend(stmt->cmds, cmd);
     855             : 
     856         142 :         cxt->alist = lappend(cxt->alist, stmt);
     857             :     }
     858       50448 : }
     859             : 
     860             : /*
     861             :  * transformTableConstraint
     862             :  *      transform a Constraint node within CREATE TABLE or ALTER TABLE
     863             :  */
     864             : static void
     865       55470 : transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
     866             : {
     867       55470 :     switch (constraint->contype)
     868             :     {
     869       30452 :         case CONSTR_PRIMARY:
     870       30452 :             if (cxt->isforeign)
     871           4 :                 ereport(ERROR,
     872             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     873             :                          errmsg("primary key constraints are not supported on foreign tables"),
     874             :                          parser_errposition(cxt->pstate,
     875             :                                             constraint->location)));
     876       30448 :             cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
     877       30448 :             break;
     878             : 
     879       22452 :         case CONSTR_UNIQUE:
     880       22452 :             if (cxt->isforeign)
     881           4 :                 ereport(ERROR,
     882             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     883             :                          errmsg("unique constraints are not supported on foreign tables"),
     884             :                          parser_errposition(cxt->pstate,
     885             :                                             constraint->location)));
     886       22448 :             cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
     887       22448 :             break;
     888             : 
     889         100 :         case CONSTR_EXCLUSION:
     890         100 :             if (cxt->isforeign)
     891           0 :                 ereport(ERROR,
     892             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     893             :                          errmsg("exclusion constraints are not supported on foreign tables"),
     894             :                          parser_errposition(cxt->pstate,
     895             :                                             constraint->location)));
     896         100 :             if (cxt->ispartitioned)
     897          16 :                 ereport(ERROR,
     898             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     899             :                          errmsg("exclusion constraints are not supported on partitioned tables"),
     900             :                          parser_errposition(cxt->pstate,
     901             :                                             constraint->location)));
     902          84 :             cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
     903          84 :             break;
     904             : 
     905         746 :         case CONSTR_CHECK:
     906         746 :             cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
     907         746 :             break;
     908             : 
     909        1720 :         case CONSTR_FOREIGN:
     910        1720 :             if (cxt->isforeign)
     911           0 :                 ereport(ERROR,
     912             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     913             :                          errmsg("foreign key constraints are not supported on foreign tables"),
     914             :                          parser_errposition(cxt->pstate,
     915             :                                             constraint->location)));
     916        1720 :             cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
     917        1720 :             break;
     918             : 
     919           0 :         case CONSTR_NULL:
     920             :         case CONSTR_NOTNULL:
     921             :         case CONSTR_DEFAULT:
     922             :         case CONSTR_ATTR_DEFERRABLE:
     923             :         case CONSTR_ATTR_NOT_DEFERRABLE:
     924             :         case CONSTR_ATTR_DEFERRED:
     925             :         case CONSTR_ATTR_IMMEDIATE:
     926           0 :             elog(ERROR, "invalid context for constraint type %d",
     927             :                  constraint->contype);
     928             :             break;
     929             : 
     930           0 :         default:
     931           0 :             elog(ERROR, "unrecognized constraint type: %d",
     932             :                  constraint->contype);
     933             :             break;
     934             :     }
     935       55446 : }
     936             : 
     937             : /*
     938             :  * transformTableLikeClause
     939             :  *
     940             :  * Change the LIKE <srctable> portion of a CREATE TABLE statement into
     941             :  * column definitions that recreate the user defined column portions of
     942             :  * <srctable>.  Also, if there are any LIKE options that we can't fully
     943             :  * process at this point, add the TableLikeClause to cxt->likeclauses, which
     944             :  * will cause utility.c to call expandTableLikeClause() after the new
     945             :  * table has been created.
     946             :  */
     947             : static void
     948         450 : transformTableLikeClause(CreateStmtContext *cxt, TableLikeClause *table_like_clause)
     949             : {
     950             :     AttrNumber  parent_attno;
     951             :     Relation    relation;
     952             :     TupleDesc   tupleDesc;
     953             :     AclResult   aclresult;
     954             :     char       *comment;
     955             :     ParseCallbackState pcbstate;
     956             : 
     957         450 :     setup_parser_errposition_callback(&pcbstate, cxt->pstate,
     958         450 :                                       table_like_clause->relation->location);
     959             : 
     960             :     /* we could support LIKE in many cases, but worry about it another day */
     961         450 :     if (cxt->isforeign)
     962           0 :         ereport(ERROR,
     963             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     964             :                  errmsg("LIKE is not supported for creating foreign tables")));
     965             : 
     966             :     /* Open the relation referenced by the LIKE clause */
     967         450 :     relation = relation_openrv(table_like_clause->relation, AccessShareLock);
     968             : 
     969         446 :     if (relation->rd_rel->relkind != RELKIND_RELATION &&
     970         262 :         relation->rd_rel->relkind != RELKIND_VIEW &&
     971         254 :         relation->rd_rel->relkind != RELKIND_MATVIEW &&
     972         254 :         relation->rd_rel->relkind != RELKIND_COMPOSITE_TYPE &&
     973         250 :         relation->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
     974         250 :         relation->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
     975           4 :         ereport(ERROR,
     976             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
     977             :                  errmsg("relation \"%s\" is invalid in LIKE clause",
     978             :                         RelationGetRelationName(relation)),
     979             :                  errdetail_relkind_not_supported(relation->rd_rel->relkind)));
     980             : 
     981         442 :     cancel_parser_errposition_callback(&pcbstate);
     982             : 
     983             :     /*
     984             :      * Check for privileges
     985             :      */
     986         442 :     if (relation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
     987             :     {
     988           4 :         aclresult = pg_type_aclcheck(relation->rd_rel->reltype, GetUserId(),
     989             :                                      ACL_USAGE);
     990           4 :         if (aclresult != ACLCHECK_OK)
     991           0 :             aclcheck_error(aclresult, OBJECT_TYPE,
     992           0 :                            RelationGetRelationName(relation));
     993             :     }
     994             :     else
     995             :     {
     996         438 :         aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
     997             :                                       ACL_SELECT);
     998         438 :         if (aclresult != ACLCHECK_OK)
     999           0 :             aclcheck_error(aclresult, get_relkind_objtype(relation->rd_rel->relkind),
    1000           0 :                            RelationGetRelationName(relation));
    1001             :     }
    1002             : 
    1003         442 :     tupleDesc = RelationGetDescr(relation);
    1004             : 
    1005             :     /*
    1006             :      * Insert the copied attributes into the cxt for the new table definition.
    1007             :      * We must do this now so that they appear in the table in the relative
    1008             :      * position where the LIKE clause is, as required by SQL99.
    1009             :      */
    1010        1330 :     for (parent_attno = 1; parent_attno <= tupleDesc->natts;
    1011         888 :          parent_attno++)
    1012             :     {
    1013         888 :         Form_pg_attribute attribute = TupleDescAttr(tupleDesc,
    1014             :                                                     parent_attno - 1);
    1015         888 :         char       *attributeName = NameStr(attribute->attname);
    1016             :         ColumnDef  *def;
    1017             : 
    1018             :         /*
    1019             :          * Ignore dropped columns in the parent.
    1020             :          */
    1021         888 :         if (attribute->attisdropped)
    1022           8 :             continue;
    1023             : 
    1024             :         /*
    1025             :          * Create a new column, which is marked as NOT inherited.
    1026             :          *
    1027             :          * For constraints, ONLY the NOT NULL constraint is inherited by the
    1028             :          * new column definition per SQL99.
    1029             :          */
    1030         880 :         def = makeNode(ColumnDef);
    1031         880 :         def->colname = pstrdup(attributeName);
    1032         880 :         def->typeName = makeTypeNameFromOid(attribute->atttypid,
    1033             :                                             attribute->atttypmod);
    1034         880 :         def->inhcount = 0;
    1035         880 :         def->is_local = true;
    1036         880 :         def->is_not_null = attribute->attnotnull;
    1037         880 :         def->is_from_type = false;
    1038         880 :         def->storage = 0;
    1039         880 :         def->raw_default = NULL;
    1040         880 :         def->cooked_default = NULL;
    1041         880 :         def->collClause = NULL;
    1042         880 :         def->collOid = attribute->attcollation;
    1043         880 :         def->constraints = NIL;
    1044         880 :         def->location = -1;
    1045             : 
    1046             :         /*
    1047             :          * Add to column list
    1048             :          */
    1049         880 :         cxt->columns = lappend(cxt->columns, def);
    1050             : 
    1051             :         /*
    1052             :          * Although we don't transfer the column's default/generation
    1053             :          * expression now, we need to mark it GENERATED if appropriate.
    1054             :          */
    1055         880 :         if (attribute->atthasdef && attribute->attgenerated &&
    1056          32 :             (table_like_clause->options & CREATE_TABLE_LIKE_GENERATED))
    1057          20 :             def->generated = attribute->attgenerated;
    1058             : 
    1059             :         /*
    1060             :          * Copy identity if requested
    1061             :          */
    1062         880 :         if (attribute->attidentity &&
    1063           8 :             (table_like_clause->options & CREATE_TABLE_LIKE_IDENTITY))
    1064             :         {
    1065             :             Oid         seq_relid;
    1066             :             List       *seq_options;
    1067             : 
    1068             :             /*
    1069             :              * find sequence owned by old column; extract sequence parameters;
    1070             :              * build new create sequence command
    1071             :              */
    1072           4 :             seq_relid = getIdentitySequence(RelationGetRelid(relation), attribute->attnum, false);
    1073           4 :             seq_options = sequence_options(seq_relid);
    1074           4 :             generateSerialExtraStmts(cxt, def,
    1075             :                                      InvalidOid, seq_options,
    1076             :                                      true, false,
    1077             :                                      NULL, NULL);
    1078           4 :             def->identity = attribute->attidentity;
    1079             :         }
    1080             : 
    1081             :         /* Likewise, copy storage if requested */
    1082         880 :         if (table_like_clause->options & CREATE_TABLE_LIKE_STORAGE)
    1083          92 :             def->storage = attribute->attstorage;
    1084             :         else
    1085         788 :             def->storage = 0;
    1086             : 
    1087             :         /* Likewise, copy compression if requested */
    1088         880 :         if ((table_like_clause->options & CREATE_TABLE_LIKE_COMPRESSION) != 0
    1089          56 :             && CompressionMethodIsValid(attribute->attcompression))
    1090           4 :             def->compression =
    1091           4 :                 pstrdup(GetCompressionMethodName(attribute->attcompression));
    1092             :         else
    1093         876 :             def->compression = NULL;
    1094             : 
    1095             :         /* Likewise, copy comment if requested */
    1096         960 :         if ((table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS) &&
    1097          80 :             (comment = GetComment(attribute->attrelid,
    1098             :                                   RelationRelationId,
    1099          80 :                                   attribute->attnum)) != NULL)
    1100             :         {
    1101          52 :             CommentStmt *stmt = makeNode(CommentStmt);
    1102             : 
    1103          52 :             stmt->objtype = OBJECT_COLUMN;
    1104          52 :             stmt->object = (Node *) list_make3(makeString(cxt->relation->schemaname),
    1105             :                                                makeString(cxt->relation->relname),
    1106             :                                                makeString(def->colname));
    1107          52 :             stmt->comment = comment;
    1108             : 
    1109          52 :             cxt->alist = lappend(cxt->alist, stmt);
    1110             :         }
    1111             :     }
    1112             : 
    1113             :     /*
    1114             :      * We cannot yet deal with defaults, CHECK constraints, or indexes, since
    1115             :      * we don't yet know what column numbers the copied columns will have in
    1116             :      * the finished table.  If any of those options are specified, add the
    1117             :      * LIKE clause to cxt->likeclauses so that expandTableLikeClause will be
    1118             :      * called after we do know that.  Also, remember the relation OID so that
    1119             :      * expandTableLikeClause is certain to open the same table.
    1120             :      */
    1121         442 :     if (table_like_clause->options &
    1122             :         (CREATE_TABLE_LIKE_DEFAULTS |
    1123             :          CREATE_TABLE_LIKE_GENERATED |
    1124             :          CREATE_TABLE_LIKE_CONSTRAINTS |
    1125             :          CREATE_TABLE_LIKE_INDEXES))
    1126             :     {
    1127         106 :         table_like_clause->relationOid = RelationGetRelid(relation);
    1128         106 :         cxt->likeclauses = lappend(cxt->likeclauses, table_like_clause);
    1129             :     }
    1130             : 
    1131             :     /*
    1132             :      * We may copy extended statistics if requested, since the representation
    1133             :      * of CreateStatsStmt doesn't depend on column numbers.
    1134             :      */
    1135         442 :     if (table_like_clause->options & CREATE_TABLE_LIKE_STATISTICS)
    1136             :     {
    1137             :         List       *parent_extstats;
    1138             :         ListCell   *l;
    1139             : 
    1140          28 :         parent_extstats = RelationGetStatExtList(relation);
    1141             : 
    1142          52 :         foreach(l, parent_extstats)
    1143             :         {
    1144          24 :             Oid         parent_stat_oid = lfirst_oid(l);
    1145             :             CreateStatsStmt *stats_stmt;
    1146             : 
    1147          24 :             stats_stmt = generateClonedExtStatsStmt(cxt->relation,
    1148             :                                                     RelationGetRelid(relation),
    1149             :                                                     parent_stat_oid);
    1150             : 
    1151             :             /* Copy comment on statistics object, if requested */
    1152          24 :             if (table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS)
    1153             :             {
    1154          24 :                 comment = GetComment(parent_stat_oid, StatisticExtRelationId, 0);
    1155             : 
    1156             :                 /*
    1157             :                  * We make use of CreateStatsStmt's stxcomment option, so as
    1158             :                  * not to need to know now what name the statistics will have.
    1159             :                  */
    1160          24 :                 stats_stmt->stxcomment = comment;
    1161             :             }
    1162             : 
    1163          24 :             cxt->extstats = lappend(cxt->extstats, stats_stmt);
    1164             :         }
    1165             : 
    1166          28 :         list_free(parent_extstats);
    1167             :     }
    1168             : 
    1169             :     /*
    1170             :      * Close the parent rel, but keep our AccessShareLock on it until xact
    1171             :      * commit.  That will prevent someone else from deleting or ALTERing the
    1172             :      * parent before we can run expandTableLikeClause.
    1173             :      */
    1174         442 :     table_close(relation, NoLock);
    1175         442 : }
    1176             : 
    1177             : /*
    1178             :  * expandTableLikeClause
    1179             :  *
    1180             :  * Process LIKE options that require knowing the final column numbers
    1181             :  * assigned to the new table's columns.  This executes after we have
    1182             :  * run DefineRelation for the new table.  It returns a list of utility
    1183             :  * commands that should be run to generate indexes etc.
    1184             :  */
    1185             : List *
    1186         106 : expandTableLikeClause(RangeVar *heapRel, TableLikeClause *table_like_clause)
    1187             : {
    1188         106 :     List       *result = NIL;
    1189         106 :     List       *atsubcmds = NIL;
    1190             :     AttrNumber  parent_attno;
    1191             :     Relation    relation;
    1192             :     Relation    childrel;
    1193             :     TupleDesc   tupleDesc;
    1194             :     TupleConstr *constr;
    1195             :     AttrMap    *attmap;
    1196             :     char       *comment;
    1197             : 
    1198             :     /*
    1199             :      * Open the relation referenced by the LIKE clause.  We should still have
    1200             :      * the table lock obtained by transformTableLikeClause (and this'll throw
    1201             :      * an assertion failure if not).  Hence, no need to recheck privileges
    1202             :      * etc.  We must open the rel by OID not name, to be sure we get the same
    1203             :      * table.
    1204             :      */
    1205         106 :     if (!OidIsValid(table_like_clause->relationOid))
    1206           0 :         elog(ERROR, "expandTableLikeClause called on untransformed LIKE clause");
    1207             : 
    1208         106 :     relation = relation_open(table_like_clause->relationOid, NoLock);
    1209             : 
    1210         106 :     tupleDesc = RelationGetDescr(relation);
    1211         106 :     constr = tupleDesc->constr;
    1212             : 
    1213             :     /*
    1214             :      * Open the newly-created child relation; we have lock on that too.
    1215             :      */
    1216         106 :     childrel = relation_openrv(heapRel, NoLock);
    1217             : 
    1218             :     /*
    1219             :      * Construct a map from the LIKE relation's attnos to the child rel's.
    1220             :      * This re-checks type match etc, although it shouldn't be possible to
    1221             :      * have a failure since both tables are locked.
    1222             :      */
    1223         106 :     attmap = build_attrmap_by_name(RelationGetDescr(childrel),
    1224             :                                    tupleDesc);
    1225             : 
    1226             :     /*
    1227             :      * Process defaults, if required.
    1228             :      */
    1229         106 :     if ((table_like_clause->options &
    1230          54 :          (CREATE_TABLE_LIKE_DEFAULTS | CREATE_TABLE_LIKE_GENERATED)) &&
    1231             :         constr != NULL)
    1232             :     {
    1233         170 :         for (parent_attno = 1; parent_attno <= tupleDesc->natts;
    1234         120 :              parent_attno++)
    1235             :         {
    1236         120 :             Form_pg_attribute attribute = TupleDescAttr(tupleDesc,
    1237             :                                                         parent_attno - 1);
    1238             : 
    1239             :             /*
    1240             :              * Ignore dropped columns in the parent.
    1241             :              */
    1242         120 :             if (attribute->attisdropped)
    1243           4 :                 continue;
    1244             : 
    1245             :             /*
    1246             :              * Copy default, if present and it should be copied.  We have
    1247             :              * separate options for plain default expressions and GENERATED
    1248             :              * defaults.
    1249             :              */
    1250         162 :             if (attribute->atthasdef &&
    1251          46 :                 (attribute->attgenerated ?
    1252          24 :                  (table_like_clause->options & CREATE_TABLE_LIKE_GENERATED) :
    1253          22 :                  (table_like_clause->options & CREATE_TABLE_LIKE_DEFAULTS)))
    1254             :             {
    1255          38 :                 Node       *this_default = NULL;
    1256          38 :                 AttrDefault *attrdef = constr->defval;
    1257             :                 AlterTableCmd *atsubcmd;
    1258             :                 bool        found_whole_row;
    1259             : 
    1260             :                 /* Find default in constraint structure */
    1261          50 :                 for (int i = 0; i < constr->num_defval; i++)
    1262             :                 {
    1263          50 :                     if (attrdef[i].adnum == parent_attno)
    1264             :                     {
    1265          38 :                         this_default = stringToNode(attrdef[i].adbin);
    1266          38 :                         break;
    1267             :                     }
    1268             :                 }
    1269          38 :                 if (this_default == NULL)
    1270           0 :                     elog(ERROR, "default expression not found for attribute %d of relation \"%s\"",
    1271             :                          parent_attno, RelationGetRelationName(relation));
    1272             : 
    1273          38 :                 atsubcmd = makeNode(AlterTableCmd);
    1274          38 :                 atsubcmd->subtype = AT_CookedColumnDefault;
    1275          38 :                 atsubcmd->num = attmap->attnums[parent_attno - 1];
    1276          38 :                 atsubcmd->def = map_variable_attnos(this_default,
    1277             :                                                     1, 0,
    1278             :                                                     attmap,
    1279             :                                                     InvalidOid,
    1280             :                                                     &found_whole_row);
    1281             : 
    1282             :                 /*
    1283             :                  * Prevent this for the same reason as for constraints below.
    1284             :                  * Note that defaults cannot contain any vars, so it's OK that
    1285             :                  * the error message refers to generated columns.
    1286             :                  */
    1287          38 :                 if (found_whole_row)
    1288           0 :                     ereport(ERROR,
    1289             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1290             :                              errmsg("cannot convert whole-row table reference"),
    1291             :                              errdetail("Generation expression for column \"%s\" contains a whole-row reference to table \"%s\".",
    1292             :                                        NameStr(attribute->attname),
    1293             :                                        RelationGetRelationName(relation))));
    1294             : 
    1295          38 :                 atsubcmds = lappend(atsubcmds, atsubcmd);
    1296             :             }
    1297             :         }
    1298             :     }
    1299             : 
    1300             :     /*
    1301             :      * Copy CHECK constraints if requested, being careful to adjust attribute
    1302             :      * numbers so they match the child.
    1303             :      */
    1304         106 :     if ((table_like_clause->options & CREATE_TABLE_LIKE_CONSTRAINTS) &&
    1305             :         constr != NULL)
    1306             :     {
    1307             :         int         ccnum;
    1308             : 
    1309         124 :         for (ccnum = 0; ccnum < constr->num_check; ccnum++)
    1310             :         {
    1311          64 :             char       *ccname = constr->check[ccnum].ccname;
    1312          64 :             char       *ccbin = constr->check[ccnum].ccbin;
    1313          64 :             bool        ccnoinherit = constr->check[ccnum].ccnoinherit;
    1314             :             Node       *ccbin_node;
    1315             :             bool        found_whole_row;
    1316             :             Constraint *n;
    1317             :             AlterTableCmd *atsubcmd;
    1318             : 
    1319          64 :             ccbin_node = map_variable_attnos(stringToNode(ccbin),
    1320             :                                              1, 0,
    1321             :                                              attmap,
    1322             :                                              InvalidOid, &found_whole_row);
    1323             : 
    1324             :             /*
    1325             :              * We reject whole-row variables because the whole point of LIKE
    1326             :              * is that the new table's rowtype might later diverge from the
    1327             :              * parent's.  So, while translation might be possible right now,
    1328             :              * it wouldn't be possible to guarantee it would work in future.
    1329             :              */
    1330          64 :             if (found_whole_row)
    1331           0 :                 ereport(ERROR,
    1332             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1333             :                          errmsg("cannot convert whole-row table reference"),
    1334             :                          errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
    1335             :                                    ccname,
    1336             :                                    RelationGetRelationName(relation))));
    1337             : 
    1338          64 :             n = makeNode(Constraint);
    1339          64 :             n->contype = CONSTR_CHECK;
    1340          64 :             n->conname = pstrdup(ccname);
    1341          64 :             n->location = -1;
    1342          64 :             n->is_no_inherit = ccnoinherit;
    1343          64 :             n->raw_expr = NULL;
    1344          64 :             n->cooked_expr = nodeToString(ccbin_node);
    1345             : 
    1346             :             /* We can skip validation, since the new table should be empty. */
    1347          64 :             n->skip_validation = true;
    1348          64 :             n->initially_valid = true;
    1349             : 
    1350          64 :             atsubcmd = makeNode(AlterTableCmd);
    1351          64 :             atsubcmd->subtype = AT_AddConstraint;
    1352          64 :             atsubcmd->def = (Node *) n;
    1353          64 :             atsubcmds = lappend(atsubcmds, atsubcmd);
    1354             : 
    1355             :             /* Copy comment on constraint */
    1356         100 :             if ((table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS) &&
    1357          36 :                 (comment = GetComment(get_relation_constraint_oid(RelationGetRelid(relation),
    1358          36 :                                                                   n->conname, false),
    1359             :                                       ConstraintRelationId,
    1360             :                                       0)) != NULL)
    1361             :             {
    1362          20 :                 CommentStmt *stmt = makeNode(CommentStmt);
    1363             : 
    1364          20 :                 stmt->objtype = OBJECT_TABCONSTRAINT;
    1365          20 :                 stmt->object = (Node *) list_make3(makeString(heapRel->schemaname),
    1366             :                                                    makeString(heapRel->relname),
    1367             :                                                    makeString(n->conname));
    1368          20 :                 stmt->comment = comment;
    1369             : 
    1370          20 :                 result = lappend(result, stmt);
    1371             :             }
    1372             :         }
    1373             :     }
    1374             : 
    1375             :     /*
    1376             :      * If we generated any ALTER TABLE actions above, wrap them into a single
    1377             :      * ALTER TABLE command.  Stick it at the front of the result, so it runs
    1378             :      * before any CommentStmts we made above.
    1379             :      */
    1380         106 :     if (atsubcmds)
    1381             :     {
    1382          82 :         AlterTableStmt *atcmd = makeNode(AlterTableStmt);
    1383             : 
    1384          82 :         atcmd->relation = copyObject(heapRel);
    1385          82 :         atcmd->cmds = atsubcmds;
    1386          82 :         atcmd->objtype = OBJECT_TABLE;
    1387          82 :         atcmd->missing_ok = false;
    1388          82 :         result = lcons(atcmd, result);
    1389             :     }
    1390             : 
    1391             :     /*
    1392             :      * Process indexes if required.
    1393             :      */
    1394         106 :     if ((table_like_clause->options & CREATE_TABLE_LIKE_INDEXES) &&
    1395          54 :         relation->rd_rel->relhasindex)
    1396             :     {
    1397             :         List       *parent_indexes;
    1398             :         ListCell   *l;
    1399             : 
    1400          42 :         parent_indexes = RelationGetIndexList(relation);
    1401             : 
    1402         118 :         foreach(l, parent_indexes)
    1403             :         {
    1404          76 :             Oid         parent_index_oid = lfirst_oid(l);
    1405             :             Relation    parent_index;
    1406             :             IndexStmt  *index_stmt;
    1407             : 
    1408          76 :             parent_index = index_open(parent_index_oid, AccessShareLock);
    1409             : 
    1410             :             /* Build CREATE INDEX statement to recreate the parent_index */
    1411          76 :             index_stmt = generateClonedIndexStmt(heapRel,
    1412             :                                                  parent_index,
    1413             :                                                  attmap,
    1414             :                                                  NULL);
    1415             : 
    1416             :             /* Copy comment on index, if requested */
    1417          76 :             if (table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS)
    1418             :             {
    1419          44 :                 comment = GetComment(parent_index_oid, RelationRelationId, 0);
    1420             : 
    1421             :                 /*
    1422             :                  * We make use of IndexStmt's idxcomment option, so as not to
    1423             :                  * need to know now what name the index will have.
    1424             :                  */
    1425          44 :                 index_stmt->idxcomment = comment;
    1426             :             }
    1427             : 
    1428          76 :             result = lappend(result, index_stmt);
    1429             : 
    1430          76 :             index_close(parent_index, AccessShareLock);
    1431             :         }
    1432             :     }
    1433             : 
    1434             :     /* Done with child rel */
    1435         106 :     table_close(childrel, NoLock);
    1436             : 
    1437             :     /*
    1438             :      * Close the parent rel, but keep our AccessShareLock on it until xact
    1439             :      * commit.  That will prevent someone else from deleting or ALTERing the
    1440             :      * parent before the child is committed.
    1441             :      */
    1442         106 :     table_close(relation, NoLock);
    1443             : 
    1444         106 :     return result;
    1445             : }
    1446             : 
    1447             : static void
    1448          74 : transformOfType(CreateStmtContext *cxt, TypeName *ofTypename)
    1449             : {
    1450             :     HeapTuple   tuple;
    1451             :     TupleDesc   tupdesc;
    1452             :     int         i;
    1453             :     Oid         ofTypeId;
    1454             : 
    1455             :     AssertArg(ofTypename);
    1456             : 
    1457          74 :     tuple = typenameType(NULL, ofTypename, NULL);
    1458          70 :     check_of_type(tuple);
    1459          66 :     ofTypeId = ((Form_pg_type) GETSTRUCT(tuple))->oid;
    1460          66 :     ofTypename->typeOid = ofTypeId; /* cached for later */
    1461             : 
    1462          66 :     tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
    1463         194 :     for (i = 0; i < tupdesc->natts; i++)
    1464             :     {
    1465         128 :         Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
    1466             :         ColumnDef  *n;
    1467             : 
    1468         128 :         if (attr->attisdropped)
    1469           0 :             continue;
    1470             : 
    1471         128 :         n = makeNode(ColumnDef);
    1472         128 :         n->colname = pstrdup(NameStr(attr->attname));
    1473         128 :         n->typeName = makeTypeNameFromOid(attr->atttypid, attr->atttypmod);
    1474         128 :         n->inhcount = 0;
    1475         128 :         n->is_local = true;
    1476         128 :         n->is_not_null = false;
    1477         128 :         n->is_from_type = true;
    1478         128 :         n->storage = 0;
    1479         128 :         n->raw_default = NULL;
    1480         128 :         n->cooked_default = NULL;
    1481         128 :         n->collClause = NULL;
    1482         128 :         n->collOid = attr->attcollation;
    1483         128 :         n->constraints = NIL;
    1484         128 :         n->location = -1;
    1485         128 :         cxt->columns = lappend(cxt->columns, n);
    1486             :     }
    1487          66 :     DecrTupleDescRefCount(tupdesc);
    1488             : 
    1489          66 :     ReleaseSysCache(tuple);
    1490          66 : }
    1491             : 
    1492             : /*
    1493             :  * Generate an IndexStmt node using information from an already existing index
    1494             :  * "source_idx".
    1495             :  *
    1496             :  * heapRel is stored into the IndexStmt's relation field, but we don't use it
    1497             :  * otherwise; some callers pass NULL, if they don't need it to be valid.
    1498             :  * (The target relation might not exist yet, so we mustn't try to access it.)
    1499             :  *
    1500             :  * Attribute numbers in expression Vars are adjusted according to attmap.
    1501             :  *
    1502             :  * If constraintOid isn't NULL, we store the OID of any constraint associated
    1503             :  * with the index there.
    1504             :  *
    1505             :  * Unlike transformIndexConstraint, we don't make any effort to force primary
    1506             :  * key columns to be NOT NULL.  The larger cloning process this is part of
    1507             :  * should have cloned their NOT NULL status separately (and DefineIndex will
    1508             :  * complain if that fails to happen).
    1509             :  */
    1510             : IndexStmt *
    1511         898 : generateClonedIndexStmt(RangeVar *heapRel, Relation source_idx,
    1512             :                         const AttrMap *attmap,
    1513             :                         Oid *constraintOid)
    1514             : {
    1515         898 :     Oid         source_relid = RelationGetRelid(source_idx);
    1516             :     HeapTuple   ht_idxrel;
    1517             :     HeapTuple   ht_idx;
    1518             :     HeapTuple   ht_am;
    1519             :     Form_pg_class idxrelrec;
    1520             :     Form_pg_index idxrec;
    1521             :     Form_pg_am  amrec;
    1522             :     oidvector  *indcollation;
    1523             :     oidvector  *indclass;
    1524             :     IndexStmt  *index;
    1525             :     List       *indexprs;
    1526             :     ListCell   *indexpr_item;
    1527             :     Oid         indrelid;
    1528             :     int         keyno;
    1529             :     Oid         keycoltype;
    1530             :     Datum       datum;
    1531             :     bool        isnull;
    1532             : 
    1533         898 :     if (constraintOid)
    1534         822 :         *constraintOid = InvalidOid;
    1535             : 
    1536             :     /*
    1537             :      * Fetch pg_class tuple of source index.  We can't use the copy in the
    1538             :      * relcache entry because it doesn't include optional fields.
    1539             :      */
    1540         898 :     ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(source_relid));
    1541         898 :     if (!HeapTupleIsValid(ht_idxrel))
    1542           0 :         elog(ERROR, "cache lookup failed for relation %u", source_relid);
    1543         898 :     idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
    1544             : 
    1545             :     /* Fetch pg_index tuple for source index from relcache entry */
    1546         898 :     ht_idx = source_idx->rd_indextuple;
    1547         898 :     idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
    1548         898 :     indrelid = idxrec->indrelid;
    1549             : 
    1550             :     /* Fetch the pg_am tuple of the index' access method */
    1551         898 :     ht_am = SearchSysCache1(AMOID, ObjectIdGetDatum(idxrelrec->relam));
    1552         898 :     if (!HeapTupleIsValid(ht_am))
    1553           0 :         elog(ERROR, "cache lookup failed for access method %u",
    1554             :              idxrelrec->relam);
    1555         898 :     amrec = (Form_pg_am) GETSTRUCT(ht_am);
    1556             : 
    1557             :     /* Extract indcollation from the pg_index tuple */
    1558         898 :     datum = SysCacheGetAttr(INDEXRELID, ht_idx,
    1559             :                             Anum_pg_index_indcollation, &isnull);
    1560             :     Assert(!isnull);
    1561         898 :     indcollation = (oidvector *) DatumGetPointer(datum);
    1562             : 
    1563             :     /* Extract indclass from the pg_index tuple */
    1564         898 :     datum = SysCacheGetAttr(INDEXRELID, ht_idx,
    1565             :                             Anum_pg_index_indclass, &isnull);
    1566             :     Assert(!isnull);
    1567         898 :     indclass = (oidvector *) DatumGetPointer(datum);
    1568             : 
    1569             :     /* Begin building the IndexStmt */
    1570         898 :     index = makeNode(IndexStmt);
    1571         898 :     index->relation = heapRel;
    1572         898 :     index->accessMethod = pstrdup(NameStr(amrec->amname));
    1573         898 :     if (OidIsValid(idxrelrec->reltablespace))
    1574           4 :         index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
    1575             :     else
    1576         894 :         index->tableSpace = NULL;
    1577         898 :     index->excludeOpNames = NIL;
    1578         898 :     index->idxcomment = NULL;
    1579         898 :     index->indexOid = InvalidOid;
    1580         898 :     index->oldNode = InvalidOid;
    1581         898 :     index->oldCreateSubid = InvalidSubTransactionId;
    1582         898 :     index->oldFirstRelfilenodeSubid = InvalidSubTransactionId;
    1583         898 :     index->unique = idxrec->indisunique;
    1584         898 :     index->primary = idxrec->indisprimary;
    1585         898 :     index->transformed = true;   /* don't need transformIndexStmt */
    1586         898 :     index->concurrent = false;
    1587         898 :     index->if_not_exists = false;
    1588         898 :     index->reset_default_tblspc = false;
    1589             : 
    1590             :     /*
    1591             :      * We don't try to preserve the name of the source index; instead, just
    1592             :      * let DefineIndex() choose a reasonable name.  (If we tried to preserve
    1593             :      * the name, we'd get duplicate-relation-name failures unless the source
    1594             :      * table was in a different schema.)
    1595             :      */
    1596         898 :     index->idxname = NULL;
    1597             : 
    1598             :     /*
    1599             :      * If the index is marked PRIMARY or has an exclusion condition, it's
    1600             :      * certainly from a constraint; else, if it's not marked UNIQUE, it
    1601             :      * certainly isn't.  If it is or might be from a constraint, we have to
    1602             :      * fetch the pg_constraint record.
    1603             :      */
    1604         898 :     if (index->primary || index->unique || idxrec->indisexclusion)
    1605         664 :     {
    1606         664 :         Oid         constraintId = get_index_constraint(source_relid);
    1607             : 
    1608         664 :         if (OidIsValid(constraintId))
    1609             :         {
    1610             :             HeapTuple   ht_constr;
    1611             :             Form_pg_constraint conrec;
    1612             : 
    1613         640 :             if (constraintOid)
    1614         604 :                 *constraintOid = constraintId;
    1615             : 
    1616         640 :             ht_constr = SearchSysCache1(CONSTROID,
    1617             :                                         ObjectIdGetDatum(constraintId));
    1618         640 :             if (!HeapTupleIsValid(ht_constr))
    1619           0 :                 elog(ERROR, "cache lookup failed for constraint %u",
    1620             :                      constraintId);
    1621         640 :             conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
    1622             : 
    1623         640 :             index->isconstraint = true;
    1624         640 :             index->deferrable = conrec->condeferrable;
    1625         640 :             index->initdeferred = conrec->condeferred;
    1626             : 
    1627             :             /* If it's an exclusion constraint, we need the operator names */
    1628         640 :             if (idxrec->indisexclusion)
    1629             :             {
    1630             :                 Datum      *elems;
    1631             :                 int         nElems;
    1632             :                 int         i;
    1633             : 
    1634             :                 Assert(conrec->contype == CONSTRAINT_EXCLUSION);
    1635             :                 /* Extract operator OIDs from the pg_constraint tuple */
    1636           2 :                 datum = SysCacheGetAttr(CONSTROID, ht_constr,
    1637             :                                         Anum_pg_constraint_conexclop,
    1638             :                                         &isnull);
    1639           2 :                 if (isnull)
    1640           0 :                     elog(ERROR, "null conexclop for constraint %u",
    1641             :                          constraintId);
    1642             : 
    1643           2 :                 deconstruct_array(DatumGetArrayTypeP(datum),
    1644             :                                   OIDOID, sizeof(Oid), true, TYPALIGN_INT,
    1645             :                                   &elems, NULL, &nElems);
    1646             : 
    1647           4 :                 for (i = 0; i < nElems; i++)
    1648             :                 {
    1649           2 :                     Oid         operid = DatumGetObjectId(elems[i]);
    1650             :                     HeapTuple   opertup;
    1651             :                     Form_pg_operator operform;
    1652             :                     char       *oprname;
    1653             :                     char       *nspname;
    1654             :                     List       *namelist;
    1655             : 
    1656           2 :                     opertup = SearchSysCache1(OPEROID,
    1657             :                                               ObjectIdGetDatum(operid));
    1658           2 :                     if (!HeapTupleIsValid(opertup))
    1659           0 :                         elog(ERROR, "cache lookup failed for operator %u",
    1660             :                              operid);
    1661           2 :                     operform = (Form_pg_operator) GETSTRUCT(opertup);
    1662           2 :                     oprname = pstrdup(NameStr(operform->oprname));
    1663             :                     /* For simplicity we always schema-qualify the op name */
    1664           2 :                     nspname = get_namespace_name(operform->oprnamespace);
    1665           2 :                     namelist = list_make2(makeString(nspname),
    1666             :                                           makeString(oprname));
    1667           2 :                     index->excludeOpNames = lappend(index->excludeOpNames,
    1668             :                                                     namelist);
    1669           2 :                     ReleaseSysCache(opertup);
    1670             :                 }
    1671             :             }
    1672             : 
    1673         640 :             ReleaseSysCache(ht_constr);
    1674             :         }
    1675             :         else
    1676          24 :             index->isconstraint = false;
    1677             :     }
    1678             :     else
    1679         234 :         index->isconstraint = false;
    1680             : 
    1681             :     /* Get the index expressions, if any */
    1682         898 :     datum = SysCacheGetAttr(INDEXRELID, ht_idx,
    1683             :                             Anum_pg_index_indexprs, &isnull);
    1684         898 :     if (!isnull)
    1685             :     {
    1686             :         char       *exprsString;
    1687             : 
    1688          52 :         exprsString = TextDatumGetCString(datum);
    1689          52 :         indexprs = (List *) stringToNode(exprsString);
    1690             :     }
    1691             :     else
    1692         846 :         indexprs = NIL;
    1693             : 
    1694             :     /* Build the list of IndexElem */
    1695         898 :     index->indexParams = NIL;
    1696         898 :     index->indexIncludingParams = NIL;
    1697             : 
    1698         898 :     indexpr_item = list_head(indexprs);
    1699        1922 :     for (keyno = 0; keyno < idxrec->indnkeyatts; keyno++)
    1700             :     {
    1701             :         IndexElem  *iparam;
    1702        1024 :         AttrNumber  attnum = idxrec->indkey.values[keyno];
    1703        1024 :         Form_pg_attribute attr = TupleDescAttr(RelationGetDescr(source_idx),
    1704             :                                                keyno);
    1705        1024 :         int16       opt = source_idx->rd_indoption[keyno];
    1706             : 
    1707        1024 :         iparam = makeNode(IndexElem);
    1708             : 
    1709        1024 :         if (AttributeNumberIsValid(attnum))
    1710             :         {
    1711             :             /* Simple index column */
    1712             :             char       *attname;
    1713             : 
    1714         972 :             attname = get_attname(indrelid, attnum, false);
    1715         972 :             keycoltype = get_atttype(indrelid, attnum);
    1716             : 
    1717         972 :             iparam->name = attname;
    1718         972 :             iparam->expr = NULL;
    1719             :         }
    1720             :         else
    1721             :         {
    1722             :             /* Expressional index */
    1723             :             Node       *indexkey;
    1724             :             bool        found_whole_row;
    1725             : 
    1726          52 :             if (indexpr_item == NULL)
    1727           0 :                 elog(ERROR, "too few entries in indexprs list");
    1728          52 :             indexkey = (Node *) lfirst(indexpr_item);
    1729          52 :             indexpr_item = lnext(indexprs, indexpr_item);
    1730             : 
    1731             :             /* Adjust Vars to match new table's column numbering */
    1732          52 :             indexkey = map_variable_attnos(indexkey,
    1733             :                                            1, 0,
    1734             :                                            attmap,
    1735             :                                            InvalidOid, &found_whole_row);
    1736             : 
    1737             :             /* As in expandTableLikeClause, reject whole-row variables */
    1738          52 :             if (found_whole_row)
    1739           0 :                 ereport(ERROR,
    1740             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1741             :                          errmsg("cannot convert whole-row table reference"),
    1742             :                          errdetail("Index \"%s\" contains a whole-row table reference.",
    1743             :                                    RelationGetRelationName(source_idx))));
    1744             : 
    1745          52 :             iparam->name = NULL;
    1746          52 :             iparam->expr = indexkey;
    1747             : 
    1748          52 :             keycoltype = exprType(indexkey);
    1749             :         }
    1750             : 
    1751             :         /* Copy the original index column name */
    1752        1024 :         iparam->indexcolname = pstrdup(NameStr(attr->attname));
    1753             : 
    1754             :         /* Add the collation name, if non-default */
    1755        1024 :         iparam->collation = get_collation(indcollation->values[keyno], keycoltype);
    1756             : 
    1757             :         /* Add the operator class name, if non-default */
    1758        1024 :         iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
    1759        1024 :         iparam->opclassopts =
    1760        1024 :             untransformRelOptions(get_attoptions(source_relid, keyno + 1));
    1761             : 
    1762        1024 :         iparam->ordering = SORTBY_DEFAULT;
    1763        1024 :         iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
    1764             : 
    1765             :         /* Adjust options if necessary */
    1766        1024 :         if (source_idx->rd_indam->amcanorder)
    1767             :         {
    1768             :             /*
    1769             :              * If it supports sort ordering, copy DESC and NULLS opts. Don't
    1770             :              * set non-default settings unnecessarily, though, so as to
    1771             :              * improve the chance of recognizing equivalence to constraint
    1772             :              * indexes.
    1773             :              */
    1774        1024 :             if (opt & INDOPTION_DESC)
    1775             :             {
    1776           0 :                 iparam->ordering = SORTBY_DESC;
    1777           0 :                 if ((opt & INDOPTION_NULLS_FIRST) == 0)
    1778           0 :                     iparam->nulls_ordering = SORTBY_NULLS_LAST;
    1779             :             }
    1780             :             else
    1781             :             {
    1782        1024 :                 if (opt & INDOPTION_NULLS_FIRST)
    1783           0 :                     iparam->nulls_ordering = SORTBY_NULLS_FIRST;
    1784             :             }
    1785             :         }
    1786             : 
    1787        1024 :         index->indexParams = lappend(index->indexParams, iparam);
    1788             :     }
    1789             : 
    1790             :     /* Handle included columns separately */
    1791         910 :     for (keyno = idxrec->indnkeyatts; keyno < idxrec->indnatts; keyno++)
    1792             :     {
    1793             :         IndexElem  *iparam;
    1794          12 :         AttrNumber  attnum = idxrec->indkey.values[keyno];
    1795          12 :         Form_pg_attribute attr = TupleDescAttr(RelationGetDescr(source_idx),
    1796             :                                                keyno);
    1797             : 
    1798          12 :         iparam = makeNode(IndexElem);
    1799             : 
    1800          12 :         if (AttributeNumberIsValid(attnum))
    1801             :         {
    1802             :             /* Simple index column */
    1803             :             char       *attname;
    1804             : 
    1805          12 :             attname = get_attname(indrelid, attnum, false);
    1806             : 
    1807          12 :             iparam->name = attname;
    1808          12 :             iparam->expr = NULL;
    1809             :         }
    1810             :         else
    1811           0 :             ereport(ERROR,
    1812             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1813             :                      errmsg("expressions are not supported in included columns")));
    1814             : 
    1815             :         /* Copy the original index column name */
    1816          12 :         iparam->indexcolname = pstrdup(NameStr(attr->attname));
    1817             : 
    1818          12 :         index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
    1819             :     }
    1820             :     /* Copy reloptions if any */
    1821         898 :     datum = SysCacheGetAttr(RELOID, ht_idxrel,
    1822             :                             Anum_pg_class_reloptions, &isnull);
    1823         898 :     if (!isnull)
    1824           0 :         index->options = untransformRelOptions(datum);
    1825             : 
    1826             :     /* If it's a partial index, decompile and append the predicate */
    1827         898 :     datum = SysCacheGetAttr(INDEXRELID, ht_idx,
    1828             :                             Anum_pg_index_indpred, &isnull);
    1829         898 :     if (!isnull)
    1830             :     {
    1831             :         char       *pred_str;
    1832             :         Node       *pred_tree;
    1833             :         bool        found_whole_row;
    1834             : 
    1835             :         /* Convert text string to node tree */
    1836          12 :         pred_str = TextDatumGetCString(datum);
    1837          12 :         pred_tree = (Node *) stringToNode(pred_str);
    1838             : 
    1839             :         /* Adjust Vars to match new table's column numbering */
    1840          12 :         pred_tree = map_variable_attnos(pred_tree,
    1841             :                                         1, 0,
    1842             :                                         attmap,
    1843             :                                         InvalidOid, &found_whole_row);
    1844             : 
    1845             :         /* As in expandTableLikeClause, reject whole-row variables */
    1846          12 :         if (found_whole_row)
    1847           0 :             ereport(ERROR,
    1848             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1849             :                      errmsg("cannot convert whole-row table reference"),
    1850             :                      errdetail("Index \"%s\" contains a whole-row table reference.",
    1851             :                                RelationGetRelationName(source_idx))));
    1852             : 
    1853          12 :         index->whereClause = pred_tree;
    1854             :     }
    1855             : 
    1856             :     /* Clean up */
    1857         898 :     ReleaseSysCache(ht_idxrel);
    1858         898 :     ReleaseSysCache(ht_am);
    1859             : 
    1860         898 :     return index;
    1861             : }
    1862             : 
    1863             : /*
    1864             :  * Generate a CreateStatsStmt node using information from an already existing
    1865             :  * extended statistic "source_statsid", for the rel identified by heapRel and
    1866             :  * heapRelid.
    1867             :  */
    1868             : static CreateStatsStmt *
    1869          24 : generateClonedExtStatsStmt(RangeVar *heapRel, Oid heapRelid,
    1870             :                            Oid source_statsid)
    1871             : {
    1872             :     HeapTuple   ht_stats;
    1873             :     Form_pg_statistic_ext statsrec;
    1874             :     CreateStatsStmt *stats;
    1875          24 :     List       *stat_types = NIL;
    1876          24 :     List       *def_names = NIL;
    1877             :     bool        isnull;
    1878             :     Datum       datum;
    1879             :     ArrayType  *arr;
    1880             :     char       *enabled;
    1881             :     int         i;
    1882             : 
    1883             :     Assert(OidIsValid(heapRelid));
    1884             :     Assert(heapRel != NULL);
    1885             : 
    1886             :     /*
    1887             :      * Fetch pg_statistic_ext tuple of source statistics object.
    1888             :      */
    1889          24 :     ht_stats = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(source_statsid));
    1890          24 :     if (!HeapTupleIsValid(ht_stats))
    1891           0 :         elog(ERROR, "cache lookup failed for statistics object %u", source_statsid);
    1892          24 :     statsrec = (Form_pg_statistic_ext) GETSTRUCT(ht_stats);
    1893             : 
    1894             :     /* Determine which statistics types exist */
    1895          24 :     datum = SysCacheGetAttr(STATEXTOID, ht_stats,
    1896             :                             Anum_pg_statistic_ext_stxkind, &isnull);
    1897             :     Assert(!isnull);
    1898          24 :     arr = DatumGetArrayTypeP(datum);
    1899          24 :     if (ARR_NDIM(arr) != 1 ||
    1900          24 :         ARR_HASNULL(arr) ||
    1901          24 :         ARR_ELEMTYPE(arr) != CHAROID)
    1902           0 :         elog(ERROR, "stxkind is not a 1-D char array");
    1903          24 :     enabled = (char *) ARR_DATA_PTR(arr);
    1904          72 :     for (i = 0; i < ARR_DIMS(arr)[0]; i++)
    1905             :     {
    1906          48 :         if (enabled[i] == STATS_EXT_NDISTINCT)
    1907          12 :             stat_types = lappend(stat_types, makeString("ndistinct"));
    1908          36 :         else if (enabled[i] == STATS_EXT_DEPENDENCIES)
    1909          12 :             stat_types = lappend(stat_types, makeString("dependencies"));
    1910          24 :         else if (enabled[i] == STATS_EXT_MCV)
    1911          12 :             stat_types = lappend(stat_types, makeString("mcv"));
    1912          12 :         else if (enabled[i] == STATS_EXT_EXPRESSIONS)
    1913             :             /* expression stats are not exposed to users */
    1914          12 :             continue;
    1915             :         else
    1916           0 :             elog(ERROR, "unrecognized statistics kind %c", enabled[i]);
    1917             :     }
    1918             : 
    1919             :     /* Determine which columns the statistics are on */
    1920          48 :     for (i = 0; i < statsrec->stxkeys.dim1; i++)
    1921             :     {
    1922          24 :         StatsElem  *selem = makeNode(StatsElem);
    1923          24 :         AttrNumber  attnum = statsrec->stxkeys.values[i];
    1924             : 
    1925          24 :         selem->name = get_attname(heapRelid, attnum, false);
    1926          24 :         selem->expr = NULL;
    1927             : 
    1928          24 :         def_names = lappend(def_names, selem);
    1929             :     }
    1930             : 
    1931             :     /*
    1932             :      * Now handle expressions, if there are any. The order (with respect to
    1933             :      * regular attributes) does not really matter for extended stats, so we
    1934             :      * simply append them after simple column references.
    1935             :      *
    1936             :      * XXX Some places during build/estimation treat expressions as if they
    1937             :      * are before attributes, but for the CREATE command that's entirely
    1938             :      * irrelevant.
    1939             :      */
    1940          24 :     datum = SysCacheGetAttr(STATEXTOID, ht_stats,
    1941             :                             Anum_pg_statistic_ext_stxexprs, &isnull);
    1942             : 
    1943          24 :     if (!isnull)
    1944             :     {
    1945             :         ListCell   *lc;
    1946          12 :         List       *exprs = NIL;
    1947             :         char       *exprsString;
    1948             : 
    1949          12 :         exprsString = TextDatumGetCString(datum);
    1950          12 :         exprs = (List *) stringToNode(exprsString);
    1951             : 
    1952          24 :         foreach(lc, exprs)
    1953             :         {
    1954          12 :             StatsElem  *selem = makeNode(StatsElem);
    1955             : 
    1956          12 :             selem->name = NULL;
    1957          12 :             selem->expr = (Node *) lfirst(lc);
    1958             : 
    1959          12 :             def_names = lappend(def_names, selem);
    1960             :         }
    1961             : 
    1962          12 :         pfree(exprsString);
    1963             :     }
    1964             : 
    1965             :     /* finally, build the output node */
    1966          24 :     stats = makeNode(CreateStatsStmt);
    1967          24 :     stats->defnames = NULL;
    1968          24 :     stats->stat_types = stat_types;
    1969          24 :     stats->exprs = def_names;
    1970          24 :     stats->relations = list_make1(heapRel);
    1971          24 :     stats->stxcomment = NULL;
    1972          24 :     stats->transformed = true;   /* don't need transformStatsStmt again */
    1973          24 :     stats->if_not_exists = false;
    1974             : 
    1975             :     /* Clean up */
    1976          24 :     ReleaseSysCache(ht_stats);
    1977             : 
    1978          24 :     return stats;
    1979             : }
    1980             : 
    1981             : /*
    1982             :  * get_collation        - fetch qualified name of a collation
    1983             :  *
    1984             :  * If collation is InvalidOid or is the default for the given actual_datatype,
    1985             :  * then the return value is NIL.
    1986             :  */
    1987             : static List *
    1988        1024 : get_collation(Oid collation, Oid actual_datatype)
    1989             : {
    1990             :     List       *result;
    1991             :     HeapTuple   ht_coll;
    1992             :     Form_pg_collation coll_rec;
    1993             :     char       *nsp_name;
    1994             :     char       *coll_name;
    1995             : 
    1996        1024 :     if (!OidIsValid(collation))
    1997         924 :         return NIL;             /* easy case */
    1998         100 :     if (collation == get_typcollation(actual_datatype))
    1999          96 :         return NIL;             /* just let it default */
    2000             : 
    2001           4 :     ht_coll = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
    2002           4 :     if (!HeapTupleIsValid(ht_coll))
    2003           0 :         elog(ERROR, "cache lookup failed for collation %u", collation);
    2004           4 :     coll_rec = (Form_pg_collation) GETSTRUCT(ht_coll);
    2005             : 
    2006             :     /* For simplicity, we always schema-qualify the name */
    2007           4 :     nsp_name = get_namespace_name(coll_rec->collnamespace);
    2008           4 :     coll_name = pstrdup(NameStr(coll_rec->collname));
    2009           4 :     result = list_make2(makeString(nsp_name), makeString(coll_name));
    2010             : 
    2011           4 :     ReleaseSysCache(ht_coll);
    2012           4 :     return result;
    2013             : }
    2014             : 
    2015             : /*
    2016             :  * get_opclass          - fetch qualified name of an index operator class
    2017             :  *
    2018             :  * If the opclass is the default for the given actual_datatype, then
    2019             :  * the return value is NIL.
    2020             :  */
    2021             : static List *
    2022        1024 : get_opclass(Oid opclass, Oid actual_datatype)
    2023             : {
    2024        1024 :     List       *result = NIL;
    2025             :     HeapTuple   ht_opc;
    2026             :     Form_pg_opclass opc_rec;
    2027             : 
    2028        1024 :     ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
    2029        1024 :     if (!HeapTupleIsValid(ht_opc))
    2030           0 :         elog(ERROR, "cache lookup failed for opclass %u", opclass);
    2031        1024 :     opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
    2032             : 
    2033        1024 :     if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
    2034             :     {
    2035             :         /* For simplicity, we always schema-qualify the name */
    2036           4 :         char       *nsp_name = get_namespace_name(opc_rec->opcnamespace);
    2037           4 :         char       *opc_name = pstrdup(NameStr(opc_rec->opcname));
    2038             : 
    2039           4 :         result = list_make2(makeString(nsp_name), makeString(opc_name));
    2040             :     }
    2041             : 
    2042        1024 :     ReleaseSysCache(ht_opc);
    2043        1024 :     return result;
    2044             : }
    2045             : 
    2046             : 
    2047             : /*
    2048             :  * transformIndexConstraints
    2049             :  *      Handle UNIQUE, PRIMARY KEY, EXCLUDE constraints, which create indexes.
    2050             :  *      We also merge in any index definitions arising from
    2051             :  *      LIKE ... INCLUDING INDEXES.
    2052             :  */
    2053             : static void
    2054       82372 : transformIndexConstraints(CreateStmtContext *cxt)
    2055             : {
    2056             :     IndexStmt  *index;
    2057       82372 :     List       *indexlist = NIL;
    2058       82372 :     List       *finalindexlist = NIL;
    2059             :     ListCell   *lc;
    2060             : 
    2061             :     /*
    2062             :      * Run through the constraints that need to generate an index. For PRIMARY
    2063             :      * KEY, mark each column as NOT NULL and create an index. For UNIQUE or
    2064             :      * EXCLUDE, create an index as for PRIMARY KEY, but do not insist on NOT
    2065             :      * NULL.
    2066             :      */
    2067      139370 :     foreach(lc, cxt->ixconstraints)
    2068             :     {
    2069       57006 :         Constraint *constraint = lfirst_node(Constraint, lc);
    2070             : 
    2071             :         Assert(constraint->contype == CONSTR_PRIMARY ||
    2072             :                constraint->contype == CONSTR_UNIQUE ||
    2073             :                constraint->contype == CONSTR_EXCLUSION);
    2074             : 
    2075       57006 :         index = transformIndexConstraint(constraint, cxt);
    2076             : 
    2077       56998 :         indexlist = lappend(indexlist, index);
    2078             :     }
    2079             : 
    2080             :     /*
    2081             :      * Scan the index list and remove any redundant index specifications. This
    2082             :      * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
    2083             :      * strict reading of SQL would suggest raising an error instead, but that
    2084             :      * strikes me as too anal-retentive. - tgl 2001-02-14
    2085             :      *
    2086             :      * XXX in ALTER TABLE case, it'd be nice to look for duplicate
    2087             :      * pre-existing indexes, too.
    2088             :      */
    2089       82364 :     if (cxt->pkey != NULL)
    2090             :     {
    2091             :         /* Make sure we keep the PKEY index in preference to others... */
    2092       34282 :         finalindexlist = list_make1(cxt->pkey);
    2093             :     }
    2094             : 
    2095      139362 :     foreach(lc, indexlist)
    2096             :     {
    2097       56998 :         bool        keep = true;
    2098             :         ListCell   *k;
    2099             : 
    2100       56998 :         index = lfirst(lc);
    2101             : 
    2102             :         /* if it's pkey, it's already in finalindexlist */
    2103       56998 :         if (index == cxt->pkey)
    2104       34282 :             continue;
    2105             : 
    2106       22820 :         foreach(k, finalindexlist)
    2107             :         {
    2108         104 :             IndexStmt  *priorindex = lfirst(k);
    2109             : 
    2110         108 :             if (equal(index->indexParams, priorindex->indexParams) &&
    2111           8 :                 equal(index->indexIncludingParams, priorindex->indexIncludingParams) &&
    2112           8 :                 equal(index->whereClause, priorindex->whereClause) &&
    2113           4 :                 equal(index->excludeOpNames, priorindex->excludeOpNames) &&
    2114           4 :                 strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
    2115           4 :                 index->deferrable == priorindex->deferrable &&
    2116           0 :                 index->initdeferred == priorindex->initdeferred)
    2117             :             {
    2118           0 :                 priorindex->unique |= index->unique;
    2119             : 
    2120             :                 /*
    2121             :                  * If the prior index is as yet unnamed, and this one is
    2122             :                  * named, then transfer the name to the prior index. This
    2123             :                  * ensures that if we have named and unnamed constraints,
    2124             :                  * we'll use (at least one of) the names for the index.
    2125             :                  */
    2126           0 :                 if (priorindex->idxname == NULL)
    2127           0 :                     priorindex->idxname = index->idxname;
    2128           0 :                 keep = false;
    2129           0 :                 break;
    2130             :             }
    2131             :         }
    2132             : 
    2133       22716 :         if (keep)
    2134       22716 :             finalindexlist = lappend(finalindexlist, index);
    2135             :     }
    2136             : 
    2137             :     /*
    2138             :      * Now append all the IndexStmts to cxt->alist.  If we generated an ALTER
    2139             :      * TABLE SET NOT NULL statement to support a primary key, it's already in
    2140             :      * cxt->alist.
    2141             :      */
    2142       82364 :     cxt->alist = list_concat(cxt->alist, finalindexlist);
    2143       82364 : }
    2144             : 
    2145             : /*
    2146             :  * transformIndexConstraint
    2147             :  *      Transform one UNIQUE, PRIMARY KEY, or EXCLUDE constraint for
    2148             :  *      transformIndexConstraints.
    2149             :  *
    2150             :  * We return an IndexStmt.  For a PRIMARY KEY constraint, we additionally
    2151             :  * produce NOT NULL constraints, either by marking ColumnDefs in cxt->columns
    2152             :  * as is_not_null or by adding an ALTER TABLE SET NOT NULL command to
    2153             :  * cxt->alist.
    2154             :  */
    2155             : static IndexStmt *
    2156       57006 : transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
    2157             : {
    2158             :     IndexStmt  *index;
    2159       57006 :     List       *notnullcmds = NIL;
    2160             :     ListCell   *lc;
    2161             : 
    2162       57006 :     index = makeNode(IndexStmt);
    2163             : 
    2164       57006 :     index->unique = (constraint->contype != CONSTR_EXCLUSION);
    2165       57006 :     index->primary = (constraint->contype == CONSTR_PRIMARY);
    2166       57006 :     if (index->primary)
    2167             :     {
    2168       34282 :         if (cxt->pkey != NULL)
    2169           0 :             ereport(ERROR,
    2170             :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    2171             :                      errmsg("multiple primary keys for table \"%s\" are not allowed",
    2172             :                             cxt->relation->relname),
    2173             :                      parser_errposition(cxt->pstate, constraint->location)));
    2174       34282 :         cxt->pkey = index;
    2175             : 
    2176             :         /*
    2177             :          * In ALTER TABLE case, a primary index might already exist, but
    2178             :          * DefineIndex will check for it.
    2179             :          */
    2180             :     }
    2181       57006 :     index->isconstraint = true;
    2182       57006 :     index->deferrable = constraint->deferrable;
    2183       57006 :     index->initdeferred = constraint->initdeferred;
    2184             : 
    2185       57006 :     if (constraint->conname != NULL)
    2186         606 :         index->idxname = pstrdup(constraint->conname);
    2187             :     else
    2188       56400 :         index->idxname = NULL;   /* DefineIndex will choose name */
    2189             : 
    2190       57006 :     index->relation = cxt->relation;
    2191       57006 :     index->accessMethod = constraint->access_method ? constraint->access_method : DEFAULT_INDEX_TYPE;
    2192       57006 :     index->options = constraint->options;
    2193       57006 :     index->tableSpace = constraint->indexspace;
    2194       57006 :     index->whereClause = constraint->where_clause;
    2195       57006 :     index->indexParams = NIL;
    2196       57006 :     index->indexIncludingParams = NIL;
    2197       57006 :     index->excludeOpNames = NIL;
    2198       57006 :     index->idxcomment = NULL;
    2199       57006 :     index->indexOid = InvalidOid;
    2200       57006 :     index->oldNode = InvalidOid;
    2201       57006 :     index->oldCreateSubid = InvalidSubTransactionId;
    2202       57006 :     index->oldFirstRelfilenodeSubid = InvalidSubTransactionId;
    2203       57006 :     index->transformed = false;
    2204       57006 :     index->concurrent = false;
    2205       57006 :     index->if_not_exists = false;
    2206       57006 :     index->reset_default_tblspc = constraint->reset_default_tblspc;
    2207             : 
    2208             :     /*
    2209             :      * If it's ALTER TABLE ADD CONSTRAINT USING INDEX, look up the index and
    2210             :      * verify it's usable, then extract the implied column name list.  (We
    2211             :      * will not actually need the column name list at runtime, but we need it
    2212             :      * now to check for duplicate column entries below.)
    2213             :      */
    2214       57006 :     if (constraint->indexname != NULL)
    2215             :     {
    2216       51616 :         char       *index_name = constraint->indexname;
    2217       51616 :         Relation    heap_rel = cxt->rel;
    2218             :         Oid         index_oid;
    2219             :         Relation    index_rel;
    2220             :         Form_pg_index index_form;
    2221             :         oidvector  *indclass;
    2222             :         Datum       indclassDatum;
    2223             :         bool        isnull;
    2224             :         int         i;
    2225             : 
    2226             :         /* Grammar should not allow this with explicit column list */
    2227             :         Assert(constraint->keys == NIL);
    2228             : 
    2229             :         /* Grammar should only allow PRIMARY and UNIQUE constraints */
    2230             :         Assert(constraint->contype == CONSTR_PRIMARY ||
    2231             :                constraint->contype == CONSTR_UNIQUE);
    2232             : 
    2233             :         /* Must be ALTER, not CREATE, but grammar doesn't enforce that */
    2234       51616 :         if (!cxt->isalter)
    2235           0 :             ereport(ERROR,
    2236             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2237             :                      errmsg("cannot use an existing index in CREATE TABLE"),
    2238             :                      parser_errposition(cxt->pstate, constraint->location)));
    2239             : 
    2240             :         /* Look for the index in the same schema as the table */
    2241       51616 :         index_oid = get_relname_relid(index_name, RelationGetNamespace(heap_rel));
    2242             : 
    2243       51616 :         if (!OidIsValid(index_oid))
    2244           0 :             ereport(ERROR,
    2245             :                     (errcode(ERRCODE_UNDEFINED_OBJECT),
    2246             :                      errmsg("index \"%s\" does not exist", index_name),
    2247             :                      parser_errposition(cxt->pstate, constraint->location)));
    2248             : 
    2249             :         /* Open the index (this will throw an error if it is not an index) */
    2250       51616 :         index_rel = index_open(index_oid, AccessShareLock);
    2251       51616 :         index_form = index_rel->rd_index;
    2252             : 
    2253             :         /* Check that it does not have an associated constraint already */
    2254       51616 :         if (OidIsValid(get_index_constraint(index_oid)))
    2255           0 :             ereport(ERROR,
    2256             :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    2257             :                      errmsg("index \"%s\" is already associated with a constraint",
    2258             :                             index_name),
    2259             :                      parser_errposition(cxt->pstate, constraint->location)));
    2260             : 
    2261             :         /* Perform validity checks on the index */
    2262       51616 :         if (index_form->indrelid != RelationGetRelid(heap_rel))
    2263           0 :             ereport(ERROR,
    2264             :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    2265             :                      errmsg("index \"%s\" does not belong to table \"%s\"",
    2266             :                             index_name, RelationGetRelationName(heap_rel)),
    2267             :                      parser_errposition(cxt->pstate, constraint->location)));
    2268             : 
    2269       51616 :         if (!index_form->indisvalid)
    2270           0 :             ereport(ERROR,
    2271             :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    2272             :                      errmsg("index \"%s\" is not valid", index_name),
    2273             :                      parser_errposition(cxt->pstate, constraint->location)));
    2274             : 
    2275       51616 :         if (!index_form->indisunique)
    2276           0 :             ereport(ERROR,
    2277             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2278             :                      errmsg("\"%s\" is not a unique index", index_name),
    2279             :                      errdetail("Cannot create a primary key or unique constraint using such an index."),
    2280             :                      parser_errposition(cxt->pstate, constraint->location)));
    2281             : 
    2282       51616 :         if (RelationGetIndexExpressions(index_rel) != NIL)
    2283           0 :             ereport(ERROR,
    2284             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2285             :                      errmsg("index \"%s\" contains expressions", index_name),
    2286             :                      errdetail("Cannot create a primary key or unique constraint using such an index."),
    2287             :                      parser_errposition(cxt->pstate, constraint->location)));
    2288             : 
    2289       51616 :         if (RelationGetIndexPredicate(index_rel) != NIL)
    2290           0 :             ereport(ERROR,
    2291             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2292             :                      errmsg("\"%s\" is a partial index", index_name),
    2293             :                      errdetail("Cannot create a primary key or unique constraint using such an index."),
    2294             :                      parser_errposition(cxt->pstate, constraint->location)));
    2295             : 
    2296             :         /*
    2297             :          * It's probably unsafe to change a deferred index to non-deferred. (A
    2298             :          * non-constraint index couldn't be deferred anyway, so this case
    2299             :          * should never occur; no need to sweat, but let's check it.)
    2300             :          */
    2301       51616 :         if (!index_form->indimmediate && !constraint->deferrable)
    2302           0 :             ereport(ERROR,
    2303             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2304             :                      errmsg("\"%s\" is a deferrable index", index_name),
    2305             :                      errdetail("Cannot create a non-deferrable constraint using a deferrable index."),
    2306             :                      parser_errposition(cxt->pstate, constraint->location)));
    2307             : 
    2308             :         /*
    2309             :          * Insist on it being a btree.  That's the only kind that supports
    2310             :          * uniqueness at the moment anyway; but we must have an index that
    2311             :          * exactly matches what you'd get from plain ADD CONSTRAINT syntax,
    2312             :          * else dump and reload will produce a different index (breaking
    2313             :          * pg_upgrade in particular).
    2314             :          */
    2315       51616 :         if (index_rel->rd_rel->relam != get_index_am_oid(DEFAULT_INDEX_TYPE, false))
    2316           0 :             ereport(ERROR,
    2317             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2318             :                      errmsg("index \"%s\" is not a btree", index_name),
    2319             :                      parser_errposition(cxt->pstate, constraint->location)));
    2320             : 
    2321             :         /* Must get indclass the hard way */
    2322       51616 :         indclassDatum = SysCacheGetAttr(INDEXRELID, index_rel->rd_indextuple,
    2323             :                                         Anum_pg_index_indclass, &isnull);
    2324             :         Assert(!isnull);
    2325       51616 :         indclass = (oidvector *) DatumGetPointer(indclassDatum);
    2326             : 
    2327      136040 :         for (i = 0; i < index_form->indnatts; i++)
    2328             :         {
    2329       84432 :             int16       attnum = index_form->indkey.values[i];
    2330             :             const FormData_pg_attribute *attform;
    2331             :             char       *attname;
    2332             :             Oid         defopclass;
    2333             : 
    2334             :             /*
    2335             :              * We shouldn't see attnum == 0 here, since we already rejected
    2336             :              * expression indexes.  If we do, SystemAttributeDefinition will
    2337             :              * throw an error.
    2338             :              */
    2339       84432 :             if (attnum > 0)
    2340             :             {
    2341             :                 Assert(attnum <= heap_rel->rd_att->natts);
    2342       84432 :                 attform = TupleDescAttr(heap_rel->rd_att, attnum - 1);
    2343             :             }
    2344             :             else
    2345           0 :                 attform = SystemAttributeDefinition(attnum);
    2346       84432 :             attname = pstrdup(NameStr(attform->attname));
    2347             : 
    2348       84432 :             if (i < index_form->indnkeyatts)
    2349             :             {
    2350             :                 /*
    2351             :                  * Insist on default opclass, collation, and sort options.
    2352             :                  * While the index would still work as a constraint with
    2353             :                  * non-default settings, it might not provide exactly the same
    2354             :                  * uniqueness semantics as you'd get from a normally-created
    2355             :                  * constraint; and there's also the dump/reload problem
    2356             :                  * mentioned above.
    2357             :                  */
    2358             :                 Datum       attoptions =
    2359       84412 :                 get_attoptions(RelationGetRelid(index_rel), i + 1);
    2360             : 
    2361       84412 :                 defopclass = GetDefaultOpClass(attform->atttypid,
    2362       84412 :                                                index_rel->rd_rel->relam);
    2363       84412 :                 if (indclass->values[i] != defopclass ||
    2364       84412 :                     attform->attcollation != index_rel->rd_indcollation[i] ||
    2365       84408 :                     attoptions != (Datum) 0 ||
    2366       84408 :                     index_rel->rd_indoption[i] != 0)
    2367           8 :                     ereport(ERROR,
    2368             :                             (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2369             :                              errmsg("index \"%s\" column number %d does not have default sorting behavior", index_name, i + 1),
    2370             :                              errdetail("Cannot create a primary key or unique constraint using such an index."),
    2371             :                              parser_errposition(cxt->pstate, constraint->location)));
    2372             : 
    2373       84404 :                 constraint->keys = lappend(constraint->keys, makeString(attname));
    2374             :             }
    2375             :             else
    2376          20 :                 constraint->including = lappend(constraint->including, makeString(attname));
    2377             :         }
    2378             : 
    2379             :         /* Close the index relation but keep the lock */
    2380       51608 :         relation_close(index_rel, NoLock);
    2381             : 
    2382       51608 :         index->indexOid = index_oid;
    2383             :     }
    2384             : 
    2385             :     /*
    2386             :      * If it's an EXCLUDE constraint, the grammar returns a list of pairs of
    2387             :      * IndexElems and operator names.  We have to break that apart into
    2388             :      * separate lists.
    2389             :      */
    2390       56998 :     if (constraint->contype == CONSTR_EXCLUSION)
    2391             :     {
    2392         190 :         foreach(lc, constraint->exclusions)
    2393             :         {
    2394         106 :             List       *pair = (List *) lfirst(lc);
    2395             :             IndexElem  *elem;
    2396             :             List       *opname;
    2397             : 
    2398             :             Assert(list_length(pair) == 2);
    2399         106 :             elem = linitial_node(IndexElem, pair);
    2400         106 :             opname = lsecond_node(List, pair);
    2401             : 
    2402         106 :             index->indexParams = lappend(index->indexParams, elem);
    2403         106 :             index->excludeOpNames = lappend(index->excludeOpNames, opname);
    2404             :         }
    2405             :     }
    2406             : 
    2407             :     /*
    2408             :      * For UNIQUE and PRIMARY KEY, we just have a list of column names.
    2409             :      *
    2410             :      * Make sure referenced keys exist.  If we are making a PRIMARY KEY index,
    2411             :      * also make sure they are NOT NULL.
    2412             :      */
    2413             :     else
    2414             :     {
    2415      147178 :         foreach(lc, constraint->keys)
    2416             :         {
    2417       90264 :             char       *key = strVal(lfirst(lc));
    2418       90264 :             bool        found = false;
    2419       90264 :             bool        forced_not_null = false;
    2420       90264 :             ColumnDef  *column = NULL;
    2421             :             ListCell   *columns;
    2422             :             IndexElem  *iparam;
    2423             : 
    2424             :             /* Make sure referenced column exists. */
    2425       90988 :             foreach(columns, cxt->columns)
    2426             :             {
    2427        5798 :                 column = lfirst_node(ColumnDef, columns);
    2428        5798 :                 if (strcmp(column->colname, key) == 0)
    2429             :                 {
    2430        5074 :                     found = true;
    2431        5074 :                     break;
    2432             :                 }
    2433             :             }
    2434       90264 :             if (found)
    2435             :             {
    2436             :                 /*
    2437             :                  * column is defined in the new table.  For PRIMARY KEY, we
    2438             :                  * can apply the NOT NULL constraint cheaply here ... unless
    2439             :                  * the column is marked is_from_type, in which case marking it
    2440             :                  * here would be ineffective (see MergeAttributes).
    2441             :                  */
    2442        5074 :                 if (constraint->contype == CONSTR_PRIMARY &&
    2443        4716 :                     !column->is_from_type)
    2444             :                 {
    2445        4698 :                     column->is_not_null = true;
    2446        4698 :                     forced_not_null = true;
    2447             :                 }
    2448             :             }
    2449       85190 :             else if (SystemAttributeByName(key) != NULL)
    2450             :             {
    2451             :                 /*
    2452             :                  * column will be a system column in the new table, so accept
    2453             :                  * it. System columns can't ever be null, so no need to worry
    2454             :                  * about PRIMARY/NOT NULL constraint.
    2455             :                  */
    2456           0 :                 found = true;
    2457             :             }
    2458       85190 :             else if (cxt->inhRelations)
    2459             :             {
    2460             :                 /* try inherited tables */
    2461             :                 ListCell   *inher;
    2462             : 
    2463          40 :                 foreach(inher, cxt->inhRelations)
    2464             :                 {
    2465          40 :                     RangeVar   *inh = lfirst_node(RangeVar, inher);
    2466             :                     Relation    rel;
    2467             :                     int         count;
    2468             : 
    2469          40 :                     rel = table_openrv(inh, AccessShareLock);
    2470             :                     /* check user requested inheritance from valid relkind */
    2471          40 :                     if (rel->rd_rel->relkind != RELKIND_RELATION &&
    2472           0 :                         rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
    2473           0 :                         rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
    2474           0 :                         ereport(ERROR,
    2475             :                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2476             :                                  errmsg("inherited relation \"%s\" is not a table or foreign table",
    2477             :                                         inh->relname)));
    2478          40 :                     for (count = 0; count < rel->rd_att->natts; count++)
    2479             :                     {
    2480          40 :                         Form_pg_attribute inhattr = TupleDescAttr(rel->rd_att,
    2481             :                                                                   count);
    2482          40 :                         char       *inhname = NameStr(inhattr->attname);
    2483             : 
    2484          40 :                         if (inhattr->attisdropped)
    2485           0 :                             continue;
    2486          40 :                         if (strcmp(key, inhname) == 0)
    2487             :                         {
    2488          40 :                             found = true;
    2489             : 
    2490             :                             /*
    2491             :                              * It's tempting to set forced_not_null if the
    2492             :                              * parent column is already NOT NULL, but that
    2493             :                              * seems unsafe because the column's NOT NULL
    2494             :                              * marking might disappear between now and
    2495             :                              * execution.  Do the runtime check to be safe.
    2496             :                              */
    2497          40 :                             break;
    2498             :                         }
    2499             :                     }
    2500          40 :                     table_close(rel, NoLock);
    2501          40 :                     if (found)
    2502          40 :                         break;
    2503             :                 }
    2504             :             }
    2505             : 
    2506             :             /*
    2507             :              * In the ALTER TABLE case, don't complain about index keys not
    2508             :              * created in the command; they may well exist already.
    2509             :              * DefineIndex will complain about them if not.
    2510             :              */
    2511       90264 :             if (!found && !cxt->isalter)
    2512           0 :                 ereport(ERROR,
    2513             :                         (errcode(ERRCODE_UNDEFINED_COLUMN),
    2514             :                          errmsg("column \"%s\" named in key does not exist", key),
    2515             :                          parser_errposition(cxt->pstate, constraint->location)));
    2516             : 
    2517             :             /* Check for PRIMARY KEY(foo, foo) */
    2518      136686 :             foreach(columns, index->indexParams)
    2519             :             {
    2520       46422 :                 iparam = (IndexElem *) lfirst(columns);
    2521       46422 :                 if (iparam->name && strcmp(key, iparam->name) == 0)
    2522             :                 {
    2523           0 :                     if (index->primary)
    2524           0 :                         ereport(ERROR,
    2525             :                                 (errcode(ERRCODE_DUPLICATE_COLUMN),
    2526             :                                  errmsg("column \"%s\" appears twice in primary key constraint",
    2527             :                                         key),
    2528             :                                  parser_errposition(cxt->pstate, constraint->location)));
    2529             :                     else
    2530           0 :                         ereport(ERROR,
    2531             :                                 (errcode(ERRCODE_DUPLICATE_COLUMN),
    2532             :                                  errmsg("column \"%s\" appears twice in unique constraint",
    2533             :                                         key),
    2534             :                                  parser_errposition(cxt->pstate, constraint->location)));
    2535             :                 }
    2536             :             }
    2537             : 
    2538             :             /* OK, add it to the index definition */
    2539       90264 :             iparam = makeNode(IndexElem);
    2540       90264 :             iparam->name = pstrdup(key);
    2541       90264 :             iparam->expr = NULL;
    2542       90264 :             iparam->indexcolname = NULL;
    2543       90264 :             iparam->collation = NIL;
    2544       90264 :             iparam->opclass = NIL;
    2545       90264 :             iparam->opclassopts = NIL;
    2546       90264 :             iparam->ordering = SORTBY_DEFAULT;
    2547       90264 :             iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
    2548       90264 :             index->indexParams = lappend(index->indexParams, iparam);
    2549             : 
    2550             :             /*
    2551             :              * For a primary-key column, also create an item for ALTER TABLE
    2552             :              * SET NOT NULL if we couldn't ensure it via is_not_null above.
    2553             :              */
    2554       90264 :             if (constraint->contype == CONSTR_PRIMARY && !forced_not_null)
    2555             :             {
    2556       39670 :                 AlterTableCmd *notnullcmd = makeNode(AlterTableCmd);
    2557             : 
    2558       39670 :                 notnullcmd->subtype = AT_SetNotNull;
    2559       39670 :                 notnullcmd->name = pstrdup(key);
    2560       39670 :                 notnullcmds = lappend(notnullcmds, notnullcmd);
    2561             :             }
    2562             :         }
    2563             :     }
    2564             : 
    2565             :     /*
    2566             :      * Add included columns to index definition.  This is much like the
    2567             :      * simple-column-name-list code above, except that we don't worry about
    2568             :      * NOT NULL marking; included columns in a primary key should not be
    2569             :      * forced NOT NULL.  We don't complain about duplicate columns, either,
    2570             :      * though maybe we should?
    2571             :      */
    2572       57230 :     foreach(lc, constraint->including)
    2573             :     {
    2574         232 :         char       *key = strVal(lfirst(lc));
    2575         232 :         bool        found = false;
    2576         232 :         ColumnDef  *column = NULL;
    2577             :         ListCell   *columns;
    2578             :         IndexElem  *iparam;
    2579             : 
    2580         490 :         foreach(columns, cxt->columns)
    2581             :         {
    2582         406 :             column = lfirst_node(ColumnDef, columns);
    2583         406 :             if (strcmp(column->colname, key) == 0)
    2584             :             {
    2585         148 :                 found = true;
    2586         148 :                 break;
    2587             :             }
    2588             :         }
    2589             : 
    2590         232 :         if (!found)
    2591             :         {
    2592          84 :             if (SystemAttributeByName(key) != NULL)
    2593             :             {
    2594             :                 /*
    2595             :                  * column will be a system column in the new table, so accept
    2596             :                  * it.
    2597             :                  */
    2598           0 :                 found = true;
    2599             :             }
    2600          84 :             else if (cxt->inhRelations)
    2601             :             {
    2602             :                 /* try inherited tables */
    2603             :                 ListCell   *inher;
    2604             : 
    2605           0 :                 foreach(inher, cxt->inhRelations)
    2606             :                 {
    2607           0 :                     RangeVar   *inh = lfirst_node(RangeVar, inher);
    2608             :                     Relation    rel;
    2609             :                     int         count;
    2610             : 
    2611           0 :                     rel = table_openrv(inh, AccessShareLock);
    2612             :                     /* check user requested inheritance from valid relkind */
    2613           0 :                     if (rel->rd_rel->relkind != RELKIND_RELATION &&
    2614           0 :                         rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
    2615           0 :                         rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
    2616           0 :                         ereport(ERROR,
    2617             :                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2618             :                                  errmsg("inherited relation \"%s\" is not a table or foreign table",
    2619             :                                         inh->relname)));
    2620           0 :                     for (count = 0; count < rel->rd_att->natts; count++)
    2621             :                     {
    2622           0 :                         Form_pg_attribute inhattr = TupleDescAttr(rel->rd_att,
    2623             :                                                                   count);
    2624           0 :                         char       *inhname = NameStr(inhattr->attname);
    2625             : 
    2626           0 :                         if (inhattr->attisdropped)
    2627           0 :                             continue;
    2628           0 :                         if (strcmp(key, inhname) == 0)
    2629             :                         {
    2630           0 :                             found = true;
    2631           0 :                             break;
    2632             :                         }
    2633             :                     }
    2634           0 :                     table_close(rel, NoLock);
    2635           0 :                     if (found)
    2636           0 :                         break;
    2637             :                 }
    2638             :             }
    2639             :         }
    2640             : 
    2641             :         /*
    2642             :          * In the ALTER TABLE case, don't complain about index keys not
    2643             :          * created in the command; they may well exist already. DefineIndex
    2644             :          * will complain about them if not.
    2645             :          */
    2646         232 :         if (!found && !cxt->isalter)
    2647           0 :             ereport(ERROR,
    2648             :                     (errcode(ERRCODE_UNDEFINED_COLUMN),
    2649             :                      errmsg("column \"%s\" named in key does not exist", key),
    2650             :                      parser_errposition(cxt->pstate, constraint->location)));
    2651             : 
    2652             :         /* OK, add it to the index definition */
    2653         232 :         iparam = makeNode(IndexElem);
    2654         232 :         iparam->name = pstrdup(key);
    2655         232 :         iparam->expr = NULL;
    2656         232 :         iparam->indexcolname = NULL;
    2657         232 :         iparam->collation = NIL;
    2658         232 :         iparam->opclass = NIL;
    2659         232 :         iparam->opclassopts = NIL;
    2660         232 :         index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
    2661             :     }
    2662             : 
    2663             :     /*
    2664             :      * If we found anything that requires run-time SET NOT NULL, build a full
    2665             :      * ALTER TABLE command for that and add it to cxt->alist.
    2666             :      */
    2667       56998 :     if (notnullcmds)
    2668             :     {
    2669       29938 :         AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
    2670             : 
    2671       29938 :         alterstmt->relation = copyObject(cxt->relation);
    2672       29938 :         alterstmt->cmds = notnullcmds;
    2673       29938 :         alterstmt->objtype = OBJECT_TABLE;
    2674       29938 :         alterstmt->missing_ok = false;
    2675             : 
    2676       29938 :         cxt->alist = lappend(cxt->alist, alterstmt);
    2677             :     }
    2678             : 
    2679       56998 :     return index;
    2680             : }
    2681             : 
    2682             : /*
    2683             :  * transformExtendedStatistics
    2684             :  *     Handle extended statistic objects
    2685             :  *
    2686             :  * Right now, there's nothing to do here, so we just append the list to
    2687             :  * the existing "after" list.
    2688             :  */
    2689             : static void
    2690       82364 : transformExtendedStatistics(CreateStmtContext *cxt)
    2691             : {
    2692       82364 :     cxt->alist = list_concat(cxt->alist, cxt->extstats);
    2693       82364 : }
    2694             : 
    2695             : /*
    2696             :  * transformCheckConstraints
    2697             :  *      handle CHECK constraints
    2698             :  *
    2699             :  * Right now, there's nothing to do here when called from ALTER TABLE,
    2700             :  * but the other constraint-transformation functions are called in both
    2701             :  * the CREATE TABLE and ALTER TABLE paths, so do the same here, and just
    2702             :  * don't do anything if we're not authorized to skip validation.
    2703             :  */
    2704             : static void
    2705       82364 : transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)
    2706             : {
    2707             :     ListCell   *ckclist;
    2708             : 
    2709       82364 :     if (cxt->ckconstraints == NIL)
    2710       81472 :         return;
    2711             : 
    2712             :     /*
    2713             :      * If creating a new table (but not a foreign table), we can safely skip
    2714             :      * validation of check constraints, and nonetheless mark them valid. (This
    2715             :      * will override any user-supplied NOT VALID flag.)
    2716             :      */
    2717         892 :     if (skipValidation)
    2718             :     {
    2719         816 :         foreach(ckclist, cxt->ckconstraints)
    2720             :         {
    2721         446 :             Constraint *constraint = (Constraint *) lfirst(ckclist);
    2722             : 
    2723         446 :             constraint->skip_validation = true;
    2724         446 :             constraint->initially_valid = true;
    2725             :         }
    2726             :     }
    2727             : }
    2728             : 
    2729             : /*
    2730             :  * transformFKConstraints
    2731             :  *      handle FOREIGN KEY constraints
    2732             :  */
    2733             : static void
    2734       82364 : transformFKConstraints(CreateStmtContext *cxt,
    2735             :                        bool skipValidation, bool isAddConstraint)
    2736             : {
    2737             :     ListCell   *fkclist;
    2738             : 
    2739       82364 :     if (cxt->fkconstraints == NIL)
    2740       80186 :         return;
    2741             : 
    2742             :     /*
    2743             :      * If CREATE TABLE or adding a column with NULL default, we can safely
    2744             :      * skip validation of FK constraints, and nonetheless mark them valid.
    2745             :      * (This will override any user-supplied NOT VALID flag.)
    2746             :      */
    2747        2178 :     if (skipValidation)
    2748             :     {
    2749        1458 :         foreach(fkclist, cxt->fkconstraints)
    2750             :         {
    2751         748 :             Constraint *constraint = (Constraint *) lfirst(fkclist);
    2752             : 
    2753         748 :             constraint->skip_validation = true;
    2754         748 :             constraint->initially_valid = true;
    2755             :         }
    2756             :     }
    2757             : 
    2758             :     /*
    2759             :      * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
    2760             :      * CONSTRAINT command to execute after the basic command is complete. (If
    2761             :      * called from ADD CONSTRAINT, that routine will add the FK constraints to
    2762             :      * its own subcommand list.)
    2763             :      *
    2764             :      * Note: the ADD CONSTRAINT command must also execute after any index
    2765             :      * creation commands.  Thus, this should run after
    2766             :      * transformIndexConstraints, so that the CREATE INDEX commands are
    2767             :      * already in cxt->alist.  See also the handling of cxt->likeclauses.
    2768             :      */
    2769        2178 :     if (!isAddConstraint)
    2770             :     {
    2771         706 :         AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
    2772             : 
    2773         706 :         alterstmt->relation = cxt->relation;
    2774         706 :         alterstmt->cmds = NIL;
    2775         706 :         alterstmt->objtype = OBJECT_TABLE;
    2776             : 
    2777        1450 :         foreach(fkclist, cxt->fkconstraints)
    2778             :         {
    2779         744 :             Constraint *constraint = (Constraint *) lfirst(fkclist);
    2780         744 :             AlterTableCmd *altercmd = makeNode(AlterTableCmd);
    2781             : 
    2782         744 :             altercmd->subtype = AT_AddConstraint;
    2783         744 :             altercmd->name = NULL;
    2784         744 :             altercmd->def = (Node *) constraint;
    2785         744 :             alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
    2786             :         }
    2787             : 
    2788         706 :         cxt->alist = lappend(cxt->alist, alterstmt);
    2789             :     }
    2790             : }
    2791             : 
    2792             : /*
    2793             :  * transformIndexStmt - parse analysis for CREATE INDEX and ALTER TABLE
    2794             :  *
    2795             :  * Note: this is a no-op for an index not using either index expressions or
    2796             :  * a predicate expression.  There are several code paths that create indexes
    2797             :  * without bothering to call this, because they know they don't have any
    2798             :  * such expressions to deal with.
    2799             :  *
    2800             :  * To avoid race conditions, it's important that this function rely only on
    2801             :  * the passed-in relid (and not on stmt->relation) to determine the target
    2802             :  * relation.
    2803             :  */
    2804             : IndexStmt *
    2805       60946 : transformIndexStmt(Oid relid, IndexStmt *stmt, const char *queryString)
    2806             : {
    2807             :     ParseState *pstate;
    2808             :     ParseNamespaceItem *nsitem;
    2809             :     ListCell   *l;
    2810             :     Relation    rel;
    2811             : 
    2812             :     /* Nothing to do if statement already transformed. */
    2813       60946 :     if (stmt->transformed)
    2814          76 :         return stmt;
    2815             : 
    2816             :     /* Set up pstate */
    2817       60870 :     pstate = make_parsestate(NULL);
    2818       60870 :     pstate->p_sourcetext = queryString;
    2819             : 
    2820             :     /*
    2821             :      * Put the parent table into the rtable so that the expressions can refer
    2822             :      * to its fields without qualification.  Caller is responsible for locking
    2823             :      * relation, but we still need to open it.
    2824             :      */
    2825       60870 :     rel = relation_open(relid, NoLock);
    2826       60870 :     nsitem = addRangeTableEntryForRelation(pstate, rel,
    2827             :                                            AccessShareLock,
    2828             :                                            NULL, false, true);
    2829             : 
    2830             :     /* no to join list, yes to namespaces */
    2831       60870 :     addNSItemToQuery(pstate, nsitem, false, true, true);
    2832             : 
    2833             :     /* take care of the where clause */
    2834       60870 :     if (stmt->whereClause)
    2835             :     {
    2836         220 :         stmt->whereClause = transformWhereClause(pstate,
    2837             :                                                  stmt->whereClause,
    2838             :                                                  EXPR_KIND_INDEX_PREDICATE,
    2839             :                                                  "WHERE");
    2840             :         /* we have to fix its collations too */
    2841         220 :         assign_expr_collations(pstate, stmt->whereClause);
    2842             :     }
    2843             : 
    2844             :     /* take care of any index expressions */
    2845      156162 :     foreach(l, stmt->indexParams)
    2846             :     {
    2847       95296 :         IndexElem  *ielem = (IndexElem *) lfirst(l);
    2848             : 
    2849       95296 :         if (ielem->expr)
    2850             :         {
    2851             :             /* Extract preliminary index col name before transforming expr */
    2852         350 :             if (ielem->indexcolname == NULL)
    2853         350 :                 ielem->indexcolname = FigureIndexColname(ielem->expr);
    2854             : 
    2855             :             /* Now do parse transformation of the expression */
    2856         350 :             ielem->expr = transformExpr(pstate, ielem->expr,
    2857             :                                         EXPR_KIND_INDEX_EXPRESSION);
    2858             : 
    2859             :             /* We have to fix its collations too */
    2860         346 :             assign_expr_collations(pstate, ielem->expr);
    2861             : 
    2862             :             /*
    2863             :              * transformExpr() should have already rejected subqueries,
    2864             :              * aggregates, window functions, and SRFs, based on the EXPR_KIND_
    2865             :              * for an index expression.
    2866             :              *
    2867             :              * DefineIndex() will make more checks.
    2868             :              */
    2869             :         }
    2870             :     }
    2871             : 
    2872             :     /*
    2873             :      * Check that only the base rel is mentioned.  (This should be dead code
    2874             :      * now that add_missing_from is history.)
    2875             :      */
    2876       60866 :     if (list_length(pstate->p_rtable) != 1)
    2877           0 :         ereport(ERROR,
    2878             :                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
    2879             :                  errmsg("index expressions and predicates can refer only to the table being indexed")));
    2880             : 
    2881       60866 :     free_parsestate(pstate);
    2882             : 
    2883             :     /* Close relation */
    2884       60866 :     table_close(rel, NoLock);
    2885             : 
    2886             :     /* Mark statement as successfully transformed */
    2887       60866 :     stmt->transformed = true;
    2888             : 
    2889       60866 :     return stmt;
    2890             : }
    2891             : 
    2892             : /*
    2893             :  * transformStatsStmt - parse analysis for CREATE STATISTICS
    2894             :  *
    2895             :  * To avoid race conditions, it's important that this function relies only on
    2896             :  * the passed-in relid (and not on stmt->relation) to determine the target
    2897             :  * relation.
    2898             :  */
    2899             : CreateStatsStmt *
    2900         370 : transformStatsStmt(Oid relid, CreateStatsStmt *stmt, const char *queryString)
    2901             : {
    2902             :     ParseState *pstate;
    2903             :     ParseNamespaceItem *nsitem;
    2904             :     ListCell   *l;
    2905             :     Relation    rel;
    2906             : 
    2907             :     /* Nothing to do if statement already transformed. */
    2908         370 :     if (stmt->transformed)
    2909          24 :         return stmt;
    2910             : 
    2911             :     /* Set up pstate */
    2912         346 :     pstate = make_parsestate(NULL);
    2913         346 :     pstate->p_sourcetext = queryString;
    2914             : 
    2915             :     /*
    2916             :      * Put the parent table into the rtable so that the expressions can refer
    2917             :      * to its fields without qualification.  Caller is responsible for locking
    2918             :      * relation, but we still need to open it.
    2919             :      */
    2920         346 :     rel = relation_open(relid, NoLock);
    2921         346 :     nsitem = addRangeTableEntryForRelation(pstate, rel,
    2922             :                                            AccessShareLock,
    2923             :                                            NULL, false, true);
    2924             : 
    2925             :     /* no to join list, yes to namespaces */
    2926         346 :     addNSItemToQuery(pstate, nsitem, false, true, true);
    2927             : 
    2928             :     /* take care of any expressions */
    2929        1248 :     foreach(l, stmt->exprs)
    2930             :     {
    2931         902 :         StatsElem  *selem = (StatsElem *) lfirst(l);
    2932             : 
    2933         902 :         if (selem->expr)
    2934             :         {
    2935             :             /* Now do parse transformation of the expression */
    2936         256 :             selem->expr = transformExpr(pstate, selem->expr,
    2937             :                                         EXPR_KIND_STATS_EXPRESSION);
    2938             : 
    2939             :             /* We have to fix its collations too */
    2940         256 :             assign_expr_collations(pstate, selem->expr);
    2941             :         }
    2942             :     }
    2943             : 
    2944             :     /*
    2945             :      * Check that only the base rel is mentioned.  (This should be dead code
    2946             :      * now that add_missing_from is history.)
    2947             :      */
    2948         346 :     if (list_length(pstate->p_rtable) != 1)
    2949           0 :         ereport(ERROR,
    2950             :                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
    2951             :                  errmsg("statistics expressions can refer only to the table being referenced")));
    2952             : 
    2953         346 :     free_parsestate(pstate);
    2954             : 
    2955             :     /* Close relation */
    2956         346 :     table_close(rel, NoLock);
    2957             : 
    2958             :     /* Mark statement as successfully transformed */
    2959         346 :     stmt->transformed = true;
    2960             : 
    2961         346 :     return stmt;
    2962             : }
    2963             : 
    2964             : 
    2965             : /*
    2966             :  * transformRuleStmt -
    2967             :  *    transform a CREATE RULE Statement. The action is a list of parse
    2968             :  *    trees which is transformed into a list of query trees, and we also
    2969             :  *    transform the WHERE clause if any.
    2970             :  *
    2971             :  * actions and whereClause are output parameters that receive the
    2972             :  * transformed results.
    2973             :  */
    2974             : void
    2975        1520 : transformRuleStmt(RuleStmt *stmt, const char *queryString,
    2976             :                   List **actions, Node **whereClause)
    2977             : {
    2978             :     Relation    rel;
    2979             :     ParseState *pstate;
    2980             :     ParseNamespaceItem *oldnsitem;
    2981             :     ParseNamespaceItem *newnsitem;
    2982             : 
    2983             :     /*
    2984             :      * To avoid deadlock, make sure the first thing we do is grab
    2985             :      * AccessExclusiveLock on the target relation.  This will be needed by
    2986             :      * DefineQueryRewrite(), and we don't want to grab a lesser lock
    2987             :      * beforehand.
    2988             :      */
    2989        1520 :     rel = table_openrv(stmt->relation, AccessExclusiveLock);
    2990             : 
    2991        1520 :     if (rel->rd_rel->relkind == RELKIND_MATVIEW)
    2992           0 :         ereport(ERROR,
    2993             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2994             :                  errmsg("rules on materialized views are not supported")));
    2995             : 
    2996             :     /* Set up pstate */
    2997        1520 :     pstate = make_parsestate(NULL);
    2998        1520 :     pstate->p_sourcetext = queryString;
    2999             : 
    3000             :     /*
    3001             :      * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
    3002             :      * Set up their ParseNamespaceItems in the main pstate for use in parsing
    3003             :      * the rule qualification.
    3004             :      */
    3005        1520 :     oldnsitem = addRangeTableEntryForRelation(pstate, rel,
    3006             :                                               AccessShareLock,
    3007             :                                               makeAlias("old", NIL),
    3008             :                                               false, false);
    3009        1520 :     newnsitem = addRangeTableEntryForRelation(pstate, rel,
    3010             :                                               AccessShareLock,
    3011             :                                               makeAlias("new", NIL),
    3012             :                                               false, false);
    3013             :     /* Must override addRangeTableEntry's default access-check flags */
    3014        1520 :     oldnsitem->p_rte->requiredPerms = 0;
    3015        1520 :     newnsitem->p_rte->requiredPerms = 0;
    3016             : 
    3017             :     /*
    3018             :      * They must be in the namespace too for lookup purposes, but only add the
    3019             :      * one(s) that are relevant for the current kind of rule.  In an UPDATE
    3020             :      * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
    3021             :      * there's no need to be so picky for INSERT & DELETE.  We do not add them
    3022             :      * to the joinlist.
    3023             :      */
    3024        1520 :     switch (stmt->event)
    3025             :     {
    3026          34 :         case CMD_SELECT:
    3027          34 :             addNSItemToQuery(pstate, oldnsitem, false, true, true);
    3028          34 :             break;
    3029        1100 :         case CMD_UPDATE:
    3030        1100 :             addNSItemToQuery(pstate, oldnsitem, false, true, true);
    3031        1100 :             addNSItemToQuery(pstate, newnsitem, false, true, true);
    3032        1100 :             break;
    3033         290 :         case CMD_INSERT:
    3034         290 :             addNSItemToQuery(pstate, newnsitem, false, true, true);
    3035         290 :             break;
    3036          96 :         case CMD_DELETE:
    3037          96 :             addNSItemToQuery(pstate, oldnsitem, false, true, true);
    3038          96 :             break;
    3039           0 :         default:
    3040           0 :             elog(ERROR, "unrecognized event type: %d",
    3041             :                  (int) stmt->event);
    3042             :             break;
    3043             :     }
    3044             : 
    3045             :     /* take care of the where clause */
    3046        1520 :     *whereClause = transformWhereClause(pstate,
    3047             :                                         stmt->whereClause,
    3048             :                                         EXPR_KIND_WHERE,
    3049             :                                         "WHERE");
    3050             :     /* we have to fix its collations too */
    3051        1520 :     assign_expr_collations(pstate, *whereClause);
    3052             : 
    3053             :     /* this is probably dead code without add_missing_from: */
    3054        1520 :     if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
    3055           0 :         ereport(ERROR,
    3056             :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    3057             :                  errmsg("rule WHERE condition cannot contain references to other relations")));
    3058             : 
    3059             :     /*
    3060             :      * 'instead nothing' rules with a qualification need a query rangetable so
    3061             :      * the rewrite handler can add the negated rule qualification to the
    3062             :      * original query. We create a query with the new command type CMD_NOTHING
    3063             :      * here that is treated specially by the rewrite system.
    3064             :      */
    3065        1520 :     if (stmt->actions == NIL)
    3066             :     {
    3067         532 :         Query      *nothing_qry = makeNode(Query);
    3068             : 
    3069         532 :         nothing_qry->commandType = CMD_NOTHING;
    3070         532 :         nothing_qry->rtable = pstate->p_rtable;
    3071         532 :         nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
    3072             : 
    3073         532 :         *actions = list_make1(nothing_qry);
    3074             :     }
    3075             :     else
    3076             :     {
    3077             :         ListCell   *l;
    3078         988 :         List       *newactions = NIL;
    3079             : 
    3080             :         /*
    3081             :          * transform each statement, like parse_sub_analyze()
    3082             :          */
    3083        1996 :         foreach(l, stmt->actions)
    3084             :         {
    3085        1020 :             Node       *action = (Node *) lfirst(l);
    3086        1020 :             ParseState *sub_pstate = make_parsestate(NULL);
    3087             :             Query      *sub_qry,
    3088             :                        *top_subqry;
    3089             :             bool        has_old,
    3090             :                         has_new;
    3091             : 
    3092             :             /*
    3093             :              * Since outer ParseState isn't parent of inner, have to pass down
    3094             :              * the query text by hand.
    3095             :              */
    3096        1020 :             sub_pstate->p_sourcetext = queryString;
    3097             : 
    3098             :             /*
    3099             :              * Set up OLD/NEW in the rtable for this statement.  The entries
    3100             :              * are added only to relnamespace, not varnamespace, because we
    3101             :              * don't want them to be referred to by unqualified field names
    3102             :              * nor "*" in the rule actions.  We decide later whether to put
    3103             :              * them in the joinlist.
    3104             :              */
    3105        1020 :             oldnsitem = addRangeTableEntryForRelation(sub_pstate, rel,
    3106             :                                                       AccessShareLock,
    3107             :                                                       makeAlias("old", NIL),
    3108             :                                                       false, false);
    3109        1020 :             newnsitem = addRangeTableEntryForRelation(sub_pstate, rel,
    3110             :                                                       AccessShareLock,
    3111             :                                                       makeAlias("new", NIL),
    3112             :                                                       false, false);
    3113        1020 :             oldnsitem->p_rte->requiredPerms = 0;
    3114        1020 :             newnsitem->p_rte->requiredPerms = 0;
    3115        1020 :             addNSItemToQuery(sub_pstate, oldnsitem, false, true, false);
    3116        1020 :             addNSItemToQuery(sub_pstate, newnsitem, false, true, false);
    3117             : 
    3118             :             /* Transform the rule action statement */
    3119        1020 :             top_subqry = transformStmt(sub_pstate, action);
    3120             : 
    3121             :             /*
    3122             :              * We cannot support utility-statement actions (eg NOTIFY) with
    3123             :              * nonempty rule WHERE conditions, because there's no way to make
    3124             :              * the utility action execute conditionally.
    3125             :              */
    3126        1012 :             if (top_subqry->commandType == CMD_UTILITY &&
    3127          22 :                 *whereClause != NULL)
    3128           0 :                 ereport(ERROR,
    3129             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    3130             :                          errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
    3131             : 
    3132             :             /*
    3133             :              * If the action is INSERT...SELECT, OLD/NEW have been pushed down
    3134             :              * into the SELECT, and that's what we need to look at. (Ugly
    3135             :              * kluge ... try to fix this when we redesign querytrees.)
    3136             :              */
    3137        1012 :             sub_qry = getInsertSelectQuery(top_subqry, NULL);
    3138             : 
    3139             :             /*
    3140             :              * If the sub_qry is a setop, we cannot attach any qualifications
    3141             :              * to it, because the planner won't notice them.  This could
    3142             :              * perhaps be relaxed someday, but for now, we may as well reject
    3143             :              * such a rule immediately.
    3144             :              */
    3145        1012 :             if (sub_qry->setOperations != NULL && *whereClause != NULL)
    3146           0 :                 ereport(ERROR,
    3147             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3148             :                          errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
    3149             : 
    3150             :             /*
    3151             :              * Validate action's use of OLD/NEW, qual too
    3152             :              */
    3153        1012 :             has_old =
    3154        1382 :                 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
    3155         370 :                 rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
    3156        1012 :             has_new =
    3157        1222 :                 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
    3158         210 :                 rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
    3159             : 
    3160        1012 :             switch (stmt->event)
    3161             :             {
    3162          34 :                 case CMD_SELECT:
    3163          34 :                     if (has_old)
    3164           0 :                         ereport(ERROR,
    3165             :                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    3166             :                                  errmsg("ON SELECT rule cannot use OLD")));
    3167          34 :                     if (has_new)
    3168           0 :                         ereport(ERROR,
    3169             :                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    3170             :                                  errmsg("ON SELECT rule cannot use NEW")));
    3171          34 :                     break;
    3172         624 :                 case CMD_UPDATE:
    3173             :                     /* both are OK */
    3174         624 :                     break;
    3175         256 :                 case CMD_INSERT:
    3176         256 :                     if (has_old)
    3177           0 :                         ereport(ERROR,
    3178             :                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    3179             :                                  errmsg("ON INSERT rule cannot use OLD")));
    3180         256 :                     break;
    3181          98 :                 case CMD_DELETE:
    3182          98 :                     if (has_new)
    3183           0 :                         ereport(ERROR,
    3184             :                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    3185             :                                  errmsg("ON DELETE rule cannot use NEW")));
    3186          98 :                     break;
    3187           0 :                 default:
    3188           0 :                     elog(ERROR, "unrecognized event type: %d",
    3189             :                          (int) stmt->event);
    3190             :                     break;
    3191             :             }
    3192             : 
    3193             :             /*
    3194             :              * OLD/NEW are not allowed in WITH queries, because they would
    3195             :              * amount to outer references for the WITH, which we disallow.
    3196             :              * However, they were already in the outer rangetable when we
    3197             :              * analyzed the query, so we have to check.
    3198             :              *
    3199             :              * Note that in the INSERT...SELECT case, we need to examine the
    3200             :              * CTE lists of both top_subqry and sub_qry.
    3201             :              *
    3202             :              * Note that we aren't digging into the body of the query looking
    3203             :              * for WITHs in nested sub-SELECTs.  A WITH down there can
    3204             :              * legitimately refer to OLD/NEW, because it'd be an
    3205             :              * indirect-correlated outer reference.
    3206             :              */
    3207        1012 :             if (rangeTableEntry_used((Node *) top_subqry->cteList,
    3208        1008 :                                      PRS2_OLD_VARNO, 0) ||
    3209        1008 :                 rangeTableEntry_used((Node *) sub_qry->cteList,
    3210             :                                      PRS2_OLD_VARNO, 0))
    3211           4 :                 ereport(ERROR,
    3212             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3213             :                          errmsg("cannot refer to OLD within WITH query")));
    3214        1008 :             if (rangeTableEntry_used((Node *) top_subqry->cteList,
    3215        1008 :                                      PRS2_NEW_VARNO, 0) ||
    3216        1008 :                 rangeTableEntry_used((Node *) sub_qry->cteList,
    3217             :                                      PRS2_NEW_VARNO, 0))
    3218           0 :                 ereport(ERROR,
    3219             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3220             :                          errmsg("cannot refer to NEW within WITH query")));
    3221             : 
    3222             :             /*
    3223             :              * For efficiency's sake, add OLD to the rule action's jointree
    3224             :              * only if it was actually referenced in the statement or qual.
    3225             :              *
    3226             :              * For INSERT, NEW is not really a relation (only a reference to
    3227             :              * the to-be-inserted tuple) and should never be added to the
    3228             :              * jointree.
    3229             :              *
    3230             :              * For UPDATE, we treat NEW as being another kind of reference to
    3231             :              * OLD, because it represents references to *transformed* tuples
    3232             :              * of the existing relation.  It would be wrong to enter NEW
    3233             :              * separately in the jointree, since that would cause a double
    3234             :              * join of the updated relation.  It's also wrong to fail to make
    3235             :              * a jointree entry if only NEW and not OLD is mentioned.
    3236             :              */
    3237        1008 :             if (has_old || (has_new && stmt->event == CMD_UPDATE))
    3238             :             {
    3239             :                 RangeTblRef *rtr;
    3240             : 
    3241             :                 /*
    3242             :                  * If sub_qry is a setop, manipulating its jointree will do no
    3243             :                  * good at all, because the jointree is dummy. (This should be
    3244             :                  * a can't-happen case because of prior tests.)
    3245             :                  */
    3246         668 :                 if (sub_qry->setOperations != NULL)
    3247           0 :                     ereport(ERROR,
    3248             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3249             :                              errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
    3250             :                 /* hackishly add OLD to the already-built FROM clause */
    3251         668 :                 rtr = makeNode(RangeTblRef);
    3252         668 :                 rtr->rtindex = oldnsitem->p_rtindex;
    3253         668 :                 sub_qry->jointree->fromlist =
    3254         668 :                     lappend(sub_qry->jointree->fromlist, rtr);
    3255             :             }
    3256             : 
    3257        1008 :             newactions = lappend(newactions, top_subqry);
    3258             : 
    3259        1008 :             free_parsestate(sub_pstate);
    3260             :         }
    3261             : 
    3262         976 :         *actions = newactions;
    3263             :     }
    3264             : 
    3265        1508 :     free_parsestate(pstate);
    3266             : 
    3267             :     /* Close relation, but keep the exclusive lock */
    3268        1508 :     table_close(rel, NoLock);
    3269        1508 : }
    3270             : 
    3271             : 
    3272             : /*
    3273             :  * transformAlterTableStmt -
    3274             :  *      parse analysis for ALTER TABLE
    3275             :  *
    3276             :  * Returns the transformed AlterTableStmt.  There may be additional actions
    3277             :  * to be done before and after the transformed statement, which are returned
    3278             :  * in *beforeStmts and *afterStmts as lists of utility command parsetrees.
    3279             :  *
    3280             :  * To avoid race conditions, it's important that this function rely only on
    3281             :  * the passed-in relid (and not on stmt->relation) to determine the target
    3282             :  * relation.
    3283             :  */
    3284             : AlterTableStmt *
    3285       58258 : transformAlterTableStmt(Oid relid, AlterTableStmt *stmt,
    3286             :                         const char *queryString,
    3287             :                         List **beforeStmts, List **afterStmts)
    3288             : {
    3289             :     Relation    rel;
    3290             :     TupleDesc   tupdesc;
    3291             :     ParseState *pstate;
    3292             :     CreateStmtContext cxt;
    3293             :     List       *save_alist;
    3294             :     ListCell   *lcmd,
    3295             :                *l;
    3296       58258 :     List       *newcmds = NIL;
    3297       58258 :     bool        skipValidation = true;
    3298             :     AlterTableCmd *newcmd;
    3299             :     ParseNamespaceItem *nsitem;
    3300             : 
    3301             :     /* Caller is responsible for locking the relation */
    3302       58258 :     rel = relation_open(relid, NoLock);
    3303       58258 :     tupdesc = RelationGetDescr(rel);
    3304             : 
    3305             :     /* Set up pstate */
    3306       58258 :     pstate = make_parsestate(NULL);
    3307       58258 :     pstate->p_sourcetext = queryString;
    3308       58258 :     nsitem = addRangeTableEntryForRelation(pstate,
    3309             :                                            rel,
    3310             :                                            AccessShareLock,
    3311             :                                            NULL,
    3312             :                                            false,
    3313             :                                            true);
    3314       58258 :     addNSItemToQuery(pstate, nsitem, false, true, true);
    3315             : 
    3316             :     /* Set up CreateStmtContext */
    3317       58258 :     cxt.pstate = pstate;
    3318       58258 :     if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
    3319             :     {
    3320         110 :         cxt.stmtType = "ALTER FOREIGN TABLE";
    3321         110 :         cxt.isforeign = true;
    3322             :     }
    3323             :     else
    3324             :     {
    3325       58148 :         cxt.stmtType = "ALTER TABLE";
    3326       58148 :         cxt.isforeign = false;
    3327             :     }
    3328       58258 :     cxt.relation = stmt->relation;
    3329       58258 :     cxt.rel = rel;
    3330       58258 :     cxt.inhRelations = NIL;
    3331       58258 :     cxt.isalter = true;
    3332       58258 :     cxt.columns = NIL;
    3333       58258 :     cxt.ckconstraints = NIL;
    3334       58258 :     cxt.fkconstraints = NIL;
    3335       58258 :     cxt.ixconstraints = NIL;
    3336       58258 :     cxt.likeclauses = NIL;
    3337       58258 :     cxt.extstats = NIL;
    3338       58258 :     cxt.blist = NIL;
    3339       58258 :     cxt.alist = NIL;
    3340       58258 :     cxt.pkey = NULL;
    3341       58258 :     cxt.ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
    3342       58258 :     cxt.partbound = NULL;
    3343       58258 :     cxt.ofType = false;
    3344             : 
    3345             :     /*
    3346             :      * Transform ALTER subcommands that need it (most don't).  These largely
    3347             :      * re-use code from CREATE TABLE.
    3348             :      */
    3349      116480 :     foreach(lcmd, stmt->cmds)
    3350             :     {
    3351       58258 :         AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
    3352             : 
    3353       58258 :         switch (cmd->subtype)
    3354             :         {
    3355        1204 :             case AT_AddColumn:
    3356             :             case AT_AddColumnRecurse:
    3357             :                 {
    3358        1204 :                     ColumnDef  *def = castNode(ColumnDef, cmd->def);
    3359             : 
    3360        1204 :                     transformColumnDefinition(&cxt, def);
    3361             : 
    3362             :                     /*
    3363             :                      * If the column has a non-null default, we can't skip
    3364             :                      * validation of foreign keys.
    3365             :                      */
    3366        1204 :                     if (def->raw_default != NULL)
    3367         482 :                         skipValidation = false;
    3368             : 
    3369             :                     /*
    3370             :                      * All constraints are processed in other ways. Remove the
    3371             :                      * original list
    3372             :                      */
    3373        1204 :                     def->constraints = NIL;
    3374             : 
    3375        1204 :                     newcmds = lappend(newcmds, cmd);
    3376        1204 :                     break;
    3377             :                 }
    3378             : 
    3379       54248 :             case AT_AddConstraint:
    3380             :             case AT_AddConstraintRecurse:
    3381             : 
    3382             :                 /*
    3383             :                  * The original AddConstraint cmd node doesn't go to newcmds
    3384             :                  */
    3385       54248 :                 if (IsA(cmd->def, Constraint))
    3386             :                 {
    3387       54248 :                     transformTableConstraint(&cxt, (Constraint *) cmd->def);
    3388       54236 :                     if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
    3389        1468 :                         skipValidation = false;
    3390             :                 }
    3391             :                 else
    3392           0 :                     elog(ERROR, "unrecognized node type: %d",
    3393             :                          (int) nodeTag(cmd->def));
    3394       54236 :                 break;
    3395             : 
    3396         722 :             case AT_AlterColumnType:
    3397             :                 {
    3398         722 :                     ColumnDef  *def = castNode(ColumnDef, cmd->def);
    3399             :                     AttrNumber  attnum;
    3400             : 
    3401             :                     /*
    3402             :                      * For ALTER COLUMN TYPE, transform the USING clause if
    3403             :                      * one was specified.
    3404             :                      */
    3405         722 :                     if (def->raw_default)
    3406             :                     {
    3407         140 :                         def->cooked_default =
    3408         140 :                             transformExpr(pstate, def->raw_default,
    3409             :                                           EXPR_KIND_ALTER_COL_TRANSFORM);
    3410             :                     }
    3411             : 
    3412             :                     /*
    3413             :                      * For identity column, create ALTER SEQUENCE command to
    3414             :                      * change the data type of the sequence.
    3415             :                      */
    3416         722 :                     attnum = get_attnum(relid, cmd->name);
    3417         722 :                     if (attnum == InvalidAttrNumber)
    3418           0 :                         ereport(ERROR,
    3419             :                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    3420             :                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
    3421             :                                         cmd->name, RelationGetRelationName(rel))));
    3422             : 
    3423         722 :                     if (TupleDescAttr(tupdesc, attnum - 1)->attidentity)
    3424             :                     {
    3425          20 :                         Oid         seq_relid = getIdentitySequence(relid, attnum, false);
    3426          20 :                         Oid         typeOid = typenameTypeId(pstate, def->typeName);
    3427          20 :                         AlterSeqStmt *altseqstmt = makeNode(AlterSeqStmt);
    3428             : 
    3429          20 :                         altseqstmt->sequence = makeRangeVar(get_namespace_name(get_rel_namespace(seq_relid)),
    3430             :                                                             get_rel_name(seq_relid),
    3431             :                                                             -1);
    3432          20 :                         altseqstmt->options = list_make1(makeDefElem("as", (Node *) makeTypeNameFromOid(typeOid, -1), -1));
    3433          20 :                         altseqstmt->for_identity = true;
    3434          20 :                         cxt.blist = lappend(cxt.blist, altseqstmt);
    3435             :                     }
    3436             : 
    3437         722 :                     newcmds = lappend(newcmds, cmd);
    3438         722 :                     break;
    3439             :                 }
    3440             : 
    3441          76 :             case AT_AddIdentity:
    3442             :                 {
    3443          76 :                     Constraint *def = castNode(Constraint, cmd->def);
    3444          76 :                     ColumnDef  *newdef = makeNode(ColumnDef);
    3445             :                     AttrNumber  attnum;
    3446             : 
    3447          76 :                     newdef->colname = cmd->name;
    3448          76 :                     newdef->identity = def->generated_when;
    3449          76 :                     cmd->def = (Node *) newdef;
    3450             : 
    3451          76 :                     attnum = get_attnum(relid, cmd->name);
    3452          76 :                     if (attnum == InvalidAttrNumber)
    3453           0 :                         ereport(ERROR,
    3454             :                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    3455             :                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
    3456             :                                         cmd->name, RelationGetRelationName(rel))));
    3457             : 
    3458          76 :                     generateSerialExtraStmts(&cxt, newdef,
    3459             :                                              get_atttype(relid, attnum),
    3460             :                                              def->options, true, true,
    3461             :                                              NULL, NULL);
    3462             : 
    3463          76 :                     newcmds = lappend(newcmds, cmd);
    3464          76 :                     break;
    3465             :                 }
    3466             : 
    3467          24 :             case AT_SetIdentity:
    3468             :                 {
    3469             :                     /*
    3470             :                      * Create an ALTER SEQUENCE statement for the internal
    3471             :                      * sequence of the identity column.
    3472             :                      */
    3473             :                     ListCell   *lc;
    3474          24 :                     List       *newseqopts = NIL;
    3475          24 :                     List       *newdef = NIL;
    3476             :                     AttrNumber  attnum;
    3477             :                     Oid         seq_relid;
    3478             : 
    3479             :                     /*
    3480             :                      * Split options into those handled by ALTER SEQUENCE and
    3481             :                      * those for ALTER TABLE proper.
    3482             :                      */
    3483          64 :                     foreach(lc, castNode(List, cmd->def))
    3484             :                     {
    3485          40 :                         DefElem    *def = lfirst_node(DefElem, lc);
    3486             : 
    3487          40 :                         if (strcmp(def->defname, "generated") == 0)
    3488          16 :                             newdef = lappend(newdef, def);
    3489             :                         else
    3490          24 :                             newseqopts = lappend(newseqopts, def);
    3491             :                     }
    3492             : 
    3493          24 :                     attnum = get_attnum(relid, cmd->name);
    3494          24 :                     if (attnum == InvalidAttrNumber)
    3495           0 :                         ereport(ERROR,
    3496             :                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    3497             :                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
    3498             :                                         cmd->name, RelationGetRelationName(rel))));
    3499             : 
    3500          24 :                     seq_relid = getIdentitySequence(relid, attnum, true);
    3501             : 
    3502          24 :                     if (seq_relid)
    3503             :                     {
    3504             :                         AlterSeqStmt *seqstmt;
    3505             : 
    3506          16 :                         seqstmt = makeNode(AlterSeqStmt);
    3507          16 :                         seqstmt->sequence = makeRangeVar(get_namespace_name(get_rel_namespace(seq_relid)),
    3508             :                                                          get_rel_name(seq_relid), -1);
    3509          16 :                         seqstmt->options = newseqopts;
    3510          16 :                         seqstmt->for_identity = true;
    3511          16 :                         seqstmt->missing_ok = false;
    3512             : 
    3513          16 :                         cxt.blist = lappend(cxt.blist, seqstmt);
    3514             :                     }
    3515             : 
    3516             :                     /*
    3517             :                      * If column was not an identity column, we just let the
    3518             :                      * ALTER TABLE command error out later.  (There are cases
    3519             :                      * this fails to cover, but we'll need to restructure
    3520             :                      * where creation of the sequence dependency linkage
    3521             :                      * happens before we can fix it.)
    3522             :                      */
    3523             : 
    3524          24 :                     cmd->def = (Node *) newdef;
    3525          24 :                     newcmds = lappend(newcmds, cmd);
    3526          24 :                     break;
    3527             :                 }
    3528             : 
    3529        1984 :             case AT_AttachPartition:
    3530             :             case AT_DetachPartition:
    3531             :                 {
    3532        1984 :                     PartitionCmd *partcmd = (PartitionCmd *) cmd->def;
    3533             : 
    3534        1984 :                     transformPartitionCmd(&cxt, partcmd);
    3535             :                     /* assign transformed value of the partition bound */
    3536        1960 :                     partcmd->bound = cxt.partbound;
    3537             :                 }
    3538             : 
    3539        1960 :                 newcmds = lappend(newcmds, cmd);
    3540        1960 :                 break;
    3541             : 
    3542           0 :             default:
    3543             : 
    3544             :                 /*
    3545             :                  * Currently, we shouldn't actually get here for subcommand
    3546             :                  * types that don't require transformation; but if we do, just
    3547             :                  * emit them unchanged.
    3548             :                  */
    3549           0 :                 newcmds = lappend(newcmds, cmd);
    3550           0 :                 break;
    3551             :         }
    3552             :     }
    3553             : 
    3554             :     /*
    3555             :      * Transfer anything we already have in cxt.alist into save_alist, to keep
    3556             :      * it separate from the output of transformIndexConstraints.
    3557             :      */
    3558       58222 :     save_alist = cxt.alist;
    3559       58222 :     cxt.alist = NIL;
    3560             : 
    3561             :     /* Postprocess constraints */
    3562       58222 :     transformIndexConstraints(&cxt);
    3563       58214 :     transformFKConstraints(&cxt, skipValidation, true);
    3564       58214 :     transformCheckConstraints(&cxt, false);
    3565             : 
    3566             :     /*
    3567             :      * Push any index-creation commands into the ALTER, so that they can be
    3568             :      * scheduled nicely by tablecmds.c.  Note that tablecmds.c assumes that
    3569             :      * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
    3570             :      * subcommand has already been through transformIndexStmt.
    3571             :      */
    3572      140394 :     foreach(l, cxt.alist)
    3573             :     {
    3574       82180 :         Node       *istmt = (Node *) lfirst(l);
    3575             : 
    3576             :         /*
    3577             :          * We assume here that cxt.alist contains only IndexStmts and possibly
    3578             :          * ALTER TABLE SET NOT NULL statements generated from primary key
    3579             :          * constraints.  We absorb the subcommands of the latter directly.
    3580             :          */
    3581       82180 :         if (IsA(istmt, IndexStmt))
    3582             :         {
    3583       52296 :             IndexStmt  *idxstmt = (IndexStmt *) istmt;
    3584             : 
    3585       52296 :             idxstmt = transformIndexStmt(relid, idxstmt, queryString);
    3586       52296 :             newcmd = makeNode(AlterTableCmd);
    3587       52296 :             newcmd->subtype = OidIsValid(idxstmt->indexOid) ? AT_AddIndexConstraint : AT_AddIndex;
    3588       52296 :             newcmd->def = (Node *) idxstmt;
    3589       52296 :             newcmds = lappend(newcmds, newcmd);
    3590             :         }
    3591       29884 :         else if (IsA(istmt, AlterTableStmt))
    3592             :         {
    3593       29884 :             AlterTableStmt *alterstmt = (AlterTableStmt *) istmt;
    3594             : 
    3595       29884 :             newcmds = list_concat(newcmds, alterstmt->cmds);
    3596             :         }
    3597             :         else
    3598           0 :             elog(ERROR, "unexpected stmt type %d", (int) nodeTag(istmt));
    3599             :     }
    3600       58214 :     cxt.alist = NIL;
    3601             : 
    3602             :     /* Append any CHECK or FK constraints to the commands list */
    3603       58716 :     foreach(l, cxt.ckconstraints)
    3604             :     {
    3605         502 :         newcmd = makeNode(AlterTableCmd);
    3606         502 :         newcmd->subtype = AT_AddConstraint;
    3607         502 :         newcmd->def = (Node *) lfirst(l);
    3608         502 :         newcmds = lappend(newcmds, newcmd);
    3609             :     }
    3610       59686 :     foreach(l, cxt.fkconstraints)
    3611             :     {
    3612        1472 :         newcmd = makeNode(AlterTableCmd);
    3613        1472 :         newcmd->subtype = AT_AddConstraint;
    3614        1472 :         newcmd->def = (Node *) lfirst(l);
    3615        1472 :         newcmds = lappend(newcmds, newcmd);
    3616             :     }
    3617             : 
    3618             :     /* Append extended statistics objects */
    3619       58214 :     transformExtendedStatistics(&cxt);
    3620             : 
    3621             :     /* Close rel */
    3622       58214 :     relation_close(rel, NoLock);
    3623             : 
    3624             :     /*
    3625             :      * Output results.
    3626             :      */
    3627       58214 :     stmt->cmds = newcmds;
    3628             : 
    3629       58214 :     *beforeStmts = cxt.blist;
    3630       58214 :     *afterStmts = list_concat(cxt.alist, save_alist);
    3631             : 
    3632       58214 :     return stmt;
    3633             : }
    3634             : 
    3635             : 
    3636             : /*
    3637             :  * Preprocess a list of column constraint clauses
    3638             :  * to attach constraint attributes to their primary constraint nodes
    3639             :  * and detect inconsistent/misplaced constraint attributes.
    3640             :  *
    3641             :  * NOTE: currently, attributes are only supported for FOREIGN KEY, UNIQUE,
    3642             :  * EXCLUSION, and PRIMARY KEY constraints, but someday they ought to be
    3643             :  * supported for other constraint types.
    3644             :  */
    3645             : static void
    3646       50504 : transformConstraintAttrs(CreateStmtContext *cxt, List *constraintList)
    3647             : {
    3648       50504 :     Constraint *lastprimarycon = NULL;
    3649       50504 :     bool        saw_deferrability = false;
    3650       50504 :     bool        saw_initially = false;
    3651             :     ListCell   *clist;
    3652             : 
    3653             : #define SUPPORTS_ATTRS(node)                \
    3654             :     ((node) != NULL &&                      \
    3655             :      ((node)->contype == CONSTR_PRIMARY ||   \
    3656             :       (node)->contype == CONSTR_UNIQUE ||    \
    3657             :       (node)->contype == CONSTR_EXCLUSION || \
    3658             :       (node)->contype == CONSTR_FOREIGN))
    3659             : 
    3660       62602 :     foreach(clist, constraintList)
    3661             :     {
    3662       12098 :         Constraint *con = (Constraint *) lfirst(clist);
    3663             : 
    3664       12098 :         if (!IsA(con, Constraint))
    3665           0 :             elog(ERROR, "unrecognized node type: %d",
    3666             :                  (int) nodeTag(con));
    3667       12098 :         switch (con->contype)
    3668             :         {
    3669          48 :             case CONSTR_ATTR_DEFERRABLE:
    3670          48 :                 if (!SUPPORTS_ATTRS(lastprimarycon))
    3671           0 :                     ereport(ERROR,
    3672             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    3673             :                              errmsg("misplaced DEFERRABLE clause"),
    3674             :                              parser_errposition(cxt->pstate, con->location)));
    3675          48 :                 if (saw_deferrability)
    3676           0 :                     ereport(ERROR,
    3677             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    3678             :                              errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
    3679             :                              parser_errposition(cxt->pstate, con->location)));
    3680          48 :                 saw_deferrability = true;
    3681          48 :                 lastprimarycon->deferrable = true;
    3682          48 :                 break;
    3683             : 
    3684           0 :             case CONSTR_ATTR_NOT_DEFERRABLE:
    3685           0 :                 if (!SUPPORTS_ATTRS(lastprimarycon))
    3686           0 :                     ereport(ERROR,
    3687             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    3688             :                              errmsg("misplaced NOT DEFERRABLE clause"),
    3689             :                              parser_errposition(cxt->pstate, con->location)));
    3690           0 :                 if (saw_deferrability)
    3691           0 :                     ereport(ERROR,
    3692             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    3693             :                              errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
    3694             :                              parser_errposition(cxt->pstate, con->location)));
    3695           0 :                 saw_deferrability = true;
    3696           0 :                 lastprimarycon->deferrable = false;
    3697           0 :                 if (saw_initially &&
    3698           0 :                     lastprimarycon->initdeferred)
    3699           0 :                     ereport(ERROR,
    3700             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    3701             :                              errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
    3702             :                              parser_errposition(cxt->pstate, con->location)));
    3703           0 :                 break;
    3704             : 
    3705          26 :             case CONSTR_ATTR_DEFERRED:
    3706          26 :                 if (!SUPPORTS_ATTRS(lastprimarycon))
    3707           0 :                     ereport(ERROR,
    3708             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    3709             :                              errmsg("misplaced INITIALLY DEFERRED clause"),
    3710             :                              parser_errposition(cxt->pstate, con->location)));
    3711          26 :                 if (saw_initially)
    3712           0 :                     ereport(ERROR,
    3713             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    3714             :                              errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
    3715             :                              parser_errposition(cxt->pstate, con->location)));
    3716          26 :                 saw_initially = true;
    3717          26 :                 lastprimarycon->initdeferred = true;
    3718             : 
    3719             :                 /*
    3720             :                  * If only INITIALLY DEFERRED appears, assume DEFERRABLE
    3721             :                  */
    3722          26 :                 if (!saw_deferrability)
    3723           0 :                     lastprimarycon->deferrable = true;
    3724          26 :                 else if (!lastprimarycon->deferrable)
    3725           0 :                     ereport(ERROR,
    3726             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    3727             :                              errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
    3728             :                              parser_errposition(cxt->pstate, con->location)));
    3729          26 :                 break;
    3730             : 
    3731           4 :             case CONSTR_ATTR_IMMEDIATE:
    3732           4 :                 if (!SUPPORTS_ATTRS(lastprimarycon))
    3733           0 :                     ereport(ERROR,
    3734             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    3735             :                              errmsg("misplaced INITIALLY IMMEDIATE clause"),
    3736             :                              parser_errposition(cxt->pstate, con->location)));
    3737           4 :                 if (saw_initially)
    3738           0 :                     ereport(ERROR,
    3739             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    3740             :                              errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
    3741             :                              parser_errposition(cxt->pstate, con->location)));
    3742           4 :                 saw_initially = true;
    3743           4 :                 lastprimarycon->initdeferred = false;
    3744           4 :                 break;
    3745             : 
    3746       12020 :             default:
    3747             :                 /* Otherwise it's not an attribute */
    3748       12020 :                 lastprimarycon = con;
    3749             :                 /* reset flags for new primary node */
    3750       12020 :                 saw_deferrability = false;
    3751       12020 :                 saw_initially = false;
    3752       12020 :                 break;
    3753             :         }
    3754             :     }
    3755       50504 : }
    3756             : 
    3757             : /*
    3758             :  * Special handling of type definition for a column
    3759             :  */
    3760             : static void
    3761       50390 : transformColumnType(CreateStmtContext *cxt, ColumnDef *column)
    3762             : {
    3763             :     /*
    3764             :      * All we really need to do here is verify that the type is valid,
    3765             :      * including any collation spec that might be present.
    3766             :      */
    3767       50390 :     Type        ctype = typenameType(cxt->pstate, column->typeName, NULL);
    3768             : 
    3769       50384 :     if (column->collClause)
    3770             :     {
    3771         130 :         Form_pg_type typtup = (Form_pg_type) GETSTRUCT(ctype);
    3772             : 
    3773         130 :         LookupCollation(cxt->pstate,
    3774         130 :                         column->collClause->collname,
    3775         130 :                         column->collClause->location);
    3776             :         /* Complain if COLLATE is applied to an uncollatable type */
    3777         130 :         if (!OidIsValid(typtup->typcollation))
    3778           4 :             ereport(ERROR,
    3779             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    3780             :                      errmsg("collations are not supported by type %s",
    3781             :                             format_type_be(typtup->oid)),
    3782             :                      parser_errposition(cxt->pstate,
    3783             :                                         column->collClause->location)));
    3784             :     }
    3785             : 
    3786       50380 :     ReleaseSysCache(ctype);
    3787       50380 : }
    3788             : 
    3789             : 
    3790             : /*
    3791             :  * transformCreateSchemaStmt -
    3792             :  *    analyzes the CREATE SCHEMA statement
    3793             :  *
    3794             :  * Split the schema element list into individual commands and place
    3795             :  * them in the result list in an order such that there are no forward
    3796             :  * references (e.g. GRANT to a table created later in the list). Note
    3797             :  * that the logic we use for determining forward references is
    3798             :  * presently quite incomplete.
    3799             :  *
    3800             :  * SQL also allows constraints to make forward references, so thumb through
    3801             :  * the table columns and move forward references to a posterior alter-table
    3802             :  * command.
    3803             :  *
    3804             :  * The result is a list of parse nodes that still need to be analyzed ---
    3805             :  * but we can't analyze the later commands until we've executed the earlier
    3806             :  * ones, because of possible inter-object references.
    3807             :  *
    3808             :  * Note: this breaks the rules a little bit by modifying schema-name fields
    3809             :  * within passed-in structs.  However, the transformation would be the same
    3810             :  * if done over, so it should be all right to scribble on the input to this
    3811             :  * extent.
    3812             :  */
    3813             : List *
    3814         922 : transformCreateSchemaStmt(CreateSchemaStmt *stmt)
    3815             : {
    3816             :     CreateSchemaStmtContext cxt;
    3817             :     List       *result;
    3818             :     ListCell   *elements;
    3819             : 
    3820         922 :     cxt.stmtType = "CREATE SCHEMA";
    3821         922 :     cxt.schemaname = stmt->schemaname;
    3822         922 :     cxt.authrole = (RoleSpec *) stmt->authrole;
    3823         922 :     cxt.sequences = NIL;
    3824         922 :     cxt.tables = NIL;
    3825         922 :     cxt.views = NIL;
    3826         922 :     cxt.indexes = NIL;
    3827         922 :     cxt.triggers = NIL;
    3828         922 :     cxt.grants = NIL;
    3829             : 
    3830             :     /*
    3831             :      * Run through each schema element in the schema element list. Separate
    3832             :      * statements by type, and do preliminary analysis.
    3833             :      */
    3834        1102 :     foreach(elements, stmt->schemaElts)
    3835             :     {
    3836         180 :         Node       *element = lfirst(elements);
    3837             : 
    3838         180 :         switch (nodeTag(element))
    3839             :         {
    3840           0 :             case T_CreateSeqStmt:
    3841             :                 {
    3842           0 :                     CreateSeqStmt *elp = (CreateSeqStmt *) element;
    3843             : 
    3844           0 :                     setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
    3845           0 :                     cxt.sequences = lappend(cxt.sequences, element);
    3846             :                 }
    3847           0 :                 break;
    3848             : 
    3849         160 :             case T_CreateStmt:
    3850             :                 {
    3851         160 :                     CreateStmt *elp = (CreateStmt *) element;
    3852             : 
    3853         160 :                     setSchemaName(cxt.schemaname, &elp->relation->schemaname);
    3854             : 
    3855             :                     /*
    3856             :                      * XXX todo: deal with constraints
    3857             :                      */
    3858         160 :                     cxt.tables = lappend(cxt.tables, element);
    3859             :                 }
    3860         160 :                 break;
    3861             : 
    3862          10 :             case T_ViewStmt:
    3863             :                 {
    3864          10 :                     ViewStmt   *elp = (ViewStmt *) element;
    3865             : 
    3866          10 :                     setSchemaName(cxt.schemaname, &elp->view->schemaname);
    3867             : 
    3868             :                     /*
    3869             :                      * XXX todo: deal with references between views
    3870             :                      */
    3871          10 :                     cxt.views = lappend(cxt.views, element);
    3872             :                 }
    3873          10 :                 break;
    3874             : 
    3875          10 :             case T_IndexStmt:
    3876             :                 {
    3877          10 :                     IndexStmt  *elp = (IndexStmt *) element;
    3878             : 
    3879          10 :                     setSchemaName(cxt.schemaname, &elp->relation->schemaname);
    3880          10 :                     cxt.indexes = lappend(cxt.indexes, element);
    3881             :                 }
    3882          10 :                 break;
    3883             : 
    3884           0 :             case T_CreateTrigStmt:
    3885             :                 {
    3886           0 :                     CreateTrigStmt *elp = (CreateTrigStmt *) element;
    3887             : 
    3888           0 :                     setSchemaName(cxt.schemaname, &elp->relation->schemaname);
    3889           0 :                     cxt.triggers = lappend(cxt.triggers, element);
    3890             :                 }
    3891           0 :                 break;
    3892             : 
    3893           0 :             case T_GrantStmt:
    3894           0 :                 cxt.grants = lappend(cxt.grants, element);
    3895           0 :                 break;
    3896             : 
    3897           0 :             default:
    3898           0 :                 elog(ERROR, "unrecognized node type: %d",
    3899             :                      (int) nodeTag(element));
    3900             :         }
    3901             :     }
    3902             : 
    3903         922 :     result = NIL;
    3904         922 :     result = list_concat(result, cxt.sequences);
    3905         922 :     result = list_concat(result, cxt.tables);
    3906         922 :     result = list_concat(result, cxt.views);
    3907         922 :     result = list_concat(result, cxt.indexes);
    3908         922 :     result = list_concat(result, cxt.triggers);
    3909         922 :     result = list_concat(result, cxt.grants);
    3910             : 
    3911         922 :     return result;
    3912             : }
    3913             : 
    3914             : /*
    3915             :  * setSchemaName
    3916             :  *      Set or check schema name in an element of a CREATE SCHEMA command
    3917             :  */
    3918             : static void
    3919         180 : setSchemaName(char *context_schema, char **stmt_schema_name)
    3920             : {
    3921         180 :     if (*stmt_schema_name == NULL)
    3922         180 :         *stmt_schema_name = context_schema;
    3923           0 :     else if (strcmp(context_schema, *stmt_schema_name) != 0)
    3924           0 :         ereport(ERROR,
    3925             :                 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
    3926             :                  errmsg("CREATE specifies a schema (%s) "
    3927             :                         "different from the one being created (%s)",
    3928             :                         *stmt_schema_name, context_schema)));
    3929         180 : }
    3930             : 
    3931             : /*
    3932             :  * transformPartitionCmd
    3933             :  *      Analyze the ATTACH/DETACH PARTITION command
    3934             :  *
    3935             :  * In case of the ATTACH PARTITION command, cxt->partbound is set to the
    3936             :  * transformed value of cmd->bound.
    3937             :  */
    3938             : static void
    3939        1984 : transformPartitionCmd(CreateStmtContext *cxt, PartitionCmd *cmd)
    3940             : {
    3941        1984 :     Relation    parentRel = cxt->rel;
    3942             : 
    3943        1984 :     switch (parentRel->rd_rel->relkind)
    3944             :     {
    3945        1732 :         case RELKIND_PARTITIONED_TABLE:
    3946             :             /* transform the partition bound, if any */
    3947             :             Assert(RelationGetPartitionKey(parentRel) != NULL);
    3948        1732 :             if (cmd->bound != NULL)
    3949        1362 :                 cxt->partbound = transformPartitionBound(cxt->pstate, parentRel,
    3950             :                                                          cmd->bound);
    3951        1720 :             break;
    3952         244 :         case RELKIND_PARTITIONED_INDEX:
    3953             : 
    3954             :             /*
    3955             :              * A partitioned index cannot have a partition bound set.  ALTER
    3956             :              * INDEX prevents that with its grammar, but not ALTER TABLE.
    3957             :              */
    3958         244 :             if (cmd->bound != NULL)
    3959           4 :                 ereport(ERROR,
    3960             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    3961             :                          errmsg("\"%s\" is not a partitioned table",
    3962             :                                 RelationGetRelationName(parentRel))));
    3963         240 :             break;
    3964           8 :         case RELKIND_RELATION:
    3965             :             /* the table must be partitioned */
    3966           8 :             ereport(ERROR,
    3967             :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    3968             :                      errmsg("table \"%s\" is not partitioned",
    3969             :                             RelationGetRelationName(parentRel))));
    3970             :             break;
    3971           0 :         case RELKIND_INDEX:
    3972             :             /* the index must be partitioned */
    3973           0 :             ereport(ERROR,
    3974             :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    3975             :                      errmsg("index \"%s\" is not partitioned",
    3976             :                             RelationGetRelationName(parentRel))));
    3977             :             break;
    3978           0 :         default:
    3979             :             /* parser shouldn't let this case through */
    3980           0 :             elog(ERROR, "\"%s\" is not a partitioned table or index",
    3981             :                  RelationGetRelationName(parentRel));
    3982             :             break;
    3983             :     }
    3984        1960 : }
    3985             : 
    3986             : /*
    3987             :  * transformPartitionBound
    3988             :  *
    3989             :  * Transform a partition bound specification
    3990             :  */
    3991             : PartitionBoundSpec *
    3992        6098 : transformPartitionBound(ParseState *pstate, Relation parent,
    3993             :                         PartitionBoundSpec *spec)
    3994             : {
    3995             :     PartitionBoundSpec *result_spec;
    3996        6098 :     PartitionKey key = RelationGetPartitionKey(parent);
    3997        6098 :     char        strategy = get_partition_strategy(key);
    3998        6098 :     int         partnatts = get_partition_natts(key);
    3999        6098 :     List       *partexprs = get_partition_exprs(key);
    4000             : 
    4001             :     /* Avoid scribbling on input */
    4002        6098 :     result_spec = copyObject(spec);
    4003             : 
    4004        6098 :     if (spec->is_default)
    4005             :     {
    4006             :         /*
    4007             :          * Hash partitioning does not support a default partition; there's no
    4008             :          * use case for it (since the set of partitions to create is perfectly
    4009             :          * defined), and if users do get into it accidentally, it's hard to
    4010             :          * back out from it afterwards.
    4011             :          */
    4012         338 :         if (strategy == PARTITION_STRATEGY_HASH)
    4013           4 :             ereport(ERROR,
    4014             :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    4015             :                      errmsg("a hash-partitioned table may not have a default partition")));
    4016             : 
    4017             :         /*
    4018             :          * In case of the default partition, parser had no way to identify the
    4019             :          * partition strategy. Assign the parent's strategy to the default
    4020             :          * partition bound spec.
    4021             :          */
    4022         334 :         result_spec->strategy = strategy;
    4023             : 
    4024         334 :         return result_spec;
    4025             :     }
    4026             : 
    4027        5760 :     if (strategy == PARTITION_STRATEGY_HASH)
    4028             :     {
    4029         308 :         if (spec->strategy != PARTITION_STRATEGY_HASH)
    4030           8 :             ereport(ERROR,
    4031             :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    4032             :                      errmsg("invalid bound specification for a hash partition"),
    4033             :                      parser_errposition(pstate, exprLocation((Node *) spec))));
    4034             : 
    4035         300 :         if (spec->modulus <= 0)
    4036           8 :             ereport(ERROR,
    4037             :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    4038             :                      errmsg("modulus for hash partition must be an integer value greater than zero")));
    4039             : 
    4040             :         Assert(spec->remainder >= 0);
    4041             : 
    4042         292 :         if (spec->remainder >= spec->modulus)
    4043           8 :             ereport(ERROR,
    4044             :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    4045             :                      errmsg("remainder for hash partition must be less than modulus")));
    4046             :     }
    4047        5452 :     else if (strategy == PARTITION_STRATEGY_LIST)
    4048             :     {
    4049             :         ListCell   *cell;
    4050             :         char       *colname;
    4051             :         Oid         coltype;
    4052             :         int32       coltypmod;
    4053             :         Oid         partcollation;
    4054             : 
    4055        3078 :         if (spec->strategy != PARTITION_STRATEGY_LIST)
    4056          12 :             ereport(ERROR,
    4057             :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    4058             :                      errmsg("invalid bound specification for a list partition"),
    4059             :                      parser_errposition(pstate, exprLocation((Node *) spec))));
    4060             : 
    4061             :         /* Get the only column's name in case we need to output an error */
    4062        3066 :         if (key->partattrs[0] != 0)
    4063        2996 :             colname = get_attname(RelationGetRelid(parent),
    4064        2996 :                                   key->partattrs[0], false);
    4065             :         else
    4066          70 :             colname = deparse_expression((Node *) linitial(partexprs),
    4067          70 :                                          deparse_context_for(RelationGetRelationName(parent),
    4068             :                                                              RelationGetRelid(parent)),
    4069             :                                          false, false);
    4070             :         /* Need its type data too */
    4071        3066 :         coltype = get_partition_col_typid(key, 0);
    4072        3066 :         coltypmod = get_partition_col_typmod(key, 0);
    4073        3066 :         partcollation = get_partition_col_collation(key, 0);
    4074             : 
    4075        3066 :         result_spec->listdatums = NIL;
    4076        7176 :         foreach(cell, spec->listdatums)
    4077             :         {
    4078        4150 :             Node       *expr = lfirst(cell);
    4079             :             Const      *value;
    4080             :             ListCell   *cell2;
    4081             :             bool        duplicate;
    4082             : 
    4083        4150 :             value = transformPartitionBoundValue(pstate, expr,
    4084             :                                                  colname, coltype, coltypmod,
    4085             :                                                  partcollation);
    4086             : 
    4087             :             /* Don't add to the result if the value is a duplicate */
    4088        4110 :             duplicate = false;
    4089        5850 :             foreach(cell2, result_spec->listdatums)
    4090             :             {
    4091        1740 :                 Const      *value2 = lfirst_node(Const, cell2);
    4092             : 
    4093        1740 :                 if (equal(value, value2))
    4094             :                 {
    4095           0 :                     duplicate = true;
    4096           0 :                     break;
    4097             :                 }
    4098             :             }
    4099        4110 :             if (duplicate)
    4100           0 :                 continue;
    4101             : 
    4102        4110 :             result_spec->listdatums = lappend(result_spec->listdatums,
    4103             :                                               value);
    4104             :         }
    4105             :     }
    4106        2374 :     else if (strategy == PARTITION_STRATEGY_RANGE)
    4107             :     {
    4108        2374 :         if (spec->strategy != PARTITION_STRATEGY_RANGE)
    4109          12 :             ereport(ERROR,
    4110             :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    4111             :                      errmsg("invalid bound specification for a range partition"),
    4112             :                      parser_errposition(pstate, exprLocation((Node *) spec))));
    4113             : 
    4114        2362 :         if (list_length(spec->lowerdatums) != partnatts)
    4115           4 :             ereport(ERROR,
    4116             :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    4117             :                      errmsg("FROM must specify exactly one value per partitioning column")));
    4118        2358 :         if (list_length(spec->upperdatums) != partnatts)
    4119           4 :             ereport(ERROR,
    4120             :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    4121             :                      errmsg("TO must specify exactly one value per partitioning column")));
    4122             : 
    4123             :         /*
    4124             :          * Convert raw parse nodes into PartitionRangeDatum nodes and perform
    4125             :          * any necessary validation.
    4126             :          */
    4127        2310 :         result_spec->lowerdatums =
    4128        2354 :             transformPartitionRangeBounds(pstate, spec->lowerdatums,
    4129             :                                           parent);
    4130        2306 :         result_spec->upperdatums =
    4131        2310 :             transformPartitionRangeBounds(pstate, spec->upperdatums,
    4132             :                                           parent);
    4133             :     }
    4134             :     else
    4135           0 :         elog(ERROR, "unexpected partition strategy: %d", (int) strategy);
    4136             : 
    4137        5616 :     return result_spec;
    4138             : }
    4139             : 
    4140             : /*
    4141             :  * transformPartitionRangeBounds
    4142             :  *      This converts the expressions for range partition bounds from the raw
    4143             :  *      grammar representation to PartitionRangeDatum structs
    4144             :  */
    4145             : static List *
    4146        4664 : transformPartitionRangeBounds(ParseState *pstate, List *blist,
    4147             :                               Relation parent)
    4148             : {
    4149        4664 :     List       *result = NIL;
    4150        4664 :     PartitionKey key = RelationGetPartitionKey(parent);
    4151        4664 :     List       *partexprs = get_partition_exprs(key);
    4152             :     ListCell   *lc;
    4153             :     int         i,
    4154             :                 j;
    4155             : 
    4156        4664 :     i = j = 0;
    4157       10592 :     foreach(lc, blist)
    4158             :     {
    4159        5964 :         Node       *expr = lfirst(lc);
    4160        5964 :         PartitionRangeDatum *prd = NULL;
    4161             : 
    4162             :         /*
    4163             :          * Infinite range bounds -- "minvalue" and "maxvalue" -- get passed in
    4164             :          * as ColumnRefs.
    4165             :          */
    4166        5964 :         if (IsA(expr, ColumnRef))
    4167             :         {
    4168         480 :             ColumnRef  *cref = (ColumnRef *) expr;
    4169         480 :             char       *cname = NULL;
    4170             : 
    4171             :             /*
    4172             :              * There should be a single field named either "minvalue" or
    4173             :              * "maxvalue".
    4174             :              */
    4175         480 :             if (list_length(cref->fields) == 1 &&
    4176         476 :                 IsA(linitial(cref->fields), String))
    4177         476 :                 cname = strVal(linitial(cref->fields));
    4178             : 
    4179         480 :             if (cname == NULL)
    4180             :             {
    4181             :                 /*
    4182             :                  * ColumnRef is not in the desired single-field-name form. For
    4183             :                  * consistency between all partition strategies, let the
    4184             :                  * expression transformation report any errors rather than
    4185             :                  * doing it ourselves.
    4186             :                  */
    4187             :             }
    4188         476 :             else if (strcmp("minvalue", cname) == 0)
    4189             :             {
    4190         242 :                 prd = makeNode(PartitionRangeDatum);
    4191         242 :                 prd->kind = PARTITION_RANGE_DATUM_MINVALUE;
    4192         242 :                 prd->value = NULL;
    4193             :             }
    4194         234 :             else if (strcmp("maxvalue", cname) == 0)
    4195             :             {
    4196         226 :                 prd = makeNode(PartitionRangeDatum);
    4197         226 :                 prd->kind = PARTITION_RANGE_DATUM_MAXVALUE;
    4198         226 :                 prd->value = NULL;
    4199             :             }
    4200             :         }
    4201             : 
    4202        5964 :         if (prd == NULL)
    4203             :         {
    4204             :             char       *colname;
    4205             :             Oid         coltype;
    4206             :             int32       coltypmod;
    4207             :             Oid         partcollation;
    4208             :             Const      *value;
    4209             : 
    4210             :             /* Get the column's name in case we need to output an error */
    4211        5496 :             if (key->partattrs[i] != 0)
    4212        4928 :                 colname = get_attname(RelationGetRelid(parent),
    4213        4928 :                                       key->partattrs[i], false);
    4214             :             else
    4215             :             {
    4216         568 :                 colname = deparse_expression((Node *) list_nth(partexprs, j),
    4217         568 :                                              deparse_context_for(RelationGetRelationName(parent),
    4218             :                                                                  RelationGetRelid(parent)),
    4219             :                                              false, false);
    4220         568 :                 ++j;
    4221             :             }
    4222             : 
    4223             :             /* Need its type data too */
    4224        5496 :             coltype = get_partition_col_typid(key, i);
    4225        5496 :             coltypmod = get_partition_col_typmod(key, i);
    4226        5496 :             partcollation = get_partition_col_collation(key, i);
    4227             : 
    4228        5496 :             value = transformPartitionBoundValue(pstate, expr,
    4229             :                                                  colname,
    4230             :                                                  coltype, coltypmod,
    4231             :                                                  partcollation);
    4232        5464 :             if (value->constisnull)
    4233           4 :                 ereport(ERROR,
    4234             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    4235             :                          errmsg("cannot specify NULL in range bound")));
    4236        5460 :             prd = makeNode(PartitionRangeDatum);
    4237        5460 :             prd->kind = PARTITION_RANGE_DATUM_VALUE;
    4238        5460 :             prd->value = (Node *) value;
    4239        5460 :             ++i;
    4240             :         }
    4241             : 
    4242        5928 :         prd->location = exprLocation(expr);
    4243             : 
    4244        5928 :         result = lappend(result, prd);
    4245             :     }
    4246             : 
    4247             :     /*
    4248             :      * Once we see MINVALUE or MAXVALUE for one column, the remaining columns
    4249             :      * must be the same.
    4250             :      */
    4251        4628 :     validateInfiniteBounds(pstate, result);
    4252             : 
    4253        4616 :     return result;
    4254             : }
    4255             : 
    4256             : /*
    4257             :  * validateInfiniteBounds
    4258             :  *
    4259             :  * Check that a MAXVALUE or MINVALUE specification in a partition bound is
    4260             :  * followed only by more of the same.
    4261             :  */
    4262             : static void
    4263        4628 : validateInfiniteBounds(ParseState *pstate, List *blist)
    4264             : {
    4265             :     ListCell   *lc;
    4266        4628 :     PartitionRangeDatumKind kind = PARTITION_RANGE_DATUM_VALUE;
    4267             : 
    4268       10540 :     foreach(lc, blist)
    4269             :     {
    4270        5924 :         PartitionRangeDatum *prd = lfirst_node(PartitionRangeDatum, lc);
    4271             : 
    4272        5924 :         if (kind == prd->kind)
    4273        5584 :             continue;
    4274             : 
    4275         340 :         switch (kind)
    4276             :         {
    4277         328 :             case PARTITION_RANGE_DATUM_VALUE:
    4278         328 :                 kind = prd->kind;
    4279         328 :                 break;
    4280             : 
    4281           4 :             case PARTITION_RANGE_DATUM_MAXVALUE:
    4282           4 :                 ereport(ERROR,
    4283             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    4284             :                          errmsg("every bound following MAXVALUE must also be MAXVALUE"),
    4285             :                          parser_errposition(pstate, exprLocation((Node *) prd))));
    4286             :                 break;
    4287             : 
    4288           8 :             case PARTITION_RANGE_DATUM_MINVALUE:
    4289           8 :                 ereport(ERROR,
    4290             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    4291             :                          errmsg("every bound following MINVALUE must also be MINVALUE"),
    4292             :                          parser_errposition(pstate, exprLocation((Node *) prd))));
    4293             :                 break;
    4294             :         }
    4295        5912 :     }
    4296        4616 : }
    4297             : 
    4298             : /*
    4299             :  * Transform one entry in a partition bound spec, producing a constant.
    4300             :  */
    4301             : static Const *
    4302        9646 : transformPartitionBoundValue(ParseState *pstate, Node *val,
    4303             :                              const char *colName, Oid colType, int32 colTypmod,
    4304             :                              Oid partCollation)
    4305             : {
    4306             :     Node       *value;
    4307             : 
    4308             :     /* Transform raw parsetree */
    4309        9646 :     value = transformExpr(pstate, val, EXPR_KIND_PARTITION_BOUND);
    4310             : 
    4311             :     /*
    4312             :      * transformExpr() should have already rejected column references,
    4313             :      * subqueries, aggregates, window functions, and SRFs, based on the
    4314             :      * EXPR_KIND_ of a partition bound expression.
    4315             :      */
    4316             :     Assert(!contain_var_clause(value));
    4317             : 
    4318             :     /*
    4319             :      * Coerce to the correct type.  This might cause an explicit coercion step
    4320             :      * to be added on top of the expression, which must be evaluated before
    4321             :      * returning the result to the caller.
    4322             :      */
    4323        9578 :     value = coerce_to_target_type(pstate,
    4324             :                                   value, exprType(value),
    4325             :                                   colType,
    4326             :                                   colTypmod,
    4327             :                                   COERCION_ASSIGNMENT,
    4328             :                                   COERCE_IMPLICIT_CAST,
    4329             :                                   -1);
    4330             : 
    4331        9578 :     if (value == NULL)
    4332           4 :         ereport(ERROR,
    4333             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    4334             :                  errmsg("specified value cannot be cast to type %s for column \"%s\"",
    4335             :                         format_type_be(colType), colName),
    4336             :                  parser_errposition(pstate, exprLocation(val))));
    4337             : 
    4338             :     /*
    4339             :      * Evaluate the expression, if needed, assigning the partition key's data
    4340             :      * type and collation to the resulting Const node.
    4341             :      */
    4342        9574 :     if (!IsA(value, Const))
    4343             :     {
    4344         282 :         assign_expr_collations(pstate, value);
    4345         282 :         value = (Node *) expression_planner((Expr *) value);
    4346         282 :         value = (Node *) evaluate_expr((Expr *) value, colType, colTypmod,
    4347             :                                        partCollation);
    4348         282 :         if (!IsA(value, Const))
    4349           0 :             elog(ERROR, "could not evaluate partition bound expression");
    4350             :     }
    4351             :     else
    4352             :     {
    4353             :         /*
    4354             :          * If the expression is already a Const, as is often the case, we can
    4355             :          * skip the rather expensive steps above.  But we still have to insert
    4356             :          * the right collation, since coerce_to_target_type doesn't handle
    4357             :          * that.
    4358             :          */
    4359        9292 :         ((Const *) value)->constcollid = partCollation;
    4360             :     }
    4361             : 
    4362             :     /*
    4363             :      * Attach original expression's parse location to the Const, so that
    4364             :      * that's what will be reported for any later errors related to this
    4365             :      * partition bound.
    4366             :      */
    4367        9574 :     ((Const *) value)->location = exprLocation(val);
    4368             : 
    4369        9574 :     return (Const *) value;
    4370             : }

Generated by: LCOV version 1.14