LCOV - code coverage report
Current view: top level - src/backend/parser - analyze.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 91.6 % 1242 1138
Test Date: 2026-08-18 12:15:49 Functions: 97.5 % 40 39
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 71.1 % 915 651

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * analyze.c
       4                 :             :  *    transform the raw parse tree into a query tree
       5                 :             :  *
       6                 :             :  * For optimizable statements, we are careful to obtain a suitable lock on
       7                 :             :  * each referenced table, and other modules of the backend preserve or
       8                 :             :  * re-obtain these locks before depending on the results.  It is therefore
       9                 :             :  * okay to do significant semantic analysis of these statements.  For
      10                 :             :  * utility commands, no locks are obtained here (and if they were, we could
      11                 :             :  * not be sure we'd still have them at execution).  Hence the general rule
      12                 :             :  * for utility commands is to just dump them into a Query node untransformed.
      13                 :             :  * DECLARE CURSOR, EXPLAIN, and CREATE TABLE AS are exceptions because they
      14                 :             :  * contain optimizable statements, which we should transform.
      15                 :             :  *
      16                 :             :  *
      17                 :             :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
      18                 :             :  * Portions Copyright (c) 1994, Regents of the University of California
      19                 :             :  *
      20                 :             :  *  src/backend/parser/analyze.c
      21                 :             :  *
      22                 :             :  *-------------------------------------------------------------------------
      23                 :             :  */
      24                 :             : 
      25                 :             : #include "postgres.h"
      26                 :             : 
      27                 :             : #include "access/stratnum.h"
      28                 :             : #include "access/sysattr.h"
      29                 :             : #include "catalog/dependency.h"
      30                 :             : #include "catalog/pg_am.h"
      31                 :             : #include "catalog/pg_operator.h"
      32                 :             : #include "catalog/pg_proc.h"
      33                 :             : #include "catalog/pg_type.h"
      34                 :             : #include "commands/defrem.h"
      35                 :             : #include "miscadmin.h"
      36                 :             : #include "nodes/makefuncs.h"
      37                 :             : #include "nodes/nodeFuncs.h"
      38                 :             : #include "nodes/queryjumble.h"
      39                 :             : #include "optimizer/optimizer.h"
      40                 :             : #include "parser/analyze.h"
      41                 :             : #include "parser/parse_agg.h"
      42                 :             : #include "parser/parse_clause.h"
      43                 :             : #include "parser/parse_coerce.h"
      44                 :             : #include "parser/parse_collate.h"
      45                 :             : #include "parser/parse_cte.h"
      46                 :             : #include "parser/parse_expr.h"
      47                 :             : #include "parser/parse_func.h"
      48                 :             : #include "parser/parse_merge.h"
      49                 :             : #include "parser/parse_oper.h"
      50                 :             : #include "parser/parse_param.h"
      51                 :             : #include "parser/parse_relation.h"
      52                 :             : #include "parser/parse_target.h"
      53                 :             : #include "parser/parse_type.h"
      54                 :             : #include "parser/parsetree.h"
      55                 :             : #include "utils/backend_status.h"
      56                 :             : #include "utils/builtins.h"
      57                 :             : #include "utils/fmgroids.h"
      58                 :             : #include "utils/guc.h"
      59                 :             : #include "utils/lsyscache.h"
      60                 :             : #include "utils/rangetypes.h"
      61                 :             : #include "utils/rel.h"
      62                 :             : #include "utils/syscache.h"
      63                 :             : 
      64                 :             : 
      65                 :             : /* Passthrough data for transformPLAssignStmtTarget */
      66                 :             : typedef struct SelectStmtPassthrough
      67                 :             : {
      68                 :             :     PLAssignStmt *stmt;         /* the assignment statement */
      69                 :             :     Node       *target;         /* node representing the target variable */
      70                 :             :     List       *indirection;    /* indirection yet to be applied to target */
      71                 :             : } SelectStmtPassthrough;
      72                 :             : 
      73                 :             : /* Hook for plugins to get control at end of parse analysis */
      74                 :             : post_parse_analyze_hook_type post_parse_analyze_hook = NULL;
      75                 :             : 
      76                 :             : static Query *transformOptionalSelectInto(ParseState *pstate, Node *parseTree);
      77                 :             : static Query *transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt);
      78                 :             : static Query *transformInsertStmt(ParseState *pstate, InsertStmt *stmt);
      79                 :             : static OnConflictExpr *transformOnConflictClause(ParseState *pstate,
      80                 :             :                                                  OnConflictClause *onConflictClause);
      81                 :             : static ForPortionOfExpr *transformForPortionOfClause(ParseState *pstate,
      82                 :             :                                                      int rtindex,
      83                 :             :                                                      const ForPortionOfClause *forPortionOf,
      84                 :             :                                                      const Node *whereClause,
      85                 :             :                                                      bool isUpdate);
      86                 :             : static int  count_rowexpr_columns(ParseState *pstate, Node *expr);
      87                 :             : static Query *transformSelectStmt(ParseState *pstate, SelectStmt *stmt,
      88                 :             :                                   SelectStmtPassthrough *passthru);
      89                 :             : static Query *transformValuesClause(ParseState *pstate, SelectStmt *stmt);
      90                 :             : static Query *transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt);
      91                 :             : static Node *transformSetOperationTree(ParseState *pstate, SelectStmt *stmt,
      92                 :             :                                        bool isTopLevel, List **targetlist);
      93                 :             : static void determineRecursiveColTypes(ParseState *pstate,
      94                 :             :                                        Node *larg, List *nrtargetlist);
      95                 :             : static Query *transformReturnStmt(ParseState *pstate, ReturnStmt *stmt);
      96                 :             : static Query *transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt);
      97                 :             : static Query *transformPLAssignStmt(ParseState *pstate,
      98                 :             :                                     PLAssignStmt *stmt);
      99                 :             : static List *transformPLAssignStmtTarget(ParseState *pstate, List *tlist,
     100                 :             :                                          SelectStmtPassthrough *passthru);
     101                 :             : static Query *transformDeclareCursorStmt(ParseState *pstate,
     102                 :             :                                          DeclareCursorStmt *stmt);
     103                 :             : static Query *transformExplainStmt(ParseState *pstate,
     104                 :             :                                    ExplainStmt *stmt);
     105                 :             : static Query *transformCreateTableAsStmt(ParseState *pstate,
     106                 :             :                                          CreateTableAsStmt *stmt);
     107                 :             : static Query *transformCallStmt(ParseState *pstate,
     108                 :             :                                 CallStmt *stmt);
     109                 :             : static void transformLockingClause(ParseState *pstate, Query *qry,
     110                 :             :                                    LockingClause *lc, bool pushedDown);
     111                 :             : #ifdef DEBUG_NODE_TESTS_ENABLED
     112                 :             : static bool test_raw_expression_coverage(Node *node, void *context);
     113                 :             : #endif
     114                 :             : 
     115                 :             : 
     116                 :             : /*
     117                 :             :  * parse_analyze_fixedparams
     118                 :             :  *      Analyze a raw parse tree and transform it to Query form.
     119                 :             :  *
     120                 :             :  * Optionally, information about $n parameter types can be supplied.
     121                 :             :  * References to $n indexes not defined by paramTypes[] are disallowed.
     122                 :             :  *
     123                 :             :  * The result is a Query node.  Optimizable statements require considerable
     124                 :             :  * transformation, while utility-type statements are simply hung off
     125                 :             :  * a dummy CMD_UTILITY Query node.
     126                 :             :  */
     127                 :             : Query *
     128                 :      493301 : parse_analyze_fixedparams(RawStmt *parseTree, const char *sourceText,
     129                 :             :                           const Oid *paramTypes, int numParams,
     130                 :             :                           QueryEnvironment *queryEnv)
     131                 :             : {
     132                 :      493301 :     ParseState *pstate = make_parsestate(NULL);
     133                 :             :     Query      *query;
     134                 :      493301 :     JumbleState *jstate = NULL;
     135                 :             : 
     136                 :             :     Assert(sourceText != NULL); /* required as of 8.4 */
     137                 :             : 
     138                 :      493301 :     pstate->p_sourcetext = sourceText;
     139                 :             : 
     140         [ +  + ]:      493301 :     if (numParams > 0)
     141                 :        1629 :         setup_parse_fixed_parameters(pstate, paramTypes, numParams);
     142                 :             : 
     143                 :      493301 :     pstate->p_queryEnv = queryEnv;
     144                 :             : 
     145                 :      493301 :     query = transformTopLevelStmt(pstate, parseTree);
     146                 :             : 
     147         [ +  + ]:      487410 :     if (IsQueryIdEnabled())
     148                 :       76709 :         jstate = JumbleQuery(query);
     149                 :             : 
     150         [ +  + ]:      487410 :     if (post_parse_analyze_hook)
     151                 :       76536 :         (*post_parse_analyze_hook) (pstate, query, jstate);
     152                 :             : 
     153                 :      487410 :     free_parsestate(pstate);
     154                 :             : 
     155                 :      487410 :     pgstat_report_query_id(query->queryId, false);
     156                 :             : 
     157                 :      487410 :     return query;
     158                 :             : }
     159                 :             : 
     160                 :             : /*
     161                 :             :  * parse_analyze_varparams
     162                 :             :  *
     163                 :             :  * This variant is used when it's okay to deduce information about $n
     164                 :             :  * symbol datatypes from context.  The passed-in paramTypes[] array can
     165                 :             :  * be modified or enlarged (via repalloc).
     166                 :             :  */
     167                 :             : Query *
     168                 :        7035 : parse_analyze_varparams(RawStmt *parseTree, const char *sourceText,
     169                 :             :                         Oid **paramTypes, int *numParams,
     170                 :             :                         QueryEnvironment *queryEnv)
     171                 :             : {
     172                 :        7035 :     ParseState *pstate = make_parsestate(NULL);
     173                 :             :     Query      *query;
     174                 :        7035 :     JumbleState *jstate = NULL;
     175                 :             : 
     176                 :             :     Assert(sourceText != NULL); /* required as of 8.4 */
     177                 :             : 
     178                 :        7035 :     pstate->p_sourcetext = sourceText;
     179                 :             : 
     180                 :        7035 :     setup_parse_variable_parameters(pstate, paramTypes, numParams);
     181                 :             : 
     182                 :        7035 :     pstate->p_queryEnv = queryEnv;
     183                 :             : 
     184                 :        7035 :     query = transformTopLevelStmt(pstate, parseTree);
     185                 :             : 
     186                 :             :     /* make sure all is well with parameter types */
     187                 :        7026 :     check_variable_parameters(pstate, query);
     188                 :             : 
     189         [ +  + ]:        7026 :     if (IsQueryIdEnabled())
     190                 :         288 :         jstate = JumbleQuery(query);
     191                 :             : 
     192         [ +  + ]:        7026 :     if (post_parse_analyze_hook)
     193                 :         288 :         (*post_parse_analyze_hook) (pstate, query, jstate);
     194                 :             : 
     195                 :        7026 :     free_parsestate(pstate);
     196                 :             : 
     197                 :        7026 :     pgstat_report_query_id(query->queryId, false);
     198                 :             : 
     199                 :        7026 :     return query;
     200                 :             : }
     201                 :             : 
     202                 :             : /*
     203                 :             :  * parse_analyze_withcb
     204                 :             :  *
     205                 :             :  * This variant is used when the caller supplies their own parser callback to
     206                 :             :  * resolve parameters and possibly other things.
     207                 :             :  */
     208                 :             : Query *
     209                 :       25536 : parse_analyze_withcb(RawStmt *parseTree, const char *sourceText,
     210                 :             :                      ParserSetupHook parserSetup,
     211                 :             :                      void *parserSetupArg,
     212                 :             :                      QueryEnvironment *queryEnv)
     213                 :             : {
     214                 :       25536 :     ParseState *pstate = make_parsestate(NULL);
     215                 :             :     Query      *query;
     216                 :       25536 :     JumbleState *jstate = NULL;
     217                 :             : 
     218                 :             :     Assert(sourceText != NULL); /* required as of 8.4 */
     219                 :             : 
     220                 :       25536 :     pstate->p_sourcetext = sourceText;
     221                 :       25536 :     pstate->p_queryEnv = queryEnv;
     222                 :       25536 :     (*parserSetup) (pstate, parserSetupArg);
     223                 :             : 
     224                 :       25536 :     query = transformTopLevelStmt(pstate, parseTree);
     225                 :             : 
     226         [ +  + ]:       25461 :     if (IsQueryIdEnabled())
     227                 :        4105 :         jstate = JumbleQuery(query);
     228                 :             : 
     229         [ +  + ]:       25461 :     if (post_parse_analyze_hook)
     230                 :        4102 :         (*post_parse_analyze_hook) (pstate, query, jstate);
     231                 :             : 
     232                 :       25461 :     free_parsestate(pstate);
     233                 :             : 
     234                 :       25461 :     pgstat_report_query_id(query->queryId, false);
     235                 :             : 
     236                 :       25461 :     return query;
     237                 :             : }
     238                 :             : 
     239                 :             : 
     240                 :             : /*
     241                 :             :  * parse_sub_analyze
     242                 :             :  *      Entry point for recursively analyzing a sub-statement.
     243                 :             :  */
     244                 :             : Query *
     245                 :       73505 : parse_sub_analyze(Node *parseTree, ParseState *parentParseState,
     246                 :             :                   CommonTableExpr *parentCTE,
     247                 :             :                   bool locked_from_parent,
     248                 :             :                   bool resolve_unknowns)
     249                 :             : {
     250                 :       73505 :     ParseState *pstate = make_parsestate(parentParseState);
     251                 :             :     Query      *query;
     252                 :             : 
     253                 :       73505 :     pstate->p_parent_cte = parentCTE;
     254                 :       73505 :     pstate->p_locked_from_parent = locked_from_parent;
     255                 :       73505 :     pstate->p_resolve_unknowns = resolve_unknowns;
     256                 :             : 
     257                 :       73505 :     query = transformStmt(pstate, parseTree);
     258                 :             : 
     259                 :       73364 :     free_parsestate(pstate);
     260                 :             : 
     261                 :       73364 :     return query;
     262                 :             : }
     263                 :             : 
     264                 :             : /*
     265                 :             :  * transformTopLevelStmt -
     266                 :             :  *    transform a Parse tree into a Query tree.
     267                 :             :  *
     268                 :             :  * This function is just responsible for transferring statement location data
     269                 :             :  * from the RawStmt into the finished Query.
     270                 :             :  */
     271                 :             : Query *
     272                 :      528320 : transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree)
     273                 :             : {
     274                 :             :     Query      *result;
     275                 :             : 
     276                 :             :     /* We're at top level, so allow SELECT INTO */
     277                 :      528320 :     result = transformOptionalSelectInto(pstate, parseTree->stmt);
     278                 :             : 
     279                 :      522341 :     result->stmt_location = parseTree->stmt_location;
     280                 :      522341 :     result->stmt_len = parseTree->stmt_len;
     281                 :             : 
     282                 :      522341 :     return result;
     283                 :             : }
     284                 :             : 
     285                 :             : /*
     286                 :             :  * transformOptionalSelectInto -
     287                 :             :  *    If SELECT has INTO, convert it to CREATE TABLE AS.
     288                 :             :  *
     289                 :             :  * The only thing we do here that we don't do in transformStmt() is to
     290                 :             :  * convert SELECT ... INTO into CREATE TABLE AS.  Since utility statements
     291                 :             :  * aren't allowed within larger statements, this is only allowed at the top
     292                 :             :  * of the parse tree, and so we only try it before entering the recursive
     293                 :             :  * transformStmt() processing.
     294                 :             :  */
     295                 :             : static Query *
     296                 :      545072 : transformOptionalSelectInto(ParseState *pstate, Node *parseTree)
     297                 :             : {
     298         [ +  + ]:      545072 :     if (IsA(parseTree, SelectStmt))
     299                 :             :     {
     300                 :      237894 :         SelectStmt *stmt = (SelectStmt *) parseTree;
     301                 :             : 
     302                 :             :         /* If it's a set-operation tree, drill down to leftmost SelectStmt */
     303   [ +  -  +  + ]:      245047 :         while (stmt && stmt->op != SETOP_NONE)
     304                 :        7153 :             stmt = stmt->larg;
     305                 :             :         Assert(stmt && IsA(stmt, SelectStmt) && stmt->larg == NULL);
     306                 :             : 
     307         [ +  + ]:      237894 :         if (stmt->intoClause)
     308                 :             :         {
     309                 :          71 :             CreateTableAsStmt *ctas = makeNode(CreateTableAsStmt);
     310                 :             : 
     311                 :          71 :             ctas->query = parseTree;
     312                 :          71 :             ctas->into = stmt->intoClause;
     313                 :          71 :             ctas->objtype = OBJECT_TABLE;
     314                 :          71 :             ctas->is_select_into = true;
     315                 :             : 
     316                 :             :             /*
     317                 :             :              * Remove the intoClause from the SelectStmt.  This makes it safe
     318                 :             :              * for transformSelectStmt to complain if it finds intoClause set
     319                 :             :              * (implying that the INTO appeared in a disallowed place).
     320                 :             :              */
     321                 :          71 :             stmt->intoClause = NULL;
     322                 :             : 
     323                 :          71 :             parseTree = (Node *) ctas;
     324                 :             :         }
     325                 :             :     }
     326                 :             : 
     327                 :      545072 :     return transformStmt(pstate, parseTree);
     328                 :             : }
     329                 :             : 
     330                 :             : /*
     331                 :             :  * transformStmt -
     332                 :             :  *    recursively transform a Parse tree into a Query tree.
     333                 :             :  */
     334                 :             : Query *
     335                 :      631298 : transformStmt(ParseState *pstate, Node *parseTree)
     336                 :             : {
     337                 :             :     Query      *result;
     338                 :             : 
     339                 :             : #ifdef DEBUG_NODE_TESTS_ENABLED
     340                 :             : 
     341                 :             :     /*
     342                 :             :      * We apply debug_raw_expression_coverage_test testing to basic DML
     343                 :             :      * statements; we can't just run it on everything because
     344                 :             :      * raw_expression_tree_walker() doesn't claim to handle utility
     345                 :             :      * statements.
     346                 :             :      */
     347         [ +  - ]:      631298 :     if (Debug_raw_expression_coverage_test)
     348                 :             :     {
     349         [ +  + ]:      631298 :         switch (nodeTag(parseTree))
     350                 :             :         {
     351                 :      378257 :             case T_SelectStmt:
     352                 :             :             case T_InsertStmt:
     353                 :             :             case T_UpdateStmt:
     354                 :             :             case T_DeleteStmt:
     355                 :             :             case T_MergeStmt:
     356                 :      378257 :                 (void) test_raw_expression_coverage(parseTree, NULL);
     357                 :      378257 :                 break;
     358                 :      253041 :             default:
     359                 :      253041 :                 break;
     360                 :             :         }
     361                 :             :     }
     362                 :             : #endif                          /* DEBUG_NODE_TESTS_ENABLED */
     363                 :             : 
     364                 :             :     /*
     365                 :             :      * Caution: when changing the set of statement types that have non-default
     366                 :             :      * processing here, see also stmt_requires_parse_analysis() and
     367                 :             :      * analyze_requires_snapshot().
     368                 :             :      */
     369   [ +  +  +  +  :      631298 :     switch (nodeTag(parseTree))
          +  +  +  +  +  
                +  +  + ]
     370                 :             :     {
     371                 :             :             /*
     372                 :             :              * Optimizable statements
     373                 :             :              */
     374                 :       43753 :         case T_InsertStmt:
     375                 :       43753 :             result = transformInsertStmt(pstate, (InsertStmt *) parseTree);
     376                 :       42758 :             break;
     377                 :             : 
     378                 :        3428 :         case T_DeleteStmt:
     379                 :        3428 :             result = transformDeleteStmt(pstate, (DeleteStmt *) parseTree);
     380                 :        3336 :             break;
     381                 :             : 
     382                 :        9396 :         case T_UpdateStmt:
     383                 :        9396 :             result = transformUpdateStmt(pstate, (UpdateStmt *) parseTree);
     384                 :        9259 :             break;
     385                 :             : 
     386                 :        1386 :         case T_MergeStmt:
     387                 :        1386 :             result = transformMergeStmt(pstate, (MergeStmt *) parseTree);
     388                 :        1342 :             break;
     389                 :             : 
     390                 :      320294 :         case T_SelectStmt:
     391                 :             :             {
     392                 :      320294 :                 SelectStmt *n = (SelectStmt *) parseTree;
     393                 :             : 
     394         [ +  + ]:      320294 :                 if (n->valuesLists)
     395                 :        5885 :                     result = transformValuesClause(pstate, n);
     396         [ +  + ]:      314409 :                 else if (n->op == SETOP_NONE)
     397                 :      305765 :                     result = transformSelectStmt(pstate, n, NULL);
     398                 :             :                 else
     399                 :        8644 :                     result = transformSetOperationStmt(pstate, n);
     400                 :             :             }
     401                 :      315472 :             break;
     402                 :             : 
     403                 :        2776 :         case T_ReturnStmt:
     404                 :        2776 :             result = transformReturnStmt(pstate, (ReturnStmt *) parseTree);
     405                 :        2772 :             break;
     406                 :             : 
     407                 :        3525 :         case T_PLAssignStmt:
     408                 :        3525 :             result = transformPLAssignStmt(pstate,
     409                 :             :                                            (PLAssignStmt *) parseTree);
     410                 :        3512 :             break;
     411                 :             : 
     412                 :             :             /*
     413                 :             :              * Special cases
     414                 :             :              */
     415                 :        2763 :         case T_DeclareCursorStmt:
     416                 :        2763 :             result = transformDeclareCursorStmt(pstate,
     417                 :             :                                                 (DeclareCursorStmt *) parseTree);
     418                 :        2750 :             break;
     419                 :             : 
     420                 :       16752 :         case T_ExplainStmt:
     421                 :       16752 :             result = transformExplainStmt(pstate,
     422                 :             :                                           (ExplainStmt *) parseTree);
     423                 :       16747 :             break;
     424                 :             : 
     425                 :        1327 :         case T_CreateTableAsStmt:
     426                 :        1327 :             result = transformCreateTableAsStmt(pstate,
     427                 :             :                                                 (CreateTableAsStmt *) parseTree);
     428                 :        1317 :             break;
     429                 :             : 
     430                 :         315 :         case T_CallStmt:
     431                 :         315 :             result = transformCallStmt(pstate,
     432                 :             :                                        (CallStmt *) parseTree);
     433                 :         294 :             break;
     434                 :             : 
     435                 :      225583 :         default:
     436                 :             : 
     437                 :             :             /*
     438                 :             :              * other statements don't require any transformation; just return
     439                 :             :              * the original parsetree with a Query node plastered on top.
     440                 :             :              */
     441                 :      225583 :             result = makeNode(Query);
     442                 :      225583 :             result->commandType = CMD_UTILITY;
     443                 :      225583 :             result->utilityStmt = parseTree;
     444                 :      225583 :             break;
     445                 :             :     }
     446                 :             : 
     447                 :             :     /* Mark as original query until we learn differently */
     448                 :      625142 :     result->querySource = QSRC_ORIGINAL;
     449                 :      625142 :     result->canSetTag = true;
     450                 :             : 
     451                 :      625142 :     return result;
     452                 :             : }
     453                 :             : 
     454                 :             : /*
     455                 :             :  * stmt_requires_parse_analysis
     456                 :             :  *      Returns true if parse analysis will do anything non-trivial
     457                 :             :  *      with the given raw parse tree.
     458                 :             :  *
     459                 :             :  * Generally, this should return true for any statement type for which
     460                 :             :  * transformStmt() does more than wrap a CMD_UTILITY Query around it.
     461                 :             :  * When it returns false, the caller can assume that there is no situation
     462                 :             :  * in which parse analysis of the raw statement could need to be re-done.
     463                 :             :  *
     464                 :             :  * Currently, since the rewriter and planner do nothing for CMD_UTILITY
     465                 :             :  * Queries, a false result means that the entire parse analysis/rewrite/plan
     466                 :             :  * pipeline will never need to be re-done.  If that ever changes, callers
     467                 :             :  * will likely need adjustment.
     468                 :             :  */
     469                 :             : bool
     470                 :    23389819 : stmt_requires_parse_analysis(RawStmt *parseTree)
     471                 :             : {
     472                 :             :     bool        result;
     473                 :             : 
     474      [ +  +  + ]:    23389819 :     switch (nodeTag(parseTree->stmt))
     475                 :             :     {
     476                 :             :             /*
     477                 :             :              * Optimizable statements
     478                 :             :              */
     479                 :    22845616 :         case T_InsertStmt:
     480                 :             :         case T_DeleteStmt:
     481                 :             :         case T_UpdateStmt:
     482                 :             :         case T_MergeStmt:
     483                 :             :         case T_SelectStmt:
     484                 :             :         case T_ReturnStmt:
     485                 :             :         case T_PLAssignStmt:
     486                 :    22845616 :             result = true;
     487                 :    22845616 :             break;
     488                 :             : 
     489                 :             :             /*
     490                 :             :              * Special cases
     491                 :             :              */
     492                 :       33677 :         case T_DeclareCursorStmt:
     493                 :             :         case T_ExplainStmt:
     494                 :             :         case T_CreateTableAsStmt:
     495                 :             :         case T_CallStmt:
     496                 :       33677 :             result = true;
     497                 :       33677 :             break;
     498                 :             : 
     499                 :      510526 :         default:
     500                 :             :             /* all other statements just get wrapped in a CMD_UTILITY Query */
     501                 :      510526 :             result = false;
     502                 :      510526 :             break;
     503                 :             :     }
     504                 :             : 
     505                 :    23389819 :     return result;
     506                 :             : }
     507                 :             : 
     508                 :             : /*
     509                 :             :  * analyze_requires_snapshot
     510                 :             :  *      Returns true if a snapshot must be set before doing parse analysis
     511                 :             :  *      on the given raw parse tree.
     512                 :             :  */
     513                 :             : bool
     514                 :      462507 : analyze_requires_snapshot(RawStmt *parseTree)
     515                 :             : {
     516                 :             :     /*
     517                 :             :      * Currently, this should return true in exactly the same cases that
     518                 :             :      * stmt_requires_parse_analysis() does, so we just invoke that function
     519                 :             :      * rather than duplicating it.  We keep the two entry points separate for
     520                 :             :      * clarity of callers, since from the callers' standpoint these are
     521                 :             :      * different conditions.
     522                 :             :      *
     523                 :             :      * While there may someday be a statement type for which transformStmt()
     524                 :             :      * does something nontrivial and yet no snapshot is needed for that
     525                 :             :      * processing, it seems likely that making such a choice would be fragile.
     526                 :             :      * If you want to install an exception, document the reasoning for it in a
     527                 :             :      * comment.
     528                 :             :      */
     529                 :      462507 :     return stmt_requires_parse_analysis(parseTree);
     530                 :             : }
     531                 :             : 
     532                 :             : /*
     533                 :             :  * query_requires_rewrite_plan()
     534                 :             :  *      Returns true if rewriting or planning is non-trivial for this Query.
     535                 :             :  *
     536                 :             :  * This is much like stmt_requires_parse_analysis(), but applies one step
     537                 :             :  * further down the pipeline.
     538                 :             :  *
     539                 :             :  * We do not provide an equivalent of analyze_requires_snapshot(): callers
     540                 :             :  * can assume that any rewriting or planning activity needs a snapshot.
     541                 :             :  */
     542                 :             : bool
     543                 :      405892 : query_requires_rewrite_plan(Query *query)
     544                 :             : {
     545                 :             :     bool        result;
     546                 :             : 
     547         [ +  - ]:      405892 :     if (query->commandType != CMD_UTILITY)
     548                 :             :     {
     549                 :             :         /* All optimizable statements require rewriting/planning */
     550                 :      405892 :         result = true;
     551                 :             :     }
     552                 :             :     else
     553                 :             :     {
     554                 :             :         /* This list should match stmt_requires_parse_analysis() */
     555         [ #  # ]:           0 :         switch (nodeTag(query->utilityStmt))
     556                 :             :         {
     557                 :           0 :             case T_DeclareCursorStmt:
     558                 :             :             case T_ExplainStmt:
     559                 :             :             case T_CreateTableAsStmt:
     560                 :             :             case T_CallStmt:
     561                 :           0 :                 result = true;
     562                 :           0 :                 break;
     563                 :           0 :             default:
     564                 :           0 :                 result = false;
     565                 :           0 :                 break;
     566                 :             :         }
     567                 :             :     }
     568                 :      405892 :     return result;
     569                 :             : }
     570                 :             : 
     571                 :             : /*
     572                 :             :  * transformDeleteStmt -
     573                 :             :  *    transforms a Delete Statement
     574                 :             :  */
     575                 :             : static Query *
     576                 :        3428 : transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
     577                 :             : {
     578                 :        3428 :     Query      *qry = makeNode(Query);
     579                 :             :     ParseNamespaceItem *nsitem;
     580                 :             :     Node       *qual;
     581                 :             : 
     582                 :        3428 :     qry->commandType = CMD_DELETE;
     583                 :             : 
     584                 :             :     /* process the WITH clause independently of all else */
     585         [ +  + ]:        3428 :     if (stmt->withClause)
     586                 :             :     {
     587                 :          20 :         qry->hasRecursive = stmt->withClause->recursive;
     588                 :          20 :         qry->cteList = transformWithClause(pstate, stmt->withClause);
     589                 :          20 :         qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
     590                 :             :     }
     591                 :             : 
     592                 :             :     /* set up range table with just the result rel */
     593                 :        6852 :     qry->resultRelation = setTargetTable(pstate, stmt->relation,
     594                 :        3428 :                                          stmt->relation->inh,
     595                 :             :                                          true,
     596                 :             :                                          ACL_DELETE);
     597                 :        3424 :     nsitem = pstate->p_target_nsitem;
     598                 :             : 
     599                 :             :     /* disallow DELETE ... WHERE CURRENT OF on a view */
     600         [ +  + ]:        3424 :     if (stmt->whereClause &&
     601         [ +  + ]:        2290 :         IsA(stmt->whereClause, CurrentOfExpr) &&
     602         [ +  + ]:          80 :         pstate->p_target_relation->rd_rel->relkind == RELKIND_VIEW)
     603         [ +  - ]:           4 :         ereport(ERROR,
     604                 :             :                 errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     605                 :             :                 errmsg("WHERE CURRENT OF on a view is not implemented"));
     606                 :             : 
     607                 :             :     /* there's no DISTINCT in DELETE */
     608                 :        3420 :     qry->distinctClause = NIL;
     609                 :             : 
     610                 :             :     /* subqueries in USING cannot access the result relation */
     611                 :        3420 :     nsitem->p_lateral_only = true;
     612                 :        3420 :     nsitem->p_lateral_ok = false;
     613                 :             : 
     614                 :             :     /*
     615                 :             :      * The USING clause is non-standard SQL syntax, and is equivalent in
     616                 :             :      * functionality to the FROM list that can be specified for UPDATE. The
     617                 :             :      * USING keyword is used rather than FROM because FROM is already a
     618                 :             :      * keyword in the DELETE syntax.
     619                 :             :      */
     620                 :        3420 :     transformFromClause(pstate, stmt->usingClause);
     621                 :             : 
     622                 :             :     /* remaining clauses can reference the result relation normally */
     623                 :        3408 :     nsitem->p_lateral_only = false;
     624                 :        3408 :     nsitem->p_lateral_ok = true;
     625                 :             : 
     626         [ +  + ]:        3408 :     if (stmt->forPortionOf)
     627                 :         451 :         qry->forPortionOf = transformForPortionOfClause(pstate,
     628                 :             :                                                         qry->resultRelation,
     629                 :         503 :                                                         stmt->forPortionOf,
     630                 :         503 :                                                         stmt->whereClause,
     631                 :             :                                                         false);
     632                 :             : 
     633                 :        3356 :     qual = transformWhereClause(pstate, stmt->whereClause,
     634                 :             :                                 EXPR_KIND_WHERE, "WHERE");
     635                 :             : 
     636                 :        3340 :     transformReturningClause(pstate, qry, stmt->returningClause,
     637                 :             :                              EXPR_KIND_RETURNING);
     638                 :             : 
     639                 :             :     /* done building the range table and jointree */
     640                 :        3336 :     qry->rtable = pstate->p_rtable;
     641                 :        3336 :     qry->rteperminfos = pstate->p_rteperminfos;
     642                 :        3336 :     qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
     643                 :             : 
     644                 :        3336 :     qry->hasSubLinks = pstate->p_hasSubLinks;
     645                 :        3336 :     qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
     646                 :        3336 :     qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
     647                 :        3336 :     qry->hasAggs = pstate->p_hasAggs;
     648                 :             : 
     649                 :        3336 :     assign_query_collations(pstate, qry);
     650                 :             : 
     651                 :             :     /* this must be done after collations, for reliable comparison of exprs */
     652         [ -  + ]:        3336 :     if (pstate->p_hasAggs)
     653                 :           0 :         parseCheckAggregates(pstate, qry);
     654                 :             : 
     655                 :        3336 :     return qry;
     656                 :             : }
     657                 :             : 
     658                 :             : /*
     659                 :             :  * transformInsertStmt -
     660                 :             :  *    transform an Insert Statement
     661                 :             :  */
     662                 :             : static Query *
     663                 :       43753 : transformInsertStmt(ParseState *pstate, InsertStmt *stmt)
     664                 :             : {
     665                 :       43753 :     Query      *qry = makeNode(Query);
     666                 :       43753 :     SelectStmt *selectStmt = (SelectStmt *) stmt->selectStmt;
     667                 :       43753 :     List       *exprList = NIL;
     668                 :             :     bool        isGeneralSelect;
     669                 :             :     List       *sub_rtable;
     670                 :             :     List       *sub_rteperminfos;
     671                 :             :     List       *sub_namespace;
     672                 :             :     List       *icolumns;
     673                 :             :     List       *attrnos;
     674                 :             :     ParseNamespaceItem *nsitem;
     675                 :             :     RTEPermissionInfo *perminfo;
     676                 :             :     ListCell   *icols;
     677                 :             :     ListCell   *attnos;
     678                 :             :     ListCell   *lc;
     679                 :             :     bool        requiresUpdatePerm;
     680                 :             :     AclMode     targetPerms;
     681                 :             : 
     682                 :             :     /* There can't be any outer WITH to worry about */
     683                 :             :     Assert(pstate->p_ctenamespace == NIL);
     684                 :             : 
     685                 :       43753 :     qry->commandType = CMD_INSERT;
     686                 :             : 
     687                 :             :     /* process the WITH clause independently of all else */
     688         [ +  + ]:       43753 :     if (stmt->withClause)
     689                 :             :     {
     690                 :         190 :         qry->hasRecursive = stmt->withClause->recursive;
     691                 :         190 :         qry->cteList = transformWithClause(pstate, stmt->withClause);
     692                 :         190 :         qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
     693                 :             :     }
     694                 :             : 
     695                 :       43753 :     qry->override = stmt->override;
     696                 :             : 
     697                 :             :     /*
     698                 :             :      * ON CONFLICT DO UPDATE and ON CONFLICT DO SELECT FOR UPDATE/SHARE
     699                 :             :      * require UPDATE permission on the target relation.
     700                 :             :      */
     701         [ +  + ]:       45314 :     requiresUpdatePerm = (stmt->onConflictClause &&
     702         [ +  + ]:        1561 :                           (stmt->onConflictClause->action == ONCONFLICT_UPDATE ||
     703         [ +  + ]:         626 :                            (stmt->onConflictClause->action == ONCONFLICT_SELECT &&
     704         [ +  + ]:         240 :                             stmt->onConflictClause->lockStrength != LCS_NONE)));
     705                 :             : 
     706                 :             :     /*
     707                 :             :      * We have three cases to deal with: DEFAULT VALUES (selectStmt == NULL),
     708                 :             :      * VALUES list, or general SELECT input.  We special-case VALUES, both for
     709                 :             :      * efficiency and so we can handle DEFAULT specifications.
     710                 :             :      *
     711                 :             :      * The grammar allows attaching ORDER BY, LIMIT, FOR UPDATE, or WITH to a
     712                 :             :      * VALUES clause.  If we have any of those, treat it as a general SELECT;
     713                 :             :      * so it will work, but you can't use DEFAULT items together with those.
     714                 :             :      */
     715   [ +  +  +  + ]:       77424 :     isGeneralSelect = (selectStmt && (selectStmt->valuesLists == NIL ||
     716         [ +  - ]:       33671 :                                       selectStmt->sortClause != NIL ||
     717         [ +  - ]:       33671 :                                       selectStmt->limitOffset != NULL ||
     718         [ +  - ]:       33671 :                                       selectStmt->limitCount != NULL ||
     719         [ +  - ]:       33671 :                                       selectStmt->lockingClause != NIL ||
     720         [ -  + ]:       33671 :                                       selectStmt->withClause != NULL));
     721                 :             : 
     722                 :             :     /*
     723                 :             :      * If a non-nil rangetable/namespace was passed in, and we are doing
     724                 :             :      * INSERT/SELECT, arrange to pass the rangetable/rteperminfos/namespace
     725                 :             :      * down to the SELECT.  This can only happen if we are inside a CREATE
     726                 :             :      * RULE, and in that case we want the rule's OLD and NEW rtable entries to
     727                 :             :      * appear as part of the SELECT's rtable, not as outer references for it.
     728                 :             :      * (Kluge!) The SELECT's joinlist is not affected however.  We must do
     729                 :             :      * this before adding the target table to the INSERT's rtable.
     730                 :             :      */
     731         [ +  + ]:       43753 :     if (isGeneralSelect)
     732                 :             :     {
     733                 :        4550 :         sub_rtable = pstate->p_rtable;
     734                 :        4550 :         pstate->p_rtable = NIL;
     735                 :        4550 :         sub_rteperminfos = pstate->p_rteperminfos;
     736                 :        4550 :         pstate->p_rteperminfos = NIL;
     737                 :        4550 :         sub_namespace = pstate->p_namespace;
     738                 :        4550 :         pstate->p_namespace = NIL;
     739                 :             :     }
     740                 :             :     else
     741                 :             :     {
     742                 :       39203 :         sub_rtable = NIL;       /* not used, but keep compiler quiet */
     743                 :       39203 :         sub_rteperminfos = NIL;
     744                 :       39203 :         sub_namespace = NIL;
     745                 :             :     }
     746                 :             : 
     747                 :             :     /*
     748                 :             :      * Must get write lock on INSERT target table before scanning SELECT, else
     749                 :             :      * we will grab the wrong kind of initial lock if the target table is also
     750                 :             :      * mentioned in the SELECT part.  Note that the target table is not added
     751                 :             :      * to the joinlist or namespace.
     752                 :             :      */
     753                 :       43753 :     targetPerms = ACL_INSERT;
     754         [ +  + ]:       43753 :     if (requiresUpdatePerm)
     755                 :        1013 :         targetPerms |= ACL_UPDATE;
     756                 :       43753 :     qry->resultRelation = setTargetTable(pstate, stmt->relation,
     757                 :             :                                          false, false, targetPerms);
     758                 :             : 
     759                 :             :     /* Validate stmt->cols list, or build default list if no list given */
     760                 :       43737 :     icolumns = checkInsertTargets(pstate, stmt->cols, &attrnos);
     761                 :             :     Assert(list_length(icolumns) == list_length(attrnos));
     762                 :             : 
     763                 :             :     /*
     764                 :             :      * Determine which variant of INSERT we have.
     765                 :             :      */
     766         [ +  + ]:       43705 :     if (selectStmt == NULL)
     767                 :             :     {
     768                 :             :         /*
     769                 :             :          * We have INSERT ... DEFAULT VALUES.  We can handle this case by
     770                 :             :          * emitting an empty targetlist --- all columns will be defaulted when
     771                 :             :          * the planner expands the targetlist.
     772                 :             :          */
     773                 :        5532 :         exprList = NIL;
     774                 :             :     }
     775         [ +  + ]:       38173 :     else if (isGeneralSelect)
     776                 :             :     {
     777                 :             :         /*
     778                 :             :          * We make the sub-pstate a child of the outer pstate so that it can
     779                 :             :          * see any Param definitions supplied from above.  Since the outer
     780                 :             :          * pstate's rtable and namespace are presently empty, there are no
     781                 :             :          * side-effects of exposing names the sub-SELECT shouldn't be able to
     782                 :             :          * see.
     783                 :             :          */
     784                 :        4550 :         ParseState *sub_pstate = make_parsestate(pstate);
     785                 :             :         Query      *selectQuery;
     786                 :             : 
     787                 :             :         /*
     788                 :             :          * Process the source SELECT.
     789                 :             :          *
     790                 :             :          * It is important that this be handled just like a standalone SELECT;
     791                 :             :          * otherwise the behavior of SELECT within INSERT might be different
     792                 :             :          * from a stand-alone SELECT. (Indeed, Postgres up through 6.5 had
     793                 :             :          * bugs of just that nature...)
     794                 :             :          *
     795                 :             :          * The sole exception is that we prevent resolving unknown-type
     796                 :             :          * outputs as TEXT.  This does not change the semantics since if the
     797                 :             :          * column type matters semantically, it would have been resolved to
     798                 :             :          * something else anyway.  Doing this lets us resolve such outputs as
     799                 :             :          * the target column's type, which we handle below.
     800                 :             :          */
     801                 :        4550 :         sub_pstate->p_rtable = sub_rtable;
     802                 :        4550 :         sub_pstate->p_rteperminfos = sub_rteperminfos;
     803                 :        4550 :         sub_pstate->p_joinexprs = NIL;   /* sub_rtable has no joins */
     804                 :        4550 :         sub_pstate->p_nullingrels = NIL;
     805                 :        4550 :         sub_pstate->p_namespace = sub_namespace;
     806                 :        4550 :         sub_pstate->p_resolve_unknowns = false;
     807                 :             : 
     808                 :        4550 :         selectQuery = transformStmt(sub_pstate, stmt->selectStmt);
     809                 :             : 
     810                 :        4546 :         free_parsestate(sub_pstate);
     811                 :             : 
     812                 :             :         /* The grammar should have produced a SELECT */
     813         [ +  - ]:        4546 :         if (!IsA(selectQuery, Query) ||
     814         [ -  + ]:        4546 :             selectQuery->commandType != CMD_SELECT)
     815         [ #  # ]:           0 :             elog(ERROR, "unexpected non-SELECT command in INSERT ... SELECT");
     816                 :             : 
     817                 :             :         /*
     818                 :             :          * Make the source be a subquery in the INSERT's rangetable, and add
     819                 :             :          * it to the INSERT's joinlist (but not the namespace).
     820                 :             :          */
     821                 :        4546 :         nsitem = addRangeTableEntryForSubquery(pstate,
     822                 :             :                                                selectQuery,
     823                 :             :                                                NULL,
     824                 :             :                                                false,
     825                 :             :                                                false);
     826                 :        4546 :         addNSItemToQuery(pstate, nsitem, true, false, false);
     827                 :             : 
     828                 :             :         /*----------
     829                 :             :          * Generate an expression list for the INSERT that selects all the
     830                 :             :          * non-resjunk columns from the subquery.  (INSERT's tlist must be
     831                 :             :          * separate from the subquery's tlist because we may add columns,
     832                 :             :          * insert datatype coercions, etc.)
     833                 :             :          *
     834                 :             :          * HACK: unknown-type constants and params in the SELECT's targetlist
     835                 :             :          * are copied up as-is rather than being referenced as subquery
     836                 :             :          * outputs.  This is to ensure that when we try to coerce them to
     837                 :             :          * the target column's datatype, the right things happen (see
     838                 :             :          * special cases in coerce_type).  Otherwise, this fails:
     839                 :             :          *      INSERT INTO foo SELECT 'bar', ... FROM baz
     840                 :             :          *----------
     841                 :             :          */
     842                 :        4546 :         exprList = NIL;
     843   [ +  +  +  +  :       15900 :         foreach(lc, selectQuery->targetList)
                   +  + ]
     844                 :             :         {
     845                 :       11354 :             TargetEntry *tle = (TargetEntry *) lfirst(lc);
     846                 :             :             Expr       *expr;
     847                 :             : 
     848         [ +  + ]:       11354 :             if (tle->resjunk)
     849                 :          64 :                 continue;
     850         [ +  - ]:       11290 :             if (tle->expr &&
     851   [ +  +  +  +  :       14006 :                 (IsA(tle->expr, Const) || IsA(tle->expr, Param)) &&
                   +  + ]
     852                 :        2716 :                 exprType((Node *) tle->expr) == UNKNOWNOID)
     853                 :         848 :                 expr = tle->expr;
     854                 :             :             else
     855                 :             :             {
     856                 :       10442 :                 Var        *var = makeVarFromTargetEntry(nsitem->p_rtindex, tle);
     857                 :             : 
     858                 :       10442 :                 var->location = exprLocation((Node *) tle->expr);
     859                 :       10442 :                 expr = (Expr *) var;
     860                 :             :             }
     861                 :       11290 :             exprList = lappend(exprList, expr);
     862                 :             :         }
     863                 :             : 
     864                 :             :         /* Prepare row for assignment to target table */
     865                 :        4546 :         exprList = transformInsertRow(pstate, exprList,
     866                 :             :                                       stmt->cols,
     867                 :             :                                       icolumns, attrnos,
     868                 :             :                                       false);
     869                 :             :     }
     870         [ +  + ]:       33623 :     else if (list_length(selectStmt->valuesLists) > 1)
     871                 :             :     {
     872                 :             :         /*
     873                 :             :          * Process INSERT ... VALUES with multiple VALUES sublists. We
     874                 :             :          * generate a VALUES RTE holding the transformed expression lists, and
     875                 :             :          * build up a targetlist containing Vars that reference the VALUES
     876                 :             :          * RTE.
     877                 :             :          */
     878                 :        3391 :         List       *exprsLists = NIL;
     879                 :        3391 :         List       *coltypes = NIL;
     880                 :        3391 :         List       *coltypmods = NIL;
     881                 :        3391 :         List       *colcollations = NIL;
     882                 :        3391 :         int         sublist_length = -1;
     883                 :        3391 :         bool        lateral = false;
     884                 :             : 
     885                 :             :         Assert(selectStmt->intoClause == NULL);
     886                 :             : 
     887   [ +  -  +  +  :       14885 :         foreach(lc, selectStmt->valuesLists)
                   +  + ]
     888                 :             :         {
     889                 :       11494 :             List       *sublist = (List *) lfirst(lc);
     890                 :             : 
     891                 :             :             /*
     892                 :             :              * Do basic expression transformation (same as a ROW() expr, but
     893                 :             :              * allow SetToDefault at top level)
     894                 :             :              */
     895                 :       11494 :             sublist = transformExpressionList(pstate, sublist,
     896                 :             :                                               EXPR_KIND_VALUES, true);
     897                 :             : 
     898                 :             :             /*
     899                 :             :              * All the sublists must be the same length, *after*
     900                 :             :              * transformation (which might expand '*' into multiple items).
     901                 :             :              * The VALUES RTE can't handle anything different.
     902                 :             :              */
     903         [ +  + ]:       11494 :             if (sublist_length < 0)
     904                 :             :             {
     905                 :             :                 /* Remember post-transformation length of first sublist */
     906                 :        3391 :                 sublist_length = list_length(sublist);
     907                 :             :             }
     908         [ -  + ]:        8103 :             else if (sublist_length != list_length(sublist))
     909                 :             :             {
     910         [ #  # ]:           0 :                 ereport(ERROR,
     911                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     912                 :             :                          errmsg("VALUES lists must all be the same length"),
     913                 :             :                          parser_errposition(pstate,
     914                 :             :                                             exprLocation((Node *) sublist))));
     915                 :             :             }
     916                 :             : 
     917                 :             :             /*
     918                 :             :              * Prepare row for assignment to target table.  We process any
     919                 :             :              * indirection on the target column specs normally but then strip
     920                 :             :              * off the resulting field/array assignment nodes, since we don't
     921                 :             :              * want the parsed statement to contain copies of those in each
     922                 :             :              * VALUES row.  (It's annoying to have to transform the
     923                 :             :              * indirection specs over and over like this, but avoiding it
     924                 :             :              * would take some really messy refactoring of
     925                 :             :              * transformAssignmentIndirection.)
     926                 :             :              */
     927                 :       11494 :             sublist = transformInsertRow(pstate, sublist,
     928                 :             :                                          stmt->cols,
     929                 :             :                                          icolumns, attrnos,
     930                 :             :                                          true);
     931                 :             : 
     932                 :             :             /*
     933                 :             :              * We must assign collations now because assign_query_collations
     934                 :             :              * doesn't process rangetable entries.  We just assign all the
     935                 :             :              * collations independently in each row, and don't worry about
     936                 :             :              * whether they are consistent vertically.  The outer INSERT query
     937                 :             :              * isn't going to care about the collations of the VALUES columns,
     938                 :             :              * so it's not worth the effort to identify a common collation for
     939                 :             :              * each one here.  (But note this does have one user-visible
     940                 :             :              * consequence: INSERT ... VALUES won't complain about conflicting
     941                 :             :              * explicit COLLATEs in a column, whereas the same VALUES
     942                 :             :              * construct in another context would complain.)
     943                 :             :              */
     944                 :       11494 :             assign_list_collations(pstate, sublist);
     945                 :             : 
     946                 :       11494 :             exprsLists = lappend(exprsLists, sublist);
     947                 :             :         }
     948                 :             : 
     949                 :             :         /*
     950                 :             :          * Construct column type/typmod/collation lists for the VALUES RTE.
     951                 :             :          * Every expression in each column has been coerced to the type/typmod
     952                 :             :          * of the corresponding target column or subfield, so it's sufficient
     953                 :             :          * to look at the exprType/exprTypmod of the first row.  We don't care
     954                 :             :          * about the collation labeling, so just fill in InvalidOid for that.
     955                 :             :          */
     956   [ +  -  +  +  :        9828 :         foreach(lc, (List *) linitial(exprsLists))
                   +  + ]
     957                 :             :         {
     958                 :        6437 :             Node       *val = (Node *) lfirst(lc);
     959                 :             : 
     960                 :        6437 :             coltypes = lappend_oid(coltypes, exprType(val));
     961                 :        6437 :             coltypmods = lappend_int(coltypmods, exprTypmod(val));
     962                 :        6437 :             colcollations = lappend_oid(colcollations, InvalidOid);
     963                 :             :         }
     964                 :             : 
     965                 :             :         /*
     966                 :             :          * Ordinarily there can't be any current-level Vars in the expression
     967                 :             :          * lists, because the namespace was empty ... but if we're inside
     968                 :             :          * CREATE RULE, then NEW/OLD references might appear.  In that case we
     969                 :             :          * have to mark the VALUES RTE as LATERAL.
     970                 :             :          */
     971   [ +  +  +  - ]:        3409 :         if (list_length(pstate->p_rtable) != 1 &&
     972                 :          18 :             contain_vars_of_level((Node *) exprsLists, 0))
     973                 :          18 :             lateral = true;
     974                 :             : 
     975                 :             :         /*
     976                 :             :          * Generate the VALUES RTE
     977                 :             :          */
     978                 :        3391 :         nsitem = addRangeTableEntryForValues(pstate, exprsLists,
     979                 :             :                                              coltypes, coltypmods, colcollations,
     980                 :             :                                              NULL, lateral, true);
     981                 :        3391 :         addNSItemToQuery(pstate, nsitem, true, false, false);
     982                 :             : 
     983                 :             :         /*
     984                 :             :          * Generate list of Vars referencing the RTE
     985                 :             :          */
     986                 :        3391 :         exprList = expandNSItemVars(pstate, nsitem, 0, -1, NULL);
     987                 :             : 
     988                 :             :         /*
     989                 :             :          * Re-apply any indirection on the target column specs to the Vars
     990                 :             :          */
     991                 :        3391 :         exprList = transformInsertRow(pstate, exprList,
     992                 :             :                                       stmt->cols,
     993                 :             :                                       icolumns, attrnos,
     994                 :             :                                       false);
     995                 :             :     }
     996                 :             :     else
     997                 :             :     {
     998                 :             :         /*
     999                 :             :          * Process INSERT ... VALUES with a single VALUES sublist.  We treat
    1000                 :             :          * this case separately for efficiency.  The sublist is just computed
    1001                 :             :          * directly as the Query's targetlist, with no VALUES RTE.  So it
    1002                 :             :          * works just like a SELECT without any FROM.
    1003                 :             :          */
    1004                 :       30232 :         List       *valuesLists = selectStmt->valuesLists;
    1005                 :             : 
    1006                 :             :         Assert(list_length(valuesLists) == 1);
    1007                 :             :         Assert(selectStmt->intoClause == NULL);
    1008                 :             : 
    1009                 :             :         /*
    1010                 :             :          * Do basic expression transformation (same as a ROW() expr, but allow
    1011                 :             :          * SetToDefault at top level)
    1012                 :             :          */
    1013                 :       30232 :         exprList = transformExpressionList(pstate,
    1014                 :       30232 :                                            (List *) linitial(valuesLists),
    1015                 :             :                                            EXPR_KIND_VALUES_SINGLE,
    1016                 :             :                                            true);
    1017                 :             : 
    1018                 :             :         /* Prepare row for assignment to target table */
    1019                 :       30216 :         exprList = transformInsertRow(pstate, exprList,
    1020                 :             :                                       stmt->cols,
    1021                 :             :                                       icolumns, attrnos,
    1022                 :             :                                       false);
    1023                 :             :     }
    1024                 :             : 
    1025                 :             :     /*
    1026                 :             :      * Generate query's target list using the computed list of expressions.
    1027                 :             :      * Also, mark all the target columns as needing insert permissions.
    1028                 :             :      */
    1029                 :       42834 :     perminfo = pstate->p_target_nsitem->p_perminfo;
    1030                 :       42834 :     qry->targetList = NIL;
    1031                 :             :     Assert(list_length(exprList) <= list_length(icolumns));
    1032   [ +  +  +  +  :      126226 :     forthree(lc, exprList, icols, icolumns, attnos, attrnos)
          +  +  +  +  +  
          +  +  +  +  +  
          +  -  +  -  +  
                      + ]
    1033                 :             :     {
    1034                 :       83392 :         Expr       *expr = (Expr *) lfirst(lc);
    1035                 :       83392 :         ResTarget  *col = lfirst_node(ResTarget, icols);
    1036                 :       83392 :         AttrNumber  attr_num = (AttrNumber) lfirst_int(attnos);
    1037                 :             :         TargetEntry *tle;
    1038                 :             : 
    1039                 :       83392 :         tle = makeTargetEntry(expr,
    1040                 :             :                               attr_num,
    1041                 :             :                               col->name,
    1042                 :             :                               false);
    1043                 :       83392 :         qry->targetList = lappend(qry->targetList, tle);
    1044                 :             : 
    1045                 :       83392 :         perminfo->insertedCols = bms_add_member(perminfo->insertedCols,
    1046                 :             :                                                 attr_num - FirstLowInvalidHeapAttributeNumber);
    1047                 :             :     }
    1048                 :             : 
    1049                 :             :     /*
    1050                 :             :      * If we have any clauses yet to process, set the query namespace to
    1051                 :             :      * contain only the target relation, removing any entries added in a
    1052                 :             :      * sub-SELECT or VALUES list.
    1053                 :             :      */
    1054   [ +  +  +  + ]:       42834 :     if (stmt->onConflictClause || stmt->returningClause)
    1055                 :             :     {
    1056                 :        2208 :         pstate->p_namespace = NIL;
    1057                 :        2208 :         addNSItemToQuery(pstate, pstate->p_target_nsitem,
    1058                 :             :                          false, true, true);
    1059                 :             :     }
    1060                 :             : 
    1061                 :             :     /* ON CONFLICT DO SELECT requires a RETURNING clause */
    1062         [ +  + ]:       42834 :     if (stmt->onConflictClause &&
    1063         [ +  + ]:        1561 :         stmt->onConflictClause->action == ONCONFLICT_SELECT &&
    1064         [ +  + ]:         240 :         !stmt->returningClause)
    1065         [ +  - ]:           4 :         ereport(ERROR,
    1066                 :             :                 errcode(ERRCODE_SYNTAX_ERROR),
    1067                 :             :                 errmsg("ON CONFLICT DO SELECT requires a RETURNING clause"),
    1068                 :             :                 parser_errposition(pstate, stmt->onConflictClause->location));
    1069                 :             : 
    1070                 :             :     /* Process ON CONFLICT, if any. */
    1071         [ +  + ]:       42830 :     if (stmt->onConflictClause)
    1072                 :        1557 :         qry->onConflict = transformOnConflictClause(pstate,
    1073                 :             :                                                     stmt->onConflictClause);
    1074                 :             : 
    1075                 :             :     /* Process RETURNING, if any. */
    1076         [ +  + ]:       42790 :     if (stmt->returningClause)
    1077                 :        1099 :         transformReturningClause(pstate, qry, stmt->returningClause,
    1078                 :             :                                  EXPR_KIND_RETURNING);
    1079                 :             : 
    1080                 :             :     /* done building the range table and jointree */
    1081                 :       42758 :     qry->rtable = pstate->p_rtable;
    1082                 :       42758 :     qry->rteperminfos = pstate->p_rteperminfos;
    1083                 :       42758 :     qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
    1084                 :             : 
    1085                 :       42758 :     qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
    1086                 :       42758 :     qry->hasSubLinks = pstate->p_hasSubLinks;
    1087                 :             : 
    1088                 :       42758 :     assign_query_collations(pstate, qry);
    1089                 :             : 
    1090                 :       42758 :     return qry;
    1091                 :             : }
    1092                 :             : 
    1093                 :             : /*
    1094                 :             :  * Prepare an INSERT row for assignment to the target table.
    1095                 :             :  *
    1096                 :             :  * exprlist: transformed expressions for source values; these might come from
    1097                 :             :  * a VALUES row, or be Vars referencing a sub-SELECT or VALUES RTE output.
    1098                 :             :  * stmtcols: original target-columns spec for INSERT (we just test for NIL)
    1099                 :             :  * icolumns: effective target-columns spec (list of ResTarget)
    1100                 :             :  * attrnos: integer column numbers (must be same length as icolumns)
    1101                 :             :  * strip_indirection: if true, remove any field/array assignment nodes
    1102                 :             :  */
    1103                 :             : List *
    1104                 :       50303 : transformInsertRow(ParseState *pstate, List *exprlist,
    1105                 :             :                    List *stmtcols, List *icolumns, List *attrnos,
    1106                 :             :                    bool strip_indirection)
    1107                 :             : {
    1108                 :             :     List       *result;
    1109                 :             :     ListCell   *lc;
    1110                 :             :     ListCell   *icols;
    1111                 :             :     ListCell   *attnos;
    1112                 :             : 
    1113                 :             :     /*
    1114                 :             :      * Check length of expr list.  It must not have more expressions than
    1115                 :             :      * there are target columns.  We allow fewer, but only if no explicit
    1116                 :             :      * columns list was given (the remaining columns are implicitly
    1117                 :             :      * defaulted).  Note we must check this *after* transformation because
    1118                 :             :      * that could expand '*' into multiple items.
    1119                 :             :      */
    1120         [ +  + ]:       50303 :     if (list_length(exprlist) > list_length(icolumns))
    1121         [ +  - ]:          17 :         ereport(ERROR,
    1122                 :             :                 (errcode(ERRCODE_SYNTAX_ERROR),
    1123                 :             :                  errmsg("INSERT has more expressions than target columns"),
    1124                 :             :                  parser_errposition(pstate,
    1125                 :             :                                     exprLocation(list_nth(exprlist,
    1126                 :             :                                                           list_length(icolumns))))));
    1127   [ +  +  +  + ]:       61261 :     if (stmtcols != NIL &&
    1128                 :       10975 :         list_length(exprlist) < list_length(icolumns))
    1129                 :             :     {
    1130                 :             :         /*
    1131                 :             :          * We can get here for cases like INSERT ... SELECT (a,b,c) FROM ...
    1132                 :             :          * where the user accidentally created a RowExpr instead of separate
    1133                 :             :          * columns.  Add a suitable hint if that seems to be the problem,
    1134                 :             :          * because the main error message is quite misleading for this case.
    1135                 :             :          * (If there's no stmtcols, you'll get something about data type
    1136                 :             :          * mismatch, which is less misleading so we don't worry about giving a
    1137                 :             :          * hint in that case.)
    1138                 :             :          */
    1139   [ +  -  -  +  :           8 :         ereport(ERROR,
                   -  - ]
    1140                 :             :                 (errcode(ERRCODE_SYNTAX_ERROR),
    1141                 :             :                  errmsg("INSERT has more target columns than expressions"),
    1142                 :             :                  ((list_length(exprlist) == 1 &&
    1143                 :             :                    count_rowexpr_columns(pstate, linitial(exprlist)) ==
    1144                 :             :                    list_length(icolumns)) ?
    1145                 :             :                   errhint("The insertion source is a row expression containing the same number of columns expected by the INSERT. Did you accidentally use extra parentheses?") : 0),
    1146                 :             :                  parser_errposition(pstate,
    1147                 :             :                                     exprLocation(list_nth(icolumns,
    1148                 :             :                                                           list_length(exprlist))))));
    1149                 :             :     }
    1150                 :             : 
    1151                 :             :     /*
    1152                 :             :      * Prepare columns for assignment to target table.
    1153                 :             :      */
    1154                 :       50278 :     result = NIL;
    1155   [ +  +  +  +  :      160270 :     forthree(lc, exprlist, icols, icolumns, attnos, attrnos)
          +  +  +  +  +  
          +  +  +  +  +  
          +  -  +  -  +  
                      + ]
    1156                 :             :     {
    1157                 :      110818 :         Expr       *expr = (Expr *) lfirst(lc);
    1158                 :      110818 :         ResTarget  *col = lfirst_node(ResTarget, icols);
    1159                 :      110818 :         int         attno = lfirst_int(attnos);
    1160                 :             : 
    1161                 :      110818 :         expr = transformAssignedExpr(pstate, expr,
    1162                 :             :                                      EXPR_KIND_INSERT_TARGET,
    1163                 :      110818 :                                      col->name,
    1164                 :             :                                      attno,
    1165                 :             :                                      col->indirection,
    1166                 :             :                                      col->location);
    1167                 :             : 
    1168         [ +  + ]:      109992 :         if (strip_indirection)
    1169                 :             :         {
    1170                 :             :             /*
    1171                 :             :              * We need to remove top-level FieldStores and SubscriptingRefs,
    1172                 :             :              * as well as any CoerceToDomain appearing above one of those ---
    1173                 :             :              * but not a CoerceToDomain that isn't above one of those.
    1174                 :             :              */
    1175         [ +  - ]:       25456 :             while (expr)
    1176                 :             :             {
    1177                 :       25456 :                 Expr       *subexpr = expr;
    1178                 :             : 
    1179         [ +  + ]:       25632 :                 while (IsA(subexpr, CoerceToDomain))
    1180                 :             :                 {
    1181                 :         176 :                     subexpr = ((CoerceToDomain *) subexpr)->arg;
    1182                 :             :                 }
    1183         [ +  + ]:       25456 :                 if (IsA(subexpr, FieldStore))
    1184                 :             :                 {
    1185                 :         144 :                     FieldStore *fstore = (FieldStore *) subexpr;
    1186                 :             : 
    1187                 :         144 :                     expr = (Expr *) linitial(fstore->newvals);
    1188                 :             :                 }
    1189         [ +  + ]:       25312 :                 else if (IsA(subexpr, SubscriptingRef))
    1190                 :             :                 {
    1191                 :         232 :                     SubscriptingRef *sbsref = (SubscriptingRef *) subexpr;
    1192                 :             : 
    1193         [ -  + ]:         232 :                     if (sbsref->refassgnexpr == NULL)
    1194                 :           0 :                         break;
    1195                 :             : 
    1196                 :         232 :                     expr = sbsref->refassgnexpr;
    1197                 :             :                 }
    1198                 :             :                 else
    1199                 :       25080 :                     break;
    1200                 :             :             }
    1201                 :             :         }
    1202                 :             : 
    1203                 :      109992 :         result = lappend(result, expr);
    1204                 :             :     }
    1205                 :             : 
    1206                 :       49452 :     return result;
    1207                 :             : }
    1208                 :             : 
    1209                 :             : /*
    1210                 :             :  * transformOnConflictClause -
    1211                 :             :  *    transforms an OnConflictClause in an INSERT
    1212                 :             :  */
    1213                 :             : static OnConflictExpr *
    1214                 :        1557 : transformOnConflictClause(ParseState *pstate,
    1215                 :             :                           OnConflictClause *onConflictClause)
    1216                 :             : {
    1217                 :        1557 :     ParseNamespaceItem *exclNSItem = NULL;
    1218                 :             :     List       *arbiterElems;
    1219                 :             :     Node       *arbiterWhere;
    1220                 :             :     Oid         arbiterConstraint;
    1221                 :        1557 :     List       *onConflictSet = NIL;
    1222                 :        1557 :     Node       *onConflictWhere = NULL;
    1223                 :        1557 :     int         exclRelIndex = 0;
    1224                 :        1557 :     List       *exclRelTlist = NIL;
    1225                 :             :     OnConflictExpr *result;
    1226                 :             : 
    1227                 :             :     /*
    1228                 :             :      * If this is ON CONFLICT DO SELECT/UPDATE, first create the range table
    1229                 :             :      * entry for the EXCLUDED pseudo relation, so that that will be present
    1230                 :             :      * while processing arbiter expressions.  (You can't actually reference it
    1231                 :             :      * from there, but this provides a useful error message if you try.)
    1232                 :             :      */
    1233         [ +  + ]:        1557 :     if (onConflictClause->action == ONCONFLICT_UPDATE ||
    1234         [ +  + ]:         622 :         onConflictClause->action == ONCONFLICT_SELECT)
    1235                 :             :     {
    1236                 :        1171 :         Relation    targetrel = pstate->p_target_relation;
    1237                 :             :         RangeTblEntry *exclRte;
    1238                 :             : 
    1239                 :        1171 :         exclNSItem = addRangeTableEntryForRelation(pstate,
    1240                 :             :                                                    targetrel,
    1241                 :             :                                                    RowExclusiveLock,
    1242                 :             :                                                    makeAlias("excluded", NIL),
    1243                 :             :                                                    false, false);
    1244                 :        1171 :         exclRte = exclNSItem->p_rte;
    1245                 :        1171 :         exclRelIndex = exclNSItem->p_rtindex;
    1246                 :             : 
    1247                 :             :         /*
    1248                 :             :          * relkind is set to composite to signal that we're not dealing with
    1249                 :             :          * an actual relation, and no permission checks are required on it.
    1250                 :             :          * (We'll check the actual target relation, instead.)
    1251                 :             :          */
    1252                 :        1171 :         exclRte->relkind = RELKIND_COMPOSITE_TYPE;
    1253                 :             : 
    1254                 :             :         /* Create EXCLUDED rel's targetlist for use by EXPLAIN */
    1255                 :        1171 :         exclRelTlist = BuildOnConflictExcludedTargetlist(targetrel,
    1256                 :             :                                                          exclRelIndex);
    1257                 :             :     }
    1258                 :             : 
    1259                 :             :     /* Process the arbiter clause, ON CONFLICT ON (...) */
    1260                 :        1557 :     transformOnConflictArbiter(pstate, onConflictClause, &arbiterElems,
    1261                 :             :                                &arbiterWhere, &arbiterConstraint);
    1262                 :             : 
    1263                 :             :     /* Process DO SELECT/UPDATE */
    1264         [ +  + ]:        1537 :     if (onConflictClause->action == ONCONFLICT_UPDATE ||
    1265         [ +  + ]:         610 :         onConflictClause->action == ONCONFLICT_SELECT)
    1266                 :             :     {
    1267                 :             :         /*
    1268                 :             :          * Add the EXCLUDED pseudo relation to the query namespace, making it
    1269                 :             :          * available in SET and WHERE subexpressions.
    1270                 :             :          */
    1271                 :        1163 :         addNSItemToQuery(pstate, exclNSItem, false, true, true);
    1272                 :             : 
    1273                 :             :         /* Process the UPDATE SET clause */
    1274         [ +  + ]:        1163 :         if (onConflictClause->action == ONCONFLICT_UPDATE)
    1275                 :             :             onConflictSet =
    1276                 :         927 :                 transformUpdateTargetList(pstate, onConflictClause->targetList, NULL);
    1277                 :             : 
    1278                 :             :         /* Process the SELECT/UPDATE WHERE clause */
    1279                 :        1143 :         onConflictWhere = transformWhereClause(pstate,
    1280                 :             :                                                onConflictClause->whereClause,
    1281                 :             :                                                EXPR_KIND_WHERE, "WHERE");
    1282                 :             : 
    1283                 :             :         /*
    1284                 :             :          * Remove the EXCLUDED pseudo relation from the query namespace, since
    1285                 :             :          * it's not supposed to be available in RETURNING.  (Maybe someday we
    1286                 :             :          * could allow that, and drop this step.)
    1287                 :             :          */
    1288                 :             :         Assert((ParseNamespaceItem *) llast(pstate->p_namespace) == exclNSItem);
    1289                 :        1143 :         pstate->p_namespace = list_delete_last(pstate->p_namespace);
    1290                 :             :     }
    1291                 :             : 
    1292                 :             :     /* Finally, build ON CONFLICT DO [NOTHING | SELECT | UPDATE] expression */
    1293                 :        1517 :     result = makeNode(OnConflictExpr);
    1294                 :             : 
    1295                 :        1517 :     result->action = onConflictClause->action;
    1296                 :        1517 :     result->arbiterElems = arbiterElems;
    1297                 :        1517 :     result->arbiterWhere = arbiterWhere;
    1298                 :        1517 :     result->constraint = arbiterConstraint;
    1299                 :        1517 :     result->lockStrength = onConflictClause->lockStrength;
    1300                 :        1517 :     result->onConflictSet = onConflictSet;
    1301                 :        1517 :     result->onConflictWhere = onConflictWhere;
    1302                 :        1517 :     result->exclRelIndex = exclRelIndex;
    1303                 :        1517 :     result->exclRelTlist = exclRelTlist;
    1304                 :             : 
    1305                 :        1517 :     return result;
    1306                 :             : }
    1307                 :             : 
    1308                 :             : /*
    1309                 :             :  * transformForPortionOfClause
    1310                 :             :  *
    1311                 :             :  *    Transforms a ForPortionOfClause in an UPDATE/DELETE statement.
    1312                 :             :  *
    1313                 :             :  *    - Look up the range/period requested.
    1314                 :             :  *    - Build a compatible range value from the FROM and TO expressions.
    1315                 :             :  *    - Build an "overlaps" expression for filtering, used later by the
    1316                 :             :  *      rewriter.
    1317                 :             :  *    - For UPDATEs, build an "intersects" expression the rewriter can add
    1318                 :             :  *      to the targetList to change the temporal bounds.
    1319                 :             :  */
    1320                 :             : static ForPortionOfExpr *
    1321                 :        1157 : transformForPortionOfClause(ParseState *pstate,
    1322                 :             :                             int rtindex,
    1323                 :             :                             const ForPortionOfClause *forPortionOf,
    1324                 :             :                             const Node *whereClause,
    1325                 :             :                             bool isUpdate)
    1326                 :             : {
    1327                 :        1157 :     Relation    targetrel = pstate->p_target_relation;
    1328                 :        1157 :     int         range_attno = InvalidAttrNumber;
    1329                 :             :     Form_pg_attribute attr;
    1330                 :             :     Oid         attbasetype;
    1331                 :             :     Oid         opclass;
    1332                 :             :     Oid         opfamily;
    1333                 :             :     Oid         opcintype;
    1334                 :        1157 :     Oid         funcid = InvalidOid;
    1335                 :             :     StrategyNumber strat;
    1336                 :             :     Oid         opid;
    1337                 :             :     OpExpr     *op;
    1338                 :             :     ForPortionOfExpr *result;
    1339                 :             :     Var        *rangeVar;
    1340                 :             : 
    1341                 :             :     /* disallow FOR PORTION OF ... WHERE CURRENT OF */
    1342   [ +  +  +  + ]:        1157 :     if (whereClause && IsA(whereClause, CurrentOfExpr))
    1343         [ +  - ]:           8 :         ereport(ERROR,
    1344                 :             :                 errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1345                 :             :                 errmsg("WHERE CURRENT OF with FOR PORTION OF is not implemented"));
    1346                 :             : 
    1347                 :        1149 :     result = makeNode(ForPortionOfExpr);
    1348                 :             : 
    1349                 :             :     /* Look up the FOR PORTION OF name requested. */
    1350                 :        1149 :     range_attno = attnameAttNum(targetrel, forPortionOf->range_name, false);
    1351         [ +  + ]:        1149 :     if (range_attno == InvalidAttrNumber)
    1352         [ +  - ]:           8 :         ereport(ERROR,
    1353                 :             :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    1354                 :             :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
    1355                 :             :                         forPortionOf->range_name,
    1356                 :             :                         RelationGetRelationName(targetrel)),
    1357                 :             :                  parser_errposition(pstate, forPortionOf->location)));
    1358                 :        1141 :     attr = TupleDescAttr(targetrel->rd_att, range_attno - 1);
    1359                 :             : 
    1360                 :        1141 :     attbasetype = getBaseType(attr->atttypid);
    1361                 :             : 
    1362                 :        1141 :     rangeVar = makeVar(rtindex,
    1363                 :             :                        range_attno,
    1364                 :             :                        attr->atttypid,
    1365                 :             :                        attr->atttypmod,
    1366                 :             :                        attr->attcollation,
    1367                 :             :                        0);
    1368                 :        1141 :     rangeVar->location = forPortionOf->location;
    1369                 :        1141 :     result->rangeVar = rangeVar;
    1370                 :             : 
    1371                 :             :     /* Require SELECT privilege on the application-time column. */
    1372                 :        1141 :     markVarForSelectPriv(pstate, rangeVar);
    1373                 :             : 
    1374                 :             :     /*
    1375                 :             :      * Use the basetype for the target, which shouldn't be required to follow
    1376                 :             :      * domain rules. The table's column type is in the Var if we need it.
    1377                 :             :      */
    1378                 :        1141 :     result->rangeType = attbasetype;
    1379                 :        1141 :     result->isDomain = attbasetype != attr->atttypid;
    1380                 :             : 
    1381         [ +  + ]:        1141 :     if (forPortionOf->target)
    1382                 :             :     {
    1383                 :         204 :         Oid         declared_target_type = attbasetype;
    1384                 :             :         Oid         actual_target_type;
    1385                 :             : 
    1386                 :             :         /*
    1387                 :             :          * We were already given an expression for the target, so we don't
    1388                 :             :          * have to build anything. We still have to make sure we got the right
    1389                 :             :          * type. NULL will be caught be the executor.
    1390                 :             :          */
    1391                 :             : 
    1392                 :         408 :         result->targetRange = transformExpr(pstate,
    1393                 :         204 :                                             forPortionOf->target,
    1394                 :             :                                             EXPR_KIND_FOR_PORTION);
    1395                 :             : 
    1396                 :         204 :         actual_target_type = exprType(result->targetRange);
    1397                 :             : 
    1398         [ +  + ]:         204 :         if (!can_coerce_type(1, &actual_target_type, &declared_target_type, COERCION_IMPLICIT))
    1399         [ +  - ]:          32 :             ereport(ERROR,
    1400                 :             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    1401                 :             :                      errmsg("could not coerce FOR PORTION OF target from %s to %s",
    1402                 :             :                             format_type_be(actual_target_type),
    1403                 :             :                             format_type_be(declared_target_type)),
    1404                 :             :                      parser_errposition(pstate, exprLocation(forPortionOf->target))));
    1405                 :             : 
    1406                 :         172 :         result->targetRange = coerce_type(pstate,
    1407                 :             :                                           result->targetRange,
    1408                 :             :                                           actual_target_type,
    1409                 :             :                                           declared_target_type,
    1410                 :             :                                           -1,
    1411                 :             :                                           COERCION_IMPLICIT,
    1412                 :             :                                           COERCE_IMPLICIT_CAST,
    1413                 :         172 :                                           exprLocation(forPortionOf->target));
    1414                 :             : 
    1415                 :             :         /*
    1416                 :             :          * XXX: For now we only support ranges and multiranges, so we fail on
    1417                 :             :          * anything else.
    1418                 :             :          */
    1419   [ +  +  +  + ]:         172 :         if (!type_is_range(attbasetype) && !type_is_multirange(attbasetype))
    1420         [ +  - ]:          24 :             ereport(ERROR,
    1421                 :             :                     (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
    1422                 :             :                      errmsg("column \"%s\" of relation \"%s\" is not a range or multirange type",
    1423                 :             :                             forPortionOf->range_name,
    1424                 :             :                             RelationGetRelationName(targetrel)),
    1425                 :             :                      parser_errposition(pstate, forPortionOf->location)));
    1426                 :             : 
    1427                 :             :     }
    1428                 :             :     else
    1429                 :             :     {
    1430                 :             :         Oid         rngsubtype;
    1431                 :             :         Oid         declared_arg_types[2];
    1432                 :             :         Oid         actual_arg_types[2];
    1433                 :             :         List       *args;
    1434                 :             : 
    1435                 :             :         /*
    1436                 :             :          * Make sure it's a range column. XXX: We could support this syntax on
    1437                 :             :          * multirange columns too, if we just built a one-range multirange
    1438                 :             :          * from the FROM/TO phrases.
    1439                 :             :          */
    1440         [ +  + ]:         937 :         if (!type_is_range(attbasetype))
    1441         [ +  - ]:           8 :             ereport(ERROR,
    1442                 :             :                     (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
    1443                 :             :                      errmsg("column \"%s\" of relation \"%s\" is not a range type",
    1444                 :             :                             forPortionOf->range_name,
    1445                 :             :                             RelationGetRelationName(targetrel)),
    1446                 :             :                      parser_errposition(pstate, forPortionOf->location)));
    1447                 :             : 
    1448                 :         929 :         rngsubtype = get_range_subtype(attbasetype);
    1449                 :         929 :         declared_arg_types[0] = rngsubtype;
    1450                 :         929 :         declared_arg_types[1] = rngsubtype;
    1451                 :             : 
    1452                 :             :         /*
    1453                 :             :          * Build a range from the FROM ... TO ... bounds. This should give a
    1454                 :             :          * constant result, so we accept functions like NOW() but not column
    1455                 :             :          * references, subqueries, etc.
    1456                 :             :          */
    1457                 :        1842 :         result->targetFrom = transformExpr(pstate,
    1458                 :         929 :                                            forPortionOf->target_start,
    1459                 :             :                                            EXPR_KIND_FOR_PORTION);
    1460                 :        1826 :         result->targetTo = transformExpr(pstate,
    1461                 :         913 :                                          forPortionOf->target_end,
    1462                 :             :                                          EXPR_KIND_FOR_PORTION);
    1463                 :         913 :         actual_arg_types[0] = exprType(result->targetFrom);
    1464                 :         913 :         actual_arg_types[1] = exprType(result->targetTo);
    1465                 :         913 :         args = list_make2(copyObject(result->targetFrom),
    1466                 :             :                           copyObject(result->targetTo));
    1467                 :             : 
    1468                 :             :         /*
    1469                 :             :          * Check the bound types separately, for better error message and
    1470                 :             :          * location
    1471                 :             :          */
    1472         [ +  + ]:         913 :         if (!can_coerce_type(1, actual_arg_types, declared_arg_types, COERCION_IMPLICIT))
    1473         [ +  - ]:           8 :             ereport(ERROR,
    1474                 :             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    1475                 :             :                      errmsg("could not coerce FOR PORTION OF %s bound from %s to %s",
    1476                 :             :                             "FROM",
    1477                 :             :                             format_type_be(actual_arg_types[0]),
    1478                 :             :                             format_type_be(declared_arg_types[0])),
    1479                 :             :                      parser_errposition(pstate, exprLocation(forPortionOf->target_start))));
    1480         [ +  + ]:         905 :         if (!can_coerce_type(1, &actual_arg_types[1], &declared_arg_types[1], COERCION_IMPLICIT))
    1481         [ +  - ]:           8 :             ereport(ERROR,
    1482                 :             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    1483                 :             :                      errmsg("could not coerce FOR PORTION OF %s bound from %s to %s",
    1484                 :             :                             "TO",
    1485                 :             :                             format_type_be(actual_arg_types[1]),
    1486                 :             :                             format_type_be(declared_arg_types[1])),
    1487                 :             :                      parser_errposition(pstate, exprLocation(forPortionOf->target_end))));
    1488                 :             : 
    1489                 :         897 :         make_fn_arguments(pstate, args, actual_arg_types, declared_arg_types);
    1490                 :         897 :         result->targetRange = (Node *) makeFuncExpr(get_range_constructor2(attbasetype),
    1491                 :             :                                                     attbasetype,
    1492                 :             :                                                     args,
    1493                 :             :                                                     InvalidOid, InvalidOid, COERCE_EXPLICIT_CALL);
    1494                 :             :     }
    1495                 :             : 
    1496                 :             :     /*
    1497                 :             :      * Build overlapsExpr to use as an extra qual. This means we only hit rows
    1498                 :             :      * matching the FROM & TO bounds. We must look up the overlaps operator
    1499                 :             :      * (usually "&&").
    1500                 :             :      */
    1501                 :        1045 :     opclass = GetDefaultOpClass(attr->atttypid, GIST_AM_OID);
    1502         [ -  + ]:        1045 :     if (!OidIsValid(opclass))
    1503         [ #  # ]:           0 :         ereport(ERROR,
    1504                 :             :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
    1505                 :             :                  errmsg("data type %s has no default operator class for access method \"%s\"",
    1506                 :             :                         format_type_be(attr->atttypid), "gist"),
    1507                 :             :                  errhint("You must define a default operator class for the data type.")));
    1508                 :             : 
    1509                 :             :     /* Look up the operators and functions we need. */
    1510                 :        1045 :     GetOperatorFromCompareType(opclass, InvalidOid, COMPARE_OVERLAP, &opid, &strat);
    1511                 :        1045 :     op = makeNode(OpExpr);
    1512                 :        1045 :     op->opno = opid;
    1513                 :        1045 :     op->opfuncid = get_opcode(opid);
    1514                 :        1045 :     op->opresulttype = BOOLOID;
    1515                 :        1045 :     op->args = list_make2(copyObject(rangeVar), copyObject(result->targetRange));
    1516                 :        1045 :     result->overlapsExpr = (Node *) op;
    1517                 :             : 
    1518                 :             :     /*
    1519                 :             :      * Look up the without_portion func. This computes the bounds of temporal
    1520                 :             :      * leftovers.
    1521                 :             :      *
    1522                 :             :      * XXX: Find a more extensible way to look up the function, permitting
    1523                 :             :      * user-defined types. An opclass support function doesn't make sense,
    1524                 :             :      * since there is no index involved. Perhaps a type support function.
    1525                 :             :      */
    1526         [ +  - ]:        1045 :     if (get_opclass_opfamily_and_input_type(opclass, &opfamily, &opcintype))
    1527      [ +  +  - ]:        1045 :         switch (opcintype)
    1528                 :             :         {
    1529                 :         957 :             case ANYRANGEOID:
    1530                 :         957 :                 result->withoutPortionProc = F_RANGE_MINUS_MULTI;
    1531                 :         957 :                 break;
    1532                 :          88 :             case ANYMULTIRANGEOID:
    1533                 :          88 :                 result->withoutPortionProc = F_MULTIRANGE_MINUS_MULTI;
    1534                 :          88 :                 break;
    1535                 :           0 :             default:
    1536         [ #  # ]:           0 :                 elog(ERROR, "unexpected opcintype: %u", opcintype);
    1537                 :             :         }
    1538                 :             :     else
    1539         [ #  # ]:           0 :         elog(ERROR, "unexpected opclass: %u", opclass);
    1540                 :             : 
    1541         [ +  + ]:        1045 :     if (isUpdate)
    1542                 :             :     {
    1543                 :             :         /*
    1544                 :             :          * Now make sure we update the start/end time of the record. For a
    1545                 :             :          * range col (r) this is `r = r * targetRange` (where * is the
    1546                 :             :          * intersect operator).
    1547                 :             :          */
    1548                 :             :         Oid         intersectoperoid;
    1549                 :             :         List       *funcArgs;
    1550                 :             :         Node       *rangeTLEExpr;
    1551                 :             :         TargetEntry *tle;
    1552                 :         594 :         RTEPermissionInfo *target_perminfo = pstate->p_target_nsitem->p_perminfo;
    1553                 :             : 
    1554                 :             :         /*
    1555                 :             :          * Whatever operator is used for intersect by temporal foreign keys,
    1556                 :             :          * we can use its backing procedure for intersects in FOR PORTION OF.
    1557                 :             :          * XXX: Share code with FindFKPeriodOpers?
    1558                 :             :          */
    1559      [ +  +  - ]:         594 :         switch (opcintype)
    1560                 :             :         {
    1561                 :         546 :             case ANYRANGEOID:
    1562                 :         546 :                 intersectoperoid = OID_RANGE_INTERSECT_RANGE_OP;
    1563                 :         546 :                 break;
    1564                 :          48 :             case ANYMULTIRANGEOID:
    1565                 :          48 :                 intersectoperoid = OID_MULTIRANGE_INTERSECT_MULTIRANGE_OP;
    1566                 :          48 :                 break;
    1567                 :           0 :             default:
    1568         [ #  # ]:           0 :                 elog(ERROR, "unexpected opcintype: %u", opcintype);
    1569                 :             :         }
    1570                 :         594 :         funcid = get_opcode(intersectoperoid);
    1571         [ -  + ]:         594 :         if (!OidIsValid(funcid))
    1572         [ #  # ]:           0 :             ereport(ERROR,
    1573                 :             :                     errcode(ERRCODE_UNDEFINED_OBJECT),
    1574                 :             :                     errmsg("could not identify an intersect function for type %s",
    1575                 :             :                            format_type_be(opcintype)));
    1576                 :             : 
    1577                 :         594 :         funcArgs = list_make2(copyObject(rangeVar),
    1578                 :             :                               copyObject(result->targetRange));
    1579                 :         594 :         rangeTLEExpr = (Node *) makeFuncExpr(funcid, attbasetype, funcArgs,
    1580                 :             :                                              InvalidOid, InvalidOid,
    1581                 :             :                                              COERCE_EXPLICIT_CALL);
    1582                 :             : 
    1583                 :             :         /*
    1584                 :             :          * Coerce to domain if necessary. If we skip this, we will allow
    1585                 :             :          * updating to forbidden values.
    1586                 :             :          */
    1587                 :         594 :         rangeTLEExpr = coerce_type(pstate,
    1588                 :             :                                    rangeTLEExpr,
    1589                 :             :                                    attbasetype,
    1590                 :             :                                    attr->atttypid,
    1591                 :             :                                    -1,
    1592                 :             :                                    COERCION_IMPLICIT,
    1593                 :             :                                    COERCE_IMPLICIT_CAST,
    1594                 :         594 :                                    exprLocation(forPortionOf->target));
    1595                 :             : 
    1596                 :             :         /* Make a TLE to set the range column */
    1597                 :         594 :         result->rangeTargetList = NIL;
    1598                 :         594 :         tle = makeTargetEntry((Expr *) rangeTLEExpr, range_attno,
    1599                 :         594 :                               forPortionOf->range_name, false);
    1600                 :         594 :         result->rangeTargetList = lappend(result->rangeTargetList, tle);
    1601                 :             : 
    1602                 :             :         /* Mark the range column as requiring update permissions */
    1603                 :         594 :         target_perminfo->updatedCols = bms_add_member(target_perminfo->updatedCols,
    1604                 :             :                                                       range_attno - FirstLowInvalidHeapAttributeNumber);
    1605                 :             :     }
    1606                 :             :     else
    1607                 :         451 :         result->rangeTargetList = NIL;
    1608                 :             : 
    1609                 :        1045 :     result->location = forPortionOf->location;
    1610                 :        1045 :     result->targetLocation = forPortionOf->target_location;
    1611                 :             : 
    1612                 :        1045 :     return result;
    1613                 :             : }
    1614                 :             : 
    1615                 :             : /*
    1616                 :             :  * BuildOnConflictExcludedTargetlist
    1617                 :             :  *      Create target list for the EXCLUDED pseudo-relation of ON CONFLICT,
    1618                 :             :  *      representing the columns of targetrel with varno exclRelIndex.
    1619                 :             :  *
    1620                 :             :  * Note: Exported for use in the rewriter.
    1621                 :             :  */
    1622                 :             : List *
    1623                 :        1319 : BuildOnConflictExcludedTargetlist(Relation targetrel,
    1624                 :             :                                   Index exclRelIndex)
    1625                 :             : {
    1626                 :        1319 :     List       *result = NIL;
    1627                 :             :     int         attno;
    1628                 :             :     Var        *var;
    1629                 :             :     TargetEntry *te;
    1630                 :             : 
    1631                 :             :     /*
    1632                 :             :      * Note that resnos of the tlist must correspond to attnos of the
    1633                 :             :      * underlying relation, hence we need entries for dropped columns too.
    1634                 :             :      */
    1635         [ +  + ]:        4727 :     for (attno = 0; attno < RelationGetNumberOfAttributes(targetrel); attno++)
    1636                 :             :     {
    1637                 :        3408 :         Form_pg_attribute attr = TupleDescAttr(targetrel->rd_att, attno);
    1638                 :             :         char       *name;
    1639                 :             : 
    1640         [ +  + ]:        3408 :         if (attr->attisdropped)
    1641                 :             :         {
    1642                 :             :             /*
    1643                 :             :              * can't use atttypid here, but it doesn't really matter what type
    1644                 :             :              * the Const claims to be.
    1645                 :             :              */
    1646                 :          74 :             var = (Var *) makeNullConst(INT4OID, -1, InvalidOid);
    1647                 :          74 :             name = NULL;
    1648                 :             :         }
    1649                 :             :         else
    1650                 :             :         {
    1651                 :        3334 :             var = makeVar(exclRelIndex, attno + 1,
    1652                 :             :                           attr->atttypid, attr->atttypmod,
    1653                 :             :                           attr->attcollation,
    1654                 :             :                           0);
    1655                 :        3334 :             name = pstrdup(NameStr(attr->attname));
    1656                 :             :         }
    1657                 :             : 
    1658                 :        3408 :         te = makeTargetEntry((Expr *) var,
    1659                 :        3408 :                              attno + 1,
    1660                 :             :                              name,
    1661                 :             :                              false);
    1662                 :             : 
    1663                 :        3408 :         result = lappend(result, te);
    1664                 :             :     }
    1665                 :             : 
    1666                 :             :     /*
    1667                 :             :      * Add a whole-row-Var entry to support references to "EXCLUDED.*".  Like
    1668                 :             :      * the other entries in the EXCLUDED tlist, its resno must match the Var's
    1669                 :             :      * varattno, else the wrong things happen while resolving references in
    1670                 :             :      * setrefs.c.  This is against normal conventions for targetlists, but
    1671                 :             :      * it's okay since we don't use this as a real tlist.
    1672                 :             :      */
    1673                 :        1319 :     var = makeVar(exclRelIndex, InvalidAttrNumber,
    1674                 :        1319 :                   targetrel->rd_rel->reltype,
    1675                 :             :                   -1, InvalidOid, 0);
    1676                 :        1319 :     te = makeTargetEntry((Expr *) var, InvalidAttrNumber, NULL, true);
    1677                 :        1319 :     result = lappend(result, te);
    1678                 :             : 
    1679                 :        1319 :     return result;
    1680                 :             : }
    1681                 :             : 
    1682                 :             : 
    1683                 :             : /*
    1684                 :             :  * count_rowexpr_columns -
    1685                 :             :  *    get number of columns contained in a ROW() expression;
    1686                 :             :  *    return -1 if expression isn't a RowExpr or a Var referencing one.
    1687                 :             :  *
    1688                 :             :  * This is currently used only for hint purposes, so we aren't terribly
    1689                 :             :  * tense about recognizing all possible cases.  The Var case is interesting
    1690                 :             :  * because that's what we'll get in the INSERT ... SELECT (...) case.
    1691                 :             :  */
    1692                 :             : static int
    1693                 :           0 : count_rowexpr_columns(ParseState *pstate, Node *expr)
    1694                 :             : {
    1695         [ #  # ]:           0 :     if (expr == NULL)
    1696                 :           0 :         return -1;
    1697         [ #  # ]:           0 :     if (IsA(expr, RowExpr))
    1698                 :           0 :         return list_length(((RowExpr *) expr)->args);
    1699         [ #  # ]:           0 :     if (IsA(expr, Var))
    1700                 :             :     {
    1701                 :           0 :         Var        *var = (Var *) expr;
    1702                 :           0 :         AttrNumber  attnum = var->varattno;
    1703                 :             : 
    1704   [ #  #  #  # ]:           0 :         if (attnum > 0 && var->vartype == RECORDOID)
    1705                 :             :         {
    1706                 :             :             RangeTblEntry *rte;
    1707                 :             : 
    1708                 :           0 :             rte = GetRTEByRangeTablePosn(pstate, var->varno, var->varlevelsup);
    1709         [ #  # ]:           0 :             if (rte->rtekind == RTE_SUBQUERY)
    1710                 :             :             {
    1711                 :             :                 /* Subselect-in-FROM: examine sub-select's output expr */
    1712                 :           0 :                 TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
    1713                 :             :                                                     attnum);
    1714                 :             : 
    1715   [ #  #  #  # ]:           0 :                 if (ste == NULL || ste->resjunk)
    1716                 :           0 :                     return -1;
    1717                 :           0 :                 expr = (Node *) ste->expr;
    1718         [ #  # ]:           0 :                 if (IsA(expr, RowExpr))
    1719                 :           0 :                     return list_length(((RowExpr *) expr)->args);
    1720                 :             :             }
    1721                 :             :         }
    1722                 :             :     }
    1723                 :           0 :     return -1;
    1724                 :             : }
    1725                 :             : 
    1726                 :             : 
    1727                 :             : /*
    1728                 :             :  * transformSelectStmt -
    1729                 :             :  *    transforms a Select Statement
    1730                 :             :  *
    1731                 :             :  * This function is also used to transform the source expression of a
    1732                 :             :  * PLAssignStmt.  In that usage, passthru is non-NULL and we need to
    1733                 :             :  * call transformPLAssignStmtTarget after the initial transformation of the
    1734                 :             :  * SELECT's targetlist.  (We could generalize this into an arbitrary callback
    1735                 :             :  * function, but for now that would just be more notation with no benefit.)
    1736                 :             :  * All the rest is the same as a regular SelectStmt.
    1737                 :             :  *
    1738                 :             :  * Note: this covers only cases with no set operations and no VALUES lists;
    1739                 :             :  * see below for the other cases.
    1740                 :             :  */
    1741                 :             : static Query *
    1742                 :      309284 : transformSelectStmt(ParseState *pstate, SelectStmt *stmt,
    1743                 :             :                     SelectStmtPassthrough *passthru)
    1744                 :             : {
    1745                 :      309284 :     Query      *qry = makeNode(Query);
    1746                 :             :     Node       *qual;
    1747                 :             :     ListCell   *l;
    1748                 :             : 
    1749                 :      309284 :     qry->commandType = CMD_SELECT;
    1750                 :             : 
    1751                 :             :     /* process the WITH clause independently of all else */
    1752         [ +  + ]:      309284 :     if (stmt->withClause)
    1753                 :             :     {
    1754                 :        1694 :         qry->hasRecursive = stmt->withClause->recursive;
    1755                 :        1694 :         qry->cteList = transformWithClause(pstate, stmt->withClause);
    1756                 :        1497 :         qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
    1757                 :             :     }
    1758                 :             : 
    1759                 :             :     /* Complain if we get called from someplace where INTO is not allowed */
    1760         [ +  + ]:      309087 :     if (stmt->intoClause)
    1761         [ +  - ]:          12 :         ereport(ERROR,
    1762                 :             :                 (errcode(ERRCODE_SYNTAX_ERROR),
    1763                 :             :                  errmsg("SELECT ... INTO is not allowed here"),
    1764                 :             :                  parser_errposition(pstate,
    1765                 :             :                                     exprLocation((Node *) stmt->intoClause))));
    1766                 :             : 
    1767                 :             :     /* make FOR UPDATE/FOR SHARE info available to addRangeTableEntry */
    1768                 :      309075 :     pstate->p_locking_clause = stmt->lockingClause;
    1769                 :             : 
    1770                 :             :     /* make WINDOW info available for window functions, too */
    1771                 :      309075 :     pstate->p_windowdefs = stmt->windowClause;
    1772                 :             : 
    1773                 :             :     /* process the FROM clause */
    1774                 :      309075 :     transformFromClause(pstate, stmt->fromClause);
    1775                 :             : 
    1776                 :             :     /* transform targetlist */
    1777                 :      308522 :     qry->targetList = transformTargetList(pstate, stmt->targetList,
    1778                 :             :                                           EXPR_KIND_SELECT_TARGET);
    1779                 :             : 
    1780                 :             :     /*
    1781                 :             :      * If we're within a PLAssignStmt, do further transformation of the
    1782                 :             :      * targetlist; that has to happen before we consider sorting or grouping.
    1783                 :             :      * Otherwise, mark column origins (which are useless in a PLAssignStmt).
    1784                 :             :      */
    1785         [ +  + ]:      304842 :     if (passthru)
    1786                 :        3519 :         qry->targetList = transformPLAssignStmtTarget(pstate, qry->targetList,
    1787                 :             :                                                       passthru);
    1788                 :             :     else
    1789                 :      301323 :         markTargetListOrigins(pstate, qry->targetList);
    1790                 :             : 
    1791                 :             :     /* transform WHERE */
    1792                 :      304835 :     qual = transformWhereClause(pstate, stmt->whereClause,
    1793                 :             :                                 EXPR_KIND_WHERE, "WHERE");
    1794                 :             : 
    1795                 :             :     /* initial processing of HAVING clause is much like WHERE clause */
    1796                 :      304764 :     qry->havingQual = transformWhereClause(pstate, stmt->havingClause,
    1797                 :             :                                            EXPR_KIND_HAVING, "HAVING");
    1798                 :             : 
    1799                 :             :     /*
    1800                 :             :      * Transform sorting/grouping stuff.  Do ORDER BY first because both
    1801                 :             :      * transformGroupClause and transformDistinctClause need the results. Note
    1802                 :             :      * that these functions can also change the targetList, so it's passed to
    1803                 :             :      * them by reference.
    1804                 :             :      */
    1805                 :      304760 :     qry->sortClause = transformSortClause(pstate,
    1806                 :             :                                           stmt->sortClause,
    1807                 :             :                                           &qry->targetList,
    1808                 :             :                                           EXPR_KIND_ORDER_BY,
    1809                 :             :                                           false /* allow SQL92 rules */ );
    1810                 :             : 
    1811                 :      304740 :     qry->groupClause = transformGroupClause(pstate,
    1812                 :             :                                             stmt->groupClause,
    1813                 :             :                                             &qry->groupingSets,
    1814                 :             :                                             &qry->targetList,
    1815                 :             :                                             qry->sortClause,
    1816                 :             :                                             EXPR_KIND_GROUP_BY,
    1817                 :             :                                             false /* allow SQL92 rules */ );
    1818                 :      304724 :     qry->groupDistinct = stmt->groupDistinct;
    1819                 :             : 
    1820         [ +  + ]:      304724 :     if (stmt->distinctClause == NIL)
    1821                 :             :     {
    1822                 :      302197 :         qry->distinctClause = NIL;
    1823                 :      302197 :         qry->hasDistinctOn = false;
    1824                 :             :     }
    1825         [ +  + ]:        2527 :     else if (linitial(stmt->distinctClause) == NULL)
    1826                 :             :     {
    1827                 :             :         /* We had SELECT DISTINCT */
    1828                 :        2328 :         qry->distinctClause = transformDistinctClause(pstate,
    1829                 :             :                                                       &qry->targetList,
    1830                 :             :                                                       qry->sortClause,
    1831                 :             :                                                       false);
    1832                 :        2328 :         qry->hasDistinctOn = false;
    1833                 :             :     }
    1834                 :             :     else
    1835                 :             :     {
    1836                 :             :         /* We had SELECT DISTINCT ON */
    1837                 :         199 :         qry->distinctClause = transformDistinctOnClause(pstate,
    1838                 :             :                                                         stmt->distinctClause,
    1839                 :             :                                                         &qry->targetList,
    1840                 :             :                                                         qry->sortClause);
    1841                 :         191 :         qry->hasDistinctOn = true;
    1842                 :             :     }
    1843                 :             : 
    1844                 :             :     /* transform LIMIT */
    1845                 :      304716 :     qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
    1846                 :             :                                             EXPR_KIND_OFFSET, "OFFSET",
    1847                 :             :                                             stmt->limitOption);
    1848                 :      304716 :     qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
    1849                 :             :                                            EXPR_KIND_LIMIT, "LIMIT",
    1850                 :             :                                            stmt->limitOption);
    1851                 :      304708 :     qry->limitOption = stmt->limitOption;
    1852                 :             : 
    1853                 :             :     /* transform window clauses after we have seen all window functions */
    1854                 :      304708 :     qry->windowClause = transformWindowDefinitions(pstate,
    1855                 :             :                                                    pstate->p_windowdefs,
    1856                 :             :                                                    &qry->targetList);
    1857                 :             : 
    1858                 :             :     /* resolve any still-unresolved output columns as being type text */
    1859         [ +  + ]:      304652 :     if (pstate->p_resolve_unknowns)
    1860                 :      277200 :         resolveTargetListUnknowns(pstate, qry->targetList);
    1861                 :             : 
    1862                 :      304652 :     qry->rtable = pstate->p_rtable;
    1863                 :      304652 :     qry->rteperminfos = pstate->p_rteperminfos;
    1864                 :      304652 :     qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
    1865                 :             : 
    1866                 :      304652 :     qry->hasSubLinks = pstate->p_hasSubLinks;
    1867                 :      304652 :     qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
    1868                 :      304652 :     qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
    1869                 :      304652 :     qry->hasAggs = pstate->p_hasAggs;
    1870                 :             : 
    1871   [ +  +  +  +  :      309679 :     foreach(l, stmt->lockingClause)
                   +  + ]
    1872                 :             :     {
    1873                 :        5059 :         transformLockingClause(pstate, qry,
    1874                 :        5059 :                                (LockingClause *) lfirst(l), false);
    1875                 :             :     }
    1876                 :             : 
    1877                 :      304620 :     assign_query_collations(pstate, qry);
    1878                 :             : 
    1879                 :             :     /* this must be done after collations, for reliable comparison of exprs */
    1880   [ +  +  +  +  :      304592 :     if (pstate->p_hasAggs || qry->groupClause || qry->groupingSets || qry->havingQual)
             +  +  +  + ]
    1881                 :       27746 :         parseCheckAggregates(pstate, qry);
    1882                 :             : 
    1883                 :      304520 :     return qry;
    1884                 :             : }
    1885                 :             : 
    1886                 :             : /*
    1887                 :             :  * transformValuesClause -
    1888                 :             :  *    transforms a VALUES clause that's being used as a standalone SELECT
    1889                 :             :  *
    1890                 :             :  * We build a Query containing a VALUES RTE, rather as if one had written
    1891                 :             :  *          SELECT * FROM (VALUES ...) AS "*VALUES*"
    1892                 :             :  */
    1893                 :             : static Query *
    1894                 :        5885 : transformValuesClause(ParseState *pstate, SelectStmt *stmt)
    1895                 :             : {
    1896                 :        5885 :     Query      *qry = makeNode(Query);
    1897                 :        5885 :     List       *exprsLists = NIL;
    1898                 :        5885 :     List       *coltypes = NIL;
    1899                 :        5885 :     List       *coltypmods = NIL;
    1900                 :        5885 :     List       *colcollations = NIL;
    1901                 :        5885 :     List      **colexprs = NULL;
    1902                 :        5885 :     int         sublist_length = -1;
    1903                 :        5885 :     bool        lateral = false;
    1904                 :             :     ParseNamespaceItem *nsitem;
    1905                 :             :     ListCell   *lc;
    1906                 :             :     ListCell   *lc2;
    1907                 :             :     int         i;
    1908                 :             : 
    1909                 :        5885 :     qry->commandType = CMD_SELECT;
    1910                 :             : 
    1911                 :             :     /* Most SELECT stuff doesn't apply in a VALUES clause */
    1912                 :             :     Assert(stmt->distinctClause == NIL);
    1913                 :             :     Assert(stmt->intoClause == NULL);
    1914                 :             :     Assert(stmt->targetList == NIL);
    1915                 :             :     Assert(stmt->fromClause == NIL);
    1916                 :             :     Assert(stmt->whereClause == NULL);
    1917                 :             :     Assert(stmt->groupClause == NIL);
    1918                 :             :     Assert(stmt->havingClause == NULL);
    1919                 :             :     Assert(stmt->windowClause == NIL);
    1920                 :             :     Assert(stmt->op == SETOP_NONE);
    1921                 :             : 
    1922                 :             :     /* process the WITH clause independently of all else */
    1923         [ +  + ]:        5885 :     if (stmt->withClause)
    1924                 :             :     {
    1925                 :          40 :         qry->hasRecursive = stmt->withClause->recursive;
    1926                 :          40 :         qry->cteList = transformWithClause(pstate, stmt->withClause);
    1927                 :          36 :         qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
    1928                 :             :     }
    1929                 :             : 
    1930                 :             :     /*
    1931                 :             :      * For each row of VALUES, transform the raw expressions.
    1932                 :             :      *
    1933                 :             :      * Note that the intermediate representation we build is column-organized
    1934                 :             :      * not row-organized.  That simplifies the type and collation processing
    1935                 :             :      * below.
    1936                 :             :      */
    1937   [ +  -  +  +  :       21813 :     foreach(lc, stmt->valuesLists)
                   +  + ]
    1938                 :             :     {
    1939                 :       15937 :         List       *sublist = (List *) lfirst(lc);
    1940                 :             : 
    1941                 :             :         /*
    1942                 :             :          * Do basic expression transformation (same as a ROW() expr, but here
    1943                 :             :          * we disallow SetToDefault)
    1944                 :             :          */
    1945                 :       15937 :         sublist = transformExpressionList(pstate, sublist,
    1946                 :             :                                           EXPR_KIND_VALUES, false);
    1947                 :             : 
    1948                 :             :         /*
    1949                 :             :          * All the sublists must be the same length, *after* transformation
    1950                 :             :          * (which might expand '*' into multiple items).  The VALUES RTE can't
    1951                 :             :          * handle anything different.
    1952                 :             :          */
    1953         [ +  + ]:       15932 :         if (sublist_length < 0)
    1954                 :             :         {
    1955                 :             :             /* Remember post-transformation length of first sublist */
    1956                 :        5876 :             sublist_length = list_length(sublist);
    1957                 :             :             /* and allocate array for per-column lists */
    1958                 :        5876 :             colexprs = palloc0_array(List *, sublist_length);
    1959                 :             :         }
    1960         [ -  + ]:       10056 :         else if (sublist_length != list_length(sublist))
    1961                 :             :         {
    1962         [ #  # ]:           0 :             ereport(ERROR,
    1963                 :             :                     (errcode(ERRCODE_SYNTAX_ERROR),
    1964                 :             :                      errmsg("VALUES lists must all be the same length"),
    1965                 :             :                      parser_errposition(pstate,
    1966                 :             :                                         exprLocation((Node *) sublist))));
    1967                 :             :         }
    1968                 :             : 
    1969                 :             :         /* Build per-column expression lists */
    1970                 :       15932 :         i = 0;
    1971   [ +  +  +  +  :       37997 :         foreach(lc2, sublist)
                   +  + ]
    1972                 :             :         {
    1973                 :       22065 :             Node       *col = (Node *) lfirst(lc2);
    1974                 :             : 
    1975                 :       22065 :             colexprs[i] = lappend(colexprs[i], col);
    1976                 :       22065 :             i++;
    1977                 :             :         }
    1978                 :             : 
    1979                 :             :         /* Release sub-list's cells to save memory */
    1980                 :       15932 :         list_free(sublist);
    1981                 :             : 
    1982                 :             :         /* Prepare an exprsLists element for this row */
    1983                 :       15932 :         exprsLists = lappend(exprsLists, NIL);
    1984                 :             :     }
    1985                 :             : 
    1986                 :             :     /*
    1987                 :             :      * Now resolve the common types of the columns, and coerce everything to
    1988                 :             :      * those types.  Then identify the common typmod and common collation, if
    1989                 :             :      * any, of each column.
    1990                 :             :      *
    1991                 :             :      * We must do collation processing now because (1) assign_query_collations
    1992                 :             :      * doesn't process rangetable entries, and (2) we need to label the VALUES
    1993                 :             :      * RTE with column collations for use in the outer query.  We don't
    1994                 :             :      * consider conflict of implicit collations to be an error here; instead
    1995                 :             :      * the column will just show InvalidOid as its collation, and you'll get a
    1996                 :             :      * failure later if that results in failure to resolve a collation.
    1997                 :             :      *
    1998                 :             :      * Note we modify the per-column expression lists in-place.
    1999                 :             :      */
    2000         [ +  + ]:       13522 :     for (i = 0; i < sublist_length; i++)
    2001                 :             :     {
    2002                 :             :         Oid         coltype;
    2003                 :             :         int32       coltypmod;
    2004                 :             :         Oid         colcoll;
    2005                 :             : 
    2006                 :        7646 :         coltype = select_common_type(pstate, colexprs[i], "VALUES", NULL);
    2007                 :             : 
    2008   [ +  -  +  +  :       29711 :         foreach(lc, colexprs[i])
                   +  + ]
    2009                 :             :         {
    2010                 :       22065 :             Node       *col = (Node *) lfirst(lc);
    2011                 :             : 
    2012                 :       22065 :             col = coerce_to_common_type(pstate, col, coltype, "VALUES");
    2013                 :       22065 :             lfirst(lc) = col;
    2014                 :             :         }
    2015                 :             : 
    2016                 :        7646 :         coltypmod = select_common_typmod(pstate, colexprs[i], coltype);
    2017                 :        7646 :         colcoll = select_common_collation(pstate, colexprs[i], true);
    2018                 :             : 
    2019                 :        7646 :         coltypes = lappend_oid(coltypes, coltype);
    2020                 :        7646 :         coltypmods = lappend_int(coltypmods, coltypmod);
    2021                 :        7646 :         colcollations = lappend_oid(colcollations, colcoll);
    2022                 :             :     }
    2023                 :             : 
    2024                 :             :     /*
    2025                 :             :      * Finally, rearrange the coerced expressions into row-organized lists.
    2026                 :             :      */
    2027         [ +  + ]:       13522 :     for (i = 0; i < sublist_length; i++)
    2028                 :             :     {
    2029   [ +  -  +  +  :       29711 :         forboth(lc, colexprs[i], lc2, exprsLists)
          +  -  +  +  +  
             +  +  -  +  
                      + ]
    2030                 :             :         {
    2031                 :       22065 :             Node       *col = (Node *) lfirst(lc);
    2032                 :       22065 :             List       *sublist = lfirst(lc2);
    2033                 :             : 
    2034                 :       22065 :             sublist = lappend(sublist, col);
    2035                 :       22065 :             lfirst(lc2) = sublist;
    2036                 :             :         }
    2037                 :        7646 :         list_free(colexprs[i]);
    2038                 :             :     }
    2039                 :             : 
    2040                 :             :     /*
    2041                 :             :      * Ordinarily there can't be any current-level Vars in the expression
    2042                 :             :      * lists, because the namespace was empty ... but if we're inside CREATE
    2043                 :             :      * RULE, then NEW/OLD references might appear.  In that case we have to
    2044                 :             :      * mark the VALUES RTE as LATERAL.
    2045                 :             :      */
    2046   [ +  +  +  - ]:        5881 :     if (pstate->p_rtable != NIL &&
    2047                 :           5 :         contain_vars_of_level((Node *) exprsLists, 0))
    2048                 :           5 :         lateral = true;
    2049                 :             : 
    2050                 :             :     /*
    2051                 :             :      * Generate the VALUES RTE
    2052                 :             :      */
    2053                 :        5876 :     nsitem = addRangeTableEntryForValues(pstate, exprsLists,
    2054                 :             :                                          coltypes, coltypmods, colcollations,
    2055                 :             :                                          NULL, lateral, true);
    2056                 :        5876 :     addNSItemToQuery(pstate, nsitem, true, true, true);
    2057                 :             : 
    2058                 :             :     /*
    2059                 :             :      * Generate a targetlist as though expanding "*"
    2060                 :             :      */
    2061                 :             :     Assert(pstate->p_next_resno == 1);
    2062                 :        5876 :     qry->targetList = expandNSItemAttrs(pstate, nsitem, 0, true, -1);
    2063                 :             : 
    2064                 :             :     /*
    2065                 :             :      * The grammar allows attaching ORDER BY, LIMIT, and FOR UPDATE to a
    2066                 :             :      * VALUES, so cope.
    2067                 :             :      */
    2068                 :        5876 :     qry->sortClause = transformSortClause(pstate,
    2069                 :             :                                           stmt->sortClause,
    2070                 :             :                                           &qry->targetList,
    2071                 :             :                                           EXPR_KIND_ORDER_BY,
    2072                 :             :                                           false /* allow SQL92 rules */ );
    2073                 :             : 
    2074                 :        5876 :     qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
    2075                 :             :                                             EXPR_KIND_OFFSET, "OFFSET",
    2076                 :             :                                             stmt->limitOption);
    2077                 :        5876 :     qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
    2078                 :             :                                            EXPR_KIND_LIMIT, "LIMIT",
    2079                 :             :                                            stmt->limitOption);
    2080                 :        5876 :     qry->limitOption = stmt->limitOption;
    2081                 :             : 
    2082         [ -  + ]:        5876 :     if (stmt->lockingClause)
    2083         [ #  # ]:           0 :         ereport(ERROR,
    2084                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2085                 :             :         /*------
    2086                 :             :           translator: %s is a SQL row locking clause such as FOR UPDATE */
    2087                 :             :                  errmsg("%s cannot be applied to VALUES",
    2088                 :             :                         LCS_asString(((LockingClause *)
    2089                 :             :                                       linitial(stmt->lockingClause))->strength))));
    2090                 :             : 
    2091                 :        5876 :     qry->rtable = pstate->p_rtable;
    2092                 :        5876 :     qry->rteperminfos = pstate->p_rteperminfos;
    2093                 :        5876 :     qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
    2094                 :             : 
    2095                 :        5876 :     qry->hasSubLinks = pstate->p_hasSubLinks;
    2096                 :             : 
    2097                 :        5876 :     assign_query_collations(pstate, qry);
    2098                 :             : 
    2099                 :        5876 :     return qry;
    2100                 :             : }
    2101                 :             : 
    2102                 :             : /*
    2103                 :             :  * transformSetOperationStmt -
    2104                 :             :  *    transforms a set-operations tree
    2105                 :             :  *
    2106                 :             :  * A set-operation tree is just a SELECT, but with UNION/INTERSECT/EXCEPT
    2107                 :             :  * structure to it.  We must transform each leaf SELECT and build up a top-
    2108                 :             :  * level Query that contains the leaf SELECTs as subqueries in its rangetable.
    2109                 :             :  * The tree of set operations is converted into the setOperations field of
    2110                 :             :  * the top-level Query.
    2111                 :             :  */
    2112                 :             : static Query *
    2113                 :        8644 : transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
    2114                 :             : {
    2115                 :        8644 :     Query      *qry = makeNode(Query);
    2116                 :             :     SelectStmt *leftmostSelect;
    2117                 :             :     int         leftmostRTI;
    2118                 :             :     Query      *leftmostQuery;
    2119                 :             :     SetOperationStmt *sostmt;
    2120                 :             :     List       *sortClause;
    2121                 :             :     Node       *limitOffset;
    2122                 :             :     Node       *limitCount;
    2123                 :             :     List       *lockingClause;
    2124                 :             :     WithClause *withClause;
    2125                 :             :     Node       *node;
    2126                 :             :     ListCell   *left_tlist,
    2127                 :             :                *lct,
    2128                 :             :                *lcm,
    2129                 :             :                *lcc,
    2130                 :             :                *l;
    2131                 :             :     List       *targetvars,
    2132                 :             :                *targetnames,
    2133                 :             :                *sv_namespace;
    2134                 :             :     int         sv_rtable_length;
    2135                 :             :     ParseNamespaceItem *jnsitem;
    2136                 :             :     ParseNamespaceColumn *sortnscolumns;
    2137                 :             :     int         sortcolindex;
    2138                 :             :     int         tllen;
    2139                 :             : 
    2140                 :        8644 :     qry->commandType = CMD_SELECT;
    2141                 :             : 
    2142                 :             :     /*
    2143                 :             :      * Find leftmost leaf SelectStmt.  We currently only need to do this in
    2144                 :             :      * order to deliver a suitable error message if there's an INTO clause
    2145                 :             :      * there, implying the set-op tree is in a context that doesn't allow
    2146                 :             :      * INTO.  (transformSetOperationTree would throw error anyway, but it
    2147                 :             :      * seems worth the trouble to throw a different error for non-leftmost
    2148                 :             :      * INTO, so we produce that error in transformSetOperationTree.)
    2149                 :             :      */
    2150                 :        8644 :     leftmostSelect = stmt->larg;
    2151   [ +  -  +  + ]:       12995 :     while (leftmostSelect && leftmostSelect->op != SETOP_NONE)
    2152                 :        4351 :         leftmostSelect = leftmostSelect->larg;
    2153                 :             :     Assert(leftmostSelect && IsA(leftmostSelect, SelectStmt) &&
    2154                 :             :            leftmostSelect->larg == NULL);
    2155         [ -  + ]:        8644 :     if (leftmostSelect->intoClause)
    2156         [ #  # ]:           0 :         ereport(ERROR,
    2157                 :             :                 (errcode(ERRCODE_SYNTAX_ERROR),
    2158                 :             :                  errmsg("SELECT ... INTO is not allowed here"),
    2159                 :             :                  parser_errposition(pstate,
    2160                 :             :                                     exprLocation((Node *) leftmostSelect->intoClause))));
    2161                 :             : 
    2162                 :             :     /*
    2163                 :             :      * We need to extract ORDER BY and other top-level clauses here and not
    2164                 :             :      * let transformSetOperationTree() see them --- else it'll just recurse
    2165                 :             :      * right back here!
    2166                 :             :      */
    2167                 :        8644 :     sortClause = stmt->sortClause;
    2168                 :        8644 :     limitOffset = stmt->limitOffset;
    2169                 :        8644 :     limitCount = stmt->limitCount;
    2170                 :        8644 :     lockingClause = stmt->lockingClause;
    2171                 :        8644 :     withClause = stmt->withClause;
    2172                 :             : 
    2173                 :        8644 :     stmt->sortClause = NIL;
    2174                 :        8644 :     stmt->limitOffset = NULL;
    2175                 :        8644 :     stmt->limitCount = NULL;
    2176                 :        8644 :     stmt->lockingClause = NIL;
    2177                 :        8644 :     stmt->withClause = NULL;
    2178                 :             : 
    2179                 :             :     /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
    2180         [ +  + ]:        8644 :     if (lockingClause)
    2181         [ +  - ]:           4 :         ereport(ERROR,
    2182                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2183                 :             :         /*------
    2184                 :             :           translator: %s is a SQL row locking clause such as FOR UPDATE */
    2185                 :             :                  errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
    2186                 :             :                         LCS_asString(((LockingClause *)
    2187                 :             :                                       linitial(lockingClause))->strength))));
    2188                 :             : 
    2189                 :             :     /* Process the WITH clause independently of all else */
    2190         [ +  + ]:        8640 :     if (withClause)
    2191                 :             :     {
    2192                 :         174 :         qry->hasRecursive = withClause->recursive;
    2193                 :         174 :         qry->cteList = transformWithClause(pstate, withClause);
    2194                 :         174 :         qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
    2195                 :             :     }
    2196                 :             : 
    2197                 :             :     /*
    2198                 :             :      * Recursively transform the components of the tree.
    2199                 :             :      */
    2200                 :        8640 :     sostmt = castNode(SetOperationStmt,
    2201                 :             :                       transformSetOperationTree(pstate, stmt, true, NULL));
    2202                 :             :     Assert(sostmt);
    2203                 :        8592 :     qry->setOperations = (Node *) sostmt;
    2204                 :             : 
    2205                 :             :     /*
    2206                 :             :      * Re-find leftmost SELECT (now it's a sub-query in rangetable)
    2207                 :             :      */
    2208                 :        8592 :     node = sostmt->larg;
    2209   [ +  -  +  + ]:       12931 :     while (node && IsA(node, SetOperationStmt))
    2210                 :        4339 :         node = ((SetOperationStmt *) node)->larg;
    2211                 :             :     Assert(node && IsA(node, RangeTblRef));
    2212                 :        8592 :     leftmostRTI = ((RangeTblRef *) node)->rtindex;
    2213                 :        8592 :     leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
    2214                 :             :     Assert(leftmostQuery != NULL);
    2215                 :             : 
    2216                 :             :     /*
    2217                 :             :      * Generate dummy targetlist for outer query using column names of
    2218                 :             :      * leftmost select and common datatypes/collations of topmost set
    2219                 :             :      * operation.  Also make lists of the dummy vars and their names for use
    2220                 :             :      * in parsing ORDER BY.
    2221                 :             :      *
    2222                 :             :      * Note: we use leftmostRTI as the varno of the dummy variables. It
    2223                 :             :      * shouldn't matter too much which RT index they have, as long as they
    2224                 :             :      * have one that corresponds to a real RT entry; else funny things may
    2225                 :             :      * happen when the tree is mashed by rule rewriting.
    2226                 :             :      */
    2227                 :        8592 :     qry->targetList = NIL;
    2228                 :        8592 :     targetvars = NIL;
    2229                 :        8592 :     targetnames = NIL;
    2230                 :        8592 :     sortnscolumns = palloc0_array(ParseNamespaceColumn, list_length(sostmt->colTypes));
    2231                 :        8592 :     sortcolindex = 0;
    2232                 :             : 
    2233   [ +  +  +  +  :       29270 :     forfour(lct, sostmt->colTypes,
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
          -  +  -  +  -  
                   +  + ]
    2234                 :             :             lcm, sostmt->colTypmods,
    2235                 :             :             lcc, sostmt->colCollations,
    2236                 :             :             left_tlist, leftmostQuery->targetList)
    2237                 :             :     {
    2238                 :       20678 :         Oid         colType = lfirst_oid(lct);
    2239                 :       20678 :         int32       colTypmod = lfirst_int(lcm);
    2240                 :       20678 :         Oid         colCollation = lfirst_oid(lcc);
    2241                 :       20678 :         TargetEntry *lefttle = (TargetEntry *) lfirst(left_tlist);
    2242                 :             :         char       *colName;
    2243                 :             :         TargetEntry *tle;
    2244                 :             :         Var        *var;
    2245                 :             : 
    2246                 :             :         Assert(!lefttle->resjunk);
    2247                 :       20678 :         colName = pstrdup(lefttle->resname);
    2248                 :       20678 :         var = makeVar(leftmostRTI,
    2249                 :       20678 :                       lefttle->resno,
    2250                 :             :                       colType,
    2251                 :             :                       colTypmod,
    2252                 :             :                       colCollation,
    2253                 :             :                       0);
    2254                 :       20678 :         var->location = exprLocation((Node *) lefttle->expr);
    2255                 :       20678 :         tle = makeTargetEntry((Expr *) var,
    2256                 :       20678 :                               (AttrNumber) pstate->p_next_resno++,
    2257                 :             :                               colName,
    2258                 :             :                               false);
    2259                 :       20678 :         qry->targetList = lappend(qry->targetList, tle);
    2260                 :       20678 :         targetvars = lappend(targetvars, var);
    2261                 :       20678 :         targetnames = lappend(targetnames, makeString(colName));
    2262                 :       20678 :         sortnscolumns[sortcolindex].p_varno = leftmostRTI;
    2263                 :       20678 :         sortnscolumns[sortcolindex].p_varattno = lefttle->resno;
    2264                 :       20678 :         sortnscolumns[sortcolindex].p_vartype = colType;
    2265                 :       20678 :         sortnscolumns[sortcolindex].p_vartypmod = colTypmod;
    2266                 :       20678 :         sortnscolumns[sortcolindex].p_varcollid = colCollation;
    2267                 :       20678 :         sortnscolumns[sortcolindex].p_varnosyn = leftmostRTI;
    2268                 :       20678 :         sortnscolumns[sortcolindex].p_varattnosyn = lefttle->resno;
    2269                 :       20678 :         sortcolindex++;
    2270                 :             :     }
    2271                 :             : 
    2272                 :             :     /*
    2273                 :             :      * As a first step towards supporting sort clauses that are expressions
    2274                 :             :      * using the output columns, generate a namespace entry that makes the
    2275                 :             :      * output columns visible.  A Join RTE node is handy for this, since we
    2276                 :             :      * can easily control the Vars generated upon matches.
    2277                 :             :      *
    2278                 :             :      * Note: we don't yet do anything useful with such cases, but at least
    2279                 :             :      * "ORDER BY upper(foo)" will draw the right error message rather than
    2280                 :             :      * "foo not found".
    2281                 :             :      */
    2282                 :        8592 :     sv_rtable_length = list_length(pstate->p_rtable);
    2283                 :             : 
    2284                 :        8592 :     jnsitem = addRangeTableEntryForJoin(pstate,
    2285                 :             :                                         targetnames,
    2286                 :             :                                         sortnscolumns,
    2287                 :             :                                         JOIN_INNER,
    2288                 :             :                                         0,
    2289                 :             :                                         targetvars,
    2290                 :             :                                         NIL,
    2291                 :             :                                         NIL,
    2292                 :             :                                         NULL,
    2293                 :             :                                         NULL,
    2294                 :             :                                         false);
    2295                 :             : 
    2296                 :        8592 :     sv_namespace = pstate->p_namespace;
    2297                 :        8592 :     pstate->p_namespace = NIL;
    2298                 :             : 
    2299                 :             :     /* add jnsitem to column namespace only */
    2300                 :        8592 :     addNSItemToQuery(pstate, jnsitem, false, false, true);
    2301                 :             : 
    2302                 :             :     /*
    2303                 :             :      * For now, we don't support resjunk sort clauses on the output of a
    2304                 :             :      * setOperation tree --- you can only use the SQL92-spec options of
    2305                 :             :      * selecting an output column by name or number.  Enforce by checking that
    2306                 :             :      * transformSortClause doesn't add any items to tlist.  Note, if changing
    2307                 :             :      * this, add_setop_child_rel_equivalences() will need to be updated.
    2308                 :             :      */
    2309                 :        8592 :     tllen = list_length(qry->targetList);
    2310                 :             : 
    2311                 :        8592 :     qry->sortClause = transformSortClause(pstate,
    2312                 :             :                                           sortClause,
    2313                 :             :                                           &qry->targetList,
    2314                 :             :                                           EXPR_KIND_ORDER_BY,
    2315                 :             :                                           false /* allow SQL92 rules */ );
    2316                 :             : 
    2317                 :             :     /* restore namespace, remove join RTE from rtable */
    2318                 :        8588 :     pstate->p_namespace = sv_namespace;
    2319                 :        8588 :     pstate->p_rtable = list_truncate(pstate->p_rtable, sv_rtable_length);
    2320                 :             : 
    2321         [ -  + ]:        8588 :     if (tllen != list_length(qry->targetList))
    2322         [ #  # ]:           0 :         ereport(ERROR,
    2323                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2324                 :             :                  errmsg("invalid UNION/INTERSECT/EXCEPT ORDER BY clause"),
    2325                 :             :                  errdetail("Only result column names can be used, not expressions or functions."),
    2326                 :             :                  errhint("Add the expression/function to every SELECT, or move the UNION into a FROM clause."),
    2327                 :             :                  parser_errposition(pstate,
    2328                 :             :                                     exprLocation(list_nth(qry->targetList, tllen)))));
    2329                 :             : 
    2330                 :        8588 :     qry->limitOffset = transformLimitClause(pstate, limitOffset,
    2331                 :             :                                             EXPR_KIND_OFFSET, "OFFSET",
    2332                 :             :                                             stmt->limitOption);
    2333                 :        8588 :     qry->limitCount = transformLimitClause(pstate, limitCount,
    2334                 :             :                                            EXPR_KIND_LIMIT, "LIMIT",
    2335                 :             :                                            stmt->limitOption);
    2336                 :        8588 :     qry->limitOption = stmt->limitOption;
    2337                 :             : 
    2338                 :        8588 :     qry->rtable = pstate->p_rtable;
    2339                 :        8588 :     qry->rteperminfos = pstate->p_rteperminfos;
    2340                 :        8588 :     qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
    2341                 :             : 
    2342                 :        8588 :     qry->hasSubLinks = pstate->p_hasSubLinks;
    2343                 :        8588 :     qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
    2344                 :        8588 :     qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
    2345                 :        8588 :     qry->hasAggs = pstate->p_hasAggs;
    2346                 :             : 
    2347   [ -  +  -  -  :        8588 :     foreach(l, lockingClause)
                   -  + ]
    2348                 :             :     {
    2349                 :           0 :         transformLockingClause(pstate, qry,
    2350                 :           0 :                                (LockingClause *) lfirst(l), false);
    2351                 :             :     }
    2352                 :             : 
    2353                 :        8588 :     assign_query_collations(pstate, qry);
    2354                 :             : 
    2355                 :             :     /* this must be done after collations, for reliable comparison of exprs */
    2356   [ +  -  +  -  :        8588 :     if (pstate->p_hasAggs || qry->groupClause || qry->groupingSets || qry->havingQual)
             +  -  -  + ]
    2357                 :           0 :         parseCheckAggregates(pstate, qry);
    2358                 :             : 
    2359                 :        8588 :     return qry;
    2360                 :             : }
    2361                 :             : 
    2362                 :             : /*
    2363                 :             :  * Make a SortGroupClause node for a SetOperationStmt's groupClauses
    2364                 :             :  *
    2365                 :             :  * If require_hash is true, the caller is indicating that they need hash
    2366                 :             :  * support or they will fail.  So look extra hard for hash support.
    2367                 :             :  */
    2368                 :             : SortGroupClause *
    2369                 :       17666 : makeSortGroupClauseForSetOp(Oid rescoltype, bool require_hash)
    2370                 :             : {
    2371                 :       17666 :     SortGroupClause *grpcl = makeNode(SortGroupClause);
    2372                 :             :     Oid         sortop;
    2373                 :             :     Oid         eqop;
    2374                 :             :     bool        hashable;
    2375                 :             : 
    2376                 :             :     /* determine the eqop and optional sortop */
    2377                 :       17666 :     get_sort_group_operators(rescoltype,
    2378                 :             :                              false, true, false,
    2379                 :             :                              &sortop, &eqop, NULL,
    2380                 :             :                              &hashable);
    2381                 :             : 
    2382                 :             :     /*
    2383                 :             :      * The type cache doesn't believe that record is hashable (see
    2384                 :             :      * cache_record_field_properties()), but if the caller really needs hash
    2385                 :             :      * support, we can assume it does.  Worst case, if any components of the
    2386                 :             :      * record don't support hashing, we will fail at execution.
    2387                 :             :      */
    2388   [ +  +  +  +  :       17666 :     if (require_hash && (rescoltype == RECORDOID || rescoltype == RECORDARRAYOID))
                   +  + ]
    2389                 :          16 :         hashable = true;
    2390                 :             : 
    2391                 :             :     /* we don't have a tlist yet, so can't assign sortgrouprefs */
    2392                 :       17666 :     grpcl->tleSortGroupRef = 0;
    2393                 :       17666 :     grpcl->eqop = eqop;
    2394                 :       17666 :     grpcl->sortop = sortop;
    2395                 :       17666 :     grpcl->reverse_sort = false; /* Sort-op is "less than", or InvalidOid */
    2396                 :       17666 :     grpcl->nulls_first = false; /* OK with or without sortop */
    2397                 :       17666 :     grpcl->hashable = hashable;
    2398                 :             : 
    2399                 :       17666 :     return grpcl;
    2400                 :             : }
    2401                 :             : 
    2402                 :             : /*
    2403                 :             :  * transformSetOperationTree
    2404                 :             :  *      Recursively transform leaves and internal nodes of a set-op tree
    2405                 :             :  *
    2406                 :             :  * In addition to returning the transformed node, if targetlist isn't NULL
    2407                 :             :  * then we return a list of its non-resjunk TargetEntry nodes.  For a leaf
    2408                 :             :  * set-op node these are the actual targetlist entries; otherwise they are
    2409                 :             :  * dummy entries created to carry the type, typmod, collation, and location
    2410                 :             :  * (for error messages) of each output column of the set-op node.  This info
    2411                 :             :  * is needed only during the internal recursion of this function, so outside
    2412                 :             :  * callers pass NULL for targetlist.  Note: the reason for passing the
    2413                 :             :  * actual targetlist entries of a leaf node is so that upper levels can
    2414                 :             :  * replace UNKNOWN Consts with properly-coerced constants.
    2415                 :             :  */
    2416                 :             : static Node *
    2417                 :       34698 : transformSetOperationTree(ParseState *pstate, SelectStmt *stmt,
    2418                 :             :                           bool isTopLevel, List **targetlist)
    2419                 :             : {
    2420                 :             :     bool        isLeaf;
    2421                 :             : 
    2422                 :             :     Assert(stmt && IsA(stmt, SelectStmt));
    2423                 :             : 
    2424                 :             :     /* Guard against stack overflow due to overly complex set-expressions */
    2425                 :       34698 :     check_stack_depth();
    2426                 :             : 
    2427                 :             :     /*
    2428                 :             :      * Validity-check both leaf and internal SELECTs for disallowed ops.
    2429                 :             :      */
    2430         [ -  + ]:       34698 :     if (stmt->intoClause)
    2431         [ #  # ]:           0 :         ereport(ERROR,
    2432                 :             :                 (errcode(ERRCODE_SYNTAX_ERROR),
    2433                 :             :                  errmsg("INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT"),
    2434                 :             :                  parser_errposition(pstate,
    2435                 :             :                                     exprLocation((Node *) stmt->intoClause))));
    2436                 :             : 
    2437                 :             :     /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
    2438         [ -  + ]:       34698 :     if (stmt->lockingClause)
    2439         [ #  # ]:           0 :         ereport(ERROR,
    2440                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2441                 :             :         /*------
    2442                 :             :           translator: %s is a SQL row locking clause such as FOR UPDATE */
    2443                 :             :                  errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
    2444                 :             :                         LCS_asString(((LockingClause *)
    2445                 :             :                                       linitial(stmt->lockingClause))->strength))));
    2446                 :             : 
    2447                 :             :     /*
    2448                 :             :      * If an internal node of a set-op tree has ORDER BY, LIMIT, FOR UPDATE,
    2449                 :             :      * or WITH clauses attached, we need to treat it like a leaf node to
    2450                 :             :      * generate an independent sub-Query tree.  Otherwise, it can be
    2451                 :             :      * represented by a SetOperationStmt node underneath the parent Query.
    2452                 :             :      */
    2453         [ +  + ]:       34698 :     if (stmt->op == SETOP_NONE)
    2454                 :             :     {
    2455                 :             :         Assert(stmt->larg == NULL && stmt->rarg == NULL);
    2456                 :       21627 :         isLeaf = true;
    2457                 :             :     }
    2458                 :             :     else
    2459                 :             :     {
    2460                 :             :         Assert(stmt->larg != NULL && stmt->rarg != NULL);
    2461   [ +  +  +  -  :       13071 :         if (stmt->sortClause || stmt->limitOffset || stmt->limitCount ||
                   +  - ]
    2462   [ +  -  +  + ]:       13055 :             stmt->lockingClause || stmt->withClause)
    2463                 :          40 :             isLeaf = true;
    2464                 :             :         else
    2465                 :       13031 :             isLeaf = false;
    2466                 :             :     }
    2467                 :             : 
    2468         [ +  + ]:       34698 :     if (isLeaf)
    2469                 :             :     {
    2470                 :             :         /* Process leaf SELECT */
    2471                 :             :         Query      *selectQuery;
    2472                 :             :         ParseNamespaceItem *nsitem;
    2473                 :             :         RangeTblRef *rtr;
    2474                 :             : 
    2475                 :             :         /*
    2476                 :             :          * Transform SelectStmt into a Query.
    2477                 :             :          *
    2478                 :             :          * This works the same as SELECT transformation normally would, except
    2479                 :             :          * that we prevent resolving unknown-type outputs as TEXT.  This does
    2480                 :             :          * not change the subquery's semantics since if the column type
    2481                 :             :          * matters semantically, it would have been resolved to something else
    2482                 :             :          * anyway.  Doing this lets us resolve such outputs using
    2483                 :             :          * select_common_type(), below.
    2484                 :             :          *
    2485                 :             :          * Note: previously transformed sub-queries don't affect the parsing
    2486                 :             :          * of this sub-query, because they are not in the toplevel pstate's
    2487                 :             :          * namespace list.
    2488                 :             :          */
    2489                 :       21667 :         selectQuery = parse_sub_analyze((Node *) stmt, pstate,
    2490                 :             :                                         NULL, false, false);
    2491                 :             : 
    2492                 :             :         /*
    2493                 :             :          * Check for bogus references to Vars on the current query level (but
    2494                 :             :          * upper-level references are okay). Normally this can't happen
    2495                 :             :          * because the namespace will be empty, but it could happen if we are
    2496                 :             :          * inside a rule.
    2497                 :             :          */
    2498         [ -  + ]:       21647 :         if (pstate->p_namespace)
    2499                 :             :         {
    2500         [ #  # ]:           0 :             if (contain_vars_of_level((Node *) selectQuery, 1))
    2501         [ #  # ]:           0 :                 ereport(ERROR,
    2502                 :             :                         (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
    2503                 :             :                          errmsg("UNION/INTERSECT/EXCEPT member statement cannot refer to other relations of same query level"),
    2504                 :             :                          parser_errposition(pstate,
    2505                 :             :                                             locate_var_of_level((Node *) selectQuery, 1))));
    2506                 :             :         }
    2507                 :             : 
    2508                 :             :         /*
    2509                 :             :          * Extract a list of the non-junk TLEs for upper-level processing.
    2510                 :             :          */
    2511         [ +  - ]:       21647 :         if (targetlist)
    2512                 :             :         {
    2513                 :             :             ListCell   *tl;
    2514                 :             : 
    2515                 :       21647 :             *targetlist = NIL;
    2516   [ +  +  +  +  :       81892 :             foreach(tl, selectQuery->targetList)
                   +  + ]
    2517                 :             :             {
    2518                 :       60245 :                 TargetEntry *tle = (TargetEntry *) lfirst(tl);
    2519                 :             : 
    2520         [ +  + ]:       60245 :                 if (!tle->resjunk)
    2521                 :       60237 :                     *targetlist = lappend(*targetlist, tle);
    2522                 :             :             }
    2523                 :             :         }
    2524                 :             : 
    2525                 :             :         /*
    2526                 :             :          * Make the leaf query be a subquery in the top-level rangetable.
    2527                 :             :          */
    2528                 :       21647 :         nsitem = addRangeTableEntryForSubquery(pstate,
    2529                 :             :                                                selectQuery,
    2530                 :             :                                                NULL,
    2531                 :             :                                                false,
    2532                 :             :                                                false);
    2533                 :             : 
    2534                 :             :         /*
    2535                 :             :          * Return a RangeTblRef to replace the SelectStmt in the set-op tree.
    2536                 :             :          */
    2537                 :       21647 :         rtr = makeNode(RangeTblRef);
    2538                 :       21647 :         rtr->rtindex = nsitem->p_rtindex;
    2539                 :       21647 :         return (Node *) rtr;
    2540                 :             :     }
    2541                 :             :     else
    2542                 :             :     {
    2543                 :             :         /* Process an internal node (set operation node) */
    2544                 :       13031 :         SetOperationStmt *op = makeNode(SetOperationStmt);
    2545                 :             :         List       *ltargetlist;
    2546                 :             :         List       *rtargetlist;
    2547                 :             :         const char *context;
    2548         [ +  + ]:       13772 :         bool        recursive = (pstate->p_parent_cte &&
    2549         [ +  + ]:         741 :                                  pstate->p_parent_cte->cterecursive);
    2550                 :             : 
    2551         [ +  + ]:       13562 :         context = (stmt->op == SETOP_UNION ? "UNION" :
    2552         [ +  + ]:         531 :                    (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
    2553                 :             :                     "EXCEPT"));
    2554                 :             : 
    2555                 :       13031 :         op->op = stmt->op;
    2556                 :       13031 :         op->all = stmt->all;
    2557                 :             : 
    2558                 :             :         /*
    2559                 :             :          * Recursively transform the left child node.
    2560                 :             :          */
    2561                 :       13031 :         op->larg = transformSetOperationTree(pstate, stmt->larg,
    2562                 :             :                                              false,
    2563                 :             :                                              &ltargetlist);
    2564                 :             : 
    2565                 :             :         /*
    2566                 :             :          * If we are processing a recursive union query, now is the time to
    2567                 :             :          * examine the non-recursive term's output columns and mark the
    2568                 :             :          * containing CTE as having those result columns.  We should do this
    2569                 :             :          * only at the topmost setop of the CTE, of course.
    2570                 :             :          */
    2571   [ +  +  +  + ]:       13027 :         if (isTopLevel && recursive)
    2572                 :         645 :             determineRecursiveColTypes(pstate, op->larg, ltargetlist);
    2573                 :             : 
    2574                 :             :         /*
    2575                 :             :          * Recursively transform the right child node.
    2576                 :             :          */
    2577                 :       13027 :         op->rarg = transformSetOperationTree(pstate, stmt->rarg,
    2578                 :             :                                              false,
    2579                 :             :                                              &rtargetlist);
    2580                 :             : 
    2581                 :       13011 :         constructSetOpTargetlist(pstate, op, ltargetlist, rtargetlist, targetlist,
    2582                 :             :                                  context, recursive);
    2583                 :             : 
    2584                 :       12983 :         return (Node *) op;
    2585                 :             :     }
    2586                 :             : }
    2587                 :             : 
    2588                 :             : /*
    2589                 :             :  * constructSetOpTargetlist
    2590                 :             :  *      Compute the types, typmods and collations of the columns in the target
    2591                 :             :  *      list of the given set operation.
    2592                 :             :  *
    2593                 :             :  * For every pair of columns in the targetlists of the children, compute the
    2594                 :             :  * common type, typmod, and collation representing the output (UNION) column.
    2595                 :             :  * If targetlist is not NULL, also build the dummy output targetlist
    2596                 :             :  * containing non-resjunk output columns.  The values are stored into the
    2597                 :             :  * given SetOperationStmt node.  context is a string for error messages
    2598                 :             :  * ("UNION" etc.).  recursive is true if it is a recursive union.
    2599                 :             :  */
    2600                 :             : void
    2601                 :       13396 : constructSetOpTargetlist(ParseState *pstate, SetOperationStmt *op,
    2602                 :             :                          const List *ltargetlist, const List *rtargetlist,
    2603                 :             :                          List **targetlist, const char *context, bool recursive)
    2604                 :             : {
    2605                 :             :     ListCell   *ltl;
    2606                 :             :     ListCell   *rtl;
    2607                 :             : 
    2608                 :             :     /*
    2609                 :             :      * Verify that the two children have the same number of non-junk columns,
    2610                 :             :      * and determine the types of the merged output columns.
    2611                 :             :      */
    2612         [ -  + ]:       13396 :     if (list_length(ltargetlist) != list_length(rtargetlist))
    2613         [ #  # ]:           0 :         ereport(ERROR,
    2614                 :             :                 (errcode(ERRCODE_SYNTAX_ERROR),
    2615                 :             :                  errmsg("each %s query must have the same number of columns",
    2616                 :             :                         context),
    2617                 :             :                  parser_errposition(pstate,
    2618                 :             :                                     exprLocation((const Node *) rtargetlist))));
    2619                 :             : 
    2620         [ +  + ]:       13396 :     if (targetlist)
    2621                 :        4643 :         *targetlist = NIL;
    2622                 :       13396 :     op->colTypes = NIL;
    2623                 :       13396 :     op->colTypmods = NIL;
    2624                 :       13396 :     op->colCollations = NIL;
    2625                 :       13396 :     op->groupClauses = NIL;
    2626                 :             : 
    2627   [ +  +  +  +  :       53852 :     forboth(ltl, ltargetlist, rtl, rtargetlist)
          +  +  +  +  +  
             +  +  -  +  
                      + ]
    2628                 :             :     {
    2629                 :       40484 :         TargetEntry *ltle = (TargetEntry *) lfirst(ltl);
    2630                 :       40484 :         TargetEntry *rtle = (TargetEntry *) lfirst(rtl);
    2631                 :       40484 :         Node       *lcolnode = (Node *) ltle->expr;
    2632                 :       40484 :         Node       *rcolnode = (Node *) rtle->expr;
    2633                 :       40484 :         Oid         lcoltype = exprType(lcolnode);
    2634                 :       40484 :         Oid         rcoltype = exprType(rcolnode);
    2635                 :             :         Node       *bestexpr;
    2636                 :             :         int         bestlocation;
    2637                 :             :         Oid         rescoltype;
    2638                 :             :         int32       rescoltypmod;
    2639                 :             :         Oid         rescolcoll;
    2640                 :             : 
    2641                 :             :         /* select common type, same as CASE et al */
    2642                 :       40484 :         rescoltype = select_common_type(pstate,
    2643                 :             :                                         list_make2(lcolnode, rcolnode),
    2644                 :             :                                         context,
    2645                 :             :                                         &bestexpr);
    2646                 :       40484 :         bestlocation = exprLocation(bestexpr);
    2647                 :             : 
    2648                 :             :         /*
    2649                 :             :          * Verify the coercions are actually possible.  If not, we'd fail
    2650                 :             :          * later anyway, but we want to fail now while we have sufficient
    2651                 :             :          * context to produce an error cursor position.
    2652                 :             :          *
    2653                 :             :          * For all non-UNKNOWN-type cases, we verify coercibility but we don't
    2654                 :             :          * modify the child's expression, for fear of changing the child
    2655                 :             :          * query's semantics.
    2656                 :             :          *
    2657                 :             :          * If a child expression is an UNKNOWN-type Const or Param, we want to
    2658                 :             :          * replace it with the coerced expression.  This can only happen when
    2659                 :             :          * the child is a leaf set-op node.  It's safe to replace the
    2660                 :             :          * expression because if the child query's semantics depended on the
    2661                 :             :          * type of this output column, it'd have already coerced the UNKNOWN
    2662                 :             :          * to something else.  We want to do this because (a) we want to
    2663                 :             :          * verify that a Const is valid for the target type, or resolve the
    2664                 :             :          * actual type of an UNKNOWN Param, and (b) we want to avoid
    2665                 :             :          * unnecessary discrepancies between the output type of the child
    2666                 :             :          * query and the resolved target type. Such a discrepancy would
    2667                 :             :          * disable optimization in the planner.
    2668                 :             :          *
    2669                 :             :          * If it's some other UNKNOWN-type node, eg a Var, we do nothing
    2670                 :             :          * (knowing that coerce_to_common_type would fail).  The planner is
    2671                 :             :          * sometimes able to fold an UNKNOWN Var to a constant before it has
    2672                 :             :          * to coerce the type, so failing now would just break cases that
    2673                 :             :          * might work.
    2674                 :             :          */
    2675         [ +  + ]:       40484 :         if (lcoltype != UNKNOWNOID)
    2676                 :       36103 :             lcolnode = coerce_to_common_type(pstate, lcolnode,
    2677                 :             :                                              rescoltype, context);
    2678         [ -  + ]:        4381 :         else if (IsA(lcolnode, Const) ||
    2679         [ #  # ]:           0 :                  IsA(lcolnode, Param))
    2680                 :             :         {
    2681                 :        4381 :             lcolnode = coerce_to_common_type(pstate, lcolnode,
    2682                 :             :                                              rescoltype, context);
    2683                 :        4381 :             ltle->expr = (Expr *) lcolnode;
    2684                 :             :         }
    2685                 :             : 
    2686         [ +  + ]:       40484 :         if (rcoltype != UNKNOWNOID)
    2687                 :       35559 :             rcolnode = coerce_to_common_type(pstate, rcolnode,
    2688                 :             :                                              rescoltype, context);
    2689         [ -  + ]:        4925 :         else if (IsA(rcolnode, Const) ||
    2690         [ #  # ]:           0 :                  IsA(rcolnode, Param))
    2691                 :             :         {
    2692                 :        4925 :             rcolnode = coerce_to_common_type(pstate, rcolnode,
    2693                 :             :                                              rescoltype, context);
    2694                 :        4921 :             rtle->expr = (Expr *) rcolnode;
    2695                 :             :         }
    2696                 :             : 
    2697                 :       40480 :         rescoltypmod = select_common_typmod(pstate,
    2698                 :             :                                             list_make2(lcolnode, rcolnode),
    2699                 :             :                                             rescoltype);
    2700                 :             : 
    2701                 :             :         /*
    2702                 :             :          * Select common collation.  A common collation is required for all
    2703                 :             :          * set operators except UNION ALL; see SQL:2008 7.13 <query
    2704                 :             :          * expression> Syntax Rule 15c.  (If we fail to identify a common
    2705                 :             :          * collation for a UNION ALL column, the colCollations element will be
    2706                 :             :          * set to InvalidOid, which may result in a runtime error if something
    2707                 :             :          * at a higher query level wants to use the column's collation.)
    2708                 :             :          */
    2709                 :       40480 :         rescolcoll = select_common_collation(pstate,
    2710                 :             :                                              list_make2(lcolnode, rcolnode),
    2711   [ +  +  +  + ]:       40480 :                                              (op->op == SETOP_UNION && op->all));
    2712                 :             : 
    2713                 :             :         /* emit results */
    2714                 :       40456 :         op->colTypes = lappend_oid(op->colTypes, rescoltype);
    2715                 :       40456 :         op->colTypmods = lappend_int(op->colTypmods, rescoltypmod);
    2716                 :       40456 :         op->colCollations = lappend_oid(op->colCollations, rescolcoll);
    2717                 :             : 
    2718                 :             :         /*
    2719                 :             :          * For all cases except UNION ALL, identify the grouping operators
    2720                 :             :          * (and, if available, sorting operators) that will be used to
    2721                 :             :          * eliminate duplicates.
    2722                 :             :          */
    2723   [ +  +  +  + ]:       40456 :         if (op->op != SETOP_UNION || !op->all)
    2724                 :             :         {
    2725                 :             :             ParseCallbackState pcbstate;
    2726                 :             : 
    2727                 :       17650 :             setup_parser_errposition_callback(&pcbstate, pstate,
    2728                 :             :                                               bestlocation);
    2729                 :             : 
    2730                 :             :             /* If it's a recursive union, we need to require hashing support. */
    2731                 :       17650 :             op->groupClauses = lappend(op->groupClauses,
    2732                 :       17650 :                                        makeSortGroupClauseForSetOp(rescoltype, recursive));
    2733                 :             : 
    2734                 :       17650 :             cancel_parser_errposition_callback(&pcbstate);
    2735                 :             :         }
    2736                 :             : 
    2737                 :             :         /*
    2738                 :             :          * Construct a dummy tlist entry to return.  We use a SetToDefault
    2739                 :             :          * node for the expression, since it carries exactly the fields
    2740                 :             :          * needed, but any other expression node type would do as well.
    2741                 :             :          */
    2742         [ +  + ]:       40456 :         if (targetlist)
    2743                 :             :         {
    2744                 :       19401 :             SetToDefault *rescolnode = makeNode(SetToDefault);
    2745                 :             :             TargetEntry *restle;
    2746                 :             : 
    2747                 :       19401 :             rescolnode->typeId = rescoltype;
    2748                 :       19401 :             rescolnode->typeMod = rescoltypmod;
    2749                 :       19401 :             rescolnode->collation = rescolcoll;
    2750                 :       19401 :             rescolnode->location = bestlocation;
    2751                 :       19401 :             restle = makeTargetEntry((Expr *) rescolnode,
    2752                 :             :                                      0, /* no need to set resno */
    2753                 :             :                                      NULL,
    2754                 :             :                                      false);
    2755                 :       19401 :             *targetlist = lappend(*targetlist, restle);
    2756                 :             :         }
    2757                 :             :     }
    2758                 :       13368 : }
    2759                 :             : 
    2760                 :             : /*
    2761                 :             :  * Process the outputs of the non-recursive term of a recursive union
    2762                 :             :  * to set up the parent CTE's columns
    2763                 :             :  */
    2764                 :             : static void
    2765                 :         645 : determineRecursiveColTypes(ParseState *pstate, Node *larg, List *nrtargetlist)
    2766                 :             : {
    2767                 :             :     Node       *node;
    2768                 :             :     int         leftmostRTI;
    2769                 :             :     Query      *leftmostQuery;
    2770                 :             :     List       *targetList;
    2771                 :             :     ListCell   *left_tlist;
    2772                 :             :     ListCell   *nrtl;
    2773                 :             :     int         next_resno;
    2774                 :             : 
    2775                 :             :     /*
    2776                 :             :      * Find leftmost leaf SELECT
    2777                 :             :      */
    2778                 :         645 :     node = larg;
    2779   [ +  -  +  + ]:         649 :     while (node && IsA(node, SetOperationStmt))
    2780                 :           4 :         node = ((SetOperationStmt *) node)->larg;
    2781                 :             :     Assert(node && IsA(node, RangeTblRef));
    2782                 :         645 :     leftmostRTI = ((RangeTblRef *) node)->rtindex;
    2783                 :         645 :     leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
    2784                 :             :     Assert(leftmostQuery != NULL);
    2785                 :             : 
    2786                 :             :     /*
    2787                 :             :      * Generate dummy targetlist using column names of leftmost select and
    2788                 :             :      * dummy result expressions of the non-recursive term.
    2789                 :             :      */
    2790                 :         645 :     targetList = NIL;
    2791                 :         645 :     next_resno = 1;
    2792                 :             : 
    2793   [ +  -  +  +  :        1992 :     forboth(nrtl, nrtargetlist, left_tlist, leftmostQuery->targetList)
          +  -  +  +  +  
             +  +  -  +  
                      + ]
    2794                 :             :     {
    2795                 :        1347 :         TargetEntry *nrtle = (TargetEntry *) lfirst(nrtl);
    2796                 :        1347 :         TargetEntry *lefttle = (TargetEntry *) lfirst(left_tlist);
    2797                 :             :         char       *colName;
    2798                 :             :         TargetEntry *tle;
    2799                 :             : 
    2800                 :             :         Assert(!lefttle->resjunk);
    2801                 :        1347 :         colName = pstrdup(lefttle->resname);
    2802                 :        1347 :         tle = makeTargetEntry(nrtle->expr,
    2803                 :        1347 :                               next_resno++,
    2804                 :             :                               colName,
    2805                 :             :                               false);
    2806                 :        1347 :         targetList = lappend(targetList, tle);
    2807                 :             :     }
    2808                 :             : 
    2809                 :             :     /* Now build CTE's output column info using dummy targetlist */
    2810                 :         645 :     analyzeCTETargetList(pstate, pstate->p_parent_cte, targetList);
    2811                 :         645 : }
    2812                 :             : 
    2813                 :             : 
    2814                 :             : /*
    2815                 :             :  * transformReturnStmt -
    2816                 :             :  *    transforms a return statement
    2817                 :             :  */
    2818                 :             : static Query *
    2819                 :        2776 : transformReturnStmt(ParseState *pstate, ReturnStmt *stmt)
    2820                 :             : {
    2821                 :        2776 :     Query      *qry = makeNode(Query);
    2822                 :             : 
    2823                 :        2776 :     qry->commandType = CMD_SELECT;
    2824                 :        2776 :     qry->isReturn = true;
    2825                 :             : 
    2826                 :        2776 :     qry->targetList = list_make1(makeTargetEntry((Expr *) transformExpr(pstate, stmt->returnval, EXPR_KIND_SELECT_TARGET),
    2827                 :             :                                                  1, NULL, false));
    2828                 :             : 
    2829         [ +  - ]:        2772 :     if (pstate->p_resolve_unknowns)
    2830                 :        2772 :         resolveTargetListUnknowns(pstate, qry->targetList);
    2831                 :        2772 :     qry->rtable = pstate->p_rtable;
    2832                 :        2772 :     qry->rteperminfos = pstate->p_rteperminfos;
    2833                 :        2772 :     qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
    2834                 :        2772 :     qry->hasSubLinks = pstate->p_hasSubLinks;
    2835                 :        2772 :     qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
    2836                 :        2772 :     qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
    2837                 :        2772 :     qry->hasAggs = pstate->p_hasAggs;
    2838                 :             : 
    2839                 :        2772 :     assign_query_collations(pstate, qry);
    2840                 :             : 
    2841                 :        2772 :     return qry;
    2842                 :             : }
    2843                 :             : 
    2844                 :             : 
    2845                 :             : /*
    2846                 :             :  * transformUpdateStmt -
    2847                 :             :  *    transforms an update statement
    2848                 :             :  */
    2849                 :             : static Query *
    2850                 :        9396 : transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
    2851                 :             : {
    2852                 :        9396 :     Query      *qry = makeNode(Query);
    2853                 :             :     ParseNamespaceItem *nsitem;
    2854                 :             :     Node       *qual;
    2855                 :             : 
    2856                 :        9396 :     qry->commandType = CMD_UPDATE;
    2857                 :             : 
    2858                 :             :     /* process the WITH clause independently of all else */
    2859         [ +  + ]:        9396 :     if (stmt->withClause)
    2860                 :             :     {
    2861                 :          55 :         qry->hasRecursive = stmt->withClause->recursive;
    2862                 :          55 :         qry->cteList = transformWithClause(pstate, stmt->withClause);
    2863                 :          55 :         qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
    2864                 :             :     }
    2865                 :             : 
    2866                 :       18791 :     qry->resultRelation = setTargetTable(pstate, stmt->relation,
    2867                 :        9396 :                                          stmt->relation->inh,
    2868                 :             :                                          true,
    2869                 :             :                                          ACL_UPDATE);
    2870                 :             : 
    2871                 :             :     /* disallow UPDATE ... WHERE CURRENT OF on a view */
    2872         [ +  + ]:        9395 :     if (stmt->whereClause &&
    2873         [ +  + ]:        7036 :         IsA(stmt->whereClause, CurrentOfExpr) &&
    2874         [ +  + ]:         108 :         pstate->p_target_relation->rd_rel->relkind == RELKIND_VIEW)
    2875         [ +  - ]:           4 :         ereport(ERROR,
    2876                 :             :                 errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2877                 :             :                 errmsg("WHERE CURRENT OF on a view is not implemented"));
    2878                 :             : 
    2879         [ +  + ]:        9391 :     if (stmt->forPortionOf)
    2880                 :         594 :         qry->forPortionOf = transformForPortionOfClause(pstate,
    2881                 :             :                                                         qry->resultRelation,
    2882                 :         654 :                                                         stmt->forPortionOf,
    2883                 :         654 :                                                         stmt->whereClause,
    2884                 :             :                                                         true);
    2885                 :             : 
    2886                 :        9331 :     nsitem = pstate->p_target_nsitem;
    2887                 :             : 
    2888                 :             :     /* subqueries in FROM cannot access the result relation */
    2889                 :        9331 :     nsitem->p_lateral_only = true;
    2890                 :        9331 :     nsitem->p_lateral_ok = false;
    2891                 :             : 
    2892                 :             :     /*
    2893                 :             :      * the FROM clause is non-standard SQL syntax. We used to be able to do
    2894                 :             :      * this with REPLACE in POSTQUEL so we keep the feature.
    2895                 :             :      */
    2896                 :        9331 :     transformFromClause(pstate, stmt->fromClause);
    2897                 :             : 
    2898                 :             :     /* remaining clauses can reference the result relation normally */
    2899                 :        9315 :     nsitem->p_lateral_only = false;
    2900                 :        9315 :     nsitem->p_lateral_ok = true;
    2901                 :             : 
    2902                 :        9315 :     qual = transformWhereClause(pstate, stmt->whereClause,
    2903                 :             :                                 EXPR_KIND_WHERE, "WHERE");
    2904                 :             : 
    2905                 :        9307 :     transformReturningClause(pstate, qry, stmt->returningClause,
    2906                 :             :                              EXPR_KIND_RETURNING);
    2907                 :             : 
    2908                 :             :     /*
    2909                 :             :      * Now we are done with SELECT-like processing, and can get on with
    2910                 :             :      * transforming the target list to match the UPDATE target columns.
    2911                 :             :      */
    2912                 :        9295 :     qry->targetList = transformUpdateTargetList(pstate, stmt->targetList,
    2913                 :             :                                                 qry->forPortionOf);
    2914                 :             : 
    2915                 :        9259 :     qry->rtable = pstate->p_rtable;
    2916                 :        9259 :     qry->rteperminfos = pstate->p_rteperminfos;
    2917                 :        9259 :     qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
    2918                 :             : 
    2919                 :        9259 :     qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
    2920                 :        9259 :     qry->hasSubLinks = pstate->p_hasSubLinks;
    2921                 :             : 
    2922                 :        9259 :     assign_query_collations(pstate, qry);
    2923                 :             : 
    2924                 :        9259 :     return qry;
    2925                 :             : }
    2926                 :             : 
    2927                 :             : /*
    2928                 :             :  * transformUpdateTargetList -
    2929                 :             :  *  handle SET clause in UPDATE/MERGE/INSERT ... ON CONFLICT UPDATE
    2930                 :             :  */
    2931                 :             : List *
    2932                 :       11209 : transformUpdateTargetList(ParseState *pstate, List *origTlist, ForPortionOfExpr *forPortionOf)
    2933                 :             : {
    2934                 :       11209 :     List       *tlist = NIL;
    2935                 :             :     RTEPermissionInfo *target_perminfo;
    2936                 :             :     ListCell   *orig_tl;
    2937                 :             :     ListCell   *tl;
    2938                 :             : 
    2939                 :       11209 :     tlist = transformTargetList(pstate, origTlist,
    2940                 :             :                                 EXPR_KIND_UPDATE_SOURCE);
    2941                 :             : 
    2942                 :             :     /* Prepare to assign non-conflicting resnos to resjunk attributes */
    2943         [ +  + ]:       11177 :     if (pstate->p_next_resno <= RelationGetNumberOfAttributes(pstate->p_target_relation))
    2944                 :        9517 :         pstate->p_next_resno = RelationGetNumberOfAttributes(pstate->p_target_relation) + 1;
    2945                 :             : 
    2946                 :             :     /* Prepare non-junk columns for assignment to target table */
    2947                 :       11177 :     target_perminfo = pstate->p_target_nsitem->p_perminfo;
    2948                 :       11177 :     orig_tl = list_head(origTlist);
    2949                 :             : 
    2950   [ +  -  +  +  :       25002 :     foreach(tl, tlist)
                   +  + ]
    2951                 :             :     {
    2952                 :       13853 :         TargetEntry *tle = (TargetEntry *) lfirst(tl);
    2953                 :             :         ResTarget  *origTarget;
    2954                 :             :         int         attrno;
    2955                 :             : 
    2956         [ +  + ]:       13853 :         if (tle->resjunk)
    2957                 :             :         {
    2958                 :             :             /*
    2959                 :             :              * Resjunk nodes need no additional processing, but be sure they
    2960                 :             :              * have resnos that do not match any target columns; else rewriter
    2961                 :             :              * or planner might get confused.  They don't need a resname
    2962                 :             :              * either.
    2963                 :             :              */
    2964                 :          91 :             tle->resno = (AttrNumber) pstate->p_next_resno++;
    2965                 :          91 :             tle->resname = NULL;
    2966                 :          91 :             continue;
    2967                 :             :         }
    2968         [ -  + ]:       13762 :         if (orig_tl == NULL)
    2969         [ #  # ]:           0 :             elog(ERROR, "UPDATE target count mismatch --- internal error");
    2970                 :       13762 :         origTarget = lfirst_node(ResTarget, orig_tl);
    2971                 :             : 
    2972                 :       13762 :         attrno = attnameAttNum(pstate->p_target_relation,
    2973                 :       13762 :                                origTarget->name, true);
    2974         [ +  + ]:       13762 :         if (attrno == InvalidAttrNumber)
    2975   [ +  -  +  +  :          16 :             ereport(ERROR,
                   +  - ]
    2976                 :             :                     (errcode(ERRCODE_UNDEFINED_COLUMN),
    2977                 :             :                      errmsg("column \"%s\" of relation \"%s\" does not exist",
    2978                 :             :                             origTarget->name,
    2979                 :             :                             RelationGetRelationName(pstate->p_target_relation)),
    2980                 :             :                      (origTarget->indirection != NIL &&
    2981                 :             :                       strcmp(origTarget->name, pstate->p_target_nsitem->p_names->aliasname) == 0) ?
    2982                 :             :                      errhint("SET target columns cannot be qualified with the relation name.") : 0,
    2983                 :             :                      parser_errposition(pstate, origTarget->location)));
    2984                 :             : 
    2985                 :             :         /*
    2986                 :             :          * If this is a FOR PORTION OF update, forbid directly setting the
    2987                 :             :          * range column, since that would conflict with the implicit updates.
    2988                 :             :          */
    2989         [ +  + ]:       13746 :         if (forPortionOf != NULL)
    2990                 :             :         {
    2991         [ +  + ]:         607 :             if (attrno == forPortionOf->rangeVar->varattno)
    2992         [ +  - ]:           4 :                 ereport(ERROR,
    2993                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    2994                 :             :                          errmsg("cannot update column \"%s\" because it is used in FOR PORTION OF",
    2995                 :             :                                 origTarget->name),
    2996                 :             :                          parser_errposition(pstate, origTarget->location)));
    2997                 :             :         }
    2998                 :             : 
    2999                 :       13742 :         updateTargetListEntry(pstate, tle, origTarget->name,
    3000                 :             :                               attrno,
    3001                 :             :                               origTarget->indirection,
    3002                 :             :                               origTarget->location);
    3003                 :             : 
    3004                 :             :         /* Mark the target column as requiring update permissions */
    3005                 :       13734 :         target_perminfo->updatedCols = bms_add_member(target_perminfo->updatedCols,
    3006                 :             :                                                       attrno - FirstLowInvalidHeapAttributeNumber);
    3007                 :             : 
    3008                 :       13734 :         orig_tl = lnext(origTlist, orig_tl);
    3009                 :             :     }
    3010         [ -  + ]:       11149 :     if (orig_tl != NULL)
    3011         [ #  # ]:           0 :         elog(ERROR, "UPDATE target count mismatch --- internal error");
    3012                 :             : 
    3013                 :       11149 :     return tlist;
    3014                 :             : }
    3015                 :             : 
    3016                 :             : /*
    3017                 :             :  * addNSItemForReturning -
    3018                 :             :  *  add a ParseNamespaceItem for the OLD or NEW alias in RETURNING.
    3019                 :             :  */
    3020                 :             : static void
    3021                 :        4630 : addNSItemForReturning(ParseState *pstate, const char *aliasname,
    3022                 :             :                       VarReturningType returning_type)
    3023                 :             : {
    3024                 :             :     List       *colnames;
    3025                 :             :     int         numattrs;
    3026                 :             :     ParseNamespaceColumn *nscolumns;
    3027                 :             :     ParseNamespaceItem *nsitem;
    3028                 :             : 
    3029                 :             :     /* copy per-column data from the target relation */
    3030                 :        4630 :     colnames = pstate->p_target_nsitem->p_rte->eref->colnames;
    3031                 :        4630 :     numattrs = list_length(colnames);
    3032                 :             : 
    3033                 :        4630 :     nscolumns = palloc_array(ParseNamespaceColumn, numattrs);
    3034                 :             : 
    3035                 :        4630 :     memcpy(nscolumns, pstate->p_target_nsitem->p_nscolumns,
    3036                 :             :            numattrs * sizeof(ParseNamespaceColumn));
    3037                 :             : 
    3038                 :             :     /* mark all columns as returning OLD/NEW */
    3039         [ +  + ]:       18226 :     for (int i = 0; i < numattrs; i++)
    3040                 :       13596 :         nscolumns[i].p_varreturningtype = returning_type;
    3041                 :             : 
    3042                 :             :     /* build the nsitem, copying most fields from the target relation */
    3043                 :        4630 :     nsitem = palloc_object(ParseNamespaceItem);
    3044                 :        4630 :     nsitem->p_names = makeAlias(aliasname, colnames);
    3045                 :        4630 :     nsitem->p_rte = pstate->p_target_nsitem->p_rte;
    3046                 :        4630 :     nsitem->p_rtindex = pstate->p_target_nsitem->p_rtindex;
    3047                 :        4630 :     nsitem->p_perminfo = pstate->p_target_nsitem->p_perminfo;
    3048                 :        4630 :     nsitem->p_nscolumns = nscolumns;
    3049                 :        4630 :     nsitem->p_returning_type = returning_type;
    3050                 :             : 
    3051                 :             :     /* add it to the query namespace as a table-only item */
    3052                 :        4630 :     addNSItemToQuery(pstate, nsitem, false, true, false);
    3053                 :        4630 : }
    3054                 :             : 
    3055                 :             : /*
    3056                 :             :  * transformReturningClause -
    3057                 :             :  *  handle a RETURNING clause in INSERT/UPDATE/DELETE/MERGE
    3058                 :             :  */
    3059                 :             : void
    3060                 :       15112 : transformReturningClause(ParseState *pstate, Query *qry,
    3061                 :             :                          ReturningClause *returningClause,
    3062                 :             :                          ParseExprKind exprKind)
    3063                 :             : {
    3064                 :       15112 :     int         save_nslen = list_length(pstate->p_namespace);
    3065                 :             :     int         save_next_resno;
    3066                 :             : 
    3067         [ +  + ]:       15112 :     if (returningClause == NULL)
    3068                 :       12751 :         return;                 /* nothing to do */
    3069                 :             : 
    3070                 :             :     /*
    3071                 :             :      * Scan RETURNING WITH(...) options for OLD/NEW alias names.  Complain if
    3072                 :             :      * there is any conflict with existing relations.
    3073                 :             :      */
    3074   [ +  +  +  +  :        4770 :     foreach_node(ReturningOption, option, returningClause->options)
                   +  + ]
    3075                 :             :     {
    3076      [ +  +  - ]:          80 :         switch (option->option)
    3077                 :             :         {
    3078                 :          36 :             case RETURNING_OPTION_OLD:
    3079         [ +  + ]:          36 :                 if (qry->returningOldAlias != NULL)
    3080         [ +  - ]:           4 :                     ereport(ERROR,
    3081                 :             :                             errcode(ERRCODE_SYNTAX_ERROR),
    3082                 :             :                     /* translator: %s is OLD or NEW */
    3083                 :             :                             errmsg("%s cannot be specified multiple times", "OLD"),
    3084                 :             :                             parser_errposition(pstate, option->location));
    3085                 :          32 :                 qry->returningOldAlias = option->value;
    3086                 :          32 :                 break;
    3087                 :             : 
    3088                 :          44 :             case RETURNING_OPTION_NEW:
    3089         [ +  + ]:          44 :                 if (qry->returningNewAlias != NULL)
    3090         [ +  - ]:           4 :                     ereport(ERROR,
    3091                 :             :                             errcode(ERRCODE_SYNTAX_ERROR),
    3092                 :             :                     /* translator: %s is OLD or NEW */
    3093                 :             :                             errmsg("%s cannot be specified multiple times", "NEW"),
    3094                 :             :                             parser_errposition(pstate, option->location));
    3095                 :          40 :                 qry->returningNewAlias = option->value;
    3096                 :          40 :                 break;
    3097                 :             : 
    3098                 :           0 :             default:
    3099         [ #  # ]:           0 :                 elog(ERROR, "unrecognized returning option: %d", option->option);
    3100                 :             :         }
    3101                 :             : 
    3102         [ +  + ]:          72 :         if (refnameNamespaceItem(pstate, NULL, option->value, -1, NULL) != NULL)
    3103         [ +  - ]:           8 :             ereport(ERROR,
    3104                 :             :                     errcode(ERRCODE_DUPLICATE_ALIAS),
    3105                 :             :                     errmsg("table name \"%s\" specified more than once",
    3106                 :             :                            option->value),
    3107                 :             :                     parser_errposition(pstate, option->location));
    3108                 :             : 
    3109                 :          64 :         addNSItemForReturning(pstate, option->value,
    3110         [ +  + ]:          64 :                               option->option == RETURNING_OPTION_OLD ?
    3111                 :             :                               VAR_RETURNING_OLD : VAR_RETURNING_NEW);
    3112                 :             :     }
    3113                 :             : 
    3114                 :             :     /*
    3115                 :             :      * If OLD/NEW alias names weren't explicitly specified, use "old"/"new"
    3116                 :             :      * unless masked by existing relations.
    3117                 :             :      */
    3118   [ +  +  +  + ]:        4670 :     if (qry->returningOldAlias == NULL &&
    3119                 :        2325 :         refnameNamespaceItem(pstate, NULL, "old", -1, NULL) == NULL)
    3120                 :             :     {
    3121                 :        2285 :         qry->returningOldAlias = "old";
    3122                 :        2285 :         addNSItemForReturning(pstate, "old", VAR_RETURNING_OLD);
    3123                 :             :     }
    3124   [ +  +  +  + ]:        4666 :     if (qry->returningNewAlias == NULL &&
    3125                 :        2321 :         refnameNamespaceItem(pstate, NULL, "new", -1, NULL) == NULL)
    3126                 :             :     {
    3127                 :        2281 :         qry->returningNewAlias = "new";
    3128                 :        2281 :         addNSItemForReturning(pstate, "new", VAR_RETURNING_NEW);
    3129                 :             :     }
    3130                 :             : 
    3131                 :             :     /*
    3132                 :             :      * We need to assign resnos starting at one in the RETURNING list. Save
    3133                 :             :      * and restore the main tlist's value of p_next_resno, just in case
    3134                 :             :      * someone looks at it later (probably won't happen).
    3135                 :             :      */
    3136                 :        2345 :     save_next_resno = pstate->p_next_resno;
    3137                 :        2345 :     pstate->p_next_resno = 1;
    3138                 :             : 
    3139                 :             :     /* transform RETURNING expressions identically to a SELECT targetlist */
    3140                 :        2345 :     qry->returningList = transformTargetList(pstate,
    3141                 :             :                                              returningClause->exprs,
    3142                 :             :                                              exprKind);
    3143                 :             : 
    3144                 :             :     /*
    3145                 :             :      * Complain if the nonempty tlist expanded to nothing (which is possible
    3146                 :             :      * if it contains only a star-expansion of a zero-column table).  If we
    3147                 :             :      * allow this, the parsed Query will look like it didn't have RETURNING,
    3148                 :             :      * with results that would probably surprise the user.
    3149                 :             :      */
    3150         [ +  + ]:        2317 :     if (qry->returningList == NIL)
    3151         [ +  - ]:           4 :         ereport(ERROR,
    3152                 :             :                 (errcode(ERRCODE_SYNTAX_ERROR),
    3153                 :             :                  errmsg("RETURNING must have at least one column"),
    3154                 :             :                  parser_errposition(pstate,
    3155                 :             :                                     exprLocation(linitial(returningClause->exprs)))));
    3156                 :             : 
    3157                 :             :     /* mark column origins */
    3158                 :        2313 :     markTargetListOrigins(pstate, qry->returningList);
    3159                 :             : 
    3160                 :             :     /* resolve any still-unresolved output columns as being type text */
    3161         [ +  - ]:        2313 :     if (pstate->p_resolve_unknowns)
    3162                 :        2313 :         resolveTargetListUnknowns(pstate, qry->returningList);
    3163                 :             : 
    3164                 :             :     /* restore state */
    3165                 :        2313 :     pstate->p_namespace = list_truncate(pstate->p_namespace, save_nslen);
    3166                 :        2313 :     pstate->p_next_resno = save_next_resno;
    3167                 :             : }
    3168                 :             : 
    3169                 :             : 
    3170                 :             : /*
    3171                 :             :  * transformPLAssignStmt -
    3172                 :             :  *    transform a PL/pgSQL assignment statement
    3173                 :             :  *
    3174                 :             :  * If there is no opt_indirection, the transformed statement looks like
    3175                 :             :  * "SELECT a_expr ...", except the expression has been cast to the type of
    3176                 :             :  * the target.  With indirection, it's still a SELECT, but the expression will
    3177                 :             :  * incorporate FieldStore and/or assignment SubscriptingRef nodes to compute a
    3178                 :             :  * new value for a container-type variable represented by the target.  The
    3179                 :             :  * expression references the target as the container source.
    3180                 :             :  */
    3181                 :             : static Query *
    3182                 :        3525 : transformPLAssignStmt(ParseState *pstate, PLAssignStmt *stmt)
    3183                 :             : {
    3184                 :             :     Query      *qry;
    3185                 :        3525 :     ColumnRef  *cref = makeNode(ColumnRef);
    3186                 :        3525 :     List       *indirection = stmt->indirection;
    3187                 :        3525 :     int         nnames = stmt->nnames;
    3188                 :             :     Node       *target;
    3189                 :             :     SelectStmtPassthrough passthru;
    3190                 :             :     bool        save_resolve_unknowns;
    3191                 :             : 
    3192                 :             :     /*
    3193                 :             :      * First, construct a ColumnRef for the target variable.  If the target
    3194                 :             :      * has more than one dotted name, we have to pull the extra names out of
    3195                 :             :      * the indirection list.
    3196                 :             :      */
    3197                 :        3525 :     cref->fields = list_make1(makeString(stmt->name));
    3198                 :        3525 :     cref->location = stmt->location;
    3199         [ +  + ]:        3525 :     if (nnames > 1)
    3200                 :             :     {
    3201                 :             :         /* avoid munging the raw parsetree */
    3202                 :         269 :         indirection = list_copy(indirection);
    3203   [ +  +  +  - ]:         545 :         while (--nnames > 0 && indirection != NIL)
    3204                 :             :         {
    3205                 :         276 :             Node       *ind = (Node *) linitial(indirection);
    3206                 :             : 
    3207         [ -  + ]:         276 :             if (!IsA(ind, String))
    3208         [ #  # ]:           0 :                 elog(ERROR, "invalid name count in PLAssignStmt");
    3209                 :         276 :             cref->fields = lappend(cref->fields, ind);
    3210                 :         276 :             indirection = list_delete_first(indirection);
    3211                 :             :         }
    3212                 :             :     }
    3213                 :             : 
    3214                 :             :     /*
    3215                 :             :      * Transform the target reference.  Typically we will get back a Param
    3216                 :             :      * node, but there's no reason to be too picky about its type.  (Note that
    3217                 :             :      * we must do this before calling transformSelectStmt.  It's tempting to
    3218                 :             :      * do it inside transformPLAssignStmtTarget, but we need to do it before
    3219                 :             :      * adding any FROM tables to the pstate's namespace, else we might wrongly
    3220                 :             :      * resolve the target as a table column.)
    3221                 :             :      */
    3222                 :        3525 :     target = transformExpr(pstate, (Node *) cref,
    3223                 :             :                            EXPR_KIND_UPDATE_TARGET);
    3224                 :             : 
    3225                 :             :     /* Set up passthrough data for transformPLAssignStmtTarget */
    3226                 :        3519 :     passthru.stmt = stmt;
    3227                 :        3519 :     passthru.target = target;
    3228                 :        3519 :     passthru.indirection = indirection;
    3229                 :             : 
    3230                 :             :     /*
    3231                 :             :      * To avoid duplicating a lot of code, we use transformSelectStmt to do
    3232                 :             :      * almost all of the work.  However, we need to do additional processing
    3233                 :             :      * on the SELECT's targetlist after it's been transformed, but before
    3234                 :             :      * possible addition of targetlist items for ORDER BY or GROUP BY.
    3235                 :             :      * transformSelectStmt knows it should call transformPLAssignStmtTarget if
    3236                 :             :      * it's passed a passthru argument.
    3237                 :             :      *
    3238                 :             :      * Also, disable resolution of unknown-type tlist items; PL/pgSQL wants to
    3239                 :             :      * deal with that itself.
    3240                 :             :      */
    3241                 :        3519 :     save_resolve_unknowns = pstate->p_resolve_unknowns;
    3242                 :        3519 :     pstate->p_resolve_unknowns = false;
    3243                 :        3519 :     qry = transformSelectStmt(pstate, stmt->val, &passthru);
    3244                 :        3512 :     pstate->p_resolve_unknowns = save_resolve_unknowns;
    3245                 :             : 
    3246                 :        3512 :     return qry;
    3247                 :             : }
    3248                 :             : 
    3249                 :             : /*
    3250                 :             :  * Callback function to adjust a SELECT's tlist to make the output suitable
    3251                 :             :  * for assignment to a PLAssignStmt's target variable.
    3252                 :             :  *
    3253                 :             :  * Note: we actually modify the tle->expr in-place, but the function's API
    3254                 :             :  * is set up to not presume that.
    3255                 :             :  */
    3256                 :             : static List *
    3257                 :        3519 : transformPLAssignStmtTarget(ParseState *pstate, List *tlist,
    3258                 :             :                             SelectStmtPassthrough *passthru)
    3259                 :             : {
    3260                 :        3519 :     PLAssignStmt *stmt = passthru->stmt;
    3261                 :        3519 :     Node       *target = passthru->target;
    3262                 :        3519 :     List       *indirection = passthru->indirection;
    3263                 :             :     Oid         targettype;
    3264                 :             :     int32       targettypmod;
    3265                 :             :     Oid         targetcollation;
    3266                 :             :     TargetEntry *tle;
    3267                 :             :     Oid         type_id;
    3268                 :             : 
    3269                 :        3519 :     targettype = exprType(target);
    3270                 :        3519 :     targettypmod = exprTypmod(target);
    3271                 :        3519 :     targetcollation = exprCollation(target);
    3272                 :             : 
    3273                 :             :     /* we should have exactly one targetlist item */
    3274         [ +  + ]:        3519 :     if (list_length(tlist) != 1)
    3275         [ +  - ]:           2 :         ereport(ERROR,
    3276                 :             :                 (errcode(ERRCODE_SYNTAX_ERROR),
    3277                 :             :                  errmsg_plural("assignment source returned %d column",
    3278                 :             :                                "assignment source returned %d columns",
    3279                 :             :                                list_length(tlist),
    3280                 :             :                                list_length(tlist))));
    3281                 :             : 
    3282                 :        3517 :     tle = linitial_node(TargetEntry, tlist);
    3283                 :             : 
    3284                 :             :     /*
    3285                 :             :      * This next bit is similar to transformAssignedExpr; the key difference
    3286                 :             :      * is we use COERCION_PLPGSQL not COERCION_ASSIGNMENT.
    3287                 :             :      */
    3288                 :        3517 :     type_id = exprType((Node *) tle->expr);
    3289                 :             : 
    3290                 :        3517 :     pstate->p_expr_kind = EXPR_KIND_UPDATE_TARGET;
    3291                 :             : 
    3292         [ +  + ]:        3517 :     if (indirection)
    3293                 :             :     {
    3294                 :          60 :         tle->expr = (Expr *)
    3295                 :          65 :             transformAssignmentIndirection(pstate,
    3296                 :             :                                            target,
    3297                 :          65 :                                            stmt->name,
    3298                 :             :                                            false,
    3299                 :             :                                            targettype,
    3300                 :             :                                            targettypmod,
    3301                 :             :                                            targetcollation,
    3302                 :             :                                            indirection,
    3303                 :             :                                            list_head(indirection),
    3304                 :          65 :                                            (Node *) tle->expr,
    3305                 :             :                                            COERCION_PLPGSQL,
    3306                 :             :                                            exprLocation(target));
    3307                 :             :     }
    3308   [ +  +  +  + ]:        3452 :     else if (targettype != type_id &&
    3309   [ +  +  +  + ]:         938 :              (targettype == RECORDOID || ISCOMPLEX(targettype)) &&
    3310         [ +  + ]:         226 :              (type_id == RECORDOID || ISCOMPLEX(type_id)))
    3311                 :             :     {
    3312                 :             :         /*
    3313                 :             :          * Hack: do not let coerce_to_target_type() deal with inconsistent
    3314                 :             :          * composite types.  Just pass the expression result through as-is,
    3315                 :             :          * and let the PL/pgSQL executor do the conversion its way.  This is
    3316                 :             :          * rather bogus, but it's needed for backwards compatibility.
    3317                 :             :          */
    3318                 :             :     }
    3319                 :             :     else
    3320                 :             :     {
    3321                 :             :         /*
    3322                 :             :          * For normal non-qualified target column, do type checking and
    3323                 :             :          * coercion.
    3324                 :             :          */
    3325                 :        3260 :         Node       *orig_expr = (Node *) tle->expr;
    3326                 :             : 
    3327                 :        3260 :         tle->expr = (Expr *)
    3328                 :        3260 :             coerce_to_target_type(pstate,
    3329                 :             :                                   orig_expr, type_id,
    3330                 :             :                                   targettype, targettypmod,
    3331                 :             :                                   COERCION_PLPGSQL,
    3332                 :             :                                   COERCE_IMPLICIT_CAST,
    3333                 :             :                                   -1);
    3334                 :             :         /* With COERCION_PLPGSQL, this error is probably unreachable */
    3335         [ -  + ]:        3260 :         if (tle->expr == NULL)
    3336         [ #  # ]:           0 :             ereport(ERROR,
    3337                 :             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    3338                 :             :                      errmsg("variable \"%s\" is of type %s"
    3339                 :             :                             " but expression is of type %s",
    3340                 :             :                             stmt->name,
    3341                 :             :                             format_type_be(targettype),
    3342                 :             :                             format_type_be(type_id)),
    3343                 :             :                      errhint("You will need to rewrite or cast the expression."),
    3344                 :             :                      parser_errposition(pstate, exprLocation(orig_expr))));
    3345                 :             :     }
    3346                 :             : 
    3347                 :        3512 :     pstate->p_expr_kind = EXPR_KIND_NONE;
    3348                 :             : 
    3349                 :        3512 :     return list_make1(tle);
    3350                 :             : }
    3351                 :             : 
    3352                 :             : 
    3353                 :             : /*
    3354                 :             :  * transformDeclareCursorStmt -
    3355                 :             :  *  transform a DECLARE CURSOR Statement
    3356                 :             :  *
    3357                 :             :  * DECLARE CURSOR is like other utility statements in that we emit it as a
    3358                 :             :  * CMD_UTILITY Query node; however, we must first transform the contained
    3359                 :             :  * query.  We used to postpone that until execution, but it's really necessary
    3360                 :             :  * to do it during the normal parse analysis phase to ensure that side effects
    3361                 :             :  * of parser hooks happen at the expected time.
    3362                 :             :  */
    3363                 :             : static Query *
    3364                 :        2763 : transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
    3365                 :             : {
    3366                 :             :     Query      *result;
    3367                 :             :     Query      *query;
    3368                 :             : 
    3369         [ +  + ]:        2763 :     if ((stmt->options & CURSOR_OPT_SCROLL) &&
    3370         [ -  + ]:         160 :         (stmt->options & CURSOR_OPT_NO_SCROLL))
    3371         [ #  # ]:           0 :         ereport(ERROR,
    3372                 :             :                 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
    3373                 :             :         /* translator: %s is a SQL keyword */
    3374                 :             :                  errmsg("cannot specify both %s and %s",
    3375                 :             :                         "SCROLL", "NO SCROLL")));
    3376                 :             : 
    3377         [ -  + ]:        2763 :     if ((stmt->options & CURSOR_OPT_ASENSITIVE) &&
    3378         [ #  # ]:           0 :         (stmt->options & CURSOR_OPT_INSENSITIVE))
    3379         [ #  # ]:           0 :         ereport(ERROR,
    3380                 :             :                 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
    3381                 :             :         /* translator: %s is a SQL keyword */
    3382                 :             :                  errmsg("cannot specify both %s and %s",
    3383                 :             :                         "ASENSITIVE", "INSENSITIVE")));
    3384                 :             : 
    3385                 :             :     /* Transform contained query, not allowing SELECT INTO */
    3386                 :        2763 :     query = transformStmt(pstate, stmt->query);
    3387                 :        2750 :     stmt->query = (Node *) query;
    3388                 :             : 
    3389                 :             :     /* Grammar should not have allowed anything but SELECT */
    3390         [ +  - ]:        2750 :     if (!IsA(query, Query) ||
    3391         [ -  + ]:        2750 :         query->commandType != CMD_SELECT)
    3392         [ #  # ]:           0 :         elog(ERROR, "unexpected non-SELECT command in DECLARE CURSOR");
    3393                 :             : 
    3394                 :             :     /*
    3395                 :             :      * We also disallow data-modifying WITH in a cursor.  (This could be
    3396                 :             :      * allowed, but the semantics of when the updates occur might be
    3397                 :             :      * surprising.)
    3398                 :             :      */
    3399         [ -  + ]:        2750 :     if (query->hasModifyingCTE)
    3400         [ #  # ]:           0 :         ereport(ERROR,
    3401                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3402                 :             :                  errmsg("DECLARE CURSOR must not contain data-modifying statements in WITH")));
    3403                 :             : 
    3404                 :             :     /* FOR UPDATE and WITH HOLD are not compatible */
    3405   [ +  +  -  + ]:        2750 :     if (query->rowMarks != NIL && (stmt->options & CURSOR_OPT_HOLD))
    3406         [ #  # ]:           0 :         ereport(ERROR,
    3407                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3408                 :             :         /*------
    3409                 :             :           translator: %s is a SQL row locking clause such as FOR UPDATE */
    3410                 :             :                  errmsg("DECLARE CURSOR WITH HOLD ... %s is not supported",
    3411                 :             :                         LCS_asString(((RowMarkClause *)
    3412                 :             :                                       linitial(query->rowMarks))->strength)),
    3413                 :             :                  errdetail("Holdable cursors must be READ ONLY.")));
    3414                 :             : 
    3415                 :             :     /* FOR UPDATE and SCROLL are not compatible */
    3416   [ +  +  -  + ]:        2750 :     if (query->rowMarks != NIL && (stmt->options & CURSOR_OPT_SCROLL))
    3417         [ #  # ]:           0 :         ereport(ERROR,
    3418                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3419                 :             :         /*------
    3420                 :             :           translator: %s is a SQL row locking clause such as FOR UPDATE */
    3421                 :             :                  errmsg("DECLARE SCROLL CURSOR ... %s is not supported",
    3422                 :             :                         LCS_asString(((RowMarkClause *)
    3423                 :             :                                       linitial(query->rowMarks))->strength)),
    3424                 :             :                  errdetail("Scrollable cursors must be READ ONLY.")));
    3425                 :             : 
    3426                 :             :     /* FOR UPDATE and INSENSITIVE are not compatible */
    3427   [ +  +  -  + ]:        2750 :     if (query->rowMarks != NIL && (stmt->options & CURSOR_OPT_INSENSITIVE))
    3428         [ #  # ]:           0 :         ereport(ERROR,
    3429                 :             :                 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
    3430                 :             :         /*------
    3431                 :             :           translator: %s is a SQL row locking clause such as FOR UPDATE */
    3432                 :             :                  errmsg("DECLARE INSENSITIVE CURSOR ... %s is not valid",
    3433                 :             :                         LCS_asString(((RowMarkClause *)
    3434                 :             :                                       linitial(query->rowMarks))->strength)),
    3435                 :             :                  errdetail("Insensitive cursors must be READ ONLY.")));
    3436                 :             : 
    3437                 :             :     /* represent the command as a utility Query */
    3438                 :        2750 :     result = makeNode(Query);
    3439                 :        2750 :     result->commandType = CMD_UTILITY;
    3440                 :        2750 :     result->utilityStmt = (Node *) stmt;
    3441                 :             : 
    3442                 :        2750 :     return result;
    3443                 :             : }
    3444                 :             : 
    3445                 :             : 
    3446                 :             : /*
    3447                 :             :  * transformExplainStmt -
    3448                 :             :  *  transform an EXPLAIN Statement
    3449                 :             :  *
    3450                 :             :  * EXPLAIN is like other utility statements in that we emit it as a
    3451                 :             :  * CMD_UTILITY Query node; however, we must first transform the contained
    3452                 :             :  * query.  We used to postpone that until execution, but it's really necessary
    3453                 :             :  * to do it during the normal parse analysis phase to ensure that side effects
    3454                 :             :  * of parser hooks happen at the expected time.
    3455                 :             :  */
    3456                 :             : static Query *
    3457                 :       16752 : transformExplainStmt(ParseState *pstate, ExplainStmt *stmt)
    3458                 :             : {
    3459                 :             :     Query      *result;
    3460                 :       16752 :     bool        generic_plan = false;
    3461                 :       16752 :     Oid        *paramTypes = NULL;
    3462                 :       16752 :     int         numParams = 0;
    3463                 :             : 
    3464                 :             :     /*
    3465                 :             :      * If we have no external source of parameter definitions, and the
    3466                 :             :      * GENERIC_PLAN option is specified, then accept variable parameter
    3467                 :             :      * definitions (similarly to PREPARE, for example).
    3468                 :             :      */
    3469         [ +  + ]:       16752 :     if (pstate->p_paramref_hook == NULL)
    3470                 :             :     {
    3471                 :             :         ListCell   *lc;
    3472                 :             : 
    3473   [ +  +  +  +  :       33309 :         foreach(lc, stmt->options)
                   +  + ]
    3474                 :             :         {
    3475                 :       16569 :             DefElem    *opt = (DefElem *) lfirst(lc);
    3476                 :             : 
    3477         [ +  + ]:       16569 :             if (strcmp(opt->defname, "generic_plan") == 0)
    3478                 :          12 :                 generic_plan = defGetBoolean(opt);
    3479                 :             :             /* don't "break", as we want the last value */
    3480                 :             :         }
    3481         [ +  + ]:       16740 :         if (generic_plan)
    3482                 :          12 :             setup_parse_variable_parameters(pstate, &paramTypes, &numParams);
    3483                 :             :     }
    3484                 :             : 
    3485                 :             :     /* transform contained query, allowing SELECT INTO */
    3486                 :       16752 :     stmt->query = (Node *) transformOptionalSelectInto(pstate, stmt->query);
    3487                 :             : 
    3488                 :             :     /* make sure all is well with parameter types */
    3489         [ +  + ]:       16747 :     if (generic_plan)
    3490                 :          12 :         check_variable_parameters(pstate, (Query *) stmt->query);
    3491                 :             : 
    3492                 :             :     /* represent the command as a utility Query */
    3493                 :       16747 :     result = makeNode(Query);
    3494                 :       16747 :     result->commandType = CMD_UTILITY;
    3495                 :       16747 :     result->utilityStmt = (Node *) stmt;
    3496                 :             : 
    3497                 :       16747 :     return result;
    3498                 :             : }
    3499                 :             : 
    3500                 :             : 
    3501                 :             : /*
    3502                 :             :  * transformCreateTableAsStmt -
    3503                 :             :  *  transform a CREATE TABLE AS, SELECT ... INTO, or CREATE MATERIALIZED VIEW
    3504                 :             :  *  Statement
    3505                 :             :  *
    3506                 :             :  * As with DECLARE CURSOR and EXPLAIN, transform the contained statement now.
    3507                 :             :  */
    3508                 :             : static Query *
    3509                 :        1327 : transformCreateTableAsStmt(ParseState *pstate, CreateTableAsStmt *stmt)
    3510                 :             : {
    3511                 :             :     Query      *result;
    3512                 :             :     Query      *query;
    3513                 :             : 
    3514                 :             :     /* transform contained query, not allowing SELECT INTO */
    3515                 :        1327 :     query = transformStmt(pstate, stmt->query);
    3516                 :        1325 :     stmt->query = (Node *) query;
    3517                 :             : 
    3518                 :             :     /* additional work needed for CREATE MATERIALIZED VIEW */
    3519         [ +  + ]:        1325 :     if (stmt->objtype == OBJECT_MATVIEW)
    3520                 :             :     {
    3521                 :             :         ObjectAddress temp_object;
    3522                 :             : 
    3523                 :             :         /*
    3524                 :             :          * Prohibit a data-modifying CTE in the query used to create a
    3525                 :             :          * materialized view. It's not sufficiently clear what the user would
    3526                 :             :          * want to happen if the MV is refreshed or incrementally maintained.
    3527                 :             :          */
    3528         [ -  + ]:         356 :         if (query->hasModifyingCTE)
    3529         [ #  # ]:           0 :             ereport(ERROR,
    3530                 :             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3531                 :             :                      errmsg("materialized views must not use data-modifying statements in WITH")));
    3532                 :             : 
    3533                 :             :         /*
    3534                 :             :          * Check whether any temporary database objects are used in the
    3535                 :             :          * creation query. It would be hard to refresh data or incrementally
    3536                 :             :          * maintain it if a source disappeared.
    3537                 :             :          */
    3538         [ +  + ]:         356 :         if (query_uses_temp_object(query, &temp_object))
    3539         [ +  - ]:           4 :             ereport(ERROR,
    3540                 :             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3541                 :             :                      errmsg("materialized views must not use temporary objects"),
    3542                 :             :                      errdetail("This view depends on temporary %s.",
    3543                 :             :                                getObjectDescription(&temp_object, false))));
    3544                 :             : 
    3545                 :             :         /*
    3546                 :             :          * A materialized view would either need to save parameters for use in
    3547                 :             :          * maintaining/loading the data or prohibit them entirely.  The latter
    3548                 :             :          * seems safer and more sane.
    3549                 :             :          */
    3550         [ -  + ]:         348 :         if (query_contains_extern_params(query))
    3551         [ #  # ]:           0 :             ereport(ERROR,
    3552                 :             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3553                 :             :                      errmsg("materialized views may not be defined using bound parameters")));
    3554                 :             : 
    3555                 :             :         /*
    3556                 :             :          * For now, we disallow unlogged materialized views, because it seems
    3557                 :             :          * like a bad idea for them to just go to empty after a crash. (If we
    3558                 :             :          * could mark them as unpopulated, that would be better, but that
    3559                 :             :          * requires catalog changes which crash recovery can't presently
    3560                 :             :          * handle.)
    3561                 :             :          */
    3562         [ -  + ]:         348 :         if (stmt->into->rel->relpersistence == RELPERSISTENCE_UNLOGGED)
    3563         [ #  # ]:           0 :             ereport(ERROR,
    3564                 :             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3565                 :             :                      errmsg("materialized views cannot be unlogged")));
    3566                 :             : 
    3567                 :             :         /*
    3568                 :             :          * At runtime, we'll need a copy of the parsed-but-not-rewritten Query
    3569                 :             :          * for purposes of creating the view's ON SELECT rule.  We stash that
    3570                 :             :          * in the IntoClause because that's where intorel_startup() can
    3571                 :             :          * conveniently get it from.
    3572                 :             :          */
    3573                 :         348 :         stmt->into->viewQuery = copyObject(query);
    3574                 :             :     }
    3575                 :             : 
    3576                 :             :     /* represent the command as a utility Query */
    3577                 :        1317 :     result = makeNode(Query);
    3578                 :        1317 :     result->commandType = CMD_UTILITY;
    3579                 :        1317 :     result->utilityStmt = (Node *) stmt;
    3580                 :             : 
    3581                 :        1317 :     return result;
    3582                 :             : }
    3583                 :             : 
    3584                 :             : /*
    3585                 :             :  * transform a CallStmt
    3586                 :             :  */
    3587                 :             : static Query *
    3588                 :         315 : transformCallStmt(ParseState *pstate, CallStmt *stmt)
    3589                 :             : {
    3590                 :             :     List       *targs;
    3591                 :             :     ListCell   *lc;
    3592                 :             :     Node       *node;
    3593                 :             :     FuncExpr   *fexpr;
    3594                 :             :     HeapTuple   proctup;
    3595                 :             :     Datum       proargmodes;
    3596                 :             :     bool        isNull;
    3597                 :         315 :     List       *outargs = NIL;
    3598                 :             :     Query      *result;
    3599                 :             : 
    3600                 :             :     /*
    3601                 :             :      * First, do standard parse analysis on the procedure call and its
    3602                 :             :      * arguments, allowing us to identify the called procedure.
    3603                 :             :      */
    3604                 :         315 :     targs = NIL;
    3605   [ +  +  +  +  :         767 :     foreach(lc, stmt->funccall->args)
                   +  + ]
    3606                 :             :     {
    3607                 :         452 :         targs = lappend(targs, transformExpr(pstate,
    3608                 :         452 :                                              (Node *) lfirst(lc),
    3609                 :             :                                              EXPR_KIND_CALL_ARGUMENT));
    3610                 :             :     }
    3611                 :             : 
    3612                 :         315 :     node = ParseFuncOrColumn(pstate,
    3613                 :         315 :                              stmt->funccall->funcname,
    3614                 :             :                              targs,
    3615                 :             :                              pstate->p_last_srf,
    3616                 :             :                              stmt->funccall,
    3617                 :             :                              true,
    3618                 :         315 :                              stmt->funccall->location);
    3619                 :             : 
    3620                 :         294 :     assign_expr_collations(pstate, node);
    3621                 :             : 
    3622                 :         294 :     fexpr = castNode(FuncExpr, node);
    3623                 :             : 
    3624                 :         294 :     proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(fexpr->funcid));
    3625         [ -  + ]:         294 :     if (!HeapTupleIsValid(proctup))
    3626         [ #  # ]:           0 :         elog(ERROR, "cache lookup failed for function %u", fexpr->funcid);
    3627                 :             : 
    3628                 :             :     /*
    3629                 :             :      * Expand the argument list to deal with named-argument notation and
    3630                 :             :      * default arguments.  For ordinary FuncExprs this'd be done during
    3631                 :             :      * planning, but a CallStmt doesn't go through planning, and there seems
    3632                 :             :      * no good reason not to do it here.
    3633                 :             :      */
    3634                 :         294 :     fexpr->args = expand_function_arguments(fexpr->args,
    3635                 :             :                                             true,
    3636                 :             :                                             fexpr->funcresulttype,
    3637                 :             :                                             proctup);
    3638                 :             : 
    3639                 :             :     /* Fetch proargmodes; if it's null, there are no output args */
    3640                 :         294 :     proargmodes = SysCacheGetAttr(PROCOID, proctup,
    3641                 :             :                                   Anum_pg_proc_proargmodes,
    3642                 :             :                                   &isNull);
    3643         [ +  + ]:         294 :     if (!isNull)
    3644                 :             :     {
    3645                 :             :         /*
    3646                 :             :          * Split the list into input arguments in fexpr->args and output
    3647                 :             :          * arguments in stmt->outargs.  INOUT arguments appear in both lists.
    3648                 :             :          */
    3649                 :             :         ArrayType  *arr;
    3650                 :             :         int         numargs;
    3651                 :             :         char       *argmodes;
    3652                 :             :         List       *inargs;
    3653                 :             :         int         i;
    3654                 :             : 
    3655                 :         119 :         arr = DatumGetArrayTypeP(proargmodes);  /* ensure not toasted */
    3656                 :         119 :         numargs = list_length(fexpr->args);
    3657         [ +  - ]:         119 :         if (ARR_NDIM(arr) != 1 ||
    3658         [ +  - ]:         119 :             ARR_DIMS(arr)[0] != numargs ||
    3659         [ +  - ]:         119 :             ARR_HASNULL(arr) ||
    3660         [ -  + ]:         119 :             ARR_ELEMTYPE(arr) != CHAROID)
    3661         [ #  # ]:           0 :             elog(ERROR, "proargmodes is not a 1-D char array of length %d or it contains nulls",
    3662                 :             :                  numargs);
    3663         [ -  + ]:         119 :         argmodes = (char *) ARR_DATA_PTR(arr);
    3664                 :             : 
    3665                 :         119 :         inargs = NIL;
    3666                 :         119 :         i = 0;
    3667   [ +  -  +  +  :         395 :         foreach(lc, fexpr->args)
                   +  + ]
    3668                 :             :         {
    3669                 :         276 :             Node       *n = lfirst(lc);
    3670                 :             : 
    3671   [ +  +  +  - ]:         276 :             switch (argmodes[i])
    3672                 :             :             {
    3673                 :          91 :                 case PROARGMODE_IN:
    3674                 :             :                 case PROARGMODE_VARIADIC:
    3675                 :          91 :                     inargs = lappend(inargs, n);
    3676                 :          91 :                     break;
    3677                 :          72 :                 case PROARGMODE_OUT:
    3678                 :          72 :                     outargs = lappend(outargs, n);
    3679                 :          72 :                     break;
    3680                 :         113 :                 case PROARGMODE_INOUT:
    3681                 :         113 :                     inargs = lappend(inargs, n);
    3682                 :         113 :                     outargs = lappend(outargs, copyObject(n));
    3683                 :         113 :                     break;
    3684                 :           0 :                 default:
    3685                 :             :                     /* note we don't support PROARGMODE_TABLE */
    3686         [ #  # ]:           0 :                     elog(ERROR, "invalid argmode %c for procedure",
    3687                 :             :                          argmodes[i]);
    3688                 :             :                     break;
    3689                 :             :             }
    3690                 :         276 :             i++;
    3691                 :             :         }
    3692                 :         119 :         fexpr->args = inargs;
    3693                 :             :     }
    3694                 :             : 
    3695                 :         294 :     stmt->funcexpr = fexpr;
    3696                 :         294 :     stmt->outargs = outargs;
    3697                 :             : 
    3698                 :         294 :     ReleaseSysCache(proctup);
    3699                 :             : 
    3700                 :             :     /* represent the command as a utility Query */
    3701                 :         294 :     result = makeNode(Query);
    3702                 :         294 :     result->commandType = CMD_UTILITY;
    3703                 :         294 :     result->utilityStmt = (Node *) stmt;
    3704                 :             : 
    3705                 :         294 :     return result;
    3706                 :             : }
    3707                 :             : 
    3708                 :             : /*
    3709                 :             :  * Produce a string representation of a LockClauseStrength value.
    3710                 :             :  * This should only be applied to valid values (not LCS_NONE).
    3711                 :             :  */
    3712                 :             : const char *
    3713                 :          36 : LCS_asString(LockClauseStrength strength)
    3714                 :             : {
    3715   [ -  -  -  +  :          36 :     switch (strength)
                   +  - ]
    3716                 :             :     {
    3717                 :           0 :         case LCS_NONE:
    3718                 :             :             Assert(false);
    3719                 :           0 :             break;
    3720                 :           0 :         case LCS_FORKEYSHARE:
    3721                 :           0 :             return "FOR KEY SHARE";
    3722                 :           0 :         case LCS_FORSHARE:
    3723                 :           0 :             return "FOR SHARE";
    3724                 :           4 :         case LCS_FORNOKEYUPDATE:
    3725                 :           4 :             return "FOR NO KEY UPDATE";
    3726                 :          32 :         case LCS_FORUPDATE:
    3727                 :          32 :             return "FOR UPDATE";
    3728                 :             :     }
    3729                 :           0 :     return "FOR some";            /* shouldn't happen */
    3730                 :             : }
    3731                 :             : 
    3732                 :             : /*
    3733                 :             :  * Check for features that are not supported with FOR [KEY] UPDATE/SHARE.
    3734                 :             :  *
    3735                 :             :  * exported so planner can check again after rewriting, query pullup, etc
    3736                 :             :  */
    3737                 :             : void
    3738                 :       11674 : CheckSelectLocking(Query *qry, LockClauseStrength strength)
    3739                 :             : {
    3740                 :             :     Assert(strength != LCS_NONE);   /* else caller error */
    3741                 :             : 
    3742         [ -  + ]:       11674 :     if (qry->setOperations)
    3743         [ #  # ]:           0 :         ereport(ERROR,
    3744                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3745                 :             :         /*------
    3746                 :             :           translator: %s is a SQL row locking clause such as FOR UPDATE */
    3747                 :             :                  errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
    3748                 :             :                         LCS_asString(strength))));
    3749         [ -  + ]:       11674 :     if (qry->distinctClause != NIL)
    3750         [ #  # ]:           0 :         ereport(ERROR,
    3751                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3752                 :             :         /*------
    3753                 :             :           translator: %s is a SQL row locking clause such as FOR UPDATE */
    3754                 :             :                  errmsg("%s is not allowed with DISTINCT clause",
    3755                 :             :                         LCS_asString(strength))));
    3756   [ +  +  +  + ]:       11674 :     if (qry->groupClause != NIL || qry->groupingSets != NIL)
    3757         [ +  - ]:           8 :         ereport(ERROR,
    3758                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3759                 :             :         /*------
    3760                 :             :           translator: %s is a SQL row locking clause such as FOR UPDATE */
    3761                 :             :                  errmsg("%s is not allowed with GROUP BY clause",
    3762                 :             :                         LCS_asString(strength))));
    3763         [ -  + ]:       11666 :     if (qry->havingQual != NULL)
    3764         [ #  # ]:           0 :         ereport(ERROR,
    3765                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3766                 :             :         /*------
    3767                 :             :           translator: %s is a SQL row locking clause such as FOR UPDATE */
    3768                 :             :                  errmsg("%s is not allowed with HAVING clause",
    3769                 :             :                         LCS_asString(strength))));
    3770         [ +  + ]:       11666 :     if (qry->hasAggs)
    3771         [ +  - ]:           4 :         ereport(ERROR,
    3772                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3773                 :             :         /*------
    3774                 :             :           translator: %s is a SQL row locking clause such as FOR UPDATE */
    3775                 :             :                  errmsg("%s is not allowed with aggregate functions",
    3776                 :             :                         LCS_asString(strength))));
    3777         [ -  + ]:       11662 :     if (qry->hasWindowFuncs)
    3778         [ #  # ]:           0 :         ereport(ERROR,
    3779                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3780                 :             :         /*------
    3781                 :             :           translator: %s is a SQL row locking clause such as FOR UPDATE */
    3782                 :             :                  errmsg("%s is not allowed with window functions",
    3783                 :             :                         LCS_asString(strength))));
    3784         [ -  + ]:       11662 :     if (qry->hasTargetSRFs)
    3785         [ #  # ]:           0 :         ereport(ERROR,
    3786                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3787                 :             :         /*------
    3788                 :             :           translator: %s is a SQL row locking clause such as FOR UPDATE */
    3789                 :             :                  errmsg("%s is not allowed with set-returning functions in the target list",
    3790                 :             :                         LCS_asString(strength))));
    3791                 :       11662 : }
    3792                 :             : 
    3793                 :             : /*
    3794                 :             :  * Transform a FOR [KEY] UPDATE/SHARE clause
    3795                 :             :  *
    3796                 :             :  * This basically involves replacing names by integer relids.
    3797                 :             :  *
    3798                 :             :  * NB: if you need to change this, see also markQueryForLocking()
    3799                 :             :  * in rewriteHandler.c, and isLockedRefname() in parse_relation.c.
    3800                 :             :  */
    3801                 :             : static void
    3802                 :        5065 : transformLockingClause(ParseState *pstate, Query *qry, LockingClause *lc,
    3803                 :             :                        bool pushedDown)
    3804                 :             : {
    3805                 :        5065 :     List       *lockedRels = lc->lockedRels;
    3806                 :             :     ListCell   *l;
    3807                 :             :     ListCell   *rt;
    3808                 :             :     Index       i;
    3809                 :             :     LockingClause *allrels;
    3810                 :             : 
    3811                 :        5065 :     CheckSelectLocking(qry, lc->strength);
    3812                 :             : 
    3813                 :             :     /* make a clause we can pass down to subqueries to select all rels */
    3814                 :        5053 :     allrels = makeNode(LockingClause);
    3815                 :        5053 :     allrels->lockedRels = NIL;   /* indicates all rels */
    3816                 :        5053 :     allrels->strength = lc->strength;
    3817                 :        5053 :     allrels->waitPolicy = lc->waitPolicy;
    3818                 :             : 
    3819         [ +  + ]:        5053 :     if (lockedRels == NIL)
    3820                 :             :     {
    3821                 :             :         /*
    3822                 :             :          * Lock all regular tables used in query and its subqueries.  We
    3823                 :             :          * examine inFromCl to exclude auto-added RTEs, particularly NEW/OLD
    3824                 :             :          * in rules.  This is a bit of an abuse of a mostly-obsolete flag, but
    3825                 :             :          * it's convenient.  We can't rely on the namespace mechanism that has
    3826                 :             :          * largely replaced inFromCl, since for example we need to lock
    3827                 :             :          * base-relation RTEs even if they are masked by upper joins.
    3828                 :             :          */
    3829                 :        3812 :         i = 0;
    3830   [ +  +  +  +  :        7674 :         foreach(rt, qry->rtable)
                   +  + ]
    3831                 :             :         {
    3832                 :        3862 :             RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
    3833                 :             : 
    3834                 :        3862 :             ++i;
    3835         [ +  + ]:        3862 :             if (!rte->inFromCl)
    3836                 :           8 :                 continue;
    3837      [ +  -  + ]:        3854 :             switch (rte->rtekind)
    3838                 :             :             {
    3839                 :        3834 :                 case RTE_RELATION:
    3840                 :             :                     {
    3841                 :             :                         RTEPermissionInfo *perminfo;
    3842                 :             : 
    3843                 :        3834 :                         applyLockingClause(qry, i,
    3844                 :             :                                            lc->strength,
    3845                 :             :                                            lc->waitPolicy,
    3846                 :             :                                            pushedDown);
    3847                 :        3834 :                         perminfo = getRTEPermissionInfo(qry->rteperminfos, rte);
    3848                 :        3834 :                         perminfo->requiredPerms |= ACL_SELECT_FOR_UPDATE;
    3849                 :             :                     }
    3850                 :        3834 :                     break;
    3851                 :           0 :                 case RTE_SUBQUERY:
    3852                 :           0 :                     applyLockingClause(qry, i, lc->strength, lc->waitPolicy,
    3853                 :             :                                        pushedDown);
    3854                 :             : 
    3855                 :             :                     /*
    3856                 :             :                      * FOR UPDATE/SHARE of subquery is propagated to all of
    3857                 :             :                      * subquery's rels, too.  We could do this later (based on
    3858                 :             :                      * the marking of the subquery RTE) but it is convenient
    3859                 :             :                      * to have local knowledge in each query level about which
    3860                 :             :                      * rels need to be opened with RowShareLock.
    3861                 :             :                      */
    3862                 :           0 :                     transformLockingClause(pstate, rte->subquery,
    3863                 :             :                                            allrels, true);
    3864                 :           0 :                     break;
    3865                 :          20 :                 default:
    3866                 :             :                     /* ignore all other RTE kinds */
    3867                 :          20 :                     break;
    3868                 :             :             }
    3869                 :             :         }
    3870                 :             :     }
    3871                 :             :     else
    3872                 :             :     {
    3873                 :             :         /*
    3874                 :             :          * Lock just the named tables.  As above, we allow locking any base
    3875                 :             :          * relation regardless of alias-visibility rules, so we need to
    3876                 :             :          * examine inFromCl to exclude OLD/NEW.
    3877                 :             :          */
    3878   [ +  -  +  +  :        2468 :         foreach(l, lockedRels)
                   +  + ]
    3879                 :             :         {
    3880                 :        1247 :             RangeVar   *thisrel = (RangeVar *) lfirst(l);
    3881                 :             : 
    3882                 :             :             /* For simplicity we insist on unqualified alias names here */
    3883   [ +  -  -  + ]:        1247 :             if (thisrel->catalogname || thisrel->schemaname)
    3884         [ #  # ]:           0 :                 ereport(ERROR,
    3885                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    3886                 :             :                 /*------
    3887                 :             :                   translator: %s is a SQL row locking clause such as FOR UPDATE */
    3888                 :             :                          errmsg("%s must specify unqualified relation names",
    3889                 :             :                                 LCS_asString(lc->strength)),
    3890                 :             :                          parser_errposition(pstate, thisrel->location)));
    3891                 :             : 
    3892                 :        1247 :             i = 0;
    3893   [ +  -  +  +  :        1441 :             foreach(rt, qry->rtable)
                   +  + ]
    3894                 :             :             {
    3895                 :        1433 :                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
    3896                 :        1433 :                 char       *rtename = rte->eref->aliasname;
    3897                 :             : 
    3898                 :        1433 :                 ++i;
    3899         [ +  + ]:        1433 :                 if (!rte->inFromCl)
    3900                 :          16 :                     continue;
    3901                 :             : 
    3902                 :             :                 /*
    3903                 :             :                  * A join RTE without an alias is not visible as a relation
    3904                 :             :                  * name and needs to be skipped (otherwise it might hide a
    3905                 :             :                  * base relation with the same name), except if it has a USING
    3906                 :             :                  * alias, which *is* visible.
    3907                 :             :                  *
    3908                 :             :                  * Subquery and values RTEs without aliases are never visible
    3909                 :             :                  * as relation names and must always be skipped.
    3910                 :             :                  */
    3911         [ +  + ]:        1417 :                 if (rte->alias == NULL)
    3912                 :             :                 {
    3913         [ +  + ]:         109 :                     if (rte->rtekind == RTE_JOIN)
    3914                 :             :                     {
    3915         [ +  + ]:          40 :                         if (rte->join_using_alias == NULL)
    3916                 :          32 :                             continue;
    3917                 :           8 :                         rtename = rte->join_using_alias->aliasname;
    3918                 :             :                     }
    3919         [ +  + ]:          69 :                     else if (rte->rtekind == RTE_SUBQUERY ||
    3920         [ -  + ]:          65 :                              rte->rtekind == RTE_VALUES)
    3921                 :           4 :                         continue;
    3922                 :             :                 }
    3923                 :             : 
    3924         [ +  + ]:        1381 :                 if (strcmp(rtename, thisrel->relname) == 0)
    3925                 :             :                 {
    3926   [ +  +  +  -  :        1239 :                     switch (rte->rtekind)
          -  -  -  -  +  
                      - ]
    3927                 :             :                     {
    3928                 :        1221 :                         case RTE_RELATION:
    3929                 :             :                             {
    3930                 :             :                                 RTEPermissionInfo *perminfo;
    3931                 :             : 
    3932                 :        1221 :                                 applyLockingClause(qry, i,
    3933                 :             :                                                    lc->strength,
    3934                 :             :                                                    lc->waitPolicy,
    3935                 :             :                                                    pushedDown);
    3936                 :        1221 :                                 perminfo = getRTEPermissionInfo(qry->rteperminfos, rte);
    3937                 :        1221 :                                 perminfo->requiredPerms |= ACL_SELECT_FOR_UPDATE;
    3938                 :             :                             }
    3939                 :        1221 :                             break;
    3940                 :           6 :                         case RTE_SUBQUERY:
    3941                 :           6 :                             applyLockingClause(qry, i, lc->strength,
    3942                 :             :                                                lc->waitPolicy, pushedDown);
    3943                 :             :                             /* see comment above */
    3944                 :           6 :                             transformLockingClause(pstate, rte->subquery,
    3945                 :             :                                                    allrels, true);
    3946                 :           6 :                             break;
    3947                 :           8 :                         case RTE_JOIN:
    3948         [ +  - ]:           8 :                             ereport(ERROR,
    3949                 :             :                                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3950                 :             :                             /*------
    3951                 :             :                               translator: %s is a SQL row locking clause such as FOR UPDATE */
    3952                 :             :                                      errmsg("%s cannot be applied to a join",
    3953                 :             :                                             LCS_asString(lc->strength)),
    3954                 :             :                                      parser_errposition(pstate, thisrel->location)));
    3955                 :             :                             break;
    3956                 :           0 :                         case RTE_FUNCTION:
    3957         [ #  # ]:           0 :                             ereport(ERROR,
    3958                 :             :                                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3959                 :             :                             /*------
    3960                 :             :                               translator: %s is a SQL row locking clause such as FOR UPDATE */
    3961                 :             :                                      errmsg("%s cannot be applied to a function",
    3962                 :             :                                             LCS_asString(lc->strength)),
    3963                 :             :                                      parser_errposition(pstate, thisrel->location)));
    3964                 :             :                             break;
    3965                 :           0 :                         case RTE_TABLEFUNC:
    3966         [ #  # ]:           0 :                             ereport(ERROR,
    3967                 :             :                                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3968                 :             :                             /*------
    3969                 :             :                               translator: %s is a SQL row locking clause such as FOR UPDATE */
    3970                 :             :                                      errmsg("%s cannot be applied to a table function",
    3971                 :             :                                             LCS_asString(lc->strength)),
    3972                 :             :                                      parser_errposition(pstate, thisrel->location)));
    3973                 :             :                             break;
    3974                 :           0 :                         case RTE_VALUES:
    3975         [ #  # ]:           0 :                             ereport(ERROR,
    3976                 :             :                                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3977                 :             :                             /*------
    3978                 :             :                               translator: %s is a SQL row locking clause such as FOR UPDATE */
    3979                 :             :                                      errmsg("%s cannot be applied to VALUES",
    3980                 :             :                                             LCS_asString(lc->strength)),
    3981                 :             :                                      parser_errposition(pstate, thisrel->location)));
    3982                 :             :                             break;
    3983                 :           0 :                         case RTE_CTE:
    3984         [ #  # ]:           0 :                             ereport(ERROR,
    3985                 :             :                                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3986                 :             :                             /*------
    3987                 :             :                               translator: %s is a SQL row locking clause such as FOR UPDATE */
    3988                 :             :                                      errmsg("%s cannot be applied to a WITH query",
    3989                 :             :                                             LCS_asString(lc->strength)),
    3990                 :             :                                      parser_errposition(pstate, thisrel->location)));
    3991                 :             :                             break;
    3992                 :           0 :                         case RTE_NAMEDTUPLESTORE:
    3993         [ #  # ]:           0 :                             ereport(ERROR,
    3994                 :             :                                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3995                 :             :                             /*------
    3996                 :             :                               translator: %s is a SQL row locking clause such as FOR UPDATE */
    3997                 :             :                                      errmsg("%s cannot be applied to a named tuplestore",
    3998                 :             :                                             LCS_asString(lc->strength)),
    3999                 :             :                                      parser_errposition(pstate, thisrel->location)));
    4000                 :             :                             break;
    4001                 :           4 :                         case RTE_GRAPH_TABLE:
    4002         [ +  - ]:           4 :                             ereport(ERROR,
    4003                 :             :                                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    4004                 :             :                             /*------
    4005                 :             :                               translator: %s is a SQL row locking clause such as FOR UPDATE */
    4006                 :             :                                      errmsg("%s cannot be applied to GRAPH_TABLE",
    4007                 :             :                                             LCS_asString(lc->strength)),
    4008                 :             :                                      parser_errposition(pstate, thisrel->location)));
    4009                 :             :                             break;
    4010                 :             : 
    4011                 :             :                             /* Shouldn't be possible to see RTE_RESULT here */
    4012                 :             : 
    4013                 :           0 :                         default:
    4014         [ #  # ]:           0 :                             elog(ERROR, "unrecognized RTE type: %d",
    4015                 :             :                                  (int) rte->rtekind);
    4016                 :             :                             break;
    4017                 :             :                     }
    4018                 :        1227 :                     break;      /* out of foreach loop */
    4019                 :             :                 }
    4020                 :             :             }
    4021         [ +  + ]:        1235 :             if (rt == NULL)
    4022         [ +  - ]:           8 :                 ereport(ERROR,
    4023                 :             :                         (errcode(ERRCODE_UNDEFINED_TABLE),
    4024                 :             :                 /*------
    4025                 :             :                   translator: %s is a SQL row locking clause such as FOR UPDATE */
    4026                 :             :                          errmsg("relation \"%s\" in %s clause not found in FROM clause",
    4027                 :             :                                 thisrel->relname,
    4028                 :             :                                 LCS_asString(lc->strength)),
    4029                 :             :                          parser_errposition(pstate, thisrel->location)));
    4030                 :             :         }
    4031                 :             :     }
    4032                 :        5033 : }
    4033                 :             : 
    4034                 :             : /*
    4035                 :             :  * Record locking info for a single rangetable item
    4036                 :             :  */
    4037                 :             : void
    4038                 :        5125 : applyLockingClause(Query *qry, Index rtindex,
    4039                 :             :                    LockClauseStrength strength, LockWaitPolicy waitPolicy,
    4040                 :             :                    bool pushedDown)
    4041                 :             : {
    4042                 :             :     RowMarkClause *rc;
    4043                 :             : 
    4044                 :             :     Assert(strength != LCS_NONE);   /* else caller error */
    4045                 :             : 
    4046                 :             :     /* If it's an explicit clause, make sure hasForUpdate gets set */
    4047         [ +  + ]:        5125 :     if (!pushedDown)
    4048                 :        5059 :         qry->hasForUpdate = true;
    4049                 :             : 
    4050                 :             :     /* Check for pre-existing entry for same rtindex */
    4051         [ -  + ]:        5125 :     if ((rc = get_parse_rowmark(qry, rtindex)) != NULL)
    4052                 :             :     {
    4053                 :             :         /*
    4054                 :             :          * If the same RTE is specified with more than one locking strength,
    4055                 :             :          * use the strongest.  (Reasonable, since you can't take both a shared
    4056                 :             :          * and exclusive lock at the same time; it'll end up being exclusive
    4057                 :             :          * anyway.)
    4058                 :             :          *
    4059                 :             :          * Similarly, if the same RTE is specified with more than one lock
    4060                 :             :          * wait policy, consider that NOWAIT wins over SKIP LOCKED, which in
    4061                 :             :          * turn wins over waiting for the lock (the default).  This is a bit
    4062                 :             :          * more debatable but raising an error doesn't seem helpful. (Consider
    4063                 :             :          * for instance SELECT FOR UPDATE NOWAIT from a view that internally
    4064                 :             :          * contains a plain FOR UPDATE spec.)  Having NOWAIT win over SKIP
    4065                 :             :          * LOCKED is reasonable since the former throws an error in case of
    4066                 :             :          * coming across a locked tuple, which may be undesirable in some
    4067                 :             :          * cases but it seems better than silently returning inconsistent
    4068                 :             :          * results.
    4069                 :             :          *
    4070                 :             :          * And of course pushedDown becomes false if any clause is explicit.
    4071                 :             :          */
    4072                 :           0 :         rc->strength = Max(rc->strength, strength);
    4073                 :           0 :         rc->waitPolicy = Max(rc->waitPolicy, waitPolicy);
    4074                 :           0 :         rc->pushedDown &= pushedDown;
    4075                 :           0 :         return;
    4076                 :             :     }
    4077                 :             : 
    4078                 :             :     /* Make a new RowMarkClause */
    4079                 :        5125 :     rc = makeNode(RowMarkClause);
    4080                 :        5125 :     rc->rti = rtindex;
    4081                 :        5125 :     rc->strength = strength;
    4082                 :        5125 :     rc->waitPolicy = waitPolicy;
    4083                 :        5125 :     rc->pushedDown = pushedDown;
    4084                 :        5125 :     qry->rowMarks = lappend(qry->rowMarks, rc);
    4085                 :             : }
    4086                 :             : 
    4087                 :             : #ifdef DEBUG_NODE_TESTS_ENABLED
    4088                 :             : /*
    4089                 :             :  * Coverage testing for raw_expression_tree_walker().
    4090                 :             :  *
    4091                 :             :  * When enabled, we run raw_expression_tree_walker() over every DML statement
    4092                 :             :  * submitted to parse analysis.  Without this provision, that function is only
    4093                 :             :  * applied in limited cases involving CTEs, and we don't really want to have
    4094                 :             :  * to test everything inside as well as outside a CTE.
    4095                 :             :  */
    4096                 :             : static bool
    4097                 :    17389559 : test_raw_expression_coverage(Node *node, void *context)
    4098                 :             : {
    4099         [ +  + ]:    17389559 :     if (node == NULL)
    4100                 :     9368040 :         return false;
    4101                 :     8021519 :     return raw_expression_tree_walker(node,
    4102                 :             :                                       test_raw_expression_coverage,
    4103                 :             :                                       context);
    4104                 :             : }
    4105                 :             : #endif                          /* DEBUG_NODE_TESTS_ENABLED */
        

Generated by: LCOV version 2.0-1