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