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

Generated by: LCOV version 1.13