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

Generated by: LCOV version 1.13