PostgreSQL Source Code git master
parse_clause.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "access/nbtree.h"
#include "access/table.h"
#include "access/tsmapi.h"
#include "catalog/catalog.h"
#include "catalog/pg_am.h"
#include "catalog/pg_amproc.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_type.h"
#include "commands/defrem.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/optimizer.h"
#include "parser/analyze.h"
#include "parser/parse_clause.h"
#include "parser/parse_coerce.h"
#include "parser/parse_collate.h"
#include "parser/parse_expr.h"
#include "parser/parse_func.h"
#include "parser/parse_oper.h"
#include "parser/parse_relation.h"
#include "parser/parse_target.h"
#include "parser/parse_type.h"
#include "parser/parser.h"
#include "rewrite/rewriteManip.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
#include "utils/lsyscache.h"
#include "utils/rel.h"
#include "utils/syscache.h"
Include dependency graph for parse_clause.c:

Go to the source code of this file.

Functions

static int extractRemainingColumns (ParseState *pstate, ParseNamespaceColumn *src_nscolumns, List *src_colnames, List **src_colnos, List **res_colnames, List **res_colvars, ParseNamespaceColumn *res_nscolumns)
 
static NodetransformJoinUsingClause (ParseState *pstate, List *leftVars, List *rightVars)
 
static NodetransformJoinOnClause (ParseState *pstate, JoinExpr *j, List *namespace)
 
static ParseNamespaceItemtransformTableEntry (ParseState *pstate, RangeVar *r)
 
static ParseNamespaceItemtransformRangeSubselect (ParseState *pstate, RangeSubselect *r)
 
static ParseNamespaceItemtransformRangeFunction (ParseState *pstate, RangeFunction *r)
 
static ParseNamespaceItemtransformRangeTableFunc (ParseState *pstate, RangeTableFunc *rtf)
 
static TableSampleClausetransformRangeTableSample (ParseState *pstate, RangeTableSample *rts)
 
static ParseNamespaceItemgetNSItemForSpecialRelationTypes (ParseState *pstate, RangeVar *rv)
 
static NodetransformFromClauseItem (ParseState *pstate, Node *n, ParseNamespaceItem **top_nsitem, List **namespace)
 
static VarbuildVarFromNSColumn (ParseState *pstate, ParseNamespaceColumn *nscol)
 
static NodebuildMergedJoinVar (ParseState *pstate, JoinType jointype, Var *l_colvar, Var *r_colvar)
 
static void markRelsAsNulledBy (ParseState *pstate, Node *n, int jindex)
 
static void setNamespaceColumnVisibility (List *namespace, bool cols_visible)
 
static void setNamespaceLateralState (List *namespace, bool lateral_only, bool lateral_ok)
 
static void checkExprIsVarFree (ParseState *pstate, Node *n, const char *constructName)
 
static TargetEntryfindTargetlistEntrySQL92 (ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
 
static TargetEntryfindTargetlistEntrySQL99 (ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
 
static int get_matching_location (int sortgroupref, List *sortgrouprefs, List *exprs)
 
static Listresolve_unique_index_expr (ParseState *pstate, InferClause *infer, Relation heapRel)
 
static ListaddTargetToGroupList (ParseState *pstate, TargetEntry *tle, List *grouplist, List *targetlist, int location)
 
static WindowClausefindWindowClause (List *wclist, const char *name)
 
static NodetransformFrameOffset (ParseState *pstate, int frameOptions, Oid rangeopfamily, Oid rangeopcintype, Oid *inRangeFunc, Node *clause)
 
void transformFromClause (ParseState *pstate, List *frmList)
 
int setTargetTable (ParseState *pstate, RangeVar *relation, bool inh, bool alsoSource, AclMode requiredPerms)
 
NodetransformWhereClause (ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
 
NodetransformLimitClause (ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName, LimitOption limitOption)
 
static void checkTargetlistEntrySQL92 (ParseState *pstate, TargetEntry *tle, ParseExprKind exprKind)
 
static Nodeflatten_grouping_sets (Node *expr, bool toplevel, bool *hasGroupingSets)
 
static Index transformGroupClauseExpr (List **flatresult, Bitmapset *seen_local, ParseState *pstate, Node *gexpr, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
 
static ListtransformGroupClauseList (List **flatresult, ParseState *pstate, List *list, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
 
static NodetransformGroupingSet (List **flatresult, ParseState *pstate, GroupingSet *gset, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
 
ListtransformGroupClause (ParseState *pstate, List *grouplist, List **groupingSets, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99)
 
ListtransformSortClause (ParseState *pstate, List *orderlist, List **targetlist, ParseExprKind exprKind, bool useSQL99)
 
ListtransformWindowDefinitions (ParseState *pstate, List *windowdefs, List **targetlist)
 
ListtransformDistinctClause (ParseState *pstate, List **targetlist, List *sortClause, bool is_agg)
 
ListtransformDistinctOnClause (ParseState *pstate, List *distinctlist, List **targetlist, List *sortClause)
 
void transformOnConflictArbiter (ParseState *pstate, OnConflictClause *onConflictClause, List **arbiterExpr, Node **arbiterWhere, Oid *constraint)
 
ListaddTargetToSortList (ParseState *pstate, TargetEntry *tle, List *sortlist, List *targetlist, SortBy *sortby)
 
Index assignSortGroupRef (TargetEntry *tle, List *tlist)
 
bool targetIsInSortList (TargetEntry *tle, Oid sortop, List *sortList)
 

Function Documentation

◆ addTargetToGroupList()

static List * addTargetToGroupList ( ParseState pstate,
TargetEntry tle,
List grouplist,
List targetlist,
int  location 
)
static

Definition at line 3537 of file parse_clause.c.

3539{
3540 Oid restype = exprType((Node *) tle->expr);
3541
3542 /* if tlist item is an UNKNOWN literal, change it to TEXT */
3543 if (restype == UNKNOWNOID)
3544 {
3545 tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3546 restype, TEXTOID, -1,
3549 -1);
3550 restype = TEXTOID;
3551 }
3552
3553 /* avoid making duplicate grouplist entries */
3554 if (!targetIsInSortList(tle, InvalidOid, grouplist))
3555 {
3557 Oid sortop;
3558 Oid eqop;
3559 bool hashable;
3560 ParseCallbackState pcbstate;
3561
3562 setup_parser_errposition_callback(&pcbstate, pstate, location);
3563
3564 /* determine the eqop and optional sortop */
3566 false, true, false,
3567 &sortop, &eqop, NULL,
3568 &hashable);
3569
3571
3572 grpcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3573 grpcl->eqop = eqop;
3574 grpcl->sortop = sortop;
3575 grpcl->reverse_sort = false; /* sortop is "less than", or
3576 * InvalidOid */
3577 grpcl->nulls_first = false; /* OK with or without sortop */
3578 grpcl->hashable = hashable;
3579
3580 grouplist = lappend(grouplist, grpcl);
3581 }
3582
3583 return grouplist;
3584}
List * lappend(List *list, void *datum)
Definition: list.c:339
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
#define makeNode(_type_)
Definition: nodes.h:155
Index assignSortGroupRef(TargetEntry *tle, List *tlist)
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:157
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:156
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:140
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:180
#define InvalidOid
Definition: postgres_ext.h:37
unsigned int Oid
Definition: postgres_ext.h:32
@ COERCE_IMPLICIT_CAST
Definition: primnodes.h:752
@ COERCION_IMPLICIT
Definition: primnodes.h:730
Definition: nodes.h:129
Index tleSortGroupRef
Definition: parsenodes.h:1447
Expr * expr
Definition: primnodes.h:2245

References assignSortGroupRef(), cancel_parser_errposition_callback(), COERCE_IMPLICIT_CAST, coerce_type(), COERCION_IMPLICIT, SortGroupClause::eqop, TargetEntry::expr, exprType(), get_sort_group_operators(), InvalidOid, lappend(), makeNode, SortGroupClause::nulls_first, SortGroupClause::reverse_sort, setup_parser_errposition_callback(), SortGroupClause::sortop, targetIsInSortList(), and SortGroupClause::tleSortGroupRef.

Referenced by transformDistinctClause(), transformDistinctOnClause(), and transformGroupClauseExpr().

◆ addTargetToSortList()

List * addTargetToSortList ( ParseState pstate,
TargetEntry tle,
List sortlist,
List targetlist,
SortBy sortby 
)

Definition at line 3393 of file parse_clause.c.

3395{
3396 Oid restype = exprType((Node *) tle->expr);
3397 Oid sortop;
3398 Oid eqop;
3399 bool hashable;
3400 bool reverse;
3401 int location;
3402 ParseCallbackState pcbstate;
3403
3404 /* if tlist item is an UNKNOWN literal, change it to TEXT */
3405 if (restype == UNKNOWNOID)
3406 {
3407 tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3408 restype, TEXTOID, -1,
3411 -1);
3412 restype = TEXTOID;
3413 }
3414
3415 /*
3416 * Rather than clutter the API of get_sort_group_operators and the other
3417 * functions we're about to use, make use of error context callback to
3418 * mark any error reports with a parse position. We point to the operator
3419 * location if present, else to the expression being sorted. (NB: use the
3420 * original untransformed expression here; the TLE entry might well point
3421 * at a duplicate expression in the regular SELECT list.)
3422 */
3423 location = sortby->location;
3424 if (location < 0)
3425 location = exprLocation(sortby->node);
3426 setup_parser_errposition_callback(&pcbstate, pstate, location);
3427
3428 /* determine the sortop, eqop, and directionality */
3429 switch (sortby->sortby_dir)
3430 {
3431 case SORTBY_DEFAULT:
3432 case SORTBY_ASC:
3434 true, true, false,
3435 &sortop, &eqop, NULL,
3436 &hashable);
3437 reverse = false;
3438 break;
3439 case SORTBY_DESC:
3441 false, true, true,
3442 NULL, &eqop, &sortop,
3443 &hashable);
3444 reverse = true;
3445 break;
3446 case SORTBY_USING:
3447 Assert(sortby->useOp != NIL);
3448 sortop = compatible_oper_opid(sortby->useOp,
3449 restype,
3450 restype,
3451 false);
3452
3453 /*
3454 * Verify it's a valid ordering operator, fetch the corresponding
3455 * equality operator, and determine whether to consider it like
3456 * ASC or DESC.
3457 */
3458 eqop = get_equality_op_for_ordering_op(sortop, &reverse);
3459 if (!OidIsValid(eqop))
3460 ereport(ERROR,
3461 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3462 errmsg("operator %s is not a valid ordering operator",
3463 strVal(llast(sortby->useOp))),
3464 errhint("Ordering operators must be \"<\" or \">\" members of btree operator families.")));
3465
3466 /*
3467 * Also see if the equality operator is hashable.
3468 */
3469 hashable = op_hashjoinable(eqop, restype);
3470 break;
3471 default:
3472 elog(ERROR, "unrecognized sortby_dir: %d", sortby->sortby_dir);
3473 sortop = InvalidOid; /* keep compiler quiet */
3474 eqop = InvalidOid;
3475 hashable = false;
3476 reverse = false;
3477 break;
3478 }
3479
3481
3482 /* avoid making duplicate sortlist entries */
3483 if (!targetIsInSortList(tle, sortop, sortlist))
3484 {
3486
3487 sortcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3488
3489 sortcl->eqop = eqop;
3490 sortcl->sortop = sortop;
3491 sortcl->hashable = hashable;
3492 sortcl->reverse_sort = reverse;
3493
3494 switch (sortby->sortby_nulls)
3495 {
3497 /* NULLS FIRST is default for DESC; other way for ASC */
3498 sortcl->nulls_first = reverse;
3499 break;
3500 case SORTBY_NULLS_FIRST:
3501 sortcl->nulls_first = true;
3502 break;
3503 case SORTBY_NULLS_LAST:
3504 sortcl->nulls_first = false;
3505 break;
3506 default:
3507 elog(ERROR, "unrecognized sortby_nulls: %d",
3508 sortby->sortby_nulls);
3509 break;
3510 }
3511
3512 sortlist = lappend(sortlist, sortcl);
3513 }
3514
3515 return sortlist;
3516}
#define Assert(condition)
Definition: c.h:815
#define OidIsValid(objectId)
Definition: c.h:732
int errhint(const char *fmt,...)
Definition: elog.c:1317
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
#define ereport(elevel,...)
Definition: elog.h:149
Oid get_equality_op_for_ordering_op(Oid opno, bool *reverse)
Definition: lsyscache.c:267
bool op_hashjoinable(Oid opno, Oid inputtype)
Definition: lsyscache.c:1437
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1388
Oid compatible_oper_opid(List *op, Oid arg1, Oid arg2, bool noError)
Definition: parse_oper.c:487
@ SORTBY_NULLS_DEFAULT
Definition: parsenodes.h:54
@ SORTBY_NULLS_LAST
Definition: parsenodes.h:56
@ SORTBY_NULLS_FIRST
Definition: parsenodes.h:55
@ SORTBY_USING
Definition: parsenodes.h:49
@ SORTBY_DESC
Definition: parsenodes.h:48
@ SORTBY_ASC
Definition: parsenodes.h:47
@ SORTBY_DEFAULT
Definition: parsenodes.h:46
#define llast(l)
Definition: pg_list.h:198
#define NIL
Definition: pg_list.h:68
SortByNulls sortby_nulls
Definition: parsenodes.h:559
Node * node
Definition: parsenodes.h:557
List * useOp
Definition: parsenodes.h:560
SortByDir sortby_dir
Definition: parsenodes.h:558
ParseLoc location
Definition: parsenodes.h:561
#define strVal(v)
Definition: value.h:82

References Assert, assignSortGroupRef(), cancel_parser_errposition_callback(), COERCE_IMPLICIT_CAST, coerce_type(), COERCION_IMPLICIT, compatible_oper_opid(), elog, SortGroupClause::eqop, ereport, errcode(), errhint(), errmsg(), ERROR, TargetEntry::expr, exprLocation(), exprType(), get_equality_op_for_ordering_op(), get_sort_group_operators(), InvalidOid, lappend(), llast, SortBy::location, makeNode, NIL, SortBy::node, SortGroupClause::nulls_first, OidIsValid, op_hashjoinable(), SortGroupClause::reverse_sort, setup_parser_errposition_callback(), SORTBY_ASC, SORTBY_DEFAULT, SORTBY_DESC, SortBy::sortby_dir, SortBy::sortby_nulls, SORTBY_NULLS_DEFAULT, SORTBY_NULLS_FIRST, SORTBY_NULLS_LAST, SORTBY_USING, SortGroupClause::sortop, strVal, targetIsInSortList(), SortGroupClause::tleSortGroupRef, and SortBy::useOp.

Referenced by transformAggregateCall(), and transformSortClause().

◆ assignSortGroupRef()

Index assignSortGroupRef ( TargetEntry tle,
List tlist 
)

Definition at line 3594 of file parse_clause.c.

3595{
3596 Index maxRef;
3597 ListCell *l;
3598
3599 if (tle->ressortgroupref) /* already has one? */
3600 return tle->ressortgroupref;
3601
3602 /* easiest way to pick an unused refnumber: max used + 1 */
3603 maxRef = 0;
3604 foreach(l, tlist)
3605 {
3606 Index ref = ((TargetEntry *) lfirst(l))->ressortgroupref;
3607
3608 if (ref > maxRef)
3609 maxRef = ref;
3610 }
3611 tle->ressortgroupref = maxRef + 1;
3612 return tle->ressortgroupref;
3613}
unsigned int Index
Definition: c.h:571
#define lfirst(lc)
Definition: pg_list.h:172
Index ressortgroupref
Definition: primnodes.h:2251

References lfirst, and TargetEntry::ressortgroupref.

Referenced by addTargetToGroupList(), addTargetToSortList(), build_minmax_path(), create_unique_plan(), generate_setop_child_grouplist(), and transformDistinctOnClause().

◆ buildMergedJoinVar()

static Node * buildMergedJoinVar ( ParseState pstate,
JoinType  jointype,
Var l_colvar,
Var r_colvar 
)
static

Definition at line 1666 of file parse_clause.c.

1668{
1669 Oid outcoltype;
1670 int32 outcoltypmod;
1671 Node *l_node,
1672 *r_node,
1673 *res_node;
1674
1675 outcoltype = select_common_type(pstate,
1676 list_make2(l_colvar, r_colvar),
1677 "JOIN/USING",
1678 NULL);
1679 outcoltypmod = select_common_typmod(pstate,
1680 list_make2(l_colvar, r_colvar),
1681 outcoltype);
1682
1683 /*
1684 * Insert coercion functions if needed. Note that a difference in typmod
1685 * can only happen if input has typmod but outcoltypmod is -1. In that
1686 * case we insert a RelabelType to clearly mark that result's typmod is
1687 * not same as input. We never need coerce_type_typmod.
1688 */
1689 if (l_colvar->vartype != outcoltype)
1690 l_node = coerce_type(pstate, (Node *) l_colvar, l_colvar->vartype,
1691 outcoltype, outcoltypmod,
1693 else if (l_colvar->vartypmod != outcoltypmod)
1694 l_node = (Node *) makeRelabelType((Expr *) l_colvar,
1695 outcoltype, outcoltypmod,
1696 InvalidOid, /* fixed below */
1698 else
1699 l_node = (Node *) l_colvar;
1700
1701 if (r_colvar->vartype != outcoltype)
1702 r_node = coerce_type(pstate, (Node *) r_colvar, r_colvar->vartype,
1703 outcoltype, outcoltypmod,
1705 else if (r_colvar->vartypmod != outcoltypmod)
1706 r_node = (Node *) makeRelabelType((Expr *) r_colvar,
1707 outcoltype, outcoltypmod,
1708 InvalidOid, /* fixed below */
1710 else
1711 r_node = (Node *) r_colvar;
1712
1713 /*
1714 * Choose what to emit
1715 */
1716 switch (jointype)
1717 {
1718 case JOIN_INNER:
1719
1720 /*
1721 * We can use either var; prefer non-coerced one if available.
1722 */
1723 if (IsA(l_node, Var))
1724 res_node = l_node;
1725 else if (IsA(r_node, Var))
1726 res_node = r_node;
1727 else
1728 res_node = l_node;
1729 break;
1730 case JOIN_LEFT:
1731 /* Always use left var */
1732 res_node = l_node;
1733 break;
1734 case JOIN_RIGHT:
1735 /* Always use right var */
1736 res_node = r_node;
1737 break;
1738 case JOIN_FULL:
1739 {
1740 /*
1741 * Here we must build a COALESCE expression to ensure that the
1742 * join output is non-null if either input is.
1743 */
1745
1746 c->coalescetype = outcoltype;
1747 /* coalescecollid will get set below */
1748 c->args = list_make2(l_node, r_node);
1749 c->location = -1;
1750 res_node = (Node *) c;
1751 break;
1752 }
1753 default:
1754 elog(ERROR, "unrecognized join type: %d", (int) jointype);
1755 res_node = NULL; /* keep compiler quiet */
1756 break;
1757 }
1758
1759 /*
1760 * Apply assign_expr_collations to fix up the collation info in the
1761 * coercion and CoalesceExpr nodes, if we made any. This must be done now
1762 * so that the join node's alias vars show correct collation info.
1763 */
1764 assign_expr_collations(pstate, res_node);
1765
1766 return res_node;
1767}
int32_t int32
Definition: c.h:484
RelabelType * makeRelabelType(Expr *arg, Oid rtype, int32 rtypmod, Oid rcollid, CoercionForm rformat)
Definition: makefuncs.c:406
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
@ JOIN_FULL
Definition: nodes.h:295
@ JOIN_INNER
Definition: nodes.h:293
@ JOIN_RIGHT
Definition: nodes.h:296
@ JOIN_LEFT
Definition: nodes.h:294
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)
void assign_expr_collations(ParseState *pstate, Node *expr)
#define list_make2(x1, x2)
Definition: pg_list.h:214
char * c
Definition: primnodes.h:261

References assign_expr_collations(), COERCE_IMPLICIT_CAST, coerce_type(), COERCION_IMPLICIT, elog, ERROR, InvalidOid, IsA, JOIN_FULL, JOIN_INNER, JOIN_LEFT, JOIN_RIGHT, list_make2, makeNode, makeRelabelType(), select_common_type(), and select_common_typmod().

Referenced by transformFromClauseItem().

◆ buildVarFromNSColumn()

static Var * buildVarFromNSColumn ( ParseState pstate,
ParseNamespaceColumn nscol 
)
static

Definition at line 1639 of file parse_clause.c.

1640{
1641 Var *var;
1642
1643 Assert(nscol->p_varno > 0); /* i.e., not deleted column */
1644 var = makeVar(nscol->p_varno,
1645 nscol->p_varattno,
1646 nscol->p_vartype,
1647 nscol->p_vartypmod,
1648 nscol->p_varcollid,
1649 0);
1650 /* makeVar doesn't offer parameters for these, so set by hand: */
1652 var->varnosyn = nscol->p_varnosyn;
1653 var->varattnosyn = nscol->p_varattnosyn;
1654
1655 /* ... and update varnullingrels */
1656 markNullableIfNeeded(pstate, var);
1657
1658 return var;
1659}
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
void markNullableIfNeeded(ParseState *pstate, Var *var)
VarReturningType p_varreturningtype
Definition: parse_node.h:351
AttrNumber p_varattno
Definition: parse_node.h:347
AttrNumber p_varattnosyn
Definition: parse_node.h:353
VarReturningType varreturningtype
Definition: primnodes.h:296

References Assert, makeVar(), markNullableIfNeeded(), ParseNamespaceColumn::p_varattno, ParseNamespaceColumn::p_varattnosyn, ParseNamespaceColumn::p_varcollid, ParseNamespaceColumn::p_varno, ParseNamespaceColumn::p_varnosyn, ParseNamespaceColumn::p_varreturningtype, ParseNamespaceColumn::p_vartype, ParseNamespaceColumn::p_vartypmod, and Var::varreturningtype.

Referenced by extractRemainingColumns(), and transformFromClauseItem().

◆ checkExprIsVarFree()

static void checkExprIsVarFree ( ParseState pstate,
Node n,
const char *  constructName 
)
static

Definition at line 1925 of file parse_clause.c.

1926{
1927 if (contain_vars_of_level(n, 0))
1928 {
1929 ereport(ERROR,
1930 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1931 /* translator: %s is name of a SQL construct, eg LIMIT */
1932 errmsg("argument of %s must not contain variables",
1933 constructName),
1934 parser_errposition(pstate,
1935 locate_var_of_level(n, 0))));
1936 }
1937}
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:106
bool contain_vars_of_level(Node *node, int levelsup)
Definition: var.c:444
int locate_var_of_level(Node *node, int levelsup)
Definition: var.c:555

References contain_vars_of_level(), ereport, errcode(), errmsg(), ERROR, locate_var_of_level(), and parser_errposition().

Referenced by transformFrameOffset(), and transformLimitClause().

◆ checkTargetlistEntrySQL92()

static void checkTargetlistEntrySQL92 ( ParseState pstate,
TargetEntry tle,
ParseExprKind  exprKind 
)
static

Definition at line 1950 of file parse_clause.c.

1952{
1953 switch (exprKind)
1954 {
1955 case EXPR_KIND_GROUP_BY:
1956 /* reject aggregates and window functions */
1957 if (pstate->p_hasAggs &&
1958 contain_aggs_of_level((Node *) tle->expr, 0))
1959 ereport(ERROR,
1960 (errcode(ERRCODE_GROUPING_ERROR),
1961 /* translator: %s is name of a SQL construct, eg GROUP BY */
1962 errmsg("aggregate functions are not allowed in %s",
1963 ParseExprKindName(exprKind)),
1964 parser_errposition(pstate,
1965 locate_agg_of_level((Node *) tle->expr, 0))));
1966 if (pstate->p_hasWindowFuncs &&
1967 contain_windowfuncs((Node *) tle->expr))
1968 ereport(ERROR,
1969 (errcode(ERRCODE_WINDOWING_ERROR),
1970 /* translator: %s is name of a SQL construct, eg GROUP BY */
1971 errmsg("window functions are not allowed in %s",
1972 ParseExprKindName(exprKind)),
1973 parser_errposition(pstate,
1974 locate_windowfunc((Node *) tle->expr))));
1975 break;
1976 case EXPR_KIND_ORDER_BY:
1977 /* no extra checks needed */
1978 break;
1980 /* no extra checks needed */
1981 break;
1982 default:
1983 elog(ERROR, "unexpected exprKind in checkTargetlistEntrySQL92");
1984 break;
1985 }
1986}
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:3121
@ EXPR_KIND_DISTINCT_ON
Definition: parse_node.h:61
@ EXPR_KIND_ORDER_BY
Definition: parse_node.h:60
@ EXPR_KIND_GROUP_BY
Definition: parse_node.h:59
bool contain_windowfuncs(Node *node)
Definition: rewriteManip.c:214
int locate_agg_of_level(Node *node, int levelsup)
Definition: rewriteManip.c:149
bool contain_aggs_of_level(Node *node, int levelsup)
Definition: rewriteManip.c:85
int locate_windowfunc(Node *node)
Definition: rewriteManip.c:251
bool p_hasWindowFuncs
Definition: parse_node.h:243
bool p_hasAggs
Definition: parse_node.h:242

References contain_aggs_of_level(), contain_windowfuncs(), elog, ereport, errcode(), errmsg(), ERROR, TargetEntry::expr, EXPR_KIND_DISTINCT_ON, EXPR_KIND_GROUP_BY, EXPR_KIND_ORDER_BY, locate_agg_of_level(), locate_windowfunc(), ParseState::p_hasAggs, ParseState::p_hasWindowFuncs, ParseExprKindName(), and parser_errposition().

Referenced by findTargetlistEntrySQL92().

◆ extractRemainingColumns()

static int extractRemainingColumns ( ParseState pstate,
ParseNamespaceColumn src_nscolumns,
List src_colnames,
List **  src_colnos,
List **  res_colnames,
List **  res_colvars,
ParseNamespaceColumn res_nscolumns 
)
static

Definition at line 253 of file parse_clause.c.

259{
260 int colcount = 0;
261 Bitmapset *prevcols;
262 int attnum;
263 ListCell *lc;
264
265 /*
266 * While we could just test "list_member_int(*src_colnos, attnum)" to
267 * detect already-merged columns in the loop below, that would be O(N^2)
268 * for a wide input table. Instead build a bitmapset of just the merged
269 * USING columns, which we won't add to within the main loop.
270 */
271 prevcols = NULL;
272 foreach(lc, *src_colnos)
273 {
274 prevcols = bms_add_member(prevcols, lfirst_int(lc));
275 }
276
277 attnum = 0;
278 foreach(lc, src_colnames)
279 {
280 char *colname = strVal(lfirst(lc));
281
282 attnum++;
283 /* Non-dropped and not already merged? */
284 if (colname[0] != '\0' && !bms_is_member(attnum, prevcols))
285 {
286 /* Yes, so emit it as next output column */
287 *src_colnos = lappend_int(*src_colnos, attnum);
288 *res_colnames = lappend(*res_colnames, lfirst(lc));
289 *res_colvars = lappend(*res_colvars,
291 src_nscolumns + attnum - 1));
292 /* Copy the input relation's nscolumn data for this column */
293 res_nscolumns[colcount] = src_nscolumns[attnum - 1];
294 colcount++;
295 }
296 }
297 return colcount;
298}
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:510
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
List * lappend_int(List *list, int datum)
Definition: list.c:357
static Var * buildVarFromNSColumn(ParseState *pstate, ParseNamespaceColumn *nscol)
int16 attnum
Definition: pg_attribute.h:74
#define lfirst_int(lc)
Definition: pg_list.h:173

References attnum, bms_add_member(), bms_is_member(), buildVarFromNSColumn(), lappend(), lappend_int(), lfirst, lfirst_int, and strVal.

Referenced by transformFromClauseItem().

◆ findTargetlistEntrySQL92()

static TargetEntry * findTargetlistEntrySQL92 ( ParseState pstate,
Node node,
List **  tlist,
ParseExprKind  exprKind 
)
static

Definition at line 2006 of file parse_clause.c.

2008{
2009 ListCell *tl;
2010
2011 /*----------
2012 * Handle two special cases as mandated by the SQL92 spec:
2013 *
2014 * 1. Bare ColumnName (no qualifier or subscripts)
2015 * For a bare identifier, we search for a matching column name
2016 * in the existing target list. Multiple matches are an error
2017 * unless they refer to identical values; for example,
2018 * we allow SELECT a, a FROM table ORDER BY a
2019 * but not SELECT a AS b, b FROM table ORDER BY b
2020 * If no match is found, we fall through and treat the identifier
2021 * as an expression.
2022 * For GROUP BY, it is incorrect to match the grouping item against
2023 * targetlist entries: according to SQL92, an identifier in GROUP BY
2024 * is a reference to a column name exposed by FROM, not to a target
2025 * list column. However, many implementations (including pre-7.0
2026 * PostgreSQL) accept this anyway. So for GROUP BY, we look first
2027 * to see if the identifier matches any FROM column name, and only
2028 * try for a targetlist name if it doesn't. This ensures that we
2029 * adhere to the spec in the case where the name could be both.
2030 * DISTINCT ON isn't in the standard, so we can do what we like there;
2031 * we choose to make it work like ORDER BY, on the rather flimsy
2032 * grounds that ordinary DISTINCT works on targetlist entries.
2033 *
2034 * 2. IntegerConstant
2035 * This means to use the n'th item in the existing target list.
2036 * Note that it would make no sense to order/group/distinct by an
2037 * actual constant, so this does not create a conflict with SQL99.
2038 * GROUP BY column-number is not allowed by SQL92, but since
2039 * the standard has no other behavior defined for this syntax,
2040 * we may as well accept this common extension.
2041 *
2042 * Note that pre-existing resjunk targets must not be used in either case,
2043 * since the user didn't write them in his SELECT list.
2044 *
2045 * If neither special case applies, fall through to treat the item as
2046 * an expression per SQL99.
2047 *----------
2048 */
2049 if (IsA(node, ColumnRef) &&
2050 list_length(((ColumnRef *) node)->fields) == 1 &&
2051 IsA(linitial(((ColumnRef *) node)->fields), String))
2052 {
2053 char *name = strVal(linitial(((ColumnRef *) node)->fields));
2054 int location = ((ColumnRef *) node)->location;
2055
2056 if (exprKind == EXPR_KIND_GROUP_BY)
2057 {
2058 /*
2059 * In GROUP BY, we must prefer a match against a FROM-clause
2060 * column to one against the targetlist. Look to see if there is
2061 * a matching column. If so, fall through to use SQL99 rules.
2062 * NOTE: if name could refer ambiguously to more than one column
2063 * name exposed by FROM, colNameToVar will ereport(ERROR). That's
2064 * just what we want here.
2065 *
2066 * Small tweak for 7.4.3: ignore matches in upper query levels.
2067 * This effectively changes the search order for bare names to (1)
2068 * local FROM variables, (2) local targetlist aliases, (3) outer
2069 * FROM variables, whereas before it was (1) (3) (2). SQL92 and
2070 * SQL99 do not allow GROUPing BY an outer reference, so this
2071 * breaks no cases that are legal per spec, and it seems a more
2072 * self-consistent behavior.
2073 */
2074 if (colNameToVar(pstate, name, true, location) != NULL)
2075 name = NULL;
2076 }
2077
2078 if (name != NULL)
2079 {
2080 TargetEntry *target_result = NULL;
2081
2082 foreach(tl, *tlist)
2083 {
2084 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2085
2086 if (!tle->resjunk &&
2087 strcmp(tle->resname, name) == 0)
2088 {
2089 if (target_result != NULL)
2090 {
2091 if (!equal(target_result->expr, tle->expr))
2092 ereport(ERROR,
2093 (errcode(ERRCODE_AMBIGUOUS_COLUMN),
2094
2095 /*------
2096 translator: first %s is name of a SQL construct, eg ORDER BY */
2097 errmsg("%s \"%s\" is ambiguous",
2098 ParseExprKindName(exprKind),
2099 name),
2100 parser_errposition(pstate, location)));
2101 }
2102 else
2103 target_result = tle;
2104 /* Stay in loop to check for ambiguity */
2105 }
2106 }
2107 if (target_result != NULL)
2108 {
2109 /* return the first match, after suitable validation */
2110 checkTargetlistEntrySQL92(pstate, target_result, exprKind);
2111 return target_result;
2112 }
2113 }
2114 }
2115 if (IsA(node, A_Const))
2116 {
2117 A_Const *aconst = castNode(A_Const, node);
2118 int targetlist_pos = 0;
2119 int target_pos;
2120
2121 if (!IsA(&aconst->val, Integer))
2122 ereport(ERROR,
2123 (errcode(ERRCODE_SYNTAX_ERROR),
2124 /* translator: %s is name of a SQL construct, eg ORDER BY */
2125 errmsg("non-integer constant in %s",
2126 ParseExprKindName(exprKind)),
2127 parser_errposition(pstate, aconst->location)));
2128
2129 target_pos = intVal(&aconst->val);
2130 foreach(tl, *tlist)
2131 {
2132 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2133
2134 if (!tle->resjunk)
2135 {
2136 if (++targetlist_pos == target_pos)
2137 {
2138 /* return the unique match, after suitable validation */
2139 checkTargetlistEntrySQL92(pstate, tle, exprKind);
2140 return tle;
2141 }
2142 }
2143 }
2144 ereport(ERROR,
2145 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2146 /* translator: %s is name of a SQL construct, eg ORDER BY */
2147 errmsg("%s position %d is not in select list",
2148 ParseExprKindName(exprKind), target_pos),
2149 parser_errposition(pstate, aconst->location)));
2150 }
2151
2152 /*
2153 * Otherwise, we have an expression, so process it per SQL99 rules.
2154 */
2155 return findTargetlistEntrySQL99(pstate, node, tlist, exprKind);
2156}
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
#define castNode(_type_, nodeptr)
Definition: nodes.h:176
static void checkTargetlistEntrySQL92(ParseState *pstate, TargetEntry *tle, ParseExprKind exprKind)
static TargetEntry * findTargetlistEntrySQL99(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
Node * colNameToVar(ParseState *pstate, const char *colname, bool localonly, int location)
static int list_length(const List *l)
Definition: pg_list.h:152
#define linitial(l)
Definition: pg_list.h:178
union ValUnion val
Definition: parsenodes.h:373
ParseLoc location
Definition: parsenodes.h:375
Definition: value.h:29
Definition: value.h:64
#define intVal(v)
Definition: value.h:79
const char * name

References castNode, checkTargetlistEntrySQL92(), colNameToVar(), equal(), ereport, errcode(), errmsg(), ERROR, TargetEntry::expr, EXPR_KIND_GROUP_BY, findTargetlistEntrySQL99(), intVal, IsA, lfirst, linitial, list_length(), A_Const::location, name, ParseExprKindName(), parser_errposition(), strVal, and A_Const::val.

Referenced by transformDistinctOnClause(), transformGroupClauseExpr(), and transformSortClause().

◆ findTargetlistEntrySQL99()

static TargetEntry * findTargetlistEntrySQL99 ( ParseState pstate,
Node node,
List **  tlist,
ParseExprKind  exprKind 
)
static

Definition at line 2172 of file parse_clause.c.

2174{
2175 TargetEntry *target_result;
2176 ListCell *tl;
2177 Node *expr;
2178
2179 /*
2180 * Convert the untransformed node to a transformed expression, and search
2181 * for a match in the tlist. NOTE: it doesn't really matter whether there
2182 * is more than one match. Also, we are willing to match an existing
2183 * resjunk target here, though the SQL92 cases above must ignore resjunk
2184 * targets.
2185 */
2186 expr = transformExpr(pstate, node, exprKind);
2187
2188 foreach(tl, *tlist)
2189 {
2190 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2191 Node *texpr;
2192
2193 /*
2194 * Ignore any implicit cast on the existing tlist expression.
2195 *
2196 * This essentially allows the ORDER/GROUP/etc item to adopt the same
2197 * datatype previously selected for a textually-equivalent tlist item.
2198 * There can't be any implicit cast at top level in an ordinary SELECT
2199 * tlist at this stage, but the case does arise with ORDER BY in an
2200 * aggregate function.
2201 */
2202 texpr = strip_implicit_coercions((Node *) tle->expr);
2203
2204 if (equal(expr, texpr))
2205 return tle;
2206 }
2207
2208 /*
2209 * If no matches, construct a new target entry which is appended to the
2210 * end of the target list. This target is given resjunk = true so that it
2211 * will not be projected into the final tuple.
2212 */
2213 target_result = transformTargetEntry(pstate, node, expr, exprKind,
2214 NULL, true);
2215
2216 *tlist = lappend(*tlist, target_result);
2217
2218 return target_result;
2219}
Node * strip_implicit_coercions(Node *node)
Definition: nodeFuncs.c:705
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:118
TargetEntry * transformTargetEntry(ParseState *pstate, Node *node, Node *expr, ParseExprKind exprKind, char *colname, bool resjunk)
Definition: parse_target.c:75

References equal(), TargetEntry::expr, lappend(), lfirst, strip_implicit_coercions(), transformExpr(), and transformTargetEntry().

Referenced by findTargetlistEntrySQL92(), transformGroupClauseExpr(), and transformSortClause().

◆ findWindowClause()

static WindowClause * findWindowClause ( List wclist,
const char *  name 
)
static

Definition at line 3662 of file parse_clause.c.

3663{
3664 ListCell *l;
3665
3666 foreach(l, wclist)
3667 {
3668 WindowClause *wc = (WindowClause *) lfirst(l);
3669
3670 if (wc->name && strcmp(wc->name, name) == 0)
3671 return wc;
3672 }
3673
3674 return NULL;
3675}

References lfirst, and name.

Referenced by transformWindowDefinitions().

◆ flatten_grouping_sets()

static Node * flatten_grouping_sets ( Node expr,
bool  toplevel,
bool *  hasGroupingSets 
)
static

Definition at line 2258 of file parse_clause.c.

2259{
2260 /* just in case of pathological input */
2262
2263 if (expr == (Node *) NIL)
2264 return (Node *) NIL;
2265
2266 switch (expr->type)
2267 {
2268 case T_RowExpr:
2269 {
2270 RowExpr *r = (RowExpr *) expr;
2271
2272 if (r->row_format == COERCE_IMPLICIT_CAST)
2273 return flatten_grouping_sets((Node *) r->args,
2274 false, NULL);
2275 }
2276 break;
2277 case T_GroupingSet:
2278 {
2279 GroupingSet *gset = (GroupingSet *) expr;
2280 ListCell *l2;
2281 List *result_set = NIL;
2282
2283 if (hasGroupingSets)
2284 *hasGroupingSets = true;
2285
2286 /*
2287 * at the top level, we skip over all empty grouping sets; the
2288 * caller can supply the canonical GROUP BY () if nothing is
2289 * left.
2290 */
2291
2292 if (toplevel && gset->kind == GROUPING_SET_EMPTY)
2293 return (Node *) NIL;
2294
2295 foreach(l2, gset->content)
2296 {
2297 Node *n1 = lfirst(l2);
2298 Node *n2 = flatten_grouping_sets(n1, false, NULL);
2299
2300 if (IsA(n1, GroupingSet) &&
2301 ((GroupingSet *) n1)->kind == GROUPING_SET_SETS)
2302 result_set = list_concat(result_set, (List *) n2);
2303 else
2304 result_set = lappend(result_set, n2);
2305 }
2306
2307 /*
2308 * At top level, keep the grouping set node; but if we're in a
2309 * nested grouping set, then we need to concat the flattened
2310 * result into the outer list if it's simply nested.
2311 */
2312
2313 if (toplevel || (gset->kind != GROUPING_SET_SETS))
2314 {
2315 return (Node *) makeGroupingSet(gset->kind, result_set, gset->location);
2316 }
2317 else
2318 return (Node *) result_set;
2319 }
2320 case T_List:
2321 {
2322 List *result = NIL;
2323 ListCell *l;
2324
2325 foreach(l, (List *) expr)
2326 {
2327 Node *n = flatten_grouping_sets(lfirst(l), toplevel, hasGroupingSets);
2328
2329 if (n != (Node *) NIL)
2330 {
2331 if (IsA(n, List))
2332 result = list_concat(result, (List *) n);
2333 else
2334 result = lappend(result, n);
2335 }
2336 }
2337
2338 return (Node *) result;
2339 }
2340 default:
2341 break;
2342 }
2343
2344 return expr;
2345}
List * list_concat(List *list1, const List *list2)
Definition: list.c:561
GroupingSet * makeGroupingSet(GroupingSetKind kind, List *content, int location)
Definition: makefuncs.c:845
static Node * flatten_grouping_sets(Node *expr, bool toplevel, bool *hasGroupingSets)
@ GROUPING_SET_SETS
Definition: parsenodes.h:1512
@ GROUPING_SET_EMPTY
Definition: parsenodes.h:1508
void check_stack_depth(void)
Definition: stack_depth.c:95
List * content
Definition: parsenodes.h:1519
ParseLoc location
Definition: parsenodes.h:1520
Definition: pg_list.h:54
NodeTag type
Definition: nodes.h:130
List * args
Definition: primnodes.h:1427

References RowExpr::args, check_stack_depth(), COERCE_IMPLICIT_CAST, GroupingSet::content, flatten_grouping_sets(), GROUPING_SET_EMPTY, GROUPING_SET_SETS, IsA, lappend(), lfirst, list_concat(), GroupingSet::location, makeGroupingSet(), NIL, and Node::type.

Referenced by flatten_grouping_sets(), and transformGroupClause().

◆ get_matching_location()

static int get_matching_location ( int  sortgroupref,
List sortgrouprefs,
List exprs 
)
static

Definition at line 3176 of file parse_clause.c.

3177{
3178 ListCell *lcs;
3179 ListCell *lce;
3180
3181 forboth(lcs, sortgrouprefs, lce, exprs)
3182 {
3183 if (lfirst_int(lcs) == sortgroupref)
3184 return exprLocation((Node *) lfirst(lce));
3185 }
3186 /* if no match, caller blew it */
3187 elog(ERROR, "get_matching_location: no matching sortgroupref");
3188 return -1; /* keep compiler quiet */
3189}
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:518

References elog, ERROR, exprLocation(), forboth, lfirst, and lfirst_int.

Referenced by transformDistinctOnClause().

◆ getNSItemForSpecialRelationTypes()

static ParseNamespaceItem * getNSItemForSpecialRelationTypes ( ParseState pstate,
RangeVar rv 
)
static

Definition at line 1011 of file parse_clause.c.

1012{
1013 ParseNamespaceItem *nsitem;
1014 CommonTableExpr *cte;
1015 Index levelsup;
1016
1017 /*
1018 * if it is a qualified name, it can't be a CTE or tuplestore reference
1019 */
1020 if (rv->schemaname)
1021 return NULL;
1022
1023 cte = scanNameSpaceForCTE(pstate, rv->relname, &levelsup);
1024 if (cte)
1025 nsitem = addRangeTableEntryForCTE(pstate, cte, levelsup, rv, true);
1026 else if (scanNameSpaceForENR(pstate, rv->relname))
1027 nsitem = addRangeTableEntryForENR(pstate, rv, true);
1028 else
1029 nsitem = NULL;
1030
1031 return nsitem;
1032}
CommonTableExpr * scanNameSpaceForCTE(ParseState *pstate, const char *refname, Index *ctelevelsup)
ParseNamespaceItem * addRangeTableEntryForENR(ParseState *pstate, RangeVar *rv, bool inFromCl)
bool scanNameSpaceForENR(ParseState *pstate, const char *refname)
ParseNamespaceItem * addRangeTableEntryForCTE(ParseState *pstate, CommonTableExpr *cte, Index levelsup, RangeVar *rv, bool inFromCl)
char * relname
Definition: primnodes.h:82
char * schemaname
Definition: primnodes.h:79

References addRangeTableEntryForCTE(), addRangeTableEntryForENR(), RangeVar::relname, scanNameSpaceForCTE(), scanNameSpaceForENR(), and RangeVar::schemaname.

Referenced by transformFromClauseItem().

◆ markRelsAsNulledBy()

static void markRelsAsNulledBy ( ParseState pstate,
Node n,
int  jindex 
)
static

Definition at line 1774 of file parse_clause.c.

1775{
1776 int varno;
1777 ListCell *lc;
1778
1779 /* Note: we can't see FromExpr here */
1780 if (IsA(n, RangeTblRef))
1781 {
1782 varno = ((RangeTblRef *) n)->rtindex;
1783 }
1784 else if (IsA(n, JoinExpr))
1785 {
1786 JoinExpr *j = (JoinExpr *) n;
1787
1788 /* recurse to children */
1789 markRelsAsNulledBy(pstate, j->larg, jindex);
1790 markRelsAsNulledBy(pstate, j->rarg, jindex);
1791 varno = j->rtindex;
1792 }
1793 else
1794 {
1795 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(n));
1796 varno = 0; /* keep compiler quiet */
1797 }
1798
1799 /*
1800 * Now add jindex to the p_nullingrels set for relation varno. Since we
1801 * maintain the p_nullingrels list lazily, we might need to extend it to
1802 * make the varno'th entry exist.
1803 */
1804 while (list_length(pstate->p_nullingrels) < varno)
1805 pstate->p_nullingrels = lappend(pstate->p_nullingrels, NULL);
1806 lc = list_nth_cell(pstate->p_nullingrels, varno - 1);
1807 lfirst(lc) = bms_add_member((Bitmapset *) lfirst(lc), jindex);
1808}
int j
Definition: isn.c:73
#define nodeTag(nodeptr)
Definition: nodes.h:133
static void markRelsAsNulledBy(ParseState *pstate, Node *n, int jindex)
static ListCell * list_nth_cell(const List *list, int n)
Definition: pg_list.h:277
List * p_nullingrels
Definition: parse_node.h:216

References bms_add_member(), elog, ERROR, IsA, j, lappend(), lfirst, list_length(), list_nth_cell(), markRelsAsNulledBy(), nodeTag, and ParseState::p_nullingrels.

Referenced by markRelsAsNulledBy(), and transformFromClauseItem().

◆ resolve_unique_index_expr()

static List * resolve_unique_index_expr ( ParseState pstate,
InferClause infer,
Relation  heapRel 
)
static

Definition at line 3201 of file parse_clause.c.

3203{
3204 List *result = NIL;
3205 ListCell *l;
3206
3207 foreach(l, infer->indexElems)
3208 {
3209 IndexElem *ielem = (IndexElem *) lfirst(l);
3211 Node *parse;
3212
3213 /*
3214 * Raw grammar re-uses CREATE INDEX infrastructure for unique index
3215 * inference clause, and so will accept opclasses by name and so on.
3216 *
3217 * Make no attempt to match ASC or DESC ordering or NULLS FIRST/NULLS
3218 * LAST ordering, since those are not significant for inference
3219 * purposes (any unique index matching the inference specification in
3220 * other regards is accepted indifferently). Actively reject this as
3221 * wrong-headed.
3222 */
3223 if (ielem->ordering != SORTBY_DEFAULT)
3224 ereport(ERROR,
3225 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3226 errmsg("ASC/DESC is not allowed in ON CONFLICT clause"),
3227 parser_errposition(pstate,
3228 exprLocation((Node *) infer))));
3230 ereport(ERROR,
3231 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3232 errmsg("NULLS FIRST/LAST is not allowed in ON CONFLICT clause"),
3233 parser_errposition(pstate,
3234 exprLocation((Node *) infer))));
3235
3236 if (!ielem->expr)
3237 {
3238 /* Simple index attribute */
3239 ColumnRef *n;
3240
3241 /*
3242 * Grammar won't have built raw expression for us in event of
3243 * plain column reference. Create one directly, and perform
3244 * expression transformation. Planner expects this, and performs
3245 * its own normalization for the purposes of matching against
3246 * pg_index.
3247 */
3248 n = makeNode(ColumnRef);
3249 n->fields = list_make1(makeString(ielem->name));
3250 /* Location is approximately that of inference specification */
3251 n->location = infer->location;
3252 parse = (Node *) n;
3253 }
3254 else
3255 {
3256 /* Do parse transformation of the raw expression */
3257 parse = (Node *) ielem->expr;
3258 }
3259
3260 /*
3261 * transformExpr() will reject subqueries, aggregates, window
3262 * functions, and SRFs, based on being passed
3263 * EXPR_KIND_INDEX_EXPRESSION. So we needn't worry about those
3264 * further ... not that they would match any available index
3265 * expression anyway.
3266 */
3268
3269 /* Perform lookup of collation and operator class as required */
3270 if (!ielem->collation)
3271 pInfer->infercollid = InvalidOid;
3272 else
3273 pInfer->infercollid = LookupCollation(pstate, ielem->collation,
3274 exprLocation(pInfer->expr));
3275
3276 if (!ielem->opclass)
3277 pInfer->inferopclass = InvalidOid;
3278 else
3279 pInfer->inferopclass = get_opclass_oid(BTREE_AM_OID,
3280 ielem->opclass, false);
3281
3282 result = lappend(result, pInfer);
3283 }
3284
3285 return result;
3286}
Oid get_opclass_oid(Oid amID, List *opclassname, bool missing_ok)
Definition: opclasscmds.c:220
@ EXPR_KIND_INDEX_EXPRESSION
Definition: parse_node.h:72
Oid LookupCollation(ParseState *pstate, List *collnames, int location)
Definition: parse_type.c:515
#define list_make1(x1)
Definition: pg_list.h:212
static struct subre * parse(struct vars *v, int stopper, int type, struct state *init, struct state *final)
Definition: regcomp.c:717
ParseLoc location
Definition: parsenodes.h:306
List * fields
Definition: parsenodes.h:305
Node * expr
Definition: parsenodes.h:795
SortByDir ordering
Definition: parsenodes.h:800
SortByNulls nulls_ordering
Definition: parsenodes.h:801
List * opclass
Definition: parsenodes.h:798
char * name
Definition: parsenodes.h:794
List * collation
Definition: parsenodes.h:797
ParseLoc location
Definition: parsenodes.h:1621
List * indexElems
Definition: parsenodes.h:1618
String * makeString(char *str)
Definition: value.c:63

References IndexElem::collation, ereport, errcode(), errmsg(), ERROR, IndexElem::expr, InferenceElem::expr, EXPR_KIND_INDEX_EXPRESSION, exprLocation(), ColumnRef::fields, get_opclass_oid(), InferClause::indexElems, InferenceElem::infercollid, InferenceElem::inferopclass, InvalidOid, lappend(), lfirst, list_make1, ColumnRef::location, LookupCollation(), makeNode, makeString(), IndexElem::name, NIL, IndexElem::nulls_ordering, IndexElem::opclass, IndexElem::ordering, parse(), parser_errposition(), SORTBY_DEFAULT, SORTBY_NULLS_DEFAULT, and transformExpr().

Referenced by transformOnConflictArbiter().

◆ setNamespaceColumnVisibility()

static void setNamespaceColumnVisibility ( List namespace,
bool  cols_visible 
)
static

Definition at line 1815 of file parse_clause.c.

1816{
1817 ListCell *lc;
1818
1819 foreach(lc, namespace)
1820 {
1822
1823 nsitem->p_cols_visible = cols_visible;
1824 }
1825}

References lfirst, and ParseNamespaceItem::p_cols_visible.

Referenced by transformFromClauseItem().

◆ setNamespaceLateralState()

static void setNamespaceLateralState ( List namespace,
bool  lateral_only,
bool  lateral_ok 
)
static

Definition at line 1832 of file parse_clause.c.

1833{
1834 ListCell *lc;
1835
1836 foreach(lc, namespace)
1837 {
1839
1840 nsitem->p_lateral_only = lateral_only;
1841 nsitem->p_lateral_ok = lateral_ok;
1842 }
1843}

References lfirst, ParseNamespaceItem::p_lateral_ok, and ParseNamespaceItem::p_lateral_only.

Referenced by transformFromClause(), transformFromClauseItem(), and transformJoinOnClause().

◆ setTargetTable()

int setTargetTable ( ParseState pstate,
RangeVar relation,
bool  inh,
bool  alsoSource,
AclMode  requiredPerms 
)

Definition at line 178 of file parse_clause.c.

180{
181 ParseNamespaceItem *nsitem;
182
183 /*
184 * ENRs hide tables of the same name, so we need to check for them first.
185 * In contrast, CTEs don't hide tables (for this purpose).
186 */
187 if (relation->schemaname == NULL &&
188 scanNameSpaceForENR(pstate, relation->relname))
190 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
191 errmsg("relation \"%s\" cannot be the target of a modifying statement",
192 relation->relname)));
193
194 /* Close old target; this could only happen for multi-action rules */
195 if (pstate->p_target_relation != NULL)
197
198 /*
199 * Open target rel and grab suitable lock (which we will hold till end of
200 * transaction).
201 *
202 * free_parsestate() will eventually do the corresponding table_close(),
203 * but *not* release the lock.
204 */
205 pstate->p_target_relation = parserOpenTable(pstate, relation,
207
208 /*
209 * Now build an RTE and a ParseNamespaceItem.
210 */
211 nsitem = addRangeTableEntryForRelation(pstate, pstate->p_target_relation,
213 relation->alias, inh, false);
214
215 /* remember the RTE/nsitem as being the query target */
216 pstate->p_target_nsitem = nsitem;
217
218 /*
219 * Override addRangeTableEntry's default ACL_SELECT permissions check, and
220 * instead mark target table as requiring exactly the specified
221 * permissions.
222 *
223 * If we find an explicit reference to the rel later during parse
224 * analysis, we will add the ACL_SELECT bit back again; see
225 * markVarForSelectPriv and its callers.
226 */
227 nsitem->p_perminfo->requiredPerms = requiredPerms;
228
229 /*
230 * If UPDATE/DELETE, add table to joinlist and namespace.
231 */
232 if (alsoSource)
233 addNSItemToQuery(pstate, nsitem, true, true, true);
234
235 return nsitem->p_rtindex;
236}
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
Relation parserOpenTable(ParseState *pstate, const RangeVar *relation, int lockmode)
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
RTEPermissionInfo * p_perminfo
Definition: parse_node.h:313
ParseNamespaceItem * p_target_nsitem
Definition: parse_node.h:226
Relation p_target_relation
Definition: parse_node.h:225
AclMode requiredPerms
Definition: parsenodes.h:1300
Alias * alias
Definition: primnodes.h:91
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126

References addNSItemToQuery(), addRangeTableEntryForRelation(), RangeVar::alias, ereport, errcode(), errmsg(), ERROR, NoLock, ParseNamespaceItem::p_perminfo, ParseNamespaceItem::p_rtindex, ParseState::p_target_nsitem, ParseState::p_target_relation, parserOpenTable(), RangeVar::relname, RTEPermissionInfo::requiredPerms, RowExclusiveLock, scanNameSpaceForENR(), RangeVar::schemaname, and table_close().

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

◆ targetIsInSortList()

bool targetIsInSortList ( TargetEntry tle,
Oid  sortop,
List sortList 
)

Definition at line 3635 of file parse_clause.c.

3636{
3637 Index ref = tle->ressortgroupref;
3638 ListCell *l;
3639
3640 /* no need to scan list if tle has no marker */
3641 if (ref == 0)
3642 return false;
3643
3644 foreach(l, sortList)
3645 {
3647
3648 if (scl->tleSortGroupRef == ref &&
3649 (sortop == InvalidOid ||
3650 sortop == scl->sortop ||
3651 sortop == get_commutator(scl->sortop)))
3652 return true;
3653 }
3654 return false;
3655}
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1509

References get_commutator(), InvalidOid, lfirst, TargetEntry::ressortgroupref, SortGroupClause::sortop, and SortGroupClause::tleSortGroupRef.

Referenced by addTargetToGroupList(), addTargetToSortList(), check_output_expressions(), examine_simple_variable(), targetIsInAllPartitionLists(), transformDistinctOnClause(), and transformGroupClauseExpr().

◆ transformDistinctClause()

List * transformDistinctClause ( ParseState pstate,
List **  targetlist,
List sortClause,
bool  is_agg 
)

Definition at line 2985 of file parse_clause.c.

2987{
2988 List *result = NIL;
2989 ListCell *slitem;
2990 ListCell *tlitem;
2991
2992 /*
2993 * The distinctClause should consist of all ORDER BY items followed by all
2994 * other non-resjunk targetlist items. There must not be any resjunk
2995 * ORDER BY items --- that would imply that we are sorting by a value that
2996 * isn't necessarily unique within a DISTINCT group, so the results
2997 * wouldn't be well-defined. This construction ensures we follow the rule
2998 * that sortClause and distinctClause match; in fact the sortClause will
2999 * always be a prefix of distinctClause.
3000 *
3001 * Note a corner case: the same TLE could be in the ORDER BY list multiple
3002 * times with different sortops. We have to include it in the
3003 * distinctClause the same way to preserve the prefix property. The net
3004 * effect will be that the TLE value will be made unique according to both
3005 * sortops.
3006 */
3007 foreach(slitem, sortClause)
3008 {
3009 SortGroupClause *scl = (SortGroupClause *) lfirst(slitem);
3010 TargetEntry *tle = get_sortgroupclause_tle(scl, *targetlist);
3011
3012 if (tle->resjunk)
3013 ereport(ERROR,
3014 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3015 is_agg ?
3016 errmsg("in an aggregate with DISTINCT, ORDER BY expressions must appear in argument list") :
3017 errmsg("for SELECT DISTINCT, ORDER BY expressions must appear in select list"),
3018 parser_errposition(pstate,
3019 exprLocation((Node *) tle->expr))));
3020 result = lappend(result, copyObject(scl));
3021 }
3022
3023 /*
3024 * Now add any remaining non-resjunk tlist items, using default sort/group
3025 * semantics for their data types.
3026 */
3027 foreach(tlitem, *targetlist)
3028 {
3029 TargetEntry *tle = (TargetEntry *) lfirst(tlitem);
3030
3031 if (tle->resjunk)
3032 continue; /* ignore junk */
3033 result = addTargetToGroupList(pstate, tle,
3034 result, *targetlist,
3035 exprLocation((Node *) tle->expr));
3036 }
3037
3038 /*
3039 * Complain if we found nothing to make DISTINCT. Returning an empty list
3040 * would cause the parsed Query to look like it didn't have DISTINCT, with
3041 * results that would probably surprise the user. Note: this case is
3042 * presently impossible for aggregates because of grammar restrictions,
3043 * but we check anyway.
3044 */
3045 if (result == NIL)
3046 ereport(ERROR,
3047 (errcode(ERRCODE_SYNTAX_ERROR),
3048 is_agg ?
3049 errmsg("an aggregate with DISTINCT must have at least one argument") :
3050 errmsg("SELECT DISTINCT must have at least one column")));
3051
3052 return result;
3053}
#define copyObject(obj)
Definition: nodes.h:224
static List * addTargetToGroupList(ParseState *pstate, TargetEntry *tle, List *grouplist, List *targetlist, int location)
TargetEntry * get_sortgroupclause_tle(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:367

References addTargetToGroupList(), copyObject, ereport, errcode(), errmsg(), ERROR, TargetEntry::expr, exprLocation(), get_sortgroupclause_tle(), lappend(), lfirst, NIL, and parser_errposition().

Referenced by transformAggregateCall(), transformPLAssignStmt(), and transformSelectStmt().

◆ transformDistinctOnClause()

List * transformDistinctOnClause ( ParseState pstate,
List distinctlist,
List **  targetlist,
List sortClause 
)

Definition at line 3069 of file parse_clause.c.

3071{
3072 List *result = NIL;
3073 List *sortgrouprefs = NIL;
3074 bool skipped_sortitem;
3075 ListCell *lc;
3076 ListCell *lc2;
3077
3078 /*
3079 * Add all the DISTINCT ON expressions to the tlist (if not already
3080 * present, they are added as resjunk items). Assign sortgroupref numbers
3081 * to them, and make a list of these numbers. (NB: we rely below on the
3082 * sortgrouprefs list being one-for-one with the original distinctlist.
3083 * Also notice that we could have duplicate DISTINCT ON expressions and
3084 * hence duplicate entries in sortgrouprefs.)
3085 */
3086 foreach(lc, distinctlist)
3087 {
3088 Node *dexpr = (Node *) lfirst(lc);
3089 int sortgroupref;
3090 TargetEntry *tle;
3091
3092 tle = findTargetlistEntrySQL92(pstate, dexpr, targetlist,
3094 sortgroupref = assignSortGroupRef(tle, *targetlist);
3095 sortgrouprefs = lappend_int(sortgrouprefs, sortgroupref);
3096 }
3097
3098 /*
3099 * If the user writes both DISTINCT ON and ORDER BY, adopt the sorting
3100 * semantics from ORDER BY items that match DISTINCT ON items, and also
3101 * adopt their column sort order. We insist that the distinctClause and
3102 * sortClause match, so throw error if we find the need to add any more
3103 * distinctClause items after we've skipped an ORDER BY item that wasn't
3104 * in DISTINCT ON.
3105 */
3106 skipped_sortitem = false;
3107 foreach(lc, sortClause)
3108 {
3109 SortGroupClause *scl = (SortGroupClause *) lfirst(lc);
3110
3111 if (list_member_int(sortgrouprefs, scl->tleSortGroupRef))
3112 {
3113 if (skipped_sortitem)
3114 ereport(ERROR,
3115 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3116 errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
3117 parser_errposition(pstate,
3119 sortgrouprefs,
3120 distinctlist))));
3121 else
3122 result = lappend(result, copyObject(scl));
3123 }
3124 else
3125 skipped_sortitem = true;
3126 }
3127
3128 /*
3129 * Now add any remaining DISTINCT ON items, using default sort/group
3130 * semantics for their data types. (Note: this is pretty questionable; if
3131 * the ORDER BY list doesn't include all the DISTINCT ON items and more
3132 * besides, you certainly aren't using DISTINCT ON in the intended way,
3133 * and you probably aren't going to get consistent results. It might be
3134 * better to throw an error or warning here. But historically we've
3135 * allowed it, so keep doing so.)
3136 */
3137 forboth(lc, distinctlist, lc2, sortgrouprefs)
3138 {
3139 Node *dexpr = (Node *) lfirst(lc);
3140 int sortgroupref = lfirst_int(lc2);
3141 TargetEntry *tle = get_sortgroupref_tle(sortgroupref, *targetlist);
3142
3143 if (targetIsInSortList(tle, InvalidOid, result))
3144 continue; /* already in list (with some semantics) */
3145 if (skipped_sortitem)
3146 ereport(ERROR,
3147 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3148 errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
3149 parser_errposition(pstate, exprLocation(dexpr))));
3150 result = addTargetToGroupList(pstate, tle,
3151 result, *targetlist,
3152 exprLocation(dexpr));
3153 }
3154
3155 /*
3156 * An empty result list is impossible here because of grammar
3157 * restrictions.
3158 */
3159 Assert(result != NIL);
3160
3161 return result;
3162}
bool list_member_int(const List *list, int datum)
Definition: list.c:702
static int get_matching_location(int sortgroupref, List *sortgrouprefs, List *exprs)
static TargetEntry * findTargetlistEntrySQL92(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
TargetEntry * get_sortgroupref_tle(Index sortref, List *targetList)
Definition: tlist.c:345

References addTargetToGroupList(), Assert, assignSortGroupRef(), copyObject, ereport, errcode(), errmsg(), ERROR, EXPR_KIND_DISTINCT_ON, exprLocation(), findTargetlistEntrySQL92(), forboth, get_matching_location(), get_sortgroupref_tle(), InvalidOid, lappend(), lappend_int(), lfirst, lfirst_int, list_member_int(), NIL, parser_errposition(), targetIsInSortList(), and SortGroupClause::tleSortGroupRef.

Referenced by transformPLAssignStmt(), and transformSelectStmt().

◆ transformFrameOffset()

static Node * transformFrameOffset ( ParseState pstate,
int  frameOptions,
Oid  rangeopfamily,
Oid  rangeopcintype,
Oid inRangeFunc,
Node clause 
)
static

Definition at line 3689 of file parse_clause.c.

3692{
3693 const char *constructName = NULL;
3694 Node *node;
3695
3696 *inRangeFunc = InvalidOid; /* default result */
3697
3698 /* Quick exit if no offset expression */
3699 if (clause == NULL)
3700 return NULL;
3701
3702 if (frameOptions & FRAMEOPTION_ROWS)
3703 {
3704 /* Transform the raw expression tree */
3705 node = transformExpr(pstate, clause, EXPR_KIND_WINDOW_FRAME_ROWS);
3706
3707 /*
3708 * Like LIMIT clause, simply coerce to int8
3709 */
3710 constructName = "ROWS";
3711 node = coerce_to_specific_type(pstate, node, INT8OID, constructName);
3712 }
3713 else if (frameOptions & FRAMEOPTION_RANGE)
3714 {
3715 /*
3716 * We must look up the in_range support function that's to be used,
3717 * possibly choosing one of several, and coerce the "offset" value to
3718 * the appropriate input type.
3719 */
3720 Oid nodeType;
3721 Oid preferredType;
3722 int nfuncs = 0;
3723 int nmatches = 0;
3724 Oid selectedType = InvalidOid;
3725 Oid selectedFunc = InvalidOid;
3726 CatCList *proclist;
3727 int i;
3728
3729 /* Transform the raw expression tree */
3730 node = transformExpr(pstate, clause, EXPR_KIND_WINDOW_FRAME_RANGE);
3731 nodeType = exprType(node);
3732
3733 /*
3734 * If there are multiple candidates, we'll prefer the one that exactly
3735 * matches nodeType; or if nodeType is as yet unknown, prefer the one
3736 * that exactly matches the sort column type. (The second rule is
3737 * like what we do for "known_type operator unknown".)
3738 */
3739 preferredType = (nodeType != UNKNOWNOID) ? nodeType : rangeopcintype;
3740
3741 /* Find the in_range support functions applicable to this case */
3742 proclist = SearchSysCacheList2(AMPROCNUM,
3743 ObjectIdGetDatum(rangeopfamily),
3744 ObjectIdGetDatum(rangeopcintype));
3745 for (i = 0; i < proclist->n_members; i++)
3746 {
3747 HeapTuple proctup = &proclist->members[i]->tuple;
3748 Form_pg_amproc procform = (Form_pg_amproc) GETSTRUCT(proctup);
3749
3750 /* The search will find all support proc types; ignore others */
3751 if (procform->amprocnum != BTINRANGE_PROC)
3752 continue;
3753 nfuncs++;
3754
3755 /* Ignore function if given value can't be coerced to that type */
3756 if (!can_coerce_type(1, &nodeType, &procform->amprocrighttype,
3758 continue;
3759 nmatches++;
3760
3761 /* Remember preferred match, or any match if didn't find that */
3762 if (selectedType != preferredType)
3763 {
3764 selectedType = procform->amprocrighttype;
3765 selectedFunc = procform->amproc;
3766 }
3767 }
3768 ReleaseCatCacheList(proclist);
3769
3770 /*
3771 * Throw error if needed. It seems worth taking the trouble to
3772 * distinguish "no support at all" from "you didn't match any
3773 * available offset type".
3774 */
3775 if (nfuncs == 0)
3776 ereport(ERROR,
3777 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3778 errmsg("RANGE with offset PRECEDING/FOLLOWING is not supported for column type %s",
3779 format_type_be(rangeopcintype)),
3780 parser_errposition(pstate, exprLocation(node))));
3781 if (nmatches == 0)
3782 ereport(ERROR,
3783 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3784 errmsg("RANGE with offset PRECEDING/FOLLOWING is not supported for column type %s and offset type %s",
3785 format_type_be(rangeopcintype),
3786 format_type_be(nodeType)),
3787 errhint("Cast the offset value to an appropriate type."),
3788 parser_errposition(pstate, exprLocation(node))));
3789 if (nmatches != 1 && selectedType != preferredType)
3790 ereport(ERROR,
3791 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3792 errmsg("RANGE with offset PRECEDING/FOLLOWING has multiple interpretations for column type %s and offset type %s",
3793 format_type_be(rangeopcintype),
3794 format_type_be(nodeType)),
3795 errhint("Cast the offset value to the exact intended type."),
3796 parser_errposition(pstate, exprLocation(node))));
3797
3798 /* OK, coerce the offset to the right type */
3799 constructName = "RANGE";
3800 node = coerce_to_specific_type(pstate, node,
3801 selectedType, constructName);
3802 *inRangeFunc = selectedFunc;
3803 }
3804 else if (frameOptions & FRAMEOPTION_GROUPS)
3805 {
3806 /* Transform the raw expression tree */
3807 node = transformExpr(pstate, clause, EXPR_KIND_WINDOW_FRAME_GROUPS);
3808
3809 /*
3810 * Like LIMIT clause, simply coerce to int8
3811 */
3812 constructName = "GROUPS";
3813 node = coerce_to_specific_type(pstate, node, INT8OID, constructName);
3814 }
3815 else
3816 {
3817 Assert(false);
3818 node = NULL;
3819 }
3820
3821 /* Disallow variables in frame offsets */
3822 checkExprIsVarFree(pstate, node, constructName);
3823
3824 return node;
3825}
void ReleaseCatCacheList(CatCList *list)
Definition: catcache.c:2071
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
static void * GETSTRUCT(const HeapTupleData *tuple)
Definition: htup_details.h:728
int i
Definition: isn.c:72
#define BTINRANGE_PROC
Definition: nbtree.h:714
static void checkExprIsVarFree(ParseState *pstate, Node *n, const char *constructName)
Node * coerce_to_specific_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *constructName)
bool can_coerce_type(int nargs, const Oid *input_typeids, const Oid *target_typeids, CoercionContext ccontext)
Definition: parse_coerce.c:556
@ EXPR_KIND_WINDOW_FRAME_RANGE
Definition: parse_node.h:51
@ EXPR_KIND_WINDOW_FRAME_GROUPS
Definition: parse_node.h:53
@ EXPR_KIND_WINDOW_FRAME_ROWS
Definition: parse_node.h:52
#define FRAMEOPTION_RANGE
Definition: parsenodes.h:593
#define FRAMEOPTION_GROUPS
Definition: parsenodes.h:595
#define FRAMEOPTION_ROWS
Definition: parsenodes.h:594
FormData_pg_amproc * Form_pg_amproc
Definition: pg_amproc.h:68
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:257
CatCTup * members[FLEXIBLE_ARRAY_MEMBER]
Definition: catcache.h:180
int n_members
Definition: catcache.h:178
HeapTupleData tuple
Definition: catcache.h:123
#define SearchSysCacheList2(cacheId, key1, key2)
Definition: syscache.h:129

References Assert, BTINRANGE_PROC, can_coerce_type(), checkExprIsVarFree(), coerce_to_specific_type(), COERCION_IMPLICIT, ereport, errcode(), errhint(), errmsg(), ERROR, EXPR_KIND_WINDOW_FRAME_GROUPS, EXPR_KIND_WINDOW_FRAME_RANGE, EXPR_KIND_WINDOW_FRAME_ROWS, exprLocation(), exprType(), format_type_be(), FRAMEOPTION_GROUPS, FRAMEOPTION_RANGE, FRAMEOPTION_ROWS, GETSTRUCT(), i, InvalidOid, catclist::members, catclist::n_members, ObjectIdGetDatum(), parser_errposition(), ReleaseCatCacheList(), SearchSysCacheList2, transformExpr(), and catctup::tuple.

Referenced by transformWindowDefinitions().

◆ transformFromClause()

void transformFromClause ( ParseState pstate,
List frmList 
)

Definition at line 112 of file parse_clause.c.

113{
114 ListCell *fl;
115
116 /*
117 * The grammar will have produced a list of RangeVars, RangeSubselects,
118 * RangeFunctions, and/or JoinExprs. Transform each one (possibly adding
119 * entries to the rtable), check for duplicate refnames, and then add it
120 * to the joinlist and namespace.
121 *
122 * Note we must process the items left-to-right for proper handling of
123 * LATERAL references.
124 */
125 foreach(fl, frmList)
126 {
127 Node *n = lfirst(fl);
128 ParseNamespaceItem *nsitem;
129 List *namespace;
130
131 n = transformFromClauseItem(pstate, n,
132 &nsitem,
133 &namespace);
134
135 checkNameSpaceConflicts(pstate, pstate->p_namespace, namespace);
136
137 /* Mark the new namespace items as visible only to LATERAL */
138 setNamespaceLateralState(namespace, true, true);
139
140 pstate->p_joinlist = lappend(pstate->p_joinlist, n);
141 pstate->p_namespace = list_concat(pstate->p_namespace, namespace);
142 }
143
144 /*
145 * We're done parsing the FROM list, so make all namespace items
146 * unconditionally visible. Note that this will also reset lateral_only
147 * for any namespace items that were already present when we were called;
148 * but those should have been that way already.
149 */
150 setNamespaceLateralState(pstate->p_namespace, false, true);
151}
static void setNamespaceLateralState(List *namespace, bool lateral_only, bool lateral_ok)
static Node * transformFromClauseItem(ParseState *pstate, Node *n, ParseNamespaceItem **top_nsitem, List **namespace)
void checkNameSpaceConflicts(ParseState *pstate, List *namespace1, List *namespace2)
List * p_namespace
Definition: parse_node.h:219
List * p_joinlist
Definition: parse_node.h:217

References checkNameSpaceConflicts(), lappend(), lfirst, list_concat(), ParseState::p_joinlist, ParseState::p_namespace, setNamespaceLateralState(), and transformFromClauseItem().

Referenced by transformDeleteStmt(), transformMergeStmt(), transformPLAssignStmt(), transformSelectStmt(), and transformUpdateStmt().

◆ transformFromClauseItem()

static Node * transformFromClauseItem ( ParseState pstate,
Node n,
ParseNamespaceItem **  top_nsitem,
List **  namespace 
)
static

Definition at line 1054 of file parse_clause.c.

1057{
1058 /* Guard against stack overflow due to overly deep subtree */
1060
1061 if (IsA(n, RangeVar))
1062 {
1063 /* Plain relation reference, or perhaps a CTE reference */
1064 RangeVar *rv = (RangeVar *) n;
1065 RangeTblRef *rtr;
1066 ParseNamespaceItem *nsitem;
1067
1068 /* Check if it's a CTE or tuplestore reference */
1069 nsitem = getNSItemForSpecialRelationTypes(pstate, rv);
1070
1071 /* if not found above, must be a table reference */
1072 if (!nsitem)
1073 nsitem = transformTableEntry(pstate, rv);
1074
1075 *top_nsitem = nsitem;
1076 *namespace = list_make1(nsitem);
1077 rtr = makeNode(RangeTblRef);
1078 rtr->rtindex = nsitem->p_rtindex;
1079 return (Node *) rtr;
1080 }
1081 else if (IsA(n, RangeSubselect))
1082 {
1083 /* sub-SELECT is like a plain relation */
1084 RangeTblRef *rtr;
1085 ParseNamespaceItem *nsitem;
1086
1087 nsitem = transformRangeSubselect(pstate, (RangeSubselect *) n);
1088 *top_nsitem = nsitem;
1089 *namespace = list_make1(nsitem);
1090 rtr = makeNode(RangeTblRef);
1091 rtr->rtindex = nsitem->p_rtindex;
1092 return (Node *) rtr;
1093 }
1094 else if (IsA(n, RangeFunction))
1095 {
1096 /* function is like a plain relation */
1097 RangeTblRef *rtr;
1098 ParseNamespaceItem *nsitem;
1099
1100 nsitem = transformRangeFunction(pstate, (RangeFunction *) n);
1101 *top_nsitem = nsitem;
1102 *namespace = list_make1(nsitem);
1103 rtr = makeNode(RangeTblRef);
1104 rtr->rtindex = nsitem->p_rtindex;
1105 return (Node *) rtr;
1106 }
1107 else if (IsA(n, RangeTableFunc) || IsA(n, JsonTable))
1108 {
1109 /* table function is like a plain relation */
1110 RangeTblRef *rtr;
1111 ParseNamespaceItem *nsitem;
1112
1113 if (IsA(n, JsonTable))
1114 nsitem = transformJsonTable(pstate, (JsonTable *) n);
1115 else
1116 nsitem = transformRangeTableFunc(pstate, (RangeTableFunc *) n);
1117
1118 *top_nsitem = nsitem;
1119 *namespace = list_make1(nsitem);
1120 rtr = makeNode(RangeTblRef);
1121 rtr->rtindex = nsitem->p_rtindex;
1122 return (Node *) rtr;
1123 }
1124 else if (IsA(n, RangeTableSample))
1125 {
1126 /* TABLESAMPLE clause (wrapping some other valid FROM node) */
1128 Node *rel;
1129 RangeTblEntry *rte;
1130
1131 /* Recursively transform the contained relation */
1132 rel = transformFromClauseItem(pstate, rts->relation,
1133 top_nsitem, namespace);
1134 rte = (*top_nsitem)->p_rte;
1135 /* We only support this on plain relations and matviews */
1136 if (rte->rtekind != RTE_RELATION ||
1137 (rte->relkind != RELKIND_RELATION &&
1138 rte->relkind != RELKIND_MATVIEW &&
1139 rte->relkind != RELKIND_PARTITIONED_TABLE))
1140 ereport(ERROR,
1141 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1142 errmsg("TABLESAMPLE clause can only be applied to tables and materialized views"),
1143 parser_errposition(pstate, exprLocation(rts->relation))));
1144
1145 /* Transform TABLESAMPLE details and attach to the RTE */
1146 rte->tablesample = transformRangeTableSample(pstate, rts);
1147 return rel;
1148 }
1149 else if (IsA(n, JoinExpr))
1150 {
1151 /* A newfangled join expression */
1152 JoinExpr *j = (JoinExpr *) n;
1153 ParseNamespaceItem *nsitem;
1154 ParseNamespaceItem *l_nsitem;
1155 ParseNamespaceItem *r_nsitem;
1156 List *l_namespace,
1157 *r_namespace,
1158 *my_namespace,
1159 *l_colnames,
1160 *r_colnames,
1161 *res_colnames,
1162 *l_colnos,
1163 *r_colnos,
1164 *res_colvars;
1165 ParseNamespaceColumn *l_nscolumns,
1166 *r_nscolumns,
1167 *res_nscolumns;
1168 int res_colindex;
1169 bool lateral_ok;
1170 int sv_namespace_length;
1171 int k;
1172
1173 /*
1174 * Recursively process the left subtree, then the right. We must do
1175 * it in this order for correct visibility of LATERAL references.
1176 */
1177 j->larg = transformFromClauseItem(pstate, j->larg,
1178 &l_nsitem,
1179 &l_namespace);
1180
1181 /*
1182 * Make the left-side RTEs available for LATERAL access within the
1183 * right side, by temporarily adding them to the pstate's namespace
1184 * list. Per SQL:2008, if the join type is not INNER or LEFT then the
1185 * left-side names must still be exposed, but it's an error to
1186 * reference them. (Stupid design, but that's what it says.) Hence,
1187 * we always push them into the namespace, but mark them as not
1188 * lateral_ok if the jointype is wrong.
1189 *
1190 * Notice that we don't require the merged namespace list to be
1191 * conflict-free. See the comments for scanNameSpaceForRefname().
1192 */
1193 lateral_ok = (j->jointype == JOIN_INNER || j->jointype == JOIN_LEFT);
1194 setNamespaceLateralState(l_namespace, true, lateral_ok);
1195
1196 sv_namespace_length = list_length(pstate->p_namespace);
1197 pstate->p_namespace = list_concat(pstate->p_namespace, l_namespace);
1198
1199 /* And now we can process the RHS */
1200 j->rarg = transformFromClauseItem(pstate, j->rarg,
1201 &r_nsitem,
1202 &r_namespace);
1203
1204 /* Remove the left-side RTEs from the namespace list again */
1205 pstate->p_namespace = list_truncate(pstate->p_namespace,
1206 sv_namespace_length);
1207
1208 /*
1209 * Check for conflicting refnames in left and right subtrees. Must do
1210 * this because higher levels will assume I hand back a self-
1211 * consistent namespace list.
1212 */
1213 checkNameSpaceConflicts(pstate, l_namespace, r_namespace);
1214
1215 /*
1216 * Generate combined namespace info for possible use below.
1217 */
1218 my_namespace = list_concat(l_namespace, r_namespace);
1219
1220 /*
1221 * We'll work from the nscolumns data and eref alias column names for
1222 * each of the input nsitems. Note that these include dropped
1223 * columns, which is helpful because we can keep track of physical
1224 * input column numbers more easily.
1225 */
1226 l_nscolumns = l_nsitem->p_nscolumns;
1227 l_colnames = l_nsitem->p_names->colnames;
1228 r_nscolumns = r_nsitem->p_nscolumns;
1229 r_colnames = r_nsitem->p_names->colnames;
1230
1231 /*
1232 * Natural join does not explicitly specify columns; must generate
1233 * columns to join. Need to run through the list of columns from each
1234 * table or join result and match up the column names. Use the first
1235 * table, and check every column in the second table for a match.
1236 * (We'll check that the matches were unique later on.) The result of
1237 * this step is a list of column names just like an explicitly-written
1238 * USING list.
1239 */
1240 if (j->isNatural)
1241 {
1242 List *rlist = NIL;
1243 ListCell *lx,
1244 *rx;
1245
1246 Assert(j->usingClause == NIL); /* shouldn't have USING() too */
1247
1248 foreach(lx, l_colnames)
1249 {
1250 char *l_colname = strVal(lfirst(lx));
1251 String *m_name = NULL;
1252
1253 if (l_colname[0] == '\0')
1254 continue; /* ignore dropped columns */
1255
1256 foreach(rx, r_colnames)
1257 {
1258 char *r_colname = strVal(lfirst(rx));
1259
1260 if (strcmp(l_colname, r_colname) == 0)
1261 {
1262 m_name = makeString(l_colname);
1263 break;
1264 }
1265 }
1266
1267 /* matched a right column? then keep as join column... */
1268 if (m_name != NULL)
1269 rlist = lappend(rlist, m_name);
1270 }
1271
1272 j->usingClause = rlist;
1273 }
1274
1275 /*
1276 * If a USING clause alias was specified, save the USING columns as
1277 * its column list.
1278 */
1279 if (j->join_using_alias)
1280 j->join_using_alias->colnames = j->usingClause;
1281
1282 /*
1283 * Now transform the join qualifications, if any.
1284 */
1285 l_colnos = NIL;
1286 r_colnos = NIL;
1287 res_colnames = NIL;
1288 res_colvars = NIL;
1289
1290 /* this may be larger than needed, but it's not worth being exact */
1291 res_nscolumns = (ParseNamespaceColumn *)
1292 palloc0((list_length(l_colnames) + list_length(r_colnames)) *
1293 sizeof(ParseNamespaceColumn));
1294 res_colindex = 0;
1295
1296 if (j->usingClause)
1297 {
1298 /*
1299 * JOIN/USING (or NATURAL JOIN, as transformed above). Transform
1300 * the list into an explicit ON-condition.
1301 */
1302 List *ucols = j->usingClause;
1303 List *l_usingvars = NIL;
1304 List *r_usingvars = NIL;
1305 ListCell *ucol;
1306
1307 Assert(j->quals == NULL); /* shouldn't have ON() too */
1308
1309 foreach(ucol, ucols)
1310 {
1311 char *u_colname = strVal(lfirst(ucol));
1312 ListCell *col;
1313 int ndx;
1314 int l_index = -1;
1315 int r_index = -1;
1316 Var *l_colvar,
1317 *r_colvar;
1318
1319 Assert(u_colname[0] != '\0');
1320
1321 /* Check for USING(foo,foo) */
1322 foreach(col, res_colnames)
1323 {
1324 char *res_colname = strVal(lfirst(col));
1325
1326 if (strcmp(res_colname, u_colname) == 0)
1327 ereport(ERROR,
1328 (errcode(ERRCODE_DUPLICATE_COLUMN),
1329 errmsg("column name \"%s\" appears more than once in USING clause",
1330 u_colname)));
1331 }
1332
1333 /* Find it in left input */
1334 ndx = 0;
1335 foreach(col, l_colnames)
1336 {
1337 char *l_colname = strVal(lfirst(col));
1338
1339 if (strcmp(l_colname, u_colname) == 0)
1340 {
1341 if (l_index >= 0)
1342 ereport(ERROR,
1343 (errcode(ERRCODE_AMBIGUOUS_COLUMN),
1344 errmsg("common column name \"%s\" appears more than once in left table",
1345 u_colname)));
1346 l_index = ndx;
1347 }
1348 ndx++;
1349 }
1350 if (l_index < 0)
1351 ereport(ERROR,
1352 (errcode(ERRCODE_UNDEFINED_COLUMN),
1353 errmsg("column \"%s\" specified in USING clause does not exist in left table",
1354 u_colname)));
1355 l_colnos = lappend_int(l_colnos, l_index + 1);
1356
1357 /* Find it in right input */
1358 ndx = 0;
1359 foreach(col, r_colnames)
1360 {
1361 char *r_colname = strVal(lfirst(col));
1362
1363 if (strcmp(r_colname, u_colname) == 0)
1364 {
1365 if (r_index >= 0)
1366 ereport(ERROR,
1367 (errcode(ERRCODE_AMBIGUOUS_COLUMN),
1368 errmsg("common column name \"%s\" appears more than once in right table",
1369 u_colname)));
1370 r_index = ndx;
1371 }
1372 ndx++;
1373 }
1374 if (r_index < 0)
1375 ereport(ERROR,
1376 (errcode(ERRCODE_UNDEFINED_COLUMN),
1377 errmsg("column \"%s\" specified in USING clause does not exist in right table",
1378 u_colname)));
1379 r_colnos = lappend_int(r_colnos, r_index + 1);
1380
1381 /* Build Vars to use in the generated JOIN ON clause */
1382 l_colvar = buildVarFromNSColumn(pstate, l_nscolumns + l_index);
1383 l_usingvars = lappend(l_usingvars, l_colvar);
1384 r_colvar = buildVarFromNSColumn(pstate, r_nscolumns + r_index);
1385 r_usingvars = lappend(r_usingvars, r_colvar);
1386
1387 /*
1388 * While we're here, add column names to the res_colnames
1389 * list. It's a bit ugly to do this here while the
1390 * corresponding res_colvars entries are not made till later,
1391 * but doing this later would require an additional traversal
1392 * of the usingClause list.
1393 */
1394 res_colnames = lappend(res_colnames, lfirst(ucol));
1395 }
1396
1397 /* Construct the generated JOIN ON clause */
1398 j->quals = transformJoinUsingClause(pstate,
1399 l_usingvars,
1400 r_usingvars);
1401 }
1402 else if (j->quals)
1403 {
1404 /* User-written ON-condition; transform it */
1405 j->quals = transformJoinOnClause(pstate, j, my_namespace);
1406 }
1407 else
1408 {
1409 /* CROSS JOIN: no quals */
1410 }
1411
1412 /*
1413 * If this is an outer join, now mark the appropriate child RTEs as
1414 * being nulled by this join. We have finished processing the child
1415 * join expressions as well as the current join's quals, which deal in
1416 * non-nulled input columns. All future references to those RTEs will
1417 * see possibly-nulled values, and we should mark generated Vars to
1418 * account for that. In particular, the join alias Vars that we're
1419 * about to build should reflect the nulling effects of this join.
1420 *
1421 * A difficulty with doing this is that we need the join's RT index,
1422 * which we don't officially have yet. However, no other RTE can get
1423 * made between here and the addRangeTableEntryForJoin call, so we can
1424 * predict what the assignment will be. (Alternatively, we could call
1425 * addRangeTableEntryForJoin before we have all the data computed, but
1426 * this seems less ugly.)
1427 */
1428 j->rtindex = list_length(pstate->p_rtable) + 1;
1429
1430 switch (j->jointype)
1431 {
1432 case JOIN_INNER:
1433 break;
1434 case JOIN_LEFT:
1435 markRelsAsNulledBy(pstate, j->rarg, j->rtindex);
1436 break;
1437 case JOIN_FULL:
1438 markRelsAsNulledBy(pstate, j->larg, j->rtindex);
1439 markRelsAsNulledBy(pstate, j->rarg, j->rtindex);
1440 break;
1441 case JOIN_RIGHT:
1442 markRelsAsNulledBy(pstate, j->larg, j->rtindex);
1443 break;
1444 default:
1445 /* shouldn't see any other types here */
1446 elog(ERROR, "unrecognized join type: %d",
1447 (int) j->jointype);
1448 break;
1449 }
1450
1451 /*
1452 * Now we can construct join alias expressions for the USING columns.
1453 */
1454 if (j->usingClause)
1455 {
1456 ListCell *lc1,
1457 *lc2;
1458
1459 /* Scan the colnos lists to recover info from the previous loop */
1460 forboth(lc1, l_colnos, lc2, r_colnos)
1461 {
1462 int l_index = lfirst_int(lc1) - 1;
1463 int r_index = lfirst_int(lc2) - 1;
1464 Var *l_colvar,
1465 *r_colvar;
1466 Node *u_colvar;
1467 ParseNamespaceColumn *res_nscolumn;
1468
1469 /*
1470 * Note we re-build these Vars: they might have different
1471 * varnullingrels than the ones made in the previous loop.
1472 */
1473 l_colvar = buildVarFromNSColumn(pstate, l_nscolumns + l_index);
1474 r_colvar = buildVarFromNSColumn(pstate, r_nscolumns + r_index);
1475
1476 /* Construct the join alias Var for this column */
1477 u_colvar = buildMergedJoinVar(pstate,
1478 j->jointype,
1479 l_colvar,
1480 r_colvar);
1481 res_colvars = lappend(res_colvars, u_colvar);
1482
1483 /* Construct column's res_nscolumns[] entry */
1484 res_nscolumn = res_nscolumns + res_colindex;
1485 res_colindex++;
1486 if (u_colvar == (Node *) l_colvar)
1487 {
1488 /* Merged column is equivalent to left input */
1489 *res_nscolumn = l_nscolumns[l_index];
1490 }
1491 else if (u_colvar == (Node *) r_colvar)
1492 {
1493 /* Merged column is equivalent to right input */
1494 *res_nscolumn = r_nscolumns[r_index];
1495 }
1496 else
1497 {
1498 /*
1499 * Merged column is not semantically equivalent to either
1500 * input, so it needs to be referenced as the join output
1501 * column.
1502 */
1503 res_nscolumn->p_varno = j->rtindex;
1504 res_nscolumn->p_varattno = res_colindex;
1505 res_nscolumn->p_vartype = exprType(u_colvar);
1506 res_nscolumn->p_vartypmod = exprTypmod(u_colvar);
1507 res_nscolumn->p_varcollid = exprCollation(u_colvar);
1508 res_nscolumn->p_varnosyn = j->rtindex;
1509 res_nscolumn->p_varattnosyn = res_colindex;
1510 }
1511 }
1512 }
1513
1514 /* Add remaining columns from each side to the output columns */
1515 res_colindex +=
1517 l_nscolumns, l_colnames, &l_colnos,
1518 &res_colnames, &res_colvars,
1519 res_nscolumns + res_colindex);
1520 res_colindex +=
1522 r_nscolumns, r_colnames, &r_colnos,
1523 &res_colnames, &res_colvars,
1524 res_nscolumns + res_colindex);
1525
1526 /* If join has an alias, it syntactically hides all inputs */
1527 if (j->alias)
1528 {
1529 for (k = 0; k < res_colindex; k++)
1530 {
1531 ParseNamespaceColumn *nscol = res_nscolumns + k;
1532
1533 nscol->p_varnosyn = j->rtindex;
1534 nscol->p_varattnosyn = k + 1;
1535 }
1536 }
1537
1538 /*
1539 * Now build an RTE and nsitem for the result of the join.
1540 */
1541 nsitem = addRangeTableEntryForJoin(pstate,
1542 res_colnames,
1543 res_nscolumns,
1544 j->jointype,
1545 list_length(j->usingClause),
1546 res_colvars,
1547 l_colnos,
1548 r_colnos,
1549 j->join_using_alias,
1550 j->alias,
1551 true);
1552
1553 /* Verify that we correctly predicted the join's RT index */
1554 Assert(j->rtindex == nsitem->p_rtindex);
1555 /* Cross-check number of columns, too */
1556 Assert(res_colindex == list_length(nsitem->p_names->colnames));
1557
1558 /*
1559 * Save a link to the JoinExpr in the proper element of p_joinexprs.
1560 * Since we maintain that list lazily, it may be necessary to fill in
1561 * empty entries before we can add the JoinExpr in the right place.
1562 */
1563 for (k = list_length(pstate->p_joinexprs) + 1; k < j->rtindex; k++)
1564 pstate->p_joinexprs = lappend(pstate->p_joinexprs, NULL);
1565 pstate->p_joinexprs = lappend(pstate->p_joinexprs, j);
1566 Assert(list_length(pstate->p_joinexprs) == j->rtindex);
1567
1568 /*
1569 * If the join has a USING alias, build a ParseNamespaceItem for that
1570 * and add it to the list of nsitems in the join's input.
1571 */
1572 if (j->join_using_alias)
1573 {
1574 ParseNamespaceItem *jnsitem;
1575
1576 jnsitem = (ParseNamespaceItem *) palloc(sizeof(ParseNamespaceItem));
1577 jnsitem->p_names = j->join_using_alias;
1578 jnsitem->p_rte = nsitem->p_rte;
1579 jnsitem->p_rtindex = nsitem->p_rtindex;
1580 jnsitem->p_perminfo = NULL;
1581 /* no need to copy the first N columns, just use res_nscolumns */
1582 jnsitem->p_nscolumns = res_nscolumns;
1583 /* set default visibility flags; might get changed later */
1584 jnsitem->p_rel_visible = true;
1585 jnsitem->p_cols_visible = true;
1586 jnsitem->p_lateral_only = false;
1587 jnsitem->p_lateral_ok = true;
1589 /* Per SQL, we must check for alias conflicts */
1590 checkNameSpaceConflicts(pstate, list_make1(jnsitem), my_namespace);
1591 my_namespace = lappend(my_namespace, jnsitem);
1592 }
1593
1594 /*
1595 * Prepare returned namespace list. If the JOIN has an alias then it
1596 * hides the contained RTEs completely; otherwise, the contained RTEs
1597 * are still visible as table names, but are not visible for
1598 * unqualified column-name access.
1599 *
1600 * Note: if there are nested alias-less JOINs, the lower-level ones
1601 * will remain in the list although they have neither p_rel_visible
1602 * nor p_cols_visible set. We could delete such list items, but it's
1603 * unclear that it's worth expending cycles to do so.
1604 */
1605 if (j->alias != NULL)
1606 my_namespace = NIL;
1607 else
1608 setNamespaceColumnVisibility(my_namespace, false);
1609
1610 /*
1611 * The join RTE itself is always made visible for unqualified column
1612 * names. It's visible as a relation name only if it has an alias.
1613 */
1614 nsitem->p_rel_visible = (j->alias != NULL);
1615 nsitem->p_cols_visible = true;
1616 nsitem->p_lateral_only = false;
1617 nsitem->p_lateral_ok = true;
1618
1619 *top_nsitem = nsitem;
1620 *namespace = lappend(my_namespace, nsitem);
1621
1622 return (Node *) j;
1623 }
1624 else
1625 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(n));
1626 return NULL; /* can't get here, keep compiler quiet */
1627}
List * list_truncate(List *list, int new_size)
Definition: list.c:631
void * palloc0(Size size)
Definition: mcxt.c:1347
void * palloc(Size size)
Definition: mcxt.c:1317
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:301
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:821
static Node * transformJoinOnClause(ParseState *pstate, JoinExpr *j, List *namespace)
Definition: parse_clause.c:365
static int extractRemainingColumns(ParseState *pstate, ParseNamespaceColumn *src_nscolumns, List *src_colnames, List **src_colnos, List **res_colnames, List **res_colvars, ParseNamespaceColumn *res_nscolumns)
Definition: parse_clause.c:253
static ParseNamespaceItem * transformRangeSubselect(ParseState *pstate, RangeSubselect *r)
Definition: parse_clause.c:405
static ParseNamespaceItem * transformRangeTableFunc(ParseState *pstate, RangeTableFunc *rtf)
Definition: parse_clause.c:686
static void setNamespaceColumnVisibility(List *namespace, bool cols_visible)
static ParseNamespaceItem * getNSItemForSpecialRelationTypes(ParseState *pstate, RangeVar *rv)
static TableSampleClause * transformRangeTableSample(ParseState *pstate, RangeTableSample *rts)
Definition: parse_clause.c:908
static Node * transformJoinUsingClause(ParseState *pstate, List *leftVars, List *rightVars)
Definition: parse_clause.c:306
static Node * buildMergedJoinVar(ParseState *pstate, JoinType jointype, Var *l_colvar, Var *r_colvar)
static ParseNamespaceItem * transformTableEntry(ParseState *pstate, RangeVar *r)
Definition: parse_clause.c:395
static ParseNamespaceItem * transformRangeFunction(ParseState *pstate, RangeFunction *r)
Definition: parse_clause.c:463
ParseNamespaceItem * transformJsonTable(ParseState *pstate, JsonTable *jt)
struct ParseNamespaceColumn ParseNamespaceColumn
Definition: parse_node.h:25
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)
@ RTE_RELATION
Definition: parsenodes.h:1026
@ VAR_RETURNING_DEFAULT
Definition: primnodes.h:255
List * colnames
Definition: primnodes.h:51
RangeTblEntry * p_rte
Definition: parse_node.h:311
ParseNamespaceColumn * p_nscolumns
Definition: parse_node.h:315
VarReturningType p_returning_type
Definition: parse_node.h:320
List * p_joinexprs
Definition: parse_node.h:215
List * p_rtable
Definition: parse_node.h:212
struct TableSampleClause * tablesample
Definition: parsenodes.h:1107
RTEKind rtekind
Definition: parsenodes.h:1056

References addRangeTableEntryForJoin(), Assert, buildMergedJoinVar(), buildVarFromNSColumn(), check_stack_depth(), checkNameSpaceConflicts(), Alias::colnames, elog, ereport, errcode(), errmsg(), ERROR, exprCollation(), exprLocation(), exprType(), exprTypmod(), extractRemainingColumns(), forboth, getNSItemForSpecialRelationTypes(), IsA, j, JOIN_FULL, JOIN_INNER, JOIN_LEFT, JOIN_RIGHT, lappend(), lappend_int(), lfirst, lfirst_int, list_concat(), list_length(), list_make1, list_truncate(), makeNode, makeString(), markRelsAsNulledBy(), NIL, nodeTag, ParseNamespaceItem::p_cols_visible, ParseState::p_joinexprs, ParseNamespaceItem::p_lateral_ok, ParseNamespaceItem::p_lateral_only, ParseNamespaceItem::p_names, ParseState::p_namespace, ParseNamespaceItem::p_nscolumns, ParseNamespaceItem::p_perminfo, ParseNamespaceItem::p_rel_visible, ParseNamespaceItem::p_returning_type, ParseState::p_rtable, ParseNamespaceItem::p_rte, ParseNamespaceItem::p_rtindex, ParseNamespaceColumn::p_varattno, ParseNamespaceColumn::p_varattnosyn, ParseNamespaceColumn::p_varcollid, ParseNamespaceColumn::p_varno, ParseNamespaceColumn::p_varnosyn, ParseNamespaceColumn::p_vartype, ParseNamespaceColumn::p_vartypmod, palloc(), palloc0(), parser_errposition(), RangeTableSample::relation, RTE_RELATION, RangeTblEntry::rtekind, RangeTblRef::rtindex, setNamespaceColumnVisibility(), setNamespaceLateralState(), strVal, RangeTblEntry::tablesample, transformFromClauseItem(), transformJoinOnClause(), transformJoinUsingClause(), transformJsonTable(), transformRangeFunction(), transformRangeSubselect(), transformRangeTableFunc(), transformRangeTableSample(), transformTableEntry(), and VAR_RETURNING_DEFAULT.

Referenced by transformFromClause(), and transformFromClauseItem().

◆ transformGroupClause()

List * transformGroupClause ( ParseState pstate,
List grouplist,
List **  groupingSets,
List **  targetlist,
List sortClause,
ParseExprKind  exprKind,
bool  useSQL99 
)

Definition at line 2632 of file parse_clause.c.

2635{
2636 List *result = NIL;
2637 List *flat_grouplist;
2638 List *gsets = NIL;
2639 ListCell *gl;
2640 bool hasGroupingSets = false;
2641 Bitmapset *seen_local = NULL;
2642
2643 /*
2644 * Recursively flatten implicit RowExprs. (Technically this is only needed
2645 * for GROUP BY, per the syntax rules for grouping sets, but we do it
2646 * anyway.)
2647 */
2648 flat_grouplist = (List *) flatten_grouping_sets((Node *) grouplist,
2649 true,
2650 &hasGroupingSets);
2651
2652 /*
2653 * If the list is now empty, but hasGroupingSets is true, it's because we
2654 * elided redundant empty grouping sets. Restore a single empty grouping
2655 * set to leave a canonical form: GROUP BY ()
2656 */
2657
2658 if (flat_grouplist == NIL && hasGroupingSets)
2659 {
2661 NIL,
2662 exprLocation((Node *) grouplist)));
2663 }
2664
2665 foreach(gl, flat_grouplist)
2666 {
2667 Node *gexpr = (Node *) lfirst(gl);
2668
2669 if (IsA(gexpr, GroupingSet))
2670 {
2671 GroupingSet *gset = (GroupingSet *) gexpr;
2672
2673 switch (gset->kind)
2674 {
2675 case GROUPING_SET_EMPTY:
2676 gsets = lappend(gsets, gset);
2677 break;
2679 /* can't happen */
2680 Assert(false);
2681 break;
2682 case GROUPING_SET_SETS:
2683 case GROUPING_SET_CUBE:
2685 gsets = lappend(gsets,
2686 transformGroupingSet(&result,
2687 pstate, gset,
2688 targetlist, sortClause,
2689 exprKind, useSQL99, true));
2690 break;
2691 }
2692 }
2693 else
2694 {
2695 Index ref = transformGroupClauseExpr(&result, seen_local,
2696 pstate, gexpr,
2697 targetlist, sortClause,
2698 exprKind, useSQL99, true);
2699
2700 if (ref > 0)
2701 {
2702 seen_local = bms_add_member(seen_local, ref);
2703 if (hasGroupingSets)
2704 gsets = lappend(gsets,
2706 list_make1_int(ref),
2707 exprLocation(gexpr)));
2708 }
2709 }
2710 }
2711
2712 /* parser should prevent this */
2713 Assert(gsets == NIL || groupingSets != NULL);
2714
2715 if (groupingSets)
2716 *groupingSets = gsets;
2717
2718 return result;
2719}
static Index transformGroupClauseExpr(List **flatresult, Bitmapset *seen_local, ParseState *pstate, Node *gexpr, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
static Node * transformGroupingSet(List **flatresult, ParseState *pstate, GroupingSet *gset, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
@ GROUPING_SET_CUBE
Definition: parsenodes.h:1511
@ GROUPING_SET_SIMPLE
Definition: parsenodes.h:1509
@ GROUPING_SET_ROLLUP
Definition: parsenodes.h:1510
#define list_make1_int(x1)
Definition: pg_list.h:227

References Assert, bms_add_member(), exprLocation(), flatten_grouping_sets(), GROUPING_SET_CUBE, GROUPING_SET_EMPTY, GROUPING_SET_ROLLUP, GROUPING_SET_SETS, GROUPING_SET_SIMPLE, IsA, lappend(), lfirst, list_make1, list_make1_int, makeGroupingSet(), NIL, transformGroupClauseExpr(), and transformGroupingSet().

Referenced by transformPLAssignStmt(), transformSelectStmt(), and transformWindowDefinitions().

◆ transformGroupClauseExpr()

static Index transformGroupClauseExpr ( List **  flatresult,
Bitmapset seen_local,
ParseState pstate,
Node gexpr,
List **  targetlist,
List sortClause,
ParseExprKind  exprKind,
bool  useSQL99,
bool  toplevel 
)
static

Definition at line 2367 of file parse_clause.c.

2371{
2372 TargetEntry *tle;
2373 bool found = false;
2374
2375 if (useSQL99)
2376 tle = findTargetlistEntrySQL99(pstate, gexpr,
2377 targetlist, exprKind);
2378 else
2379 tle = findTargetlistEntrySQL92(pstate, gexpr,
2380 targetlist, exprKind);
2381
2382 if (tle->ressortgroupref > 0)
2383 {
2384 ListCell *sl;
2385
2386 /*
2387 * Eliminate duplicates (GROUP BY x, x) but only at local level.
2388 * (Duplicates in grouping sets can affect the number of returned
2389 * rows, so can't be dropped indiscriminately.)
2390 *
2391 * Since we don't care about anything except the sortgroupref, we can
2392 * use a bitmapset rather than scanning lists.
2393 */
2394 if (bms_is_member(tle->ressortgroupref, seen_local))
2395 return 0;
2396
2397 /*
2398 * If we're already in the flat clause list, we don't need to consider
2399 * adding ourselves again.
2400 */
2401 found = targetIsInSortList(tle, InvalidOid, *flatresult);
2402 if (found)
2403 return tle->ressortgroupref;
2404
2405 /*
2406 * If the GROUP BY tlist entry also appears in ORDER BY, copy operator
2407 * info from the (first) matching ORDER BY item. This means that if
2408 * you write something like "GROUP BY foo ORDER BY foo USING <<<", the
2409 * GROUP BY operation silently takes on the equality semantics implied
2410 * by the ORDER BY. There are two reasons to do this: it improves the
2411 * odds that we can implement both GROUP BY and ORDER BY with a single
2412 * sort step, and it allows the user to choose the equality semantics
2413 * used by GROUP BY, should she be working with a datatype that has
2414 * more than one equality operator.
2415 *
2416 * If we're in a grouping set, though, we force our requested ordering
2417 * to be NULLS LAST, because if we have any hope of using a sorted agg
2418 * for the job, we're going to be tacking on generated NULL values
2419 * after the corresponding groups. If the user demands nulls first,
2420 * another sort step is going to be inevitable, but that's the
2421 * planner's problem.
2422 */
2423
2424 foreach(sl, sortClause)
2425 {
2427
2428 if (sc->tleSortGroupRef == tle->ressortgroupref)
2429 {
2430 SortGroupClause *grpc = copyObject(sc);
2431
2432 if (!toplevel)
2433 grpc->nulls_first = false;
2434 *flatresult = lappend(*flatresult, grpc);
2435 found = true;
2436 break;
2437 }
2438 }
2439 }
2440
2441 /*
2442 * If no match in ORDER BY, just add it to the result using default
2443 * sort/group semantics.
2444 */
2445 if (!found)
2446 *flatresult = addTargetToGroupList(pstate, tle,
2447 *flatresult, *targetlist,
2448 exprLocation(gexpr));
2449
2450 /*
2451 * _something_ must have assigned us a sortgroupref by now...
2452 */
2453
2454 return tle->ressortgroupref;
2455}

References addTargetToGroupList(), bms_is_member(), copyObject, exprLocation(), findTargetlistEntrySQL92(), findTargetlistEntrySQL99(), InvalidOid, lappend(), lfirst, SortGroupClause::nulls_first, TargetEntry::ressortgroupref, targetIsInSortList(), and SortGroupClause::tleSortGroupRef.

Referenced by transformGroupClause(), transformGroupClauseList(), and transformGroupingSet().

◆ transformGroupClauseList()

static List * transformGroupClauseList ( List **  flatresult,
ParseState pstate,
List list,
List **  targetlist,
List sortClause,
ParseExprKind  exprKind,
bool  useSQL99,
bool  toplevel 
)
static

Definition at line 2475 of file parse_clause.c.

2479{
2480 Bitmapset *seen_local = NULL;
2481 List *result = NIL;
2482 ListCell *gl;
2483
2484 foreach(gl, list)
2485 {
2486 Node *gexpr = (Node *) lfirst(gl);
2487
2488 Index ref = transformGroupClauseExpr(flatresult,
2489 seen_local,
2490 pstate,
2491 gexpr,
2492 targetlist,
2493 sortClause,
2494 exprKind,
2495 useSQL99,
2496 toplevel);
2497
2498 if (ref > 0)
2499 {
2500 seen_local = bms_add_member(seen_local, ref);
2501 result = lappend_int(result, ref);
2502 }
2503 }
2504
2505 return result;
2506}

References bms_add_member(), lappend_int(), lfirst, sort-test::list, NIL, and transformGroupClauseExpr().

Referenced by transformGroupingSet().

◆ transformGroupingSet()

static Node * transformGroupingSet ( List **  flatresult,
ParseState pstate,
GroupingSet gset,
List **  targetlist,
List sortClause,
ParseExprKind  exprKind,
bool  useSQL99,
bool  toplevel 
)
static

Definition at line 2528 of file parse_clause.c.

2532{
2533 ListCell *gl;
2534 List *content = NIL;
2535
2536 Assert(toplevel || gset->kind != GROUPING_SET_SETS);
2537
2538 foreach(gl, gset->content)
2539 {
2540 Node *n = lfirst(gl);
2541
2542 if (IsA(n, List))
2543 {
2544 List *l = transformGroupClauseList(flatresult,
2545 pstate, (List *) n,
2546 targetlist, sortClause,
2547 exprKind, useSQL99, false);
2548
2549 content = lappend(content, makeGroupingSet(GROUPING_SET_SIMPLE,
2550 l,
2551 exprLocation(n)));
2552 }
2553 else if (IsA(n, GroupingSet))
2554 {
2555 GroupingSet *gset2 = (GroupingSet *) lfirst(gl);
2556
2557 content = lappend(content, transformGroupingSet(flatresult,
2558 pstate, gset2,
2559 targetlist, sortClause,
2560 exprKind, useSQL99, false));
2561 }
2562 else
2563 {
2564 Index ref = transformGroupClauseExpr(flatresult,
2565 NULL,
2566 pstate,
2567 n,
2568 targetlist,
2569 sortClause,
2570 exprKind,
2571 useSQL99,
2572 false);
2573
2574 content = lappend(content, makeGroupingSet(GROUPING_SET_SIMPLE,
2575 list_make1_int(ref),
2576 exprLocation(n)));
2577 }
2578 }
2579
2580 /* Arbitrarily cap the size of CUBE, which has exponential growth */
2581 if (gset->kind == GROUPING_SET_CUBE)
2582 {
2583 if (list_length(content) > 12)
2584 ereport(ERROR,
2585 (errcode(ERRCODE_TOO_MANY_COLUMNS),
2586 errmsg("CUBE is limited to 12 elements"),
2587 parser_errposition(pstate, gset->location)));
2588 }
2589
2590 return (Node *) makeGroupingSet(gset->kind, content, gset->location);
2591}
static List * transformGroupClauseList(List **flatresult, ParseState *pstate, List *list, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)

References Assert, GroupingSet::content, ereport, errcode(), errmsg(), ERROR, exprLocation(), GROUPING_SET_CUBE, GROUPING_SET_SETS, GROUPING_SET_SIMPLE, IsA, lappend(), lfirst, list_length(), list_make1_int, GroupingSet::location, makeGroupingSet(), NIL, parser_errposition(), transformGroupClauseExpr(), transformGroupClauseList(), and transformGroupingSet().

Referenced by transformGroupClause(), and transformGroupingSet().

◆ transformJoinOnClause()

static Node * transformJoinOnClause ( ParseState pstate,
JoinExpr j,
List namespace 
)
static

Definition at line 365 of file parse_clause.c.

366{
367 Node *result;
368 List *save_namespace;
369
370 /*
371 * The namespace that the join expression should see is just the two
372 * subtrees of the JOIN plus any outer references from upper pstate
373 * levels. Temporarily set this pstate's namespace accordingly. (We need
374 * not check for refname conflicts, because transformFromClauseItem()
375 * already did.) All namespace items are marked visible regardless of
376 * LATERAL state.
377 */
378 setNamespaceLateralState(namespace, false, true);
379
380 save_namespace = pstate->p_namespace;
381 pstate->p_namespace = namespace;
382
383 result = transformWhereClause(pstate, j->quals,
384 EXPR_KIND_JOIN_ON, "JOIN/ON");
385
386 pstate->p_namespace = save_namespace;
387
388 return result;
389}
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
@ EXPR_KIND_JOIN_ON
Definition: parse_node.h:42

References EXPR_KIND_JOIN_ON, j, ParseState::p_namespace, setNamespaceLateralState(), and transformWhereClause().

Referenced by transformFromClauseItem().

◆ transformJoinUsingClause()

static Node * transformJoinUsingClause ( ParseState pstate,
List leftVars,
List rightVars 
)
static

Definition at line 306 of file parse_clause.c.

308{
309 Node *result;
310 List *andargs = NIL;
311 ListCell *lvars,
312 *rvars;
313
314 /*
315 * We cheat a little bit here by building an untransformed operator tree
316 * whose leaves are the already-transformed Vars. This requires collusion
317 * from transformExpr(), which normally could be expected to complain
318 * about already-transformed subnodes. However, this does mean that we
319 * have to mark the columns as requiring SELECT privilege for ourselves;
320 * transformExpr() won't do it.
321 */
322 forboth(lvars, leftVars, rvars, rightVars)
323 {
324 Var *lvar = (Var *) lfirst(lvars);
325 Var *rvar = (Var *) lfirst(rvars);
326 A_Expr *e;
327
328 /* Require read access to the join variables */
329 markVarForSelectPriv(pstate, lvar);
330 markVarForSelectPriv(pstate, rvar);
331
332 /* Now create the lvar = rvar join condition */
334 (Node *) copyObject(lvar), (Node *) copyObject(rvar),
335 -1);
336
337 /* Prepare to combine into an AND clause, if multiple join columns */
338 andargs = lappend(andargs, e);
339 }
340
341 /* Only need an AND if there's more than one join column */
342 if (list_length(andargs) == 1)
343 result = (Node *) linitial(andargs);
344 else
345 result = (Node *) makeBoolExpr(AND_EXPR, andargs, -1);
346
347 /*
348 * Since the references are already Vars, and are certainly from the input
349 * relations, we don't have to go through the same pushups that
350 * transformJoinOnClause() does. Just invoke transformExpr() to fix up
351 * the operators, and we're done.
352 */
353 result = transformExpr(pstate, result, EXPR_KIND_JOIN_USING);
354
355 result = coerce_to_boolean(pstate, result, "JOIN/USING");
356
357 return result;
358}
Expr * makeBoolExpr(BoolExprType boolop, List *args, int location)
Definition: makefuncs.c:373
A_Expr * makeSimpleA_Expr(A_Expr_Kind kind, char *name, Node *lexpr, Node *rexpr, int location)
Definition: makefuncs.c:48
Node * coerce_to_boolean(ParseState *pstate, Node *node, const char *constructName)
@ EXPR_KIND_JOIN_USING
Definition: parse_node.h:43
void markVarForSelectPriv(ParseState *pstate, Var *var)
@ AEXPR_OP
Definition: parsenodes.h:324
e
Definition: preproc-init.c:82
@ AND_EXPR
Definition: primnodes.h:947

References AEXPR_OP, AND_EXPR, coerce_to_boolean(), copyObject, EXPR_KIND_JOIN_USING, forboth, lappend(), lfirst, linitial, list_length(), makeBoolExpr(), makeSimpleA_Expr(), markVarForSelectPriv(), NIL, and transformExpr().

Referenced by transformFromClauseItem().

◆ transformLimitClause()

Node * transformLimitClause ( ParseState pstate,
Node clause,
ParseExprKind  exprKind,
const char *  constructName,
LimitOption  limitOption 
)

Definition at line 1881 of file parse_clause.c.

1884{
1885 Node *qual;
1886
1887 if (clause == NULL)
1888 return NULL;
1889
1890 qual = transformExpr(pstate, clause, exprKind);
1891
1892 qual = coerce_to_specific_type(pstate, qual, INT8OID, constructName);
1893
1894 /* LIMIT can't refer to any variables of the current query */
1895 checkExprIsVarFree(pstate, qual, constructName);
1896
1897 /*
1898 * Don't allow NULLs in FETCH FIRST .. WITH TIES. This test is ugly and
1899 * extremely simplistic, in that you can pass a NULL anyway by hiding it
1900 * inside an expression -- but this protects ruleutils against emitting an
1901 * unadorned NULL that's not accepted back by the grammar.
1902 */
1903 if (exprKind == EXPR_KIND_LIMIT && limitOption == LIMIT_OPTION_WITH_TIES &&
1904 IsA(clause, A_Const) && castNode(A_Const, clause)->isnull)
1905 ereport(ERROR,
1906 (errcode(ERRCODE_INVALID_ROW_COUNT_IN_LIMIT_CLAUSE),
1907 errmsg("row count cannot be null in FETCH FIRST ... WITH TIES clause")));
1908
1909 return qual;
1910}
@ LIMIT_OPTION_WITH_TIES
Definition: nodes.h:432
@ EXPR_KIND_LIMIT
Definition: parse_node.h:62

References castNode, checkExprIsVarFree(), coerce_to_specific_type(), ereport, errcode(), errmsg(), ERROR, EXPR_KIND_LIMIT, IsA, LIMIT_OPTION_WITH_TIES, and transformExpr().

Referenced by transformPLAssignStmt(), transformSelectStmt(), transformSetOperationStmt(), and transformValuesClause().

◆ transformOnConflictArbiter()

void transformOnConflictArbiter ( ParseState pstate,
OnConflictClause onConflictClause,
List **  arbiterExpr,
Node **  arbiterWhere,
Oid constraint 
)

Definition at line 3297 of file parse_clause.c.

3301{
3302 InferClause *infer = onConflictClause->infer;
3303
3304 *arbiterExpr = NIL;
3305 *arbiterWhere = NULL;
3306 *constraint = InvalidOid;
3307
3308 if (onConflictClause->action == ONCONFLICT_UPDATE && !infer)
3309 ereport(ERROR,
3310 (errcode(ERRCODE_SYNTAX_ERROR),
3311 errmsg("ON CONFLICT DO UPDATE requires inference specification or constraint name"),
3312 errhint("For example, ON CONFLICT (column_name)."),
3313 parser_errposition(pstate,
3314 exprLocation((Node *) onConflictClause))));
3315
3316 /*
3317 * To simplify certain aspects of its design, speculative insertion into
3318 * system catalogs is disallowed
3319 */
3321 ereport(ERROR,
3322 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3323 errmsg("ON CONFLICT is not supported with system catalog tables"),
3324 parser_errposition(pstate,
3325 exprLocation((Node *) onConflictClause))));
3326
3327 /* Same applies to table used by logical decoding as catalog table */
3329 ereport(ERROR,
3330 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3331 errmsg("ON CONFLICT is not supported on table \"%s\" used as a catalog table",
3333 parser_errposition(pstate,
3334 exprLocation((Node *) onConflictClause))));
3335
3336 /* ON CONFLICT DO NOTHING does not require an inference clause */
3337 if (infer)
3338 {
3339 if (infer->indexElems)
3340 *arbiterExpr = resolve_unique_index_expr(pstate, infer,
3341 pstate->p_target_relation);
3342
3343 /*
3344 * Handling inference WHERE clause (for partial unique index
3345 * inference)
3346 */
3347 if (infer->whereClause)
3348 *arbiterWhere = transformExpr(pstate, infer->whereClause,
3350
3351 /*
3352 * If the arbiter is specified by constraint name, get the constraint
3353 * OID and mark the constrained columns as requiring SELECT privilege,
3354 * in the same way as would have happened if the arbiter had been
3355 * specified by explicit reference to the constraint's index columns.
3356 */
3357 if (infer->conname)
3358 {
3359 Oid relid = RelationGetRelid(pstate->p_target_relation);
3360 RTEPermissionInfo *perminfo = pstate->p_target_nsitem->p_perminfo;
3361 Bitmapset *conattnos;
3362
3363 conattnos = get_relation_constraint_attnos(relid, infer->conname,
3364 false, constraint);
3365
3366 /* Make sure the rel as a whole is marked for SELECT access */
3367 perminfo->requiredPerms |= ACL_SELECT;
3368 /* Mark the constrained columns as requiring SELECT access */
3369 perminfo->selectedCols = bms_add_members(perminfo->selectedCols,
3370 conattnos);
3371 }
3372 }
3373
3374 /*
3375 * It's convenient to form a list of expressions based on the
3376 * representation used by CREATE INDEX, since the same restrictions are
3377 * appropriate (e.g. on subqueries). However, from here on, a dedicated
3378 * primnode representation is used for inference elements, and so
3379 * assign_query_collations() can be trusted to do the right thing with the
3380 * post parse analysis query tree inference clause representation.
3381 */
3382}
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:917
bool IsCatalogRelation(Relation relation)
Definition: catalog.c:103
@ ONCONFLICT_UPDATE
Definition: nodes.h:420
static List * resolve_unique_index_expr(ParseState *pstate, InferClause *infer, Relation heapRel)
@ EXPR_KIND_INDEX_PREDICATE
Definition: parse_node.h:73
#define ACL_SELECT
Definition: parsenodes.h:77
Bitmapset * get_relation_constraint_attnos(Oid relid, const char *conname, bool missing_ok, Oid *constraintOid)
#define RelationGetRelid(relation)
Definition: rel.h:505
#define RelationIsUsedAsCatalogTable(relation)
Definition: rel.h:386
#define RelationGetRelationName(relation)
Definition: rel.h:539
char * conname
Definition: parsenodes.h:1620
Node * whereClause
Definition: parsenodes.h:1619
InferClause * infer
Definition: parsenodes.h:1634
OnConflictAction action
Definition: parsenodes.h:1633
Bitmapset * selectedCols
Definition: parsenodes.h:1302

References ACL_SELECT, OnConflictClause::action, bms_add_members(), InferClause::conname, ereport, errcode(), errhint(), errmsg(), ERROR, EXPR_KIND_INDEX_PREDICATE, exprLocation(), get_relation_constraint_attnos(), InferClause::indexElems, OnConflictClause::infer, InvalidOid, IsCatalogRelation(), NIL, ONCONFLICT_UPDATE, ParseNamespaceItem::p_perminfo, ParseState::p_target_nsitem, ParseState::p_target_relation, parser_errposition(), RelationGetRelationName, RelationGetRelid, RelationIsUsedAsCatalogTable, RTEPermissionInfo::requiredPerms, resolve_unique_index_expr(), RTEPermissionInfo::selectedCols, transformExpr(), and InferClause::whereClause.

Referenced by transformOnConflictClause().

◆ transformRangeFunction()

static ParseNamespaceItem * transformRangeFunction ( ParseState pstate,
RangeFunction r 
)
static

Definition at line 463 of file parse_clause.c.

464{
465 List *funcexprs = NIL;
466 List *funcnames = NIL;
467 List *coldeflists = NIL;
468 bool is_lateral;
469 ListCell *lc;
470
471 /*
472 * We make lateral_only names of this level visible, whether or not the
473 * RangeFunction is explicitly marked LATERAL. This is needed for SQL
474 * spec compliance in the case of UNNEST(), and seems useful on
475 * convenience grounds for all functions in FROM.
476 *
477 * (LATERAL can't nest within a single pstate level, so we don't need
478 * save/restore logic here.)
479 */
480 Assert(!pstate->p_lateral_active);
481 pstate->p_lateral_active = true;
482
483 /*
484 * Transform the raw expressions.
485 *
486 * While transforming, also save function names for possible use as alias
487 * and column names. We use the same transformation rules as for a SELECT
488 * output expression. For a FuncCall node, the result will be the
489 * function name, but it is possible for the grammar to hand back other
490 * node types.
491 *
492 * We have to get this info now, because FigureColname only works on raw
493 * parsetrees. Actually deciding what to do with the names is left up to
494 * addRangeTableEntryForFunction.
495 *
496 * Likewise, collect column definition lists if there were any. But
497 * complain if we find one here and the RangeFunction has one too.
498 */
499 foreach(lc, r->functions)
500 {
501 List *pair = (List *) lfirst(lc);
502 Node *fexpr;
503 List *coldeflist;
504 Node *newfexpr;
505 Node *last_srf;
506
507 /* Disassemble the function-call/column-def-list pairs */
508 Assert(list_length(pair) == 2);
509 fexpr = (Node *) linitial(pair);
510 coldeflist = (List *) lsecond(pair);
511
512 /*
513 * If we find a function call unnest() with more than one argument and
514 * no special decoration, transform it into separate unnest() calls on
515 * each argument. This is a kluge, for sure, but it's less nasty than
516 * other ways of implementing the SQL-standard UNNEST() syntax.
517 *
518 * If there is any decoration (including a coldeflist), we don't
519 * transform, which probably means a no-such-function error later. We
520 * could alternatively throw an error right now, but that doesn't seem
521 * tremendously helpful. If someone is using any such decoration,
522 * then they're not using the SQL-standard syntax, and they're more
523 * likely expecting an un-tweaked function call.
524 *
525 * Note: the transformation changes a non-schema-qualified unnest()
526 * function name into schema-qualified pg_catalog.unnest(). This
527 * choice is also a bit debatable, but it seems reasonable to force
528 * use of built-in unnest() when we make this transformation.
529 */
530 if (IsA(fexpr, FuncCall))
531 {
532 FuncCall *fc = (FuncCall *) fexpr;
533
534 if (list_length(fc->funcname) == 1 &&
535 strcmp(strVal(linitial(fc->funcname)), "unnest") == 0 &&
536 list_length(fc->args) > 1 &&
537 fc->agg_order == NIL &&
538 fc->agg_filter == NULL &&
539 fc->over == NULL &&
540 !fc->agg_star &&
541 !fc->agg_distinct &&
542 !fc->func_variadic &&
543 coldeflist == NIL)
544 {
545 ListCell *lc2;
546
547 foreach(lc2, fc->args)
548 {
549 Node *arg = (Node *) lfirst(lc2);
550 FuncCall *newfc;
551
552 last_srf = pstate->p_last_srf;
553
554 newfc = makeFuncCall(SystemFuncName("unnest"),
557 fc->location);
558
559 newfexpr = transformExpr(pstate, (Node *) newfc,
561
562 /* nodeFunctionscan.c requires SRFs to be at top level */
563 if (pstate->p_last_srf != last_srf &&
564 pstate->p_last_srf != newfexpr)
566 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
567 errmsg("set-returning functions must appear at top level of FROM"),
568 parser_errposition(pstate,
569 exprLocation(pstate->p_last_srf))));
570
571 funcexprs = lappend(funcexprs, newfexpr);
572
573 funcnames = lappend(funcnames,
574 FigureColname((Node *) newfc));
575
576 /* coldeflist is empty, so no error is possible */
577
578 coldeflists = lappend(coldeflists, coldeflist);
579 }
580 continue; /* done with this function item */
581 }
582 }
583
584 /* normal case ... */
585 last_srf = pstate->p_last_srf;
586
587 newfexpr = transformExpr(pstate, fexpr,
589
590 /* nodeFunctionscan.c requires SRFs to be at top level */
591 if (pstate->p_last_srf != last_srf &&
592 pstate->p_last_srf != newfexpr)
594 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
595 errmsg("set-returning functions must appear at top level of FROM"),
596 parser_errposition(pstate,
597 exprLocation(pstate->p_last_srf))));
598
599 funcexprs = lappend(funcexprs, newfexpr);
600
601 funcnames = lappend(funcnames,
602 FigureColname(fexpr));
603
604 if (coldeflist && r->coldeflist)
606 (errcode(ERRCODE_SYNTAX_ERROR),
607 errmsg("multiple column definition lists are not allowed for the same function"),
608 parser_errposition(pstate,
609 exprLocation((Node *) r->coldeflist))));
610
611 coldeflists = lappend(coldeflists, coldeflist);
612 }
613
614 pstate->p_lateral_active = false;
615
616 /*
617 * We must assign collations now so that the RTE exposes correct collation
618 * info for Vars created from it.
619 */
620 assign_list_collations(pstate, funcexprs);
621
622 /*
623 * Install the top-level coldeflist if there was one (we already checked
624 * that there was no conflicting per-function coldeflist).
625 *
626 * We only allow this when there's a single function (even after UNNEST
627 * expansion) and no WITH ORDINALITY. The reason for the latter
628 * restriction is that it's not real clear whether the ordinality column
629 * should be in the coldeflist, and users are too likely to make mistakes
630 * in one direction or the other. Putting the coldeflist inside ROWS
631 * FROM() is much clearer in this case.
632 */
633 if (r->coldeflist)
634 {
635 if (list_length(funcexprs) != 1)
636 {
637 if (r->is_rowsfrom)
639 (errcode(ERRCODE_SYNTAX_ERROR),
640 errmsg("ROWS FROM() with multiple functions cannot have a column definition list"),
641 errhint("Put a separate column definition list for each function inside ROWS FROM()."),
642 parser_errposition(pstate,
643 exprLocation((Node *) r->coldeflist))));
644 else
646 (errcode(ERRCODE_SYNTAX_ERROR),
647 errmsg("UNNEST() with multiple arguments cannot have a column definition list"),
648 errhint("Use separate UNNEST() calls inside ROWS FROM(), and attach a column definition list to each one."),
649 parser_errposition(pstate,
650 exprLocation((Node *) r->coldeflist))));
651 }
652 if (r->ordinality)
654 (errcode(ERRCODE_SYNTAX_ERROR),
655 errmsg("WITH ORDINALITY cannot be used with a column definition list"),
656 errhint("Put the column definition list inside ROWS FROM()."),
657 parser_errposition(pstate,
658 exprLocation((Node *) r->coldeflist))));
659
660 coldeflists = list_make1(r->coldeflist);
661 }
662
663 /*
664 * Mark the RTE as LATERAL if the user said LATERAL explicitly, or if
665 * there are any lateral cross-references in it.
666 */
667 is_lateral = r->lateral || contain_vars_of_level((Node *) funcexprs, 0);
668
669 /*
670 * OK, build an RTE and nsitem for the function.
671 */
672 return addRangeTableEntryForFunction(pstate,
673 funcnames, funcexprs, coldeflists,
674 r, is_lateral, true);
675}
FuncCall * makeFuncCall(List *name, List *args, CoercionForm funcformat, int location)
Definition: makefuncs.c:629
void assign_list_collations(ParseState *pstate, List *exprs)
@ EXPR_KIND_FROM_FUNCTION
Definition: parse_node.h:45
ParseNamespaceItem * addRangeTableEntryForFunction(ParseState *pstate, List *funcnames, List *funcexprs, List *coldeflists, RangeFunction *rangefunc, bool lateral, bool inFromCl)
char * FigureColname(Node *node)
List * SystemFuncName(char *name)
void * arg
#define lsecond(l)
Definition: pg_list.h:183
static int fc(const char *x)
Definition: preproc-init.c:99
@ COERCE_EXPLICIT_CALL
Definition: primnodes.h:750
Node * p_last_srf
Definition: parse_node.h:248
bool p_lateral_active
Definition: parse_node.h:221
bool is_rowsfrom
Definition: parsenodes.h:653
List * coldeflist
Definition: parsenodes.h:656
List * functions
Definition: parsenodes.h:654

References addRangeTableEntryForFunction(), arg, Assert, assign_list_collations(), COERCE_EXPLICIT_CALL, RangeFunction::coldeflist, contain_vars_of_level(), ereport, errcode(), errhint(), errmsg(), ERROR, EXPR_KIND_FROM_FUNCTION, exprLocation(), fc(), FigureColname(), RangeFunction::functions, RangeFunction::is_rowsfrom, IsA, lappend(), RangeFunction::lateral, lfirst, linitial, list_length(), list_make1, lsecond, makeFuncCall(), NIL, RangeFunction::ordinality, ParseState::p_last_srf, ParseState::p_lateral_active, parser_errposition(), strVal, SystemFuncName(), and transformExpr().

Referenced by transformFromClauseItem().

◆ transformRangeSubselect()

static ParseNamespaceItem * transformRangeSubselect ( ParseState pstate,
RangeSubselect r 
)
static

Definition at line 405 of file parse_clause.c.

406{
407 Query *query;
408
409 /*
410 * Set p_expr_kind to show this parse level is recursing to a subselect.
411 * We can't be nested within any expression, so don't need save-restore
412 * logic here.
413 */
416
417 /*
418 * If the subselect is LATERAL, make lateral_only names of this level
419 * visible to it. (LATERAL can't nest within a single pstate level, so we
420 * don't need save/restore logic here.)
421 */
422 Assert(!pstate->p_lateral_active);
423 pstate->p_lateral_active = r->lateral;
424
425 /*
426 * Analyze and transform the subquery. Note that if the subquery doesn't
427 * have an alias, it can't be explicitly selected for locking, but locking
428 * might still be required (if there is an all-tables locking clause).
429 */
430 query = parse_sub_analyze(r->subquery, pstate, NULL,
431 isLockedRefname(pstate,
432 r->alias == NULL ? NULL :
433 r->alias->aliasname),
434 true);
435
436 /* Restore state */
437 pstate->p_lateral_active = false;
438 pstate->p_expr_kind = EXPR_KIND_NONE;
439
440 /*
441 * Check that we got a SELECT. Anything else should be impossible given
442 * restrictions of the grammar, but check anyway.
443 */
444 if (!IsA(query, Query) ||
445 query->commandType != CMD_SELECT)
446 elog(ERROR, "unexpected non-SELECT command in subquery in FROM");
447
448 /*
449 * OK, build an RTE and nsitem for the subquery.
450 */
451 return addRangeTableEntryForSubquery(pstate,
452 query,
453 r->alias,
454 r->lateral,
455 true);
456}
@ CMD_SELECT
Definition: nodes.h:265
@ EXPR_KIND_FROM_SUBSELECT
Definition: parse_node.h:44
@ EXPR_KIND_NONE
Definition: parse_node.h:40
bool isLockedRefname(ParseState *pstate, const char *refname)
ParseNamespaceItem * addRangeTableEntryForSubquery(ParseState *pstate, Query *subquery, Alias *alias, bool lateral, bool inFromCl)
Query * parse_sub_analyze(Node *parseTree, ParseState *parentParseState, CommonTableExpr *parentCTE, bool locked_from_parent, bool resolve_unknowns)
Definition: analyze.c:222
char * aliasname
Definition: primnodes.h:50
ParseExprKind p_expr_kind
Definition: parse_node.h:230
CmdType commandType
Definition: parsenodes.h:121
Node * subquery
Definition: parsenodes.h:630
Alias * alias
Definition: parsenodes.h:631

References addRangeTableEntryForSubquery(), RangeSubselect::alias, Alias::aliasname, Assert, CMD_SELECT, Query::commandType, elog, ERROR, EXPR_KIND_FROM_SUBSELECT, EXPR_KIND_NONE, IsA, isLockedRefname(), RangeSubselect::lateral, ParseState::p_expr_kind, ParseState::p_lateral_active, parse_sub_analyze(), and RangeSubselect::subquery.

Referenced by transformFromClauseItem().

◆ transformRangeTableFunc()

static ParseNamespaceItem * transformRangeTableFunc ( ParseState pstate,
RangeTableFunc rtf 
)
static

Definition at line 686 of file parse_clause.c.

687{
689 const char *constructName;
690 Oid docType;
691 bool is_lateral;
692 ListCell *col;
693 char **names;
694 int colno;
695
696 /*
697 * Currently we only support XMLTABLE here. See transformJsonTable() for
698 * JSON_TABLE support.
699 */
701 constructName = "XMLTABLE";
702 docType = XMLOID;
703
704 /*
705 * We make lateral_only names of this level visible, whether or not the
706 * RangeTableFunc is explicitly marked LATERAL. This is needed for SQL
707 * spec compliance and seems useful on convenience grounds for all
708 * functions in FROM.
709 *
710 * (LATERAL can't nest within a single pstate level, so we don't need
711 * save/restore logic here.)
712 */
713 Assert(!pstate->p_lateral_active);
714 pstate->p_lateral_active = true;
715
716 /* Transform and apply typecast to the row-generating expression ... */
717 Assert(rtf->rowexpr != NULL);
718 tf->rowexpr = coerce_to_specific_type(pstate,
720 TEXTOID,
721 constructName);
722 assign_expr_collations(pstate, tf->rowexpr);
723
724 /* ... and to the document itself */
725 Assert(rtf->docexpr != NULL);
726 tf->docexpr = coerce_to_specific_type(pstate,
728 docType,
729 constructName);
730 assign_expr_collations(pstate, tf->docexpr);
731
732 /* undef ordinality column number */
733 tf->ordinalitycol = -1;
734
735 /* Process column specs */
736 names = palloc(sizeof(char *) * list_length(rtf->columns));
737
738 colno = 0;
739 foreach(col, rtf->columns)
740 {
742 Oid typid;
743 int32 typmod;
744 Node *colexpr;
745 Node *coldefexpr;
746 int j;
747
748 tf->colnames = lappend(tf->colnames,
749 makeString(pstrdup(rawc->colname)));
750
751 /*
752 * Determine the type and typmod for the new column. FOR ORDINALITY
753 * columns are INTEGER per spec; the others are user-specified.
754 */
755 if (rawc->for_ordinality)
756 {
757 if (tf->ordinalitycol != -1)
759 (errcode(ERRCODE_SYNTAX_ERROR),
760 errmsg("only one FOR ORDINALITY column is allowed"),
761 parser_errposition(pstate, rawc->location)));
762
763 typid = INT4OID;
764 typmod = -1;
765 tf->ordinalitycol = colno;
766 }
767 else
768 {
769 if (rawc->typeName->setof)
771 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
772 errmsg("column \"%s\" cannot be declared SETOF",
773 rawc->colname),
774 parser_errposition(pstate, rawc->location)));
775
776 typenameTypeIdAndMod(pstate, rawc->typeName,
777 &typid, &typmod);
778 }
779
780 tf->coltypes = lappend_oid(tf->coltypes, typid);
781 tf->coltypmods = lappend_int(tf->coltypmods, typmod);
782 tf->colcollations = lappend_oid(tf->colcollations,
783 get_typcollation(typid));
784
785 /* Transform the PATH and DEFAULT expressions */
786 if (rawc->colexpr)
787 {
788 colexpr = coerce_to_specific_type(pstate,
789 transformExpr(pstate, rawc->colexpr,
791 TEXTOID,
792 constructName);
793 assign_expr_collations(pstate, colexpr);
794 }
795 else
796 colexpr = NULL;
797
798 if (rawc->coldefexpr)
799 {
800 coldefexpr = coerce_to_specific_type_typmod(pstate,
801 transformExpr(pstate, rawc->coldefexpr,
803 typid, typmod,
804 constructName);
805 assign_expr_collations(pstate, coldefexpr);
806 }
807 else
808 coldefexpr = NULL;
809
810 tf->colexprs = lappend(tf->colexprs, colexpr);
811 tf->coldefexprs = lappend(tf->coldefexprs, coldefexpr);
812
813 if (rawc->is_not_null)
814 tf->notnulls = bms_add_member(tf->notnulls, colno);
815
816 /* make sure column names are unique */
817 for (j = 0; j < colno; j++)
818 if (strcmp(names[j], rawc->colname) == 0)
820 (errcode(ERRCODE_SYNTAX_ERROR),
821 errmsg("column name \"%s\" is not unique",
822 rawc->colname),
823 parser_errposition(pstate, rawc->location)));
824 names[colno] = rawc->colname;
825
826 colno++;
827 }
828 pfree(names);
829
830 /* Namespaces, if any, also need to be transformed */
831 if (rtf->namespaces != NIL)
832 {
833 ListCell *ns;
834 ListCell *lc2;
835 List *ns_uris = NIL;
836 List *ns_names = NIL;
837 bool default_ns_seen = false;
838
839 foreach(ns, rtf->namespaces)
840 {
841 ResTarget *r = (ResTarget *) lfirst(ns);
842 Node *ns_uri;
843
844 Assert(IsA(r, ResTarget));
845 ns_uri = transformExpr(pstate, r->val, EXPR_KIND_FROM_FUNCTION);
846 ns_uri = coerce_to_specific_type(pstate, ns_uri,
847 TEXTOID, constructName);
848 assign_expr_collations(pstate, ns_uri);
849 ns_uris = lappend(ns_uris, ns_uri);
850
851 /* Verify consistency of name list: no dupes, only one DEFAULT */
852 if (r->name != NULL)
853 {
854 foreach(lc2, ns_names)
855 {
856 String *ns_node = lfirst_node(String, lc2);
857
858 if (ns_node == NULL)
859 continue;
860 if (strcmp(strVal(ns_node), r->name) == 0)
862 (errcode(ERRCODE_SYNTAX_ERROR),
863 errmsg("namespace name \"%s\" is not unique",
864 r->name),
865 parser_errposition(pstate, r->location)));
866 }
867 }
868 else
869 {
870 if (default_ns_seen)
872 (errcode(ERRCODE_SYNTAX_ERROR),
873 errmsg("only one default namespace is allowed"),
874 parser_errposition(pstate, r->location)));
875 default_ns_seen = true;
876 }
877
878 /* We represent DEFAULT by a null pointer */
879 ns_names = lappend(ns_names,
880 r->name ? makeString(r->name) : NULL);
881 }
882
883 tf->ns_uris = ns_uris;
884 tf->ns_names = ns_names;
885 }
886
887 tf->location = rtf->location;
888
889 pstate->p_lateral_active = false;
890
891 /*
892 * Mark the RTE as LATERAL if the user said LATERAL explicitly, or if
893 * there are any lateral cross-references in it.
894 */
895 is_lateral = rtf->lateral || contain_vars_of_level((Node *) tf, 0);
896
897 return addRangeTableEntryForTableFunc(pstate,
898 tf, rtf->alias, is_lateral, true);
899}
List * lappend_oid(List *list, Oid datum)
Definition: list.c:375
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:3056
char * pstrdup(const char *in)
Definition: mcxt.c:1696
void pfree(void *pointer)
Definition: mcxt.c:1521
Node * coerce_to_specific_type_typmod(ParseState *pstate, Node *node, Oid targetTypeId, int32 targetTypmod, const char *constructName)
ParseNamespaceItem * addRangeTableEntryForTableFunc(ParseState *pstate, TableFunc *tf, Alias *alias, bool lateral, bool inFromCl)
void typenameTypeIdAndMod(ParseState *pstate, const TypeName *typeName, Oid *typeid_p, int32 *typmod_p)
Definition: parse_type.c:310
#define lfirst_node(type, lc)
Definition: pg_list.h:176
@ TFT_XMLTABLE
Definition: primnodes.h:99
ParseLoc location
Definition: parsenodes.h:693
TypeName * typeName
Definition: parsenodes.h:688
List * namespaces
Definition: parsenodes.h:672
Node * docexpr
Definition: parsenodes.h:670
ParseLoc location
Definition: parsenodes.h:675
Node * rowexpr
Definition: parsenodes.h:671
List * columns
Definition: parsenodes.h:673
Alias * alias
Definition: parsenodes.h:674
Node * val
Definition: parsenodes.h:530
ParseLoc location
Definition: parsenodes.h:531
char * name
Definition: parsenodes.h:528
ParseLoc location
Definition: primnodes.h:145
Node * docexpr
Definition: primnodes.h:119
Node * rowexpr
Definition: primnodes.h:121
List * colexprs
Definition: primnodes.h:131
TableFuncType functype
Definition: primnodes.h:113
bool setof
Definition: parsenodes.h:281

References addRangeTableEntryForTableFunc(), RangeTableFunc::alias, Assert, assign_expr_collations(), bms_add_member(), coerce_to_specific_type(), coerce_to_specific_type_typmod(), RangeTableFuncCol::coldefexpr, RangeTableFuncCol::colexpr, TableFunc::colexprs, RangeTableFuncCol::colname, RangeTableFunc::columns, contain_vars_of_level(), RangeTableFunc::docexpr, TableFunc::docexpr, ereport, errcode(), errmsg(), ERROR, EXPR_KIND_FROM_FUNCTION, RangeTableFuncCol::for_ordinality, TableFunc::functype, get_typcollation(), RangeTableFuncCol::is_not_null, IsA, j, lappend(), lappend_int(), lappend_oid(), RangeTableFunc::lateral, lfirst, lfirst_node, list_length(), ResTarget::location, RangeTableFunc::location, RangeTableFuncCol::location, TableFunc::location, makeNode, makeString(), ResTarget::name, RangeTableFunc::namespaces, NIL, ParseState::p_lateral_active, palloc(), parser_errposition(), pfree(), pstrdup(), RangeTableFunc::rowexpr, TableFunc::rowexpr, TypeName::setof, strVal, TFT_XMLTABLE, transformExpr(), RangeTableFuncCol::typeName, typenameTypeIdAndMod(), and ResTarget::val.

Referenced by transformFromClauseItem().

◆ transformRangeTableSample()

static TableSampleClause * transformRangeTableSample ( ParseState pstate,
RangeTableSample rts 
)
static

Definition at line 908 of file parse_clause.c.

909{
910 TableSampleClause *tablesample;
911 Oid handlerOid;
912 Oid funcargtypes[1];
913 TsmRoutine *tsm;
914 List *fargs;
915 ListCell *larg,
916 *ltyp;
917
918 /*
919 * To validate the sample method name, look up the handler function, which
920 * has the same name, one dummy INTERNAL argument, and a result type of
921 * tsm_handler. (Note: tablesample method names are not schema-qualified
922 * in the SQL standard; but since they are just functions to us, we allow
923 * schema qualification to resolve any potential ambiguity.)
924 */
925 funcargtypes[0] = INTERNALOID;
926
927 handlerOid = LookupFuncName(rts->method, 1, funcargtypes, true);
928
929 /* we want error to complain about no-such-method, not no-such-function */
930 if (!OidIsValid(handlerOid))
932 (errcode(ERRCODE_UNDEFINED_OBJECT),
933 errmsg("tablesample method %s does not exist",
935 parser_errposition(pstate, rts->location)));
936
937 /* check that handler has correct return type */
938 if (get_func_rettype(handlerOid) != TSM_HANDLEROID)
940 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
941 errmsg("function %s must return type %s",
942 NameListToString(rts->method), "tsm_handler"),
943 parser_errposition(pstate, rts->location)));
944
945 /* OK, run the handler to get TsmRoutine, for argument type info */
946 tsm = GetTsmRoutine(handlerOid);
947
948 tablesample = makeNode(TableSampleClause);
949 tablesample->tsmhandler = handlerOid;
950
951 /* check user provided the expected number of arguments */
952 if (list_length(rts->args) != list_length(tsm->parameterTypes))
954 (errcode(ERRCODE_INVALID_TABLESAMPLE_ARGUMENT),
955 errmsg_plural("tablesample method %s requires %d argument, not %d",
956 "tablesample method %s requires %d arguments, not %d",
960 list_length(rts->args)),
961 parser_errposition(pstate, rts->location)));
962
963 /*
964 * Transform the arguments, typecasting them as needed. Note we must also
965 * assign collations now, because assign_query_collations() doesn't
966 * examine any substructure of RTEs.
967 */
968 fargs = NIL;
969 forboth(larg, rts->args, ltyp, tsm->parameterTypes)
970 {
971 Node *arg = (Node *) lfirst(larg);
972 Oid argtype = lfirst_oid(ltyp);
973
975 arg = coerce_to_specific_type(pstate, arg, argtype, "TABLESAMPLE");
977 fargs = lappend(fargs, arg);
978 }
979 tablesample->args = fargs;
980
981 /* Process REPEATABLE (seed) */
982 if (rts->repeatable != NULL)
983 {
984 Node *arg;
985
988 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
989 errmsg("tablesample method %s does not support REPEATABLE",
991 parser_errposition(pstate, rts->location)));
992
994 arg = coerce_to_specific_type(pstate, arg, FLOAT8OID, "REPEATABLE");
996 tablesample->repeatable = (Expr *) arg;
997 }
998 else
999 tablesample->repeatable = NULL;
1000
1001 return tablesample;
1002}
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1180
Oid get_func_rettype(Oid funcid)
Definition: lsyscache.c:1655
char * NameListToString(const List *names)
Definition: namespace.c:3594
Oid LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool missing_ok)
Definition: parse_func.c:2144
#define lfirst_oid(lc)
Definition: pg_list.h:174
ParseLoc location
Definition: parsenodes.h:713
List * parameterTypes
Definition: tsmapi.h:61
bool repeatable_across_queries
Definition: tsmapi.h:64
TsmRoutine * GetTsmRoutine(Oid tsmhandler)
Definition: tablesample.c:27

References arg, RangeTableSample::args, TableSampleClause::args, assign_expr_collations(), coerce_to_specific_type(), ereport, errcode(), errmsg(), errmsg_plural(), ERROR, EXPR_KIND_FROM_FUNCTION, forboth, get_func_rettype(), GetTsmRoutine(), lappend(), lfirst, lfirst_oid, list_length(), RangeTableSample::location, LookupFuncName(), makeNode, RangeTableSample::method, NameListToString(), NIL, OidIsValid, TsmRoutine::parameterTypes, parser_errposition(), RangeTableSample::repeatable, TableSampleClause::repeatable, TsmRoutine::repeatable_across_queries, transformExpr(), and TableSampleClause::tsmhandler.

Referenced by transformFromClauseItem().

◆ transformSortClause()

List * transformSortClause ( ParseState pstate,
List orderlist,
List **  targetlist,
ParseExprKind  exprKind,
bool  useSQL99 
)

Definition at line 2732 of file parse_clause.c.

2737{
2738 List *sortlist = NIL;
2739 ListCell *olitem;
2740
2741 foreach(olitem, orderlist)
2742 {
2743 SortBy *sortby = (SortBy *) lfirst(olitem);
2744 TargetEntry *tle;
2745
2746 if (useSQL99)
2747 tle = findTargetlistEntrySQL99(pstate, sortby->node,
2748 targetlist, exprKind);
2749 else
2750 tle = findTargetlistEntrySQL92(pstate, sortby->node,
2751 targetlist, exprKind);
2752
2753 sortlist = addTargetToSortList(pstate, tle,
2754 sortlist, *targetlist, sortby);
2755 }
2756
2757 return sortlist;
2758}
List * addTargetToSortList(ParseState *pstate, TargetEntry *tle, List *sortlist, List *targetlist, SortBy *sortby)

References addTargetToSortList(), findTargetlistEntrySQL92(), findTargetlistEntrySQL99(), lfirst, NIL, and SortBy::node.

Referenced by transformAggregateCall(), transformPLAssignStmt(), transformSelectStmt(), transformSetOperationStmt(), transformValuesClause(), and transformWindowDefinitions().

◆ transformTableEntry()

static ParseNamespaceItem * transformTableEntry ( ParseState pstate,
RangeVar r 
)
static

Definition at line 395 of file parse_clause.c.

396{
397 /* addRangeTableEntry does all the work */
398 return addRangeTableEntry(pstate, r, r->alias, r->inh, true);
399}
ParseNamespaceItem * addRangeTableEntry(ParseState *pstate, RangeVar *relation, Alias *alias, bool inh, bool inFromCl)
bool inh
Definition: primnodes.h:85

References addRangeTableEntry(), RangeVar::alias, and RangeVar::inh.

Referenced by transformFromClauseItem().

◆ transformWhereClause()

Node * transformWhereClause ( ParseState pstate,
Node clause,
ParseExprKind  exprKind,
const char *  constructName 
)

◆ transformWindowDefinitions()

List * transformWindowDefinitions ( ParseState pstate,
List windowdefs,
List **  targetlist 
)

Definition at line 2765 of file parse_clause.c.

2768{
2769 List *result = NIL;
2770 Index winref = 0;
2771 ListCell *lc;
2772
2773 foreach(lc, windowdefs)
2774 {
2775 WindowDef *windef = (WindowDef *) lfirst(lc);
2776 WindowClause *refwc = NULL;
2777 List *partitionClause;
2778 List *orderClause;
2779 Oid rangeopfamily = InvalidOid;
2780 Oid rangeopcintype = InvalidOid;
2781 WindowClause *wc;
2782
2783 winref++;
2784
2785 /*
2786 * Check for duplicate window names.
2787 */
2788 if (windef->name &&
2789 findWindowClause(result, windef->name) != NULL)
2790 ereport(ERROR,
2791 (errcode(ERRCODE_WINDOWING_ERROR),
2792 errmsg("window \"%s\" is already defined", windef->name),
2793 parser_errposition(pstate, windef->location)));
2794
2795 /*
2796 * If it references a previous window, look that up.
2797 */
2798 if (windef->refname)
2799 {
2800 refwc = findWindowClause(result, windef->refname);
2801 if (refwc == NULL)
2802 ereport(ERROR,
2803 (errcode(ERRCODE_UNDEFINED_OBJECT),
2804 errmsg("window \"%s\" does not exist",
2805 windef->refname),
2806 parser_errposition(pstate, windef->location)));
2807 }
2808
2809 /*
2810 * Transform PARTITION and ORDER specs, if any. These are treated
2811 * almost exactly like top-level GROUP BY and ORDER BY clauses,
2812 * including the special handling of nondefault operator semantics.
2813 */
2814 orderClause = transformSortClause(pstate,
2815 windef->orderClause,
2816 targetlist,
2818 true /* force SQL99 rules */ );
2819 partitionClause = transformGroupClause(pstate,
2820 windef->partitionClause,
2821 NULL,
2822 targetlist,
2823 orderClause,
2825 true /* force SQL99 rules */ );
2826
2827 /*
2828 * And prepare the new WindowClause.
2829 */
2830 wc = makeNode(WindowClause);
2831 wc->name = windef->name;
2832 wc->refname = windef->refname;
2833
2834 /*
2835 * Per spec, a windowdef that references a previous one copies the
2836 * previous partition clause (and mustn't specify its own). It can
2837 * specify its own ordering clause, but only if the previous one had
2838 * none. It always specifies its own frame clause, and the previous
2839 * one must not have a frame clause. Yeah, it's bizarre that each of
2840 * these cases works differently, but SQL:2008 says so; see 7.11
2841 * <window clause> syntax rule 10 and general rule 1. The frame
2842 * clause rule is especially bizarre because it makes "OVER foo"
2843 * different from "OVER (foo)", and requires the latter to throw an
2844 * error if foo has a nondefault frame clause. Well, ours not to
2845 * reason why, but we do go out of our way to throw a useful error
2846 * message for such cases.
2847 */
2848 if (refwc)
2849 {
2850 if (partitionClause)
2851 ereport(ERROR,
2852 (errcode(ERRCODE_WINDOWING_ERROR),
2853 errmsg("cannot override PARTITION BY clause of window \"%s\"",
2854 windef->refname),
2855 parser_errposition(pstate, windef->location)));
2857 }
2858 else
2859 wc->partitionClause = partitionClause;
2860 if (refwc)
2861 {
2862 if (orderClause && refwc->orderClause)
2863 ereport(ERROR,
2864 (errcode(ERRCODE_WINDOWING_ERROR),
2865 errmsg("cannot override ORDER BY clause of window \"%s\"",
2866 windef->refname),
2867 parser_errposition(pstate, windef->location)));
2868 if (orderClause)
2869 {
2870 wc->orderClause = orderClause;
2871 wc->copiedOrder = false;
2872 }
2873 else
2874 {
2875 wc->orderClause = copyObject(refwc->orderClause);
2876 wc->copiedOrder = true;
2877 }
2878 }
2879 else
2880 {
2881 wc->orderClause = orderClause;
2882 wc->copiedOrder = false;
2883 }
2884 if (refwc && refwc->frameOptions != FRAMEOPTION_DEFAULTS)
2885 {
2886 /*
2887 * Use this message if this is a WINDOW clause, or if it's an OVER
2888 * clause that includes ORDER BY or framing clauses. (We already
2889 * rejected PARTITION BY above, so no need to check that.)
2890 */
2891 if (windef->name ||
2892 orderClause || windef->frameOptions != FRAMEOPTION_DEFAULTS)
2893 ereport(ERROR,
2894 (errcode(ERRCODE_WINDOWING_ERROR),
2895 errmsg("cannot copy window \"%s\" because it has a frame clause",
2896 windef->refname),
2897 parser_errposition(pstate, windef->location)));
2898 /* Else this clause is just OVER (foo), so say this: */
2899 ereport(ERROR,
2900 (errcode(ERRCODE_WINDOWING_ERROR),
2901 errmsg("cannot copy window \"%s\" because it has a frame clause",
2902 windef->refname),
2903 errhint("Omit the parentheses in this OVER clause."),
2904 parser_errposition(pstate, windef->location)));
2905 }
2906 wc->frameOptions = windef->frameOptions;
2907
2908 /*
2909 * RANGE offset PRECEDING/FOLLOWING requires exactly one ORDER BY
2910 * column; check that and get its sort opfamily info.
2911 */
2912 if ((wc->frameOptions & FRAMEOPTION_RANGE) &&
2915 {
2916 SortGroupClause *sortcl;
2917 Node *sortkey;
2918 int16 rangestrategy;
2919
2920 if (list_length(wc->orderClause) != 1)
2921 ereport(ERROR,
2922 (errcode(ERRCODE_WINDOWING_ERROR),
2923 errmsg("RANGE with offset PRECEDING/FOLLOWING requires exactly one ORDER BY column"),
2924 parser_errposition(pstate, windef->location)));
2926 sortkey = get_sortgroupclause_expr(sortcl, *targetlist);
2927 /* Find the sort operator in pg_amop */
2929 &rangeopfamily,
2930 &rangeopcintype,
2931 &rangestrategy))
2932 elog(ERROR, "operator %u is not a valid ordering operator",
2933 sortcl->sortop);
2934 /* Record properties of sort ordering */
2935 wc->inRangeColl = exprCollation(sortkey);
2936 wc->inRangeAsc = !sortcl->reverse_sort;
2937 wc->inRangeNullsFirst = sortcl->nulls_first;
2938 }
2939
2940 /* Per spec, GROUPS mode requires an ORDER BY clause */
2942 {
2943 if (wc->orderClause == NIL)
2944 ereport(ERROR,
2945 (errcode(ERRCODE_WINDOWING_ERROR),
2946 errmsg("GROUPS mode requires an ORDER BY clause"),
2947 parser_errposition(pstate, windef->location)));
2948 }
2949
2950 /* Process frame offset expressions */
2952 rangeopfamily, rangeopcintype,
2953 &wc->startInRangeFunc,
2954 windef->startOffset);
2956 rangeopfamily, rangeopcintype,
2957 &wc->endInRangeFunc,
2958 windef->endOffset);
2959 wc->winref = winref;
2960
2961 result = lappend(result, wc);
2962 }
2963
2964 return result;
2965}
int16_t int16
Definition: c.h:483
bool get_ordering_op_properties(Oid opno, Oid *opfamily, Oid *opcintype, int16 *strategy)
Definition: lsyscache.c:207
List * transformGroupClause(ParseState *pstate, List *grouplist, List **groupingSets, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99)
List * transformSortClause(ParseState *pstate, List *orderlist, List **targetlist, ParseExprKind exprKind, bool useSQL99)
static Node * transformFrameOffset(ParseState *pstate, int frameOptions, Oid rangeopfamily, Oid rangeopcintype, Oid *inRangeFunc, Node *clause)
static WindowClause * findWindowClause(List *wclist, const char *name)
@ EXPR_KIND_WINDOW_PARTITION
Definition: parse_node.h:49
@ EXPR_KIND_WINDOW_ORDER
Definition: parse_node.h:50
#define FRAMEOPTION_END_OFFSET
Definition: parsenodes.h:613
#define FRAMEOPTION_START_OFFSET
Definition: parsenodes.h:611
#define FRAMEOPTION_DEFAULTS
Definition: parsenodes.h:619
#define linitial_node(type, l)
Definition: pg_list.h:181
Node * startOffset
Definition: parsenodes.h:1556
List * partitionClause
Definition: parsenodes.h:1552
Node * endOffset
Definition: parsenodes.h:1557
List * orderClause
Definition: parsenodes.h:1554
List * orderClause
Definition: parsenodes.h:578
ParseLoc location
Definition: parsenodes.h:582
List * partitionClause
Definition: parsenodes.h:577
Node * startOffset
Definition: parsenodes.h:580
char * refname
Definition: parsenodes.h:576
Node * endOffset
Definition: parsenodes.h:581
int frameOptions
Definition: parsenodes.h:579
char * name
Definition: parsenodes.h:575
Node * get_sortgroupclause_expr(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:379

References copyObject, elog, WindowDef::endOffset, WindowClause::endOffset, ereport, errcode(), errhint(), errmsg(), ERROR, EXPR_KIND_WINDOW_ORDER, EXPR_KIND_WINDOW_PARTITION, exprCollation(), findWindowClause(), FRAMEOPTION_DEFAULTS, FRAMEOPTION_END_OFFSET, FRAMEOPTION_GROUPS, FRAMEOPTION_RANGE, FRAMEOPTION_START_OFFSET, WindowDef::frameOptions, WindowClause::frameOptions, get_ordering_op_properties(), get_sortgroupclause_expr(), InvalidOid, lappend(), lfirst, linitial_node, list_length(), WindowDef::location, makeNode, WindowDef::name, NIL, SortGroupClause::nulls_first, WindowDef::orderClause, WindowClause::orderClause, parser_errposition(), WindowDef::partitionClause, WindowClause::partitionClause, WindowDef::refname, SortGroupClause::reverse_sort, SortGroupClause::sortop, WindowDef::startOffset, WindowClause::startOffset, transformFrameOffset(), transformGroupClause(), transformSortClause(), and WindowClause::winref.

Referenced by transformPLAssignStmt(), and transformSelectStmt().