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

Generated by: LCOV version 1.13