LCOV - differential code coverage report
Current view: top level - src/backend/parser - parse_utilcmd.c (source / functions) Coverage Total Hit UBC GNC CBC DCB
Current: f76c13edadc2b319036e0d238703ed56bb23f934 vs 9e17d25e79d4756be08b4a5521b4b58450217137 Lines: 91.0 % 1718 1564 154 5 1559 2
Current Date: 2026-09-20 14:13:17 +0900 Functions: 100.0 % 29 29 1 28
Baseline: lcov-20260920-baseline Branches: 69.8 % 1455 1015 440 8 1007
Baseline Date: 2026-09-20 14:13:13 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 91.9 % 37 34 3 34
(30,360] days: 97.7 % 86 84 2 5 79
(360..) days: 90.7 % 1595 1446 149 1446
Function coverage date bins:
(7,30] days: 100.0 % 2 2 2
(30,360] days: 100.0 % 3 3 3
(360..) days: 100.0 % 24 24 1 23
Branch coverage date bins:
(7,30] days: 100.0 % 12 12 12
(30,360] days: 88.9 % 45 40 5 8 32
(360..) days: 68.9 % 1398 963 435 963

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

Generated by: LCOV version 2.0-1