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

Generated by: LCOV version 1.14