PostgreSQL Source Code  git master
parse_clause.h File Reference
Include dependency graph for parse_clause.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

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)
 
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)
 
ParseNamespaceItemtransformJsonTable (ParseState *pstate, JsonTable *jt)
 

Function Documentation

◆ addTargetToSortList()

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

Definition at line 3268 of file parse_clause.c.

3270 {
3271  Oid restype = exprType((Node *) tle->expr);
3272  Oid sortop;
3273  Oid eqop;
3274  bool hashable;
3275  bool reverse;
3276  int location;
3277  ParseCallbackState pcbstate;
3278 
3279  /* if tlist item is an UNKNOWN literal, change it to TEXT */
3280  if (restype == UNKNOWNOID)
3281  {
3282  tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3283  restype, TEXTOID, -1,
3286  -1);
3287  restype = TEXTOID;
3288  }
3289 
3290  /*
3291  * Rather than clutter the API of get_sort_group_operators and the other
3292  * functions we're about to use, make use of error context callback to
3293  * mark any error reports with a parse position. We point to the operator
3294  * location if present, else to the expression being sorted. (NB: use the
3295  * original untransformed expression here; the TLE entry might well point
3296  * at a duplicate expression in the regular SELECT list.)
3297  */
3298  location = sortby->location;
3299  if (location < 0)
3300  location = exprLocation(sortby->node);
3301  setup_parser_errposition_callback(&pcbstate, pstate, location);
3302 
3303  /* determine the sortop, eqop, and directionality */
3304  switch (sortby->sortby_dir)
3305  {
3306  case SORTBY_DEFAULT:
3307  case SORTBY_ASC:
3308  get_sort_group_operators(restype,
3309  true, true, false,
3310  &sortop, &eqop, NULL,
3311  &hashable);
3312  reverse = false;
3313  break;
3314  case SORTBY_DESC:
3315  get_sort_group_operators(restype,
3316  false, true, true,
3317  NULL, &eqop, &sortop,
3318  &hashable);
3319  reverse = true;
3320  break;
3321  case SORTBY_USING:
3322  Assert(sortby->useOp != NIL);
3323  sortop = compatible_oper_opid(sortby->useOp,
3324  restype,
3325  restype,
3326  false);
3327 
3328  /*
3329  * Verify it's a valid ordering operator, fetch the corresponding
3330  * equality operator, and determine whether to consider it like
3331  * ASC or DESC.
3332  */
3333  eqop = get_equality_op_for_ordering_op(sortop, &reverse);
3334  if (!OidIsValid(eqop))
3335  ereport(ERROR,
3336  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3337  errmsg("operator %s is not a valid ordering operator",
3338  strVal(llast(sortby->useOp))),
3339  errhint("Ordering operators must be \"<\" or \">\" members of btree operator families.")));
3340 
3341  /*
3342  * Also see if the equality operator is hashable.
3343  */
3344  hashable = op_hashjoinable(eqop, restype);
3345  break;
3346  default:
3347  elog(ERROR, "unrecognized sortby_dir: %d", sortby->sortby_dir);
3348  sortop = InvalidOid; /* keep compiler quiet */
3349  eqop = InvalidOid;
3350  hashable = false;
3351  reverse = false;
3352  break;
3353  }
3354 
3356 
3357  /* avoid making duplicate sortlist entries */
3358  if (!targetIsInSortList(tle, sortop, sortlist))
3359  {
3361 
3362  sortcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3363 
3364  sortcl->eqop = eqop;
3365  sortcl->sortop = sortop;
3366  sortcl->hashable = hashable;
3367 
3368  switch (sortby->sortby_nulls)
3369  {
3370  case SORTBY_NULLS_DEFAULT:
3371  /* NULLS FIRST is default for DESC; other way for ASC */
3372  sortcl->nulls_first = reverse;
3373  break;
3374  case SORTBY_NULLS_FIRST:
3375  sortcl->nulls_first = true;
3376  break;
3377  case SORTBY_NULLS_LAST:
3378  sortcl->nulls_first = false;
3379  break;
3380  default:
3381  elog(ERROR, "unrecognized sortby_nulls: %d",
3382  sortby->sortby_nulls);
3383  break;
3384  }
3385 
3386  sortlist = lappend(sortlist, sortcl);
3387  }
3388 
3389  return sortlist;
3390 }
#define OidIsValid(objectId)
Definition: c.h:710
int errhint(const char *fmt,...)
Definition: elog.c:1151
int errcode(int sqlerrcode)
Definition: elog.c:693
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define ERROR
Definition: elog.h:33
#define elog(elevel,...)
Definition: elog.h:218
#define ereport(elevel,...)
Definition: elog.h:143
Assert(fmt[strlen(fmt) - 1] !='\n')
List * lappend(List *list, void *datum)
Definition: list.c:336
Oid get_equality_op_for_ordering_op(Oid opno, bool *reverse)
Definition: lsyscache.c:265
bool op_hashjoinable(Oid opno, Oid inputtype)
Definition: lsyscache.c:1418
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1343
#define makeNode(_type_)
Definition: nodes.h:621
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:160
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:144
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:192
Oid compatible_oper_opid(List *op, Oid arg1, Oid arg2, bool noError)
Definition: parse_oper.c:499
@ SORTBY_NULLS_DEFAULT
Definition: parsenodes.h:60
@ SORTBY_NULLS_LAST
Definition: parsenodes.h:62
@ SORTBY_NULLS_FIRST
Definition: parsenodes.h:61
@ SORTBY_USING
Definition: parsenodes.h:55
@ SORTBY_DESC
Definition: parsenodes.h:54
@ SORTBY_ASC
Definition: parsenodes.h:53
@ SORTBY_DEFAULT
Definition: parsenodes.h:52
#define llast(l)
Definition: pg_list.h:194
#define NIL
Definition: pg_list.h:65
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
@ COERCE_IMPLICIT_CAST
Definition: primnodes.h:494
@ COERCION_IMPLICIT
Definition: primnodes.h:472
Definition: nodes.h:574
SortByNulls sortby_nulls
Definition: parsenodes.h:502
Node * node
Definition: parsenodes.h:500
List * useOp
Definition: parsenodes.h:503
SortByDir sortby_dir
Definition: parsenodes.h:501
int location
Definition: parsenodes.h:504
Index tleSortGroupRef
Definition: parsenodes.h:1305
Expr * expr
Definition: primnodes.h:1716
#define strVal(v)
Definition: value.h:72

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(), SortGroupClause::hashable, InvalidOid, lappend(), llast, SortBy::location, makeNode, NIL, SortBy::node, SortGroupClause::nulls_first, OidIsValid, op_hashjoinable(), 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 3466 of file parse_clause.c.

3467 {
3468  Index maxRef;
3469  ListCell *l;
3470 
3471  if (tle->ressortgroupref) /* already has one? */
3472  return tle->ressortgroupref;
3473 
3474  /* easiest way to pick an unused refnumber: max used + 1 */
3475  maxRef = 0;
3476  foreach(l, tlist)
3477  {
3478  Index ref = ((TargetEntry *) lfirst(l))->ressortgroupref;
3479 
3480  if (ref > maxRef)
3481  maxRef = ref;
3482  }
3483  tle->ressortgroupref = maxRef + 1;
3484  return tle->ressortgroupref;
3485 }
unsigned int Index
Definition: c.h:549
#define lfirst(lc)
Definition: pg_list.h:169
Index ressortgroupref
Definition: primnodes.h:1719

References lfirst, and TargetEntry::ressortgroupref.

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

◆ setTargetTable()

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

Definition at line 177 of file parse_clause.c.

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

References addNSItemToQuery(), addRangeTableEntryForRelation(), RangeVar::alias, ereport, errcode(), errmsg(), ERROR, NoLock, ParseNamespaceItem::p_rte, ParseNamespaceItem::p_rtindex, ParseState::p_target_nsitem, ParseState::p_target_relation, parserOpenTable(), RangeVar::relname, RangeTblEntry::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 3507 of file parse_clause.c.

3508 {
3509  Index ref = tle->ressortgroupref;
3510  ListCell *l;
3511 
3512  /* no need to scan list if tle has no marker */
3513  if (ref == 0)
3514  return false;
3515 
3516  foreach(l, sortList)
3517  {
3518  SortGroupClause *scl = (SortGroupClause *) lfirst(l);
3519 
3520  if (scl->tleSortGroupRef == ref &&
3521  (sortop == InvalidOid ||
3522  sortop == scl->sortop ||
3523  sortop == get_commutator(scl->sortop)))
3524  return true;
3525  }
3526  return false;
3527 }
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1490

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 2861 of file parse_clause.c.

2863 {
2864  List *result = NIL;
2865  ListCell *slitem;
2866  ListCell *tlitem;
2867 
2868  /*
2869  * The distinctClause should consist of all ORDER BY items followed by all
2870  * other non-resjunk targetlist items. There must not be any resjunk
2871  * ORDER BY items --- that would imply that we are sorting by a value that
2872  * isn't necessarily unique within a DISTINCT group, so the results
2873  * wouldn't be well-defined. This construction ensures we follow the rule
2874  * that sortClause and distinctClause match; in fact the sortClause will
2875  * always be a prefix of distinctClause.
2876  *
2877  * Note a corner case: the same TLE could be in the ORDER BY list multiple
2878  * times with different sortops. We have to include it in the
2879  * distinctClause the same way to preserve the prefix property. The net
2880  * effect will be that the TLE value will be made unique according to both
2881  * sortops.
2882  */
2883  foreach(slitem, sortClause)
2884  {
2885  SortGroupClause *scl = (SortGroupClause *) lfirst(slitem);
2886  TargetEntry *tle = get_sortgroupclause_tle(scl, *targetlist);
2887 
2888  if (tle->resjunk)
2889  ereport(ERROR,
2890  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2891  is_agg ?
2892  errmsg("in an aggregate with DISTINCT, ORDER BY expressions must appear in argument list") :
2893  errmsg("for SELECT DISTINCT, ORDER BY expressions must appear in select list"),
2894  parser_errposition(pstate,
2895  exprLocation((Node *) tle->expr))));
2896  result = lappend(result, copyObject(scl));
2897  }
2898 
2899  /*
2900  * Now add any remaining non-resjunk tlist items, using default sort/group
2901  * semantics for their data types.
2902  */
2903  foreach(tlitem, *targetlist)
2904  {
2905  TargetEntry *tle = (TargetEntry *) lfirst(tlitem);
2906 
2907  if (tle->resjunk)
2908  continue; /* ignore junk */
2909  result = addTargetToGroupList(pstate, tle,
2910  result, *targetlist,
2911  exprLocation((Node *) tle->expr));
2912  }
2913 
2914  /*
2915  * Complain if we found nothing to make DISTINCT. Returning an empty list
2916  * would cause the parsed Query to look like it didn't have DISTINCT, with
2917  * results that would probably surprise the user. Note: this case is
2918  * presently impossible for aggregates because of grammar restrictions,
2919  * but we check anyway.
2920  */
2921  if (result == NIL)
2922  ereport(ERROR,
2923  (errcode(ERRCODE_SYNTAX_ERROR),
2924  is_agg ?
2925  errmsg("an aggregate with DISTINCT must have at least one argument") :
2926  errmsg("SELECT DISTINCT must have at least one column")));
2927 
2928  return result;
2929 }
#define copyObject(obj)
Definition: nodes.h:689
static List * addTargetToGroupList(ParseState *pstate, TargetEntry *tle, List *grouplist, List *targetlist, int location)
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
Definition: pg_list.h:51
bool resjunk
Definition: primnodes.h:1723
TargetEntry * get_sortgroupclause_tle(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:356

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

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

◆ transformDistinctOnClause()

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

Definition at line 2945 of file parse_clause.c.

2947 {
2948  List *result = NIL;
2949  List *sortgrouprefs = NIL;
2950  bool skipped_sortitem;
2951  ListCell *lc;
2952  ListCell *lc2;
2953 
2954  /*
2955  * Add all the DISTINCT ON expressions to the tlist (if not already
2956  * present, they are added as resjunk items). Assign sortgroupref numbers
2957  * to them, and make a list of these numbers. (NB: we rely below on the
2958  * sortgrouprefs list being one-for-one with the original distinctlist.
2959  * Also notice that we could have duplicate DISTINCT ON expressions and
2960  * hence duplicate entries in sortgrouprefs.)
2961  */
2962  foreach(lc, distinctlist)
2963  {
2964  Node *dexpr = (Node *) lfirst(lc);
2965  int sortgroupref;
2966  TargetEntry *tle;
2967 
2968  tle = findTargetlistEntrySQL92(pstate, dexpr, targetlist,
2970  sortgroupref = assignSortGroupRef(tle, *targetlist);
2971  sortgrouprefs = lappend_int(sortgrouprefs, sortgroupref);
2972  }
2973 
2974  /*
2975  * If the user writes both DISTINCT ON and ORDER BY, adopt the sorting
2976  * semantics from ORDER BY items that match DISTINCT ON items, and also
2977  * adopt their column sort order. We insist that the distinctClause and
2978  * sortClause match, so throw error if we find the need to add any more
2979  * distinctClause items after we've skipped an ORDER BY item that wasn't
2980  * in DISTINCT ON.
2981  */
2982  skipped_sortitem = false;
2983  foreach(lc, sortClause)
2984  {
2985  SortGroupClause *scl = (SortGroupClause *) lfirst(lc);
2986 
2987  if (list_member_int(sortgrouprefs, scl->tleSortGroupRef))
2988  {
2989  if (skipped_sortitem)
2990  ereport(ERROR,
2991  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2992  errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
2993  parser_errposition(pstate,
2995  sortgrouprefs,
2996  distinctlist))));
2997  else
2998  result = lappend(result, copyObject(scl));
2999  }
3000  else
3001  skipped_sortitem = true;
3002  }
3003 
3004  /*
3005  * Now add any remaining DISTINCT ON items, using default sort/group
3006  * semantics for their data types. (Note: this is pretty questionable; if
3007  * the ORDER BY list doesn't include all the DISTINCT ON items and more
3008  * besides, you certainly aren't using DISTINCT ON in the intended way,
3009  * and you probably aren't going to get consistent results. It might be
3010  * better to throw an error or warning here. But historically we've
3011  * allowed it, so keep doing so.)
3012  */
3013  forboth(lc, distinctlist, lc2, sortgrouprefs)
3014  {
3015  Node *dexpr = (Node *) lfirst(lc);
3016  int sortgroupref = lfirst_int(lc2);
3017  TargetEntry *tle = get_sortgroupref_tle(sortgroupref, *targetlist);
3018 
3019  if (targetIsInSortList(tle, InvalidOid, result))
3020  continue; /* already in list (with some semantics) */
3021  if (skipped_sortitem)
3022  ereport(ERROR,
3023  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3024  errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
3025  parser_errposition(pstate, exprLocation(dexpr))));
3026  result = addTargetToGroupList(pstate, tle,
3027  result, *targetlist,
3028  exprLocation(dexpr));
3029  }
3030 
3031  /*
3032  * An empty result list is impossible here because of grammar
3033  * restrictions.
3034  */
3035  Assert(result != NIL);
3036 
3037  return result;
3038 }
List * lappend_int(List *list, int datum)
Definition: list.c:354
bool list_member_int(const List *list, int datum)
Definition: list.c:681
static int get_matching_location(int sortgroupref, List *sortgrouprefs, List *exprs)
static TargetEntry * findTargetlistEntrySQL92(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
@ EXPR_KIND_DISTINCT_ON
Definition: parse_node.h:61
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:446
#define lfirst_int(lc)
Definition: pg_list.h:170
TargetEntry * get_sortgroupref_tle(Index sortref, List *targetList)
Definition: tlist.c:334

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().

◆ transformFromClause()

void transformFromClause ( ParseState pstate,
List frmList 
)

Definition at line 113 of file parse_clause.c.

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

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

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

◆ transformGroupClause()

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

Definition at line 2507 of file parse_clause.c.

2510 {
2511  List *result = NIL;
2512  List *flat_grouplist;
2513  List *gsets = NIL;
2514  ListCell *gl;
2515  bool hasGroupingSets = false;
2516  Bitmapset *seen_local = NULL;
2517 
2518  /*
2519  * Recursively flatten implicit RowExprs. (Technically this is only needed
2520  * for GROUP BY, per the syntax rules for grouping sets, but we do it
2521  * anyway.)
2522  */
2523  flat_grouplist = (List *) flatten_grouping_sets((Node *) grouplist,
2524  true,
2525  &hasGroupingSets);
2526 
2527  /*
2528  * If the list is now empty, but hasGroupingSets is true, it's because we
2529  * elided redundant empty grouping sets. Restore a single empty grouping
2530  * set to leave a canonical form: GROUP BY ()
2531  */
2532 
2533  if (flat_grouplist == NIL && hasGroupingSets)
2534  {
2536  NIL,
2537  exprLocation((Node *) grouplist)));
2538  }
2539 
2540  foreach(gl, flat_grouplist)
2541  {
2542  Node *gexpr = (Node *) lfirst(gl);
2543 
2544  if (IsA(gexpr, GroupingSet))
2545  {
2546  GroupingSet *gset = (GroupingSet *) gexpr;
2547 
2548  switch (gset->kind)
2549  {
2550  case GROUPING_SET_EMPTY:
2551  gsets = lappend(gsets, gset);
2552  break;
2553  case GROUPING_SET_SIMPLE:
2554  /* can't happen */
2555  Assert(false);
2556  break;
2557  case GROUPING_SET_SETS:
2558  case GROUPING_SET_CUBE:
2559  case GROUPING_SET_ROLLUP:
2560  gsets = lappend(gsets,
2561  transformGroupingSet(&result,
2562  pstate, gset,
2563  targetlist, sortClause,
2564  exprKind, useSQL99, true));
2565  break;
2566  }
2567  }
2568  else
2569  {
2570  Index ref = transformGroupClauseExpr(&result, seen_local,
2571  pstate, gexpr,
2572  targetlist, sortClause,
2573  exprKind, useSQL99, true);
2574 
2575  if (ref > 0)
2576  {
2577  seen_local = bms_add_member(seen_local, ref);
2578  if (hasGroupingSets)
2579  gsets = lappend(gsets,
2581  list_make1_int(ref),
2582  exprLocation(gexpr)));
2583  }
2584  }
2585  }
2586 
2587  /* parser should prevent this */
2588  Assert(gsets == NIL || groupingSets != NULL);
2589 
2590  if (groupingSets)
2591  *groupingSets = gsets;
2592 
2593  return result;
2594 }
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:738
GroupingSet * makeGroupingSet(GroupingSetKind kind, List *content, int location)
Definition: makefuncs.c:798
#define IsA(nodeptr, _type_)
Definition: nodes.h:624
static Node * transformGroupingSet(List **flatresult, ParseState *pstate, GroupingSet *gset, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
static Node * flatten_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)
@ GROUPING_SET_CUBE
Definition: parsenodes.h:1367
@ GROUPING_SET_SIMPLE
Definition: parsenodes.h:1365
@ GROUPING_SET_ROLLUP
Definition: parsenodes.h:1366
@ GROUPING_SET_SETS
Definition: parsenodes.h:1368
@ GROUPING_SET_EMPTY
Definition: parsenodes.h:1364
#define list_make1(x1)
Definition: pg_list.h:206
#define list_make1_int(x1)
Definition: pg_list.h:221
GroupingSetKind kind
Definition: parsenodes.h:1374

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, GroupingSet::kind, lappend(), lfirst, list_make1, list_make1_int, makeGroupingSet(), NIL, transformGroupClauseExpr(), and transformGroupingSet().

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

◆ transformJsonTable()

ParseNamespaceItem* transformJsonTable ( ParseState pstate,
JsonTable jt 
)

Definition at line 642 of file parse_jsontable.c.

643 {
644  JsonTableContext cxt;
647  JsonTablePlan *plan = jt->plan;
648  JsonCommon *jscommon;
649  char *rootPathName = jt->common->pathname;
650  char *rootPath;
651  bool is_lateral;
652 
653  cxt.pstate = pstate;
654  cxt.table = jt;
655  cxt.tablefunc = tf;
656  cxt.pathNames = NIL;
657  cxt.pathNameId = 0;
658 
659  if (rootPathName)
660  registerJsonTableColumn(&cxt, rootPathName);
661 
663 
664 #if 0 /* XXX it' unclear from the standard whether
665  * root path name is mandatory or not */
666  if (plan && plan->plan_type != JSTP_DEFAULT && !rootPathName)
667  {
668  /* Assign root path name and create corresponding plan node */
669  JsonTablePlan *rootNode = makeNode(JsonTablePlan);
670  JsonTablePlan *rootPlan = (JsonTablePlan *)
672  (Node *) plan, jt->location);
673 
674  rootPathName = generateJsonTablePathName(&cxt);
675 
676  rootNode->plan_type = JSTP_SIMPLE;
677  rootNode->pathname = rootPathName;
678 
679  plan = rootPlan;
680  }
681 #endif
682 
683  jscommon = copyObject(jt->common);
684  jscommon->pathspec = makeStringConst(pstrdup("$"), -1);
685 
686  jfe->op = JSON_TABLE_OP;
687  jfe->common = jscommon;
688  jfe->on_error = jt->on_error;
689  jfe->location = jt->common->location;
690 
691  /*
692  * We make lateral_only names of this level visible, whether or not the
693  * RangeTableFunc is explicitly marked LATERAL. This is needed for SQL
694  * spec compliance and seems useful on convenience grounds for all
695  * functions in FROM.
696  *
697  * (LATERAL can't nest within a single pstate level, so we don't need
698  * save/restore logic here.)
699  */
700  Assert(!pstate->p_lateral_active);
701  pstate->p_lateral_active = true;
702 
703  tf->functype = TFT_JSON_TABLE;
704  tf->docexpr = transformExpr(pstate, (Node *) jfe, EXPR_KIND_FROM_FUNCTION);
705 
706  cxt.contextItemTypid = exprType(tf->docexpr);
707 
708  if (!IsA(jt->common->pathspec, A_Const) ||
709  castNode(A_Const, jt->common->pathspec)->val.node.type != T_String)
710  ereport(ERROR,
711  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
712  errmsg("only string constants supported in JSON_TABLE path specification"),
713  parser_errposition(pstate,
714  exprLocation(jt->common->pathspec))));
715 
716  rootPath = castNode(A_Const, jt->common->pathspec)->val.sval.sval;
717 
718  tf->plan = (Node *) transformJsonTableColumns(&cxt, plan, jt->columns,
719  rootPath, &rootPathName,
720  jt->common->location);
721 
722  tf->ordinalitycol = -1; /* undefine ordinality column number */
723  tf->location = jt->location;
724 
725  pstate->p_lateral_active = false;
726 
727  /*
728  * Mark the RTE as LATERAL if the user said LATERAL explicitly, or if
729  * there are any lateral cross-references in it.
730  */
731  is_lateral = jt->lateral || contain_vars_of_level((Node *) tf, 0);
732 
733  return addRangeTableEntryForTableFunc(pstate,
734  tf, jt->alias, is_lateral, true);
735 }
Node * makeJsonTableJoinedPlan(JsonTablePlanJoinType type, Node *plan1, Node *plan2, int location)
Definition: makefuncs.c:875
char * pstrdup(const char *in)
Definition: mcxt.c:1305
@ T_String
Definition: nodes.h:311
#define castNode(_type_, nodeptr)
Definition: nodes.h:642
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:112
static Node * makeStringConst(char *str, int location)
static void registerJsonTableColumn(JsonTableContext *cxt, char *colname)
static JsonTableParent * transformJsonTableColumns(JsonTableContext *cxt, JsonTablePlan *plan, List *columns, char *pathSpec, char **pathName, int location)
static void registerAllJsonTableColumns(JsonTableContext *cxt, List *columns)
static char * generateJsonTablePathName(JsonTableContext *cxt)
@ EXPR_KIND_FROM_FUNCTION
Definition: parse_node.h:45
ParseNamespaceItem * addRangeTableEntryForTableFunc(ParseState *pstate, TableFunc *tf, Alias *alias, bool lateral, bool inFromCl)
@ JSTP_DEFAULT
Definition: parsenodes.h:1703
@ JSTP_SIMPLE
Definition: parsenodes.h:1704
@ JSTPJ_OUTER
Definition: parsenodes.h:1715
@ TFT_JSON_TABLE
Definition: primnodes.h:79
@ JSON_TABLE_OP
Definition: primnodes.h:1254
char * pathname
Definition: parsenodes.h:1654
Node * pathspec
Definition: parsenodes.h:1653
JsonExprOp op
Definition: parsenodes.h:1666
JsonBehavior * on_error
Definition: parsenodes.h:1670
JsonCommon * common
Definition: parsenodes.h:1667
ParseState * pstate
TableFunc * tablefunc
JsonTable * table
char * pathname
Definition: parsenodes.h:1733
JsonTablePlanType plan_type
Definition: parsenodes.h:1729
JsonBehavior * on_error
Definition: parsenodes.h:1747
List * columns
Definition: parsenodes.h:1745
JsonCommon * common
Definition: parsenodes.h:1744
Alias * alias
Definition: parsenodes.h:1748
bool lateral
Definition: parsenodes.h:1749
JsonTablePlan * plan
Definition: parsenodes.h:1746
int location
Definition: parsenodes.h:1750
bool p_lateral_active
Definition: parse_node.h:189
Node * docexpr
Definition: primnodes.h:94
Node * plan
Definition: primnodes.h:104
int location
Definition: primnodes.h:106
TableFuncType functype
Definition: primnodes.h:91
int ordinalitycol
Definition: primnodes.h:105
bool contain_vars_of_level(Node *node, int levelsup)
Definition: var.c:438

References addRangeTableEntryForTableFunc(), JsonTable::alias, Assert(), castNode, JsonTable::columns, JsonFuncExpr::common, JsonTable::common, contain_vars_of_level(), JsonTableContext::contextItemTypid, copyObject, TableFunc::docexpr, ereport, errcode(), errmsg(), ERROR, EXPR_KIND_FROM_FUNCTION, exprLocation(), exprType(), TableFunc::functype, generateJsonTablePathName(), IsA, JSON_TABLE_OP, JSTP_DEFAULT, JSTP_SIMPLE, JSTPJ_OUTER, JsonTable::lateral, JsonCommon::location, JsonFuncExpr::location, JsonTable::location, TableFunc::location, makeJsonTableJoinedPlan(), makeNode, makeStringConst(), NIL, JsonFuncExpr::on_error, JsonTable::on_error, JsonFuncExpr::op, TableFunc::ordinalitycol, ParseState::p_lateral_active, parser_errposition(), JsonCommon::pathname, JsonTablePlan::pathname, JsonTableContext::pathNameId, JsonTableContext::pathNames, JsonCommon::pathspec, JsonTable::plan, TableFunc::plan, JsonTablePlan::plan_type, JsonTableContext::pstate, pstrdup(), registerAllJsonTableColumns(), registerJsonTableColumn(), T_String, JsonTableContext::table, JsonTableContext::tablefunc, TFT_JSON_TABLE, transformExpr(), and transformJsonTableColumns().

Referenced by transformFromClauseItem().

◆ transformLimitClause()

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

Definition at line 1756 of file parse_clause.c.

1759 {
1760  Node *qual;
1761 
1762  if (clause == NULL)
1763  return NULL;
1764 
1765  qual = transformExpr(pstate, clause, exprKind);
1766 
1767  qual = coerce_to_specific_type(pstate, qual, INT8OID, constructName);
1768 
1769  /* LIMIT can't refer to any variables of the current query */
1770  checkExprIsVarFree(pstate, qual, constructName);
1771 
1772  /*
1773  * Don't allow NULLs in FETCH FIRST .. WITH TIES. This test is ugly and
1774  * extremely simplistic, in that you can pass a NULL anyway by hiding it
1775  * inside an expression -- but this protects ruleutils against emitting an
1776  * unadorned NULL that's not accepted back by the grammar.
1777  */
1778  if (exprKind == EXPR_KIND_LIMIT && limitOption == LIMIT_OPTION_WITH_TIES &&
1779  IsA(clause, A_Const) && castNode(A_Const, clause)->isnull)
1780  ereport(ERROR,
1781  (errcode(ERRCODE_INVALID_ROW_COUNT_IN_LIMIT_CLAUSE),
1782  errmsg("row count cannot be null in FETCH FIRST ... WITH TIES clause")));
1783 
1784  return qual;
1785 }
@ LIMIT_OPTION_WITH_TIES
Definition: nodes.h:885
static void checkExprIsVarFree(ParseState *pstate, Node *n, const char *constructName)
Node * coerce_to_specific_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *constructName)
@ 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 3173 of file parse_clause.c.

3177 {
3178  InferClause *infer = onConflictClause->infer;
3179 
3180  *arbiterExpr = NIL;
3181  *arbiterWhere = NULL;
3182  *constraint = InvalidOid;
3183 
3184  if (onConflictClause->action == ONCONFLICT_UPDATE && !infer)
3185  ereport(ERROR,
3186  (errcode(ERRCODE_SYNTAX_ERROR),
3187  errmsg("ON CONFLICT DO UPDATE requires inference specification or constraint name"),
3188  errhint("For example, ON CONFLICT (column_name)."),
3189  parser_errposition(pstate,
3190  exprLocation((Node *) onConflictClause))));
3191 
3192  /*
3193  * To simplify certain aspects of its design, speculative insertion into
3194  * system catalogs is disallowed
3195  */
3196  if (IsCatalogRelation(pstate->p_target_relation))
3197  ereport(ERROR,
3198  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3199  errmsg("ON CONFLICT is not supported with system catalog tables"),
3200  parser_errposition(pstate,
3201  exprLocation((Node *) onConflictClause))));
3202 
3203  /* Same applies to table used by logical decoding as catalog table */
3205  ereport(ERROR,
3206  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3207  errmsg("ON CONFLICT is not supported on table \"%s\" used as a catalog table",
3209  parser_errposition(pstate,
3210  exprLocation((Node *) onConflictClause))));
3211 
3212  /* ON CONFLICT DO NOTHING does not require an inference clause */
3213  if (infer)
3214  {
3215  if (infer->indexElems)
3216  *arbiterExpr = resolve_unique_index_expr(pstate, infer,
3217  pstate->p_target_relation);
3218 
3219  /*
3220  * Handling inference WHERE clause (for partial unique index
3221  * inference)
3222  */
3223  if (infer->whereClause)
3224  *arbiterWhere = transformExpr(pstate, infer->whereClause,
3226 
3227  /*
3228  * If the arbiter is specified by constraint name, get the constraint
3229  * OID and mark the constrained columns as requiring SELECT privilege,
3230  * in the same way as would have happened if the arbiter had been
3231  * specified by explicit reference to the constraint's index columns.
3232  */
3233  if (infer->conname)
3234  {
3235  Oid relid = RelationGetRelid(pstate->p_target_relation);
3236  RangeTblEntry *rte = pstate->p_target_nsitem->p_rte;
3237  Bitmapset *conattnos;
3238 
3239  conattnos = get_relation_constraint_attnos(relid, infer->conname,
3240  false, constraint);
3241 
3242  /* Make sure the rel as a whole is marked for SELECT access */
3243  rte->requiredPerms |= ACL_SELECT;
3244  /* Mark the constrained columns as requiring SELECT access */
3245  rte->selectedCols = bms_add_members(rte->selectedCols, conattnos);
3246  }
3247  }
3248 
3249  /*
3250  * It's convenient to form a list of expressions based on the
3251  * representation used by CREATE INDEX, since the same restrictions are
3252  * appropriate (e.g. on subqueries). However, from here on, a dedicated
3253  * primnode representation is used for inference elements, and so
3254  * assign_query_collations() can be trusted to do the right thing with the
3255  * post parse analysis query tree inference clause representation.
3256  */
3257 }
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:795
bool IsCatalogRelation(Relation relation)
Definition: catalog.c:105
@ ONCONFLICT_UPDATE
Definition: nodes.h:873
static List * resolve_unique_index_expr(ParseState *pstate, InferClause *infer, Relation heapRel)
@ EXPR_KIND_INDEX_PREDICATE
Definition: parse_node.h:72
#define ACL_SELECT
Definition: parsenodes.h:83
Bitmapset * get_relation_constraint_attnos(Oid relid, const char *conname, bool missing_ok, Oid *constraintOid)
#define RelationGetRelid(relation)
Definition: rel.h:489
#define RelationIsUsedAsCatalogTable(relation)
Definition: rel.h:370
#define RelationGetRelationName(relation)
Definition: rel.h:523
char * conname
Definition: parsenodes.h:1463
List * indexElems
Definition: parsenodes.h:1461
Node * whereClause
Definition: parsenodes.h:1462
InferClause * infer
Definition: parsenodes.h:1477
OnConflictAction action
Definition: parsenodes.h:1476
Bitmapset * selectedCols
Definition: parsenodes.h:1167

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_rte, ParseState::p_target_nsitem, ParseState::p_target_relation, parser_errposition(), RelationGetRelationName, RelationGetRelid, RelationIsUsedAsCatalogTable, RangeTblEntry::requiredPerms, resolve_unique_index_expr(), RangeTblEntry::selectedCols, transformExpr(), and InferClause::whereClause.

Referenced by transformOnConflictClause().

◆ transformSortClause()

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

Definition at line 2607 of file parse_clause.c.

2612 {
2613  List *sortlist = NIL;
2614  ListCell *olitem;
2615 
2616  foreach(olitem, orderlist)
2617  {
2618  SortBy *sortby = (SortBy *) lfirst(olitem);
2619  TargetEntry *tle;
2620 
2621  if (useSQL99)
2622  tle = findTargetlistEntrySQL99(pstate, sortby->node,
2623  targetlist, exprKind);
2624  else
2625  tle = findTargetlistEntrySQL92(pstate, sortby->node,
2626  targetlist, exprKind);
2627 
2628  sortlist = addTargetToSortList(pstate, tle,
2629  sortlist, *targetlist, sortby);
2630  }
2631 
2632  return sortlist;
2633 }
List * addTargetToSortList(ParseState *pstate, TargetEntry *tle, List *sortlist, List *targetlist, SortBy *sortby)
static TargetEntry * findTargetlistEntrySQL99(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)

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

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

◆ transformWhereClause()

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

Definition at line 1729 of file parse_clause.c.

1731 {
1732  Node *qual;
1733 
1734  if (clause == NULL)
1735  return NULL;
1736 
1737  qual = transformExpr(pstate, clause, exprKind);
1738 
1739  qual = coerce_to_boolean(pstate, qual, constructName);
1740 
1741  return qual;
1742 }
Node * coerce_to_boolean(ParseState *pstate, Node *node, const char *constructName)

References coerce_to_boolean(), and transformExpr().

Referenced by AlterPolicy(), CreatePolicy(), CreateTriggerFiringOn(), ParseFuncOrColumn(), test_rls_hooks_permissive(), test_rls_hooks_restrictive(), transformDeleteStmt(), transformIndexStmt(), transformJoinOnClause(), transformJsonAggConstructor(), transformMergeStmt(), transformOnConflictClause(), transformPLAssignStmt(), TransformPubWhereClauses(), transformRuleStmt(), transformSelectStmt(), and transformUpdateStmt().

◆ transformWindowDefinitions()

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

Definition at line 2640 of file parse_clause.c.

2643 {
2644  List *result = NIL;
2645  Index winref = 0;
2646  ListCell *lc;
2647 
2648  foreach(lc, windowdefs)
2649  {
2650  WindowDef *windef = (WindowDef *) lfirst(lc);
2651  WindowClause *refwc = NULL;
2652  List *partitionClause;
2653  List *orderClause;
2654  Oid rangeopfamily = InvalidOid;
2655  Oid rangeopcintype = InvalidOid;
2656  WindowClause *wc;
2657 
2658  winref++;
2659 
2660  /*
2661  * Check for duplicate window names.
2662  */
2663  if (windef->name &&
2664  findWindowClause(result, windef->name) != NULL)
2665  ereport(ERROR,
2666  (errcode(ERRCODE_WINDOWING_ERROR),
2667  errmsg("window \"%s\" is already defined", windef->name),
2668  parser_errposition(pstate, windef->location)));
2669 
2670  /*
2671  * If it references a previous window, look that up.
2672  */
2673  if (windef->refname)
2674  {
2675  refwc = findWindowClause(result, windef->refname);
2676  if (refwc == NULL)
2677  ereport(ERROR,
2678  (errcode(ERRCODE_UNDEFINED_OBJECT),
2679  errmsg("window \"%s\" does not exist",
2680  windef->refname),
2681  parser_errposition(pstate, windef->location)));
2682  }
2683 
2684  /*
2685  * Transform PARTITION and ORDER specs, if any. These are treated
2686  * almost exactly like top-level GROUP BY and ORDER BY clauses,
2687  * including the special handling of nondefault operator semantics.
2688  */
2689  orderClause = transformSortClause(pstate,
2690  windef->orderClause,
2691  targetlist,
2693  true /* force SQL99 rules */ );
2694  partitionClause = transformGroupClause(pstate,
2695  windef->partitionClause,
2696  NULL,
2697  targetlist,
2698  orderClause,
2700  true /* force SQL99 rules */ );
2701 
2702  /*
2703  * And prepare the new WindowClause.
2704  */
2705  wc = makeNode(WindowClause);
2706  wc->name = windef->name;
2707  wc->refname = windef->refname;
2708 
2709  /*
2710  * Per spec, a windowdef that references a previous one copies the
2711  * previous partition clause (and mustn't specify its own). It can
2712  * specify its own ordering clause, but only if the previous one had
2713  * none. It always specifies its own frame clause, and the previous
2714  * one must not have a frame clause. Yeah, it's bizarre that each of
2715  * these cases works differently, but SQL:2008 says so; see 7.11
2716  * <window clause> syntax rule 10 and general rule 1. The frame
2717  * clause rule is especially bizarre because it makes "OVER foo"
2718  * different from "OVER (foo)", and requires the latter to throw an
2719  * error if foo has a nondefault frame clause. Well, ours not to
2720  * reason why, but we do go out of our way to throw a useful error
2721  * message for such cases.
2722  */
2723  if (refwc)
2724  {
2725  if (partitionClause)
2726  ereport(ERROR,
2727  (errcode(ERRCODE_WINDOWING_ERROR),
2728  errmsg("cannot override PARTITION BY clause of window \"%s\"",
2729  windef->refname),
2730  parser_errposition(pstate, windef->location)));
2732  }
2733  else
2734  wc->partitionClause = partitionClause;
2735  if (refwc)
2736  {
2737  if (orderClause && refwc->orderClause)
2738  ereport(ERROR,
2739  (errcode(ERRCODE_WINDOWING_ERROR),
2740  errmsg("cannot override ORDER BY clause of window \"%s\"",
2741  windef->refname),
2742  parser_errposition(pstate, windef->location)));
2743  if (orderClause)
2744  {
2745  wc->orderClause = orderClause;
2746  wc->copiedOrder = false;
2747  }
2748  else
2749  {
2750  wc->orderClause = copyObject(refwc->orderClause);
2751  wc->copiedOrder = true;
2752  }
2753  }
2754  else
2755  {
2756  wc->orderClause = orderClause;
2757  wc->copiedOrder = false;
2758  }
2759  if (refwc && refwc->frameOptions != FRAMEOPTION_DEFAULTS)
2760  {
2761  /*
2762  * Use this message if this is a WINDOW clause, or if it's an OVER
2763  * clause that includes ORDER BY or framing clauses. (We already
2764  * rejected PARTITION BY above, so no need to check that.)
2765  */
2766  if (windef->name ||
2767  orderClause || windef->frameOptions != FRAMEOPTION_DEFAULTS)
2768  ereport(ERROR,
2769  (errcode(ERRCODE_WINDOWING_ERROR),
2770  errmsg("cannot copy window \"%s\" because it has a frame clause",
2771  windef->refname),
2772  parser_errposition(pstate, windef->location)));
2773  /* Else this clause is just OVER (foo), so say this: */
2774  ereport(ERROR,
2775  (errcode(ERRCODE_WINDOWING_ERROR),
2776  errmsg("cannot copy window \"%s\" because it has a frame clause",
2777  windef->refname),
2778  errhint("Omit the parentheses in this OVER clause."),
2779  parser_errposition(pstate, windef->location)));
2780  }
2781  wc->frameOptions = windef->frameOptions;
2782 
2783  /*
2784  * RANGE offset PRECEDING/FOLLOWING requires exactly one ORDER BY
2785  * column; check that and get its sort opfamily info.
2786  */
2787  if ((wc->frameOptions & FRAMEOPTION_RANGE) &&
2790  {
2791  SortGroupClause *sortcl;
2792  Node *sortkey;
2793  int16 rangestrategy;
2794 
2795  if (list_length(wc->orderClause) != 1)
2796  ereport(ERROR,
2797  (errcode(ERRCODE_WINDOWING_ERROR),
2798  errmsg("RANGE with offset PRECEDING/FOLLOWING requires exactly one ORDER BY column"),
2799  parser_errposition(pstate, windef->location)));
2800  sortcl = linitial_node(SortGroupClause, wc->orderClause);
2801  sortkey = get_sortgroupclause_expr(sortcl, *targetlist);
2802  /* Find the sort operator in pg_amop */
2803  if (!get_ordering_op_properties(sortcl->sortop,
2804  &rangeopfamily,
2805  &rangeopcintype,
2806  &rangestrategy))
2807  elog(ERROR, "operator %u is not a valid ordering operator",
2808  sortcl->sortop);
2809  /* Record properties of sort ordering */
2810  wc->inRangeColl = exprCollation(sortkey);
2811  wc->inRangeAsc = (rangestrategy == BTLessStrategyNumber);
2812  wc->inRangeNullsFirst = sortcl->nulls_first;
2813  }
2814 
2815  /* Per spec, GROUPS mode requires an ORDER BY clause */
2816  if (wc->frameOptions & FRAMEOPTION_GROUPS)
2817  {
2818  if (wc->orderClause == NIL)
2819  ereport(ERROR,
2820  (errcode(ERRCODE_WINDOWING_ERROR),
2821  errmsg("GROUPS mode requires an ORDER BY clause"),
2822  parser_errposition(pstate, windef->location)));
2823  }
2824 
2825  /* Process frame offset expressions */
2826  wc->startOffset = transformFrameOffset(pstate, wc->frameOptions,
2827  rangeopfamily, rangeopcintype,
2828  &wc->startInRangeFunc,
2829  windef->startOffset);
2830  wc->endOffset = transformFrameOffset(pstate, wc->frameOptions,
2831  rangeopfamily, rangeopcintype,
2832  &wc->endInRangeFunc,
2833  windef->endOffset);
2834  wc->runCondition = NIL;
2835  wc->winref = winref;
2836 
2837  result = lappend(result, wc);
2838  }
2839 
2840  return result;
2841 }
signed short int16
Definition: c.h:428
bool get_ordering_op_properties(Oid opno, Oid *opfamily, Oid *opcintype, int16 *strategy)
Definition: lsyscache.c:205
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:788
List * transformSortClause(ParseState *pstate, List *orderlist, List **targetlist, ParseExprKind exprKind, bool useSQL99)
List * transformGroupClause(ParseState *pstate, List *grouplist, List **groupingSets, List **targetlist, List *sortClause, 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:556
#define FRAMEOPTION_START_OFFSET
Definition: parsenodes.h:554
#define FRAMEOPTION_RANGE
Definition: parsenodes.h:536
#define FRAMEOPTION_GROUPS
Definition: parsenodes.h:538
#define FRAMEOPTION_DEFAULTS
Definition: parsenodes.h:562
static int list_length(const List *l)
Definition: pg_list.h:149
#define linitial_node(type, l)
Definition: pg_list.h:177
#define BTLessStrategyNumber
Definition: stratnum.h:29
Oid endInRangeFunc
Definition: parsenodes.h:1408
bool copiedOrder
Definition: parsenodes.h:1413
Node * startOffset
Definition: parsenodes.h:1404
char * refname
Definition: parsenodes.h:1400
List * partitionClause
Definition: parsenodes.h:1401
Oid startInRangeFunc
Definition: parsenodes.h:1407
bool inRangeNullsFirst
Definition: parsenodes.h:1411
Node * endOffset
Definition: parsenodes.h:1405
List * runCondition
Definition: parsenodes.h:1406
List * orderClause
Definition: parsenodes.h:1402
List * orderClause
Definition: parsenodes.h:521
List * partitionClause
Definition: parsenodes.h:520
Node * startOffset
Definition: parsenodes.h:523
char * refname
Definition: parsenodes.h:519
Node * endOffset
Definition: parsenodes.h:524
int frameOptions
Definition: parsenodes.h:522
int location
Definition: parsenodes.h:525
char * name
Definition: parsenodes.h:518
Node * get_sortgroupclause_expr(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:368

References BTLessStrategyNumber, WindowClause::copiedOrder, copyObject, elog, WindowClause::endInRangeFunc, 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(), WindowClause::inRangeAsc, WindowClause::inRangeColl, WindowClause::inRangeNullsFirst, InvalidOid, lappend(), lfirst, linitial_node, list_length(), WindowDef::location, makeNode, WindowDef::name, WindowClause::name, NIL, SortGroupClause::nulls_first, WindowDef::orderClause, WindowClause::orderClause, parser_errposition(), WindowDef::partitionClause, WindowClause::partitionClause, WindowDef::refname, WindowClause::refname, WindowClause::runCondition, SortGroupClause::sortop, WindowClause::startInRangeFunc, WindowDef::startOffset, WindowClause::startOffset, transformFrameOffset(), transformGroupClause(), transformSortClause(), and WindowClause::winref.

Referenced by transformPLAssignStmt(), and transformSelectStmt().