Coverage Report

Created: 2026-11-09 07:20

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