LCOV - code coverage report
Current view: top level - src/backend/parser - analyze.c (source / functions) Coverage Total Hit
Test: Code coverage Lines: 91.5 % 1491 1364
Test Date: 2026-01-26 10:56:24 Functions: 94.7 % 38 36
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 61.4 % 980 602

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

Generated by: LCOV version 2.3.2-1