LCOV - code coverage report
Current view: top level - src/backend/parser - analyze.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 1074 1181 90.9 %
Date: 2025-04-24 12:15:10 Functions: 37 38 97.4 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.14