PostgreSQL Source Code git master
Loading...
Searching...
No Matches
analyze.c File Reference
#include "postgres.h"
#include "access/stratnum.h"
#include "access/sysattr.h"
#include "catalog/dependency.h"
#include "catalog/pg_am.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "commands/defrem.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "nodes/queryjumble.h"
#include "optimizer/optimizer.h"
#include "parser/analyze.h"
#include "parser/parse_agg.h"
#include "parser/parse_clause.h"
#include "parser/parse_coerce.h"
#include "parser/parse_collate.h"
#include "parser/parse_cte.h"
#include "parser/parse_expr.h"
#include "parser/parse_func.h"
#include "parser/parse_merge.h"
#include "parser/parse_oper.h"
#include "parser/parse_param.h"
#include "parser/parse_relation.h"
#include "parser/parse_target.h"
#include "parser/parse_type.h"
#include "parser/parsetree.h"
#include "utils/backend_status.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/rangetypes.h"
#include "utils/rel.h"
#include "utils/syscache.h"
Include dependency graph for analyze.c:

Go to the source code of this file.

Data Structures

struct  SelectStmtPassthrough
 

Typedefs

typedef struct SelectStmtPassthrough SelectStmtPassthrough
 

Functions

static QuerytransformOptionalSelectInto (ParseState *pstate, Node *parseTree)
 
static QuerytransformDeleteStmt (ParseState *pstate, DeleteStmt *stmt)
 
static QuerytransformInsertStmt (ParseState *pstate, InsertStmt *stmt)
 
static OnConflictExprtransformOnConflictClause (ParseState *pstate, OnConflictClause *onConflictClause)
 
static ForPortionOfExprtransformForPortionOfClause (ParseState *pstate, int rtindex, const ForPortionOfClause *forPortionOf, bool isUpdate)
 
static int count_rowexpr_columns (ParseState *pstate, Node *expr)
 
static QuerytransformSelectStmt (ParseState *pstate, SelectStmt *stmt, SelectStmtPassthrough *passthru)
 
static QuerytransformValuesClause (ParseState *pstate, SelectStmt *stmt)
 
static QuerytransformSetOperationStmt (ParseState *pstate, SelectStmt *stmt)
 
static NodetransformSetOperationTree (ParseState *pstate, SelectStmt *stmt, bool isTopLevel, List **targetlist)
 
static void determineRecursiveColTypes (ParseState *pstate, Node *larg, List *nrtargetlist)
 
static QuerytransformReturnStmt (ParseState *pstate, ReturnStmt *stmt)
 
static QuerytransformUpdateStmt (ParseState *pstate, UpdateStmt *stmt)
 
static QuerytransformPLAssignStmt (ParseState *pstate, PLAssignStmt *stmt)
 
static ListtransformPLAssignStmtTarget (ParseState *pstate, List *tlist, SelectStmtPassthrough *passthru)
 
static QuerytransformDeclareCursorStmt (ParseState *pstate, DeclareCursorStmt *stmt)
 
static QuerytransformExplainStmt (ParseState *pstate, ExplainStmt *stmt)
 
static QuerytransformCreateTableAsStmt (ParseState *pstate, CreateTableAsStmt *stmt)
 
static QuerytransformCallStmt (ParseState *pstate, CallStmt *stmt)
 
static void transformLockingClause (ParseState *pstate, Query *qry, LockingClause *lc, bool pushedDown)
 
Queryparse_analyze_fixedparams (RawStmt *parseTree, const char *sourceText, const Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
 
Queryparse_analyze_varparams (RawStmt *parseTree, const char *sourceText, Oid **paramTypes, int *numParams, QueryEnvironment *queryEnv)
 
Queryparse_analyze_withcb (RawStmt *parseTree, const char *sourceText, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
 
Queryparse_sub_analyze (Node *parseTree, ParseState *parentParseState, CommonTableExpr *parentCTE, bool locked_from_parent, bool resolve_unknowns)
 
QuerytransformTopLevelStmt (ParseState *pstate, RawStmt *parseTree)
 
QuerytransformStmt (ParseState *pstate, Node *parseTree)
 
bool stmt_requires_parse_analysis (RawStmt *parseTree)
 
bool analyze_requires_snapshot (RawStmt *parseTree)
 
bool query_requires_rewrite_plan (Query *query)
 
ListtransformInsertRow (ParseState *pstate, List *exprlist, List *stmtcols, List *icolumns, List *attrnos, bool strip_indirection)
 
ListBuildOnConflictExcludedTargetlist (Relation targetrel, Index exclRelIndex)
 
SortGroupClausemakeSortGroupClauseForSetOp (Oid rescoltype, bool require_hash)
 
void constructSetOpTargetlist (ParseState *pstate, SetOperationStmt *op, const List *ltargetlist, const List *rtargetlist, List **targetlist, const char *context, bool recursive)
 
ListtransformUpdateTargetList (ParseState *pstate, List *origTlist, ForPortionOfExpr *forPortionOf)
 
static void addNSItemForReturning (ParseState *pstate, const char *aliasname, VarReturningType returning_type)
 
void transformReturningClause (ParseState *pstate, Query *qry, ReturningClause *returningClause, ParseExprKind exprKind)
 
const charLCS_asString (LockClauseStrength strength)
 
void CheckSelectLocking (Query *qry, LockClauseStrength strength)
 
void applyLockingClause (Query *qry, Index rtindex, LockClauseStrength strength, LockWaitPolicy waitPolicy, bool pushedDown)
 

Variables

post_parse_analyze_hook_type post_parse_analyze_hook = NULL
 

Typedef Documentation

◆ SelectStmtPassthrough

Function Documentation

◆ addNSItemForReturning()

static void addNSItemForReturning ( ParseState pstate,
const char aliasname,
VarReturningType  returning_type 
)
static

Definition at line 3024 of file analyze.c.

3026{
3027 List *colnames;
3028 int numattrs;
3031
3032 /* copy per-column data from the target relation */
3033 colnames = pstate->p_target_nsitem->p_rte->eref->colnames;
3034 numattrs = list_length(colnames);
3035
3037
3039 numattrs * sizeof(ParseNamespaceColumn));
3040
3041 /* mark all columns as returning OLD/NEW */
3042 for (int i = 0; i < numattrs; i++)
3043 nscolumns[i].p_varreturningtype = returning_type;
3044
3045 /* build the nsitem, copying most fields from the target relation */
3047 nsitem->p_names = makeAlias(aliasname, colnames);
3048 nsitem->p_rte = pstate->p_target_nsitem->p_rte;
3049 nsitem->p_rtindex = pstate->p_target_nsitem->p_rtindex;
3050 nsitem->p_perminfo = pstate->p_target_nsitem->p_perminfo;
3051 nsitem->p_nscolumns = nscolumns;
3052 nsitem->p_returning_type = returning_type;
3053
3054 /* add it to the query namespace as a table-only item */
3055 addNSItemToQuery(pstate, nsitem, false, true, false);
3056}
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
#define palloc_object(type)
Definition fe_memutils.h:89
#define palloc_array(type, count)
Definition fe_memutils.h:91
int i
Definition isn.c:77
Alias * makeAlias(const char *aliasname, List *colnames)
Definition makefuncs.c:438
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
static int list_length(const List *l)
Definition pg_list.h:152
static int fb(int x)
Definition pg_list.h:54
RangeTblEntry * p_rte
Definition parse_node.h:315
ParseNamespaceColumn * p_nscolumns
Definition parse_node.h:319
RTEPermissionInfo * p_perminfo
Definition parse_node.h:317
ParseNamespaceItem * p_target_nsitem
Definition parse_node.h:229

References addNSItemToQuery(), fb(), i, list_length(), makeAlias(), memcpy(), ParseNamespaceItem::p_nscolumns, ParseNamespaceItem::p_perminfo, ParseNamespaceItem::p_rte, ParseNamespaceItem::p_rtindex, ParseState::p_target_nsitem, palloc_array, and palloc_object.

Referenced by transformReturningClause().

◆ analyze_requires_snapshot()

bool analyze_requires_snapshot ( RawStmt parseTree)

Definition at line 513 of file analyze.c.

514{
515 /*
516 * Currently, this should return true in exactly the same cases that
517 * stmt_requires_parse_analysis() does, so we just invoke that function
518 * rather than duplicating it. We keep the two entry points separate for
519 * clarity of callers, since from the callers' standpoint these are
520 * different conditions.
521 *
522 * While there may someday be a statement type for which transformStmt()
523 * does something nontrivial and yet no snapshot is needed for that
524 * processing, it seems likely that making such a choice would be fragile.
525 * If you want to install an exception, document the reasoning for it in a
526 * comment.
527 */
529}
bool stmt_requires_parse_analysis(RawStmt *parseTree)
Definition analyze.c:469

References fb(), and stmt_requires_parse_analysis().

Referenced by BuildingPlanRequiresSnapshot(), exec_bind_message(), exec_parse_message(), and exec_simple_query().

◆ applyLockingClause()

void applyLockingClause ( Query qry,
Index  rtindex,
LockClauseStrength  strength,
LockWaitPolicy  waitPolicy,
bool  pushedDown 
)

Definition at line 4032 of file analyze.c.

4035{
4036 RowMarkClause *rc;
4037
4038 Assert(strength != LCS_NONE); /* else caller error */
4039
4040 /* If it's an explicit clause, make sure hasForUpdate gets set */
4041 if (!pushedDown)
4042 qry->hasForUpdate = true;
4043
4044 /* Check for pre-existing entry for same rtindex */
4045 if ((rc = get_parse_rowmark(qry, rtindex)) != NULL)
4046 {
4047 /*
4048 * If the same RTE is specified with more than one locking strength,
4049 * use the strongest. (Reasonable, since you can't take both a shared
4050 * and exclusive lock at the same time; it'll end up being exclusive
4051 * anyway.)
4052 *
4053 * Similarly, if the same RTE is specified with more than one lock
4054 * wait policy, consider that NOWAIT wins over SKIP LOCKED, which in
4055 * turn wins over waiting for the lock (the default). This is a bit
4056 * more debatable but raising an error doesn't seem helpful. (Consider
4057 * for instance SELECT FOR UPDATE NOWAIT from a view that internally
4058 * contains a plain FOR UPDATE spec.) Having NOWAIT win over SKIP
4059 * LOCKED is reasonable since the former throws an error in case of
4060 * coming across a locked tuple, which may be undesirable in some
4061 * cases but it seems better than silently returning inconsistent
4062 * results.
4063 *
4064 * And of course pushedDown becomes false if any clause is explicit.
4065 */
4066 rc->strength = Max(rc->strength, strength);
4067 rc->waitPolicy = Max(rc->waitPolicy, waitPolicy);
4068 rc->pushedDown &= pushedDown;
4069 return;
4070 }
4071
4072 /* Make a new RowMarkClause */
4073 rc = makeNode(RowMarkClause);
4074 rc->rti = rtindex;
4075 rc->strength = strength;
4076 rc->waitPolicy = waitPolicy;
4077 rc->pushedDown = pushedDown;
4078 qry->rowMarks = lappend(qry->rowMarks, rc);
4079}
#define Max(x, y)
Definition c.h:1085
#define Assert(condition)
Definition c.h:943
List * lappend(List *list, void *datum)
Definition list.c:339
@ LCS_NONE
Definition lockoptions.h:23
#define makeNode(_type_)
Definition nodes.h:161
RowMarkClause * get_parse_rowmark(Query *qry, Index rtindex)
List * rowMarks
Definition parsenodes.h:237
LockClauseStrength strength
LockWaitPolicy waitPolicy

References Assert, fb(), get_parse_rowmark(), lappend(), LCS_NONE, makeNode, Max, RowMarkClause::pushedDown, Query::rowMarks, RowMarkClause::rti, RowMarkClause::strength, and RowMarkClause::waitPolicy.

Referenced by markQueryForLocking(), and transformLockingClause().

◆ BuildOnConflictExcludedTargetlist()

List * BuildOnConflictExcludedTargetlist ( Relation  targetrel,
Index  exclRelIndex 
)

Definition at line 1624 of file analyze.c.

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}
#define InvalidAttrNumber
Definition attnum.h:23
#define NameStr(name)
Definition c.h:835
uint32 result
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition makefuncs.c:66
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition makefuncs.c:388
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition makefuncs.c:289
char * pstrdup(const char *in)
Definition mcxt.c:1910
FormData_pg_attribute * Form_pg_attribute
#define NIL
Definition pg_list.h:68
#define InvalidOid
#define RelationGetNumberOfAttributes(relation)
Definition rel.h:522
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:178
const char * name

References fb(), InvalidAttrNumber, InvalidOid, lappend(), makeNullConst(), makeTargetEntry(), makeVar(), name, NameStr, NIL, pstrdup(), RelationGetNumberOfAttributes, result, and TupleDescAttr().

Referenced by rewriteTargetView(), and transformOnConflictClause().

◆ CheckSelectLocking()

void CheckSelectLocking ( Query qry,
LockClauseStrength  strength 
)

Definition at line 3741 of file analyze.c.

3742{
3743 Assert(strength != LCS_NONE); /* else caller error */
3744
3745 if (qry->setOperations)
3746 ereport(ERROR,
3748 /*------
3749 translator: %s is a SQL row locking clause such as FOR UPDATE */
3750 errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
3751 LCS_asString(strength))));
3752 if (qry->distinctClause != NIL)
3753 ereport(ERROR,
3755 /*------
3756 translator: %s is a SQL row locking clause such as FOR UPDATE */
3757 errmsg("%s is not allowed with DISTINCT clause",
3758 LCS_asString(strength))));
3759 if (qry->groupClause != NIL || qry->groupingSets != NIL)
3760 ereport(ERROR,
3762 /*------
3763 translator: %s is a SQL row locking clause such as FOR UPDATE */
3764 errmsg("%s is not allowed with GROUP BY clause",
3765 LCS_asString(strength))));
3766 if (qry->havingQual != NULL)
3767 ereport(ERROR,
3769 /*------
3770 translator: %s is a SQL row locking clause such as FOR UPDATE */
3771 errmsg("%s is not allowed with HAVING clause",
3772 LCS_asString(strength))));
3773 if (qry->hasAggs)
3774 ereport(ERROR,
3776 /*------
3777 translator: %s is a SQL row locking clause such as FOR UPDATE */
3778 errmsg("%s is not allowed with aggregate functions",
3779 LCS_asString(strength))));
3780 if (qry->hasWindowFuncs)
3781 ereport(ERROR,
3783 /*------
3784 translator: %s is a SQL row locking clause such as FOR UPDATE */
3785 errmsg("%s is not allowed with window functions",
3786 LCS_asString(strength))));
3787 if (qry->hasTargetSRFs)
3788 ereport(ERROR,
3790 /*------
3791 translator: %s is a SQL row locking clause such as FOR UPDATE */
3792 errmsg("%s is not allowed with set-returning functions in the target list",
3793 LCS_asString(strength))));
3794}
int errcode(int sqlerrcode)
Definition elog.c:875
#define ERROR
Definition elog.h:40
#define ereport(elevel,...)
Definition elog.h:152
static char * errmsg
const char * LCS_asString(LockClauseStrength strength)
Definition analyze.c:3716
Node * setOperations
Definition parsenodes.h:239
List * groupClause
Definition parsenodes.h:219
Node * havingQual
Definition parsenodes.h:225
List * groupingSets
Definition parsenodes.h:223
List * distinctClause
Definition parsenodes.h:229

References Assert, Query::distinctClause, ereport, errcode(), errmsg, ERROR, fb(), Query::groupClause, Query::groupingSets, Query::havingQual, LCS_asString(), LCS_NONE, NIL, and Query::setOperations.

Referenced by preprocess_rowmarks(), and transformLockingClause().

◆ constructSetOpTargetlist()

void constructSetOpTargetlist ( ParseState pstate,
SetOperationStmt op,
const List ltargetlist,
const List rtargetlist,
List **  targetlist,
const char context,
bool  recursive 
)

Definition at line 2605 of file analyze.c.

2608{
2609 ListCell *ltl;
2610 ListCell *rtl;
2611
2612 /*
2613 * Verify that the two children have the same number of non-junk columns,
2614 * and determine the types of the merged output columns.
2615 */
2617 ereport(ERROR,
2619 errmsg("each %s query must have the same number of columns",
2620 context),
2621 parser_errposition(pstate,
2622 exprLocation((const Node *) rtargetlist))));
2623
2624 if (targetlist)
2625 *targetlist = NIL;
2626 op->colTypes = NIL;
2627 op->colTypmods = NIL;
2628 op->colCollations = NIL;
2629 op->groupClauses = NIL;
2630
2632 {
2635 Node *lcolnode = (Node *) ltle->expr;
2636 Node *rcolnode = (Node *) rtle->expr;
2639 Node *bestexpr;
2640 int bestlocation;
2644
2645 /* select common type, same as CASE et al */
2648 context,
2649 &bestexpr);
2651
2652 /*
2653 * Verify the coercions are actually possible. If not, we'd fail
2654 * later anyway, but we want to fail now while we have sufficient
2655 * context to produce an error cursor position.
2656 *
2657 * For all non-UNKNOWN-type cases, we verify coercibility but we don't
2658 * modify the child's expression, for fear of changing the child
2659 * query's semantics.
2660 *
2661 * If a child expression is an UNKNOWN-type Const or Param, we want to
2662 * replace it with the coerced expression. This can only happen when
2663 * the child is a leaf set-op node. It's safe to replace the
2664 * expression because if the child query's semantics depended on the
2665 * type of this output column, it'd have already coerced the UNKNOWN
2666 * to something else. We want to do this because (a) we want to
2667 * verify that a Const is valid for the target type, or resolve the
2668 * actual type of an UNKNOWN Param, and (b) we want to avoid
2669 * unnecessary discrepancies between the output type of the child
2670 * query and the resolved target type. Such a discrepancy would
2671 * disable optimization in the planner.
2672 *
2673 * If it's some other UNKNOWN-type node, eg a Var, we do nothing
2674 * (knowing that coerce_to_common_type would fail). The planner is
2675 * sometimes able to fold an UNKNOWN Var to a constant before it has
2676 * to coerce the type, so failing now would just break cases that
2677 * might work.
2678 */
2679 if (lcoltype != UNKNOWNOID)
2681 rescoltype, context);
2682 else if (IsA(lcolnode, Const) ||
2683 IsA(lcolnode, Param))
2684 {
2686 rescoltype, context);
2687 ltle->expr = (Expr *) lcolnode;
2688 }
2689
2690 if (rcoltype != UNKNOWNOID)
2692 rescoltype, context);
2693 else if (IsA(rcolnode, Const) ||
2694 IsA(rcolnode, Param))
2695 {
2697 rescoltype, context);
2698 rtle->expr = (Expr *) rcolnode;
2699 }
2700
2703 rescoltype);
2704
2705 /*
2706 * Select common collation. A common collation is required for all
2707 * set operators except UNION ALL; see SQL:2008 7.13 <query
2708 * expression> Syntax Rule 15c. (If we fail to identify a common
2709 * collation for a UNION ALL column, the colCollations element will be
2710 * set to InvalidOid, which may result in a runtime error if something
2711 * at a higher query level wants to use the column's collation.)
2712 */
2715 (op->op == SETOP_UNION && op->all));
2716
2717 /* emit results */
2718 op->colTypes = lappend_oid(op->colTypes, rescoltype);
2719 op->colTypmods = lappend_int(op->colTypmods, rescoltypmod);
2720 op->colCollations = lappend_oid(op->colCollations, rescolcoll);
2721
2722 /*
2723 * For all cases except UNION ALL, identify the grouping operators
2724 * (and, if available, sorting operators) that will be used to
2725 * eliminate duplicates.
2726 */
2727 if (op->op != SETOP_UNION || !op->all)
2728 {
2730
2732 bestlocation);
2733
2734 /* If it's a recursive union, we need to require hashing support. */
2735 op->groupClauses = lappend(op->groupClauses,
2737
2739 }
2740
2741 /*
2742 * Construct a dummy tlist entry to return. We use a SetToDefault
2743 * node for the expression, since it carries exactly the fields
2744 * needed, but any other expression node type would do as well.
2745 */
2746 if (targetlist)
2747 {
2750
2751 rescolnode->typeId = rescoltype;
2752 rescolnode->typeMod = rescoltypmod;
2753 rescolnode->collation = rescolcoll;
2754 rescolnode->location = bestlocation;
2756 0, /* no need to set resno */
2757 NULL,
2758 false);
2759 *targetlist = lappend(*targetlist, restle);
2760 }
2761 }
2762}
int32_t int32
Definition c.h:620
List * lappend_int(List *list, int datum)
Definition list.c:357
List * lappend_oid(List *list, Oid datum)
Definition list.c:375
Oid exprType(const Node *expr)
Definition nodeFuncs.c:42
int exprLocation(const Node *expr)
Definition nodeFuncs.c:1403
#define IsA(nodeptr, _type_)
Definition nodes.h:164
Node * coerce_to_common_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *context)
int32 select_common_typmod(ParseState *pstate, List *exprs, Oid common_type)
Oid select_common_type(ParseState *pstate, List *exprs, const char *context, Node **which_expr)
Oid select_common_collation(ParseState *pstate, List *exprs, bool none_ok)
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition parse_node.c:156
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
@ SETOP_UNION
SortGroupClause * makeSortGroupClauseForSetOp(Oid rescoltype, bool require_hash)
Definition analyze.c:2373
#define lfirst(lc)
Definition pg_list.h:172
#define forboth(cell1, list1, cell2, list2)
Definition pg_list.h:550
#define list_make2(x1, x2)
Definition pg_list.h:246
unsigned int Oid
Definition nodes.h:135
SetOperation op

References SetOperationStmt::all, cancel_parser_errposition_callback(), coerce_to_common_type(), ereport, errcode(), errmsg, ERROR, exprLocation(), exprType(), fb(), forboth, IsA, lappend(), lappend_int(), lappend_oid(), lfirst, list_length(), list_make2, makeNode, makeSortGroupClauseForSetOp(), makeTargetEntry(), NIL, SetOperationStmt::op, parser_errposition(), select_common_collation(), select_common_type(), select_common_typmod(), SETOP_UNION, and setup_parser_errposition_callback().

Referenced by generate_setop_from_pathqueries(), and transformSetOperationTree().

◆ count_rowexpr_columns()

static int count_rowexpr_columns ( ParseState pstate,
Node expr 
)
static

Definition at line 1694 of file analyze.c.

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}
int16 AttrNumber
Definition attnum.h:21
TargetEntry * get_tle_by_resno(List *tlist, AttrNumber resno)
RangeTblEntry * GetRTEByRangeTablePosn(ParseState *pstate, int varno, int sublevels_up)
@ RTE_SUBQUERY
int16 attnum
AttrNumber varattno
Definition primnodes.h:275
int varno
Definition primnodes.h:270
Index varlevelsup
Definition primnodes.h:295

References attnum, fb(), get_tle_by_resno(), GetRTEByRangeTablePosn(), IsA, list_length(), RTE_SUBQUERY, Var::varattno, Var::varlevelsup, and Var::varno.

Referenced by transformInsertRow().

◆ determineRecursiveColTypes()

static void determineRecursiveColTypes ( ParseState pstate,
Node larg,
List nrtargetlist 
)
static

Definition at line 2769 of file analyze.c.

2770{
2771 Node *node;
2772 int leftmostRTI;
2774 List *targetList;
2776 ListCell *nrtl;
2777 int next_resno;
2778
2779 /*
2780 * Find leftmost leaf SELECT
2781 */
2782 node = larg;
2783 while (node && IsA(node, SetOperationStmt))
2784 node = ((SetOperationStmt *) node)->larg;
2785 Assert(node && IsA(node, RangeTblRef));
2786 leftmostRTI = ((RangeTblRef *) node)->rtindex;
2787 leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
2789
2790 /*
2791 * Generate dummy targetlist using column names of leftmost select and
2792 * dummy result expressions of the non-recursive term.
2793 */
2794 targetList = NIL;
2795 next_resno = 1;
2796
2798 {
2801 char *colName;
2803
2804 Assert(!lefttle->resjunk);
2805 colName = pstrdup(lefttle->resname);
2806 tle = makeTargetEntry(nrtle->expr,
2807 next_resno++,
2808 colName,
2809 false);
2810 targetList = lappend(targetList, tle);
2811 }
2812
2813 /* Now build CTE's output column info using dummy targetlist */
2814 analyzeCTETargetList(pstate, pstate->p_parent_cte, targetList);
2815}
void analyzeCTETargetList(ParseState *pstate, CommonTableExpr *cte, List *tlist)
Definition parse_cte.c:571
#define rt_fetch(rangetable_index, rangetable)
Definition parsetree.h:31
CommonTableExpr * p_parent_cte
Definition parse_node.h:227
List * p_rtable
Definition parse_node.h:215

References analyzeCTETargetList(), Assert, fb(), forboth, IsA, lappend(), lfirst, makeTargetEntry(), NIL, ParseState::p_parent_cte, ParseState::p_rtable, pstrdup(), and rt_fetch.

Referenced by transformSetOperationTree().

◆ LCS_asString()

const char * LCS_asString ( LockClauseStrength  strength)

Definition at line 3716 of file analyze.c.

3717{
3718 switch (strength)
3719 {
3720 case LCS_NONE:
3721 Assert(false);
3722 break;
3723 case LCS_FORKEYSHARE:
3724 return "FOR KEY SHARE";
3725 case LCS_FORSHARE:
3726 return "FOR SHARE";
3727 case LCS_FORNOKEYUPDATE:
3728 return "FOR NO KEY UPDATE";
3729 case LCS_FORUPDATE:
3730 return "FOR UPDATE";
3731 }
3732 return "FOR some"; /* shouldn't happen */
3733}
@ LCS_FORUPDATE
Definition lockoptions.h:28
@ LCS_FORSHARE
Definition lockoptions.h:26
@ LCS_FORKEYSHARE
Definition lockoptions.h:25
@ LCS_FORNOKEYUPDATE
Definition lockoptions.h:27

References Assert, LCS_FORKEYSHARE, LCS_FORNOKEYUPDATE, LCS_FORSHARE, LCS_FORUPDATE, and LCS_NONE.

Referenced by CheckSelectLocking(), grouping_planner(), make_outerjoininfo(), transformDeclareCursorStmt(), transformLockingClause(), transformSetOperationStmt(), transformSetOperationTree(), and transformValuesClause().

◆ makeSortGroupClauseForSetOp()

SortGroupClause * makeSortGroupClauseForSetOp ( Oid  rescoltype,
bool  require_hash 
)

Definition at line 2373 of file analyze.c.

2374{
2376 Oid sortop;
2377 Oid eqop;
2378 bool hashable;
2379
2380 /* determine the eqop and optional sortop */
2382 false, true, false,
2383 &sortop, &eqop, NULL,
2384 &hashable);
2385
2386 /*
2387 * The type cache doesn't believe that record is hashable (see
2388 * cache_record_field_properties()), but if the caller really needs hash
2389 * support, we can assume it does. Worst case, if any components of the
2390 * record don't support hashing, we will fail at execution.
2391 */
2393 hashable = true;
2394
2395 /* we don't have a tlist yet, so can't assign sortgrouprefs */
2396 grpcl->tleSortGroupRef = 0;
2397 grpcl->eqop = eqop;
2398 grpcl->sortop = sortop;
2399 grpcl->reverse_sort = false; /* Sort-op is "less than", or InvalidOid */
2400 grpcl->nulls_first = false; /* OK with or without sortop */
2401 grpcl->hashable = hashable;
2402
2403 return grpcl;
2404}
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

References fb(), get_sort_group_operators(), and makeNode.

Referenced by constructSetOpTargetlist(), and rewriteSearchAndCycle().

◆ parse_analyze_fixedparams()

Query * parse_analyze_fixedparams ( RawStmt parseTree,
const char sourceText,
const Oid paramTypes,
int  numParams,
QueryEnvironment queryEnv 
)

Definition at line 127 of file analyze.c.

130{
132 Query *query;
134
135 Assert(sourceText != NULL); /* required as of 8.4 */
136
137 pstate->p_sourcetext = sourceText;
138
139 if (numParams > 0)
140 setup_parse_fixed_parameters(pstate, paramTypes, numParams);
141
142 pstate->p_queryEnv = queryEnv;
143
144 query = transformTopLevelStmt(pstate, parseTree);
145
146 if (IsQueryIdEnabled())
147 jstate = JumbleQuery(query);
148
150 (*post_parse_analyze_hook) (pstate, query, jstate);
151
152 free_parsestate(pstate);
153
154 pgstat_report_query_id(query->queryId, false);
155
156 return query;
157}
void pgstat_report_query_id(int64 query_id, bool force)
void free_parsestate(ParseState *pstate)
Definition parse_node.c:72
ParseState * make_parsestate(ParseState *parentParseState)
Definition parse_node.c:39
void setup_parse_fixed_parameters(ParseState *pstate, const Oid *paramTypes, int numParams)
Definition parse_param.c:68
post_parse_analyze_hook_type post_parse_analyze_hook
Definition analyze.c:74
Query * transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree)
Definition analyze.c:271
static bool IsQueryIdEnabled(void)
JumbleState * JumbleQuery(Query *query)
QueryEnvironment * p_queryEnv
Definition parse_node.h:241
const char * p_sourcetext
Definition parse_node.h:214

References Assert, fb(), free_parsestate(), IsQueryIdEnabled(), JumbleQuery(), make_parsestate(), ParseState::p_queryEnv, ParseState::p_sourcetext, pgstat_report_query_id(), post_parse_analyze_hook, setup_parse_fixed_parameters(), and transformTopLevelStmt().

Referenced by DefineView(), and pg_analyze_and_rewrite_fixedparams().

◆ parse_analyze_varparams()

Query * parse_analyze_varparams ( RawStmt parseTree,
const char sourceText,
Oid **  paramTypes,
int numParams,
QueryEnvironment queryEnv 
)

Definition at line 167 of file analyze.c.

170{
172 Query *query;
174
175 Assert(sourceText != NULL); /* required as of 8.4 */
176
177 pstate->p_sourcetext = sourceText;
178
179 setup_parse_variable_parameters(pstate, paramTypes, numParams);
180
181 pstate->p_queryEnv = queryEnv;
182
183 query = transformTopLevelStmt(pstate, parseTree);
184
185 /* make sure all is well with parameter types */
186 check_variable_parameters(pstate, query);
187
188 if (IsQueryIdEnabled())
189 jstate = JumbleQuery(query);
190
192 (*post_parse_analyze_hook) (pstate, query, jstate);
193
194 free_parsestate(pstate);
195
196 pgstat_report_query_id(query->queryId, false);
197
198 return query;
199}
void check_variable_parameters(ParseState *pstate, Query *query)
void setup_parse_variable_parameters(ParseState *pstate, Oid **paramTypes, int *numParams)
Definition parse_param.c:84

References Assert, check_variable_parameters(), fb(), free_parsestate(), IsQueryIdEnabled(), JumbleQuery(), make_parsestate(), ParseState::p_queryEnv, ParseState::p_sourcetext, pgstat_report_query_id(), post_parse_analyze_hook, setup_parse_variable_parameters(), and transformTopLevelStmt().

Referenced by pg_analyze_and_rewrite_varparams().

◆ parse_analyze_withcb()

Query * parse_analyze_withcb ( RawStmt parseTree,
const char sourceText,
ParserSetupHook  parserSetup,
void parserSetupArg,
QueryEnvironment queryEnv 
)

Definition at line 208 of file analyze.c.

212{
214 Query *query;
216
217 Assert(sourceText != NULL); /* required as of 8.4 */
218
219 pstate->p_sourcetext = sourceText;
220 pstate->p_queryEnv = queryEnv;
221 (*parserSetup) (pstate, parserSetupArg);
222
223 query = transformTopLevelStmt(pstate, parseTree);
224
225 if (IsQueryIdEnabled())
226 jstate = JumbleQuery(query);
227
229 (*post_parse_analyze_hook) (pstate, query, jstate);
230
231 free_parsestate(pstate);
232
233 pgstat_report_query_id(query->queryId, false);
234
235 return query;
236}

References Assert, fb(), free_parsestate(), IsQueryIdEnabled(), JumbleQuery(), make_parsestate(), ParseState::p_queryEnv, ParseState::p_sourcetext, pgstat_report_query_id(), post_parse_analyze_hook, and transformTopLevelStmt().

Referenced by pg_analyze_and_rewrite_withcb().

◆ parse_sub_analyze()

Query * parse_sub_analyze ( Node parseTree,
ParseState parentParseState,
CommonTableExpr parentCTE,
bool  locked_from_parent,
bool  resolve_unknowns 
)

Definition at line 244 of file analyze.c.

248{
249 ParseState *pstate = make_parsestate(parentParseState);
250 Query *query;
251
252 pstate->p_parent_cte = parentCTE;
255
256 query = transformStmt(pstate, parseTree);
257
258 free_parsestate(pstate);
259
260 return query;
261}
Query * transformStmt(ParseState *pstate, Node *parseTree)
Definition analyze.c:334
bool p_locked_from_parent
Definition parse_node.h:236
bool p_resolve_unknowns
Definition parse_node.h:238

References fb(), free_parsestate(), make_parsestate(), ParseState::p_locked_from_parent, ParseState::p_parent_cte, ParseState::p_resolve_unknowns, and transformStmt().

Referenced by analyzeCTE(), transformRangeSubselect(), transformSetOperationTree(), and transformSubLink().

◆ query_requires_rewrite_plan()

bool query_requires_rewrite_plan ( Query query)

Definition at line 542 of file analyze.c.

543{
544 bool result;
545
546 if (query->commandType != CMD_UTILITY)
547 {
548 /* All optimizable statements require rewriting/planning */
549 result = true;
550 }
551 else
552 {
553 /* This list should match stmt_requires_parse_analysis() */
554 switch (nodeTag(query->utilityStmt))
555 {
557 case T_ExplainStmt:
559 case T_CallStmt:
560 result = true;
561 break;
562 default:
563 result = false;
564 break;
565 }
566 }
567 return result;
568}
#define nodeTag(nodeptr)
Definition nodes.h:139
@ CMD_UTILITY
Definition nodes.h:280
CmdType commandType
Definition parsenodes.h:121
Node * utilityStmt
Definition parsenodes.h:141

References CMD_UTILITY, Query::commandType, fb(), nodeTag, result, and Query::utilityStmt.

Referenced by BuildingPlanRequiresSnapshot(), and StmtPlanRequiresRevalidation().

◆ stmt_requires_parse_analysis()

bool stmt_requires_parse_analysis ( RawStmt parseTree)

Definition at line 469 of file analyze.c.

470{
471 bool result;
472
473 switch (nodeTag(parseTree->stmt))
474 {
475 /*
476 * Optimizable statements
477 */
478 case T_InsertStmt:
479 case T_DeleteStmt:
480 case T_UpdateStmt:
481 case T_MergeStmt:
482 case T_SelectStmt:
483 case T_ReturnStmt:
484 case T_PLAssignStmt:
485 result = true;
486 break;
487
488 /*
489 * Special cases
490 */
492 case T_ExplainStmt:
494 case T_CallStmt:
495 result = true;
496 break;
497
498 default:
499 /* all other statements just get wrapped in a CMD_UTILITY Query */
500 result = false;
501 break;
502 }
503
504 return result;
505}

References fb(), nodeTag, and result.

Referenced by analyze_requires_snapshot(), and StmtPlanRequiresRevalidation().

◆ transformCallStmt()

static Query * transformCallStmt ( ParseState pstate,
CallStmt stmt 
)
static

Definition at line 3591 of file analyze.c.

3592{
3593 List *targs;
3594 ListCell *lc;
3595 Node *node;
3596 FuncExpr *fexpr;
3599 bool isNull;
3600 List *outargs = NIL;
3601 Query *result;
3602
3603 /*
3604 * First, do standard parse analysis on the procedure call and its
3605 * arguments, allowing us to identify the called procedure.
3606 */
3607 targs = NIL;
3608 foreach(lc, stmt->funccall->args)
3609 {
3610 targs = lappend(targs, transformExpr(pstate,
3611 (Node *) lfirst(lc),
3613 }
3614
3615 node = ParseFuncOrColumn(pstate,
3616 stmt->funccall->funcname,
3617 targs,
3618 pstate->p_last_srf,
3619 stmt->funccall,
3620 true,
3621 stmt->funccall->location);
3622
3623 assign_expr_collations(pstate, node);
3624
3625 fexpr = castNode(FuncExpr, node);
3626
3629 elog(ERROR, "cache lookup failed for function %u", fexpr->funcid);
3630
3631 /*
3632 * Expand the argument list to deal with named-argument notation and
3633 * default arguments. For ordinary FuncExprs this'd be done during
3634 * planning, but a CallStmt doesn't go through planning, and there seems
3635 * no good reason not to do it here.
3636 */
3638 true,
3639 fexpr->funcresulttype,
3640 proctup);
3641
3642 /* Fetch proargmodes; if it's null, there are no output args */
3645 &isNull);
3646 if (!isNull)
3647 {
3648 /*
3649 * Split the list into input arguments in fexpr->args and output
3650 * arguments in stmt->outargs. INOUT arguments appear in both lists.
3651 */
3652 ArrayType *arr;
3653 int numargs;
3654 char *argmodes;
3655 List *inargs;
3656 int i;
3657
3658 arr = DatumGetArrayTypeP(proargmodes); /* ensure not toasted */
3659 numargs = list_length(fexpr->args);
3660 if (ARR_NDIM(arr) != 1 ||
3661 ARR_DIMS(arr)[0] != numargs ||
3662 ARR_HASNULL(arr) ||
3663 ARR_ELEMTYPE(arr) != CHAROID)
3664 elog(ERROR, "proargmodes is not a 1-D char array of length %d or it contains nulls",
3665 numargs);
3666 argmodes = (char *) ARR_DATA_PTR(arr);
3667
3668 inargs = NIL;
3669 i = 0;
3670 foreach(lc, fexpr->args)
3671 {
3672 Node *n = lfirst(lc);
3673
3674 switch (argmodes[i])
3675 {
3676 case PROARGMODE_IN:
3678 inargs = lappend(inargs, n);
3679 break;
3680 case PROARGMODE_OUT:
3681 outargs = lappend(outargs, n);
3682 break;
3683 case PROARGMODE_INOUT:
3684 inargs = lappend(inargs, n);
3685 outargs = lappend(outargs, copyObject(n));
3686 break;
3687 default:
3688 /* note we don't support PROARGMODE_TABLE */
3689 elog(ERROR, "invalid argmode %c for procedure",
3690 argmodes[i]);
3691 break;
3692 }
3693 i++;
3694 }
3695 fexpr->args = inargs;
3696 }
3697
3698 stmt->funcexpr = fexpr;
3699 stmt->outargs = outargs;
3700
3702
3703 /* represent the command as a utility Query */
3705 result->commandType = CMD_UTILITY;
3706 result->utilityStmt = (Node *) stmt;
3707
3708 return result;
3709}
#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
List * expand_function_arguments(List *args, bool include_out_arguments, Oid result_type, HeapTuple func_tuple)
Definition clauses.c:4930
#define elog(elevel,...)
Definition elog.h:228
#define HeapTupleIsValid(tuple)
Definition htup.h:78
#define stmt
#define copyObject(obj)
Definition nodes.h:232
#define castNode(_type_, nodeptr)
Definition nodes.h:182
void assign_expr_collations(ParseState *pstate, Node *expr)
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition parse_expr.c:121
Node * ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs, Node *last_srf, FuncCall *fn, bool proc_call, int location)
Definition parse_func.c:92
@ EXPR_KIND_CALL_ARGUMENT
Definition parse_node.h:82
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
uint64_t Datum
Definition postgres.h:70
Node * p_last_srf
Definition parse_node.h:252
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

References ARR_DATA_PTR, ARR_DIMS, ARR_ELEMTYPE, ARR_HASNULL, ARR_NDIM, assign_expr_collations(), castNode, CMD_UTILITY, copyObject, DatumGetArrayTypeP, elog, ERROR, expand_function_arguments(), EXPR_KIND_CALL_ARGUMENT, fb(), HeapTupleIsValid, i, lappend(), lfirst, list_length(), makeNode, NIL, ObjectIdGetDatum(), ParseState::p_last_srf, ParseFuncOrColumn(), ReleaseSysCache(), result, SearchSysCache1(), stmt, SysCacheGetAttr(), and transformExpr().

Referenced by transformStmt().

◆ transformCreateTableAsStmt()

static Query * transformCreateTableAsStmt ( ParseState pstate,
CreateTableAsStmt stmt 
)
static

Definition at line 3512 of file analyze.c.

3513{
3514 Query *result;
3515 Query *query;
3516
3517 /* transform contained query, not allowing SELECT INTO */
3518 query = transformStmt(pstate, stmt->query);
3519 stmt->query = (Node *) query;
3520
3521 /* additional work needed for CREATE MATERIALIZED VIEW */
3522 if (stmt->objtype == OBJECT_MATVIEW)
3523 {
3525
3526 /*
3527 * Prohibit a data-modifying CTE in the query used to create a
3528 * materialized view. It's not sufficiently clear what the user would
3529 * want to happen if the MV is refreshed or incrementally maintained.
3530 */
3531 if (query->hasModifyingCTE)
3532 ereport(ERROR,
3534 errmsg("materialized views must not use data-modifying statements in WITH")));
3535
3536 /*
3537 * Check whether any temporary database objects are used in the
3538 * creation query. It would be hard to refresh data or incrementally
3539 * maintain it if a source disappeared.
3540 */
3542 ereport(ERROR,
3544 errmsg("materialized views must not use temporary objects"),
3545 errdetail("This view depends on temporary %s.",
3547
3548 /*
3549 * A materialized view would either need to save parameters for use in
3550 * maintaining/loading the data or prohibit them entirely. The latter
3551 * seems safer and more sane.
3552 */
3554 ereport(ERROR,
3556 errmsg("materialized views may not be defined using bound parameters")));
3557
3558 /*
3559 * For now, we disallow unlogged materialized views, because it seems
3560 * like a bad idea for them to just go to empty after a crash. (If we
3561 * could mark them as unpopulated, that would be better, but that
3562 * requires catalog changes which crash recovery can't presently
3563 * handle.)
3564 */
3565 if (stmt->into->rel->relpersistence == RELPERSISTENCE_UNLOGGED)
3566 ereport(ERROR,
3568 errmsg("materialized views cannot be unlogged")));
3569
3570 /*
3571 * At runtime, we'll need a copy of the parsed-but-not-rewritten Query
3572 * for purposes of creating the view's ON SELECT rule. We stash that
3573 * in the IntoClause because that's where intorel_startup() can
3574 * conveniently get it from.
3575 */
3576 stmt->into->viewQuery = copyObject(query);
3577 }
3578
3579 /* represent the command as a utility Query */
3581 result->commandType = CMD_UTILITY;
3582 result->utilityStmt = (Node *) stmt;
3583
3584 return result;
3585}
bool query_uses_temp_object(Query *query, ObjectAddress *temp_object)
int errdetail(const char *fmt,...) pg_attribute_printf(1
char * getObjectDescription(const ObjectAddress *object, bool missing_ok)
bool query_contains_extern_params(Query *query)
@ OBJECT_MATVIEW

References CMD_UTILITY, copyObject, ereport, errcode(), errdetail(), errmsg, ERROR, fb(), getObjectDescription(), makeNode, OBJECT_MATVIEW, query_contains_extern_params(), query_uses_temp_object(), result, stmt, and transformStmt().

Referenced by transformStmt().

◆ transformDeclareCursorStmt()

static Query * transformDeclareCursorStmt ( ParseState pstate,
DeclareCursorStmt stmt 
)
static

Definition at line 3367 of file analyze.c.

3368{
3369 Query *result;
3370 Query *query;
3371
3372 if ((stmt->options & CURSOR_OPT_SCROLL) &&
3373 (stmt->options & CURSOR_OPT_NO_SCROLL))
3374 ereport(ERROR,
3376 /* translator: %s is a SQL keyword */
3377 errmsg("cannot specify both %s and %s",
3378 "SCROLL", "NO SCROLL")));
3379
3380 if ((stmt->options & CURSOR_OPT_ASENSITIVE) &&
3381 (stmt->options & CURSOR_OPT_INSENSITIVE))
3382 ereport(ERROR,
3384 /* translator: %s is a SQL keyword */
3385 errmsg("cannot specify both %s and %s",
3386 "ASENSITIVE", "INSENSITIVE")));
3387
3388 /* Transform contained query, not allowing SELECT INTO */
3389 query = transformStmt(pstate, stmt->query);
3390 stmt->query = (Node *) query;
3391
3392 /* Grammar should not have allowed anything but SELECT */
3393 if (!IsA(query, Query) ||
3394 query->commandType != CMD_SELECT)
3395 elog(ERROR, "unexpected non-SELECT command in DECLARE CURSOR");
3396
3397 /*
3398 * We also disallow data-modifying WITH in a cursor. (This could be
3399 * allowed, but the semantics of when the updates occur might be
3400 * surprising.)
3401 */
3402 if (query->hasModifyingCTE)
3403 ereport(ERROR,
3405 errmsg("DECLARE CURSOR must not contain data-modifying statements in WITH")));
3406
3407 /* FOR UPDATE and WITH HOLD are not compatible */
3408 if (query->rowMarks != NIL && (stmt->options & CURSOR_OPT_HOLD))
3409 ereport(ERROR,
3411 /*------
3412 translator: %s is a SQL row locking clause such as FOR UPDATE */
3413 errmsg("DECLARE CURSOR WITH HOLD ... %s is not supported",
3415 linitial(query->rowMarks))->strength)),
3416 errdetail("Holdable cursors must be READ ONLY.")));
3417
3418 /* FOR UPDATE and SCROLL are not compatible */
3419 if (query->rowMarks != NIL && (stmt->options & CURSOR_OPT_SCROLL))
3420 ereport(ERROR,
3422 /*------
3423 translator: %s is a SQL row locking clause such as FOR UPDATE */
3424 errmsg("DECLARE SCROLL CURSOR ... %s is not supported",
3426 linitial(query->rowMarks))->strength)),
3427 errdetail("Scrollable cursors must be READ ONLY.")));
3428
3429 /* FOR UPDATE and INSENSITIVE are not compatible */
3430 if (query->rowMarks != NIL && (stmt->options & CURSOR_OPT_INSENSITIVE))
3431 ereport(ERROR,
3433 /*------
3434 translator: %s is a SQL row locking clause such as FOR UPDATE */
3435 errmsg("DECLARE INSENSITIVE CURSOR ... %s is not valid",
3437 linitial(query->rowMarks))->strength)),
3438 errdetail("Insensitive cursors must be READ ONLY.")));
3439
3440 /* represent the command as a utility Query */
3442 result->commandType = CMD_UTILITY;
3443 result->utilityStmt = (Node *) stmt;
3444
3445 return result;
3446}
@ CMD_SELECT
Definition nodes.h:275
#define CURSOR_OPT_INSENSITIVE
#define CURSOR_OPT_SCROLL
#define CURSOR_OPT_HOLD
#define CURSOR_OPT_ASENSITIVE
#define CURSOR_OPT_NO_SCROLL
#define linitial(l)
Definition pg_list.h:178

References CMD_SELECT, CMD_UTILITY, Query::commandType, CURSOR_OPT_ASENSITIVE, CURSOR_OPT_HOLD, CURSOR_OPT_INSENSITIVE, CURSOR_OPT_NO_SCROLL, CURSOR_OPT_SCROLL, elog, ereport, errcode(), errdetail(), errmsg, ERROR, fb(), IsA, LCS_asString(), linitial, makeNode, NIL, result, Query::rowMarks, stmt, and transformStmt().

Referenced by transformStmt().

◆ transformDeleteStmt()

static Query * transformDeleteStmt ( ParseState pstate,
DeleteStmt stmt 
)
static

Definition at line 575 of file analyze.c.

576{
577 Query *qry = makeNode(Query);
579 Node *qual;
580
581 qry->commandType = CMD_DELETE;
582
583 /* process the WITH clause independently of all else */
584 if (stmt->withClause)
585 {
586 qry->hasRecursive = stmt->withClause->recursive;
587 qry->cteList = transformWithClause(pstate, stmt->withClause);
588 qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
589 }
590
591 /* set up range table with just the result rel */
592 qry->resultRelation = setTargetTable(pstate, stmt->relation,
593 stmt->relation->inh,
594 true,
595 ACL_DELETE);
596 nsitem = pstate->p_target_nsitem;
597
598 /* disallow DELETE ... WHERE CURRENT OF on a view */
599 if (stmt->whereClause &&
600 IsA(stmt->whereClause, CurrentOfExpr) &&
601 pstate->p_target_relation->rd_rel->relkind == RELKIND_VIEW)
604 errmsg("WHERE CURRENT OF on a view is not implemented"));
605
606 /* there's no DISTINCT in DELETE */
607 qry->distinctClause = NIL;
608
609 /* subqueries in USING cannot access the result relation */
610 nsitem->p_lateral_only = true;
611 nsitem->p_lateral_ok = false;
612
613 /*
614 * The USING clause is non-standard SQL syntax, and is equivalent in
615 * functionality to the FROM list that can be specified for UPDATE. The
616 * USING keyword is used rather than FROM because FROM is already a
617 * keyword in the DELETE syntax.
618 */
619 transformFromClause(pstate, stmt->usingClause);
620
621 /* remaining clauses can reference the result relation normally */
622 nsitem->p_lateral_only = false;
623 nsitem->p_lateral_ok = true;
624
625 if (stmt->forPortionOf)
627 qry->resultRelation,
629 false);
630
631 qual = transformWhereClause(pstate, stmt->whereClause,
632 EXPR_KIND_WHERE, "WHERE");
633
634 transformReturningClause(pstate, qry, stmt->returningClause,
636
637 /* done building the range table and jointree */
638 qry->rtable = pstate->p_rtable;
639 qry->rteperminfos = pstate->p_rteperminfos;
640 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
641
642 qry->hasSubLinks = pstate->p_hasSubLinks;
643 qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
644 qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
645 qry->hasAggs = pstate->p_hasAggs;
646
647 assign_query_collations(pstate, qry);
648
649 /* this must be done after collations, for reliable comparison of exprs */
650 if (pstate->p_hasAggs)
651 parseCheckAggregates(pstate, qry);
652
653 return qry;
654}
FromExpr * makeFromExpr(List *fromlist, Node *quals)
Definition makefuncs.c:336
@ CMD_DELETE
Definition nodes.h:278
void parseCheckAggregates(ParseState *pstate, Query *qry)
Definition parse_agg.c:1160
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
void transformFromClause(ParseState *pstate, List *frmList)
int setTargetTable(ParseState *pstate, RangeVar *relation, bool inh, bool alsoSource, AclMode requiredPerms)
void assign_query_collations(ParseState *pstate, Query *query)
List * transformWithClause(ParseState *pstate, WithClause *withClause)
Definition parse_cte.c:110
@ EXPR_KIND_WHERE
Definition parse_node.h:46
@ EXPR_KIND_RETURNING
Definition parse_node.h:65
#define ACL_DELETE
Definition parsenodes.h:79
static ForPortionOfExpr * transformForPortionOfClause(ParseState *pstate, int rtindex, const ForPortionOfClause *forPortionOf, bool isUpdate)
Definition analyze.c:1319
void transformReturningClause(ParseState *pstate, Query *qry, ReturningClause *returningClause, ParseExprKind exprKind)
Definition analyze.c:3063
bool p_hasTargetSRFs
Definition parse_node.h:248
bool p_hasWindowFuncs
Definition parse_node.h:247
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
bool p_hasSubLinks
Definition parse_node.h:249
List * p_joinlist
Definition parse_node.h:220
bool p_hasAggs
Definition parse_node.h:246
FromExpr * jointree
Definition parsenodes.h:185
List * cteList
Definition parsenodes.h:176
ForPortionOfExpr * forPortionOf
Definition parsenodes.h:151
List * rtable
Definition parsenodes.h:178
Form_pg_class rd_rel
Definition rel.h:111

References ACL_DELETE, assign_query_collations(), CMD_DELETE, Query::commandType, Query::cteList, Query::distinctClause, ereport, errcode(), errmsg, ERROR, EXPR_KIND_RETURNING, EXPR_KIND_WHERE, fb(), Query::forPortionOf, IsA, Query::jointree, makeFromExpr(), makeNode, NIL, ParseState::p_hasAggs, ParseState::p_hasModifyingCTE, ParseState::p_hasSubLinks, ParseState::p_hasTargetSRFs, ParseState::p_hasWindowFuncs, ParseState::p_joinlist, ParseState::p_rtable, ParseState::p_rteperminfos, ParseState::p_target_nsitem, ParseState::p_target_relation, parseCheckAggregates(), RelationData::rd_rel, Query::rtable, setTargetTable(), stmt, transformForPortionOfClause(), transformFromClause(), transformReturningClause(), transformWhereClause(), and transformWithClause().

Referenced by transformStmt().

◆ transformExplainStmt()

static Query * transformExplainStmt ( ParseState pstate,
ExplainStmt stmt 
)
static

Definition at line 3460 of file analyze.c.

3461{
3462 Query *result;
3463 bool generic_plan = false;
3464 Oid *paramTypes = NULL;
3465 int numParams = 0;
3466
3467 /*
3468 * If we have no external source of parameter definitions, and the
3469 * GENERIC_PLAN option is specified, then accept variable parameter
3470 * definitions (similarly to PREPARE, for example).
3471 */
3472 if (pstate->p_paramref_hook == NULL)
3473 {
3474 ListCell *lc;
3475
3476 foreach(lc, stmt->options)
3477 {
3478 DefElem *opt = (DefElem *) lfirst(lc);
3479
3480 if (strcmp(opt->defname, "generic_plan") == 0)
3482 /* don't "break", as we want the last value */
3483 }
3484 if (generic_plan)
3485 setup_parse_variable_parameters(pstate, &paramTypes, &numParams);
3486 }
3487
3488 /* transform contained query, allowing SELECT INTO */
3489 stmt->query = (Node *) transformOptionalSelectInto(pstate, stmt->query);
3490
3491 /* make sure all is well with parameter types */
3492 if (generic_plan)
3493 check_variable_parameters(pstate, (Query *) stmt->query);
3494
3495 /* represent the command as a utility Query */
3497 result->commandType = CMD_UTILITY;
3498 result->utilityStmt = (Node *) stmt;
3499
3500 return result;
3501}
bool defGetBoolean(DefElem *def)
Definition define.c:93
static Query * transformOptionalSelectInto(ParseState *pstate, Node *parseTree)
Definition analyze.c:295
char * defname
Definition parsenodes.h:860
ParseParamRefHook p_paramref_hook
Definition parse_node.h:260

References check_variable_parameters(), CMD_UTILITY, defGetBoolean(), DefElem::defname, fb(), lfirst, makeNode, ParseState::p_paramref_hook, result, setup_parse_variable_parameters(), stmt, and transformOptionalSelectInto().

Referenced by transformStmt().

◆ transformForPortionOfClause()

static ForPortionOfExpr * transformForPortionOfClause ( ParseState pstate,
int  rtindex,
const ForPortionOfClause forPortionOf,
bool  isUpdate 
)
static

Definition at line 1319 of file analyze.c.

1323{
1326 Form_pg_attribute attr;
1328 Oid opclass;
1329 Oid opfamily;
1330 Oid opcintype;
1331 Oid funcid = InvalidOid;
1333 Oid opid;
1334 OpExpr *op;
1336 Var *rangeVar;
1337
1338 /* We don't support FOR PORTION OF FDW queries. */
1339 if (targetrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1340 ereport(ERROR,
1342 errmsg("foreign tables don't support FOR PORTION OF")));
1343
1345
1346 /* Look up the FOR PORTION OF name requested. */
1347 range_attno = attnameAttNum(targetrel, forPortionOf->range_name, false);
1349 ereport(ERROR,
1351 errmsg("column \"%s\" of relation \"%s\" does not exist",
1352 forPortionOf->range_name,
1354 parser_errposition(pstate, forPortionOf->location)));
1355 attr = TupleDescAttr(targetrel->rd_att, range_attno - 1);
1356
1357 attbasetype = getBaseType(attr->atttypid);
1358
1359 rangeVar = makeVar(rtindex,
1361 attr->atttypid,
1362 attr->atttypmod,
1363 attr->attcollation,
1364 0);
1365 rangeVar->location = forPortionOf->location;
1366 result->rangeVar = rangeVar;
1367
1368 /* Require SELECT privilege on the application-time column. */
1369 markVarForSelectPriv(pstate, rangeVar);
1370
1371 /*
1372 * Use the basetype for the target, which shouldn't be required to follow
1373 * domain rules. The table's column type is in the Var if we need it.
1374 */
1375 result->rangeType = attbasetype;
1376 result->isDomain = attbasetype != attr->atttypid;
1377
1378 if (forPortionOf->target)
1379 {
1382
1383 /*
1384 * We were already given an expression for the target, so we don't
1385 * have to build anything. We still have to make sure we got the right
1386 * type. NULL will be caught be the executor.
1387 */
1388
1389 result->targetRange = transformExpr(pstate,
1390 forPortionOf->target,
1392
1393 actual_target_type = exprType(result->targetRange);
1394
1396 ereport(ERROR,
1398 errmsg("could not coerce FOR PORTION OF target from %s to %s",
1401 parser_errposition(pstate, exprLocation(forPortionOf->target))));
1402
1403 result->targetRange = coerce_type(pstate,
1404 result->targetRange,
1407 -1,
1410 exprLocation(forPortionOf->target));
1411
1412 /*
1413 * XXX: For now we only support ranges and multiranges, so we fail on
1414 * anything else.
1415 */
1417 ereport(ERROR,
1419 errmsg("column \"%s\" of relation \"%s\" is not a range or multirange type",
1420 forPortionOf->range_name,
1422 parser_errposition(pstate, forPortionOf->location)));
1423
1424 }
1425 else
1426 {
1430 List *args;
1431
1432 /*
1433 * Make sure it's a range column. XXX: We could support this syntax on
1434 * multirange columns too, if we just built a one-range multirange
1435 * from the FROM/TO phrases.
1436 */
1438 ereport(ERROR,
1440 errmsg("column \"%s\" of relation \"%s\" is not a range type",
1441 forPortionOf->range_name,
1443 parser_errposition(pstate, forPortionOf->location)));
1444
1448
1449 /*
1450 * Build a range from the FROM ... TO ... bounds. This should give a
1451 * constant result, so we accept functions like NOW() but not column
1452 * references, subqueries, etc.
1453 */
1454 result->targetFrom = transformExpr(pstate,
1455 forPortionOf->target_start,
1457 result->targetTo = transformExpr(pstate,
1458 forPortionOf->target_end,
1460 actual_arg_types[0] = exprType(result->targetFrom);
1461 actual_arg_types[1] = exprType(result->targetTo);
1462 args = list_make2(copyObject(result->targetFrom),
1463 copyObject(result->targetTo));
1464
1465 /*
1466 * Check the bound types separately, for better error message and
1467 * location
1468 */
1470 ereport(ERROR,
1472 errmsg("could not coerce FOR PORTION OF %s bound from %s to %s",
1473 "FROM",
1476 parser_errposition(pstate, exprLocation(forPortionOf->target_start))));
1478 ereport(ERROR,
1480 errmsg("could not coerce FOR PORTION OF %s bound from %s to %s",
1481 "TO",
1484 parser_errposition(pstate, exprLocation(forPortionOf->target_end))));
1485
1489 args,
1491 }
1493 ereport(ERROR,
1494 (errmsg("FOR PORTION OF bounds cannot contain volatile functions")));
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}
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition bitmapset.c:799
#define OidIsValid(objectId)
Definition c.h:858
bool contain_volatile_functions_after_planning(Expr *expr)
Definition clauses.c:672
@ COMPARE_OVERLAP
Definition cmptype.h:40
int errhint(const char *fmt,...) pg_attribute_printf(1
char * format_type_be(Oid type_oid)
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition indexcmds.c:2371
void GetOperatorFromCompareType(Oid opclass, Oid rhstype, CompareType cmptype, Oid *opid, StrategyNumber *strat)
Definition indexcmds.c:2473
Oid get_range_subtype(Oid rangeOid)
Definition lsyscache.c:3735
RegProcedure get_range_constructor2(Oid rangeOid)
Definition lsyscache.c:3786
bool type_is_range(Oid typid)
Definition lsyscache.c:2996
bool get_opclass_opfamily_and_input_type(Oid opclass, Oid *opfamily, Oid *opcintype)
Definition lsyscache.c:1479
RegProcedure get_opcode(Oid opno)
Definition lsyscache.c:1577
Oid getBaseType(Oid typid)
Definition lsyscache.c:2829
bool type_is_multirange(Oid typid)
Definition lsyscache.c:3006
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Definition makefuncs.c:594
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
bool can_coerce_type(int nargs, const Oid *input_typeids, const Oid *target_typeids, CoercionContext ccontext)
void make_fn_arguments(ParseState *pstate, List *fargs, Oid *actual_arg_types, Oid *declared_arg_types)
@ EXPR_KIND_FOR_PORTION
Definition parse_node.h:59
void markVarForSelectPriv(ParseState *pstate, Var *var)
int attnameAttNum(Relation rd, const char *attname, bool sysColOK)
@ COERCE_IMPLICIT_CAST
Definition primnodes.h:769
@ COERCE_EXPLICIT_CALL
Definition primnodes.h:767
@ COERCION_IMPLICIT
Definition primnodes.h:747
#define RelationGetRelationName(relation)
Definition rel.h:550
uint16 StrategyNumber
Definition stratnum.h:22
ParseLoc target_location
Oid opno
Definition primnodes.h:851
List * args
Definition primnodes.h:869
ParseLoc location
Definition primnodes.h:311
#define FirstLowInvalidHeapAttributeNumber
Definition sysattr.h:27

References OpExpr::args, attnameAttNum(), bms_add_member(), can_coerce_type(), COERCE_EXPLICIT_CALL, COERCE_IMPLICIT_CAST, coerce_type(), COERCION_IMPLICIT, COMPARE_OVERLAP, contain_volatile_functions_after_planning(), copyObject, elog, ereport, errcode(), errhint(), errmsg, ERROR, EXPR_KIND_FOR_PORTION, exprLocation(), exprType(), fb(), FirstLowInvalidHeapAttributeNumber, format_type_be(), get_opclass_opfamily_and_input_type(), get_opcode(), get_range_constructor2(), get_range_subtype(), getBaseType(), GetDefaultOpClass(), GetOperatorFromCompareType(), InvalidAttrNumber, InvalidOid, lappend(), list_make2, ForPortionOfClause::location, Var::location, make_fn_arguments(), makeFuncExpr(), makeNode, makeTargetEntry(), makeVar(), markVarForSelectPriv(), NIL, OidIsValid, OpExpr::opno, ParseNamespaceItem::p_perminfo, ParseState::p_target_nsitem, ParseState::p_target_relation, parser_errposition(), ForPortionOfClause::range_name, RelationGetRelationName, result, ForPortionOfClause::target, ForPortionOfClause::target_end, ForPortionOfClause::target_location, ForPortionOfClause::target_start, transformExpr(), TupleDescAttr(), type_is_multirange(), and type_is_range().

Referenced by transformDeleteStmt(), and transformUpdateStmt().

◆ transformInsertRow()

List * transformInsertRow ( ParseState pstate,
List exprlist,
List stmtcols,
List icolumns,
List attrnos,
bool  strip_indirection 
)

Definition at line 1102 of file analyze.c.

1105{
1106 List *result;
1107 ListCell *lc;
1108 ListCell *icols;
1110
1111 /*
1112 * Check length of expr list. It must not have more expressions than
1113 * there are target columns. We allow fewer, but only if no explicit
1114 * columns list was given (the remaining columns are implicitly
1115 * defaulted). Note we must check this *after* transformation because
1116 * that could expand '*' into multiple items.
1117 */
1119 ereport(ERROR,
1121 errmsg("INSERT has more expressions than target columns"),
1122 parser_errposition(pstate,
1124 list_length(icolumns))))));
1125 if (stmtcols != NIL &&
1127 {
1128 /*
1129 * We can get here for cases like INSERT ... SELECT (a,b,c) FROM ...
1130 * where the user accidentally created a RowExpr instead of separate
1131 * columns. Add a suitable hint if that seems to be the problem,
1132 * because the main error message is quite misleading for this case.
1133 * (If there's no stmtcols, you'll get something about data type
1134 * mismatch, which is less misleading so we don't worry about giving a
1135 * hint in that case.)
1136 */
1137 ereport(ERROR,
1139 errmsg("INSERT has more target columns than expressions"),
1140 ((list_length(exprlist) == 1 &&
1143 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),
1144 parser_errposition(pstate,
1146 list_length(exprlist))))));
1147 }
1148
1149 /*
1150 * Prepare columns for assignment to target table.
1151 */
1152 result = NIL;
1154 {
1155 Expr *expr = (Expr *) lfirst(lc);
1157 int attno = lfirst_int(attnos);
1158
1159 expr = transformAssignedExpr(pstate, expr,
1161 col->name,
1162 attno,
1163 col->indirection,
1164 col->location);
1165
1167 {
1168 /*
1169 * We need to remove top-level FieldStores and SubscriptingRefs,
1170 * as well as any CoerceToDomain appearing above one of those ---
1171 * but not a CoerceToDomain that isn't above one of those.
1172 */
1173 while (expr)
1174 {
1175 Expr *subexpr = expr;
1176
1177 while (IsA(subexpr, CoerceToDomain))
1178 {
1179 subexpr = ((CoerceToDomain *) subexpr)->arg;
1180 }
1181 if (IsA(subexpr, FieldStore))
1182 {
1183 FieldStore *fstore = (FieldStore *) subexpr;
1184
1185 expr = (Expr *) linitial(fstore->newvals);
1186 }
1187 else if (IsA(subexpr, SubscriptingRef))
1188 {
1189 SubscriptingRef *sbsref = (SubscriptingRef *) subexpr;
1190
1191 if (sbsref->refassgnexpr == NULL)
1192 break;
1193
1194 expr = sbsref->refassgnexpr;
1195 }
1196 else
1197 break;
1198 }
1199 }
1200
1201 result = lappend(result, expr);
1202 }
1203
1204 return result;
1205}
@ EXPR_KIND_INSERT_TARGET
Definition parse_node.h:55
Expr * transformAssignedExpr(ParseState *pstate, Expr *expr, ParseExprKind exprKind, const char *colname, int attrno, List *indirection, int location)
static int count_rowexpr_columns(ParseState *pstate, Node *expr)
Definition analyze.c:1694
#define lfirst_node(type, lc)
Definition pg_list.h:176
#define lfirst_int(lc)
Definition pg_list.h:173
#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
List * newvals
Definition primnodes.h:1195
Expr * refassgnexpr
Definition primnodes.h:736

References count_rowexpr_columns(), ereport, errcode(), errhint(), errmsg, ERROR, EXPR_KIND_INSERT_TARGET, exprLocation(), fb(), forthree, IsA, lappend(), lfirst, lfirst_int, lfirst_node, linitial, list_length(), list_nth(), FieldStore::newvals, NIL, parser_errposition(), SubscriptingRef::refassgnexpr, result, and transformAssignedExpr().

Referenced by transformInsertStmt(), and transformMergeStmt().

◆ transformInsertStmt()

static Query * transformInsertStmt ( ParseState pstate,
InsertStmt stmt 
)
static

Definition at line 661 of file analyze.c.

662{
663 Query *qry = makeNode(Query);
664 SelectStmt *selectStmt = (SelectStmt *) stmt->selectStmt;
665 List *exprList = NIL;
666 bool isGeneralSelect;
670 List *icolumns;
671 List *attrnos;
676 ListCell *lc;
679
680 /* There can't be any outer WITH to worry about */
681 Assert(pstate->p_ctenamespace == NIL);
682
683 qry->commandType = CMD_INSERT;
684
685 /* process the WITH clause independently of all else */
686 if (stmt->withClause)
687 {
688 qry->hasRecursive = stmt->withClause->recursive;
689 qry->cteList = transformWithClause(pstate, stmt->withClause);
690 qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
691 }
692
693 qry->override = stmt->override;
694
695 /*
696 * ON CONFLICT DO UPDATE and ON CONFLICT DO SELECT FOR UPDATE/SHARE
697 * require UPDATE permission on the target relation.
698 */
699 requiresUpdatePerm = (stmt->onConflictClause &&
700 (stmt->onConflictClause->action == ONCONFLICT_UPDATE ||
701 (stmt->onConflictClause->action == ONCONFLICT_SELECT &&
702 stmt->onConflictClause->lockStrength != LCS_NONE)));
703
704 /*
705 * We have three cases to deal with: DEFAULT VALUES (selectStmt == NULL),
706 * VALUES list, or general SELECT input. We special-case VALUES, both for
707 * efficiency and so we can handle DEFAULT specifications.
708 *
709 * The grammar allows attaching ORDER BY, LIMIT, FOR UPDATE, or WITH to a
710 * VALUES clause. If we have any of those, treat it as a general SELECT;
711 * so it will work, but you can't use DEFAULT items together with those.
712 */
713 isGeneralSelect = (selectStmt && (selectStmt->valuesLists == NIL ||
714 selectStmt->sortClause != NIL ||
715 selectStmt->limitOffset != NULL ||
716 selectStmt->limitCount != NULL ||
717 selectStmt->lockingClause != NIL ||
718 selectStmt->withClause != NULL));
719
720 /*
721 * If a non-nil rangetable/namespace was passed in, and we are doing
722 * INSERT/SELECT, arrange to pass the rangetable/rteperminfos/namespace
723 * down to the SELECT. This can only happen if we are inside a CREATE
724 * RULE, and in that case we want the rule's OLD and NEW rtable entries to
725 * appear as part of the SELECT's rtable, not as outer references for it.
726 * (Kluge!) The SELECT's joinlist is not affected however. We must do
727 * this before adding the target table to the INSERT's rtable.
728 */
729 if (isGeneralSelect)
730 {
731 sub_rtable = pstate->p_rtable;
732 pstate->p_rtable = NIL;
734 pstate->p_rteperminfos = NIL;
735 sub_namespace = pstate->p_namespace;
736 pstate->p_namespace = NIL;
737 }
738 else
739 {
740 sub_rtable = NIL; /* not used, but keep compiler quiet */
743 }
744
745 /*
746 * Must get write lock on INSERT target table before scanning SELECT, else
747 * we will grab the wrong kind of initial lock if the target table is also
748 * mentioned in the SELECT part. Note that the target table is not added
749 * to the joinlist or namespace.
750 */
754 qry->resultRelation = setTargetTable(pstate, stmt->relation,
755 false, false, targetPerms);
756
757 /* Validate stmt->cols list, or build default list if no list given */
758 icolumns = checkInsertTargets(pstate, stmt->cols, &attrnos);
760
761 /*
762 * Determine which variant of INSERT we have.
763 */
764 if (selectStmt == NULL)
765 {
766 /*
767 * We have INSERT ... DEFAULT VALUES. We can handle this case by
768 * emitting an empty targetlist --- all columns will be defaulted when
769 * the planner expands the targetlist.
770 */
771 exprList = NIL;
772 }
773 else if (isGeneralSelect)
774 {
775 /*
776 * We make the sub-pstate a child of the outer pstate so that it can
777 * see any Param definitions supplied from above. Since the outer
778 * pstate's rtable and namespace are presently empty, there are no
779 * side-effects of exposing names the sub-SELECT shouldn't be able to
780 * see.
781 */
784
785 /*
786 * Process the source SELECT.
787 *
788 * It is important that this be handled just like a standalone SELECT;
789 * otherwise the behavior of SELECT within INSERT might be different
790 * from a stand-alone SELECT. (Indeed, Postgres up through 6.5 had
791 * bugs of just that nature...)
792 *
793 * The sole exception is that we prevent resolving unknown-type
794 * outputs as TEXT. This does not change the semantics since if the
795 * column type matters semantically, it would have been resolved to
796 * something else anyway. Doing this lets us resolve such outputs as
797 * the target column's type, which we handle below.
798 */
799 sub_pstate->p_rtable = sub_rtable;
800 sub_pstate->p_rteperminfos = sub_rteperminfos;
801 sub_pstate->p_joinexprs = NIL; /* sub_rtable has no joins */
802 sub_pstate->p_nullingrels = NIL;
803 sub_pstate->p_namespace = sub_namespace;
804 sub_pstate->p_resolve_unknowns = false;
805
807
809
810 /* The grammar should have produced a SELECT */
811 if (!IsA(selectQuery, Query) ||
812 selectQuery->commandType != CMD_SELECT)
813 elog(ERROR, "unexpected non-SELECT command in INSERT ... SELECT");
814
815 /*
816 * Make the source be a subquery in the INSERT's rangetable, and add
817 * it to the INSERT's joinlist (but not the namespace).
818 */
821 NULL,
822 false,
823 false);
824 addNSItemToQuery(pstate, nsitem, true, false, false);
825
826 /*----------
827 * Generate an expression list for the INSERT that selects all the
828 * non-resjunk columns from the subquery. (INSERT's tlist must be
829 * separate from the subquery's tlist because we may add columns,
830 * insert datatype coercions, etc.)
831 *
832 * HACK: unknown-type constants and params in the SELECT's targetlist
833 * are copied up as-is rather than being referenced as subquery
834 * outputs. This is to ensure that when we try to coerce them to
835 * the target column's datatype, the right things happen (see
836 * special cases in coerce_type). Otherwise, this fails:
837 * INSERT INTO foo SELECT 'bar', ... FROM baz
838 *----------
839 */
840 exprList = NIL;
841 foreach(lc, selectQuery->targetList)
842 {
844 Expr *expr;
845
846 if (tle->resjunk)
847 continue;
848 if (tle->expr &&
849 (IsA(tle->expr, Const) || IsA(tle->expr, Param)) &&
850 exprType((Node *) tle->expr) == UNKNOWNOID)
851 expr = tle->expr;
852 else
853 {
854 Var *var = makeVarFromTargetEntry(nsitem->p_rtindex, tle);
855
856 var->location = exprLocation((Node *) tle->expr);
857 expr = (Expr *) var;
858 }
859 exprList = lappend(exprList, expr);
860 }
861
862 /* Prepare row for assignment to target table */
864 stmt->cols,
866 false);
867 }
868 else if (list_length(selectStmt->valuesLists) > 1)
869 {
870 /*
871 * Process INSERT ... VALUES with multiple VALUES sublists. We
872 * generate a VALUES RTE holding the transformed expression lists, and
873 * build up a targetlist containing Vars that reference the VALUES
874 * RTE.
875 */
877 List *coltypes = NIL;
880 int sublist_length = -1;
881 bool lateral = false;
882
883 Assert(selectStmt->intoClause == NULL);
884
885 foreach(lc, selectStmt->valuesLists)
886 {
887 List *sublist = (List *) lfirst(lc);
888
889 /*
890 * Do basic expression transformation (same as a ROW() expr, but
891 * allow SetToDefault at top level)
892 */
894 EXPR_KIND_VALUES, true);
895
896 /*
897 * All the sublists must be the same length, *after*
898 * transformation (which might expand '*' into multiple items).
899 * The VALUES RTE can't handle anything different.
900 */
901 if (sublist_length < 0)
902 {
903 /* Remember post-transformation length of first sublist */
905 }
907 {
910 errmsg("VALUES lists must all be the same length"),
911 parser_errposition(pstate,
912 exprLocation((Node *) sublist))));
913 }
914
915 /*
916 * Prepare row for assignment to target table. We process any
917 * indirection on the target column specs normally but then strip
918 * off the resulting field/array assignment nodes, since we don't
919 * want the parsed statement to contain copies of those in each
920 * VALUES row. (It's annoying to have to transform the
921 * indirection specs over and over like this, but avoiding it
922 * would take some really messy refactoring of
923 * transformAssignmentIndirection.)
924 */
926 stmt->cols,
928 true);
929
930 /*
931 * We must assign collations now because assign_query_collations
932 * doesn't process rangetable entries. We just assign all the
933 * collations independently in each row, and don't worry about
934 * whether they are consistent vertically. The outer INSERT query
935 * isn't going to care about the collations of the VALUES columns,
936 * so it's not worth the effort to identify a common collation for
937 * each one here. (But note this does have one user-visible
938 * consequence: INSERT ... VALUES won't complain about conflicting
939 * explicit COLLATEs in a column, whereas the same VALUES
940 * construct in another context would complain.)
941 */
943
945 }
946
947 /*
948 * Construct column type/typmod/collation lists for the VALUES RTE.
949 * Every expression in each column has been coerced to the type/typmod
950 * of the corresponding target column or subfield, so it's sufficient
951 * to look at the exprType/exprTypmod of the first row. We don't care
952 * about the collation labeling, so just fill in InvalidOid for that.
953 */
954 foreach(lc, (List *) linitial(exprsLists))
955 {
956 Node *val = (Node *) lfirst(lc);
957
961 }
962
963 /*
964 * Ordinarily there can't be any current-level Vars in the expression
965 * lists, because the namespace was empty ... but if we're inside
966 * CREATE RULE, then NEW/OLD references might appear. In that case we
967 * have to mark the VALUES RTE as LATERAL.
968 */
969 if (list_length(pstate->p_rtable) != 1 &&
971 lateral = true;
972
973 /*
974 * Generate the VALUES RTE
975 */
978 NULL, lateral, true);
979 addNSItemToQuery(pstate, nsitem, true, false, false);
980
981 /*
982 * Generate list of Vars referencing the RTE
983 */
984 exprList = expandNSItemVars(pstate, nsitem, 0, -1, NULL);
985
986 /*
987 * Re-apply any indirection on the target column specs to the Vars
988 */
990 stmt->cols,
992 false);
993 }
994 else
995 {
996 /*
997 * Process INSERT ... VALUES with a single VALUES sublist. We treat
998 * this case separately for efficiency. The sublist is just computed
999 * directly as the Query's targetlist, with no VALUES RTE. So it
1000 * works just like a SELECT without any FROM.
1001 */
1002 List *valuesLists = selectStmt->valuesLists;
1003
1004 Assert(list_length(valuesLists) == 1);
1005 Assert(selectStmt->intoClause == NULL);
1006
1007 /*
1008 * Do basic expression transformation (same as a ROW() expr, but allow
1009 * SetToDefault at top level)
1010 */
1012 (List *) linitial(valuesLists),
1014 true);
1015
1016 /* Prepare row for assignment to target table */
1018 stmt->cols,
1020 false);
1021 }
1022
1023 /*
1024 * Generate query's target list using the computed list of expressions.
1025 * Also, mark all the target columns as needing insert permissions.
1026 */
1028 qry->targetList = NIL;
1031 {
1032 Expr *expr = (Expr *) lfirst(lc);
1036
1037 tle = makeTargetEntry(expr,
1038 attr_num,
1039 col->name,
1040 false);
1041 qry->targetList = lappend(qry->targetList, tle);
1042
1043 perminfo->insertedCols = bms_add_member(perminfo->insertedCols,
1045 }
1046
1047 /*
1048 * If we have any clauses yet to process, set the query namespace to
1049 * contain only the target relation, removing any entries added in a
1050 * sub-SELECT or VALUES list.
1051 */
1052 if (stmt->onConflictClause || stmt->returningClause)
1053 {
1054 pstate->p_namespace = NIL;
1055 addNSItemToQuery(pstate, pstate->p_target_nsitem,
1056 false, true, true);
1057 }
1058
1059 /* ON CONFLICT DO SELECT requires a RETURNING clause */
1060 if (stmt->onConflictClause &&
1061 stmt->onConflictClause->action == ONCONFLICT_SELECT &&
1062 !stmt->returningClause)
1063 ereport(ERROR,
1065 errmsg("ON CONFLICT DO SELECT requires a RETURNING clause"),
1066 parser_errposition(pstate, stmt->onConflictClause->location));
1067
1068 /* Process ON CONFLICT, if any. */
1069 if (stmt->onConflictClause)
1070 qry->onConflict = transformOnConflictClause(pstate,
1071 stmt->onConflictClause);
1072
1073 /* Process RETURNING, if any. */
1074 if (stmt->returningClause)
1075 transformReturningClause(pstate, qry, stmt->returningClause,
1077
1078 /* done building the range table and jointree */
1079 qry->rtable = pstate->p_rtable;
1080 qry->rteperminfos = pstate->p_rteperminfos;
1081 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
1082
1083 qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
1084 qry->hasSubLinks = pstate->p_hasSubLinks;
1085
1086 assign_query_collations(pstate, qry);
1087
1088 return qry;
1089}
long val
Definition informix.c:689
Var * makeVarFromTargetEntry(int varno, TargetEntry *tle)
Definition makefuncs.c:107
int32 exprTypmod(const Node *expr)
Definition nodeFuncs.c:304
@ ONCONFLICT_SELECT
Definition nodes.h:431
@ ONCONFLICT_UPDATE
Definition nodes.h:430
@ CMD_INSERT
Definition nodes.h:277
void assign_list_collations(ParseState *pstate, List *exprs)
@ EXPR_KIND_VALUES
Definition parse_node.h:67
@ EXPR_KIND_VALUES_SINGLE
Definition parse_node.h:68
List * expandNSItemVars(ParseState *pstate, ParseNamespaceItem *nsitem, int sublevels_up, int location, List **colnames)
ParseNamespaceItem * addRangeTableEntryForSubquery(ParseState *pstate, Query *subquery, Alias *alias, bool lateral, bool inFromCl)
ParseNamespaceItem * addRangeTableEntryForValues(ParseState *pstate, List *exprs, List *coltypes, List *coltypmods, List *colcollations, Alias *alias, bool lateral, bool inFromCl)
List * transformExpressionList(ParseState *pstate, List *exprlist, ParseExprKind exprKind, bool allowDefault)
List * checkInsertTargets(ParseState *pstate, List *cols, List **attrnos)
uint64 AclMode
Definition parsenodes.h:74
#define ACL_INSERT
Definition parsenodes.h:76
#define ACL_UPDATE
Definition parsenodes.h:78
static OnConflictExpr * transformOnConflictClause(ParseState *pstate, OnConflictClause *onConflictClause)
Definition analyze.c:1212
List * transformInsertRow(ParseState *pstate, List *exprlist, List *stmtcols, List *icolumns, List *attrnos, bool strip_indirection)
Definition analyze.c:1102
List * p_ctenamespace
Definition parse_node.h:225
List * p_namespace
Definition parse_node.h:222
bool contain_vars_of_level(Node *node, int levelsup)
Definition var.c:444

References ACL_INSERT, ACL_UPDATE, addNSItemToQuery(), addRangeTableEntryForSubquery(), addRangeTableEntryForValues(), Assert, assign_list_collations(), assign_query_collations(), bms_add_member(), checkInsertTargets(), CMD_INSERT, CMD_SELECT, Query::commandType, contain_vars_of_level(), Query::cteList, elog, ereport, errcode(), errmsg, ERROR, expandNSItemVars(), EXPR_KIND_RETURNING, EXPR_KIND_VALUES, EXPR_KIND_VALUES_SINGLE, exprLocation(), exprType(), exprTypmod(), fb(), FirstLowInvalidHeapAttributeNumber, forthree, free_parsestate(), SelectStmt::intoClause, InvalidOid, IsA, Query::jointree, lappend(), lappend_int(), lappend_oid(), LCS_NONE, lfirst, lfirst_int, lfirst_node, SelectStmt::limitCount, SelectStmt::limitOffset, linitial, list_length(), Var::location, SelectStmt::lockingClause, make_parsestate(), makeFromExpr(), makeNode, makeTargetEntry(), makeVarFromTargetEntry(), NIL, Query::onConflict, ONCONFLICT_SELECT, ONCONFLICT_UPDATE, ParseState::p_ctenamespace, ParseState::p_hasModifyingCTE, ParseState::p_hasSubLinks, ParseState::p_hasTargetSRFs, ParseState::p_joinlist, ParseState::p_namespace, ParseNamespaceItem::p_perminfo, ParseState::p_rtable, ParseState::p_rteperminfos, ParseState::p_target_nsitem, parser_errposition(), Query::rtable, setTargetTable(), SelectStmt::sortClause, stmt, Query::targetList, transformExpressionList(), transformInsertRow(), transformOnConflictClause(), transformReturningClause(), transformStmt(), transformWithClause(), val, SelectStmt::valuesLists, and SelectStmt::withClause.

Referenced by transformStmt().

◆ transformLockingClause()

static void transformLockingClause ( ParseState pstate,
Query qry,
LockingClause lc,
bool  pushedDown 
)
static

Definition at line 3805 of file analyze.c.

3807{
3808 List *lockedRels = lc->lockedRels;
3809 ListCell *l;
3810 ListCell *rt;
3811 Index i;
3813
3814 CheckSelectLocking(qry, lc->strength);
3815
3816 /* make a clause we can pass down to subqueries to select all rels */
3818 allrels->lockedRels = NIL; /* indicates all rels */
3819 allrels->strength = lc->strength;
3820 allrels->waitPolicy = lc->waitPolicy;
3821
3822 if (lockedRels == NIL)
3823 {
3824 /*
3825 * Lock all regular tables used in query and its subqueries. We
3826 * examine inFromCl to exclude auto-added RTEs, particularly NEW/OLD
3827 * in rules. This is a bit of an abuse of a mostly-obsolete flag, but
3828 * it's convenient. We can't rely on the namespace mechanism that has
3829 * largely replaced inFromCl, since for example we need to lock
3830 * base-relation RTEs even if they are masked by upper joins.
3831 */
3832 i = 0;
3833 foreach(rt, qry->rtable)
3834 {
3836
3837 ++i;
3838 if (!rte->inFromCl)
3839 continue;
3840 switch (rte->rtekind)
3841 {
3842 case RTE_RELATION:
3843 {
3845
3846 applyLockingClause(qry, i,
3847 lc->strength,
3848 lc->waitPolicy,
3849 pushedDown);
3850 perminfo = getRTEPermissionInfo(qry->rteperminfos, rte);
3851 perminfo->requiredPerms |= ACL_SELECT_FOR_UPDATE;
3852 }
3853 break;
3854 case RTE_SUBQUERY:
3855 applyLockingClause(qry, i, lc->strength, lc->waitPolicy,
3856 pushedDown);
3857
3858 /*
3859 * FOR UPDATE/SHARE of subquery is propagated to all of
3860 * subquery's rels, too. We could do this later (based on
3861 * the marking of the subquery RTE) but it is convenient
3862 * to have local knowledge in each query level about which
3863 * rels need to be opened with RowShareLock.
3864 */
3865 transformLockingClause(pstate, rte->subquery,
3866 allrels, true);
3867 break;
3868 default:
3869 /* ignore JOIN, SPECIAL, FUNCTION, VALUES, CTE RTEs */
3870 break;
3871 }
3872 }
3873 }
3874 else
3875 {
3876 /*
3877 * Lock just the named tables. As above, we allow locking any base
3878 * relation regardless of alias-visibility rules, so we need to
3879 * examine inFromCl to exclude OLD/NEW.
3880 */
3881 foreach(l, lockedRels)
3882 {
3883 RangeVar *thisrel = (RangeVar *) lfirst(l);
3884
3885 /* For simplicity we insist on unqualified alias names here */
3886 if (thisrel->catalogname || thisrel->schemaname)
3887 ereport(ERROR,
3889 /*------
3890 translator: %s is a SQL row locking clause such as FOR UPDATE */
3891 errmsg("%s must specify unqualified relation names",
3892 LCS_asString(lc->strength)),
3893 parser_errposition(pstate, thisrel->location)));
3894
3895 i = 0;
3896 foreach(rt, qry->rtable)
3897 {
3899 char *rtename = rte->eref->aliasname;
3900
3901 ++i;
3902 if (!rte->inFromCl)
3903 continue;
3904
3905 /*
3906 * A join RTE without an alias is not visible as a relation
3907 * name and needs to be skipped (otherwise it might hide a
3908 * base relation with the same name), except if it has a USING
3909 * alias, which *is* visible.
3910 *
3911 * Subquery and values RTEs without aliases are never visible
3912 * as relation names and must always be skipped.
3913 */
3914 if (rte->alias == NULL)
3915 {
3916 if (rte->rtekind == RTE_JOIN)
3917 {
3918 if (rte->join_using_alias == NULL)
3919 continue;
3920 rtename = rte->join_using_alias->aliasname;
3921 }
3922 else if (rte->rtekind == RTE_SUBQUERY ||
3923 rte->rtekind == RTE_VALUES)
3924 continue;
3925 }
3926
3927 if (strcmp(rtename, thisrel->relname) == 0)
3928 {
3929 switch (rte->rtekind)
3930 {
3931 case RTE_RELATION:
3932 {
3934
3935 applyLockingClause(qry, i,
3936 lc->strength,
3937 lc->waitPolicy,
3938 pushedDown);
3939 perminfo = getRTEPermissionInfo(qry->rteperminfos, rte);
3940 perminfo->requiredPerms |= ACL_SELECT_FOR_UPDATE;
3941 }
3942 break;
3943 case RTE_SUBQUERY:
3944 applyLockingClause(qry, i, lc->strength,
3945 lc->waitPolicy, pushedDown);
3946 /* see comment above */
3947 transformLockingClause(pstate, rte->subquery,
3948 allrels, true);
3949 break;
3950 case RTE_JOIN:
3951 ereport(ERROR,
3953 /*------
3954 translator: %s is a SQL row locking clause such as FOR UPDATE */
3955 errmsg("%s cannot be applied to a join",
3956 LCS_asString(lc->strength)),
3957 parser_errposition(pstate, thisrel->location)));
3958 break;
3959 case RTE_FUNCTION:
3960 ereport(ERROR,
3962 /*------
3963 translator: %s is a SQL row locking clause such as FOR UPDATE */
3964 errmsg("%s cannot be applied to a function",
3965 LCS_asString(lc->strength)),
3966 parser_errposition(pstate, thisrel->location)));
3967 break;
3968 case RTE_TABLEFUNC:
3969 ereport(ERROR,
3971 /*------
3972 translator: %s is a SQL row locking clause such as FOR UPDATE */
3973 errmsg("%s cannot be applied to a table function",
3974 LCS_asString(lc->strength)),
3975 parser_errposition(pstate, thisrel->location)));
3976 break;
3977 case RTE_VALUES:
3978 ereport(ERROR,
3980 /*------
3981 translator: %s is a SQL row locking clause such as FOR UPDATE */
3982 errmsg("%s cannot be applied to VALUES",
3983 LCS_asString(lc->strength)),
3984 parser_errposition(pstate, thisrel->location)));
3985 break;
3986 case RTE_CTE:
3987 ereport(ERROR,
3989 /*------
3990 translator: %s is a SQL row locking clause such as FOR UPDATE */
3991 errmsg("%s cannot be applied to a WITH query",
3992 LCS_asString(lc->strength)),
3993 parser_errposition(pstate, thisrel->location)));
3994 break;
3996 ereport(ERROR,
3998 /*------
3999 translator: %s is a SQL row locking clause such as FOR UPDATE */
4000 errmsg("%s cannot be applied to a named tuplestore",
4001 LCS_asString(lc->strength)),
4002 parser_errposition(pstate, thisrel->location)));
4003 break;
4004
4005 /* Shouldn't be possible to see RTE_RESULT here */
4006
4007 default:
4008 elog(ERROR, "unrecognized RTE type: %d",
4009 (int) rte->rtekind);
4010 break;
4011 }
4012 break; /* out of foreach loop */
4013 }
4014 }
4015 if (rt == NULL)
4016 ereport(ERROR,
4018 /*------
4019 translator: %s is a SQL row locking clause such as FOR UPDATE */
4020 errmsg("relation \"%s\" in %s clause not found in FROM clause",
4021 thisrel->relname,
4022 LCS_asString(lc->strength)),
4023 parser_errposition(pstate, thisrel->location)));
4024 }
4025 }
4026}
unsigned int Index
Definition c.h:698
RTEPermissionInfo * getRTEPermissionInfo(List *rteperminfos, RangeTblEntry *rte)
@ RTE_JOIN
@ RTE_CTE
@ RTE_NAMEDTUPLESTORE
@ RTE_VALUES
@ RTE_FUNCTION
@ RTE_TABLEFUNC
@ RTE_RELATION
#define ACL_SELECT_FOR_UPDATE
Definition parsenodes.h:94
static void transformLockingClause(ParseState *pstate, Query *qry, LockingClause *lc, bool pushedDown)
Definition analyze.c:3805
void CheckSelectLocking(Query *qry, LockClauseStrength strength)
Definition analyze.c:3741
void applyLockingClause(Query *qry, Index rtindex, LockClauseStrength strength, LockWaitPolicy waitPolicy, bool pushedDown)
Definition analyze.c:4032
#define ERRCODE_UNDEFINED_TABLE
Definition pgbench.c:79

References ACL_SELECT_FOR_UPDATE, applyLockingClause(), CheckSelectLocking(), elog, ereport, errcode(), ERRCODE_UNDEFINED_TABLE, errmsg, ERROR, fb(), getRTEPermissionInfo(), i, LCS_asString(), lfirst, makeNode, NIL, parser_errposition(), Query::rtable, RTE_CTE, RTE_FUNCTION, RTE_JOIN, RTE_NAMEDTUPLESTORE, RTE_RELATION, RTE_SUBQUERY, RTE_TABLEFUNC, RTE_VALUES, and transformLockingClause().

Referenced by transformLockingClause(), transformSelectStmt(), and transformSetOperationStmt().

◆ transformOnConflictClause()

static OnConflictExpr * transformOnConflictClause ( ParseState pstate,
OnConflictClause onConflictClause 
)
static

Definition at line 1212 of file analyze.c.

1214{
1216 List *arbiterElems;
1217 Node *arbiterWhere;
1219 List *onConflictSet = NIL;
1220 Node *onConflictWhere = NULL;
1221 int exclRelIndex = 0;
1222 List *exclRelTlist = NIL;
1224
1225 /*
1226 * If this is ON CONFLICT DO SELECT/UPDATE, first create the range table
1227 * entry for the EXCLUDED pseudo relation, so that that will be present
1228 * while processing arbiter expressions. (You can't actually reference it
1229 * from there, but this provides a useful error message if you try.)
1230 */
1231 if (onConflictClause->action == ONCONFLICT_UPDATE ||
1232 onConflictClause->action == ONCONFLICT_SELECT)
1233 {
1236
1238 targetrel,
1240 makeAlias("excluded", NIL),
1241 false, false);
1242 exclRte = exclNSItem->p_rte;
1243 exclRelIndex = exclNSItem->p_rtindex;
1244
1245 /*
1246 * relkind is set to composite to signal that we're not dealing with
1247 * an actual relation, and no permission checks are required on it.
1248 * (We'll check the actual target relation, instead.)
1249 */
1251
1252 /* Create EXCLUDED rel's targetlist for use by EXPLAIN */
1254 exclRelIndex);
1255 }
1256
1257 /* Process the arbiter clause, ON CONFLICT ON (...) */
1258 transformOnConflictArbiter(pstate, onConflictClause, &arbiterElems,
1259 &arbiterWhere, &arbiterConstraint);
1260
1261 /* Process DO SELECT/UPDATE */
1262 if (onConflictClause->action == ONCONFLICT_UPDATE ||
1263 onConflictClause->action == ONCONFLICT_SELECT)
1264 {
1265 /*
1266 * Add the EXCLUDED pseudo relation to the query namespace, making it
1267 * available in SET and WHERE subexpressions.
1268 */
1269 addNSItemToQuery(pstate, exclNSItem, false, true, true);
1270
1271 /* Process the UPDATE SET clause */
1272 if (onConflictClause->action == ONCONFLICT_UPDATE)
1273 onConflictSet =
1274 transformUpdateTargetList(pstate, onConflictClause->targetList, NULL);
1275
1276 /* Process the SELECT/UPDATE WHERE clause */
1277 onConflictWhere = transformWhereClause(pstate,
1278 onConflictClause->whereClause,
1279 EXPR_KIND_WHERE, "WHERE");
1280
1281 /*
1282 * Remove the EXCLUDED pseudo relation from the query namespace, since
1283 * it's not supposed to be available in RETURNING. (Maybe someday we
1284 * could allow that, and drop this step.)
1285 */
1287 pstate->p_namespace = list_delete_last(pstate->p_namespace);
1288 }
1289
1290 /* Finally, build ON CONFLICT DO [NOTHING | SELECT | UPDATE] expression */
1292
1293 result->action = onConflictClause->action;
1294 result->arbiterElems = arbiterElems;
1295 result->arbiterWhere = arbiterWhere;
1296 result->constraint = arbiterConstraint;
1297 result->lockStrength = onConflictClause->lockStrength;
1298 result->onConflictSet = onConflictSet;
1299 result->onConflictWhere = onConflictWhere;
1300 result->exclRelIndex = exclRelIndex;
1301 result->exclRelTlist = exclRelTlist;
1302
1303 return result;
1304}
List * list_delete_last(List *list)
Definition list.c:957
#define RowExclusiveLock
Definition lockdefs.h:38
void transformOnConflictArbiter(ParseState *pstate, OnConflictClause *onConflictClause, List **arbiterExpr, Node **arbiterWhere, Oid *constraint)
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, LOCKMODE lockmode, Alias *alias, bool inh, bool inFromCl)
List * transformUpdateTargetList(ParseState *pstate, List *origTlist, ForPortionOfExpr *forPortionOf)
Definition analyze.c:2935
List * BuildOnConflictExcludedTargetlist(Relation targetrel, Index exclRelIndex)
Definition analyze.c:1624
#define llast(l)
Definition pg_list.h:198
OnConflictAction action
LockClauseStrength lockStrength

References OnConflictClause::action, addNSItemToQuery(), addRangeTableEntryForRelation(), Assert, BuildOnConflictExcludedTargetlist(), EXPR_KIND_WHERE, fb(), list_delete_last(), llast, OnConflictClause::lockStrength, makeAlias(), makeNode, NIL, ONCONFLICT_SELECT, ONCONFLICT_UPDATE, ParseState::p_namespace, ParseState::p_target_relation, result, RowExclusiveLock, OnConflictClause::targetList, transformOnConflictArbiter(), transformUpdateTargetList(), transformWhereClause(), and OnConflictClause::whereClause.

Referenced by transformInsertStmt().

◆ transformOptionalSelectInto()

static Query * transformOptionalSelectInto ( ParseState pstate,
Node parseTree 
)
static

Definition at line 295 of file analyze.c.

296{
298 {
300
301 /* If it's a set-operation tree, drill down to leftmost SelectStmt */
302 while (stmt && stmt->op != SETOP_NONE)
303 stmt = stmt->larg;
304 Assert(stmt && IsA(stmt, SelectStmt) && stmt->larg == NULL);
305
306 if (stmt->intoClause)
307 {
309
310 ctas->query = parseTree;
311 ctas->into = stmt->intoClause;
312 ctas->objtype = OBJECT_TABLE;
313 ctas->is_select_into = true;
314
315 /*
316 * Remove the intoClause from the SelectStmt. This makes it safe
317 * for transformSelectStmt to complain if it finds intoClause set
318 * (implying that the INTO appeared in a disallowed place).
319 */
320 stmt->intoClause = NULL;
321
322 parseTree = (Node *) ctas;
323 }
324 }
325
326 return transformStmt(pstate, parseTree);
327}
@ SETOP_NONE
@ OBJECT_TABLE
struct SelectStmt * larg

References Assert, fb(), IsA, SelectStmt::larg, makeNode, OBJECT_TABLE, SETOP_NONE, stmt, and transformStmt().

Referenced by transformExplainStmt(), and transformTopLevelStmt().

◆ transformPLAssignStmt()

static Query * transformPLAssignStmt ( ParseState pstate,
PLAssignStmt stmt 
)
static

Definition at line 3185 of file analyze.c.

3186{
3187 Query *qry;
3189 List *indirection = stmt->indirection;
3190 int nnames = stmt->nnames;
3191 Node *target;
3194
3195 /*
3196 * First, construct a ColumnRef for the target variable. If the target
3197 * has more than one dotted name, we have to pull the extra names out of
3198 * the indirection list.
3199 */
3200 cref->fields = list_make1(makeString(stmt->name));
3201 cref->location = stmt->location;
3202 if (nnames > 1)
3203 {
3204 /* avoid munging the raw parsetree */
3205 indirection = list_copy(indirection);
3206 while (--nnames > 0 && indirection != NIL)
3207 {
3208 Node *ind = (Node *) linitial(indirection);
3209
3210 if (!IsA(ind, String))
3211 elog(ERROR, "invalid name count in PLAssignStmt");
3212 cref->fields = lappend(cref->fields, ind);
3213 indirection = list_delete_first(indirection);
3214 }
3215 }
3216
3217 /*
3218 * Transform the target reference. Typically we will get back a Param
3219 * node, but there's no reason to be too picky about its type. (Note that
3220 * we must do this before calling transformSelectStmt. It's tempting to
3221 * do it inside transformPLAssignStmtTarget, but we need to do it before
3222 * adding any FROM tables to the pstate's namespace, else we might wrongly
3223 * resolve the target as a table column.)
3224 */
3225 target = transformExpr(pstate, (Node *) cref,
3227
3228 /* Set up passthrough data for transformPLAssignStmtTarget */
3229 passthru.stmt = stmt;
3230 passthru.target = target;
3231 passthru.indirection = indirection;
3232
3233 /*
3234 * To avoid duplicating a lot of code, we use transformSelectStmt to do
3235 * almost all of the work. However, we need to do additional processing
3236 * on the SELECT's targetlist after it's been transformed, but before
3237 * possible addition of targetlist items for ORDER BY or GROUP BY.
3238 * transformSelectStmt knows it should call transformPLAssignStmtTarget if
3239 * it's passed a passthru argument.
3240 *
3241 * Also, disable resolution of unknown-type tlist items; PL/pgSQL wants to
3242 * deal with that itself.
3243 */
3245 pstate->p_resolve_unknowns = false;
3246 qry = transformSelectStmt(pstate, stmt->val, &passthru);
3248
3249 return qry;
3250}
List * list_delete_first(List *list)
Definition list.c:943
List * list_copy(const List *oldlist)
Definition list.c:1573
@ EXPR_KIND_UPDATE_TARGET
Definition parse_node.h:57
static Query * transformSelectStmt(ParseState *pstate, SelectStmt *stmt, SelectStmtPassthrough *passthru)
Definition analyze.c:1743
#define list_make1(x1)
Definition pg_list.h:244
Definition value.h:64
String * makeString(char *str)
Definition value.c:63

References elog, ERROR, EXPR_KIND_UPDATE_TARGET, fb(), IsA, lappend(), linitial, list_copy(), list_delete_first(), list_make1, makeNode, makeString(), NIL, ParseState::p_resolve_unknowns, stmt, transformExpr(), and transformSelectStmt().

Referenced by transformStmt().

◆ transformPLAssignStmtTarget()

static List * transformPLAssignStmtTarget ( ParseState pstate,
List tlist,
SelectStmtPassthrough passthru 
)
static

Definition at line 3260 of file analyze.c.

3262{
3263 PLAssignStmt *stmt = passthru->stmt;
3264 Node *target = passthru->target;
3265 List *indirection = passthru->indirection;
3266 Oid targettype;
3267 int32 targettypmod;
3270 Oid type_id;
3271
3272 targettype = exprType(target);
3273 targettypmod = exprTypmod(target);
3275
3276 /* we should have exactly one targetlist item */
3277 if (list_length(tlist) != 1)
3278 ereport(ERROR,
3280 errmsg_plural("assignment source returned %d column",
3281 "assignment source returned %d columns",
3282 list_length(tlist),
3283 list_length(tlist))));
3284
3285 tle = linitial_node(TargetEntry, tlist);
3286
3287 /*
3288 * This next bit is similar to transformAssignedExpr; the key difference
3289 * is we use COERCION_PLPGSQL not COERCION_ASSIGNMENT.
3290 */
3291 type_id = exprType((Node *) tle->expr);
3292
3294
3295 if (indirection)
3296 {
3297 tle->expr = (Expr *)
3299 target,
3300 stmt->name,
3301 false,
3302 targettype,
3303 targettypmod,
3305 indirection,
3306 list_head(indirection),
3307 (Node *) tle->expr,
3309 exprLocation(target));
3310 }
3311 else if (targettype != type_id &&
3312 (targettype == RECORDOID || ISCOMPLEX(targettype)) &&
3313 (type_id == RECORDOID || ISCOMPLEX(type_id)))
3314 {
3315 /*
3316 * Hack: do not let coerce_to_target_type() deal with inconsistent
3317 * composite types. Just pass the expression result through as-is,
3318 * and let the PL/pgSQL executor do the conversion its way. This is
3319 * rather bogus, but it's needed for backwards compatibility.
3320 */
3321 }
3322 else
3323 {
3324 /*
3325 * For normal non-qualified target column, do type checking and
3326 * coercion.
3327 */
3328 Node *orig_expr = (Node *) tle->expr;
3329
3330 tle->expr = (Expr *)
3331 coerce_to_target_type(pstate,
3332 orig_expr, type_id,
3333 targettype, targettypmod,
3336 -1);
3337 /* With COERCION_PLPGSQL, this error is probably unreachable */
3338 if (tle->expr == NULL)
3339 ereport(ERROR,
3341 errmsg("variable \"%s\" is of type %s"
3342 " but expression is of type %s",
3343 stmt->name,
3344 format_type_be(targettype),
3345 format_type_be(type_id)),
3346 errhint("You will need to rewrite or cast the expression."),
3348 }
3349
3350 pstate->p_expr_kind = EXPR_KIND_NONE;
3351
3352 return list_make1(tle);
3353}
int int int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...) pg_attribute_printf(1
Oid exprCollation(const Node *expr)
Definition nodeFuncs.c:826
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
@ EXPR_KIND_NONE
Definition parse_node.h:40
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)
#define ISCOMPLEX(typeid)
Definition parse_type.h:59
#define linitial_node(type, l)
Definition pg_list.h:181
static ListCell * list_head(const List *l)
Definition pg_list.h:128
@ COERCION_PLPGSQL
Definition primnodes.h:749
ParseExprKind p_expr_kind
Definition parse_node.h:232

References COERCE_IMPLICIT_CAST, coerce_to_target_type(), COERCION_PLPGSQL, ereport, errcode(), errhint(), errmsg, errmsg_plural(), ERROR, EXPR_KIND_NONE, EXPR_KIND_UPDATE_TARGET, exprCollation(), exprLocation(), exprType(), exprTypmod(), fb(), format_type_be(), ISCOMPLEX, linitial_node, list_head(), list_length(), list_make1, ParseState::p_expr_kind, parser_errposition(), stmt, and transformAssignmentIndirection().

Referenced by transformSelectStmt().

◆ transformReturningClause()

void transformReturningClause ( ParseState pstate,
Query qry,
ReturningClause returningClause,
ParseExprKind  exprKind 
)

Definition at line 3063 of file analyze.c.

3066{
3067 int save_nslen = list_length(pstate->p_namespace);
3068 int save_next_resno;
3069
3070 if (returningClause == NULL)
3071 return; /* nothing to do */
3072
3073 /*
3074 * Scan RETURNING WITH(...) options for OLD/NEW alias names. Complain if
3075 * there is any conflict with existing relations.
3076 */
3077 foreach_node(ReturningOption, option, returningClause->options)
3078 {
3079 switch (option->option)
3080 {
3082 if (qry->returningOldAlias != NULL)
3083 ereport(ERROR,
3085 /* translator: %s is OLD or NEW */
3086 errmsg("%s cannot be specified multiple times", "OLD"),
3087 parser_errposition(pstate, option->location));
3088 qry->returningOldAlias = option->value;
3089 break;
3090
3092 if (qry->returningNewAlias != NULL)
3093 ereport(ERROR,
3095 /* translator: %s is OLD or NEW */
3096 errmsg("%s cannot be specified multiple times", "NEW"),
3097 parser_errposition(pstate, option->location));
3098 qry->returningNewAlias = option->value;
3099 break;
3100
3101 default:
3102 elog(ERROR, "unrecognized returning option: %d", option->option);
3103 }
3104
3105 if (refnameNamespaceItem(pstate, NULL, option->value, -1, NULL) != NULL)
3106 ereport(ERROR,
3108 errmsg("table name \"%s\" specified more than once",
3109 option->value),
3110 parser_errposition(pstate, option->location));
3111
3112 addNSItemForReturning(pstate, option->value,
3113 option->option == RETURNING_OPTION_OLD ?
3115 }
3116
3117 /*
3118 * If OLD/NEW alias names weren't explicitly specified, use "old"/"new"
3119 * unless masked by existing relations.
3120 */
3121 if (qry->returningOldAlias == NULL &&
3122 refnameNamespaceItem(pstate, NULL, "old", -1, NULL) == NULL)
3123 {
3124 qry->returningOldAlias = "old";
3126 }
3127 if (qry->returningNewAlias == NULL &&
3128 refnameNamespaceItem(pstate, NULL, "new", -1, NULL) == NULL)
3129 {
3130 qry->returningNewAlias = "new";
3132 }
3133
3134 /*
3135 * We need to assign resnos starting at one in the RETURNING list. Save
3136 * and restore the main tlist's value of p_next_resno, just in case
3137 * someone looks at it later (probably won't happen).
3138 */
3139 save_next_resno = pstate->p_next_resno;
3140 pstate->p_next_resno = 1;
3141
3142 /* transform RETURNING expressions identically to a SELECT targetlist */
3143 qry->returningList = transformTargetList(pstate,
3144 returningClause->exprs,
3145 exprKind);
3146
3147 /*
3148 * Complain if the nonempty tlist expanded to nothing (which is possible
3149 * if it contains only a star-expansion of a zero-column table). If we
3150 * allow this, the parsed Query will look like it didn't have RETURNING,
3151 * with results that would probably surprise the user.
3152 */
3153 if (qry->returningList == NIL)
3154 ereport(ERROR,
3156 errmsg("RETURNING must have at least one column"),
3157 parser_errposition(pstate,
3158 exprLocation(linitial(returningClause->exprs)))));
3159
3160 /* mark column origins */
3162
3163 /* resolve any still-unresolved output columns as being type text */
3164 if (pstate->p_resolve_unknowns)
3166
3167 /* restore state */
3168 pstate->p_namespace = list_truncate(pstate->p_namespace, save_nslen);
3169 pstate->p_next_resno = save_next_resno;
3170}
List * list_truncate(List *list, int new_size)
Definition list.c:631
ParseNamespaceItem * refnameNamespaceItem(ParseState *pstate, const char *schemaname, const char *refname, int location, int *sublevels_up)
List * transformTargetList(ParseState *pstate, List *targetlist, ParseExprKind exprKind)
void resolveTargetListUnknowns(ParseState *pstate, List *targetlist)
void markTargetListOrigins(ParseState *pstate, List *targetlist)
@ RETURNING_OPTION_NEW
@ RETURNING_OPTION_OLD
static void addNSItemForReturning(ParseState *pstate, const char *aliasname, VarReturningType returning_type)
Definition analyze.c:3024
#define foreach_node(type, var, lst)
Definition pg_list.h:528
@ VAR_RETURNING_OLD
Definition primnodes.h:258
@ VAR_RETURNING_NEW
Definition primnodes.h:259
int p_next_resno
Definition parse_node.h:233
List * returningList
Definition parsenodes.h:217

References addNSItemForReturning(), elog, ereport, errcode(), errmsg, ERROR, exprLocation(), ReturningClause::exprs, fb(), foreach_node, linitial, list_length(), list_truncate(), markTargetListOrigins(), NIL, ReturningClause::options, ParseState::p_namespace, ParseState::p_next_resno, ParseState::p_resolve_unknowns, parser_errposition(), refnameNamespaceItem(), resolveTargetListUnknowns(), RETURNING_OPTION_NEW, RETURNING_OPTION_OLD, Query::returningList, transformTargetList(), VAR_RETURNING_NEW, and VAR_RETURNING_OLD.

Referenced by transformDeleteStmt(), transformInsertStmt(), transformMergeStmt(), and transformUpdateStmt().

◆ transformReturnStmt()

static Query * transformReturnStmt ( ParseState pstate,
ReturnStmt stmt 
)
static

Definition at line 2823 of file analyze.c.

2824{
2825 Query *qry = makeNode(Query);
2826
2827 qry->commandType = CMD_SELECT;
2828 qry->isReturn = true;
2829
2831 1, NULL, false));
2832
2833 if (pstate->p_resolve_unknowns)
2835 qry->rtable = pstate->p_rtable;
2836 qry->rteperminfos = pstate->p_rteperminfos;
2837 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
2838 qry->hasSubLinks = pstate->p_hasSubLinks;
2839 qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
2840 qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
2841 qry->hasAggs = pstate->p_hasAggs;
2842
2843 assign_query_collations(pstate, qry);
2844
2845 return qry;
2846}
@ EXPR_KIND_SELECT_TARGET
Definition parse_node.h:54
List * targetList
Definition parsenodes.h:201

References assign_query_collations(), CMD_SELECT, Query::commandType, EXPR_KIND_SELECT_TARGET, fb(), Query::jointree, list_make1, makeFromExpr(), makeNode, makeTargetEntry(), ParseState::p_hasAggs, ParseState::p_hasSubLinks, ParseState::p_hasTargetSRFs, ParseState::p_hasWindowFuncs, ParseState::p_joinlist, ParseState::p_resolve_unknowns, ParseState::p_rtable, ParseState::p_rteperminfos, resolveTargetListUnknowns(), Query::rtable, stmt, Query::targetList, and transformExpr().

Referenced by transformStmt().

◆ transformSelectStmt()

static Query * transformSelectStmt ( ParseState pstate,
SelectStmt stmt,
SelectStmtPassthrough passthru 
)
static

Definition at line 1743 of file analyze.c.

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 stmt->groupByAll,
1815 &qry->groupingSets,
1816 &qry->targetList,
1817 qry->sortClause,
1819 false /* allow SQL92 rules */ );
1820 qry->groupDistinct = stmt->groupDistinct;
1821 qry->groupByAll = stmt->groupByAll;
1822
1823 if (stmt->distinctClause == NIL)
1824 {
1825 qry->distinctClause = NIL;
1826 qry->hasDistinctOn = false;
1827 }
1828 else if (linitial(stmt->distinctClause) == NULL)
1829 {
1830 /* We had SELECT DISTINCT */
1832 &qry->targetList,
1833 qry->sortClause,
1834 false);
1835 qry->hasDistinctOn = false;
1836 }
1837 else
1838 {
1839 /* We had SELECT DISTINCT ON */
1841 stmt->distinctClause,
1842 &qry->targetList,
1843 qry->sortClause);
1844 qry->hasDistinctOn = true;
1845 }
1846
1847 /* transform LIMIT */
1848 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
1849 EXPR_KIND_OFFSET, "OFFSET",
1850 stmt->limitOption);
1851 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
1852 EXPR_KIND_LIMIT, "LIMIT",
1853 stmt->limitOption);
1854 qry->limitOption = stmt->limitOption;
1855
1856 /* transform window clauses after we have seen all window functions */
1858 pstate->p_windowdefs,
1859 &qry->targetList);
1860
1861 /* resolve any still-unresolved output columns as being type text */
1862 if (pstate->p_resolve_unknowns)
1864
1865 qry->rtable = pstate->p_rtable;
1866 qry->rteperminfos = pstate->p_rteperminfos;
1867 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
1868
1869 qry->hasSubLinks = pstate->p_hasSubLinks;
1870 qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
1871 qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
1872 qry->hasAggs = pstate->p_hasAggs;
1873
1874 foreach(l, stmt->lockingClause)
1875 {
1876 transformLockingClause(pstate, qry,
1877 (LockingClause *) lfirst(l), false);
1878 }
1879
1880 assign_query_collations(pstate, qry);
1881
1882 /* this must be done after collations, for reliable comparison of exprs */
1883 if (pstate->p_hasAggs || qry->groupClause || qry->groupingSets || qry->havingQual)
1884 parseCheckAggregates(pstate, qry);
1885
1886 return qry;
1887}
List * transformGroupClause(ParseState *pstate, List *grouplist, bool groupByAll, List **groupingSets, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99)
List * transformSortClause(ParseState *pstate, List *orderlist, List **targetlist, ParseExprKind exprKind, bool useSQL99)
List * transformDistinctOnClause(ParseState *pstate, List *distinctlist, List **targetlist, List *sortClause)
List * transformWindowDefinitions(ParseState *pstate, List *windowdefs, List **targetlist)
List * transformDistinctClause(ParseState *pstate, List **targetlist, List *sortClause, bool is_agg)
Node * transformLimitClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName, LimitOption limitOption)
@ 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_LIMIT
Definition parse_node.h:63
@ EXPR_KIND_GROUP_BY
Definition parse_node.h:60
static List * transformPLAssignStmtTarget(ParseState *pstate, List *tlist, SelectStmtPassthrough *passthru)
Definition analyze.c:3260
List * p_windowdefs
Definition parse_node.h:231
List * p_locking_clause
Definition parse_node.h:235
bool groupDistinct
Definition parsenodes.h:220
Node * limitCount
Definition parsenodes.h:234
Node * limitOffset
Definition parsenodes.h:233
LimitOption limitOption
Definition parsenodes.h:235
List * windowClause
Definition parsenodes.h:227
bool groupByAll
Definition parsenodes.h:221
List * sortClause
Definition parsenodes.h:231

References assign_query_collations(), CMD_SELECT, Query::commandType, Query::cteList, Query::distinctClause, ereport, errcode(), errmsg, ERROR, EXPR_KIND_GROUP_BY, EXPR_KIND_HAVING, EXPR_KIND_LIMIT, EXPR_KIND_OFFSET, EXPR_KIND_ORDER_BY, EXPR_KIND_SELECT_TARGET, EXPR_KIND_WHERE, exprLocation(), fb(), Query::groupByAll, Query::groupClause, Query::groupDistinct, Query::groupingSets, Query::havingQual, Query::jointree, lfirst, Query::limitCount, Query::limitOffset, Query::limitOption, linitial, makeFromExpr(), makeNode, markTargetListOrigins(), NIL, ParseState::p_hasAggs, ParseState::p_hasModifyingCTE, ParseState::p_hasSubLinks, ParseState::p_hasTargetSRFs, ParseState::p_hasWindowFuncs, ParseState::p_joinlist, ParseState::p_locking_clause, ParseState::p_resolve_unknowns, ParseState::p_rtable, ParseState::p_rteperminfos, ParseState::p_windowdefs, parseCheckAggregates(), parser_errposition(), resolveTargetListUnknowns(), Query::rtable, Query::sortClause, stmt, Query::targetList, transformDistinctClause(), transformDistinctOnClause(), transformFromClause(), transformGroupClause(), transformLimitClause(), transformLockingClause(), transformPLAssignStmtTarget(), transformSortClause(), transformTargetList(), transformWhereClause(), transformWindowDefinitions(), transformWithClause(), and Query::windowClause.

Referenced by transformPLAssignStmt(), and transformStmt().

◆ transformSetOperationStmt()

static Query * transformSetOperationStmt ( ParseState pstate,
SelectStmt stmt 
)
static

Definition at line 2116 of file analyze.c.

2117{
2118 Query *qry = makeNode(Query);
2120 int leftmostRTI;
2123 List *sortClause;
2124 Node *limitOffset;
2125 Node *limitCount;
2126 List *lockingClause;
2127 WithClause *withClause;
2128 Node *node;
2130 *lct,
2131 *lcm,
2132 *lcc,
2133 *l;
2135 *targetnames,
2136 *sv_namespace;
2137 int sv_rtable_length;
2140 int sortcolindex;
2141 int tllen;
2142
2143 qry->commandType = CMD_SELECT;
2144
2145 /*
2146 * Find leftmost leaf SelectStmt. We currently only need to do this in
2147 * order to deliver a suitable error message if there's an INTO clause
2148 * there, implying the set-op tree is in a context that doesn't allow
2149 * INTO. (transformSetOperationTree would throw error anyway, but it
2150 * seems worth the trouble to throw a different error for non-leftmost
2151 * INTO, so we produce that error in transformSetOperationTree.)
2152 */
2153 leftmostSelect = stmt->larg;
2154 while (leftmostSelect && leftmostSelect->op != SETOP_NONE)
2157 leftmostSelect->larg == NULL);
2158 if (leftmostSelect->intoClause)
2159 ereport(ERROR,
2161 errmsg("SELECT ... INTO is not allowed here"),
2162 parser_errposition(pstate,
2163 exprLocation((Node *) leftmostSelect->intoClause))));
2164
2165 /*
2166 * We need to extract ORDER BY and other top-level clauses here and not
2167 * let transformSetOperationTree() see them --- else it'll just recurse
2168 * right back here!
2169 */
2170 sortClause = stmt->sortClause;
2171 limitOffset = stmt->limitOffset;
2172 limitCount = stmt->limitCount;
2173 lockingClause = stmt->lockingClause;
2174 withClause = stmt->withClause;
2175
2176 stmt->sortClause = NIL;
2177 stmt->limitOffset = NULL;
2178 stmt->limitCount = NULL;
2179 stmt->lockingClause = NIL;
2180 stmt->withClause = NULL;
2181
2182 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
2183 if (lockingClause)
2184 ereport(ERROR,
2186 /*------
2187 translator: %s is a SQL row locking clause such as FOR UPDATE */
2188 errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
2190 linitial(lockingClause))->strength))));
2191
2192 /* Process the WITH clause independently of all else */
2193 if (withClause)
2194 {
2195 qry->hasRecursive = withClause->recursive;
2196 qry->cteList = transformWithClause(pstate, withClause);
2197 qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
2198 }
2199
2200 /*
2201 * Recursively transform the components of the tree.
2202 */
2204 transformSetOperationTree(pstate, stmt, true, NULL));
2205 Assert(sostmt);
2206 qry->setOperations = (Node *) sostmt;
2207
2208 /*
2209 * Re-find leftmost SELECT (now it's a sub-query in rangetable)
2210 */
2211 node = sostmt->larg;
2212 while (node && IsA(node, SetOperationStmt))
2213 node = ((SetOperationStmt *) node)->larg;
2214 Assert(node && IsA(node, RangeTblRef));
2215 leftmostRTI = ((RangeTblRef *) node)->rtindex;
2216 leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
2218
2219 /*
2220 * Generate dummy targetlist for outer query using column names of
2221 * leftmost select and common datatypes/collations of topmost set
2222 * operation. Also make lists of the dummy vars and their names for use
2223 * in parsing ORDER BY.
2224 *
2225 * Note: we use leftmostRTI as the varno of the dummy variables. It
2226 * shouldn't matter too much which RT index they have, as long as they
2227 * have one that corresponds to a real RT entry; else funny things may
2228 * happen when the tree is mashed by rule rewriting.
2229 */
2230 qry->targetList = NIL;
2231 targetvars = NIL;
2232 targetnames = NIL;
2234 palloc0(list_length(sostmt->colTypes) * sizeof(ParseNamespaceColumn));
2235 sortcolindex = 0;
2236
2237 forfour(lct, sostmt->colTypes,
2238 lcm, sostmt->colTypmods,
2239 lcc, sostmt->colCollations,
2240 left_tlist, leftmostQuery->targetList)
2241 {
2246 char *colName;
2248 Var *var;
2249
2250 Assert(!lefttle->resjunk);
2251 colName = pstrdup(lefttle->resname);
2252 var = makeVar(leftmostRTI,
2253 lefttle->resno,
2254 colType,
2255 colTypmod,
2257 0);
2258 var->location = exprLocation((Node *) lefttle->expr);
2259 tle = makeTargetEntry((Expr *) var,
2260 (AttrNumber) pstate->p_next_resno++,
2261 colName,
2262 false);
2263 qry->targetList = lappend(qry->targetList, tle);
2267 sortnscolumns[sortcolindex].p_varattno = lefttle->resno;
2268 sortnscolumns[sortcolindex].p_vartype = colType;
2269 sortnscolumns[sortcolindex].p_vartypmod = colTypmod;
2272 sortnscolumns[sortcolindex].p_varattnosyn = lefttle->resno;
2273 sortcolindex++;
2274 }
2275
2276 /*
2277 * As a first step towards supporting sort clauses that are expressions
2278 * using the output columns, generate a namespace entry that makes the
2279 * output columns visible. A Join RTE node is handy for this, since we
2280 * can easily control the Vars generated upon matches.
2281 *
2282 * Note: we don't yet do anything useful with such cases, but at least
2283 * "ORDER BY upper(foo)" will draw the right error message rather than
2284 * "foo not found".
2285 */
2287
2291 JOIN_INNER,
2292 0,
2293 targetvars,
2294 NIL,
2295 NIL,
2296 NULL,
2297 NULL,
2298 false);
2299
2300 sv_namespace = pstate->p_namespace;
2301 pstate->p_namespace = NIL;
2302
2303 /* add jnsitem to column namespace only */
2304 addNSItemToQuery(pstate, jnsitem, false, false, true);
2305
2306 /*
2307 * For now, we don't support resjunk sort clauses on the output of a
2308 * setOperation tree --- you can only use the SQL92-spec options of
2309 * selecting an output column by name or number. Enforce by checking that
2310 * transformSortClause doesn't add any items to tlist. Note, if changing
2311 * this, add_setop_child_rel_equivalences() will need to be updated.
2312 */
2314
2315 qry->sortClause = transformSortClause(pstate,
2316 sortClause,
2317 &qry->targetList,
2319 false /* allow SQL92 rules */ );
2320
2321 /* restore namespace, remove join RTE from rtable */
2322 pstate->p_namespace = sv_namespace;
2323 pstate->p_rtable = list_truncate(pstate->p_rtable, sv_rtable_length);
2324
2325 if (tllen != list_length(qry->targetList))
2326 ereport(ERROR,
2328 errmsg("invalid UNION/INTERSECT/EXCEPT ORDER BY clause"),
2329 errdetail("Only result column names can be used, not expressions or functions."),
2330 errhint("Add the expression/function to every SELECT, or move the UNION into a FROM clause."),
2331 parser_errposition(pstate,
2333
2334 qry->limitOffset = transformLimitClause(pstate, limitOffset,
2335 EXPR_KIND_OFFSET, "OFFSET",
2336 stmt->limitOption);
2337 qry->limitCount = transformLimitClause(pstate, limitCount,
2338 EXPR_KIND_LIMIT, "LIMIT",
2339 stmt->limitOption);
2340 qry->limitOption = stmt->limitOption;
2341
2342 qry->rtable = pstate->p_rtable;
2343 qry->rteperminfos = pstate->p_rteperminfos;
2344 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
2345
2346 qry->hasSubLinks = pstate->p_hasSubLinks;
2347 qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
2348 qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
2349 qry->hasAggs = pstate->p_hasAggs;
2350
2351 foreach(l, lockingClause)
2352 {
2353 transformLockingClause(pstate, qry,
2354 (LockingClause *) lfirst(l), false);
2355 }
2356
2357 assign_query_collations(pstate, qry);
2358
2359 /* this must be done after collations, for reliable comparison of exprs */
2360 if (pstate->p_hasAggs || qry->groupClause || qry->groupingSets || qry->havingQual)
2361 parseCheckAggregates(pstate, qry);
2362
2363 return qry;
2364}
void * palloc0(Size size)
Definition mcxt.c:1420
@ JOIN_INNER
Definition nodes.h:303
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)
static Node * transformSetOperationTree(ParseState *pstate, SelectStmt *stmt, bool isTopLevel, List **targetlist)
Definition analyze.c:2421
#define forfour(cell1, list1, cell2, list2, cell3, list3, cell4, list4)
Definition pg_list.h:607
#define lfirst_oid(lc)
Definition pg_list.h:174

References addNSItemToQuery(), addRangeTableEntryForJoin(), Assert, assign_query_collations(), castNode, CMD_SELECT, Query::commandType, Query::cteList, ereport, errcode(), errdetail(), errhint(), errmsg, ERROR, EXPR_KIND_LIMIT, EXPR_KIND_OFFSET, EXPR_KIND_ORDER_BY, exprLocation(), fb(), forfour, Query::groupClause, Query::groupingSets, Query::havingQual, IsA, JOIN_INNER, Query::jointree, lappend(), LCS_asString(), lfirst, lfirst_int, lfirst_oid, Query::limitCount, Query::limitOffset, Query::limitOption, linitial, list_length(), list_nth(), list_truncate(), Var::location, makeFromExpr(), makeNode, makeString(), makeTargetEntry(), makeVar(), NIL, ParseState::p_hasAggs, ParseState::p_hasModifyingCTE, ParseState::p_hasSubLinks, ParseState::p_hasTargetSRFs, ParseState::p_hasWindowFuncs, ParseState::p_joinlist, ParseState::p_namespace, ParseState::p_next_resno, ParseState::p_rtable, ParseState::p_rteperminfos, palloc0(), parseCheckAggregates(), parser_errposition(), pstrdup(), WithClause::recursive, rt_fetch, Query::rtable, SETOP_NONE, Query::setOperations, Query::sortClause, stmt, Query::targetList, transformLimitClause(), transformLockingClause(), transformSetOperationTree(), transformSortClause(), and transformWithClause().

Referenced by transformStmt().

◆ transformSetOperationTree()

static Node * transformSetOperationTree ( ParseState pstate,
SelectStmt stmt,
bool  isTopLevel,
List **  targetlist 
)
static

Definition at line 2421 of file analyze.c.

2423{
2424 bool isLeaf;
2425
2427
2428 /* Guard against stack overflow due to overly complex set-expressions */
2430
2431 /*
2432 * Validity-check both leaf and internal SELECTs for disallowed ops.
2433 */
2434 if (stmt->intoClause)
2435 ereport(ERROR,
2437 errmsg("INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT"),
2438 parser_errposition(pstate,
2439 exprLocation((Node *) stmt->intoClause))));
2440
2441 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
2442 if (stmt->lockingClause)
2443 ereport(ERROR,
2445 /*------
2446 translator: %s is a SQL row locking clause such as FOR UPDATE */
2447 errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
2449 linitial(stmt->lockingClause))->strength))));
2450
2451 /*
2452 * If an internal node of a set-op tree has ORDER BY, LIMIT, FOR UPDATE,
2453 * or WITH clauses attached, we need to treat it like a leaf node to
2454 * generate an independent sub-Query tree. Otherwise, it can be
2455 * represented by a SetOperationStmt node underneath the parent Query.
2456 */
2457 if (stmt->op == SETOP_NONE)
2458 {
2459 Assert(stmt->larg == NULL && stmt->rarg == NULL);
2460 isLeaf = true;
2461 }
2462 else
2463 {
2464 Assert(stmt->larg != NULL && stmt->rarg != NULL);
2465 if (stmt->sortClause || stmt->limitOffset || stmt->limitCount ||
2466 stmt->lockingClause || stmt->withClause)
2467 isLeaf = true;
2468 else
2469 isLeaf = false;
2470 }
2471
2472 if (isLeaf)
2473 {
2474 /* Process leaf SELECT */
2478
2479 /*
2480 * Transform SelectStmt into a Query.
2481 *
2482 * This works the same as SELECT transformation normally would, except
2483 * that we prevent resolving unknown-type outputs as TEXT. This does
2484 * not change the subquery's semantics since if the column type
2485 * matters semantically, it would have been resolved to something else
2486 * anyway. Doing this lets us resolve such outputs using
2487 * select_common_type(), below.
2488 *
2489 * Note: previously transformed sub-queries don't affect the parsing
2490 * of this sub-query, because they are not in the toplevel pstate's
2491 * namespace list.
2492 */
2493 selectQuery = parse_sub_analyze((Node *) stmt, pstate,
2494 NULL, false, false);
2495
2496 /*
2497 * Check for bogus references to Vars on the current query level (but
2498 * upper-level references are okay). Normally this can't happen
2499 * because the namespace will be empty, but it could happen if we are
2500 * inside a rule.
2501 */
2502 if (pstate->p_namespace)
2503 {
2505 ereport(ERROR,
2507 errmsg("UNION/INTERSECT/EXCEPT member statement cannot refer to other relations of same query level"),
2508 parser_errposition(pstate,
2510 }
2511
2512 /*
2513 * Extract a list of the non-junk TLEs for upper-level processing.
2514 */
2515 if (targetlist)
2516 {
2517 ListCell *tl;
2518
2519 *targetlist = NIL;
2520 foreach(tl, selectQuery->targetList)
2521 {
2523
2524 if (!tle->resjunk)
2525 *targetlist = lappend(*targetlist, tle);
2526 }
2527 }
2528
2529 /*
2530 * Make the leaf query be a subquery in the top-level rangetable.
2531 */
2534 NULL,
2535 false,
2536 false);
2537
2538 /*
2539 * Return a RangeTblRef to replace the SelectStmt in the set-op tree.
2540 */
2542 rtr->rtindex = nsitem->p_rtindex;
2543 return (Node *) rtr;
2544 }
2545 else
2546 {
2547 /* Process an internal node (set operation node) */
2551 const char *context;
2552 bool recursive = (pstate->p_parent_cte &&
2553 pstate->p_parent_cte->cterecursive);
2554
2555 context = (stmt->op == SETOP_UNION ? "UNION" :
2556 (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
2557 "EXCEPT"));
2558
2559 op->op = stmt->op;
2560 op->all = stmt->all;
2561
2562 /*
2563 * Recursively transform the left child node.
2564 */
2565 op->larg = transformSetOperationTree(pstate, stmt->larg,
2566 false,
2567 &ltargetlist);
2568
2569 /*
2570 * If we are processing a recursive union query, now is the time to
2571 * examine the non-recursive term's output columns and mark the
2572 * containing CTE as having those result columns. We should do this
2573 * only at the topmost setop of the CTE, of course.
2574 */
2575 if (isTopLevel && recursive)
2577
2578 /*
2579 * Recursively transform the right child node.
2580 */
2581 op->rarg = transformSetOperationTree(pstate, stmt->rarg,
2582 false,
2583 &rtargetlist);
2584
2585 constructSetOpTargetlist(pstate, op, ltargetlist, rtargetlist, targetlist,
2586 context, recursive);
2587
2588 return (Node *) op;
2589 }
2590}
@ SETOP_INTERSECT
static void determineRecursiveColTypes(ParseState *pstate, Node *larg, List *nrtargetlist)
Definition analyze.c:2769
void constructSetOpTargetlist(ParseState *pstate, SetOperationStmt *op, const List *ltargetlist, const List *rtargetlist, List **targetlist, const char *context, bool recursive)
Definition analyze.c:2605
Query * parse_sub_analyze(Node *parseTree, ParseState *parentParseState, CommonTableExpr *parentCTE, bool locked_from_parent, bool resolve_unknowns)
Definition analyze.c:244
void check_stack_depth(void)
Definition stack_depth.c:96
int locate_var_of_level(Node *node, int levelsup)
Definition var.c:555

References addRangeTableEntryForSubquery(), SetOperationStmt::all, Assert, check_stack_depth(), constructSetOpTargetlist(), contain_vars_of_level(), determineRecursiveColTypes(), ereport, errcode(), errmsg, ERROR, exprLocation(), fb(), IsA, lappend(), SetOperationStmt::larg, LCS_asString(), lfirst, linitial, locate_var_of_level(), makeNode, NIL, SetOperationStmt::op, ParseState::p_namespace, ParseState::p_parent_cte, parse_sub_analyze(), parser_errposition(), SetOperationStmt::rarg, SETOP_INTERSECT, SETOP_NONE, SETOP_UNION, stmt, and transformSetOperationTree().

Referenced by transformSetOperationStmt(), and transformSetOperationTree().

◆ transformStmt()

Query * transformStmt ( ParseState pstate,
Node parseTree 
)

Definition at line 334 of file analyze.c.

335{
336 Query *result;
337
338#ifdef DEBUG_NODE_TESTS_ENABLED
339
340 /*
341 * We apply debug_raw_expression_coverage_test testing to basic DML
342 * statements; we can't just run it on everything because
343 * raw_expression_tree_walker() doesn't claim to handle utility
344 * statements.
345 */
347 {
348 switch (nodeTag(parseTree))
349 {
350 case T_SelectStmt:
351 case T_InsertStmt:
352 case T_UpdateStmt:
353 case T_DeleteStmt:
354 case T_MergeStmt:
356 break;
357 default:
358 break;
359 }
360 }
361#endif /* DEBUG_NODE_TESTS_ENABLED */
362
363 /*
364 * Caution: when changing the set of statement types that have non-default
365 * processing here, see also stmt_requires_parse_analysis() and
366 * analyze_requires_snapshot().
367 */
368 switch (nodeTag(parseTree))
369 {
370 /*
371 * Optimizable statements
372 */
373 case T_InsertStmt:
375 break;
376
377 case T_DeleteStmt:
379 break;
380
381 case T_UpdateStmt:
383 break;
384
385 case T_MergeStmt:
387 break;
388
389 case T_SelectStmt:
390 {
392
393 if (n->valuesLists)
394 result = transformValuesClause(pstate, n);
395 else if (n->op == SETOP_NONE)
396 result = transformSelectStmt(pstate, n, NULL);
397 else
399 }
400 break;
401
402 case T_ReturnStmt:
404 break;
405
406 case T_PLAssignStmt:
409 break;
410
411 /*
412 * Special cases
413 */
417 break;
418
419 case T_ExplainStmt:
422 break;
423
427 break;
428
429 case T_CallStmt:
430 result = transformCallStmt(pstate,
431 (CallStmt *) parseTree);
432 break;
433
434 default:
435
436 /*
437 * other statements don't require any transformation; just return
438 * the original parsetree with a Query node plastered on top.
439 */
441 result->commandType = CMD_UTILITY;
442 result->utilityStmt = parseTree;
443 break;
444 }
445
446 /* Mark as original query until we learn differently */
447 result->querySource = QSRC_ORIGINAL;
448 result->canSetTag = true;
449
450 return result;
451}
Query * transformMergeStmt(ParseState *pstate, MergeStmt *stmt)
@ QSRC_ORIGINAL
Definition parsenodes.h:36
static Query * transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
Definition analyze.c:575
static Query * transformReturnStmt(ParseState *pstate, ReturnStmt *stmt)
Definition analyze.c:2823
static Query * transformPLAssignStmt(ParseState *pstate, PLAssignStmt *stmt)
Definition analyze.c:3185
static Query * transformCreateTableAsStmt(ParseState *pstate, CreateTableAsStmt *stmt)
Definition analyze.c:3512
static Query * transformCallStmt(ParseState *pstate, CallStmt *stmt)
Definition analyze.c:3591
static Query * transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
Definition analyze.c:2116
static Query * transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
Definition analyze.c:2854
static Query * transformExplainStmt(ParseState *pstate, ExplainStmt *stmt)
Definition analyze.c:3460
static Query * transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
Definition analyze.c:3367
static Query * transformInsertStmt(ParseState *pstate, InsertStmt *stmt)
Definition analyze.c:661
static Query * transformValuesClause(ParseState *pstate, SelectStmt *stmt)
Definition analyze.c:1897
List * valuesLists
SetOperation op

References CMD_UTILITY, fb(), makeNode, nodeTag, SelectStmt::op, QSRC_ORIGINAL, result, SETOP_NONE, transformCallStmt(), transformCreateTableAsStmt(), transformDeclareCursorStmt(), transformDeleteStmt(), transformExplainStmt(), transformInsertStmt(), transformMergeStmt(), transformPLAssignStmt(), transformReturnStmt(), transformSelectStmt(), transformSetOperationStmt(), transformUpdateStmt(), transformValuesClause(), and SelectStmt::valuesLists.

Referenced by interpret_AS_clause(), parse_sub_analyze(), transformCreateTableAsStmt(), transformDeclareCursorStmt(), transformInsertStmt(), transformJsonArrayQueryConstructor(), transformOptionalSelectInto(), and transformRuleStmt().

◆ transformTopLevelStmt()

Query * transformTopLevelStmt ( ParseState pstate,
RawStmt parseTree 
)

Definition at line 271 of file analyze.c.

272{
273 Query *result;
274
275 /* We're at top level, so allow SELECT INTO */
277
278 result->stmt_location = parseTree->stmt_location;
279 result->stmt_len = parseTree->stmt_len;
280
281 return result;
282}

References fb(), result, and transformOptionalSelectInto().

Referenced by inline_function(), parse_analyze_fixedparams(), parse_analyze_varparams(), and parse_analyze_withcb().

◆ transformUpdateStmt()

static Query * transformUpdateStmt ( ParseState pstate,
UpdateStmt stmt 
)
static

Definition at line 2854 of file analyze.c.

2855{
2856 Query *qry = makeNode(Query);
2858 Node *qual;
2859
2860 qry->commandType = CMD_UPDATE;
2861
2862 /* process the WITH clause independently of all else */
2863 if (stmt->withClause)
2864 {
2865 qry->hasRecursive = stmt->withClause->recursive;
2866 qry->cteList = transformWithClause(pstate, stmt->withClause);
2867 qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
2868 }
2869
2870 qry->resultRelation = setTargetTable(pstate, stmt->relation,
2871 stmt->relation->inh,
2872 true,
2873 ACL_UPDATE);
2874
2875 /* disallow UPDATE ... WHERE CURRENT OF on a view */
2876 if (stmt->whereClause &&
2877 IsA(stmt->whereClause, CurrentOfExpr) &&
2878 pstate->p_target_relation->rd_rel->relkind == RELKIND_VIEW)
2879 ereport(ERROR,
2881 errmsg("WHERE CURRENT OF on a view is not implemented"));
2882
2883 if (stmt->forPortionOf)
2885 qry->resultRelation,
2887 true);
2888
2889 nsitem = pstate->p_target_nsitem;
2890
2891 /* subqueries in FROM cannot access the result relation */
2892 nsitem->p_lateral_only = true;
2893 nsitem->p_lateral_ok = false;
2894
2895 /*
2896 * the FROM clause is non-standard SQL syntax. We used to be able to do
2897 * this with REPLACE in POSTQUEL so we keep the feature.
2898 */
2899 transformFromClause(pstate, stmt->fromClause);
2900
2901 /* remaining clauses can reference the result relation normally */
2902 nsitem->p_lateral_only = false;
2903 nsitem->p_lateral_ok = true;
2904
2905 qual = transformWhereClause(pstate, stmt->whereClause,
2906 EXPR_KIND_WHERE, "WHERE");
2907
2908 transformReturningClause(pstate, qry, stmt->returningClause,
2910
2911 /*
2912 * Now we are done with SELECT-like processing, and can get on with
2913 * transforming the target list to match the UPDATE target columns.
2914 */
2915 qry->targetList = transformUpdateTargetList(pstate, stmt->targetList,
2916 qry->forPortionOf);
2917
2918 qry->rtable = pstate->p_rtable;
2919 qry->rteperminfos = pstate->p_rteperminfos;
2920 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
2921
2922 qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
2923 qry->hasSubLinks = pstate->p_hasSubLinks;
2924
2925 assign_query_collations(pstate, qry);
2926
2927 return qry;
2928}
@ CMD_UPDATE
Definition nodes.h:276

References ACL_UPDATE, assign_query_collations(), CMD_UPDATE, Query::commandType, Query::cteList, ereport, errcode(), errmsg, ERROR, EXPR_KIND_RETURNING, EXPR_KIND_WHERE, fb(), Query::forPortionOf, IsA, Query::jointree, makeFromExpr(), makeNode, ParseState::p_hasModifyingCTE, ParseState::p_hasSubLinks, ParseState::p_hasTargetSRFs, ParseState::p_joinlist, ParseNamespaceItem::p_lateral_only, ParseState::p_rtable, ParseState::p_rteperminfos, ParseState::p_target_nsitem, ParseState::p_target_relation, RelationData::rd_rel, Query::rtable, setTargetTable(), stmt, Query::targetList, transformForPortionOfClause(), transformFromClause(), transformReturningClause(), transformUpdateTargetList(), transformWhereClause(), and transformWithClause().

Referenced by transformStmt().

◆ transformUpdateTargetList()

List * transformUpdateTargetList ( ParseState pstate,
List origTlist,
ForPortionOfExpr forPortionOf 
)

Definition at line 2935 of file analyze.c.

2936{
2937 List *tlist = NIL;
2940 ListCell *tl;
2941
2942 tlist = transformTargetList(pstate, origTlist,
2944
2945 /* Prepare to assign non-conflicting resnos to resjunk attributes */
2948
2949 /* Prepare non-junk columns for assignment to target table */
2952
2953 foreach(tl, tlist)
2954 {
2957 int attrno;
2958
2959 if (tle->resjunk)
2960 {
2961 /*
2962 * Resjunk nodes need no additional processing, but be sure they
2963 * have resnos that do not match any target columns; else rewriter
2964 * or planner might get confused. They don't need a resname
2965 * either.
2966 */
2967 tle->resno = (AttrNumber) pstate->p_next_resno++;
2968 tle->resname = NULL;
2969 continue;
2970 }
2971 if (orig_tl == NULL)
2972 elog(ERROR, "UPDATE target count mismatch --- internal error");
2974
2976 origTarget->name, true);
2978 ereport(ERROR,
2980 errmsg("column \"%s\" of relation \"%s\" does not exist",
2981 origTarget->name,
2983 (origTarget->indirection != NIL &&
2984 strcmp(origTarget->name, pstate->p_target_nsitem->p_names->aliasname) == 0) ?
2985 errhint("SET target columns cannot be qualified with the relation name.") : 0,
2986 parser_errposition(pstate, origTarget->location)));
2987
2988 /*
2989 * If this is a FOR PORTION OF update, forbid directly setting the
2990 * range column, since that would conflict with the implicit updates.
2991 */
2992 if (forPortionOf != NULL)
2993 {
2994 if (attrno == forPortionOf->rangeVar->varattno)
2995 ereport(ERROR,
2997 errmsg("cannot update column \"%s\" because it is used in FOR PORTION OF",
2998 origTarget->name),
2999 parser_errposition(pstate, origTarget->location)));
3000 }
3001
3002 updateTargetListEntry(pstate, tle, origTarget->name,
3003 attrno,
3004 origTarget->indirection,
3005 origTarget->location);
3006
3007 /* Mark the target column as requiring update permissions */
3008 target_perminfo->updatedCols = bms_add_member(target_perminfo->updatedCols,
3010
3012 }
3013 if (orig_tl != NULL)
3014 elog(ERROR, "UPDATE target count mismatch --- internal error");
3015
3016 return tlist;
3017}
@ EXPR_KIND_UPDATE_SOURCE
Definition parse_node.h:56
void updateTargetListEntry(ParseState *pstate, TargetEntry *tle, char *colname, int attrno, List *indirection, int location)
static ListCell * lnext(const List *l, const ListCell *c)
Definition pg_list.h:375
char * aliasname
Definition primnodes.h:52

References Alias::aliasname, attnameAttNum(), bms_add_member(), elog, ereport, errcode(), errhint(), errmsg, ERROR, EXPR_KIND_UPDATE_SOURCE, fb(), FirstLowInvalidHeapAttributeNumber, InvalidAttrNumber, lfirst, lfirst_node, list_head(), lnext(), NIL, ParseNamespaceItem::p_names, ParseState::p_next_resno, ParseNamespaceItem::p_perminfo, ParseState::p_target_nsitem, ParseState::p_target_relation, parser_errposition(), ForPortionOfExpr::rangeVar, RelationGetNumberOfAttributes, RelationGetRelationName, transformTargetList(), updateTargetListEntry(), and Var::varattno.

Referenced by transformMergeStmt(), transformOnConflictClause(), and transformUpdateStmt().

◆ transformValuesClause()

static Query * transformValuesClause ( ParseState pstate,
SelectStmt stmt 
)
static

Definition at line 1897 of file analyze.c.

1898{
1899 Query *qry = makeNode(Query);
1900 List *exprsLists = NIL;
1901 List *coltypes = NIL;
1902 List *coltypmods = NIL;
1904 List **colexprs = NULL;
1905 int sublist_length = -1;
1906 bool lateral = false;
1908 ListCell *lc;
1909 ListCell *lc2;
1910 int i;
1911
1912 qry->commandType = CMD_SELECT;
1913
1914 /* Most SELECT stuff doesn't apply in a VALUES clause */
1915 Assert(stmt->distinctClause == NIL);
1916 Assert(stmt->intoClause == NULL);
1917 Assert(stmt->targetList == NIL);
1918 Assert(stmt->fromClause == NIL);
1919 Assert(stmt->whereClause == NULL);
1920 Assert(stmt->groupClause == NIL);
1921 Assert(stmt->havingClause == NULL);
1922 Assert(stmt->windowClause == NIL);
1923 Assert(stmt->op == SETOP_NONE);
1924
1925 /* process the WITH clause independently of all else */
1926 if (stmt->withClause)
1927 {
1928 qry->hasRecursive = stmt->withClause->recursive;
1929 qry->cteList = transformWithClause(pstate, stmt->withClause);
1930 qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
1931 }
1932
1933 /*
1934 * For each row of VALUES, transform the raw expressions.
1935 *
1936 * Note that the intermediate representation we build is column-organized
1937 * not row-organized. That simplifies the type and collation processing
1938 * below.
1939 */
1940 foreach(lc, stmt->valuesLists)
1941 {
1942 List *sublist = (List *) lfirst(lc);
1943
1944 /*
1945 * Do basic expression transformation (same as a ROW() expr, but here
1946 * we disallow SetToDefault)
1947 */
1949 EXPR_KIND_VALUES, false);
1950
1951 /*
1952 * All the sublists must be the same length, *after* transformation
1953 * (which might expand '*' into multiple items). The VALUES RTE can't
1954 * handle anything different.
1955 */
1956 if (sublist_length < 0)
1957 {
1958 /* Remember post-transformation length of first sublist */
1960 /* and allocate array for per-column lists */
1961 colexprs = (List **) palloc0(sublist_length * sizeof(List *));
1962 }
1963 else if (sublist_length != list_length(sublist))
1964 {
1965 ereport(ERROR,
1967 errmsg("VALUES lists must all be the same length"),
1968 parser_errposition(pstate,
1969 exprLocation((Node *) sublist))));
1970 }
1971
1972 /* Build per-column expression lists */
1973 i = 0;
1974 foreach(lc2, sublist)
1975 {
1976 Node *col = (Node *) lfirst(lc2);
1977
1978 colexprs[i] = lappend(colexprs[i], col);
1979 i++;
1980 }
1981
1982 /* Release sub-list's cells to save memory */
1984
1985 /* Prepare an exprsLists element for this row */
1987 }
1988
1989 /*
1990 * Now resolve the common types of the columns, and coerce everything to
1991 * those types. Then identify the common typmod and common collation, if
1992 * any, of each column.
1993 *
1994 * We must do collation processing now because (1) assign_query_collations
1995 * doesn't process rangetable entries, and (2) we need to label the VALUES
1996 * RTE with column collations for use in the outer query. We don't
1997 * consider conflict of implicit collations to be an error here; instead
1998 * the column will just show InvalidOid as its collation, and you'll get a
1999 * failure later if that results in failure to resolve a collation.
2000 *
2001 * Note we modify the per-column expression lists in-place.
2002 */
2003 for (i = 0; i < sublist_length; i++)
2004 {
2005 Oid coltype;
2007 Oid colcoll;
2008
2009 coltype = select_common_type(pstate, colexprs[i], "VALUES", NULL);
2010
2011 foreach(lc, colexprs[i])
2012 {
2013 Node *col = (Node *) lfirst(lc);
2014
2015 col = coerce_to_common_type(pstate, col, coltype, "VALUES");
2016 lfirst(lc) = col;
2017 }
2018
2019 coltypmod = select_common_typmod(pstate, colexprs[i], coltype);
2020 colcoll = select_common_collation(pstate, colexprs[i], true);
2021
2022 coltypes = lappend_oid(coltypes, coltype);
2025 }
2026
2027 /*
2028 * Finally, rearrange the coerced expressions into row-organized lists.
2029 */
2030 for (i = 0; i < sublist_length; i++)
2031 {
2032 forboth(lc, colexprs[i], lc2, exprsLists)
2033 {
2034 Node *col = (Node *) lfirst(lc);
2035 List *sublist = lfirst(lc2);
2036
2038 lfirst(lc2) = sublist;
2039 }
2040 list_free(colexprs[i]);
2041 }
2042
2043 /*
2044 * Ordinarily there can't be any current-level Vars in the expression
2045 * lists, because the namespace was empty ... but if we're inside CREATE
2046 * RULE, then NEW/OLD references might appear. In that case we have to
2047 * mark the VALUES RTE as LATERAL.
2048 */
2049 if (pstate->p_rtable != NIL &&
2051 lateral = true;
2052
2053 /*
2054 * Generate the VALUES RTE
2055 */
2058 NULL, lateral, true);
2059 addNSItemToQuery(pstate, nsitem, true, true, true);
2060
2061 /*
2062 * Generate a targetlist as though expanding "*"
2063 */
2064 Assert(pstate->p_next_resno == 1);
2065 qry->targetList = expandNSItemAttrs(pstate, nsitem, 0, true, -1);
2066
2067 /*
2068 * The grammar allows attaching ORDER BY, LIMIT, and FOR UPDATE to a
2069 * VALUES, so cope.
2070 */
2071 qry->sortClause = transformSortClause(pstate,
2072 stmt->sortClause,
2073 &qry->targetList,
2075 false /* allow SQL92 rules */ );
2076
2077 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
2078 EXPR_KIND_OFFSET, "OFFSET",
2079 stmt->limitOption);
2080 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
2081 EXPR_KIND_LIMIT, "LIMIT",
2082 stmt->limitOption);
2083 qry->limitOption = stmt->limitOption;
2084
2085 if (stmt->lockingClause)
2086 ereport(ERROR,
2088 /*------
2089 translator: %s is a SQL row locking clause such as FOR UPDATE */
2090 errmsg("%s cannot be applied to VALUES",
2092 linitial(stmt->lockingClause))->strength))));
2093
2094 qry->rtable = pstate->p_rtable;
2095 qry->rteperminfos = pstate->p_rteperminfos;
2096 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
2097
2098 qry->hasSubLinks = pstate->p_hasSubLinks;
2099
2100 assign_query_collations(pstate, qry);
2101
2102 return qry;
2103}
void list_free(List *list)
Definition list.c:1546
List * expandNSItemAttrs(ParseState *pstate, ParseNamespaceItem *nsitem, int sublevels_up, bool require_col_privs, int location)

References addNSItemToQuery(), addRangeTableEntryForValues(), Assert, assign_query_collations(), CMD_SELECT, coerce_to_common_type(), Query::commandType, contain_vars_of_level(), Query::cteList, ereport, errcode(), errmsg, ERROR, expandNSItemAttrs(), EXPR_KIND_LIMIT, EXPR_KIND_OFFSET, EXPR_KIND_ORDER_BY, EXPR_KIND_VALUES, exprLocation(), fb(), forboth, i, Query::jointree, lappend(), lappend_int(), lappend_oid(), LCS_asString(), lfirst, Query::limitCount, Query::limitOffset, Query::limitOption, linitial, list_free(), list_length(), makeFromExpr(), makeNode, NIL, ParseState::p_hasModifyingCTE, ParseState::p_hasSubLinks, ParseState::p_joinlist, ParseState::p_next_resno, ParseState::p_rtable, ParseState::p_rteperminfos, palloc0(), parser_errposition(), Query::rtable, select_common_collation(), select_common_type(), select_common_typmod(), SETOP_NONE, Query::sortClause, stmt, Query::targetList, transformExpressionList(), transformLimitClause(), transformSortClause(), and transformWithClause().

Referenced by transformStmt().

Variable Documentation

◆ post_parse_analyze_hook