LCOV - differential code coverage report
Current view: top level - src/backend/parser - parse_utilcmd.c (source / functions) Coverage Total Hit UBC CBC
Current: a2387c32f2f8a1643c7d71b951587e6bcb2d4744 vs 371a302eecdc82274b0ae2967d18fd726a0aa6a1 Lines: 90.3 % 1644 1484 160 1484
Current Date: 2025-10-26 12:31:50 -0700 Functions: 100.0 % 28 28 28
Baseline: lcov-20251027-010456-baseline Branches: 68.6 % 1420 974 446 974
Baseline Date: 2025-10-26 11:01:32 +1300 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(30,360] days: 98.6 % 144 142 2 142
(360..) days: 89.5 % 1500 1342 158 1342
Function coverage date bins:
(360..) days: 100.0 % 28 28 28
Branch coverage date bins:
(30,360] days: 86.3 % 190 164 26 164
(360..) days: 65.9 % 1230 810 420 810

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

Generated by: LCOV version 2.4-beta