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

Generated by: LCOV version 1.13