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

Generated by: LCOV version 1.16