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