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 {
1165 SubscriptingRef *sbsref = (SubscriptingRef *) subexpr;
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
2146 /*
2147 * Transform SelectStmt into a Query.
2148 *
2149 * This works the same as SELECT transformation normally would, except
2150 * that we prevent resolving unknown-type outputs as TEXT. This does
2151 * not change the subquery's semantics since if the column type
2152 * matters semantically, it would have been resolved to something else
2153 * anyway. Doing this lets us resolve such outputs using
2154 * select_common_type(), below.
2155 *
2156 * Note: previously transformed sub-queries don't affect the parsing
2157 * of this sub-query, because they are not in the toplevel pstate's
2158 * namespace list.
2159 */
2160 selectQuery = parse_sub_analyze((Node *) stmt, pstate,
2161 NULL, false, false);
2162
2163 /*
2164 * Check for bogus references to Vars on the current query level (but
2165 * upper-level references are okay). Normally this can't happen
2166 * because the namespace will be empty, but it could happen if we are
2167 * inside a rule.
2168 */
2169 if (pstate->p_namespace)
2170 {
2172 ereport(ERROR,
2174 errmsg("UNION/INTERSECT/EXCEPT member statement cannot refer to other relations of same query level"),
2175 parser_errposition(pstate,
2177 }
2178
2179 /*
2180 * Extract a list of the non-junk TLEs for upper-level processing.
2181 */
2182 if (targetlist)
2183 {
2184 ListCell *tl;
2185
2186 *targetlist = NIL;
2187 foreach(tl, selectQuery->targetList)
2188 {
2190
2191 if (!tle->resjunk)
2192 *targetlist = lappend(*targetlist, tle);
2193 }
2194 }
2195
2196 /*
2197 * Make the leaf query be a subquery in the top-level rangetable.
2198 */
2201 NULL,
2202 false,
2203 false);
2204
2205 /*
2206 * Return a RangeTblRef to replace the SelectStmt in the set-op tree.
2207 */
2209 rtr->rtindex = nsitem->p_rtindex;
2210 return (Node *) rtr;
2211 }
2212 else
2213 {
2214 /* Process an internal node (set operation node) */
2218 const char *context;
2219 bool recursive = (pstate->p_parent_cte &&
2220 pstate->p_parent_cte->cterecursive);
2221
2222 context = (stmt->op == SETOP_UNION ? "UNION" :
2223 (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
2224 "EXCEPT"));
2225
2226 op->op = stmt->op;
2227 op->all = stmt->all;
2228
2229 /*
2230 * Recursively transform the left child node.
2231 */
2232 op->larg = transformSetOperationTree(pstate, stmt->larg,
2233 false,
2234 &ltargetlist);
2235
2236 /*
2237 * If we are processing a recursive union query, now is the time to
2238 * examine the non-recursive term's output columns and mark the
2239 * containing CTE as having those result columns. We should do this
2240 * only at the topmost setop of the CTE, of course.
2241 */
2242 if (isTopLevel && recursive)
2244
2245 /*
2246 * Recursively transform the right child node.
2247 */
2248 op->rarg = transformSetOperationTree(pstate, stmt->rarg,
2249 false,
2250 &rtargetlist);
2251
2252 constructSetOpTargetlist(pstate, op, ltargetlist, rtargetlist, targetlist,
2253 context, recursive);
2254
2255 return (Node *) op;
2256 }
2257}
2258
2259/*
2260 * constructSetOpTargetlist
2261 * Compute the types, typmods and collations of the columns in the target
2262 * list of the given set operation.
2263 *
2264 * For every pair of columns in the targetlists of the children, compute the
2265 * common type, typmod, and collation representing the output (UNION) column.
2266 * If targetlist is not NULL, also build the dummy output targetlist
2267 * containing non-resjunk output columns. The values are stored into the
2268 * given SetOperationStmt node. context is a string for error messages
2269 * ("UNION" etc.). recursive is true if it is a recursive union.
2270 */
2271void
2273 const List *ltargetlist, const List *rtargetlist,
2274 List **targetlist, const char *context, bool recursive)
2275{
2276 ListCell *ltl;
2277 ListCell *rtl;
2278
2279 /*
2280 * Verify that the two children have the same number of non-junk columns,
2281 * and determine the types of the merged output columns.
2282 */
2284 ereport(ERROR,
2286 errmsg("each %s query must have the same number of columns",
2287 context),
2288 parser_errposition(pstate,
2289 exprLocation((const Node *) rtargetlist))));
2290
2291 if (targetlist)
2292 *targetlist = NIL;
2293 op->colTypes = NIL;
2294 op->colTypmods = NIL;
2295 op->colCollations = NIL;
2296 op->groupClauses = NIL;
2297
2299 {
2302 Node *lcolnode = (Node *) ltle->expr;
2303 Node *rcolnode = (Node *) rtle->expr;
2306 Node *bestexpr;
2307 int bestlocation;
2311
2312 /* select common type, same as CASE et al */
2315 context,
2316 &bestexpr);
2318
2319 /*
2320 * Verify the coercions are actually possible. If not, we'd fail
2321 * later anyway, but we want to fail now while we have sufficient
2322 * context to produce an error cursor position.
2323 *
2324 * For all non-UNKNOWN-type cases, we verify coercibility but we don't
2325 * modify the child's expression, for fear of changing the child
2326 * query's semantics.
2327 *
2328 * If a child expression is an UNKNOWN-type Const or Param, we want to
2329 * replace it with the coerced expression. This can only happen when
2330 * the child is a leaf set-op node. It's safe to replace the
2331 * expression because if the child query's semantics depended on the
2332 * type of this output column, it'd have already coerced the UNKNOWN
2333 * to something else. We want to do this because (a) we want to
2334 * verify that a Const is valid for the target type, or resolve the
2335 * actual type of an UNKNOWN Param, and (b) we want to avoid
2336 * unnecessary discrepancies between the output type of the child
2337 * query and the resolved target type. Such a discrepancy would
2338 * disable optimization in the planner.
2339 *
2340 * If it's some other UNKNOWN-type node, eg a Var, we do nothing
2341 * (knowing that coerce_to_common_type would fail). The planner is
2342 * sometimes able to fold an UNKNOWN Var to a constant before it has
2343 * to coerce the type, so failing now would just break cases that
2344 * might work.
2345 */
2346 if (lcoltype != UNKNOWNOID)
2348 rescoltype, context);
2349 else if (IsA(lcolnode, Const) ||
2350 IsA(lcolnode, Param))
2351 {
2353 rescoltype, context);
2354 ltle->expr = (Expr *) lcolnode;
2355 }
2356
2357 if (rcoltype != UNKNOWNOID)
2359 rescoltype, context);
2360 else if (IsA(rcolnode, Const) ||
2361 IsA(rcolnode, Param))
2362 {
2364 rescoltype, context);
2365 rtle->expr = (Expr *) rcolnode;
2366 }
2367
2370 rescoltype);
2371
2372 /*
2373 * Select common collation. A common collation is required for all
2374 * set operators except UNION ALL; see SQL:2008 7.13 <query
2375 * expression> Syntax Rule 15c. (If we fail to identify a common
2376 * collation for a UNION ALL column, the colCollations element will be
2377 * set to InvalidOid, which may result in a runtime error if something
2378 * at a higher query level wants to use the column's collation.)
2379 */
2382 (op->op == SETOP_UNION && op->all));
2383
2384 /* emit results */
2385 op->colTypes = lappend_oid(op->colTypes, rescoltype);
2386 op->colTypmods = lappend_int(op->colTypmods, rescoltypmod);
2387 op->colCollations = lappend_oid(op->colCollations, rescolcoll);
2388
2389 /*
2390 * For all cases except UNION ALL, identify the grouping operators
2391 * (and, if available, sorting operators) that will be used to
2392 * eliminate duplicates.
2393 */
2394 if (op->op != SETOP_UNION || !op->all)
2395 {
2397
2399 bestlocation);
2400
2401 /* If it's a recursive union, we need to require hashing support. */
2402 op->groupClauses = lappend(op->groupClauses,
2404
2406 }
2407
2408 /*
2409 * Construct a dummy tlist entry to return. We use a SetToDefault
2410 * node for the expression, since it carries exactly the fields
2411 * needed, but any other expression node type would do as well.
2412 */
2413 if (targetlist)
2414 {
2417
2418 rescolnode->typeId = rescoltype;
2419 rescolnode->typeMod = rescoltypmod;
2420 rescolnode->collation = rescolcoll;
2421 rescolnode->location = bestlocation;
2423 0, /* no need to set resno */
2424 NULL,
2425 false);
2426 *targetlist = lappend(*targetlist, restle);
2427 }
2428 }
2429}
2430
2431/*
2432 * Process the outputs of the non-recursive term of a recursive union
2433 * to set up the parent CTE's columns
2434 */
2435static void
2437{
2438 Node *node;
2439 int leftmostRTI;
2441 List *targetList;
2443 ListCell *nrtl;
2444 int next_resno;
2445
2446 /*
2447 * Find leftmost leaf SELECT
2448 */
2449 node = larg;
2450 while (node && IsA(node, SetOperationStmt))
2451 node = ((SetOperationStmt *) node)->larg;
2452 Assert(node && IsA(node, RangeTblRef));
2453 leftmostRTI = ((RangeTblRef *) node)->rtindex;
2454 leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
2456
2457 /*
2458 * Generate dummy targetlist using column names of leftmost select and
2459 * dummy result expressions of the non-recursive term.
2460 */
2461 targetList = NIL;
2462 next_resno = 1;
2463
2465 {
2468 char *colName;
2470
2471 Assert(!lefttle->resjunk);
2472 colName = pstrdup(lefttle->resname);
2473 tle = makeTargetEntry(nrtle->expr,
2474 next_resno++,
2475 colName,
2476 false);
2477 targetList = lappend(targetList, tle);
2478 }
2479
2480 /* Now build CTE's output column info using dummy targetlist */
2481 analyzeCTETargetList(pstate, pstate->p_parent_cte, targetList);
2482}
2483
2484
2485/*
2486 * transformReturnStmt -
2487 * transforms a return statement
2488 */
2489static Query *
2491{
2492 Query *qry = makeNode(Query);
2493
2494 qry->commandType = CMD_SELECT;
2495 qry->isReturn = true;
2496
2498 1, NULL, false));
2499
2500 if (pstate->p_resolve_unknowns)
2502 qry->rtable = pstate->p_rtable;
2503 qry->rteperminfos = pstate->p_rteperminfos;
2504 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
2505 qry->hasSubLinks = pstate->p_hasSubLinks;
2506 qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
2507 qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
2508 qry->hasAggs = pstate->p_hasAggs;
2509
2510 assign_query_collations(pstate, qry);
2511
2512 return qry;
2513}
2514
2515
2516/*
2517 * transformUpdateStmt -
2518 * transforms an update statement
2519 */
2520static Query *
2522{
2523 Query *qry = makeNode(Query);
2525 Node *qual;
2526
2527 qry->commandType = CMD_UPDATE;
2528
2529 /* process the WITH clause independently of all else */
2530 if (stmt->withClause)
2531 {
2532 qry->hasRecursive = stmt->withClause->recursive;
2533 qry->cteList = transformWithClause(pstate, stmt->withClause);
2534 qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
2535 }
2536
2537 qry->resultRelation = setTargetTable(pstate, stmt->relation,
2538 stmt->relation->inh,
2539 true,
2540 ACL_UPDATE);
2541 nsitem = pstate->p_target_nsitem;
2542
2543 /* subqueries in FROM cannot access the result relation */
2544 nsitem->p_lateral_only = true;
2545 nsitem->p_lateral_ok = false;
2546
2547 /*
2548 * the FROM clause is non-standard SQL syntax. We used to be able to do
2549 * this with REPLACE in POSTQUEL so we keep the feature.
2550 */
2551 transformFromClause(pstate, stmt->fromClause);
2552
2553 /* remaining clauses can reference the result relation normally */
2554 nsitem->p_lateral_only = false;
2555 nsitem->p_lateral_ok = true;
2556
2557 qual = transformWhereClause(pstate, stmt->whereClause,
2558 EXPR_KIND_WHERE, "WHERE");
2559
2560 transformReturningClause(pstate, qry, stmt->returningClause,
2562
2563 /*
2564 * Now we are done with SELECT-like processing, and can get on with
2565 * transforming the target list to match the UPDATE target columns.
2566 */
2567 qry->targetList = transformUpdateTargetList(pstate, stmt->targetList);
2568
2569 qry->rtable = pstate->p_rtable;
2570 qry->rteperminfos = pstate->p_rteperminfos;
2571 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
2572
2573 qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
2574 qry->hasSubLinks = pstate->p_hasSubLinks;
2575
2576 assign_query_collations(pstate, qry);
2577
2578 return qry;
2579}
2580
2581/*
2582 * transformUpdateTargetList -
2583 * handle SET clause in UPDATE/MERGE/INSERT ... ON CONFLICT UPDATE
2584 */
2585List *
2587{
2588 List *tlist = NIL;
2591 ListCell *tl;
2592
2593 tlist = transformTargetList(pstate, origTlist,
2595
2596 /* Prepare to assign non-conflicting resnos to resjunk attributes */
2599
2600 /* Prepare non-junk columns for assignment to target table */
2603
2604 foreach(tl, tlist)
2605 {
2608 int attrno;
2609
2610 if (tle->resjunk)
2611 {
2612 /*
2613 * Resjunk nodes need no additional processing, but be sure they
2614 * have resnos that do not match any target columns; else rewriter
2615 * or planner might get confused. They don't need a resname
2616 * either.
2617 */
2618 tle->resno = (AttrNumber) pstate->p_next_resno++;
2619 tle->resname = NULL;
2620 continue;
2621 }
2622 if (orig_tl == NULL)
2623 elog(ERROR, "UPDATE target count mismatch --- internal error");
2625
2627 origTarget->name, true);
2629 ereport(ERROR,
2631 errmsg("column \"%s\" of relation \"%s\" does not exist",
2632 origTarget->name,
2634 (origTarget->indirection != NIL &&
2635 strcmp(origTarget->name, pstate->p_target_nsitem->p_names->aliasname) == 0) ?
2636 errhint("SET target columns cannot be qualified with the relation name.") : 0,
2637 parser_errposition(pstate, origTarget->location)));
2638
2639 updateTargetListEntry(pstate, tle, origTarget->name,
2640 attrno,
2641 origTarget->indirection,
2642 origTarget->location);
2643
2644 /* Mark the target column as requiring update permissions */
2645 target_perminfo->updatedCols = bms_add_member(target_perminfo->updatedCols,
2647
2649 }
2650 if (orig_tl != NULL)
2651 elog(ERROR, "UPDATE target count mismatch --- internal error");
2652
2653 return tlist;
2654}
2655
2656/*
2657 * addNSItemForReturning -
2658 * add a ParseNamespaceItem for the OLD or NEW alias in RETURNING.
2659 */
2660static void
2661addNSItemForReturning(ParseState *pstate, const char *aliasname,
2662 VarReturningType returning_type)
2663{
2664 List *colnames;
2665 int numattrs;
2668
2669 /* copy per-column data from the target relation */
2670 colnames = pstate->p_target_nsitem->p_rte->eref->colnames;
2671 numattrs = list_length(colnames);
2672
2674
2676 numattrs * sizeof(ParseNamespaceColumn));
2677
2678 /* mark all columns as returning OLD/NEW */
2679 for (int i = 0; i < numattrs; i++)
2680 nscolumns[i].p_varreturningtype = returning_type;
2681
2682 /* build the nsitem, copying most fields from the target relation */
2684 nsitem->p_names = makeAlias(aliasname, colnames);
2685 nsitem->p_rte = pstate->p_target_nsitem->p_rte;
2686 nsitem->p_rtindex = pstate->p_target_nsitem->p_rtindex;
2687 nsitem->p_perminfo = pstate->p_target_nsitem->p_perminfo;
2688 nsitem->p_nscolumns = nscolumns;
2689 nsitem->p_returning_type = returning_type;
2690
2691 /* add it to the query namespace as a table-only item */
2692 addNSItemToQuery(pstate, nsitem, false, true, false);
2693}
2694
2695/*
2696 * transformReturningClause -
2697 * handle a RETURNING clause in INSERT/UPDATE/DELETE/MERGE
2698 */
2699void
2701 ReturningClause *returningClause,
2703{
2704 int save_nslen = list_length(pstate->p_namespace);
2705 int save_next_resno;
2706
2707 if (returningClause == NULL)
2708 return; /* nothing to do */
2709
2710 /*
2711 * Scan RETURNING WITH(...) options for OLD/NEW alias names. Complain if
2712 * there is any conflict with existing relations.
2713 */
2714 foreach_node(ReturningOption, option, returningClause->options)
2715 {
2716 switch (option->option)
2717 {
2719 if (qry->returningOldAlias != NULL)
2720 ereport(ERROR,
2722 /* translator: %s is OLD or NEW */
2723 errmsg("%s cannot be specified multiple times", "OLD"),
2724 parser_errposition(pstate, option->location));
2725 qry->returningOldAlias = option->value;
2726 break;
2727
2729 if (qry->returningNewAlias != NULL)
2730 ereport(ERROR,
2732 /* translator: %s is OLD or NEW */
2733 errmsg("%s cannot be specified multiple times", "NEW"),
2734 parser_errposition(pstate, option->location));
2735 qry->returningNewAlias = option->value;
2736 break;
2737
2738 default:
2739 elog(ERROR, "unrecognized returning option: %d", option->option);
2740 }
2741
2742 if (refnameNamespaceItem(pstate, NULL, option->value, -1, NULL) != NULL)
2743 ereport(ERROR,
2745 errmsg("table name \"%s\" specified more than once",
2746 option->value),
2747 parser_errposition(pstate, option->location));
2748
2749 addNSItemForReturning(pstate, option->value,
2750 option->option == RETURNING_OPTION_OLD ?
2752 }
2753
2754 /*
2755 * If OLD/NEW alias names weren't explicitly specified, use "old"/"new"
2756 * unless masked by existing relations.
2757 */
2758 if (qry->returningOldAlias == NULL &&
2759 refnameNamespaceItem(pstate, NULL, "old", -1, NULL) == NULL)
2760 {
2761 qry->returningOldAlias = "old";
2763 }
2764 if (qry->returningNewAlias == NULL &&
2765 refnameNamespaceItem(pstate, NULL, "new", -1, NULL) == NULL)
2766 {
2767 qry->returningNewAlias = "new";
2769 }
2770
2771 /*
2772 * We need to assign resnos starting at one in the RETURNING list. Save
2773 * and restore the main tlist's value of p_next_resno, just in case
2774 * someone looks at it later (probably won't happen).
2775 */
2776 save_next_resno = pstate->p_next_resno;
2777 pstate->p_next_resno = 1;
2778
2779 /* transform RETURNING expressions identically to a SELECT targetlist */
2780 qry->returningList = transformTargetList(pstate,
2781 returningClause->exprs,
2782 exprKind);
2783
2784 /*
2785 * Complain if the nonempty tlist expanded to nothing (which is possible
2786 * if it contains only a star-expansion of a zero-column table). If we
2787 * allow this, the parsed Query will look like it didn't have RETURNING,
2788 * with results that would probably surprise the user.
2789 */
2790 if (qry->returningList == NIL)
2791 ereport(ERROR,
2793 errmsg("RETURNING must have at least one column"),
2794 parser_errposition(pstate,
2795 exprLocation(linitial(returningClause->exprs)))));
2796
2797 /* mark column origins */
2799
2800 /* resolve any still-unresolved output columns as being type text */
2801 if (pstate->p_resolve_unknowns)
2803
2804 /* restore state */
2805 pstate->p_namespace = list_truncate(pstate->p_namespace, save_nslen);
2806 pstate->p_next_resno = save_next_resno;
2807}
2808
2809
2810/*
2811 * transformPLAssignStmt -
2812 * transform a PL/pgSQL assignment statement
2813 *
2814 * If there is no opt_indirection, the transformed statement looks like
2815 * "SELECT a_expr ...", except the expression has been cast to the type of
2816 * the target. With indirection, it's still a SELECT, but the expression will
2817 * incorporate FieldStore and/or assignment SubscriptingRef nodes to compute a
2818 * new value for a container-type variable represented by the target. The
2819 * expression references the target as the container source.
2820 */
2821static Query *
2823{
2824 Query *qry;
2826 List *indirection = stmt->indirection;
2827 int nnames = stmt->nnames;
2828 Node *target;
2831
2832 /*
2833 * First, construct a ColumnRef for the target variable. If the target
2834 * has more than one dotted name, we have to pull the extra names out of
2835 * the indirection list.
2836 */
2837 cref->fields = list_make1(makeString(stmt->name));
2838 cref->location = stmt->location;
2839 if (nnames > 1)
2840 {
2841 /* avoid munging the raw parsetree */
2842 indirection = list_copy(indirection);
2843 while (--nnames > 0 && indirection != NIL)
2844 {
2845 Node *ind = (Node *) linitial(indirection);
2846
2847 if (!IsA(ind, String))
2848 elog(ERROR, "invalid name count in PLAssignStmt");
2849 cref->fields = lappend(cref->fields, ind);
2850 indirection = list_delete_first(indirection);
2851 }
2852 }
2853
2854 /*
2855 * Transform the target reference. Typically we will get back a Param
2856 * node, but there's no reason to be too picky about its type. (Note that
2857 * we must do this before calling transformSelectStmt. It's tempting to
2858 * do it inside transformPLAssignStmtTarget, but we need to do it before
2859 * adding any FROM tables to the pstate's namespace, else we might wrongly
2860 * resolve the target as a table column.)
2861 */
2862 target = transformExpr(pstate, (Node *) cref,
2864
2865 /* Set up passthrough data for transformPLAssignStmtTarget */
2866 passthru.stmt = stmt;
2867 passthru.target = target;
2868 passthru.indirection = indirection;
2869
2870 /*
2871 * To avoid duplicating a lot of code, we use transformSelectStmt to do
2872 * almost all of the work. However, we need to do additional processing
2873 * on the SELECT's targetlist after it's been transformed, but before
2874 * possible addition of targetlist items for ORDER BY or GROUP BY.
2875 * transformSelectStmt knows it should call transformPLAssignStmtTarget if
2876 * it's passed a passthru argument.
2877 *
2878 * Also, disable resolution of unknown-type tlist items; PL/pgSQL wants to
2879 * deal with that itself.
2880 */
2882 pstate->p_resolve_unknowns = false;
2883 qry = transformSelectStmt(pstate, stmt->val, &passthru);
2885
2886 return qry;
2887}
2888
2889/*
2890 * Callback function to adjust a SELECT's tlist to make the output suitable
2891 * for assignment to a PLAssignStmt's target variable.
2892 *
2893 * Note: we actually modify the tle->expr in-place, but the function's API
2894 * is set up to not presume that.
2895 */
2896static List *
2899{
2900 PLAssignStmt *stmt = passthru->stmt;
2901 Node *target = passthru->target;
2902 List *indirection = passthru->indirection;
2903 Oid targettype;
2904 int32 targettypmod;
2907 Oid type_id;
2908
2909 targettype = exprType(target);
2910 targettypmod = exprTypmod(target);
2912
2913 /* we should have exactly one targetlist item */
2914 if (list_length(tlist) != 1)
2915 ereport(ERROR,
2917 errmsg_plural("assignment source returned %d column",
2918 "assignment source returned %d columns",
2919 list_length(tlist),
2920 list_length(tlist))));
2921
2922 tle = linitial_node(TargetEntry, tlist);
2923
2924 /*
2925 * This next bit is similar to transformAssignedExpr; the key difference
2926 * is we use COERCION_PLPGSQL not COERCION_ASSIGNMENT.
2927 */
2928 type_id = exprType((Node *) tle->expr);
2929
2931
2932 if (indirection)
2933 {
2934 tle->expr = (Expr *)
2936 target,
2937 stmt->name,
2938 false,
2939 targettype,
2940 targettypmod,
2942 indirection,
2943 list_head(indirection),
2944 (Node *) tle->expr,
2946 exprLocation(target));
2947 }
2948 else if (targettype != type_id &&
2949 (targettype == RECORDOID || ISCOMPLEX(targettype)) &&
2950 (type_id == RECORDOID || ISCOMPLEX(type_id)))
2951 {
2952 /*
2953 * Hack: do not let coerce_to_target_type() deal with inconsistent
2954 * composite types. Just pass the expression result through as-is,
2955 * and let the PL/pgSQL executor do the conversion its way. This is
2956 * rather bogus, but it's needed for backwards compatibility.
2957 */
2958 }
2959 else
2960 {
2961 /*
2962 * For normal non-qualified target column, do type checking and
2963 * coercion.
2964 */
2965 Node *orig_expr = (Node *) tle->expr;
2966
2967 tle->expr = (Expr *)
2968 coerce_to_target_type(pstate,
2969 orig_expr, type_id,
2970 targettype, targettypmod,
2973 -1);
2974 /* With COERCION_PLPGSQL, this error is probably unreachable */
2975 if (tle->expr == NULL)
2976 ereport(ERROR,
2978 errmsg("variable \"%s\" is of type %s"
2979 " but expression is of type %s",
2980 stmt->name,
2981 format_type_be(targettype),
2982 format_type_be(type_id)),
2983 errhint("You will need to rewrite or cast the expression."),
2985 }
2986
2987 pstate->p_expr_kind = EXPR_KIND_NONE;
2988
2989 return list_make1(tle);
2990}
2991
2992
2993/*
2994 * transformDeclareCursorStmt -
2995 * transform a DECLARE CURSOR Statement
2996 *
2997 * DECLARE CURSOR is like other utility statements in that we emit it as a
2998 * CMD_UTILITY Query node; however, we must first transform the contained
2999 * query. We used to postpone that until execution, but it's really necessary
3000 * to do it during the normal parse analysis phase to ensure that side effects
3001 * of parser hooks happen at the expected time.
3002 */
3003static Query *
3005{
3006 Query *result;
3007 Query *query;
3008
3009 if ((stmt->options & CURSOR_OPT_SCROLL) &&
3010 (stmt->options & CURSOR_OPT_NO_SCROLL))
3011 ereport(ERROR,
3013 /* translator: %s is a SQL keyword */
3014 errmsg("cannot specify both %s and %s",
3015 "SCROLL", "NO SCROLL")));
3016
3017 if ((stmt->options & CURSOR_OPT_ASENSITIVE) &&
3018 (stmt->options & CURSOR_OPT_INSENSITIVE))
3019 ereport(ERROR,
3021 /* translator: %s is a SQL keyword */
3022 errmsg("cannot specify both %s and %s",
3023 "ASENSITIVE", "INSENSITIVE")));
3024
3025 /* Transform contained query, not allowing SELECT INTO */
3026 query = transformStmt(pstate, stmt->query);
3027 stmt->query = (Node *) query;
3028
3029 /* Grammar should not have allowed anything but SELECT */
3030 if (!IsA(query, Query) ||
3031 query->commandType != CMD_SELECT)
3032 elog(ERROR, "unexpected non-SELECT command in DECLARE CURSOR");
3033
3034 /*
3035 * We also disallow data-modifying WITH in a cursor. (This could be
3036 * allowed, but the semantics of when the updates occur might be
3037 * surprising.)
3038 */
3039 if (query->hasModifyingCTE)
3040 ereport(ERROR,
3042 errmsg("DECLARE CURSOR must not contain data-modifying statements in WITH")));
3043
3044 /* FOR UPDATE and WITH HOLD are not compatible */
3045 if (query->rowMarks != NIL && (stmt->options & CURSOR_OPT_HOLD))
3046 ereport(ERROR,
3048 /*------
3049 translator: %s is a SQL row locking clause such as FOR UPDATE */
3050 errmsg("DECLARE CURSOR WITH HOLD ... %s is not supported",
3052 linitial(query->rowMarks))->strength)),
3053 errdetail("Holdable cursors must be READ ONLY.")));
3054
3055 /* FOR UPDATE and SCROLL are not compatible */
3056 if (query->rowMarks != NIL && (stmt->options & CURSOR_OPT_SCROLL))
3057 ereport(ERROR,
3059 /*------
3060 translator: %s is a SQL row locking clause such as FOR UPDATE */
3061 errmsg("DECLARE SCROLL CURSOR ... %s is not supported",
3063 linitial(query->rowMarks))->strength)),
3064 errdetail("Scrollable cursors must be READ ONLY.")));
3065
3066 /* FOR UPDATE and INSENSITIVE are not compatible */
3067 if (query->rowMarks != NIL && (stmt->options & CURSOR_OPT_INSENSITIVE))
3068 ereport(ERROR,
3070 /*------
3071 translator: %s is a SQL row locking clause such as FOR UPDATE */
3072 errmsg("DECLARE INSENSITIVE CURSOR ... %s is not valid",
3074 linitial(query->rowMarks))->strength)),
3075 errdetail("Insensitive cursors must be READ ONLY.")));
3076
3077 /* represent the command as a utility Query */
3078 result = makeNode(Query);
3079 result->commandType = CMD_UTILITY;
3080 result->utilityStmt = (Node *) stmt;
3081
3082 return result;
3083}
3084
3085
3086/*
3087 * transformExplainStmt -
3088 * transform an EXPLAIN Statement
3089 *
3090 * EXPLAIN is like other utility statements in that we emit it as a
3091 * CMD_UTILITY Query node; however, we must first transform the contained
3092 * query. We used to postpone that until execution, but it's really necessary
3093 * to do it during the normal parse analysis phase to ensure that side effects
3094 * of parser hooks happen at the expected time.
3095 */
3096static Query *
3098{
3099 Query *result;
3100 bool generic_plan = false;
3101 Oid *paramTypes = NULL;
3102 int numParams = 0;
3103
3104 /*
3105 * If we have no external source of parameter definitions, and the
3106 * GENERIC_PLAN option is specified, then accept variable parameter
3107 * definitions (similarly to PREPARE, for example).
3108 */
3109 if (pstate->p_paramref_hook == NULL)
3110 {
3111 ListCell *lc;
3112
3113 foreach(lc, stmt->options)
3114 {
3115 DefElem *opt = (DefElem *) lfirst(lc);
3116
3117 if (strcmp(opt->defname, "generic_plan") == 0)
3119 /* don't "break", as we want the last value */
3120 }
3121 if (generic_plan)
3122 setup_parse_variable_parameters(pstate, &paramTypes, &numParams);
3123 }
3124
3125 /* transform contained query, allowing SELECT INTO */
3126 stmt->query = (Node *) transformOptionalSelectInto(pstate, stmt->query);
3127
3128 /* make sure all is well with parameter types */
3129 if (generic_plan)
3130 check_variable_parameters(pstate, (Query *) stmt->query);
3131
3132 /* represent the command as a utility Query */
3133 result = makeNode(Query);
3134 result->commandType = CMD_UTILITY;
3135 result->utilityStmt = (Node *) stmt;
3136
3137 return result;
3138}
3139
3140
3141/*
3142 * transformCreateTableAsStmt -
3143 * transform a CREATE TABLE AS, SELECT ... INTO, or CREATE MATERIALIZED VIEW
3144 * Statement
3145 *
3146 * As with DECLARE CURSOR and EXPLAIN, transform the contained statement now.
3147 */
3148static Query *
3150{
3151 Query *result;
3152 Query *query;
3153
3154 /* transform contained query, not allowing SELECT INTO */
3155 query = transformStmt(pstate, stmt->query);
3156 stmt->query = (Node *) query;
3157
3158 /* additional work needed for CREATE MATERIALIZED VIEW */
3159 if (stmt->objtype == OBJECT_MATVIEW)
3160 {
3162
3163 /*
3164 * Prohibit a data-modifying CTE in the query used to create a
3165 * materialized view. It's not sufficiently clear what the user would
3166 * want to happen if the MV is refreshed or incrementally maintained.
3167 */
3168 if (query->hasModifyingCTE)
3169 ereport(ERROR,
3171 errmsg("materialized views must not use data-modifying statements in WITH")));
3172
3173 /*
3174 * Check whether any temporary database objects are used in the
3175 * creation query. It would be hard to refresh data or incrementally
3176 * maintain it if a source disappeared.
3177 */
3179 ereport(ERROR,
3181 errmsg("materialized views must not use temporary objects"),
3182 errdetail("This view depends on temporary %s.",
3184
3185 /*
3186 * A materialized view would either need to save parameters for use in
3187 * maintaining/loading the data or prohibit them entirely. The latter
3188 * seems safer and more sane.
3189 */
3191 ereport(ERROR,
3193 errmsg("materialized views may not be defined using bound parameters")));
3194
3195 /*
3196 * For now, we disallow unlogged materialized views, because it seems
3197 * like a bad idea for them to just go to empty after a crash. (If we
3198 * could mark them as unpopulated, that would be better, but that
3199 * requires catalog changes which crash recovery can't presently
3200 * handle.)
3201 */
3202 if (stmt->into->rel->relpersistence == RELPERSISTENCE_UNLOGGED)
3203 ereport(ERROR,
3205 errmsg("materialized views cannot be unlogged")));
3206
3207 /*
3208 * At runtime, we'll need a copy of the parsed-but-not-rewritten Query
3209 * for purposes of creating the view's ON SELECT rule. We stash that
3210 * in the IntoClause because that's where intorel_startup() can
3211 * conveniently get it from.
3212 */
3213 stmt->into->viewQuery = copyObject(query);
3214 }
3215
3216 /* represent the command as a utility Query */
3217 result = makeNode(Query);
3218 result->commandType = CMD_UTILITY;
3219 result->utilityStmt = (Node *) stmt;
3220
3221 return result;
3222}
3223
3224/*
3225 * transform a CallStmt
3226 */
3227static Query *
3229{
3230 List *targs;
3231 ListCell *lc;
3232 Node *node;
3233 FuncExpr *fexpr;
3236 bool isNull;
3237 List *outargs = NIL;
3238 Query *result;
3239
3240 /*
3241 * First, do standard parse analysis on the procedure call and its
3242 * arguments, allowing us to identify the called procedure.
3243 */
3244 targs = NIL;
3245 foreach(lc, stmt->funccall->args)
3246 {
3247 targs = lappend(targs, transformExpr(pstate,
3248 (Node *) lfirst(lc),
3250 }
3251
3252 node = ParseFuncOrColumn(pstate,
3253 stmt->funccall->funcname,
3254 targs,
3255 pstate->p_last_srf,
3256 stmt->funccall,
3257 true,
3258 stmt->funccall->location);
3259
3260 assign_expr_collations(pstate, node);
3261
3262 fexpr = castNode(FuncExpr, node);
3263
3266 elog(ERROR, "cache lookup failed for function %u", fexpr->funcid);
3267
3268 /*
3269 * Expand the argument list to deal with named-argument notation and
3270 * default arguments. For ordinary FuncExprs this'd be done during
3271 * planning, but a CallStmt doesn't go through planning, and there seems
3272 * no good reason not to do it here.
3273 */
3275 true,
3276 fexpr->funcresulttype,
3277 proctup);
3278
3279 /* Fetch proargmodes; if it's null, there are no output args */
3282 &isNull);
3283 if (!isNull)
3284 {
3285 /*
3286 * Split the list into input arguments in fexpr->args and output
3287 * arguments in stmt->outargs. INOUT arguments appear in both lists.
3288 */
3289 ArrayType *arr;
3290 int numargs;
3291 char *argmodes;
3292 List *inargs;
3293 int i;
3294
3295 arr = DatumGetArrayTypeP(proargmodes); /* ensure not toasted */
3296 numargs = list_length(fexpr->args);
3297 if (ARR_NDIM(arr) != 1 ||
3298 ARR_DIMS(arr)[0] != numargs ||
3299 ARR_HASNULL(arr) ||
3300 ARR_ELEMTYPE(arr) != CHAROID)
3301 elog(ERROR, "proargmodes is not a 1-D char array of length %d or it contains nulls",
3302 numargs);
3303 argmodes = (char *) ARR_DATA_PTR(arr);
3304
3305 inargs = NIL;
3306 i = 0;
3307 foreach(lc, fexpr->args)
3308 {
3309 Node *n = lfirst(lc);
3310
3311 switch (argmodes[i])
3312 {
3313 case PROARGMODE_IN:
3315 inargs = lappend(inargs, n);
3316 break;
3317 case PROARGMODE_OUT:
3318 outargs = lappend(outargs, n);
3319 break;
3320 case PROARGMODE_INOUT:
3321 inargs = lappend(inargs, n);
3322 outargs = lappend(outargs, copyObject(n));
3323 break;
3324 default:
3325 /* note we don't support PROARGMODE_TABLE */
3326 elog(ERROR, "invalid argmode %c for procedure",
3327 argmodes[i]);
3328 break;
3329 }
3330 i++;
3331 }
3332 fexpr->args = inargs;
3333 }
3334
3335 stmt->funcexpr = fexpr;
3336 stmt->outargs = outargs;
3337
3339
3340 /* represent the command as a utility Query */
3341 result = makeNode(Query);
3342 result->commandType = CMD_UTILITY;
3343 result->utilityStmt = (Node *) stmt;
3344
3345 return result;
3346}
3347
3348/*
3349 * Produce a string representation of a LockClauseStrength value.
3350 * This should only be applied to valid values (not LCS_NONE).
3351 */
3352const char *
3354{
3355 switch (strength)
3356 {
3357 case LCS_NONE:
3358 Assert(false);
3359 break;
3360 case LCS_FORKEYSHARE:
3361 return "FOR KEY SHARE";
3362 case LCS_FORSHARE:
3363 return "FOR SHARE";
3364 case LCS_FORNOKEYUPDATE:
3365 return "FOR NO KEY UPDATE";
3366 case LCS_FORUPDATE:
3367 return "FOR UPDATE";
3368 }
3369 return "FOR some"; /* shouldn't happen */
3370}
3371
3372/*
3373 * Check for features that are not supported with FOR [KEY] UPDATE/SHARE.
3374 *
3375 * exported so planner can check again after rewriting, query pullup, etc
3376 */
3377void
3379{
3380 Assert(strength != LCS_NONE); /* else caller error */
3381
3382 if (qry->setOperations)
3383 ereport(ERROR,
3385 /*------
3386 translator: %s is a SQL row locking clause such as FOR UPDATE */
3387 errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
3388 LCS_asString(strength))));
3389 if (qry->distinctClause != NIL)
3390 ereport(ERROR,
3392 /*------
3393 translator: %s is a SQL row locking clause such as FOR UPDATE */
3394 errmsg("%s is not allowed with DISTINCT clause",
3395 LCS_asString(strength))));
3396 if (qry->groupClause != NIL || qry->groupingSets != NIL)
3397 ereport(ERROR,
3399 /*------
3400 translator: %s is a SQL row locking clause such as FOR UPDATE */
3401 errmsg("%s is not allowed with GROUP BY clause",
3402 LCS_asString(strength))));
3403 if (qry->havingQual != NULL)
3404 ereport(ERROR,
3406 /*------
3407 translator: %s is a SQL row locking clause such as FOR UPDATE */
3408 errmsg("%s is not allowed with HAVING clause",
3409 LCS_asString(strength))));
3410 if (qry->hasAggs)
3411 ereport(ERROR,
3413 /*------
3414 translator: %s is a SQL row locking clause such as FOR UPDATE */
3415 errmsg("%s is not allowed with aggregate functions",
3416 LCS_asString(strength))));
3417 if (qry->hasWindowFuncs)
3418 ereport(ERROR,
3420 /*------
3421 translator: %s is a SQL row locking clause such as FOR UPDATE */
3422 errmsg("%s is not allowed with window functions",
3423 LCS_asString(strength))));
3424 if (qry->hasTargetSRFs)
3425 ereport(ERROR,
3427 /*------
3428 translator: %s is a SQL row locking clause such as FOR UPDATE */
3429 errmsg("%s is not allowed with set-returning functions in the target list",
3430 LCS_asString(strength))));
3431}
3432
3433/*
3434 * Transform a FOR [KEY] UPDATE/SHARE clause
3435 *
3436 * This basically involves replacing names by integer relids.
3437 *
3438 * NB: if you need to change this, see also markQueryForLocking()
3439 * in rewriteHandler.c, and isLockedRefname() in parse_relation.c.
3440 */
3441static void
3443 bool pushedDown)
3444{
3445 List *lockedRels = lc->lockedRels;
3446 ListCell *l;
3447 ListCell *rt;
3448 Index i;
3450
3451 CheckSelectLocking(qry, lc->strength);
3452
3453 /* make a clause we can pass down to subqueries to select all rels */
3455 allrels->lockedRels = NIL; /* indicates all rels */
3456 allrels->strength = lc->strength;
3457 allrels->waitPolicy = lc->waitPolicy;
3458
3459 if (lockedRels == NIL)
3460 {
3461 /*
3462 * Lock all regular tables used in query and its subqueries. We
3463 * examine inFromCl to exclude auto-added RTEs, particularly NEW/OLD
3464 * in rules. This is a bit of an abuse of a mostly-obsolete flag, but
3465 * it's convenient. We can't rely on the namespace mechanism that has
3466 * largely replaced inFromCl, since for example we need to lock
3467 * base-relation RTEs even if they are masked by upper joins.
3468 */
3469 i = 0;
3470 foreach(rt, qry->rtable)
3471 {
3473
3474 ++i;
3475 if (!rte->inFromCl)
3476 continue;
3477 switch (rte->rtekind)
3478 {
3479 case RTE_RELATION:
3480 {
3482
3483 applyLockingClause(qry, i,
3484 lc->strength,
3485 lc->waitPolicy,
3486 pushedDown);
3487 perminfo = getRTEPermissionInfo(qry->rteperminfos, rte);
3488 perminfo->requiredPerms |= ACL_SELECT_FOR_UPDATE;
3489 }
3490 break;
3491 case RTE_SUBQUERY:
3492 applyLockingClause(qry, i, lc->strength, lc->waitPolicy,
3493 pushedDown);
3494
3495 /*
3496 * FOR UPDATE/SHARE of subquery is propagated to all of
3497 * subquery's rels, too. We could do this later (based on
3498 * the marking of the subquery RTE) but it is convenient
3499 * to have local knowledge in each query level about which
3500 * rels need to be opened with RowShareLock.
3501 */
3502 transformLockingClause(pstate, rte->subquery,
3503 allrels, true);
3504 break;
3505 default:
3506 /* ignore JOIN, SPECIAL, FUNCTION, VALUES, CTE RTEs */
3507 break;
3508 }
3509 }
3510 }
3511 else
3512 {
3513 /*
3514 * Lock just the named tables. As above, we allow locking any base
3515 * relation regardless of alias-visibility rules, so we need to
3516 * examine inFromCl to exclude OLD/NEW.
3517 */
3518 foreach(l, lockedRels)
3519 {
3520 RangeVar *thisrel = (RangeVar *) lfirst(l);
3521
3522 /* For simplicity we insist on unqualified alias names here */
3523 if (thisrel->catalogname || thisrel->schemaname)
3524 ereport(ERROR,
3526 /*------
3527 translator: %s is a SQL row locking clause such as FOR UPDATE */
3528 errmsg("%s must specify unqualified relation names",
3529 LCS_asString(lc->strength)),
3530 parser_errposition(pstate, thisrel->location)));
3531
3532 i = 0;
3533 foreach(rt, qry->rtable)
3534 {
3536 char *rtename = rte->eref->aliasname;
3537
3538 ++i;
3539 if (!rte->inFromCl)
3540 continue;
3541
3542 /*
3543 * A join RTE without an alias is not visible as a relation
3544 * name and needs to be skipped (otherwise it might hide a
3545 * base relation with the same name), except if it has a USING
3546 * alias, which *is* visible.
3547 *
3548 * Subquery and values RTEs without aliases are never visible
3549 * as relation names and must always be skipped.
3550 */
3551 if (rte->alias == NULL)
3552 {
3553 if (rte->rtekind == RTE_JOIN)
3554 {
3555 if (rte->join_using_alias == NULL)
3556 continue;
3557 rtename = rte->join_using_alias->aliasname;
3558 }
3559 else if (rte->rtekind == RTE_SUBQUERY ||
3560 rte->rtekind == RTE_VALUES)
3561 continue;
3562 }
3563
3564 if (strcmp(rtename, thisrel->relname) == 0)
3565 {
3566 switch (rte->rtekind)
3567 {
3568 case RTE_RELATION:
3569 {
3571
3572 applyLockingClause(qry, i,
3573 lc->strength,
3574 lc->waitPolicy,
3575 pushedDown);
3576 perminfo = getRTEPermissionInfo(qry->rteperminfos, rte);
3577 perminfo->requiredPerms |= ACL_SELECT_FOR_UPDATE;
3578 }
3579 break;
3580 case RTE_SUBQUERY:
3581 applyLockingClause(qry, i, lc->strength,
3582 lc->waitPolicy, pushedDown);
3583 /* see comment above */
3584 transformLockingClause(pstate, rte->subquery,
3585 allrels, true);
3586 break;
3587 case RTE_JOIN:
3588 ereport(ERROR,
3590 /*------
3591 translator: %s is a SQL row locking clause such as FOR UPDATE */
3592 errmsg("%s cannot be applied to a join",
3593 LCS_asString(lc->strength)),
3594 parser_errposition(pstate, thisrel->location)));
3595 break;
3596 case RTE_FUNCTION:
3597 ereport(ERROR,
3599 /*------
3600 translator: %s is a SQL row locking clause such as FOR UPDATE */
3601 errmsg("%s cannot be applied to a function",
3602 LCS_asString(lc->strength)),
3603 parser_errposition(pstate, thisrel->location)));
3604 break;
3605 case RTE_TABLEFUNC:
3606 ereport(ERROR,
3608 /*------
3609 translator: %s is a SQL row locking clause such as FOR UPDATE */
3610 errmsg("%s cannot be applied to a table function",
3611 LCS_asString(lc->strength)),
3612 parser_errposition(pstate, thisrel->location)));
3613 break;
3614 case RTE_VALUES:
3615 ereport(ERROR,
3617 /*------
3618 translator: %s is a SQL row locking clause such as FOR UPDATE */
3619 errmsg("%s cannot be applied to VALUES",
3620 LCS_asString(lc->strength)),
3621 parser_errposition(pstate, thisrel->location)));
3622 break;
3623 case RTE_CTE:
3624 ereport(ERROR,
3626 /*------
3627 translator: %s is a SQL row locking clause such as FOR UPDATE */
3628 errmsg("%s cannot be applied to a WITH query",
3629 LCS_asString(lc->strength)),
3630 parser_errposition(pstate, thisrel->location)));
3631 break;
3633 ereport(ERROR,
3635 /*------
3636 translator: %s is a SQL row locking clause such as FOR UPDATE */
3637 errmsg("%s cannot be applied to a named tuplestore",
3638 LCS_asString(lc->strength)),
3639 parser_errposition(pstate, thisrel->location)));
3640 break;
3641
3642 /* Shouldn't be possible to see RTE_RESULT here */
3643
3644 default:
3645 elog(ERROR, "unrecognized RTE type: %d",
3646 (int) rte->rtekind);
3647 break;
3648 }
3649 break; /* out of foreach loop */
3650 }
3651 }
3652 if (rt == NULL)
3653 ereport(ERROR,
3655 /*------
3656 translator: %s is a SQL row locking clause such as FOR UPDATE */
3657 errmsg("relation \"%s\" in %s clause not found in FROM clause",
3658 thisrel->relname,
3659 LCS_asString(lc->strength)),
3660 parser_errposition(pstate, thisrel->location)));
3661 }
3662 }
3663}
3664
3665/*
3666 * Record locking info for a single rangetable item
3667 */
3668void
3670 LockClauseStrength strength, LockWaitPolicy waitPolicy,
3671 bool pushedDown)
3672{
3673 RowMarkClause *rc;
3674
3675 Assert(strength != LCS_NONE); /* else caller error */
3676
3677 /* If it's an explicit clause, make sure hasForUpdate gets set */
3678 if (!pushedDown)
3679 qry->hasForUpdate = true;
3680
3681 /* Check for pre-existing entry for same rtindex */
3682 if ((rc = get_parse_rowmark(qry, rtindex)) != NULL)
3683 {
3684 /*
3685 * If the same RTE is specified with more than one locking strength,
3686 * use the strongest. (Reasonable, since you can't take both a shared
3687 * and exclusive lock at the same time; it'll end up being exclusive
3688 * anyway.)
3689 *
3690 * Similarly, if the same RTE is specified with more than one lock
3691 * wait policy, consider that NOWAIT wins over SKIP LOCKED, which in
3692 * turn wins over waiting for the lock (the default). This is a bit
3693 * more debatable but raising an error doesn't seem helpful. (Consider
3694 * for instance SELECT FOR UPDATE NOWAIT from a view that internally
3695 * contains a plain FOR UPDATE spec.) Having NOWAIT win over SKIP
3696 * LOCKED is reasonable since the former throws an error in case of
3697 * coming across a locked tuple, which may be undesirable in some
3698 * cases but it seems better than silently returning inconsistent
3699 * results.
3700 *
3701 * And of course pushedDown becomes false if any clause is explicit.
3702 */
3703 rc->strength = Max(rc->strength, strength);
3704 rc->waitPolicy = Max(rc->waitPolicy, waitPolicy);
3705 rc->pushedDown &= pushedDown;
3706 return;
3707 }
3708
3709 /* Make a new RowMarkClause */
3710 rc = makeNode(RowMarkClause);
3711 rc->rti = rtindex;
3712 rc->strength = strength;
3713 rc->waitPolicy = waitPolicy;
3714 rc->pushedDown = pushedDown;
3715 qry->rowMarks = lappend(qry->rowMarks, rc);
3716}
3717
3718#ifdef DEBUG_NODE_TESTS_ENABLED
3719/*
3720 * Coverage testing for raw_expression_tree_walker().
3721 *
3722 * When enabled, we run raw_expression_tree_walker() over every DML statement
3723 * submitted to parse analysis. Without this provision, that function is only
3724 * applied in limited cases involving CTEs, and we don't really want to have
3725 * to test everything inside as well as outside a CTE.
3726 */
3727static bool
3728test_raw_expression_coverage(Node *node, void *context)
3729{
3730 if (node == NULL)
3731 return false;
3732 return raw_expression_tree_walker(node,
3734 context);
3735}
3736#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:837
#define Max(x, y)
Definition c.h:1087
#define Assert(condition)
Definition c.h:945
int32_t int32
Definition c.h:614
unsigned int Index
Definition c.h:700
List * expand_function_arguments(List *args, bool include_out_arguments, Oid result_type, HeapTuple func_tuple)
Definition clauses.c:4891
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 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:304
Oid exprCollation(const Node *expr)
Definition nodeFuncs.c:826
int exprLocation(const Node *expr)
Definition nodeFuncs.c:1392
#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
static char * errmsg
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:1150
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:121
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:3442
static Query * transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
Definition analyze.c:565
void CheckSelectLocking(Query *qry, LockClauseStrength strength)
Definition analyze.c:3378
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:3669
static void determineRecursiveColTypes(ParseState *pstate, Node *larg, List *nrtargetlist)
Definition analyze.c:2436
void constructSetOpTargetlist(ParseState *pstate, SetOperationStmt *op, const List *ltargetlist, const List *rtargetlist, List **targetlist, const char *context, bool recursive)
Definition analyze.c:2272
static Query * transformReturnStmt(ParseState *pstate, ReturnStmt *stmt)
Definition analyze.c:2490
static void addNSItemForReturning(ParseState *pstate, const char *aliasname, VarReturningType returning_type)
Definition analyze.c:2661
void transformReturningClause(ParseState *pstate, Query *qry, ReturningClause *returningClause, ParseExprKind exprKind)
Definition analyze.c:2700
static Query * transformPLAssignStmt(ParseState *pstate, PLAssignStmt *stmt)
Definition analyze.c:2822
static Query * transformCreateTableAsStmt(ParseState *pstate, CreateTableAsStmt *stmt)
Definition analyze.c:3149
post_parse_analyze_hook_type post_parse_analyze_hook
Definition analyze.c:68
static Query * transformCallStmt(ParseState *pstate, CallStmt *stmt)
Definition analyze.c:3228
List * transformUpdateTargetList(ParseState *pstate, List *origTlist)
Definition analyze.c:2586
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:3353
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:2521
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:3097
List * BuildOnConflictExcludedTargetlist(Relation targetrel, Index exclRelIndex)
Definition analyze.c:1291
static List * transformPLAssignStmtTarget(ParseState *pstate, List *tlist, SelectStmtPassthrough *passthru)
Definition analyze.c:2897
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:3004
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:252
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:857
List * newvals
Definition primnodes.h:1194
Definition pg_list.h:54
Definition nodes.h:135
OnConflictAction action
LockClauseStrength lockStrength
List * arbiterElems
Definition primnodes.h:2402
OnConflictAction action
Definition primnodes.h:2399
LockClauseStrength lockStrength
Definition primnodes.h:2408
List * onConflictSet
Definition primnodes.h:2411
List * exclRelTlist
Definition primnodes.h:2416
Node * onConflictWhere
Definition primnodes.h:2414
Node * arbiterWhere
Definition primnodes.h:2404
RangeTblEntry * p_rte
Definition parse_node.h:311
ParseNamespaceColumn * p_nscolumns
Definition parse_node.h:315
RTEPermissionInfo * p_perminfo
Definition parse_node.h:313
bool p_hasTargetSRFs
Definition parse_node.h:244
List * p_ctenamespace
Definition parse_node.h:221
bool p_hasWindowFuncs
Definition parse_node.h:243
ParseNamespaceItem * p_target_nsitem
Definition parse_node.h:225
ParseExprKind p_expr_kind
Definition parse_node.h:228
bool p_locked_from_parent
Definition parse_node.h:232
ParseParamRefHook p_paramref_hook
Definition parse_node.h:256
List * p_namespace
Definition parse_node.h:218
QueryEnvironment * p_queryEnv
Definition parse_node.h:237
const char * p_sourcetext
Definition parse_node.h:210
List * p_windowdefs
Definition parse_node.h:227
bool p_resolve_unknowns
Definition parse_node.h:234
int p_next_resno
Definition parse_node.h:229
bool p_hasModifyingCTE
Definition parse_node.h:246
List * p_rteperminfos
Definition parse_node.h:212
Relation p_target_relation
Definition parse_node.h:224
CommonTableExpr * p_parent_cte
Definition parse_node.h:223
bool p_hasSubLinks
Definition parse_node.h:245
Node * p_last_srf
Definition parse_node.h:248
List * p_joinlist
Definition parse_node.h:216
List * p_locking_clause
Definition parse_node.h:231
List * p_rtable
Definition parse_node.h:211
bool p_hasAggs
Definition parse_node.h:242
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:178
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