LCOV - code coverage report
Current view: top level - src/backend/parser - parse_utilcmd.c (source / functions) Hit Total Coverage
Test: PostgreSQL 19devel Lines: 1468 1628 90.2 %
Date: 2025-07-09 20:18:08 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       39306 : 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       39306 :     pstate = make_parsestate(NULL);
     177       39306 :     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       39306 :     setup_parser_errposition_callback(&pcbstate, pstate,
     186       39306 :                                       stmt->relation->location);
     187             :     namespaceid =
     188       39306 :         RangeVarGetAndCheckCreationNamespace(stmt->relation, NoLock,
     189             :                                              &existing_relid);
     190       39294 :     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       39294 :     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       39284 :     if (stmt->relation->schemaname == NULL
     223       34584 :         && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
     224       32250 :         stmt->relation->schemaname = get_namespace_name(namespaceid);
     225             : 
     226             :     /* Set up CreateStmtContext */
     227       39284 :     cxt.pstate = pstate;
     228       39284 :     if (IsA(stmt, CreateForeignTableStmt))
     229             :     {
     230         484 :         cxt.stmtType = "CREATE FOREIGN TABLE";
     231         484 :         cxt.isforeign = true;
     232             :     }
     233             :     else
     234             :     {
     235       38800 :         cxt.stmtType = "CREATE TABLE";
     236       38800 :         cxt.isforeign = false;
     237             :     }
     238       39284 :     cxt.relation = stmt->relation;
     239       39284 :     cxt.rel = NULL;
     240       39284 :     cxt.inhRelations = stmt->inhRelations;
     241       39284 :     cxt.isalter = false;
     242       39284 :     cxt.columns = NIL;
     243       39284 :     cxt.ckconstraints = NIL;
     244       39284 :     cxt.nnconstraints = NIL;
     245       39284 :     cxt.fkconstraints = NIL;
     246       39284 :     cxt.ixconstraints = NIL;
     247       39284 :     cxt.likeclauses = NIL;
     248       39284 :     cxt.blist = NIL;
     249       39284 :     cxt.alist = NIL;
     250       39284 :     cxt.pkey = NULL;
     251       39284 :     cxt.ispartitioned = stmt->partspec != NULL;
     252       39284 :     cxt.partbound = stmt->partbound;
     253       39284 :     cxt.ofType = (stmt->ofTypename != NULL);
     254             : 
     255             :     Assert(!stmt->ofTypename || !stmt->inhRelations); /* grammar enforces */
     256             : 
     257       39284 :     if (stmt->ofTypename)
     258         134 :         transformOfType(&cxt, stmt->ofTypename);
     259             : 
     260       39266 :     if (stmt->partspec)
     261             :     {
     262        5152 :         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      113286 :     foreach(elements, stmt->tableElts)
     273             :     {
     274       74268 :         Node       *element = lfirst(elements);
     275             : 
     276       74268 :         switch (nodeTag(element))
     277             :         {
     278       70668 :             case T_ColumnDef:
     279       70668 :                 transformColumnDefinition(&cxt, (ColumnDef *) element);
     280       70450 :                 break;
     281             : 
     282        2826 :             case T_Constraint:
     283        2826 :                 transformTableConstraint(&cxt, (Constraint *) element);
     284        2814 :                 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       39018 :     save_alist = cxt.alist;
     304       39018 :     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       90252 :     foreach_node(Constraint, nn, cxt.nnconstraints)
     317             :     {
     318       12216 :         char       *colname = strVal(linitial(nn->keys));
     319             : 
     320       28788 :         foreach_node(ColumnDef, cd, cxt.columns)
     321             :         {
     322             :             /* not our column? */
     323       16536 :             if (strcmp(cd->colname, colname) != 0)
     324        4356 :                 continue;
     325             :             /* Already marked not-null? Nothing to do */
     326       12180 :             if (cd->is_not_null)
     327       11684 :                 break;
     328             :             /* Bingo, we're done for this constraint */
     329         496 :             cd->is_not_null = true;
     330         496 :             break;
     331             :         }
     332             :     }
     333             : 
     334             :     /*
     335             :      * Postprocess constraints that give rise to index definitions.
     336             :      */
     337       39018 :     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       38976 :     cxt.alist = list_concat(cxt.alist, cxt.likeclauses);
     352             : 
     353             :     /*
     354             :      * Postprocess foreign-key constraints.
     355             :      */
     356       38976 :     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       38976 :     transformCheckConstraints(&cxt, !cxt.isforeign);
     365             : 
     366             :     /*
     367             :      * Output results.
     368             :      */
     369       38976 :     stmt->tableElts = cxt.columns;
     370       38976 :     stmt->constraints = cxt.ckconstraints;
     371       38976 :     stmt->nnconstraints = cxt.nnconstraints;
     372             : 
     373       38976 :     result = lappend(cxt.blist, stmt);
     374       38976 :     result = list_concat(result, cxt.alist);
     375       38976 :     result = list_concat(result, save_alist);
     376             : 
     377       38976 :     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        1340 : 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        1340 :     DefElem    *nameEl = NULL;
     397        1340 :     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        1340 :     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        1984 :     foreach(option, seqoptions)
     415             :     {
     416         644 :         DefElem    *defel = lfirst_node(DefElem, option);
     417             : 
     418         644 :         if (strcmp(defel->defname, "sequence_name") == 0)
     419             :         {
     420          88 :             if (nameEl)
     421           0 :                 errorConflictingDefElem(defel, cxt->pstate);
     422          88 :             nameEl = defel;
     423          88 :             seqoptions = foreach_delete_current(seqoptions, option);
     424             :         }
     425         556 :         else if (strcmp(defel->defname, "logged") == 0 ||
     426         552 :                  strcmp(defel->defname, "unlogged") == 0)
     427             :         {
     428           8 :             if (loggedEl)
     429           0 :                 errorConflictingDefElem(defel, cxt->pstate);
     430           8 :             loggedEl = defel;
     431           8 :             seqoptions = foreach_delete_current(seqoptions, option);
     432             :         }
     433             :     }
     434             : 
     435             :     /*
     436             :      * Determine namespace and name to use for the sequence.
     437             :      */
     438        1340 :     if (nameEl)
     439             :     {
     440             :         /* Use specified name */
     441          88 :         RangeVar   *rv = makeRangeVarFromNameList(castNode(List, nameEl->arg));
     442             : 
     443          88 :         snamespace = rv->schemaname;
     444          88 :         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          88 :         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        1252 :         if (cxt->rel)
     469         202 :             snamespaceid = RelationGetNamespace(cxt->rel);
     470             :         else
     471             :         {
     472        1050 :             snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
     473        1050 :             RangeVarAdjustRelationPersistence(cxt->relation, snamespaceid);
     474             :         }
     475        1252 :         snamespace = get_namespace_name(snamespaceid);
     476        1252 :         sname = ChooseRelationName(cxt->relation->relname,
     477        1252 :                                    column->colname,
     478             :                                    "seq",
     479             :                                    snamespaceid,
     480             :                                    false);
     481             :     }
     482             : 
     483        1340 :     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        1340 :     seqpersistence = cxt->rel ? cxt->rel->rd_rel->relpersistence : cxt->relation->relpersistence;
     499        1340 :     if (loggedEl)
     500             :     {
     501           8 :         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           8 :         else if (strcmp(loggedEl->defname, "logged") == 0)
     507           4 :             seqpersistence = RELPERSISTENCE_PERMANENT;
     508             :         else
     509           4 :             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        1340 :     seqstmt = makeNode(CreateSeqStmt);
     517        1340 :     seqstmt->for_identity = for_identity;
     518        1340 :     seqstmt->sequence = makeRangeVar(snamespace, sname, -1);
     519        1340 :     seqstmt->sequence->relpersistence = seqpersistence;
     520        1340 :     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        1340 :     if (seqtypid)
     529        1328 :         seqstmt->options = lcons(makeDefElem("as",
     530        1328 :                                              (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        1340 :     if (cxt->rel)
     542         290 :         seqstmt->ownerId = cxt->rel->rd_rel->relowner;
     543             :     else
     544        1050 :         seqstmt->ownerId = InvalidOid;
     545             : 
     546        1340 :     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        1340 :     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        1340 :     altseqstmt = makeNode(AlterSeqStmt);
     566        1340 :     altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
     567        1340 :     attnamelist = list_make3(makeString(snamespace),
     568             :                              makeString(cxt->relation->relname),
     569             :                              makeString(column->colname));
     570        1340 :     altseqstmt->options = list_make1(makeDefElem("owned_by",
     571             :                                                  (Node *) attnamelist, -1));
     572        1340 :     altseqstmt->for_identity = for_identity;
     573             : 
     574        1340 :     if (col_exists)
     575         204 :         cxt->blist = lappend(cxt->blist, altseqstmt);
     576             :     else
     577        1136 :         cxt->alist = lappend(cxt->alist, altseqstmt);
     578             : 
     579        1340 :     if (snamespace_p)
     580         834 :         *snamespace_p = snamespace;
     581        1340 :     if (sname_p)
     582         834 :         *sname_p = sname;
     583        1340 : }
     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       72718 : 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       72718 :     bool        need_notnull = false;
     599       72718 :     bool        disallow_noinherit_notnull = false;
     600       72718 :     Constraint *notnull_constraint = NULL;
     601             : 
     602       72718 :     cxt->columns = lappend(cxt->columns, column);
     603             : 
     604             :     /* Check for SERIAL pseudo-types */
     605       72718 :     is_serial = false;
     606       72718 :     if (column->typeName
     607       72364 :         && list_length(column->typeName->names) == 1
     608       29446 :         && !column->typeName->pct_type)
     609             :     {
     610       29446 :         char       *typname = strVal(linitial(column->typeName->names));
     611             : 
     612       29446 :         if (strcmp(typname, "smallserial") == 0 ||
     613       29438 :             strcmp(typname, "serial2") == 0)
     614             :         {
     615          14 :             is_serial = true;
     616          14 :             column->typeName->names = NIL;
     617          14 :             column->typeName->typeOid = INT2OID;
     618             :         }
     619       29432 :         else if (strcmp(typname, "serial") == 0 ||
     620       28634 :                  strcmp(typname, "serial4") == 0)
     621             :         {
     622         798 :             is_serial = true;
     623         798 :             column->typeName->names = NIL;
     624         798 :             column->typeName->typeOid = INT4OID;
     625             :         }
     626       28634 :         else if (strcmp(typname, "bigserial") == 0 ||
     627       28624 :                  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       29446 :         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       72718 :     if (column->typeName)
     649       72364 :         transformColumnType(cxt, column);
     650             : 
     651             :     /* Special actions for SERIAL pseudo-types */
     652       72680 :     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         834 :         generateSerialExtraStmts(cxt, column,
     663         834 :                                  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         834 :         qstring = quote_qualified_identifier(snamespace, sname);
     678         834 :         snamenode = makeNode(A_Const);
     679         834 :         snamenode->val.node.type = T_String;
     680         834 :         snamenode->val.sval.sval = qstring;
     681         834 :         snamenode->location = -1;
     682         834 :         castnode = makeNode(TypeCast);
     683         834 :         castnode->typeName = SystemTypeName("regclass");
     684         834 :         castnode->arg = (Node *) snamenode;
     685         834 :         castnode->location = -1;
     686         834 :         funccallnode = makeFuncCall(SystemFuncName("nextval"),
     687         834 :                                     list_make1(castnode),
     688             :                                     COERCE_EXPLICIT_CALL,
     689             :                                     -1);
     690         834 :         constraint = makeNode(Constraint);
     691         834 :         constraint->contype = CONSTR_DEFAULT;
     692         834 :         constraint->location = -1;
     693         834 :         constraint->raw_expr = (Node *) funccallnode;
     694         834 :         constraint->cooked_expr = NULL;
     695         834 :         column->constraints = lappend(column->constraints, constraint);
     696             : 
     697             :         /* have a not-null constraint added later */
     698         834 :         need_notnull = true;
     699         834 :         disallow_noinherit_notnull = true;
     700             :     }
     701             : 
     702             :     /* Process column constraints, if any... */
     703       72680 :     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       72656 :     if (!disallow_noinherit_notnull)
     718             :     {
     719      161492 :         foreach_node(Constraint, constraint, column->constraints)
     720             :         {
     721       17848 :             switch (constraint->contype)
     722             :             {
     723        5584 :                 case CONSTR_IDENTITY:
     724             :                 case CONSTR_PRIMARY:
     725        5584 :                     disallow_noinherit_notnull = true;
     726        5584 :                     break;
     727       12264 :                 default:
     728       12264 :                     break;
     729             :             }
     730             :         }
     731             :     }
     732             : 
     733             :     /* Now scan them again to do full processing */
     734       72656 :     saw_nullable = false;
     735       72656 :     saw_default = false;
     736       72656 :     saw_identity = false;
     737       72656 :     saw_generated = false;
     738             : 
     739      164212 :     foreach_node(Constraint, constraint, column->constraints)
     740             :     {
     741       19224 :         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        6922 :             case CONSTR_NOTNULL:
     756        6922 :                 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        6916 :                 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        6916 :                 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        6886 :                 if (!column->is_not_null)
     788             :                 {
     789        6862 :                     column->is_not_null = true;
     790        6862 :                     saw_nullable = true;
     791        6862 :                     need_notnull = false;
     792             : 
     793        6862 :                     constraint->keys = list_make1(makeString(column->colname));
     794        6862 :                     notnull_constraint = constraint;
     795        6862 :                     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        6880 :                 break;
     816             : 
     817        2524 :             case CONSTR_DEFAULT:
     818        2524 :                 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        2524 :                 column->raw_default = constraint->raw_expr;
     826             :                 Assert(constraint->cooked_expr == NULL);
     827        2524 :                 saw_default = true;
     828        2524 :                 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        1840 :             case CONSTR_GENERATED:
     881        1840 :                 if (cxt->ofType)
     882          12 :                     ereport(ERROR,
     883             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     884             :                              errmsg("generated columns are not supported on typed tables")));
     885        1828 :                 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        1816 :                 column->generated = constraint->generated_kind;
     893        1816 :                 column->raw_default = constraint->raw_expr;
     894             :                 Assert(constraint->cooked_expr == NULL);
     895        1816 :                 saw_generated = true;
     896        1816 :                 break;
     897             : 
     898         500 :             case CONSTR_CHECK:
     899         500 :                 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
     900         500 :                 break;
     901             : 
     902        5688 :             case CONSTR_PRIMARY:
     903        5688 :                 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        5688 :                 need_notnull = true;
     911             : 
     912        5688 :                 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        6036 :                 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        6036 :                 if (constraint->keys == NIL)
     928        6036 :                     constraint->keys = list_make1(makeString(column->colname));
     929        6036 :                 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
     930        6036 :                 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         810 :             case CONSTR_FOREIGN:
     938         810 :                 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         804 :                 constraint->fk_attrs = list_make1(makeString(column->colname));
     950         804 :                 cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
     951         804 :                 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       19098 :         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       19086 :         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       19074 :         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       72494 :     if (need_notnull && !(saw_nullable && column->is_not_null))
     998             :     {
     999        5112 :         column->is_not_null = true;
    1000        5112 :         notnull_constraint = makeNotNullConstraint(makeString(column->colname));
    1001        5112 :         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       72494 :     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       72494 : }
    1029             : 
    1030             : /*
    1031             :  * transformTableConstraint
    1032             :  *      transform a Constraint node within CREATE TABLE or ALTER TABLE
    1033             :  */
    1034             : static void
    1035       19904 : transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
    1036             : {
    1037       19904 :     switch (constraint->contype)
    1038             :     {
    1039        8478 :         case CONSTR_PRIMARY:
    1040        8478 :             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        8472 :             cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
    1047        8472 :             break;
    1048             : 
    1049        5348 :         case CONSTR_UNIQUE:
    1050        5348 :             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        5342 :             cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
    1057        5342 :             break;
    1058             : 
    1059         238 :         case CONSTR_EXCLUSION:
    1060         238 :             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         238 :             cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
    1067         238 :             break;
    1068             : 
    1069        1464 :         case CONSTR_CHECK:
    1070        1464 :             cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
    1071        1464 :             break;
    1072             : 
    1073        1114 :         case CONSTR_NOTNULL:
    1074        1114 :             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        1108 :             cxt->nnconstraints = lappend(cxt->nnconstraints, constraint);
    1080        1108 :             break;
    1081             : 
    1082        3262 :         case CONSTR_FOREIGN:
    1083        3262 :             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        3262 :             cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
    1090        3262 :             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       19886 : }
    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         228 :         for (ccnum = 0; ccnum < constr->num_check; ccnum++)
    1460             :         {
    1461         126 :             char       *ccname = constr->check[ccnum].ccname;
    1462         126 :             char       *ccbin = constr->check[ccnum].ccbin;
    1463         126 :             bool        ccenforced = constr->check[ccnum].ccenforced;
    1464         126 :             bool        ccvalid = constr->check[ccnum].ccvalid;
    1465         126 :             bool        ccnoinherit = constr->check[ccnum].ccnoinherit;
    1466             :             Node       *ccbin_node;
    1467             :             bool        found_whole_row;
    1468             :             Constraint *n;
    1469             :             AlterTableCmd *atsubcmd;
    1470             : 
    1471         126 :             ccbin_node = map_variable_attnos(stringToNode(ccbin),
    1472             :                                              1, 0,
    1473             :                                              attmap,
    1474             :                                              InvalidOid, &found_whole_row);
    1475             : 
    1476             :             /*
    1477             :              * We reject whole-row variables because the whole point of LIKE
    1478             :              * is that the new table's rowtype might later diverge from the
    1479             :              * parent's.  So, while translation might be possible right now,
    1480             :              * it wouldn't be possible to guarantee it would work in future.
    1481             :              */
    1482         126 :             if (found_whole_row)
    1483           0 :                 ereport(ERROR,
    1484             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1485             :                          errmsg("cannot convert whole-row table reference"),
    1486             :                          errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
    1487             :                                    ccname,
    1488             :                                    RelationGetRelationName(relation))));
    1489             : 
    1490         126 :             n = makeNode(Constraint);
    1491         126 :             n->contype = CONSTR_CHECK;
    1492         126 :             n->conname = pstrdup(ccname);
    1493         126 :             n->location = -1;
    1494         126 :             n->is_enforced = ccenforced;
    1495         126 :             n->initially_valid = ccvalid;
    1496         126 :             n->is_no_inherit = ccnoinherit;
    1497         126 :             n->raw_expr = NULL;
    1498         126 :             n->cooked_expr = nodeToString(ccbin_node);
    1499             : 
    1500             :             /* We can skip validation, since the new table should be empty. */
    1501         126 :             n->skip_validation = true;
    1502             : 
    1503         126 :             atsubcmd = makeNode(AlterTableCmd);
    1504         126 :             atsubcmd->subtype = AT_AddConstraint;
    1505         126 :             atsubcmd->def = (Node *) n;
    1506         126 :             atsubcmds = lappend(atsubcmds, atsubcmd);
    1507             : 
    1508             :             /* Copy comment on constraint */
    1509         216 :             if ((table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS) &&
    1510          90 :                 (comment = GetComment(get_relation_constraint_oid(RelationGetRelid(relation),
    1511          90 :                                                                   n->conname, false),
    1512             :                                       ConstraintRelationId,
    1513             :                                       0)) != NULL)
    1514             :             {
    1515          30 :                 CommentStmt *stmt = makeNode(CommentStmt);
    1516             : 
    1517          30 :                 stmt->objtype = OBJECT_TABCONSTRAINT;
    1518          30 :                 stmt->object = (Node *) list_make3(makeString(heapRel->schemaname),
    1519             :                                                    makeString(heapRel->relname),
    1520             :                                                    makeString(n->conname));
    1521          30 :                 stmt->comment = comment;
    1522             : 
    1523          30 :                 result = lappend(result, stmt);
    1524             :             }
    1525             :         }
    1526             :     }
    1527             : 
    1528             :     /*
    1529             :      * If we generated any ALTER TABLE actions above, wrap them into a single
    1530             :      * ALTER TABLE command.  Stick it at the front of the result, so it runs
    1531             :      * before any CommentStmts we made above.
    1532             :      */
    1533         194 :     if (atsubcmds)
    1534             :     {
    1535         134 :         AlterTableStmt *atcmd = makeNode(AlterTableStmt);
    1536             : 
    1537         134 :         atcmd->relation = copyObject(heapRel);
    1538         134 :         atcmd->cmds = atsubcmds;
    1539         134 :         atcmd->objtype = OBJECT_TABLE;
    1540         134 :         atcmd->missing_ok = false;
    1541         134 :         result = lcons(atcmd, result);
    1542             :     }
    1543             : 
    1544             :     /*
    1545             :      * Process indexes if required.
    1546             :      */
    1547         194 :     if ((table_like_clause->options & CREATE_TABLE_LIKE_INDEXES) &&
    1548         110 :         relation->rd_rel->relhasindex &&
    1549          86 :         childrel->rd_rel->relkind != RELKIND_FOREIGN_TABLE)
    1550             :     {
    1551             :         List       *parent_indexes;
    1552             :         ListCell   *l;
    1553             : 
    1554          80 :         parent_indexes = RelationGetIndexList(relation);
    1555             : 
    1556         210 :         foreach(l, parent_indexes)
    1557             :         {
    1558         130 :             Oid         parent_index_oid = lfirst_oid(l);
    1559             :             Relation    parent_index;
    1560             :             IndexStmt  *index_stmt;
    1561             : 
    1562         130 :             parent_index = index_open(parent_index_oid, AccessShareLock);
    1563             : 
    1564             :             /* Build CREATE INDEX statement to recreate the parent_index */
    1565         130 :             index_stmt = generateClonedIndexStmt(heapRel,
    1566             :                                                  parent_index,
    1567             :                                                  attmap,
    1568             :                                                  NULL);
    1569             : 
    1570             :             /* Copy comment on index, if requested */
    1571         130 :             if (table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS)
    1572             :             {
    1573          72 :                 comment = GetComment(parent_index_oid, RelationRelationId, 0);
    1574             : 
    1575             :                 /*
    1576             :                  * We make use of IndexStmt's idxcomment option, so as not to
    1577             :                  * need to know now what name the index will have.
    1578             :                  */
    1579          72 :                 index_stmt->idxcomment = comment;
    1580             :             }
    1581             : 
    1582         130 :             result = lappend(result, index_stmt);
    1583             : 
    1584         130 :             index_close(parent_index, AccessShareLock);
    1585             :         }
    1586             :     }
    1587             : 
    1588             :     /*
    1589             :      * Process extended statistics if required.
    1590             :      */
    1591         194 :     if (table_like_clause->options & CREATE_TABLE_LIKE_STATISTICS)
    1592             :     {
    1593             :         List       *parent_extstats;
    1594             :         ListCell   *l;
    1595             : 
    1596          60 :         parent_extstats = RelationGetStatExtList(relation);
    1597             : 
    1598         108 :         foreach(l, parent_extstats)
    1599             :         {
    1600          48 :             Oid         parent_stat_oid = lfirst_oid(l);
    1601             :             CreateStatsStmt *stats_stmt;
    1602             : 
    1603          48 :             stats_stmt = generateClonedExtStatsStmt(heapRel,
    1604             :                                                     RelationGetRelid(childrel),
    1605             :                                                     parent_stat_oid,
    1606             :                                                     attmap);
    1607             : 
    1608             :             /* Copy comment on statistics object, if requested */
    1609          48 :             if (table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS)
    1610             :             {
    1611          48 :                 comment = GetComment(parent_stat_oid, StatisticExtRelationId, 0);
    1612             : 
    1613             :                 /*
    1614             :                  * We make use of CreateStatsStmt's stxcomment option, so as
    1615             :                  * not to need to know now what name the statistics will have.
    1616             :                  */
    1617          48 :                 stats_stmt->stxcomment = comment;
    1618             :             }
    1619             : 
    1620          48 :             result = lappend(result, stats_stmt);
    1621             :         }
    1622             : 
    1623          60 :         list_free(parent_extstats);
    1624             :     }
    1625             : 
    1626             :     /* Done with child rel */
    1627         194 :     table_close(childrel, NoLock);
    1628             : 
    1629             :     /*
    1630             :      * Close the parent rel, but keep our AccessShareLock on it until xact
    1631             :      * commit.  That will prevent someone else from deleting or ALTERing the
    1632             :      * parent before the child is committed.
    1633             :      */
    1634         194 :     table_close(relation, NoLock);
    1635             : 
    1636         194 :     return result;
    1637             : }
    1638             : 
    1639             : static void
    1640         134 : transformOfType(CreateStmtContext *cxt, TypeName *ofTypename)
    1641             : {
    1642             :     HeapTuple   tuple;
    1643             :     TupleDesc   tupdesc;
    1644             :     int         i;
    1645             :     Oid         ofTypeId;
    1646             : 
    1647             :     Assert(ofTypename);
    1648             : 
    1649         134 :     tuple = typenameType(cxt->pstate, ofTypename, NULL);
    1650         128 :     check_of_type(tuple);
    1651         116 :     ofTypeId = ((Form_pg_type) GETSTRUCT(tuple))->oid;
    1652         116 :     ofTypename->typeOid = ofTypeId; /* cached for later */
    1653             : 
    1654         116 :     tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
    1655         344 :     for (i = 0; i < tupdesc->natts; i++)
    1656             :     {
    1657         228 :         Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
    1658             :         ColumnDef  *n;
    1659             : 
    1660         228 :         if (attr->attisdropped)
    1661           0 :             continue;
    1662             : 
    1663         228 :         n = makeColumnDef(NameStr(attr->attname), attr->atttypid,
    1664             :                           attr->atttypmod, attr->attcollation);
    1665         228 :         n->is_from_type = true;
    1666             : 
    1667         228 :         cxt->columns = lappend(cxt->columns, n);
    1668             :     }
    1669         116 :     ReleaseTupleDesc(tupdesc);
    1670             : 
    1671         116 :     ReleaseSysCache(tuple);
    1672         116 : }
    1673             : 
    1674             : /*
    1675             :  * Generate an IndexStmt node using information from an already existing index
    1676             :  * "source_idx".
    1677             :  *
    1678             :  * heapRel is stored into the IndexStmt's relation field, but we don't use it
    1679             :  * otherwise; some callers pass NULL, if they don't need it to be valid.
    1680             :  * (The target relation might not exist yet, so we mustn't try to access it.)
    1681             :  *
    1682             :  * Attribute numbers in expression Vars are adjusted according to attmap.
    1683             :  *
    1684             :  * If constraintOid isn't NULL, we store the OID of any constraint associated
    1685             :  * with the index there.
    1686             :  *
    1687             :  * Unlike transformIndexConstraint, we don't make any effort to force primary
    1688             :  * key columns to be not-null.  The larger cloning process this is part of
    1689             :  * should have cloned their not-null status separately (and DefineIndex will
    1690             :  * complain if that fails to happen).
    1691             :  */
    1692             : IndexStmt *
    1693        2590 : generateClonedIndexStmt(RangeVar *heapRel, Relation source_idx,
    1694             :                         const AttrMap *attmap,
    1695             :                         Oid *constraintOid)
    1696             : {
    1697        2590 :     Oid         source_relid = RelationGetRelid(source_idx);
    1698             :     HeapTuple   ht_idxrel;
    1699             :     HeapTuple   ht_idx;
    1700             :     HeapTuple   ht_am;
    1701             :     Form_pg_class idxrelrec;
    1702             :     Form_pg_index idxrec;
    1703             :     Form_pg_am  amrec;
    1704             :     oidvector  *indcollation;
    1705             :     oidvector  *indclass;
    1706             :     IndexStmt  *index;
    1707             :     List       *indexprs;
    1708             :     ListCell   *indexpr_item;
    1709             :     Oid         indrelid;
    1710             :     int         keyno;
    1711             :     Oid         keycoltype;
    1712             :     Datum       datum;
    1713             :     bool        isnull;
    1714             : 
    1715        2590 :     if (constraintOid)
    1716        1626 :         *constraintOid = InvalidOid;
    1717             : 
    1718             :     /*
    1719             :      * Fetch pg_class tuple of source index.  We can't use the copy in the
    1720             :      * relcache entry because it doesn't include optional fields.
    1721             :      */
    1722        2590 :     ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(source_relid));
    1723        2590 :     if (!HeapTupleIsValid(ht_idxrel))
    1724           0 :         elog(ERROR, "cache lookup failed for relation %u", source_relid);
    1725        2590 :     idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
    1726             : 
    1727             :     /* Fetch pg_index tuple for source index from relcache entry */
    1728        2590 :     ht_idx = source_idx->rd_indextuple;
    1729        2590 :     idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
    1730        2590 :     indrelid = idxrec->indrelid;
    1731             : 
    1732             :     /* Fetch the pg_am tuple of the index' access method */
    1733        2590 :     ht_am = SearchSysCache1(AMOID, ObjectIdGetDatum(idxrelrec->relam));
    1734        2590 :     if (!HeapTupleIsValid(ht_am))
    1735           0 :         elog(ERROR, "cache lookup failed for access method %u",
    1736             :              idxrelrec->relam);
    1737        2590 :     amrec = (Form_pg_am) GETSTRUCT(ht_am);
    1738             : 
    1739             :     /* Extract indcollation from the pg_index tuple */
    1740        2590 :     datum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
    1741             :                                    Anum_pg_index_indcollation);
    1742        2590 :     indcollation = (oidvector *) DatumGetPointer(datum);
    1743             : 
    1744             :     /* Extract indclass from the pg_index tuple */
    1745        2590 :     datum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx, Anum_pg_index_indclass);
    1746        2590 :     indclass = (oidvector *) DatumGetPointer(datum);
    1747             : 
    1748             :     /* Begin building the IndexStmt */
    1749        2590 :     index = makeNode(IndexStmt);
    1750        2590 :     index->relation = heapRel;
    1751        2590 :     index->accessMethod = pstrdup(NameStr(amrec->amname));
    1752        2590 :     if (OidIsValid(idxrelrec->reltablespace))
    1753          52 :         index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
    1754             :     else
    1755        2538 :         index->tableSpace = NULL;
    1756        2590 :     index->excludeOpNames = NIL;
    1757        2590 :     index->idxcomment = NULL;
    1758        2590 :     index->indexOid = InvalidOid;
    1759        2590 :     index->oldNumber = InvalidRelFileNumber;
    1760        2590 :     index->oldCreateSubid = InvalidSubTransactionId;
    1761        2590 :     index->oldFirstRelfilelocatorSubid = InvalidSubTransactionId;
    1762        2590 :     index->unique = idxrec->indisunique;
    1763        2590 :     index->nulls_not_distinct = idxrec->indnullsnotdistinct;
    1764        2590 :     index->primary = idxrec->indisprimary;
    1765        2590 :     index->iswithoutoverlaps = (idxrec->indisprimary || idxrec->indisunique) && idxrec->indisexclusion;
    1766        2590 :     index->transformed = true;   /* don't need transformIndexStmt */
    1767        2590 :     index->concurrent = false;
    1768        2590 :     index->if_not_exists = false;
    1769        2590 :     index->reset_default_tblspc = false;
    1770             : 
    1771             :     /*
    1772             :      * We don't try to preserve the name of the source index; instead, just
    1773             :      * let DefineIndex() choose a reasonable name.  (If we tried to preserve
    1774             :      * the name, we'd get duplicate-relation-name failures unless the source
    1775             :      * table was in a different schema.)
    1776             :      */
    1777        2590 :     index->idxname = NULL;
    1778             : 
    1779             :     /*
    1780             :      * If the index is marked PRIMARY or has an exclusion condition, it's
    1781             :      * certainly from a constraint; else, if it's not marked UNIQUE, it
    1782             :      * certainly isn't.  If it is or might be from a constraint, we have to
    1783             :      * fetch the pg_constraint record.
    1784             :      */
    1785        2590 :     if (index->primary || index->unique || idxrec->indisexclusion)
    1786        1474 :     {
    1787        1474 :         Oid         constraintId = get_index_constraint(source_relid);
    1788             : 
    1789        1474 :         if (OidIsValid(constraintId))
    1790             :         {
    1791             :             HeapTuple   ht_constr;
    1792             :             Form_pg_constraint conrec;
    1793             : 
    1794        1424 :             if (constraintOid)
    1795        1244 :                 *constraintOid = constraintId;
    1796             : 
    1797        1424 :             ht_constr = SearchSysCache1(CONSTROID,
    1798             :                                         ObjectIdGetDatum(constraintId));
    1799        1424 :             if (!HeapTupleIsValid(ht_constr))
    1800           0 :                 elog(ERROR, "cache lookup failed for constraint %u",
    1801             :                      constraintId);
    1802        1424 :             conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
    1803             : 
    1804        1424 :             index->isconstraint = true;
    1805        1424 :             index->deferrable = conrec->condeferrable;
    1806        1424 :             index->initdeferred = conrec->condeferred;
    1807             : 
    1808             :             /* If it's an exclusion constraint, we need the operator names */
    1809        1424 :             if (idxrec->indisexclusion)
    1810             :             {
    1811             :                 Datum      *elems;
    1812             :                 int         nElems;
    1813             :                 int         i;
    1814             : 
    1815             :                 Assert(conrec->contype == CONSTRAINT_EXCLUSION ||
    1816             :                        (index->iswithoutoverlaps &&
    1817             :                         (conrec->contype == CONSTRAINT_PRIMARY || conrec->contype == CONSTRAINT_UNIQUE)));
    1818             :                 /* Extract operator OIDs from the pg_constraint tuple */
    1819          84 :                 datum = SysCacheGetAttrNotNull(CONSTROID, ht_constr,
    1820             :                                                Anum_pg_constraint_conexclop);
    1821          84 :                 deconstruct_array_builtin(DatumGetArrayTypeP(datum), OIDOID, &elems, NULL, &nElems);
    1822             : 
    1823         250 :                 for (i = 0; i < nElems; i++)
    1824             :                 {
    1825         166 :                     Oid         operid = DatumGetObjectId(elems[i]);
    1826             :                     HeapTuple   opertup;
    1827             :                     Form_pg_operator operform;
    1828             :                     char       *oprname;
    1829             :                     char       *nspname;
    1830             :                     List       *namelist;
    1831             : 
    1832         166 :                     opertup = SearchSysCache1(OPEROID,
    1833             :                                               ObjectIdGetDatum(operid));
    1834         166 :                     if (!HeapTupleIsValid(opertup))
    1835           0 :                         elog(ERROR, "cache lookup failed for operator %u",
    1836             :                              operid);
    1837         166 :                     operform = (Form_pg_operator) GETSTRUCT(opertup);
    1838         166 :                     oprname = pstrdup(NameStr(operform->oprname));
    1839             :                     /* For simplicity we always schema-qualify the op name */
    1840         166 :                     nspname = get_namespace_name(operform->oprnamespace);
    1841         166 :                     namelist = list_make2(makeString(nspname),
    1842             :                                           makeString(oprname));
    1843         166 :                     index->excludeOpNames = lappend(index->excludeOpNames,
    1844             :                                                     namelist);
    1845         166 :                     ReleaseSysCache(opertup);
    1846             :                 }
    1847             :             }
    1848             : 
    1849        1424 :             ReleaseSysCache(ht_constr);
    1850             :         }
    1851             :         else
    1852          50 :             index->isconstraint = false;
    1853             :     }
    1854             :     else
    1855        1116 :         index->isconstraint = false;
    1856             : 
    1857             :     /* Get the index expressions, if any */
    1858        2590 :     datum = SysCacheGetAttr(INDEXRELID, ht_idx,
    1859             :                             Anum_pg_index_indexprs, &isnull);
    1860        2590 :     if (!isnull)
    1861             :     {
    1862             :         char       *exprsString;
    1863             : 
    1864         166 :         exprsString = TextDatumGetCString(datum);
    1865         166 :         indexprs = (List *) stringToNode(exprsString);
    1866             :     }
    1867             :     else
    1868        2424 :         indexprs = NIL;
    1869             : 
    1870             :     /* Build the list of IndexElem */
    1871        2590 :     index->indexParams = NIL;
    1872        2590 :     index->indexIncludingParams = NIL;
    1873             : 
    1874        2590 :     indexpr_item = list_head(indexprs);
    1875        5722 :     for (keyno = 0; keyno < idxrec->indnkeyatts; keyno++)
    1876             :     {
    1877             :         IndexElem  *iparam;
    1878        3132 :         AttrNumber  attnum = idxrec->indkey.values[keyno];
    1879        3132 :         Form_pg_attribute attr = TupleDescAttr(RelationGetDescr(source_idx),
    1880             :                                                keyno);
    1881        3132 :         int16       opt = source_idx->rd_indoption[keyno];
    1882             : 
    1883        3132 :         iparam = makeNode(IndexElem);
    1884             : 
    1885        3132 :         if (AttributeNumberIsValid(attnum))
    1886             :         {
    1887             :             /* Simple index column */
    1888             :             char       *attname;
    1889             : 
    1890        2966 :             attname = get_attname(indrelid, attnum, false);
    1891        2966 :             keycoltype = get_atttype(indrelid, attnum);
    1892             : 
    1893        2966 :             iparam->name = attname;
    1894        2966 :             iparam->expr = NULL;
    1895             :         }
    1896             :         else
    1897             :         {
    1898             :             /* Expressional index */
    1899             :             Node       *indexkey;
    1900             :             bool        found_whole_row;
    1901             : 
    1902         166 :             if (indexpr_item == NULL)
    1903           0 :                 elog(ERROR, "too few entries in indexprs list");
    1904         166 :             indexkey = (Node *) lfirst(indexpr_item);
    1905         166 :             indexpr_item = lnext(indexprs, indexpr_item);
    1906             : 
    1907             :             /* Adjust Vars to match new table's column numbering */
    1908         166 :             indexkey = map_variable_attnos(indexkey,
    1909             :                                            1, 0,
    1910             :                                            attmap,
    1911             :                                            InvalidOid, &found_whole_row);
    1912             : 
    1913             :             /* As in expandTableLikeClause, reject whole-row variables */
    1914         166 :             if (found_whole_row)
    1915           0 :                 ereport(ERROR,
    1916             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1917             :                          errmsg("cannot convert whole-row table reference"),
    1918             :                          errdetail("Index \"%s\" contains a whole-row table reference.",
    1919             :                                    RelationGetRelationName(source_idx))));
    1920             : 
    1921         166 :             iparam->name = NULL;
    1922         166 :             iparam->expr = indexkey;
    1923             : 
    1924         166 :             keycoltype = exprType(indexkey);
    1925             :         }
    1926             : 
    1927             :         /* Copy the original index column name */
    1928        3132 :         iparam->indexcolname = pstrdup(NameStr(attr->attname));
    1929             : 
    1930             :         /* Add the collation name, if non-default */
    1931        3132 :         iparam->collation = get_collation(indcollation->values[keyno], keycoltype);
    1932             : 
    1933             :         /* Add the operator class name, if non-default */
    1934        3132 :         iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
    1935        3132 :         iparam->opclassopts =
    1936        3132 :             untransformRelOptions(get_attoptions(source_relid, keyno + 1));
    1937             : 
    1938        3132 :         iparam->ordering = SORTBY_DEFAULT;
    1939        3132 :         iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
    1940             : 
    1941             :         /* Adjust options if necessary */
    1942        3132 :         if (source_idx->rd_indam->amcanorder)
    1943             :         {
    1944             :             /*
    1945             :              * If it supports sort ordering, copy DESC and NULLS opts. Don't
    1946             :              * set non-default settings unnecessarily, though, so as to
    1947             :              * improve the chance of recognizing equivalence to constraint
    1948             :              * indexes.
    1949             :              */
    1950        2938 :             if (opt & INDOPTION_DESC)
    1951             :             {
    1952           0 :                 iparam->ordering = SORTBY_DESC;
    1953           0 :                 if ((opt & INDOPTION_NULLS_FIRST) == 0)
    1954           0 :                     iparam->nulls_ordering = SORTBY_NULLS_LAST;
    1955             :             }
    1956             :             else
    1957             :             {
    1958        2938 :                 if (opt & INDOPTION_NULLS_FIRST)
    1959           0 :                     iparam->nulls_ordering = SORTBY_NULLS_FIRST;
    1960             :             }
    1961             :         }
    1962             : 
    1963        3132 :         index->indexParams = lappend(index->indexParams, iparam);
    1964             :     }
    1965             : 
    1966             :     /* Handle included columns separately */
    1967        2608 :     for (keyno = idxrec->indnkeyatts; keyno < idxrec->indnatts; keyno++)
    1968             :     {
    1969             :         IndexElem  *iparam;
    1970          18 :         AttrNumber  attnum = idxrec->indkey.values[keyno];
    1971          18 :         Form_pg_attribute attr = TupleDescAttr(RelationGetDescr(source_idx),
    1972             :                                                keyno);
    1973             : 
    1974          18 :         iparam = makeNode(IndexElem);
    1975             : 
    1976          18 :         if (AttributeNumberIsValid(attnum))
    1977             :         {
    1978             :             /* Simple index column */
    1979             :             char       *attname;
    1980             : 
    1981          18 :             attname = get_attname(indrelid, attnum, false);
    1982             : 
    1983          18 :             iparam->name = attname;
    1984          18 :             iparam->expr = NULL;
    1985             :         }
    1986             :         else
    1987           0 :             ereport(ERROR,
    1988             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1989             :                      errmsg("expressions are not supported in included columns")));
    1990             : 
    1991             :         /* Copy the original index column name */
    1992          18 :         iparam->indexcolname = pstrdup(NameStr(attr->attname));
    1993             : 
    1994          18 :         index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
    1995             :     }
    1996             :     /* Copy reloptions if any */
    1997        2590 :     datum = SysCacheGetAttr(RELOID, ht_idxrel,
    1998             :                             Anum_pg_class_reloptions, &isnull);
    1999        2590 :     if (!isnull)
    2000           0 :         index->options = untransformRelOptions(datum);
    2001             : 
    2002             :     /* If it's a partial index, decompile and append the predicate */
    2003        2590 :     datum = SysCacheGetAttr(INDEXRELID, ht_idx,
    2004             :                             Anum_pg_index_indpred, &isnull);
    2005        2590 :     if (!isnull)
    2006             :     {
    2007             :         char       *pred_str;
    2008             :         Node       *pred_tree;
    2009             :         bool        found_whole_row;
    2010             : 
    2011             :         /* Convert text string to node tree */
    2012          30 :         pred_str = TextDatumGetCString(datum);
    2013          30 :         pred_tree = (Node *) stringToNode(pred_str);
    2014             : 
    2015             :         /* Adjust Vars to match new table's column numbering */
    2016          30 :         pred_tree = map_variable_attnos(pred_tree,
    2017             :                                         1, 0,
    2018             :                                         attmap,
    2019             :                                         InvalidOid, &found_whole_row);
    2020             : 
    2021             :         /* As in expandTableLikeClause, reject whole-row variables */
    2022          30 :         if (found_whole_row)
    2023           0 :             ereport(ERROR,
    2024             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2025             :                      errmsg("cannot convert whole-row table reference"),
    2026             :                      errdetail("Index \"%s\" contains a whole-row table reference.",
    2027             :                                RelationGetRelationName(source_idx))));
    2028             : 
    2029          30 :         index->whereClause = pred_tree;
    2030             :     }
    2031             : 
    2032             :     /* Clean up */
    2033        2590 :     ReleaseSysCache(ht_idxrel);
    2034        2590 :     ReleaseSysCache(ht_am);
    2035             : 
    2036        2590 :     return index;
    2037             : }
    2038             : 
    2039             : /*
    2040             :  * Generate a CreateStatsStmt node using information from an already existing
    2041             :  * extended statistic "source_statsid", for the rel identified by heapRel and
    2042             :  * heapRelid.
    2043             :  *
    2044             :  * Attribute numbers in expression Vars are adjusted according to attmap.
    2045             :  */
    2046             : static CreateStatsStmt *
    2047          48 : generateClonedExtStatsStmt(RangeVar *heapRel, Oid heapRelid,
    2048             :                            Oid source_statsid, const AttrMap *attmap)
    2049             : {
    2050             :     HeapTuple   ht_stats;
    2051             :     Form_pg_statistic_ext statsrec;
    2052             :     CreateStatsStmt *stats;
    2053          48 :     List       *stat_types = NIL;
    2054          48 :     List       *def_names = NIL;
    2055             :     bool        isnull;
    2056             :     Datum       datum;
    2057             :     ArrayType  *arr;
    2058             :     char       *enabled;
    2059             :     int         i;
    2060             : 
    2061             :     Assert(OidIsValid(heapRelid));
    2062             :     Assert(heapRel != NULL);
    2063             : 
    2064             :     /*
    2065             :      * Fetch pg_statistic_ext tuple of source statistics object.
    2066             :      */
    2067          48 :     ht_stats = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(source_statsid));
    2068          48 :     if (!HeapTupleIsValid(ht_stats))
    2069           0 :         elog(ERROR, "cache lookup failed for statistics object %u", source_statsid);
    2070          48 :     statsrec = (Form_pg_statistic_ext) GETSTRUCT(ht_stats);
    2071             : 
    2072             :     /* Determine which statistics types exist */
    2073          48 :     datum = SysCacheGetAttrNotNull(STATEXTOID, ht_stats,
    2074             :                                    Anum_pg_statistic_ext_stxkind);
    2075          48 :     arr = DatumGetArrayTypeP(datum);
    2076          48 :     if (ARR_NDIM(arr) != 1 ||
    2077          48 :         ARR_HASNULL(arr) ||
    2078          48 :         ARR_ELEMTYPE(arr) != CHAROID)
    2079           0 :         elog(ERROR, "stxkind is not a 1-D char array");
    2080          48 :     enabled = (char *) ARR_DATA_PTR(arr);
    2081         144 :     for (i = 0; i < ARR_DIMS(arr)[0]; i++)
    2082             :     {
    2083          96 :         if (enabled[i] == STATS_EXT_NDISTINCT)
    2084          24 :             stat_types = lappend(stat_types, makeString("ndistinct"));
    2085          72 :         else if (enabled[i] == STATS_EXT_DEPENDENCIES)
    2086          24 :             stat_types = lappend(stat_types, makeString("dependencies"));
    2087          48 :         else if (enabled[i] == STATS_EXT_MCV)
    2088          24 :             stat_types = lappend(stat_types, makeString("mcv"));
    2089          24 :         else if (enabled[i] == STATS_EXT_EXPRESSIONS)
    2090             :             /* expression stats are not exposed to users */
    2091          24 :             continue;
    2092             :         else
    2093           0 :             elog(ERROR, "unrecognized statistics kind %c", enabled[i]);
    2094             :     }
    2095             : 
    2096             :     /* Determine which columns the statistics are on */
    2097          96 :     for (i = 0; i < statsrec->stxkeys.dim1; i++)
    2098             :     {
    2099          48 :         StatsElem  *selem = makeNode(StatsElem);
    2100          48 :         AttrNumber  attnum = statsrec->stxkeys.values[i];
    2101             : 
    2102          48 :         selem->name = get_attname(heapRelid, attnum, false);
    2103          48 :         selem->expr = NULL;
    2104             : 
    2105          48 :         def_names = lappend(def_names, selem);
    2106             :     }
    2107             : 
    2108             :     /*
    2109             :      * Now handle expressions, if there are any. The order (with respect to
    2110             :      * regular attributes) does not really matter for extended stats, so we
    2111             :      * simply append them after simple column references.
    2112             :      *
    2113             :      * XXX Some places during build/estimation treat expressions as if they
    2114             :      * are before attributes, but for the CREATE command that's entirely
    2115             :      * irrelevant.
    2116             :      */
    2117          48 :     datum = SysCacheGetAttr(STATEXTOID, ht_stats,
    2118             :                             Anum_pg_statistic_ext_stxexprs, &isnull);
    2119             : 
    2120          48 :     if (!isnull)
    2121             :     {
    2122             :         ListCell   *lc;
    2123          24 :         List       *exprs = NIL;
    2124             :         char       *exprsString;
    2125             : 
    2126          24 :         exprsString = TextDatumGetCString(datum);
    2127          24 :         exprs = (List *) stringToNode(exprsString);
    2128             : 
    2129          48 :         foreach(lc, exprs)
    2130             :         {
    2131          24 :             Node       *expr = (Node *) lfirst(lc);
    2132          24 :             StatsElem  *selem = makeNode(StatsElem);
    2133             :             bool        found_whole_row;
    2134             : 
    2135             :             /* Adjust Vars to match new table's column numbering */
    2136          24 :             expr = map_variable_attnos(expr,
    2137             :                                        1, 0,
    2138             :                                        attmap,
    2139             :                                        InvalidOid,
    2140             :                                        &found_whole_row);
    2141             : 
    2142          24 :             selem->name = NULL;
    2143          24 :             selem->expr = expr;
    2144             : 
    2145          24 :             def_names = lappend(def_names, selem);
    2146             :         }
    2147             : 
    2148          24 :         pfree(exprsString);
    2149             :     }
    2150             : 
    2151             :     /* finally, build the output node */
    2152          48 :     stats = makeNode(CreateStatsStmt);
    2153          48 :     stats->defnames = NULL;
    2154          48 :     stats->stat_types = stat_types;
    2155          48 :     stats->exprs = def_names;
    2156          48 :     stats->relations = list_make1(heapRel);
    2157          48 :     stats->stxcomment = NULL;
    2158          48 :     stats->transformed = true;   /* don't need transformStatsStmt again */
    2159          48 :     stats->if_not_exists = false;
    2160             : 
    2161             :     /* Clean up */
    2162          48 :     ReleaseSysCache(ht_stats);
    2163             : 
    2164          48 :     return stats;
    2165             : }
    2166             : 
    2167             : /*
    2168             :  * get_collation        - fetch qualified name of a collation
    2169             :  *
    2170             :  * If collation is InvalidOid or is the default for the given actual_datatype,
    2171             :  * then the return value is NIL.
    2172             :  */
    2173             : static List *
    2174        3132 : get_collation(Oid collation, Oid actual_datatype)
    2175             : {
    2176             :     List       *result;
    2177             :     HeapTuple   ht_coll;
    2178             :     Form_pg_collation coll_rec;
    2179             :     char       *nsp_name;
    2180             :     char       *coll_name;
    2181             : 
    2182        3132 :     if (!OidIsValid(collation))
    2183        2866 :         return NIL;             /* easy case */
    2184         266 :     if (collation == get_typcollation(actual_datatype))
    2185         244 :         return NIL;             /* just let it default */
    2186             : 
    2187          22 :     ht_coll = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
    2188          22 :     if (!HeapTupleIsValid(ht_coll))
    2189           0 :         elog(ERROR, "cache lookup failed for collation %u", collation);
    2190          22 :     coll_rec = (Form_pg_collation) GETSTRUCT(ht_coll);
    2191             : 
    2192             :     /* For simplicity, we always schema-qualify the name */
    2193          22 :     nsp_name = get_namespace_name(coll_rec->collnamespace);
    2194          22 :     coll_name = pstrdup(NameStr(coll_rec->collname));
    2195          22 :     result = list_make2(makeString(nsp_name), makeString(coll_name));
    2196             : 
    2197          22 :     ReleaseSysCache(ht_coll);
    2198          22 :     return result;
    2199             : }
    2200             : 
    2201             : /*
    2202             :  * get_opclass          - fetch qualified name of an index operator class
    2203             :  *
    2204             :  * If the opclass is the default for the given actual_datatype, then
    2205             :  * the return value is NIL.
    2206             :  */
    2207             : static List *
    2208        3132 : get_opclass(Oid opclass, Oid actual_datatype)
    2209             : {
    2210        3132 :     List       *result = NIL;
    2211             :     HeapTuple   ht_opc;
    2212             :     Form_pg_opclass opc_rec;
    2213             : 
    2214        3132 :     ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
    2215        3132 :     if (!HeapTupleIsValid(ht_opc))
    2216           0 :         elog(ERROR, "cache lookup failed for opclass %u", opclass);
    2217        3132 :     opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
    2218             : 
    2219        3132 :     if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
    2220             :     {
    2221             :         /* For simplicity, we always schema-qualify the name */
    2222          24 :         char       *nsp_name = get_namespace_name(opc_rec->opcnamespace);
    2223          24 :         char       *opc_name = pstrdup(NameStr(opc_rec->opcname));
    2224             : 
    2225          24 :         result = list_make2(makeString(nsp_name), makeString(opc_name));
    2226             :     }
    2227             : 
    2228        3132 :     ReleaseSysCache(ht_opc);
    2229        3132 :     return result;
    2230             : }
    2231             : 
    2232             : 
    2233             : /*
    2234             :  * transformIndexConstraints
    2235             :  *      Handle UNIQUE, PRIMARY KEY, EXCLUDE constraints, which create indexes.
    2236             :  *      We also merge in any index definitions arising from
    2237             :  *      LIKE ... INCLUDING INDEXES.
    2238             :  */
    2239             : static void
    2240       63560 : transformIndexConstraints(CreateStmtContext *cxt)
    2241             : {
    2242             :     IndexStmt  *index;
    2243       63560 :     List       *indexlist = NIL;
    2244       63560 :     List       *finalindexlist = NIL;
    2245             :     ListCell   *lc;
    2246             : 
    2247             :     /*
    2248             :      * Run through the constraints that need to generate an index, and do so.
    2249             :      *
    2250             :      * For PRIMARY KEY, this queues not-null constraints for each column, if
    2251             :      * needed.
    2252             :      */
    2253       83540 :     foreach(lc, cxt->ixconstraints)
    2254             :     {
    2255       20046 :         Constraint *constraint = lfirst_node(Constraint, lc);
    2256             : 
    2257             :         Assert(constraint->contype == CONSTR_PRIMARY ||
    2258             :                constraint->contype == CONSTR_UNIQUE ||
    2259             :                constraint->contype == CONSTR_EXCLUSION);
    2260             : 
    2261       20046 :         index = transformIndexConstraint(constraint, cxt);
    2262             : 
    2263       19980 :         indexlist = lappend(indexlist, index);
    2264             :     }
    2265             : 
    2266             :     /*
    2267             :      * Scan the index list and remove any redundant index specifications. This
    2268             :      * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
    2269             :      * strict reading of SQL would suggest raising an error instead, but that
    2270             :      * strikes me as too anal-retentive. - tgl 2001-02-14
    2271             :      *
    2272             :      * XXX in ALTER TABLE case, it'd be nice to look for duplicate
    2273             :      * pre-existing indexes, too.
    2274             :      */
    2275       63494 :     if (cxt->pkey != NULL)
    2276             :     {
    2277             :         /* Make sure we keep the PKEY index in preference to others... */
    2278       14082 :         finalindexlist = list_make1(cxt->pkey);
    2279             :     }
    2280             : 
    2281       83474 :     foreach(lc, indexlist)
    2282             :     {
    2283       19980 :         bool        keep = true;
    2284             :         ListCell   *k;
    2285             : 
    2286       19980 :         index = lfirst(lc);
    2287             : 
    2288             :         /* if it's pkey, it's already in finalindexlist */
    2289       19980 :         if (index == cxt->pkey)
    2290       14082 :             continue;
    2291             : 
    2292        6092 :         foreach(k, finalindexlist)
    2293             :         {
    2294         194 :             IndexStmt  *priorindex = lfirst(k);
    2295             : 
    2296         200 :             if (equal(index->indexParams, priorindex->indexParams) &&
    2297          12 :                 equal(index->indexIncludingParams, priorindex->indexIncludingParams) &&
    2298          12 :                 equal(index->whereClause, priorindex->whereClause) &&
    2299           6 :                 equal(index->excludeOpNames, priorindex->excludeOpNames) &&
    2300           6 :                 strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
    2301           6 :                 index->nulls_not_distinct == priorindex->nulls_not_distinct &&
    2302           6 :                 index->deferrable == priorindex->deferrable &&
    2303           0 :                 index->initdeferred == priorindex->initdeferred)
    2304             :             {
    2305           0 :                 priorindex->unique |= index->unique;
    2306             : 
    2307             :                 /*
    2308             :                  * If the prior index is as yet unnamed, and this one is
    2309             :                  * named, then transfer the name to the prior index. This
    2310             :                  * ensures that if we have named and unnamed constraints,
    2311             :                  * we'll use (at least one of) the names for the index.
    2312             :                  */
    2313           0 :                 if (priorindex->idxname == NULL)
    2314           0 :                     priorindex->idxname = index->idxname;
    2315           0 :                 keep = false;
    2316           0 :                 break;
    2317             :             }
    2318             :         }
    2319             : 
    2320        5898 :         if (keep)
    2321        5898 :             finalindexlist = lappend(finalindexlist, index);
    2322             :     }
    2323             : 
    2324             :     /*
    2325             :      * Now append all the IndexStmts to cxt->alist.
    2326             :      */
    2327       63494 :     cxt->alist = list_concat(cxt->alist, finalindexlist);
    2328       63494 : }
    2329             : 
    2330             : /*
    2331             :  * transformIndexConstraint
    2332             :  *      Transform one UNIQUE, PRIMARY KEY, or EXCLUDE constraint for
    2333             :  *      transformIndexConstraints. An IndexStmt is returned.
    2334             :  *
    2335             :  * For a PRIMARY KEY constraint, we additionally create not-null constraints
    2336             :  * for columns that don't already have them.
    2337             :  */
    2338             : static IndexStmt *
    2339       20046 : transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
    2340             : {
    2341             :     IndexStmt  *index;
    2342             :     ListCell   *lc;
    2343             : 
    2344       20046 :     index = makeNode(IndexStmt);
    2345             : 
    2346       20046 :     index->unique = (constraint->contype != CONSTR_EXCLUSION);
    2347       20046 :     index->primary = (constraint->contype == CONSTR_PRIMARY);
    2348       20046 :     if (index->primary)
    2349             :     {
    2350       14112 :         if (cxt->pkey != NULL)
    2351           0 :             ereport(ERROR,
    2352             :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    2353             :                      errmsg("multiple primary keys for table \"%s\" are not allowed",
    2354             :                             cxt->relation->relname),
    2355             :                      parser_errposition(cxt->pstate, constraint->location)));
    2356       14112 :         cxt->pkey = index;
    2357             : 
    2358             :         /*
    2359             :          * In ALTER TABLE case, a primary index might already exist, but
    2360             :          * DefineIndex will check for it.
    2361             :          */
    2362             :     }
    2363       20046 :     index->nulls_not_distinct = constraint->nulls_not_distinct;
    2364       20046 :     index->isconstraint = true;
    2365       20046 :     index->iswithoutoverlaps = constraint->without_overlaps;
    2366       20046 :     index->deferrable = constraint->deferrable;
    2367       20046 :     index->initdeferred = constraint->initdeferred;
    2368             : 
    2369       20046 :     if (constraint->conname != NULL)
    2370        1738 :         index->idxname = pstrdup(constraint->conname);
    2371             :     else
    2372       18308 :         index->idxname = NULL;   /* DefineIndex will choose name */
    2373             : 
    2374       20046 :     index->relation = cxt->relation;
    2375       20046 :     index->accessMethod = constraint->access_method ? constraint->access_method : DEFAULT_INDEX_TYPE;
    2376       20046 :     index->options = constraint->options;
    2377       20046 :     index->tableSpace = constraint->indexspace;
    2378       20046 :     index->whereClause = constraint->where_clause;
    2379       20046 :     index->indexParams = NIL;
    2380       20046 :     index->indexIncludingParams = NIL;
    2381       20046 :     index->excludeOpNames = NIL;
    2382       20046 :     index->idxcomment = NULL;
    2383       20046 :     index->indexOid = InvalidOid;
    2384       20046 :     index->oldNumber = InvalidRelFileNumber;
    2385       20046 :     index->oldCreateSubid = InvalidSubTransactionId;
    2386       20046 :     index->oldFirstRelfilelocatorSubid = InvalidSubTransactionId;
    2387       20046 :     index->transformed = false;
    2388       20046 :     index->concurrent = false;
    2389       20046 :     index->if_not_exists = false;
    2390       20046 :     index->reset_default_tblspc = constraint->reset_default_tblspc;
    2391             : 
    2392             :     /*
    2393             :      * If it's ALTER TABLE ADD CONSTRAINT USING INDEX, look up the index and
    2394             :      * verify it's usable, then extract the implied column name list.  (We
    2395             :      * will not actually need the column name list at runtime, but we need it
    2396             :      * now to check for duplicate column entries below.)
    2397             :      */
    2398       20046 :     if (constraint->indexname != NULL)
    2399             :     {
    2400       10884 :         char       *index_name = constraint->indexname;
    2401       10884 :         Relation    heap_rel = cxt->rel;
    2402             :         Oid         index_oid;
    2403             :         Relation    index_rel;
    2404             :         Form_pg_index index_form;
    2405             :         oidvector  *indclass;
    2406             :         Datum       indclassDatum;
    2407             :         int         i;
    2408             : 
    2409             :         /* Grammar should not allow this with explicit column list */
    2410             :         Assert(constraint->keys == NIL);
    2411             : 
    2412             :         /* Grammar should only allow PRIMARY and UNIQUE constraints */
    2413             :         Assert(constraint->contype == CONSTR_PRIMARY ||
    2414             :                constraint->contype == CONSTR_UNIQUE);
    2415             : 
    2416             :         /* Must be ALTER, not CREATE, but grammar doesn't enforce that */
    2417       10884 :         if (!cxt->isalter)
    2418           0 :             ereport(ERROR,
    2419             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2420             :                      errmsg("cannot use an existing index in CREATE TABLE"),
    2421             :                      parser_errposition(cxt->pstate, constraint->location)));
    2422             : 
    2423             :         /* Look for the index in the same schema as the table */
    2424       10884 :         index_oid = get_relname_relid(index_name, RelationGetNamespace(heap_rel));
    2425             : 
    2426       10884 :         if (!OidIsValid(index_oid))
    2427           0 :             ereport(ERROR,
    2428             :                     (errcode(ERRCODE_UNDEFINED_OBJECT),
    2429             :                      errmsg("index \"%s\" does not exist", index_name),
    2430             :                      parser_errposition(cxt->pstate, constraint->location)));
    2431             : 
    2432             :         /* Open the index (this will throw an error if it is not an index) */
    2433       10884 :         index_rel = index_open(index_oid, AccessShareLock);
    2434       10884 :         index_form = index_rel->rd_index;
    2435             : 
    2436             :         /* Check that it does not have an associated constraint already */
    2437       10884 :         if (OidIsValid(get_index_constraint(index_oid)))
    2438           0 :             ereport(ERROR,
    2439             :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    2440             :                      errmsg("index \"%s\" is already associated with a constraint",
    2441             :                             index_name),
    2442             :                      parser_errposition(cxt->pstate, constraint->location)));
    2443             : 
    2444             :         /* Perform validity checks on the index */
    2445       10884 :         if (index_form->indrelid != RelationGetRelid(heap_rel))
    2446           0 :             ereport(ERROR,
    2447             :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    2448             :                      errmsg("index \"%s\" does not belong to table \"%s\"",
    2449             :                             index_name, RelationGetRelationName(heap_rel)),
    2450             :                      parser_errposition(cxt->pstate, constraint->location)));
    2451             : 
    2452       10884 :         if (!index_form->indisvalid)
    2453           0 :             ereport(ERROR,
    2454             :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    2455             :                      errmsg("index \"%s\" is not valid", index_name),
    2456             :                      parser_errposition(cxt->pstate, constraint->location)));
    2457             : 
    2458             :         /*
    2459             :          * Today we forbid non-unique indexes, but we could permit GiST
    2460             :          * indexes whose last entry is a range type and use that to create a
    2461             :          * WITHOUT OVERLAPS constraint (i.e. a temporal constraint).
    2462             :          */
    2463       10884 :         if (!index_form->indisunique)
    2464          12 :             ereport(ERROR,
    2465             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2466             :                      errmsg("\"%s\" is not a unique index", index_name),
    2467             :                      errdetail("Cannot create a primary key or unique constraint using such an index."),
    2468             :                      parser_errposition(cxt->pstate, constraint->location)));
    2469             : 
    2470       10872 :         if (RelationGetIndexExpressions(index_rel) != NIL)
    2471           0 :             ereport(ERROR,
    2472             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2473             :                      errmsg("index \"%s\" contains expressions", index_name),
    2474             :                      errdetail("Cannot create a primary key or unique constraint using such an index."),
    2475             :                      parser_errposition(cxt->pstate, constraint->location)));
    2476             : 
    2477       10872 :         if (RelationGetIndexPredicate(index_rel) != NIL)
    2478           0 :             ereport(ERROR,
    2479             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2480             :                      errmsg("\"%s\" is a partial index", index_name),
    2481             :                      errdetail("Cannot create a primary key or unique constraint using such an index."),
    2482             :                      parser_errposition(cxt->pstate, constraint->location)));
    2483             : 
    2484             :         /*
    2485             :          * It's probably unsafe to change a deferred index to non-deferred. (A
    2486             :          * non-constraint index couldn't be deferred anyway, so this case
    2487             :          * should never occur; no need to sweat, but let's check it.)
    2488             :          */
    2489       10872 :         if (!index_form->indimmediate && !constraint->deferrable)
    2490           0 :             ereport(ERROR,
    2491             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2492             :                      errmsg("\"%s\" is a deferrable index", index_name),
    2493             :                      errdetail("Cannot create a non-deferrable constraint using a deferrable index."),
    2494             :                      parser_errposition(cxt->pstate, constraint->location)));
    2495             : 
    2496             :         /*
    2497             :          * Insist on it being a btree.  We must have an index that exactly
    2498             :          * matches what you'd get from plain ADD CONSTRAINT syntax, else dump
    2499             :          * and reload will produce a different index (breaking pg_upgrade in
    2500             :          * particular).
    2501             :          */
    2502       10872 :         if (index_rel->rd_rel->relam != get_index_am_oid(DEFAULT_INDEX_TYPE, false))
    2503           0 :             ereport(ERROR,
    2504             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2505             :                      errmsg("index \"%s\" is not a btree", index_name),
    2506             :                      parser_errposition(cxt->pstate, constraint->location)));
    2507             : 
    2508             :         /* Must get indclass the hard way */
    2509       10872 :         indclassDatum = SysCacheGetAttrNotNull(INDEXRELID,
    2510       10872 :                                                index_rel->rd_indextuple,
    2511             :                                                Anum_pg_index_indclass);
    2512       10872 :         indclass = (oidvector *) DatumGetPointer(indclassDatum);
    2513             : 
    2514       28756 :         for (i = 0; i < index_form->indnatts; i++)
    2515             :         {
    2516       17896 :             int16       attnum = index_form->indkey.values[i];
    2517             :             const FormData_pg_attribute *attform;
    2518             :             char       *attname;
    2519             :             Oid         defopclass;
    2520             : 
    2521             :             /*
    2522             :              * We shouldn't see attnum == 0 here, since we already rejected
    2523             :              * expression indexes.  If we do, SystemAttributeDefinition will
    2524             :              * throw an error.
    2525             :              */
    2526       17896 :             if (attnum > 0)
    2527             :             {
    2528             :                 Assert(attnum <= heap_rel->rd_att->natts);
    2529       17896 :                 attform = TupleDescAttr(heap_rel->rd_att, attnum - 1);
    2530             :             }
    2531             :             else
    2532           0 :                 attform = SystemAttributeDefinition(attnum);
    2533       17896 :             attname = pstrdup(NameStr(attform->attname));
    2534             : 
    2535       17896 :             if (i < index_form->indnkeyatts)
    2536             :             {
    2537             :                 /*
    2538             :                  * Insist on default opclass, collation, and sort options.
    2539             :                  * While the index would still work as a constraint with
    2540             :                  * non-default settings, it might not provide exactly the same
    2541             :                  * uniqueness semantics as you'd get from a normally-created
    2542             :                  * constraint; and there's also the dump/reload problem
    2543             :                  * mentioned above.
    2544             :                  */
    2545             :                 Datum       attoptions =
    2546       17866 :                     get_attoptions(RelationGetRelid(index_rel), i + 1);
    2547             : 
    2548       17866 :                 defopclass = GetDefaultOpClass(attform->atttypid,
    2549       17866 :                                                index_rel->rd_rel->relam);
    2550       17866 :                 if (indclass->values[i] != defopclass ||
    2551       17866 :                     attform->attcollation != index_rel->rd_indcollation[i] ||
    2552       17860 :                     attoptions != (Datum) 0 ||
    2553       17860 :                     index_rel->rd_indoption[i] != 0)
    2554          12 :                     ereport(ERROR,
    2555             :                             (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2556             :                              errmsg("index \"%s\" column number %d does not have default sorting behavior", index_name, i + 1),
    2557             :                              errdetail("Cannot create a primary key or unique constraint using such an index."),
    2558             :                              parser_errposition(cxt->pstate, constraint->location)));
    2559             : 
    2560             :                 /* If a PK, ensure the columns get not null constraints */
    2561       17854 :                 if (constraint->contype == CONSTR_PRIMARY)
    2562        8120 :                     cxt->nnconstraints =
    2563        8120 :                         lappend(cxt->nnconstraints,
    2564        8120 :                                 makeNotNullConstraint(makeString(attname)));
    2565             : 
    2566       17854 :                 constraint->keys = lappend(constraint->keys, makeString(attname));
    2567             :             }
    2568             :             else
    2569          30 :                 constraint->including = lappend(constraint->including, makeString(attname));
    2570             :         }
    2571             : 
    2572             :         /* Close the index relation but keep the lock */
    2573       10860 :         relation_close(index_rel, NoLock);
    2574             : 
    2575       10860 :         index->indexOid = index_oid;
    2576             :     }
    2577             : 
    2578             :     /*
    2579             :      * If it's an EXCLUDE constraint, the grammar returns a list of pairs of
    2580             :      * IndexElems and operator names.  We have to break that apart into
    2581             :      * separate lists.
    2582             :      */
    2583       20022 :     if (constraint->contype == CONSTR_EXCLUSION)
    2584             :     {
    2585         586 :         foreach(lc, constraint->exclusions)
    2586             :         {
    2587         348 :             List       *pair = (List *) lfirst(lc);
    2588             :             IndexElem  *elem;
    2589             :             List       *opname;
    2590             : 
    2591             :             Assert(list_length(pair) == 2);
    2592         348 :             elem = linitial_node(IndexElem, pair);
    2593         348 :             opname = lsecond_node(List, pair);
    2594             : 
    2595         348 :             index->indexParams = lappend(index->indexParams, elem);
    2596         348 :             index->excludeOpNames = lappend(index->excludeOpNames, opname);
    2597             :         }
    2598             :     }
    2599             : 
    2600             :     /*
    2601             :      * For UNIQUE and PRIMARY KEY, we just have a list of column names.
    2602             :      *
    2603             :      * Make sure referenced keys exist.  If we are making a PRIMARY KEY index,
    2604             :      * also make sure they are not-null.  For WITHOUT OVERLAPS constraints, we
    2605             :      * make sure the last part is a range or multirange.
    2606             :      */
    2607             :     else
    2608             :     {
    2609       48048 :         foreach(lc, constraint->keys)
    2610             :         {
    2611       28294 :             char       *key = strVal(lfirst(lc));
    2612       28294 :             bool        found = false;
    2613       28294 :             ColumnDef  *column = NULL;
    2614             :             ListCell   *columns;
    2615             :             IndexElem  *iparam;
    2616       28294 :             Oid         typid = InvalidOid;
    2617             : 
    2618             :             /* Make sure referenced column exists. */
    2619       29962 :             foreach(columns, cxt->columns)
    2620             :             {
    2621       10042 :                 column = lfirst_node(ColumnDef, columns);
    2622       10042 :                 if (strcmp(column->colname, key) == 0)
    2623             :                 {
    2624        8374 :                     found = true;
    2625        8374 :                     break;
    2626             :                 }
    2627             :             }
    2628       28294 :             if (!found)
    2629       19920 :                 column = NULL;
    2630             : 
    2631       28294 :             if (found)
    2632             :             {
    2633             :                 /*
    2634             :                  * column is defined in the new table.  For CREATE TABLE with
    2635             :                  * a PRIMARY KEY, we can apply the not-null constraint cheaply
    2636             :                  * here.  If the not-null constraint already exists, we can
    2637             :                  * (albeit not so cheaply) verify that it's not a NO INHERIT
    2638             :                  * constraint.
    2639             :                  *
    2640             :                  * Note that ALTER TABLE never needs either check, because
    2641             :                  * those constraints have already been added by
    2642             :                  * ATPrepAddPrimaryKey.
    2643             :                  */
    2644        8374 :                 if (constraint->contype == CONSTR_PRIMARY &&
    2645        7592 :                     !cxt->isalter)
    2646             :                 {
    2647        7568 :                     if (column->is_not_null)
    2648             :                     {
    2649       12106 :                         foreach_node(Constraint, nn, cxt->nnconstraints)
    2650             :                         {
    2651        6128 :                             if (strcmp(strVal(linitial(nn->keys)), key) == 0)
    2652             :                             {
    2653        5984 :                                 if (nn->is_no_inherit)
    2654           6 :                                     ereport(ERROR,
    2655             :                                             errcode(ERRCODE_SYNTAX_ERROR),
    2656             :                                             errmsg("conflicting NO INHERIT declaration for not-null constraint on column \"%s\"",
    2657             :                                                    key));
    2658        5978 :                                 break;
    2659             :                             }
    2660             :                         }
    2661             :                     }
    2662             :                     else
    2663             :                     {
    2664        1584 :                         column->is_not_null = true;
    2665        1584 :                         cxt->nnconstraints =
    2666        1584 :                             lappend(cxt->nnconstraints,
    2667        1584 :                                     makeNotNullConstraint(makeString(key)));
    2668             :                     }
    2669             :                 }
    2670          24 :                 else if (constraint->contype == CONSTR_PRIMARY)
    2671             :                     Assert(column->is_not_null);
    2672             :             }
    2673       19920 :             else if (SystemAttributeByName(key) != NULL)
    2674             :             {
    2675             :                 /*
    2676             :                  * column will be a system column in the new table, so accept
    2677             :                  * it. System columns can't ever be null, so no need to worry
    2678             :                  * about PRIMARY/NOT NULL constraint.
    2679             :                  */
    2680           0 :                 found = true;
    2681             :             }
    2682       19920 :             else if (cxt->inhRelations)
    2683             :             {
    2684             :                 /* try inherited tables */
    2685             :                 ListCell   *inher;
    2686             : 
    2687          96 :                 foreach(inher, cxt->inhRelations)
    2688             :                 {
    2689          96 :                     RangeVar   *inh = lfirst_node(RangeVar, inher);
    2690             :                     Relation    rel;
    2691             :                     int         count;
    2692             : 
    2693          96 :                     rel = table_openrv(inh, AccessShareLock);
    2694             :                     /* check user requested inheritance from valid relkind */
    2695          96 :                     if (rel->rd_rel->relkind != RELKIND_RELATION &&
    2696           0 :                         rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
    2697           0 :                         rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
    2698           0 :                         ereport(ERROR,
    2699             :                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2700             :                                  errmsg("inherited relation \"%s\" is not a table or foreign table",
    2701             :                                         inh->relname)));
    2702         102 :                     for (count = 0; count < rel->rd_att->natts; count++)
    2703             :                     {
    2704         102 :                         Form_pg_attribute inhattr = TupleDescAttr(rel->rd_att,
    2705             :                                                                   count);
    2706         102 :                         char       *inhname = NameStr(inhattr->attname);
    2707             : 
    2708         102 :                         if (inhattr->attisdropped)
    2709           0 :                             continue;
    2710         102 :                         if (strcmp(key, inhname) == 0)
    2711             :                         {
    2712          96 :                             found = true;
    2713          96 :                             typid = inhattr->atttypid;
    2714             : 
    2715          96 :                             if (constraint->contype == CONSTR_PRIMARY)
    2716          84 :                                 cxt->nnconstraints =
    2717          84 :                                     lappend(cxt->nnconstraints,
    2718          84 :                                             makeNotNullConstraint(makeString(pstrdup(inhname))));
    2719          96 :                             break;
    2720             :                         }
    2721             :                     }
    2722          96 :                     table_close(rel, NoLock);
    2723          96 :                     if (found)
    2724          96 :                         break;
    2725             :                 }
    2726             :             }
    2727             : 
    2728             :             /*
    2729             :              * In the ALTER TABLE case, don't complain about index keys not
    2730             :              * created in the command; they may well exist already.
    2731             :              * DefineIndex will complain about them if not.
    2732             :              */
    2733       28288 :             if (!found && !cxt->isalter)
    2734          12 :                 ereport(ERROR,
    2735             :                         (errcode(ERRCODE_UNDEFINED_COLUMN),
    2736             :                          errmsg("column \"%s\" named in key does not exist", key),
    2737             :                          parser_errposition(cxt->pstate, constraint->location)));
    2738             : 
    2739             :             /* Check for PRIMARY KEY(foo, foo) */
    2740       39742 :             foreach(columns, index->indexParams)
    2741             :             {
    2742       11466 :                 iparam = (IndexElem *) lfirst(columns);
    2743       11466 :                 if (iparam->name && strcmp(key, iparam->name) == 0)
    2744             :                 {
    2745           0 :                     if (index->primary)
    2746           0 :                         ereport(ERROR,
    2747             :                                 (errcode(ERRCODE_DUPLICATE_COLUMN),
    2748             :                                  errmsg("column \"%s\" appears twice in primary key constraint",
    2749             :                                         key),
    2750             :                                  parser_errposition(cxt->pstate, constraint->location)));
    2751             :                     else
    2752           0 :                         ereport(ERROR,
    2753             :                                 (errcode(ERRCODE_DUPLICATE_COLUMN),
    2754             :                                  errmsg("column \"%s\" appears twice in unique constraint",
    2755             :                                         key),
    2756             :                                  parser_errposition(cxt->pstate, constraint->location)));
    2757             :                 }
    2758             :             }
    2759             : 
    2760             :             /*
    2761             :              * The WITHOUT OVERLAPS part (if any) must be a range or
    2762             :              * multirange type.
    2763             :              */
    2764       28276 :             if (constraint->without_overlaps && lc == list_last_cell(constraint->keys))
    2765             :             {
    2766         558 :                 if (!found && cxt->isalter)
    2767             :                 {
    2768             :                     /*
    2769             :                      * Look up the column type on existing table. If we can't
    2770             :                      * find it, let things fail in DefineIndex.
    2771             :                      */
    2772         182 :                     Relation    rel = cxt->rel;
    2773             : 
    2774         372 :                     for (int i = 0; i < rel->rd_att->natts; i++)
    2775             :                     {
    2776         372 :                         Form_pg_attribute attr = TupleDescAttr(rel->rd_att, i);
    2777             :                         const char *attname;
    2778             : 
    2779         372 :                         if (attr->attisdropped)
    2780           0 :                             break;
    2781             : 
    2782         372 :                         attname = NameStr(attr->attname);
    2783         372 :                         if (strcmp(attname, key) == 0)
    2784             :                         {
    2785         182 :                             found = true;
    2786         182 :                             typid = attr->atttypid;
    2787         182 :                             break;
    2788             :                         }
    2789             :                     }
    2790             :                 }
    2791         558 :                 if (found)
    2792             :                 {
    2793         558 :                     if (!OidIsValid(typid) && column)
    2794         370 :                         typid = typenameTypeId(NULL, column->typeName);
    2795             : 
    2796         558 :                     if (!OidIsValid(typid) || !(type_is_range(typid) || type_is_multirange(typid)))
    2797          12 :                         ereport(ERROR,
    2798             :                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    2799             :                                  errmsg("column \"%s\" in WITHOUT OVERLAPS is not a range or multirange type", key),
    2800             :                                  parser_errposition(cxt->pstate, constraint->location)));
    2801             :                 }
    2802             :             }
    2803             : 
    2804             :             /* OK, add it to the index definition */
    2805       28264 :             iparam = makeNode(IndexElem);
    2806       28264 :             iparam->name = pstrdup(key);
    2807       28264 :             iparam->expr = NULL;
    2808       28264 :             iparam->indexcolname = NULL;
    2809       28264 :             iparam->collation = NIL;
    2810       28264 :             iparam->opclass = NIL;
    2811       28264 :             iparam->opclassopts = NIL;
    2812       28264 :             iparam->ordering = SORTBY_DEFAULT;
    2813       28264 :             iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
    2814       28264 :             index->indexParams = lappend(index->indexParams, iparam);
    2815             :         }
    2816             : 
    2817       19754 :         if (constraint->without_overlaps)
    2818             :         {
    2819             :             /*
    2820             :              * This enforces that there is at least one equality column
    2821             :              * besides the WITHOUT OVERLAPS columns.  This is per SQL
    2822             :              * standard.  XXX Do we need this?
    2823             :              */
    2824         546 :             if (list_length(constraint->keys) < 2)
    2825          12 :                 ereport(ERROR,
    2826             :                         errcode(ERRCODE_SYNTAX_ERROR),
    2827             :                         errmsg("constraint using WITHOUT OVERLAPS needs at least two columns"));
    2828             : 
    2829             :             /* WITHOUT OVERLAPS requires a GiST index */
    2830         534 :             index->accessMethod = "gist";
    2831             :         }
    2832             : 
    2833             :     }
    2834             : 
    2835             :     /*
    2836             :      * Add included columns to index definition.  This is much like the
    2837             :      * simple-column-name-list code above, except that we don't worry about
    2838             :      * NOT NULL marking; included columns in a primary key should not be
    2839             :      * forced NOT NULL.  We don't complain about duplicate columns, either,
    2840             :      * though maybe we should?
    2841             :      */
    2842       20304 :     foreach(lc, constraint->including)
    2843             :     {
    2844         324 :         char       *key = strVal(lfirst(lc));
    2845         324 :         bool        found = false;
    2846         324 :         ColumnDef  *column = NULL;
    2847             :         ListCell   *columns;
    2848             :         IndexElem  *iparam;
    2849             : 
    2850         678 :         foreach(columns, cxt->columns)
    2851             :         {
    2852         544 :             column = lfirst_node(ColumnDef, columns);
    2853         544 :             if (strcmp(column->colname, key) == 0)
    2854             :             {
    2855         190 :                 found = true;
    2856         190 :                 break;
    2857             :             }
    2858             :         }
    2859             : 
    2860         324 :         if (!found)
    2861             :         {
    2862         134 :             if (SystemAttributeByName(key) != NULL)
    2863             :             {
    2864             :                 /*
    2865             :                  * column will be a system column in the new table, so accept
    2866             :                  * it.
    2867             :                  */
    2868           0 :                 found = true;
    2869             :             }
    2870         134 :             else if (cxt->inhRelations)
    2871             :             {
    2872             :                 /* try inherited tables */
    2873             :                 ListCell   *inher;
    2874             : 
    2875           0 :                 foreach(inher, cxt->inhRelations)
    2876             :                 {
    2877           0 :                     RangeVar   *inh = lfirst_node(RangeVar, inher);
    2878             :                     Relation    rel;
    2879             :                     int         count;
    2880             : 
    2881           0 :                     rel = table_openrv(inh, AccessShareLock);
    2882             :                     /* check user requested inheritance from valid relkind */
    2883           0 :                     if (rel->rd_rel->relkind != RELKIND_RELATION &&
    2884           0 :                         rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
    2885           0 :                         rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
    2886           0 :                         ereport(ERROR,
    2887             :                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2888             :                                  errmsg("inherited relation \"%s\" is not a table or foreign table",
    2889             :                                         inh->relname)));
    2890           0 :                     for (count = 0; count < rel->rd_att->natts; count++)
    2891             :                     {
    2892           0 :                         Form_pg_attribute inhattr = TupleDescAttr(rel->rd_att,
    2893             :                                                                   count);
    2894           0 :                         char       *inhname = NameStr(inhattr->attname);
    2895             : 
    2896           0 :                         if (inhattr->attisdropped)
    2897           0 :                             continue;
    2898           0 :                         if (strcmp(key, inhname) == 0)
    2899             :                         {
    2900           0 :                             found = true;
    2901           0 :                             break;
    2902             :                         }
    2903             :                     }
    2904           0 :                     table_close(rel, NoLock);
    2905           0 :                     if (found)
    2906           0 :                         break;
    2907             :                 }
    2908             :             }
    2909             :         }
    2910             : 
    2911             :         /*
    2912             :          * In the ALTER TABLE case, don't complain about index keys not
    2913             :          * created in the command; they may well exist already. DefineIndex
    2914             :          * will complain about them if not.
    2915             :          */
    2916         324 :         if (!found && !cxt->isalter)
    2917           0 :             ereport(ERROR,
    2918             :                     (errcode(ERRCODE_UNDEFINED_COLUMN),
    2919             :                      errmsg("column \"%s\" named in key does not exist", key),
    2920             :                      parser_errposition(cxt->pstate, constraint->location)));
    2921             : 
    2922             :         /* OK, add it to the index definition */
    2923         324 :         iparam = makeNode(IndexElem);
    2924         324 :         iparam->name = pstrdup(key);
    2925         324 :         iparam->expr = NULL;
    2926         324 :         iparam->indexcolname = NULL;
    2927         324 :         iparam->collation = NIL;
    2928         324 :         iparam->opclass = NIL;
    2929         324 :         iparam->opclassopts = NIL;
    2930         324 :         index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
    2931             :     }
    2932             : 
    2933       19980 :     return index;
    2934             : }
    2935             : 
    2936             : /*
    2937             :  * transformCheckConstraints
    2938             :  *      handle CHECK constraints
    2939             :  *
    2940             :  * Right now, there's nothing to do here when called from ALTER TABLE,
    2941             :  * but the other constraint-transformation functions are called in both
    2942             :  * the CREATE TABLE and ALTER TABLE paths, so do the same here, and just
    2943             :  * don't do anything if we're not authorized to skip validation.
    2944             :  */
    2945             : static void
    2946       63494 : transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)
    2947             : {
    2948             :     ListCell   *ckclist;
    2949             : 
    2950       63494 :     if (cxt->ckconstraints == NIL)
    2951       61694 :         return;
    2952             : 
    2953             :     /*
    2954             :      * When creating a new table (but not a foreign table), we can safely skip
    2955             :      * the validation of check constraints and mark them as valid based on the
    2956             :      * constraint enforcement flag, since NOT ENFORCED constraints must always
    2957             :      * be marked as NOT VALID. (This will override any user-supplied NOT VALID
    2958             :      * flag.)
    2959             :      */
    2960        1800 :     if (skipValidation)
    2961             :     {
    2962        1692 :         foreach(ckclist, cxt->ckconstraints)
    2963             :         {
    2964         924 :             Constraint *constraint = (Constraint *) lfirst(ckclist);
    2965             : 
    2966         924 :             constraint->skip_validation = true;
    2967         924 :             constraint->initially_valid = constraint->is_enforced;
    2968             :         }
    2969             :     }
    2970             : }
    2971             : 
    2972             : /*
    2973             :  * transformFKConstraints
    2974             :  *      handle FOREIGN KEY constraints
    2975             :  */
    2976             : static void
    2977       63494 : transformFKConstraints(CreateStmtContext *cxt,
    2978             :                        bool skipValidation, bool isAddConstraint)
    2979             : {
    2980             :     ListCell   *fkclist;
    2981             : 
    2982       63494 :     if (cxt->fkconstraints == NIL)
    2983       59496 :         return;
    2984             : 
    2985             :     /*
    2986             :      * If CREATE TABLE or adding a column with NULL default, we can safely
    2987             :      * skip validation of FK constraints, and mark them as valid based on the
    2988             :      * constraint enforcement flag, since NOT ENFORCED constraints must always
    2989             :      * be marked as NOT VALID. (This will override any user-supplied NOT VALID
    2990             :      * flag.)
    2991             :      */
    2992        3998 :     if (skipValidation)
    2993             :     {
    2994        2776 :         foreach(fkclist, cxt->fkconstraints)
    2995             :         {
    2996        1422 :             Constraint *constraint = (Constraint *) lfirst(fkclist);
    2997             : 
    2998        1422 :             constraint->skip_validation = true;
    2999        1422 :             constraint->initially_valid = constraint->is_enforced;
    3000             :         }
    3001             :     }
    3002             : 
    3003             :     /*
    3004             :      * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
    3005             :      * CONSTRAINT command to execute after the basic command is complete. (If
    3006             :      * called from ADD CONSTRAINT, that routine will add the FK constraints to
    3007             :      * its own subcommand list.)
    3008             :      *
    3009             :      * Note: the ADD CONSTRAINT command must also execute after any index
    3010             :      * creation commands.  Thus, this should run after
    3011             :      * transformIndexConstraints, so that the CREATE INDEX commands are
    3012             :      * already in cxt->alist.  See also the handling of cxt->likeclauses.
    3013             :      */
    3014        3998 :     if (!isAddConstraint)
    3015             :     {
    3016        1348 :         AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
    3017             : 
    3018        1348 :         alterstmt->relation = cxt->relation;
    3019        1348 :         alterstmt->cmds = NIL;
    3020        1348 :         alterstmt->objtype = OBJECT_TABLE;
    3021             : 
    3022        2764 :         foreach(fkclist, cxt->fkconstraints)
    3023             :         {
    3024        1416 :             Constraint *constraint = (Constraint *) lfirst(fkclist);
    3025        1416 :             AlterTableCmd *altercmd = makeNode(AlterTableCmd);
    3026             : 
    3027        1416 :             altercmd->subtype = AT_AddConstraint;
    3028        1416 :             altercmd->name = NULL;
    3029        1416 :             altercmd->def = (Node *) constraint;
    3030        1416 :             alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
    3031             :         }
    3032             : 
    3033        1348 :         cxt->alist = lappend(cxt->alist, alterstmt);
    3034             :     }
    3035             : }
    3036             : 
    3037             : /*
    3038             :  * transformIndexStmt - parse analysis for CREATE INDEX and ALTER TABLE
    3039             :  *
    3040             :  * Note: this is a no-op for an index not using either index expressions or
    3041             :  * a predicate expression.  There are several code paths that create indexes
    3042             :  * without bothering to call this, because they know they don't have any
    3043             :  * such expressions to deal with.
    3044             :  *
    3045             :  * To avoid race conditions, it's important that this function rely only on
    3046             :  * the passed-in relid (and not on stmt->relation) to determine the target
    3047             :  * relation.
    3048             :  */
    3049             : IndexStmt *
    3050       26838 : transformIndexStmt(Oid relid, IndexStmt *stmt, const char *queryString)
    3051             : {
    3052             :     ParseState *pstate;
    3053             :     ParseNamespaceItem *nsitem;
    3054             :     ListCell   *l;
    3055             :     Relation    rel;
    3056             : 
    3057             :     /* Nothing to do if statement already transformed. */
    3058       26838 :     if (stmt->transformed)
    3059         130 :         return stmt;
    3060             : 
    3061             :     /* Set up pstate */
    3062       26708 :     pstate = make_parsestate(NULL);
    3063       26708 :     pstate->p_sourcetext = queryString;
    3064             : 
    3065             :     /*
    3066             :      * Put the parent table into the rtable so that the expressions can refer
    3067             :      * to its fields without qualification.  Caller is responsible for locking
    3068             :      * relation, but we still need to open it.
    3069             :      */
    3070       26708 :     rel = relation_open(relid, NoLock);
    3071       26708 :     nsitem = addRangeTableEntryForRelation(pstate, rel,
    3072             :                                            AccessShareLock,
    3073             :                                            NULL, false, true);
    3074             : 
    3075             :     /* no to join list, yes to namespaces */
    3076       26708 :     addNSItemToQuery(pstate, nsitem, false, true, true);
    3077             : 
    3078             :     /* take care of the where clause */
    3079       26708 :     if (stmt->whereClause)
    3080             :     {
    3081         404 :         stmt->whereClause = transformWhereClause(pstate,
    3082             :                                                  stmt->whereClause,
    3083             :                                                  EXPR_KIND_INDEX_PREDICATE,
    3084             :                                                  "WHERE");
    3085             :         /* we have to fix its collations too */
    3086         404 :         assign_expr_collations(pstate, stmt->whereClause);
    3087             :     }
    3088             : 
    3089             :     /* take care of any index expressions */
    3090       63872 :     foreach(l, stmt->indexParams)
    3091             :     {
    3092       37176 :         IndexElem  *ielem = (IndexElem *) lfirst(l);
    3093             : 
    3094       37176 :         if (ielem->expr)
    3095             :         {
    3096             :             /* Extract preliminary index col name before transforming expr */
    3097         980 :             if (ielem->indexcolname == NULL)
    3098         980 :                 ielem->indexcolname = FigureIndexColname(ielem->expr);
    3099             : 
    3100             :             /* Now do parse transformation of the expression */
    3101         980 :             ielem->expr = transformExpr(pstate, ielem->expr,
    3102             :                                         EXPR_KIND_INDEX_EXPRESSION);
    3103             : 
    3104             :             /* We have to fix its collations too */
    3105         968 :             assign_expr_collations(pstate, ielem->expr);
    3106             : 
    3107             :             /*
    3108             :              * transformExpr() should have already rejected subqueries,
    3109             :              * aggregates, window functions, and SRFs, based on the EXPR_KIND_
    3110             :              * for an index expression.
    3111             :              *
    3112             :              * DefineIndex() will make more checks.
    3113             :              */
    3114             :         }
    3115             :     }
    3116             : 
    3117             :     /*
    3118             :      * Check that only the base rel is mentioned.  (This should be dead code
    3119             :      * now that add_missing_from is history.)
    3120             :      */
    3121       26696 :     if (list_length(pstate->p_rtable) != 1)
    3122           0 :         ereport(ERROR,
    3123             :                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
    3124             :                  errmsg("index expressions and predicates can refer only to the table being indexed")));
    3125             : 
    3126       26696 :     free_parsestate(pstate);
    3127             : 
    3128             :     /* Close relation */
    3129       26696 :     table_close(rel, NoLock);
    3130             : 
    3131             :     /* Mark statement as successfully transformed */
    3132       26696 :     stmt->transformed = true;
    3133             : 
    3134       26696 :     return stmt;
    3135             : }
    3136             : 
    3137             : /*
    3138             :  * transformStatsStmt - parse analysis for CREATE STATISTICS
    3139             :  *
    3140             :  * To avoid race conditions, it's important that this function relies only on
    3141             :  * the passed-in relid (and not on stmt->relation) to determine the target
    3142             :  * relation.
    3143             :  */
    3144             : CreateStatsStmt *
    3145         744 : transformStatsStmt(Oid relid, CreateStatsStmt *stmt, const char *queryString)
    3146             : {
    3147             :     ParseState *pstate;
    3148             :     ParseNamespaceItem *nsitem;
    3149             :     ListCell   *l;
    3150             :     Relation    rel;
    3151             : 
    3152             :     /* Nothing to do if statement already transformed. */
    3153         744 :     if (stmt->transformed)
    3154          48 :         return stmt;
    3155             : 
    3156             :     /* Set up pstate */
    3157         696 :     pstate = make_parsestate(NULL);
    3158         696 :     pstate->p_sourcetext = queryString;
    3159             : 
    3160             :     /*
    3161             :      * Put the parent table into the rtable so that the expressions can refer
    3162             :      * to its fields without qualification.  Caller is responsible for locking
    3163             :      * relation, but we still need to open it.
    3164             :      */
    3165         696 :     rel = relation_open(relid, NoLock);
    3166         696 :     nsitem = addRangeTableEntryForRelation(pstate, rel,
    3167             :                                            AccessShareLock,
    3168             :                                            NULL, false, true);
    3169             : 
    3170             :     /* no to join list, yes to namespaces */
    3171         696 :     addNSItemToQuery(pstate, nsitem, false, true, true);
    3172             : 
    3173             :     /* take care of any expressions */
    3174        2368 :     foreach(l, stmt->exprs)
    3175             :     {
    3176        1672 :         StatsElem  *selem = (StatsElem *) lfirst(l);
    3177             : 
    3178        1672 :         if (selem->expr)
    3179             :         {
    3180             :             /* Now do parse transformation of the expression */
    3181         510 :             selem->expr = transformExpr(pstate, selem->expr,
    3182             :                                         EXPR_KIND_STATS_EXPRESSION);
    3183             : 
    3184             :             /* We have to fix its collations too */
    3185         510 :             assign_expr_collations(pstate, selem->expr);
    3186             :         }
    3187             :     }
    3188             : 
    3189             :     /*
    3190             :      * Check that only the base rel is mentioned.  (This should be dead code
    3191             :      * now that add_missing_from is history.)
    3192             :      */
    3193         696 :     if (list_length(pstate->p_rtable) != 1)
    3194           0 :         ereport(ERROR,
    3195             :                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
    3196             :                  errmsg("statistics expressions can refer only to the table being referenced")));
    3197             : 
    3198         696 :     free_parsestate(pstate);
    3199             : 
    3200             :     /* Close relation */
    3201         696 :     table_close(rel, NoLock);
    3202             : 
    3203             :     /* Mark statement as successfully transformed */
    3204         696 :     stmt->transformed = true;
    3205             : 
    3206         696 :     return stmt;
    3207             : }
    3208             : 
    3209             : 
    3210             : /*
    3211             :  * transformRuleStmt -
    3212             :  *    transform a CREATE RULE Statement. The action is a list of parse
    3213             :  *    trees which is transformed into a list of query trees, and we also
    3214             :  *    transform the WHERE clause if any.
    3215             :  *
    3216             :  * actions and whereClause are output parameters that receive the
    3217             :  * transformed results.
    3218             :  */
    3219             : void
    3220        1174 : transformRuleStmt(RuleStmt *stmt, const char *queryString,
    3221             :                   List **actions, Node **whereClause)
    3222             : {
    3223             :     Relation    rel;
    3224             :     ParseState *pstate;
    3225             :     ParseNamespaceItem *oldnsitem;
    3226             :     ParseNamespaceItem *newnsitem;
    3227             : 
    3228             :     /*
    3229             :      * To avoid deadlock, make sure the first thing we do is grab
    3230             :      * AccessExclusiveLock on the target relation.  This will be needed by
    3231             :      * DefineQueryRewrite(), and we don't want to grab a lesser lock
    3232             :      * beforehand.
    3233             :      */
    3234        1174 :     rel = table_openrv(stmt->relation, AccessExclusiveLock);
    3235             : 
    3236        1174 :     if (rel->rd_rel->relkind == RELKIND_MATVIEW)
    3237           0 :         ereport(ERROR,
    3238             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3239             :                  errmsg("rules on materialized views are not supported")));
    3240             : 
    3241             :     /* Set up pstate */
    3242        1174 :     pstate = make_parsestate(NULL);
    3243        1174 :     pstate->p_sourcetext = queryString;
    3244             : 
    3245             :     /*
    3246             :      * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
    3247             :      * Set up their ParseNamespaceItems in the main pstate for use in parsing
    3248             :      * the rule qualification.
    3249             :      */
    3250        1174 :     oldnsitem = addRangeTableEntryForRelation(pstate, rel,
    3251             :                                               AccessShareLock,
    3252             :                                               makeAlias("old", NIL),
    3253             :                                               false, false);
    3254        1174 :     newnsitem = addRangeTableEntryForRelation(pstate, rel,
    3255             :                                               AccessShareLock,
    3256             :                                               makeAlias("new", NIL),
    3257             :                                               false, false);
    3258             : 
    3259             :     /*
    3260             :      * They must be in the namespace too for lookup purposes, but only add the
    3261             :      * one(s) that are relevant for the current kind of rule.  In an UPDATE
    3262             :      * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
    3263             :      * there's no need to be so picky for INSERT & DELETE.  We do not add them
    3264             :      * to the joinlist.
    3265             :      */
    3266        1174 :     switch (stmt->event)
    3267             :     {
    3268          18 :         case CMD_SELECT:
    3269          18 :             addNSItemToQuery(pstate, oldnsitem, false, true, true);
    3270          18 :             break;
    3271         456 :         case CMD_UPDATE:
    3272         456 :             addNSItemToQuery(pstate, oldnsitem, false, true, true);
    3273         456 :             addNSItemToQuery(pstate, newnsitem, false, true, true);
    3274         456 :             break;
    3275         520 :         case CMD_INSERT:
    3276         520 :             addNSItemToQuery(pstate, newnsitem, false, true, true);
    3277         520 :             break;
    3278         180 :         case CMD_DELETE:
    3279         180 :             addNSItemToQuery(pstate, oldnsitem, false, true, true);
    3280         180 :             break;
    3281           0 :         default:
    3282           0 :             elog(ERROR, "unrecognized event type: %d",
    3283             :                  (int) stmt->event);
    3284             :             break;
    3285             :     }
    3286             : 
    3287             :     /* take care of the where clause */
    3288        1174 :     *whereClause = transformWhereClause(pstate,
    3289             :                                         stmt->whereClause,
    3290             :                                         EXPR_KIND_WHERE,
    3291             :                                         "WHERE");
    3292             :     /* we have to fix its collations too */
    3293        1174 :     assign_expr_collations(pstate, *whereClause);
    3294             : 
    3295             :     /* this is probably dead code without add_missing_from: */
    3296        1174 :     if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
    3297           0 :         ereport(ERROR,
    3298             :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    3299             :                  errmsg("rule WHERE condition cannot contain references to other relations")));
    3300             : 
    3301             :     /*
    3302             :      * 'instead nothing' rules with a qualification need a query rangetable so
    3303             :      * the rewrite handler can add the negated rule qualification to the
    3304             :      * original query. We create a query with the new command type CMD_NOTHING
    3305             :      * here that is treated specially by the rewrite system.
    3306             :      */
    3307        1174 :     if (stmt->actions == NIL)
    3308             :     {
    3309         170 :         Query      *nothing_qry = makeNode(Query);
    3310             : 
    3311         170 :         nothing_qry->commandType = CMD_NOTHING;
    3312         170 :         nothing_qry->rtable = pstate->p_rtable;
    3313         170 :         nothing_qry->rteperminfos = pstate->p_rteperminfos;
    3314         170 :         nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
    3315             : 
    3316         170 :         *actions = list_make1(nothing_qry);
    3317             :     }
    3318             :     else
    3319             :     {
    3320             :         ListCell   *l;
    3321        1004 :         List       *newactions = NIL;
    3322             : 
    3323             :         /*
    3324             :          * transform each statement, like parse_sub_analyze()
    3325             :          */
    3326        2040 :         foreach(l, stmt->actions)
    3327             :         {
    3328        1054 :             Node       *action = (Node *) lfirst(l);
    3329        1054 :             ParseState *sub_pstate = make_parsestate(NULL);
    3330             :             Query      *sub_qry,
    3331             :                        *top_subqry;
    3332             :             bool        has_old,
    3333             :                         has_new;
    3334             : 
    3335             :             /*
    3336             :              * Since outer ParseState isn't parent of inner, have to pass down
    3337             :              * the query text by hand.
    3338             :              */
    3339        1054 :             sub_pstate->p_sourcetext = queryString;
    3340             : 
    3341             :             /*
    3342             :              * Set up OLD/NEW in the rtable for this statement.  The entries
    3343             :              * are added only to relnamespace, not varnamespace, because we
    3344             :              * don't want them to be referred to by unqualified field names
    3345             :              * nor "*" in the rule actions.  We decide later whether to put
    3346             :              * them in the joinlist.
    3347             :              */
    3348        1054 :             oldnsitem = addRangeTableEntryForRelation(sub_pstate, rel,
    3349             :                                                       AccessShareLock,
    3350             :                                                       makeAlias("old", NIL),
    3351             :                                                       false, false);
    3352        1054 :             newnsitem = addRangeTableEntryForRelation(sub_pstate, rel,
    3353             :                                                       AccessShareLock,
    3354             :                                                       makeAlias("new", NIL),
    3355             :                                                       false, false);
    3356        1054 :             addNSItemToQuery(sub_pstate, oldnsitem, false, true, false);
    3357        1054 :             addNSItemToQuery(sub_pstate, newnsitem, false, true, false);
    3358             : 
    3359             :             /* Transform the rule action statement */
    3360        1054 :             top_subqry = transformStmt(sub_pstate, action);
    3361             : 
    3362             :             /*
    3363             :              * We cannot support utility-statement actions (eg NOTIFY) with
    3364             :              * nonempty rule WHERE conditions, because there's no way to make
    3365             :              * the utility action execute conditionally.
    3366             :              */
    3367        1042 :             if (top_subqry->commandType == CMD_UTILITY &&
    3368          42 :                 *whereClause != NULL)
    3369           0 :                 ereport(ERROR,
    3370             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    3371             :                          errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
    3372             : 
    3373             :             /*
    3374             :              * If the action is INSERT...SELECT, OLD/NEW have been pushed down
    3375             :              * into the SELECT, and that's what we need to look at. (Ugly
    3376             :              * kluge ... try to fix this when we redesign querytrees.)
    3377             :              */
    3378        1042 :             sub_qry = getInsertSelectQuery(top_subqry, NULL);
    3379             : 
    3380             :             /*
    3381             :              * If the sub_qry is a setop, we cannot attach any qualifications
    3382             :              * to it, because the planner won't notice them.  This could
    3383             :              * perhaps be relaxed someday, but for now, we may as well reject
    3384             :              * such a rule immediately.
    3385             :              */
    3386        1042 :             if (sub_qry->setOperations != NULL && *whereClause != NULL)
    3387           0 :                 ereport(ERROR,
    3388             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3389             :                          errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
    3390             : 
    3391             :             /*
    3392             :              * Validate action's use of OLD/NEW, qual too
    3393             :              */
    3394        1042 :             has_old =
    3395        1660 :                 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
    3396         618 :                 rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
    3397        1042 :             has_new =
    3398        1384 :                 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
    3399         342 :                 rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
    3400             : 
    3401        1042 :             switch (stmt->event)
    3402             :             {
    3403          18 :                 case CMD_SELECT:
    3404          18 :                     if (has_old)
    3405           0 :                         ereport(ERROR,
    3406             :                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    3407             :                                  errmsg("ON SELECT rule cannot use OLD")));
    3408          18 :                     if (has_new)
    3409           0 :                         ereport(ERROR,
    3410             :                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    3411             :                                  errmsg("ON SELECT rule cannot use NEW")));
    3412          18 :                     break;
    3413         368 :                 case CMD_UPDATE:
    3414             :                     /* both are OK */
    3415         368 :                     break;
    3416         470 :                 case CMD_INSERT:
    3417         470 :                     if (has_old)
    3418           0 :                         ereport(ERROR,
    3419             :                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    3420             :                                  errmsg("ON INSERT rule cannot use OLD")));
    3421         470 :                     break;
    3422         186 :                 case CMD_DELETE:
    3423         186 :                     if (has_new)
    3424           0 :                         ereport(ERROR,
    3425             :                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    3426             :                                  errmsg("ON DELETE rule cannot use NEW")));
    3427         186 :                     break;
    3428           0 :                 default:
    3429           0 :                     elog(ERROR, "unrecognized event type: %d",
    3430             :                          (int) stmt->event);
    3431             :                     break;
    3432             :             }
    3433             : 
    3434             :             /*
    3435             :              * OLD/NEW are not allowed in WITH queries, because they would
    3436             :              * amount to outer references for the WITH, which we disallow.
    3437             :              * However, they were already in the outer rangetable when we
    3438             :              * analyzed the query, so we have to check.
    3439             :              *
    3440             :              * Note that in the INSERT...SELECT case, we need to examine the
    3441             :              * CTE lists of both top_subqry and sub_qry.
    3442             :              *
    3443             :              * Note that we aren't digging into the body of the query looking
    3444             :              * for WITHs in nested sub-SELECTs.  A WITH down there can
    3445             :              * legitimately refer to OLD/NEW, because it'd be an
    3446             :              * indirect-correlated outer reference.
    3447             :              */
    3448        1042 :             if (rangeTableEntry_used((Node *) top_subqry->cteList,
    3449        1036 :                                      PRS2_OLD_VARNO, 0) ||
    3450        1036 :                 rangeTableEntry_used((Node *) sub_qry->cteList,
    3451             :                                      PRS2_OLD_VARNO, 0))
    3452           6 :                 ereport(ERROR,
    3453             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3454             :                          errmsg("cannot refer to OLD within WITH query")));
    3455        1036 :             if (rangeTableEntry_used((Node *) top_subqry->cteList,
    3456        1036 :                                      PRS2_NEW_VARNO, 0) ||
    3457        1036 :                 rangeTableEntry_used((Node *) sub_qry->cteList,
    3458             :                                      PRS2_NEW_VARNO, 0))
    3459           0 :                 ereport(ERROR,
    3460             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3461             :                          errmsg("cannot refer to NEW within WITH query")));
    3462             : 
    3463             :             /*
    3464             :              * For efficiency's sake, add OLD to the rule action's jointree
    3465             :              * only if it was actually referenced in the statement or qual.
    3466             :              *
    3467             :              * For INSERT, NEW is not really a relation (only a reference to
    3468             :              * the to-be-inserted tuple) and should never be added to the
    3469             :              * jointree.
    3470             :              *
    3471             :              * For UPDATE, we treat NEW as being another kind of reference to
    3472             :              * OLD, because it represents references to *transformed* tuples
    3473             :              * of the existing relation.  It would be wrong to enter NEW
    3474             :              * separately in the jointree, since that would cause a double
    3475             :              * join of the updated relation.  It's also wrong to fail to make
    3476             :              * a jointree entry if only NEW and not OLD is mentioned.
    3477             :              */
    3478        1036 :             if (has_old || (has_new && stmt->event == CMD_UPDATE))
    3479             :             {
    3480             :                 RangeTblRef *rtr;
    3481             : 
    3482             :                 /*
    3483             :                  * If sub_qry is a setop, manipulating its jointree will do no
    3484             :                  * good at all, because the jointree is dummy. (This should be
    3485             :                  * a can't-happen case because of prior tests.)
    3486             :                  */
    3487         470 :                 if (sub_qry->setOperations != NULL)
    3488           0 :                     ereport(ERROR,
    3489             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3490             :                              errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
    3491             :                 /* hackishly add OLD to the already-built FROM clause */
    3492         470 :                 rtr = makeNode(RangeTblRef);
    3493         470 :                 rtr->rtindex = oldnsitem->p_rtindex;
    3494         470 :                 sub_qry->jointree->fromlist =
    3495         470 :                     lappend(sub_qry->jointree->fromlist, rtr);
    3496             :             }
    3497             : 
    3498        1036 :             newactions = lappend(newactions, top_subqry);
    3499             : 
    3500        1036 :             free_parsestate(sub_pstate);
    3501             :         }
    3502             : 
    3503         986 :         *actions = newactions;
    3504             :     }
    3505             : 
    3506        1156 :     free_parsestate(pstate);
    3507             : 
    3508             :     /* Close relation, but keep the exclusive lock */
    3509        1156 :     table_close(rel, NoLock);
    3510        1156 : }
    3511             : 
    3512             : 
    3513             : /*
    3514             :  * transformAlterTableStmt -
    3515             :  *      parse analysis for ALTER TABLE
    3516             :  *
    3517             :  * Returns the transformed AlterTableStmt.  There may be additional actions
    3518             :  * to be done before and after the transformed statement, which are returned
    3519             :  * in *beforeStmts and *afterStmts as lists of utility command parsetrees.
    3520             :  *
    3521             :  * To avoid race conditions, it's important that this function rely only on
    3522             :  * the passed-in relid (and not on stmt->relation) to determine the target
    3523             :  * relation.
    3524             :  */
    3525             : AlterTableStmt *
    3526       24584 : transformAlterTableStmt(Oid relid, AlterTableStmt *stmt,
    3527             :                         const char *queryString,
    3528             :                         List **beforeStmts, List **afterStmts)
    3529             : {
    3530             :     Relation    rel;
    3531             :     TupleDesc   tupdesc;
    3532             :     ParseState *pstate;
    3533             :     CreateStmtContext cxt;
    3534             :     List       *save_alist;
    3535             :     ListCell   *lcmd,
    3536             :                *l;
    3537       24584 :     List       *newcmds = NIL;
    3538       24584 :     bool        skipValidation = true;
    3539             :     AlterTableCmd *newcmd;
    3540             :     ParseNamespaceItem *nsitem;
    3541             : 
    3542             :     /* Caller is responsible for locking the relation */
    3543       24584 :     rel = relation_open(relid, NoLock);
    3544       24584 :     tupdesc = RelationGetDescr(rel);
    3545             : 
    3546             :     /* Set up pstate */
    3547       24584 :     pstate = make_parsestate(NULL);
    3548       24584 :     pstate->p_sourcetext = queryString;
    3549       24584 :     nsitem = addRangeTableEntryForRelation(pstate,
    3550             :                                            rel,
    3551             :                                            AccessShareLock,
    3552             :                                            NULL,
    3553             :                                            false,
    3554             :                                            true);
    3555       24584 :     addNSItemToQuery(pstate, nsitem, false, true, true);
    3556             : 
    3557             :     /* Set up CreateStmtContext */
    3558       24584 :     cxt.pstate = pstate;
    3559       24584 :     if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
    3560             :     {
    3561         180 :         cxt.stmtType = "ALTER FOREIGN TABLE";
    3562         180 :         cxt.isforeign = true;
    3563             :     }
    3564             :     else
    3565             :     {
    3566       24404 :         cxt.stmtType = "ALTER TABLE";
    3567       24404 :         cxt.isforeign = false;
    3568             :     }
    3569       24584 :     cxt.relation = stmt->relation;
    3570       24584 :     cxt.rel = rel;
    3571       24584 :     cxt.inhRelations = NIL;
    3572       24584 :     cxt.isalter = true;
    3573       24584 :     cxt.columns = NIL;
    3574       24584 :     cxt.ckconstraints = NIL;
    3575       24584 :     cxt.nnconstraints = NIL;
    3576       24584 :     cxt.fkconstraints = NIL;
    3577       24584 :     cxt.ixconstraints = NIL;
    3578       24584 :     cxt.likeclauses = NIL;
    3579       24584 :     cxt.blist = NIL;
    3580       24584 :     cxt.alist = NIL;
    3581       24584 :     cxt.pkey = NULL;
    3582       24584 :     cxt.ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
    3583       24584 :     cxt.partbound = NULL;
    3584       24584 :     cxt.ofType = false;
    3585             : 
    3586             :     /*
    3587             :      * Transform ALTER subcommands that need it (most don't).  These largely
    3588             :      * re-use code from CREATE TABLE.
    3589             :      */
    3590       49126 :     foreach(lcmd, stmt->cmds)
    3591             :     {
    3592       24584 :         AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
    3593             : 
    3594       24584 :         switch (cmd->subtype)
    3595             :         {
    3596        2050 :             case AT_AddColumn:
    3597             :                 {
    3598        2050 :                     ColumnDef  *def = castNode(ColumnDef, cmd->def);
    3599             : 
    3600        2050 :                     transformColumnDefinition(&cxt, def);
    3601             : 
    3602             :                     /*
    3603             :                      * If the column has a non-null default, we can't skip
    3604             :                      * validation of foreign keys.
    3605             :                      */
    3606        2044 :                     if (def->raw_default != NULL)
    3607         832 :                         skipValidation = false;
    3608             : 
    3609             :                     /*
    3610             :                      * All constraints are processed in other ways. Remove the
    3611             :                      * original list
    3612             :                      */
    3613        2044 :                     def->constraints = NIL;
    3614             : 
    3615        2044 :                     newcmds = lappend(newcmds, cmd);
    3616        2044 :                     break;
    3617             :                 }
    3618             : 
    3619       17078 :             case AT_AddConstraint:
    3620             : 
    3621             :                 /*
    3622             :                  * The original AddConstraint cmd node doesn't go to newcmds
    3623             :                  */
    3624       17078 :                 if (IsA(cmd->def, Constraint))
    3625             :                 {
    3626       17078 :                     transformTableConstraint(&cxt, (Constraint *) cmd->def);
    3627       17072 :                     if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
    3628        2644 :                         skipValidation = false;
    3629             :                 }
    3630             :                 else
    3631           0 :                     elog(ERROR, "unrecognized node type: %d",
    3632             :                          (int) nodeTag(cmd->def));
    3633       17072 :                 break;
    3634             : 
    3635        1318 :             case AT_AlterColumnType:
    3636             :                 {
    3637        1318 :                     ColumnDef  *def = castNode(ColumnDef, cmd->def);
    3638             :                     AttrNumber  attnum;
    3639             : 
    3640             :                     /*
    3641             :                      * For ALTER COLUMN TYPE, transform the USING clause if
    3642             :                      * one was specified.
    3643             :                      */
    3644        1318 :                     if (def->raw_default)
    3645             :                     {
    3646         252 :                         def->cooked_default =
    3647         252 :                             transformExpr(pstate, def->raw_default,
    3648             :                                           EXPR_KIND_ALTER_COL_TRANSFORM);
    3649             :                     }
    3650             : 
    3651             :                     /*
    3652             :                      * For identity column, create ALTER SEQUENCE command to
    3653             :                      * change the data type of the sequence. Identity sequence
    3654             :                      * is associated with the top level partitioned table.
    3655             :                      * Hence ignore partitions.
    3656             :                      */
    3657        1318 :                     if (!RelationGetForm(rel)->relispartition)
    3658             :                     {
    3659        1216 :                         attnum = get_attnum(relid, cmd->name);
    3660        1216 :                         if (attnum == InvalidAttrNumber)
    3661           0 :                             ereport(ERROR,
    3662             :                                     (errcode(ERRCODE_UNDEFINED_COLUMN),
    3663             :                                      errmsg("column \"%s\" of relation \"%s\" does not exist",
    3664             :                                             cmd->name, RelationGetRelationName(rel))));
    3665             : 
    3666        1216 :                         if (attnum > 0 &&
    3667        1210 :                             TupleDescAttr(tupdesc, attnum - 1)->attidentity)
    3668             :                         {
    3669          36 :                             Oid         seq_relid = getIdentitySequence(rel, attnum, false);
    3670          36 :                             Oid         typeOid = typenameTypeId(pstate, def->typeName);
    3671          36 :                             AlterSeqStmt *altseqstmt = makeNode(AlterSeqStmt);
    3672             : 
    3673             :                             altseqstmt->sequence
    3674          36 :                                 = makeRangeVar(get_namespace_name(get_rel_namespace(seq_relid)),
    3675             :                                                get_rel_name(seq_relid),
    3676             :                                                -1);
    3677          36 :                             altseqstmt->options = list_make1(makeDefElem("as",
    3678             :                                                                          (Node *) makeTypeNameFromOid(typeOid, -1),
    3679             :                                                                          -1));
    3680          36 :                             altseqstmt->for_identity = true;
    3681          36 :                             cxt.blist = lappend(cxt.blist, altseqstmt);
    3682             :                         }
    3683             :                     }
    3684             : 
    3685        1318 :                     newcmds = lappend(newcmds, cmd);
    3686        1318 :                     break;
    3687             :                 }
    3688             : 
    3689         210 :             case AT_AddIdentity:
    3690             :                 {
    3691         210 :                     Constraint *def = castNode(Constraint, cmd->def);
    3692         210 :                     ColumnDef  *newdef = makeNode(ColumnDef);
    3693             :                     AttrNumber  attnum;
    3694             : 
    3695         210 :                     newdef->colname = cmd->name;
    3696         210 :                     newdef->identity = def->generated_when;
    3697         210 :                     cmd->def = (Node *) newdef;
    3698             : 
    3699         210 :                     attnum = get_attnum(relid, cmd->name);
    3700         210 :                     if (attnum == InvalidAttrNumber)
    3701           6 :                         ereport(ERROR,
    3702             :                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    3703             :                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
    3704             :                                         cmd->name, RelationGetRelationName(rel))));
    3705             : 
    3706         204 :                     generateSerialExtraStmts(&cxt, newdef,
    3707             :                                              get_atttype(relid, attnum),
    3708             :                                              def->options, true, true,
    3709             :                                              NULL, NULL);
    3710             : 
    3711         204 :                     newcmds = lappend(newcmds, cmd);
    3712         204 :                     break;
    3713             :                 }
    3714             : 
    3715          62 :             case AT_SetIdentity:
    3716             :                 {
    3717             :                     /*
    3718             :                      * Create an ALTER SEQUENCE statement for the internal
    3719             :                      * sequence of the identity column.
    3720             :                      */
    3721             :                     ListCell   *lc;
    3722          62 :                     List       *newseqopts = NIL;
    3723          62 :                     List       *newdef = NIL;
    3724             :                     AttrNumber  attnum;
    3725             :                     Oid         seq_relid;
    3726             : 
    3727             :                     /*
    3728             :                      * Split options into those handled by ALTER SEQUENCE and
    3729             :                      * those for ALTER TABLE proper.
    3730             :                      */
    3731         184 :                     foreach(lc, castNode(List, cmd->def))
    3732             :                     {
    3733         122 :                         DefElem    *def = lfirst_node(DefElem, lc);
    3734             : 
    3735         122 :                         if (strcmp(def->defname, "generated") == 0)
    3736          44 :                             newdef = lappend(newdef, def);
    3737             :                         else
    3738          78 :                             newseqopts = lappend(newseqopts, def);
    3739             :                     }
    3740             : 
    3741          62 :                     attnum = get_attnum(relid, cmd->name);
    3742          62 :                     if (attnum == InvalidAttrNumber)
    3743           0 :                         ereport(ERROR,
    3744             :                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    3745             :                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
    3746             :                                         cmd->name, RelationGetRelationName(rel))));
    3747             : 
    3748          62 :                     seq_relid = getIdentitySequence(rel, attnum, true);
    3749             : 
    3750          62 :                     if (seq_relid)
    3751             :                     {
    3752             :                         AlterSeqStmt *seqstmt;
    3753             : 
    3754          50 :                         seqstmt = makeNode(AlterSeqStmt);
    3755          50 :                         seqstmt->sequence = makeRangeVar(get_namespace_name(get_rel_namespace(seq_relid)),
    3756             :                                                          get_rel_name(seq_relid), -1);
    3757          50 :                         seqstmt->options = newseqopts;
    3758          50 :                         seqstmt->for_identity = true;
    3759          50 :                         seqstmt->missing_ok = false;
    3760             : 
    3761          50 :                         cxt.blist = lappend(cxt.blist, seqstmt);
    3762             :                     }
    3763             : 
    3764             :                     /*
    3765             :                      * If column was not an identity column, we just let the
    3766             :                      * ALTER TABLE command error out later.  (There are cases
    3767             :                      * this fails to cover, but we'll need to restructure
    3768             :                      * where creation of the sequence dependency linkage
    3769             :                      * happens before we can fix it.)
    3770             :                      */
    3771             : 
    3772          62 :                     cmd->def = (Node *) newdef;
    3773          62 :                     newcmds = lappend(newcmds, cmd);
    3774          62 :                     break;
    3775             :                 }
    3776             : 
    3777        3866 :             case AT_AttachPartition:
    3778             :             case AT_DetachPartition:
    3779             :                 {
    3780        3866 :                     PartitionCmd *partcmd = (PartitionCmd *) cmd->def;
    3781             : 
    3782        3866 :                     transformPartitionCmd(&cxt, partcmd);
    3783             :                     /* assign transformed value of the partition bound */
    3784        3842 :                     partcmd->bound = cxt.partbound;
    3785             :                 }
    3786             : 
    3787        3842 :                 newcmds = lappend(newcmds, cmd);
    3788        3842 :                 break;
    3789             : 
    3790           0 :             default:
    3791             : 
    3792             :                 /*
    3793             :                  * Currently, we shouldn't actually get here for subcommand
    3794             :                  * types that don't require transformation; but if we do, just
    3795             :                  * emit them unchanged.
    3796             :                  */
    3797           0 :                 newcmds = lappend(newcmds, cmd);
    3798           0 :                 break;
    3799             :         }
    3800             :     }
    3801             : 
    3802             :     /*
    3803             :      * Transfer anything we already have in cxt.alist into save_alist, to keep
    3804             :      * it separate from the output of transformIndexConstraints.
    3805             :      */
    3806       24542 :     save_alist = cxt.alist;
    3807       24542 :     cxt.alist = NIL;
    3808             : 
    3809             :     /* Postprocess constraints */
    3810       24542 :     transformIndexConstraints(&cxt);
    3811       24518 :     transformFKConstraints(&cxt, skipValidation, true);
    3812       24518 :     transformCheckConstraints(&cxt, false);
    3813             : 
    3814             :     /*
    3815             :      * Push any index-creation commands into the ALTER, so that they can be
    3816             :      * scheduled nicely by tablecmds.c.  Note that tablecmds.c assumes that
    3817             :      * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
    3818             :      * subcommand has already been through transformIndexStmt.
    3819             :      */
    3820       37074 :     foreach(l, cxt.alist)
    3821             :     {
    3822       12556 :         Node       *istmt = (Node *) lfirst(l);
    3823             : 
    3824             :         /*
    3825             :          * We assume here that cxt.alist contains only IndexStmts generated
    3826             :          * from primary key constraints.
    3827             :          */
    3828       12556 :         if (IsA(istmt, IndexStmt))
    3829             :         {
    3830       12556 :             IndexStmt  *idxstmt = (IndexStmt *) istmt;
    3831             : 
    3832       12556 :             idxstmt = transformIndexStmt(relid, idxstmt, queryString);
    3833       12556 :             newcmd = makeNode(AlterTableCmd);
    3834       12556 :             newcmd->subtype = OidIsValid(idxstmt->indexOid) ? AT_AddIndexConstraint : AT_AddIndex;
    3835       12556 :             newcmd->def = (Node *) idxstmt;
    3836       12556 :             newcmds = lappend(newcmds, newcmd);
    3837             :         }
    3838             :         else
    3839           0 :             elog(ERROR, "unexpected stmt type %d", (int) nodeTag(istmt));
    3840             :     }
    3841       24518 :     cxt.alist = NIL;
    3842             : 
    3843             :     /* Append any CHECK, NOT NULL or FK constraints to the commands list */
    3844       50046 :     foreach_node(Constraint, def, cxt.ckconstraints)
    3845             :     {
    3846        1010 :         newcmd = makeNode(AlterTableCmd);
    3847        1010 :         newcmd->subtype = AT_AddConstraint;
    3848        1010 :         newcmd->def = (Node *) def;
    3849        1010 :         newcmds = lappend(newcmds, newcmd);
    3850             :     }
    3851       58378 :     foreach_node(Constraint, def, cxt.nnconstraints)
    3852             :     {
    3853        9342 :         newcmd = makeNode(AlterTableCmd);
    3854        9342 :         newcmd->subtype = AT_AddConstraint;
    3855        9342 :         newcmd->def = (Node *) def;
    3856        9342 :         newcmds = lappend(newcmds, newcmd);
    3857             :     }
    3858       51686 :     foreach_node(Constraint, def, cxt.fkconstraints)
    3859             :     {
    3860        2650 :         newcmd = makeNode(AlterTableCmd);
    3861        2650 :         newcmd->subtype = AT_AddConstraint;
    3862        2650 :         newcmd->def = (Node *) def;
    3863        2650 :         newcmds = lappend(newcmds, newcmd);
    3864             :     }
    3865             : 
    3866             :     /* Close rel */
    3867       24518 :     relation_close(rel, NoLock);
    3868             : 
    3869             :     /*
    3870             :      * Output results.
    3871             :      */
    3872       24518 :     stmt->cmds = newcmds;
    3873             : 
    3874       24518 :     *beforeStmts = cxt.blist;
    3875       24518 :     *afterStmts = list_concat(cxt.alist, save_alist);
    3876             : 
    3877       24518 :     return stmt;
    3878             : }
    3879             : 
    3880             : 
    3881             : /*
    3882             :  * Preprocess a list of column constraint clauses
    3883             :  * to attach constraint attributes to their primary constraint nodes
    3884             :  * and detect inconsistent/misplaced constraint attributes.
    3885             :  *
    3886             :  * NOTE: currently, attributes are only supported for FOREIGN KEY, UNIQUE,
    3887             :  * EXCLUSION, and PRIMARY KEY constraints, but someday they ought to be
    3888             :  * supported for other constraint types.
    3889             :  */
    3890             : static void
    3891       72680 : transformConstraintAttrs(CreateStmtContext *cxt, List *constraintList)
    3892             : {
    3893       72680 :     Constraint *lastprimarycon = NULL;
    3894       72680 :     bool        saw_deferrability = false;
    3895       72680 :     bool        saw_initially = false;
    3896       72680 :     bool        saw_enforced = false;
    3897             :     ListCell   *clist;
    3898             : 
    3899             : #define SUPPORTS_ATTRS(node)                \
    3900             :     ((node) != NULL &&                      \
    3901             :      ((node)->contype == CONSTR_PRIMARY ||   \
    3902             :       (node)->contype == CONSTR_UNIQUE ||    \
    3903             :       (node)->contype == CONSTR_EXCLUSION || \
    3904             :       (node)->contype == CONSTR_FOREIGN))
    3905             : 
    3906       91970 :     foreach(clist, constraintList)
    3907             :     {
    3908       19314 :         Constraint *con = (Constraint *) lfirst(clist);
    3909             : 
    3910       19314 :         if (!IsA(con, Constraint))
    3911           0 :             elog(ERROR, "unrecognized node type: %d",
    3912             :                  (int) nodeTag(con));
    3913       19314 :         switch (con->contype)
    3914             :         {
    3915          94 :             case CONSTR_ATTR_DEFERRABLE:
    3916          94 :                 if (!SUPPORTS_ATTRS(lastprimarycon))
    3917           0 :                     ereport(ERROR,
    3918             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    3919             :                              errmsg("misplaced DEFERRABLE clause"),
    3920             :                              parser_errposition(cxt->pstate, con->location)));
    3921          94 :                 if (saw_deferrability)
    3922           0 :                     ereport(ERROR,
    3923             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    3924             :                              errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
    3925             :                              parser_errposition(cxt->pstate, con->location)));
    3926          94 :                 saw_deferrability = true;
    3927          94 :                 lastprimarycon->deferrable = true;
    3928          94 :                 break;
    3929             : 
    3930           0 :             case CONSTR_ATTR_NOT_DEFERRABLE:
    3931           0 :                 if (!SUPPORTS_ATTRS(lastprimarycon))
    3932           0 :                     ereport(ERROR,
    3933             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    3934             :                              errmsg("misplaced NOT DEFERRABLE clause"),
    3935             :                              parser_errposition(cxt->pstate, con->location)));
    3936           0 :                 if (saw_deferrability)
    3937           0 :                     ereport(ERROR,
    3938             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    3939             :                              errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
    3940             :                              parser_errposition(cxt->pstate, con->location)));
    3941           0 :                 saw_deferrability = true;
    3942           0 :                 lastprimarycon->deferrable = false;
    3943           0 :                 if (saw_initially &&
    3944           0 :                     lastprimarycon->initdeferred)
    3945           0 :                     ereport(ERROR,
    3946             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    3947             :                              errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
    3948             :                              parser_errposition(cxt->pstate, con->location)));
    3949           0 :                 break;
    3950             : 
    3951          76 :             case CONSTR_ATTR_DEFERRED:
    3952          76 :                 if (!SUPPORTS_ATTRS(lastprimarycon))
    3953           0 :                     ereport(ERROR,
    3954             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    3955             :                              errmsg("misplaced INITIALLY DEFERRED clause"),
    3956             :                              parser_errposition(cxt->pstate, con->location)));
    3957          76 :                 if (saw_initially)
    3958           0 :                     ereport(ERROR,
    3959             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    3960             :                              errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
    3961             :                              parser_errposition(cxt->pstate, con->location)));
    3962          76 :                 saw_initially = true;
    3963          76 :                 lastprimarycon->initdeferred = true;
    3964             : 
    3965             :                 /*
    3966             :                  * If only INITIALLY DEFERRED appears, assume DEFERRABLE
    3967             :                  */
    3968          76 :                 if (!saw_deferrability)
    3969          26 :                     lastprimarycon->deferrable = true;
    3970          50 :                 else if (!lastprimarycon->deferrable)
    3971           0 :                     ereport(ERROR,
    3972             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    3973             :                              errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
    3974             :                              parser_errposition(cxt->pstate, con->location)));
    3975          76 :                 break;
    3976             : 
    3977           6 :             case CONSTR_ATTR_IMMEDIATE:
    3978           6 :                 if (!SUPPORTS_ATTRS(lastprimarycon))
    3979           0 :                     ereport(ERROR,
    3980             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    3981             :                              errmsg("misplaced INITIALLY IMMEDIATE clause"),
    3982             :                              parser_errposition(cxt->pstate, con->location)));
    3983           6 :                 if (saw_initially)
    3984           0 :                     ereport(ERROR,
    3985             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    3986             :                              errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
    3987             :                              parser_errposition(cxt->pstate, con->location)));
    3988           6 :                 saw_initially = true;
    3989           6 :                 lastprimarycon->initdeferred = false;
    3990           6 :                 break;
    3991             : 
    3992          36 :             case CONSTR_ATTR_ENFORCED:
    3993          36 :                 if (lastprimarycon == NULL ||
    3994          36 :                     (lastprimarycon->contype != CONSTR_CHECK &&
    3995          12 :                      lastprimarycon->contype != CONSTR_FOREIGN))
    3996           6 :                     ereport(ERROR,
    3997             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    3998             :                              errmsg("misplaced ENFORCED clause"),
    3999             :                              parser_errposition(cxt->pstate, con->location)));
    4000          30 :                 if (saw_enforced)
    4001           6 :                     ereport(ERROR,
    4002             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    4003             :                              errmsg("multiple ENFORCED/NOT ENFORCED clauses not allowed"),
    4004             :                              parser_errposition(cxt->pstate, con->location)));
    4005          24 :                 saw_enforced = true;
    4006          24 :                 lastprimarycon->is_enforced = true;
    4007          24 :                 break;
    4008             : 
    4009          60 :             case CONSTR_ATTR_NOT_ENFORCED:
    4010          60 :                 if (lastprimarycon == NULL ||
    4011          60 :                     (lastprimarycon->contype != CONSTR_CHECK &&
    4012          18 :                      lastprimarycon->contype != CONSTR_FOREIGN))
    4013           6 :                     ereport(ERROR,
    4014             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    4015             :                              errmsg("misplaced NOT ENFORCED clause"),
    4016             :                              parser_errposition(cxt->pstate, con->location)));
    4017          54 :                 if (saw_enforced)
    4018           6 :                     ereport(ERROR,
    4019             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    4020             :                              errmsg("multiple ENFORCED/NOT ENFORCED clauses not allowed"),
    4021             :                              parser_errposition(cxt->pstate, con->location)));
    4022          48 :                 saw_enforced = true;
    4023          48 :                 lastprimarycon->is_enforced = false;
    4024             : 
    4025             :                 /* A NOT ENFORCED constraint must be marked as invalid. */
    4026          48 :                 lastprimarycon->skip_validation = true;
    4027          48 :                 lastprimarycon->initially_valid = false;
    4028          48 :                 break;
    4029             : 
    4030       19042 :             default:
    4031             :                 /* Otherwise it's not an attribute */
    4032       19042 :                 lastprimarycon = con;
    4033             :                 /* reset flags for new primary node */
    4034       19042 :                 saw_deferrability = false;
    4035       19042 :                 saw_initially = false;
    4036       19042 :                 saw_enforced = false;
    4037       19042 :                 break;
    4038             :         }
    4039             :     }
    4040       72656 : }
    4041             : 
    4042             : /*
    4043             :  * Special handling of type definition for a column
    4044             :  */
    4045             : static void
    4046       72364 : transformColumnType(CreateStmtContext *cxt, ColumnDef *column)
    4047             : {
    4048             :     /*
    4049             :      * All we really need to do here is verify that the type is valid,
    4050             :      * including any collation spec that might be present.
    4051             :      */
    4052       72364 :     Type        ctype = typenameType(cxt->pstate, column->typeName, NULL);
    4053             : 
    4054       72350 :     if (column->collClause)
    4055             :     {
    4056         522 :         Form_pg_type typtup = (Form_pg_type) GETSTRUCT(ctype);
    4057             : 
    4058         522 :         LookupCollation(cxt->pstate,
    4059         522 :                         column->collClause->collname,
    4060         522 :                         column->collClause->location);
    4061             :         /* Complain if COLLATE is applied to an uncollatable type */
    4062         510 :         if (!OidIsValid(typtup->typcollation))
    4063          12 :             ereport(ERROR,
    4064             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    4065             :                      errmsg("collations are not supported by type %s",
    4066             :                             format_type_be(typtup->oid)),
    4067             :                      parser_errposition(cxt->pstate,
    4068             :                                         column->collClause->location)));
    4069             :     }
    4070             : 
    4071       72326 :     ReleaseSysCache(ctype);
    4072       72326 : }
    4073             : 
    4074             : 
    4075             : /*
    4076             :  * transformCreateSchemaStmtElements -
    4077             :  *    analyzes the elements of a CREATE SCHEMA statement
    4078             :  *
    4079             :  * Split the schema element list from a CREATE SCHEMA statement into
    4080             :  * individual commands and place them in the result list in an order
    4081             :  * such that there are no forward references (e.g. GRANT to a table
    4082             :  * created later in the list). Note that the logic we use for determining
    4083             :  * forward references is presently quite incomplete.
    4084             :  *
    4085             :  * "schemaName" is the name of the schema that will be used for the creation
    4086             :  * of the objects listed, that may be compiled from the schema name defined
    4087             :  * in the statement or a role specification.
    4088             :  *
    4089             :  * SQL also allows constraints to make forward references, so thumb through
    4090             :  * the table columns and move forward references to a posterior alter-table
    4091             :  * command.
    4092             :  *
    4093             :  * The result is a list of parse nodes that still need to be analyzed ---
    4094             :  * but we can't analyze the later commands until we've executed the earlier
    4095             :  * ones, because of possible inter-object references.
    4096             :  *
    4097             :  * Note: this breaks the rules a little bit by modifying schema-name fields
    4098             :  * within passed-in structs.  However, the transformation would be the same
    4099             :  * if done over, so it should be all right to scribble on the input to this
    4100             :  * extent.
    4101             :  */
    4102             : List *
    4103        1022 : transformCreateSchemaStmtElements(List *schemaElts, const char *schemaName)
    4104             : {
    4105             :     CreateSchemaStmtContext cxt;
    4106             :     List       *result;
    4107             :     ListCell   *elements;
    4108             : 
    4109        1022 :     cxt.schemaname = schemaName;
    4110        1022 :     cxt.sequences = NIL;
    4111        1022 :     cxt.tables = NIL;
    4112        1022 :     cxt.views = NIL;
    4113        1022 :     cxt.indexes = NIL;
    4114        1022 :     cxt.triggers = NIL;
    4115        1022 :     cxt.grants = NIL;
    4116             : 
    4117             :     /*
    4118             :      * Run through each schema element in the schema element list. Separate
    4119             :      * statements by type, and do preliminary analysis.
    4120             :      */
    4121        1472 :     foreach(elements, schemaElts)
    4122             :     {
    4123         540 :         Node       *element = lfirst(elements);
    4124             : 
    4125         540 :         switch (nodeTag(element))
    4126             :         {
    4127          18 :             case T_CreateSeqStmt:
    4128             :                 {
    4129          18 :                     CreateSeqStmt *elp = (CreateSeqStmt *) element;
    4130             : 
    4131          18 :                     setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
    4132           0 :                     cxt.sequences = lappend(cxt.sequences, element);
    4133             :                 }
    4134           0 :                 break;
    4135             : 
    4136         428 :             case T_CreateStmt:
    4137             :                 {
    4138         428 :                     CreateStmt *elp = (CreateStmt *) element;
    4139             : 
    4140         428 :                     setSchemaName(cxt.schemaname, &elp->relation->schemaname);
    4141             : 
    4142             :                     /*
    4143             :                      * XXX todo: deal with constraints
    4144             :                      */
    4145         410 :                     cxt.tables = lappend(cxt.tables, element);
    4146             :                 }
    4147         410 :                 break;
    4148             : 
    4149          44 :             case T_ViewStmt:
    4150             :                 {
    4151          44 :                     ViewStmt   *elp = (ViewStmt *) element;
    4152             : 
    4153          44 :                     setSchemaName(cxt.schemaname, &elp->view->schemaname);
    4154             : 
    4155             :                     /*
    4156             :                      * XXX todo: deal with references between views
    4157             :                      */
    4158          26 :                     cxt.views = lappend(cxt.views, element);
    4159             :                 }
    4160          26 :                 break;
    4161             : 
    4162          32 :             case T_IndexStmt:
    4163             :                 {
    4164          32 :                     IndexStmt  *elp = (IndexStmt *) element;
    4165             : 
    4166          32 :                     setSchemaName(cxt.schemaname, &elp->relation->schemaname);
    4167          14 :                     cxt.indexes = lappend(cxt.indexes, element);
    4168             :                 }
    4169          14 :                 break;
    4170             : 
    4171          18 :             case T_CreateTrigStmt:
    4172             :                 {
    4173          18 :                     CreateTrigStmt *elp = (CreateTrigStmt *) element;
    4174             : 
    4175          18 :                     setSchemaName(cxt.schemaname, &elp->relation->schemaname);
    4176           0 :                     cxt.triggers = lappend(cxt.triggers, element);
    4177             :                 }
    4178           0 :                 break;
    4179             : 
    4180           0 :             case T_GrantStmt:
    4181           0 :                 cxt.grants = lappend(cxt.grants, element);
    4182           0 :                 break;
    4183             : 
    4184           0 :             default:
    4185           0 :                 elog(ERROR, "unrecognized node type: %d",
    4186             :                      (int) nodeTag(element));
    4187             :         }
    4188             :     }
    4189             : 
    4190         932 :     result = NIL;
    4191         932 :     result = list_concat(result, cxt.sequences);
    4192         932 :     result = list_concat(result, cxt.tables);
    4193         932 :     result = list_concat(result, cxt.views);
    4194         932 :     result = list_concat(result, cxt.indexes);
    4195         932 :     result = list_concat(result, cxt.triggers);
    4196         932 :     result = list_concat(result, cxt.grants);
    4197             : 
    4198         932 :     return result;
    4199             : }
    4200             : 
    4201             : /*
    4202             :  * setSchemaName
    4203             :  *      Set or check schema name in an element of a CREATE SCHEMA command
    4204             :  */
    4205             : static void
    4206         540 : setSchemaName(const char *context_schema, char **stmt_schema_name)
    4207             : {
    4208         540 :     if (*stmt_schema_name == NULL)
    4209         432 :         *stmt_schema_name = unconstify(char *, context_schema);
    4210         108 :     else if (strcmp(context_schema, *stmt_schema_name) != 0)
    4211          90 :         ereport(ERROR,
    4212             :                 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
    4213             :                  errmsg("CREATE specifies a schema (%s) "
    4214             :                         "different from the one being created (%s)",
    4215             :                         *stmt_schema_name, context_schema)));
    4216         450 : }
    4217             : 
    4218             : /*
    4219             :  * transformPartitionCmd
    4220             :  *      Analyze the ATTACH/DETACH PARTITION command
    4221             :  *
    4222             :  * In case of the ATTACH PARTITION command, cxt->partbound is set to the
    4223             :  * transformed value of cmd->bound.
    4224             :  */
    4225             : static void
    4226        3866 : transformPartitionCmd(CreateStmtContext *cxt, PartitionCmd *cmd)
    4227             : {
    4228        3866 :     Relation    parentRel = cxt->rel;
    4229             : 
    4230        3866 :     switch (parentRel->rd_rel->relkind)
    4231             :     {
    4232        3384 :         case RELKIND_PARTITIONED_TABLE:
    4233             :             /* transform the partition bound, if any */
    4234             :             Assert(RelationGetPartitionKey(parentRel) != NULL);
    4235        3384 :             if (cmd->bound != NULL)
    4236        2814 :                 cxt->partbound = transformPartitionBound(cxt->pstate, parentRel,
    4237             :                                                          cmd->bound);
    4238        3366 :             break;
    4239         482 :         case RELKIND_PARTITIONED_INDEX:
    4240             : 
    4241             :             /*
    4242             :              * A partitioned index cannot have a partition bound set.  ALTER
    4243             :              * INDEX prevents that with its grammar, but not ALTER TABLE.
    4244             :              */
    4245         482 :             if (cmd->bound != NULL)
    4246           6 :                 ereport(ERROR,
    4247             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    4248             :                          errmsg("\"%s\" is not a partitioned table",
    4249             :                                 RelationGetRelationName(parentRel))));
    4250         476 :             break;
    4251           0 :         case RELKIND_RELATION:
    4252             :             /* the table must be partitioned */
    4253           0 :             ereport(ERROR,
    4254             :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    4255             :                      errmsg("table \"%s\" is not partitioned",
    4256             :                             RelationGetRelationName(parentRel))));
    4257             :             break;
    4258           0 :         case RELKIND_INDEX:
    4259             :             /* the index must be partitioned */
    4260           0 :             ereport(ERROR,
    4261             :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    4262             :                      errmsg("index \"%s\" is not partitioned",
    4263             :                             RelationGetRelationName(parentRel))));
    4264             :             break;
    4265           0 :         default:
    4266             :             /* parser shouldn't let this case through */
    4267           0 :             elog(ERROR, "\"%s\" is not a partitioned table or index",
    4268             :                  RelationGetRelationName(parentRel));
    4269             :             break;
    4270             :     }
    4271        3842 : }
    4272             : 
    4273             : /*
    4274             :  * transformPartitionBound
    4275             :  *
    4276             :  * Transform a partition bound specification
    4277             :  */
    4278             : PartitionBoundSpec *
    4279       10670 : transformPartitionBound(ParseState *pstate, Relation parent,
    4280             :                         PartitionBoundSpec *spec)
    4281             : {
    4282             :     PartitionBoundSpec *result_spec;
    4283       10670 :     PartitionKey key = RelationGetPartitionKey(parent);
    4284       10670 :     char        strategy = get_partition_strategy(key);
    4285       10670 :     int         partnatts = get_partition_natts(key);
    4286       10670 :     List       *partexprs = get_partition_exprs(key);
    4287             : 
    4288             :     /* Avoid scribbling on input */
    4289       10670 :     result_spec = copyObject(spec);
    4290             : 
    4291       10670 :     if (spec->is_default)
    4292             :     {
    4293             :         /*
    4294             :          * Hash partitioning does not support a default partition; there's no
    4295             :          * use case for it (since the set of partitions to create is perfectly
    4296             :          * defined), and if users do get into it accidentally, it's hard to
    4297             :          * back out from it afterwards.
    4298             :          */
    4299         598 :         if (strategy == PARTITION_STRATEGY_HASH)
    4300           6 :             ereport(ERROR,
    4301             :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    4302             :                      errmsg("a hash-partitioned table may not have a default partition")));
    4303             : 
    4304             :         /*
    4305             :          * In case of the default partition, parser had no way to identify the
    4306             :          * partition strategy. Assign the parent's strategy to the default
    4307             :          * partition bound spec.
    4308             :          */
    4309         592 :         result_spec->strategy = strategy;
    4310             : 
    4311         592 :         return result_spec;
    4312             :     }
    4313             : 
    4314       10072 :     if (strategy == PARTITION_STRATEGY_HASH)
    4315             :     {
    4316         726 :         if (spec->strategy != PARTITION_STRATEGY_HASH)
    4317          12 :             ereport(ERROR,
    4318             :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    4319             :                      errmsg("invalid bound specification for a hash partition"),
    4320             :                      parser_errposition(pstate, exprLocation((Node *) spec))));
    4321             : 
    4322         714 :         if (spec->modulus <= 0)
    4323          12 :             ereport(ERROR,
    4324             :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    4325             :                      errmsg("modulus for hash partition must be an integer value greater than zero")));
    4326             : 
    4327             :         Assert(spec->remainder >= 0);
    4328             : 
    4329         702 :         if (spec->remainder >= spec->modulus)
    4330          12 :             ereport(ERROR,
    4331             :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    4332             :                      errmsg("remainder for hash partition must be less than modulus")));
    4333             :     }
    4334        9346 :     else if (strategy == PARTITION_STRATEGY_LIST)
    4335             :     {
    4336             :         ListCell   *cell;
    4337             :         char       *colname;
    4338             :         Oid         coltype;
    4339             :         int32       coltypmod;
    4340             :         Oid         partcollation;
    4341             : 
    4342        5020 :         if (spec->strategy != PARTITION_STRATEGY_LIST)
    4343          18 :             ereport(ERROR,
    4344             :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    4345             :                      errmsg("invalid bound specification for a list partition"),
    4346             :                      parser_errposition(pstate, exprLocation((Node *) spec))));
    4347             : 
    4348             :         /* Get the only column's name in case we need to output an error */
    4349        5002 :         if (key->partattrs[0] != 0)
    4350        4864 :             colname = get_attname(RelationGetRelid(parent),
    4351        4864 :                                   key->partattrs[0], false);
    4352             :         else
    4353         138 :             colname = deparse_expression((Node *) linitial(partexprs),
    4354         138 :                                          deparse_context_for(RelationGetRelationName(parent),
    4355             :                                                              RelationGetRelid(parent)),
    4356             :                                          false, false);
    4357             :         /* Need its type data too */
    4358        5002 :         coltype = get_partition_col_typid(key, 0);
    4359        5002 :         coltypmod = get_partition_col_typmod(key, 0);
    4360        5002 :         partcollation = get_partition_col_collation(key, 0);
    4361             : 
    4362        5002 :         result_spec->listdatums = NIL;
    4363       12446 :         foreach(cell, spec->listdatums)
    4364             :         {
    4365        7504 :             Node       *expr = lfirst(cell);
    4366             :             Const      *value;
    4367             :             ListCell   *cell2;
    4368             :             bool        duplicate;
    4369             : 
    4370        7504 :             value = transformPartitionBoundValue(pstate, expr,
    4371             :                                                  colname, coltype, coltypmod,
    4372             :                                                  partcollation);
    4373             : 
    4374             :             /* Don't add to the result if the value is a duplicate */
    4375        7444 :             duplicate = false;
    4376       12964 :             foreach(cell2, result_spec->listdatums)
    4377             :             {
    4378        5520 :                 Const      *value2 = lfirst_node(Const, cell2);
    4379             : 
    4380        5520 :                 if (equal(value, value2))
    4381             :                 {
    4382           0 :                     duplicate = true;
    4383           0 :                     break;
    4384             :                 }
    4385             :             }
    4386        7444 :             if (duplicate)
    4387           0 :                 continue;
    4388             : 
    4389        7444 :             result_spec->listdatums = lappend(result_spec->listdatums,
    4390             :                                               value);
    4391             :         }
    4392             :     }
    4393        4326 :     else if (strategy == PARTITION_STRATEGY_RANGE)
    4394             :     {
    4395        4326 :         if (spec->strategy != PARTITION_STRATEGY_RANGE)
    4396          18 :             ereport(ERROR,
    4397             :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    4398             :                      errmsg("invalid bound specification for a range partition"),
    4399             :                      parser_errposition(pstate, exprLocation((Node *) spec))));
    4400             : 
    4401        4308 :         if (list_length(spec->lowerdatums) != partnatts)
    4402           6 :             ereport(ERROR,
    4403             :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    4404             :                      errmsg("FROM must specify exactly one value per partitioning column")));
    4405        4302 :         if (list_length(spec->upperdatums) != partnatts)
    4406           6 :             ereport(ERROR,
    4407             :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    4408             :                      errmsg("TO must specify exactly one value per partitioning column")));
    4409             : 
    4410             :         /*
    4411             :          * Convert raw parse nodes into PartitionRangeDatum nodes and perform
    4412             :          * any necessary validation.
    4413             :          */
    4414        4230 :         result_spec->lowerdatums =
    4415        4296 :             transformPartitionRangeBounds(pstate, spec->lowerdatums,
    4416             :                                           parent);
    4417        4224 :         result_spec->upperdatums =
    4418        4230 :             transformPartitionRangeBounds(pstate, spec->upperdatums,
    4419             :                                           parent);
    4420             :     }
    4421             :     else
    4422           0 :         elog(ERROR, "unexpected partition strategy: %d", (int) strategy);
    4423             : 
    4424        9856 :     return result_spec;
    4425             : }
    4426             : 
    4427             : /*
    4428             :  * transformPartitionRangeBounds
    4429             :  *      This converts the expressions for range partition bounds from the raw
    4430             :  *      grammar representation to PartitionRangeDatum structs
    4431             :  */
    4432             : static List *
    4433        8526 : transformPartitionRangeBounds(ParseState *pstate, List *blist,
    4434             :                               Relation parent)
    4435             : {
    4436        8526 :     List       *result = NIL;
    4437        8526 :     PartitionKey key = RelationGetPartitionKey(parent);
    4438        8526 :     List       *partexprs = get_partition_exprs(key);
    4439             :     ListCell   *lc;
    4440             :     int         i,
    4441             :                 j;
    4442             : 
    4443        8526 :     i = j = 0;
    4444       19070 :     foreach(lc, blist)
    4445             :     {
    4446       10598 :         Node       *expr = lfirst(lc);
    4447       10598 :         PartitionRangeDatum *prd = NULL;
    4448             : 
    4449             :         /*
    4450             :          * Infinite range bounds -- "minvalue" and "maxvalue" -- get passed in
    4451             :          * as ColumnRefs.
    4452             :          */
    4453       10598 :         if (IsA(expr, ColumnRef))
    4454             :         {
    4455         752 :             ColumnRef  *cref = (ColumnRef *) expr;
    4456         752 :             char       *cname = NULL;
    4457             : 
    4458             :             /*
    4459             :              * There should be a single field named either "minvalue" or
    4460             :              * "maxvalue".
    4461             :              */
    4462         752 :             if (list_length(cref->fields) == 1 &&
    4463         746 :                 IsA(linitial(cref->fields), String))
    4464         746 :                 cname = strVal(linitial(cref->fields));
    4465             : 
    4466         752 :             if (cname == NULL)
    4467             :             {
    4468             :                 /*
    4469             :                  * ColumnRef is not in the desired single-field-name form. For
    4470             :                  * consistency between all partition strategies, let the
    4471             :                  * expression transformation report any errors rather than
    4472             :                  * doing it ourselves.
    4473             :                  */
    4474             :             }
    4475         746 :             else if (strcmp("minvalue", cname) == 0)
    4476             :             {
    4477         380 :                 prd = makeNode(PartitionRangeDatum);
    4478         380 :                 prd->kind = PARTITION_RANGE_DATUM_MINVALUE;
    4479         380 :                 prd->value = NULL;
    4480             :             }
    4481         366 :             else if (strcmp("maxvalue", cname) == 0)
    4482             :             {
    4483         354 :                 prd = makeNode(PartitionRangeDatum);
    4484         354 :                 prd->kind = PARTITION_RANGE_DATUM_MAXVALUE;
    4485         354 :                 prd->value = NULL;
    4486             :             }
    4487             :         }
    4488             : 
    4489       10598 :         if (prd == NULL)
    4490             :         {
    4491             :             char       *colname;
    4492             :             Oid         coltype;
    4493             :             int32       coltypmod;
    4494             :             Oid         partcollation;
    4495             :             Const      *value;
    4496             : 
    4497             :             /* Get the column's name in case we need to output an error */
    4498        9864 :             if (key->partattrs[i] != 0)
    4499        8978 :                 colname = get_attname(RelationGetRelid(parent),
    4500        8978 :                                       key->partattrs[i], false);
    4501             :             else
    4502             :             {
    4503         886 :                 colname = deparse_expression((Node *) list_nth(partexprs, j),
    4504         886 :                                              deparse_context_for(RelationGetRelationName(parent),
    4505             :                                                                  RelationGetRelid(parent)),
    4506             :                                              false, false);
    4507         886 :                 ++j;
    4508             :             }
    4509             : 
    4510             :             /* Need its type data too */
    4511        9864 :             coltype = get_partition_col_typid(key, i);
    4512        9864 :             coltypmod = get_partition_col_typmod(key, i);
    4513        9864 :             partcollation = get_partition_col_collation(key, i);
    4514             : 
    4515        9864 :             value = transformPartitionBoundValue(pstate, expr,
    4516             :                                                  colname,
    4517             :                                                  coltype, coltypmod,
    4518             :                                                  partcollation);
    4519        9816 :             if (value->constisnull)
    4520           6 :                 ereport(ERROR,
    4521             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    4522             :                          errmsg("cannot specify NULL in range bound")));
    4523        9810 :             prd = makeNode(PartitionRangeDatum);
    4524        9810 :             prd->kind = PARTITION_RANGE_DATUM_VALUE;
    4525        9810 :             prd->value = (Node *) value;
    4526        9810 :             ++i;
    4527             :         }
    4528             : 
    4529       10544 :         prd->location = exprLocation(expr);
    4530             : 
    4531       10544 :         result = lappend(result, prd);
    4532             :     }
    4533             : 
    4534             :     /*
    4535             :      * Once we see MINVALUE or MAXVALUE for one column, the remaining columns
    4536             :      * must be the same.
    4537             :      */
    4538        8472 :     validateInfiniteBounds(pstate, result);
    4539             : 
    4540        8454 :     return result;
    4541             : }
    4542             : 
    4543             : /*
    4544             :  * validateInfiniteBounds
    4545             :  *
    4546             :  * Check that a MAXVALUE or MINVALUE specification in a partition bound is
    4547             :  * followed only by more of the same.
    4548             :  */
    4549             : static void
    4550        8472 : validateInfiniteBounds(ParseState *pstate, List *blist)
    4551             : {
    4552             :     ListCell   *lc;
    4553        8472 :     PartitionRangeDatumKind kind = PARTITION_RANGE_DATUM_VALUE;
    4554             : 
    4555       18992 :     foreach(lc, blist)
    4556             :     {
    4557       10538 :         PartitionRangeDatum *prd = lfirst_node(PartitionRangeDatum, lc);
    4558             : 
    4559       10538 :         if (kind == prd->kind)
    4560        9996 :             continue;
    4561             : 
    4562         542 :         switch (kind)
    4563             :         {
    4564         524 :             case PARTITION_RANGE_DATUM_VALUE:
    4565         524 :                 kind = prd->kind;
    4566         524 :                 break;
    4567             : 
    4568           6 :             case PARTITION_RANGE_DATUM_MAXVALUE:
    4569           6 :                 ereport(ERROR,
    4570             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    4571             :                          errmsg("every bound following MAXVALUE must also be MAXVALUE"),
    4572             :                          parser_errposition(pstate, exprLocation((Node *) prd))));
    4573             :                 break;
    4574             : 
    4575          12 :             case PARTITION_RANGE_DATUM_MINVALUE:
    4576          12 :                 ereport(ERROR,
    4577             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    4578             :                          errmsg("every bound following MINVALUE must also be MINVALUE"),
    4579             :                          parser_errposition(pstate, exprLocation((Node *) prd))));
    4580             :                 break;
    4581             :         }
    4582             :     }
    4583        8454 : }
    4584             : 
    4585             : /*
    4586             :  * Transform one entry in a partition bound spec, producing a constant.
    4587             :  */
    4588             : static Const *
    4589       17368 : transformPartitionBoundValue(ParseState *pstate, Node *val,
    4590             :                              const char *colName, Oid colType, int32 colTypmod,
    4591             :                              Oid partCollation)
    4592             : {
    4593             :     Node       *value;
    4594             : 
    4595             :     /* Transform raw parsetree */
    4596       17368 :     value = transformExpr(pstate, val, EXPR_KIND_PARTITION_BOUND);
    4597             : 
    4598             :     /*
    4599             :      * transformExpr() should have already rejected column references,
    4600             :      * subqueries, aggregates, window functions, and SRFs, based on the
    4601             :      * EXPR_KIND_ of a partition bound expression.
    4602             :      */
    4603             :     Assert(!contain_var_clause(value));
    4604             : 
    4605             :     /*
    4606             :      * Coerce to the correct type.  This might cause an explicit coercion step
    4607             :      * to be added on top of the expression, which must be evaluated before
    4608             :      * returning the result to the caller.
    4609             :      */
    4610       17266 :     value = coerce_to_target_type(pstate,
    4611             :                                   value, exprType(value),
    4612             :                                   colType,
    4613             :                                   colTypmod,
    4614             :                                   COERCION_ASSIGNMENT,
    4615             :                                   COERCE_IMPLICIT_CAST,
    4616             :                                   -1);
    4617             : 
    4618       17266 :     if (value == NULL)
    4619           6 :         ereport(ERROR,
    4620             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    4621             :                  errmsg("specified value cannot be cast to type %s for column \"%s\"",
    4622             :                         format_type_be(colType), colName),
    4623             :                  parser_errposition(pstate, exprLocation(val))));
    4624             : 
    4625             :     /*
    4626             :      * Evaluate the expression, if needed, assigning the partition key's data
    4627             :      * type and collation to the resulting Const node.
    4628             :      */
    4629       17260 :     if (!IsA(value, Const))
    4630             :     {
    4631         550 :         assign_expr_collations(pstate, value);
    4632         550 :         value = (Node *) expression_planner((Expr *) value);
    4633         550 :         value = (Node *) evaluate_expr((Expr *) value, colType, colTypmod,
    4634             :                                        partCollation);
    4635         550 :         if (!IsA(value, Const))
    4636           0 :             elog(ERROR, "could not evaluate partition bound expression");
    4637             :     }
    4638             :     else
    4639             :     {
    4640             :         /*
    4641             :          * If the expression is already a Const, as is often the case, we can
    4642             :          * skip the rather expensive steps above.  But we still have to insert
    4643             :          * the right collation, since coerce_to_target_type doesn't handle
    4644             :          * that.
    4645             :          */
    4646       16710 :         ((Const *) value)->constcollid = partCollation;
    4647             :     }
    4648             : 
    4649             :     /*
    4650             :      * Attach original expression's parse location to the Const, so that
    4651             :      * that's what will be reported for any later errors related to this
    4652             :      * partition bound.
    4653             :      */
    4654       17260 :     ((Const *) value)->location = exprLocation(val);
    4655             : 
    4656       17260 :     return (Const *) value;
    4657             : }

Generated by: LCOV version 1.16