PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
parse_clause.c File Reference
#include "postgres.h"
#include "miscadmin.h"
#include "access/heapam.h"
#include "access/tsmapi.h"
#include "catalog/catalog.h"
#include "catalog/heap.h"
#include "catalog/pg_am.h"
#include "catalog/pg_constraint_fn.h"
#include "catalog/pg_type.h"
#include "commands/defrem.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/tlist.h"
#include "optimizer/var.h"
#include "parser/analyze.h"
#include "parser/parsetree.h"
#include "parser/parser.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 "rewrite/rewriteManip.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/rel.h"
Include dependency graph for parse_clause.c:

Go to the source code of this file.

Macros

#define makeDefaultNSItem(rte)   makeNamespaceItem(rte, true, true, false, true)
 

Functions

static void extractRemainingColumns (List *common_colnames, List *src_colnames, List *src_colvars, List **res_colnames, List **res_colvars)
 
static NodetransformJoinUsingClause (ParseState *pstate, RangeTblEntry *leftRTE, RangeTblEntry *rightRTE, List *leftVars, List *rightVars)
 
static NodetransformJoinOnClause (ParseState *pstate, JoinExpr *j, List *namespace)
 
static RangeTblEntrytransformTableEntry (ParseState *pstate, RangeVar *r)
 
static RangeTblEntrytransformCTEReference (ParseState *pstate, RangeVar *r, CommonTableExpr *cte, Index levelsup)
 
static RangeTblEntrytransformRangeSubselect (ParseState *pstate, RangeSubselect *r)
 
static RangeTblEntrytransformRangeFunction (ParseState *pstate, RangeFunction *r)
 
static TableSampleClausetransformRangeTableSample (ParseState *pstate, RangeTableSample *rts)
 
static NodetransformFromClauseItem (ParseState *pstate, Node *n, RangeTblEntry **top_rte, int *top_rti, List **namespace)
 
static NodebuildMergedJoinVar (ParseState *pstate, JoinType jointype, Var *l_colvar, Var *r_colvar)
 
static ParseNamespaceItemmakeNamespaceItem (RangeTblEntry *rte, bool rel_visible, bool cols_visible, bool lateral_only, bool lateral_ok)
 
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, Node *clause)
 
void transformFromClause (ParseState *pstate, List *frmList)
 
int setTargetTable (ParseState *pstate, RangeVar *relation, bool inh, bool alsoSource, AclMode requiredPerms)
 
bool interpretOidsOption (List *defList, bool allowOids)
 
NodetransformWhereClause (ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
 
NodetransformLimitClause (ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
 
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)
 

Macro Definition Documentation

#define makeDefaultNSItem (   rte)    makeNamespaceItem(rte, true, true, false, true)

Definition at line 51 of file parse_clause.c.

Function Documentation

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

Definition at line 3048 of file parse_clause.c.

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

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

3050 {
3051  Oid restype = exprType((Node *) tle->expr);
3052 
3053  /* if tlist item is an UNKNOWN literal, change it to TEXT */
3054  if (restype == UNKNOWNOID)
3055  {
3056  tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3057  restype, TEXTOID, -1,
3060  -1);
3061  restype = TEXTOID;
3062  }
3063 
3064  /* avoid making duplicate grouplist entries */
3065  if (!targetIsInSortList(tle, InvalidOid, grouplist))
3066  {
3068  Oid sortop;
3069  Oid eqop;
3070  bool hashable;
3071  ParseCallbackState pcbstate;
3072 
3073  setup_parser_errposition_callback(&pcbstate, pstate, location);
3074 
3075  /* determine the eqop and optional sortop */
3076  get_sort_group_operators(restype,
3077  false, true, false,
3078  &sortop, &eqop, NULL,
3079  &hashable);
3080 
3082 
3083  grpcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3084  grpcl->eqop = eqop;
3085  grpcl->sortop = sortop;
3086  grpcl->nulls_first = false; /* OK with or without sortop */
3087  grpcl->hashable = hashable;
3088 
3089  grouplist = lappend(grouplist, grpcl);
3090  }
3091 
3092  return grouplist;
3093 }
Index assignSortGroupRef(TargetEntry *tle, List *tlist)
#define TEXTOID
Definition: pg_type.h:324
Index tleSortGroupRef
Definition: parsenodes.h:1102
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:156
Definition: nodes.h:508
unsigned int Oid
Definition: postgres_ext.h:31
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:159
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:143
List * lappend(List *list, void *datum)
Definition: list.c:128
#define InvalidOid
Definition: postgres_ext.h:36
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
#define makeNode(_type_)
Definition: nodes.h:556
#define NULL
Definition: c.h:226
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:185
Expr * expr
Definition: primnodes.h:1330
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
#define UNKNOWNOID
Definition: pg_type.h:423
List* addTargetToSortList ( ParseState pstate,
TargetEntry tle,
List sortlist,
List targetlist,
SortBy sortby 
)

Definition at line 2905 of file parse_clause.c.

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, NULL, 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(), TEXTOID, SortGroupClause::tleSortGroupRef, UNKNOWNOID, and SortBy::useOp.

Referenced by transformAggregateCall(), and transformSortClause().

2907 {
2908  Oid restype = exprType((Node *) tle->expr);
2909  Oid sortop;
2910  Oid eqop;
2911  bool hashable;
2912  bool reverse;
2913  int location;
2914  ParseCallbackState pcbstate;
2915 
2916  /* if tlist item is an UNKNOWN literal, change it to TEXT */
2917  if (restype == UNKNOWNOID)
2918  {
2919  tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
2920  restype, TEXTOID, -1,
2923  -1);
2924  restype = TEXTOID;
2925  }
2926 
2927  /*
2928  * Rather than clutter the API of get_sort_group_operators and the other
2929  * functions we're about to use, make use of error context callback to
2930  * mark any error reports with a parse position. We point to the operator
2931  * location if present, else to the expression being sorted. (NB: use the
2932  * original untransformed expression here; the TLE entry might well point
2933  * at a duplicate expression in the regular SELECT list.)
2934  */
2935  location = sortby->location;
2936  if (location < 0)
2937  location = exprLocation(sortby->node);
2938  setup_parser_errposition_callback(&pcbstate, pstate, location);
2939 
2940  /* determine the sortop, eqop, and directionality */
2941  switch (sortby->sortby_dir)
2942  {
2943  case SORTBY_DEFAULT:
2944  case SORTBY_ASC:
2945  get_sort_group_operators(restype,
2946  true, true, false,
2947  &sortop, &eqop, NULL,
2948  &hashable);
2949  reverse = false;
2950  break;
2951  case SORTBY_DESC:
2952  get_sort_group_operators(restype,
2953  false, true, true,
2954  NULL, &eqop, &sortop,
2955  &hashable);
2956  reverse = true;
2957  break;
2958  case SORTBY_USING:
2959  Assert(sortby->useOp != NIL);
2960  sortop = compatible_oper_opid(sortby->useOp,
2961  restype,
2962  restype,
2963  false);
2964 
2965  /*
2966  * Verify it's a valid ordering operator, fetch the corresponding
2967  * equality operator, and determine whether to consider it like
2968  * ASC or DESC.
2969  */
2970  eqop = get_equality_op_for_ordering_op(sortop, &reverse);
2971  if (!OidIsValid(eqop))
2972  ereport(ERROR,
2973  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2974  errmsg("operator %s is not a valid ordering operator",
2975  strVal(llast(sortby->useOp))),
2976  errhint("Ordering operators must be \"<\" or \">\" members of btree operator families.")));
2977 
2978  /*
2979  * Also see if the equality operator is hashable.
2980  */
2981  hashable = op_hashjoinable(eqop, restype);
2982  break;
2983  default:
2984  elog(ERROR, "unrecognized sortby_dir: %d", sortby->sortby_dir);
2985  sortop = InvalidOid; /* keep compiler quiet */
2986  eqop = InvalidOid;
2987  hashable = false;
2988  reverse = false;
2989  break;
2990  }
2991 
2993 
2994  /* avoid making duplicate sortlist entries */
2995  if (!targetIsInSortList(tle, sortop, sortlist))
2996  {
2998 
2999  sortcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3000 
3001  sortcl->eqop = eqop;
3002  sortcl->sortop = sortop;
3003  sortcl->hashable = hashable;
3004 
3005  switch (sortby->sortby_nulls)
3006  {
3007  case SORTBY_NULLS_DEFAULT:
3008  /* NULLS FIRST is default for DESC; other way for ASC */
3009  sortcl->nulls_first = reverse;
3010  break;
3011  case SORTBY_NULLS_FIRST:
3012  sortcl->nulls_first = true;
3013  break;
3014  case SORTBY_NULLS_LAST:
3015  sortcl->nulls_first = false;
3016  break;
3017  default:
3018  elog(ERROR, "unrecognized sortby_nulls: %d",
3019  sortby->sortby_nulls);
3020  break;
3021  }
3022 
3023  sortlist = lappend(sortlist, sortcl);
3024  }
3025 
3026  return sortlist;
3027 }
#define NIL
Definition: pg_list.h:69
Index assignSortGroupRef(TargetEntry *tle, List *tlist)
int errhint(const char *fmt,...)
Definition: elog.c:987
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1204
SortByDir sortby_dir
Definition: parsenodes.h:461
#define TEXTOID
Definition: pg_type.h:324
List * useOp
Definition: parsenodes.h:463
Oid get_equality_op_for_ordering_op(Oid opno, bool *reverse)
Definition: lsyscache.c:264
#define llast(l)
Definition: pg_list.h:126
Index tleSortGroupRef
Definition: parsenodes.h:1102
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:156
Definition: nodes.h:508
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:575
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:534
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:159
bool op_hashjoinable(Oid opno, Oid inputtype)
Definition: lsyscache.c:1214
#define ERROR
Definition: elog.h:43
SortByNulls sortby_nulls
Definition: parsenodes.h:462
#define ereport(elevel, rest)
Definition: elog.h:122
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:143
List * lappend(List *list, void *datum)
Definition: list.c:128
#define InvalidOid
Definition: postgres_ext.h:36
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
#define makeNode(_type_)
Definition: nodes.h:556
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
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:185
Expr * expr
Definition: primnodes.h:1330
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
#define UNKNOWNOID
Definition: pg_type.h:423
int errmsg(const char *fmt,...)
Definition: elog.c:797
Oid compatible_oper_opid(List *op, Oid arg1, Oid arg2, bool noError)
Definition: parse_oper.c:492
#define elog
Definition: elog.h:219
Node * node
Definition: parsenodes.h:460
int location
Definition: parsenodes.h:464
Index assignSortGroupRef ( TargetEntry tle,
List tlist 
)

Definition at line 3103 of file parse_clause.c.

References lfirst, and TargetEntry::ressortgroupref.

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

3104 {
3105  Index maxRef;
3106  ListCell *l;
3107 
3108  if (tle->ressortgroupref) /* already has one? */
3109  return tle->ressortgroupref;
3110 
3111  /* easiest way to pick an unused refnumber: max used + 1 */
3112  maxRef = 0;
3113  foreach(l, tlist)
3114  {
3115  Index ref = ((TargetEntry *) lfirst(l))->ressortgroupref;
3116 
3117  if (ref > maxRef)
3118  maxRef = ref;
3119  }
3120  tle->ressortgroupref = maxRef + 1;
3121  return tle->ressortgroupref;
3122 }
unsigned int Index
Definition: c.h:362
#define lfirst(lc)
Definition: pg_list.h:106
Index ressortgroupref
Definition: primnodes.h:1333
static Node * buildMergedJoinVar ( ParseState pstate,
JoinType  jointype,
Var l_colvar,
Var r_colvar 
)
static

Definition at line 1252 of file parse_clause.c.

References CoalesceExpr::args, assign_expr_collations(), CoalesceExpr::coalescetype, COERCE_IMPLICIT_CAST, coerce_type(), COERCION_IMPLICIT, elog, ERROR, InvalidOid, IsA, JOIN_FULL, JOIN_INNER, JOIN_LEFT, JOIN_RIGHT, list_make2, CoalesceExpr::location, makeNode, makeRelabelType(), NULL, select_common_type(), Var::vartype, and Var::vartypmod.

Referenced by transformFromClauseItem().

1254 {
1255  Oid outcoltype;
1256  int32 outcoltypmod;
1257  Node *l_node,
1258  *r_node,
1259  *res_node;
1260 
1261  /*
1262  * Choose output type if input types are dissimilar.
1263  */
1264  outcoltype = l_colvar->vartype;
1265  outcoltypmod = l_colvar->vartypmod;
1266  if (outcoltype != r_colvar->vartype)
1267  {
1268  outcoltype = select_common_type(pstate,
1269  list_make2(l_colvar, r_colvar),
1270  "JOIN/USING",
1271  NULL);
1272  outcoltypmod = -1; /* ie, unknown */
1273  }
1274  else if (outcoltypmod != r_colvar->vartypmod)
1275  {
1276  /* same type, but not same typmod */
1277  outcoltypmod = -1; /* ie, unknown */
1278  }
1279 
1280  /*
1281  * Insert coercion functions if needed. Note that a difference in typmod
1282  * can only happen if input has typmod but outcoltypmod is -1. In that
1283  * case we insert a RelabelType to clearly mark that result's typmod is
1284  * not same as input. We never need coerce_type_typmod.
1285  */
1286  if (l_colvar->vartype != outcoltype)
1287  l_node = coerce_type(pstate, (Node *) l_colvar, l_colvar->vartype,
1288  outcoltype, outcoltypmod,
1290  else if (l_colvar->vartypmod != outcoltypmod)
1291  l_node = (Node *) makeRelabelType((Expr *) l_colvar,
1292  outcoltype, outcoltypmod,
1293  InvalidOid, /* fixed below */
1295  else
1296  l_node = (Node *) l_colvar;
1297 
1298  if (r_colvar->vartype != outcoltype)
1299  r_node = coerce_type(pstate, (Node *) r_colvar, r_colvar->vartype,
1300  outcoltype, outcoltypmod,
1302  else if (r_colvar->vartypmod != outcoltypmod)
1303  r_node = (Node *) makeRelabelType((Expr *) r_colvar,
1304  outcoltype, outcoltypmod,
1305  InvalidOid, /* fixed below */
1307  else
1308  r_node = (Node *) r_colvar;
1309 
1310  /*
1311  * Choose what to emit
1312  */
1313  switch (jointype)
1314  {
1315  case JOIN_INNER:
1316 
1317  /*
1318  * We can use either var; prefer non-coerced one if available.
1319  */
1320  if (IsA(l_node, Var))
1321  res_node = l_node;
1322  else if (IsA(r_node, Var))
1323  res_node = r_node;
1324  else
1325  res_node = l_node;
1326  break;
1327  case JOIN_LEFT:
1328  /* Always use left var */
1329  res_node = l_node;
1330  break;
1331  case JOIN_RIGHT:
1332  /* Always use right var */
1333  res_node = r_node;
1334  break;
1335  case JOIN_FULL:
1336  {
1337  /*
1338  * Here we must build a COALESCE expression to ensure that the
1339  * join output is non-null if either input is.
1340  */
1342 
1343  c->coalescetype = outcoltype;
1344  /* coalescecollid will get set below */
1345  c->args = list_make2(l_node, r_node);
1346  c->location = -1;
1347  res_node = (Node *) c;
1348  break;
1349  }
1350  default:
1351  elog(ERROR, "unrecognized join type: %d", (int) jointype);
1352  res_node = NULL; /* keep compiler quiet */
1353  break;
1354  }
1355 
1356  /*
1357  * Apply assign_expr_collations to fix up the collation info in the
1358  * coercion and CoalesceExpr nodes, if we made any. This must be done now
1359  * so that the join node's alias vars show correct collation info.
1360  */
1361  assign_expr_collations(pstate, res_node);
1362 
1363  return res_node;
1364 }
#define list_make2(x1, x2)
Definition: pg_list.h:134
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:156
Definition: nodes.h:508
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:141
signed int int32
Definition: c.h:253
void assign_expr_collations(ParseState *pstate, Node *expr)
#define ERROR
Definition: elog.h:43
Oid vartype
Definition: primnodes.h:148
List * args
Definition: primnodes.h:1023
char * c
RelabelType * makeRelabelType(Expr *arg, Oid rtype, int32 rtypmod, Oid rcollid, CoercionForm rformat)
Definition: makefuncs.c:399
#define InvalidOid
Definition: postgres_ext.h:36
#define makeNode(_type_)
Definition: nodes.h:556
#define NULL
Definition: c.h:226
Oid coalescetype
Definition: primnodes.h:1021
Oid select_common_type(ParseState *pstate, List *exprs, const char *context, Node **which_expr)
#define elog
Definition: elog.h:219
int32 vartypmod
Definition: primnodes.h:149
static void checkExprIsVarFree ( ParseState pstate,
Node n,
const char *  constructName 
)
static

Definition at line 1487 of file parse_clause.c.

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

Referenced by transformFrameOffset(), and transformLimitClause().

1488 {
1489  if (contain_vars_of_level(n, 0))
1490  {
1491  ereport(ERROR,
1492  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1493  /* translator: %s is name of a SQL construct, eg LIMIT */
1494  errmsg("argument of %s must not contain variables",
1495  constructName),
1496  parser_errposition(pstate,
1497  locate_var_of_level(n, 0))));
1498  }
1499 }
int errcode(int sqlerrcode)
Definition: elog.c:575
int locate_var_of_level(Node *node, int levelsup)
Definition: var.c:437
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
bool contain_vars_of_level(Node *node, int levelsup)
Definition: var.c:369
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:109
int errmsg(const char *fmt,...)
Definition: elog.c:797
static void checkTargetlistEntrySQL92 ( ParseState pstate,
TargetEntry tle,
ParseExprKind  exprKind 
)
static

Definition at line 1512 of file parse_clause.c.

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

1514 {
1515  switch (exprKind)
1516  {
1517  case EXPR_KIND_GROUP_BY:
1518  /* reject aggregates and window functions */
1519  if (pstate->p_hasAggs &&
1520  contain_aggs_of_level((Node *) tle->expr, 0))
1521  ereport(ERROR,
1522  (errcode(ERRCODE_GROUPING_ERROR),
1523  /* translator: %s is name of a SQL construct, eg GROUP BY */
1524  errmsg("aggregate functions are not allowed in %s",
1525  ParseExprKindName(exprKind)),
1526  parser_errposition(pstate,
1527  locate_agg_of_level((Node *) tle->expr, 0))));
1528  if (pstate->p_hasWindowFuncs &&
1529  contain_windowfuncs((Node *) tle->expr))
1530  ereport(ERROR,
1531  (errcode(ERRCODE_WINDOWING_ERROR),
1532  /* translator: %s is name of a SQL construct, eg GROUP BY */
1533  errmsg("window functions are not allowed in %s",
1534  ParseExprKindName(exprKind)),
1535  parser_errposition(pstate,
1536  locate_windowfunc((Node *) tle->expr))));
1537  break;
1538  case EXPR_KIND_ORDER_BY:
1539  /* no extra checks needed */
1540  break;
1541  case EXPR_KIND_DISTINCT_ON:
1542  /* no extra checks needed */
1543  break;
1544  default:
1545  elog(ERROR, "unexpected exprKind in checkTargetlistEntrySQL92");
1546  break;
1547  }
1548 }
Definition: nodes.h:508
int errcode(int sqlerrcode)
Definition: elog.c:575
bool p_hasAggs
Definition: parse_node.h:192
int locate_windowfunc(Node *node)
Definition: rewriteManip.c:235
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:3352
bool p_hasWindowFuncs
Definition: parse_node.h:193
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
int locate_agg_of_level(Node *node, int levelsup)
Definition: rewriteManip.c:131
Expr * expr
Definition: primnodes.h:1330
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:109
bool contain_aggs_of_level(Node *node, int levelsup)
Definition: rewriteManip.c:67
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
bool contain_windowfuncs(Node *node)
Definition: rewriteManip.c:197
static void extractRemainingColumns ( List common_colnames,
List src_colnames,
List src_colvars,
List **  res_colnames,
List **  res_colvars 
)
static

Definition at line 274 of file parse_clause.c.

References Assert, cnames, forboth, lappend(), lfirst, list_length(), NIL, and strVal.

Referenced by transformFromClauseItem().

277 {
278  List *new_colnames = NIL;
279  List *new_colvars = NIL;
280  ListCell *lnames,
281  *lvars;
282 
283  Assert(list_length(src_colnames) == list_length(src_colvars));
284 
285  forboth(lnames, src_colnames, lvars, src_colvars)
286  {
287  char *colname = strVal(lfirst(lnames));
288  bool match = false;
289  ListCell *cnames;
290 
291  foreach(cnames, common_colnames)
292  {
293  char *ccolname = strVal(lfirst(cnames));
294 
295  if (strcmp(colname, ccolname) == 0)
296  {
297  match = true;
298  break;
299  }
300  }
301 
302  if (!match)
303  {
304  new_colnames = lappend(new_colnames, lfirst(lnames));
305  new_colvars = lappend(new_colvars, lfirst(lvars));
306  }
307  }
308 
309  *res_colnames = new_colnames;
310  *res_colvars = new_colvars;
311 }
#define NIL
Definition: pg_list.h:69
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:174
#define strVal(v)
Definition: value.h:54
List * lappend(List *list, void *datum)
Definition: list.c:128
HashCompareFunc match
Definition: dynahash.c:198
#define Assert(condition)
Definition: c.h:671
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
static const struct cname cnames[]
Definition: pg_list.h:45
static TargetEntry * findTargetlistEntrySQL92 ( ParseState pstate,
Node node,
List **  tlist,
ParseExprKind  exprKind 
)
static

Definition at line 1568 of file parse_clause.c.

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

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

1570 {
1571  ListCell *tl;
1572 
1573  /*----------
1574  * Handle two special cases as mandated by the SQL92 spec:
1575  *
1576  * 1. Bare ColumnName (no qualifier or subscripts)
1577  * For a bare identifier, we search for a matching column name
1578  * in the existing target list. Multiple matches are an error
1579  * unless they refer to identical values; for example,
1580  * we allow SELECT a, a FROM table ORDER BY a
1581  * but not SELECT a AS b, b FROM table ORDER BY b
1582  * If no match is found, we fall through and treat the identifier
1583  * as an expression.
1584  * For GROUP BY, it is incorrect to match the grouping item against
1585  * targetlist entries: according to SQL92, an identifier in GROUP BY
1586  * is a reference to a column name exposed by FROM, not to a target
1587  * list column. However, many implementations (including pre-7.0
1588  * PostgreSQL) accept this anyway. So for GROUP BY, we look first
1589  * to see if the identifier matches any FROM column name, and only
1590  * try for a targetlist name if it doesn't. This ensures that we
1591  * adhere to the spec in the case where the name could be both.
1592  * DISTINCT ON isn't in the standard, so we can do what we like there;
1593  * we choose to make it work like ORDER BY, on the rather flimsy
1594  * grounds that ordinary DISTINCT works on targetlist entries.
1595  *
1596  * 2. IntegerConstant
1597  * This means to use the n'th item in the existing target list.
1598  * Note that it would make no sense to order/group/distinct by an
1599  * actual constant, so this does not create a conflict with SQL99.
1600  * GROUP BY column-number is not allowed by SQL92, but since
1601  * the standard has no other behavior defined for this syntax,
1602  * we may as well accept this common extension.
1603  *
1604  * Note that pre-existing resjunk targets must not be used in either case,
1605  * since the user didn't write them in his SELECT list.
1606  *
1607  * If neither special case applies, fall through to treat the item as
1608  * an expression per SQL99.
1609  *----------
1610  */
1611  if (IsA(node, ColumnRef) &&
1612  list_length(((ColumnRef *) node)->fields) == 1 &&
1613  IsA(linitial(((ColumnRef *) node)->fields), String))
1614  {
1615  char *name = strVal(linitial(((ColumnRef *) node)->fields));
1616  int location = ((ColumnRef *) node)->location;
1617 
1618  if (exprKind == EXPR_KIND_GROUP_BY)
1619  {
1620  /*
1621  * In GROUP BY, we must prefer a match against a FROM-clause
1622  * column to one against the targetlist. Look to see if there is
1623  * a matching column. If so, fall through to use SQL99 rules.
1624  * NOTE: if name could refer ambiguously to more than one column
1625  * name exposed by FROM, colNameToVar will ereport(ERROR). That's
1626  * just what we want here.
1627  *
1628  * Small tweak for 7.4.3: ignore matches in upper query levels.
1629  * This effectively changes the search order for bare names to (1)
1630  * local FROM variables, (2) local targetlist aliases, (3) outer
1631  * FROM variables, whereas before it was (1) (3) (2). SQL92 and
1632  * SQL99 do not allow GROUPing BY an outer reference, so this
1633  * breaks no cases that are legal per spec, and it seems a more
1634  * self-consistent behavior.
1635  */
1636  if (colNameToVar(pstate, name, true, location) != NULL)
1637  name = NULL;
1638  }
1639 
1640  if (name != NULL)
1641  {
1642  TargetEntry *target_result = NULL;
1643 
1644  foreach(tl, *tlist)
1645  {
1646  TargetEntry *tle = (TargetEntry *) lfirst(tl);
1647 
1648  if (!tle->resjunk &&
1649  strcmp(tle->resname, name) == 0)
1650  {
1651  if (target_result != NULL)
1652  {
1653  if (!equal(target_result->expr, tle->expr))
1654  ereport(ERROR,
1655  (errcode(ERRCODE_AMBIGUOUS_COLUMN),
1656 
1657  /*------
1658  translator: first %s is name of a SQL construct, eg ORDER BY */
1659  errmsg("%s \"%s\" is ambiguous",
1660  ParseExprKindName(exprKind),
1661  name),
1662  parser_errposition(pstate, location)));
1663  }
1664  else
1665  target_result = tle;
1666  /* Stay in loop to check for ambiguity */
1667  }
1668  }
1669  if (target_result != NULL)
1670  {
1671  /* return the first match, after suitable validation */
1672  checkTargetlistEntrySQL92(pstate, target_result, exprKind);
1673  return target_result;
1674  }
1675  }
1676  }
1677  if (IsA(node, A_Const))
1678  {
1679  Value *val = &((A_Const *) node)->val;
1680  int location = ((A_Const *) node)->location;
1681  int targetlist_pos = 0;
1682  int target_pos;
1683 
1684  if (!IsA(val, Integer))
1685  ereport(ERROR,
1686  (errcode(ERRCODE_SYNTAX_ERROR),
1687  /* translator: %s is name of a SQL construct, eg ORDER BY */
1688  errmsg("non-integer constant in %s",
1689  ParseExprKindName(exprKind)),
1690  parser_errposition(pstate, location)));
1691 
1692  target_pos = intVal(val);
1693  foreach(tl, *tlist)
1694  {
1695  TargetEntry *tle = (TargetEntry *) lfirst(tl);
1696 
1697  if (!tle->resjunk)
1698  {
1699  if (++targetlist_pos == target_pos)
1700  {
1701  /* return the unique match, after suitable validation */
1702  checkTargetlistEntrySQL92(pstate, tle, exprKind);
1703  return tle;
1704  }
1705  }
1706  }
1707  ereport(ERROR,
1708  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1709  /* translator: %s is name of a SQL construct, eg ORDER BY */
1710  errmsg("%s position %d is not in select list",
1711  ParseExprKindName(exprKind), target_pos),
1712  parser_errposition(pstate, location)));
1713  }
1714 
1715  /*
1716  * Otherwise, we have an expression, so process it per SQL99 rules.
1717  */
1718  return findTargetlistEntrySQL99(pstate, node, tlist, exprKind);
1719 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2870
static TargetEntry * findTargetlistEntrySQL99(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:575
char * resname
Definition: primnodes.h:1332
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:3352
bool resjunk
Definition: primnodes.h:1337
#define linitial(l)
Definition: pg_list.h:110
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
Node * colNameToVar(ParseState *pstate, char *colname, bool localonly, int location)
#define NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
Definition: value.h:42
Expr * expr
Definition: primnodes.h:1330
static int list_length(const List *l)
Definition: pg_list.h:89
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:109
static void checkTargetlistEntrySQL92(ParseState *pstate, TargetEntry *tle, ParseExprKind exprKind)
const char * name
Definition: encode.c:521
#define intVal(v)
Definition: value.h:52
int errmsg(const char *fmt,...)
Definition: elog.c:797
long val
Definition: informix.c:689
static TargetEntry * findTargetlistEntrySQL99 ( ParseState pstate,
Node node,
List **  tlist,
ParseExprKind  exprKind 
)
static

Definition at line 1735 of file parse_clause.c.

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

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

1737 {
1738  TargetEntry *target_result;
1739  ListCell *tl;
1740  Node *expr;
1741 
1742  /*
1743  * Convert the untransformed node to a transformed expression, and search
1744  * for a match in the tlist. NOTE: it doesn't really matter whether there
1745  * is more than one match. Also, we are willing to match an existing
1746  * resjunk target here, though the SQL92 cases above must ignore resjunk
1747  * targets.
1748  */
1749  expr = transformExpr(pstate, node, exprKind);
1750 
1751  foreach(tl, *tlist)
1752  {
1753  TargetEntry *tle = (TargetEntry *) lfirst(tl);
1754  Node *texpr;
1755 
1756  /*
1757  * Ignore any implicit cast on the existing tlist expression.
1758  *
1759  * This essentially allows the ORDER/GROUP/etc item to adopt the same
1760  * datatype previously selected for a textually-equivalent tlist item.
1761  * There can't be any implicit cast at top level in an ordinary SELECT
1762  * tlist at this stage, but the case does arise with ORDER BY in an
1763  * aggregate function.
1764  */
1765  texpr = strip_implicit_coercions((Node *) tle->expr);
1766 
1767  if (equal(expr, texpr))
1768  return tle;
1769  }
1770 
1771  /*
1772  * If no matches, construct a new target entry which is appended to the
1773  * end of the target list. This target is given resjunk = TRUE so that it
1774  * will not be projected into the final tuple.
1775  */
1776  target_result = transformTargetEntry(pstate, node, expr, exprKind,
1777  NULL, true);
1778 
1779  *tlist = lappend(*tlist, target_result);
1780 
1781  return target_result;
1782 }
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2870
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:147
Definition: nodes.h:508
List * lappend(List *list, void *datum)
Definition: list.c:128
#define NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
Expr * expr
Definition: primnodes.h:1330
TargetEntry * transformTargetEntry(ParseState *pstate, Node *node, Node *expr, ParseExprKind exprKind, char *colname, bool resjunk)
Definition: parse_target.c:85
Node * strip_implicit_coercions(Node *node)
Definition: nodeFuncs.c:609
static WindowClause * findWindowClause ( List wclist,
const char *  name 
)
static

Definition at line 3171 of file parse_clause.c.

References lfirst, WindowClause::name, and NULL.

Referenced by transformWindowDefinitions().

3172 {
3173  ListCell *l;
3174 
3175  foreach(l, wclist)
3176  {
3177  WindowClause *wc = (WindowClause *) lfirst(l);
3178 
3179  if (wc->name && strcmp(wc->name, name) == 0)
3180  return wc;
3181  }
3182 
3183  return NULL;
3184 }
#define NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
const char * name
Definition: encode.c:521
static Node* flatten_grouping_sets ( Node expr,
bool  toplevel,
bool hasGroupingSets 
)
static

Definition at line 1821 of file parse_clause.c.

References RowExpr::args, check_stack_depth(), COERCE_IMPLICIT_CAST, GroupingSet::content, GROUPING_SET_EMPTY, GROUPING_SET_SETS, IsA, GroupingSet::kind, lappend(), lfirst, list_concat(), GroupingSet::location, makeGroupingSet(), NIL, NULL, RowExpr::row_format, T_GroupingSet, T_List, T_RowExpr, and Node::type.

Referenced by transformGroupClause().

1822 {
1823  /* just in case of pathological input */
1825 
1826  if (expr == (Node *) NIL)
1827  return (Node *) NIL;
1828 
1829  switch (expr->type)
1830  {
1831  case T_RowExpr:
1832  {
1833  RowExpr *r = (RowExpr *) expr;
1834 
1835  if (r->row_format == COERCE_IMPLICIT_CAST)
1836  return flatten_grouping_sets((Node *) r->args,
1837  false, NULL);
1838  }
1839  break;
1840  case T_GroupingSet:
1841  {
1842  GroupingSet *gset = (GroupingSet *) expr;
1843  ListCell *l2;
1844  List *result_set = NIL;
1845 
1846  if (hasGroupingSets)
1847  *hasGroupingSets = true;
1848 
1849  /*
1850  * at the top level, we skip over all empty grouping sets; the
1851  * caller can supply the canonical GROUP BY () if nothing is
1852  * left.
1853  */
1854 
1855  if (toplevel && gset->kind == GROUPING_SET_EMPTY)
1856  return (Node *) NIL;
1857 
1858  foreach(l2, gset->content)
1859  {
1860  Node *n1 = lfirst(l2);
1861  Node *n2 = flatten_grouping_sets(n1, false, NULL);
1862 
1863  if (IsA(n1, GroupingSet) &&
1864  ((GroupingSet *) n1)->kind == GROUPING_SET_SETS)
1865  {
1866  result_set = list_concat(result_set, (List *) n2);
1867  }
1868  else
1869  result_set = lappend(result_set, n2);
1870  }
1871 
1872  /*
1873  * At top level, keep the grouping set node; but if we're in a
1874  * nested grouping set, then we need to concat the flattened
1875  * result into the outer list if it's simply nested.
1876  */
1877 
1878  if (toplevel || (gset->kind != GROUPING_SET_SETS))
1879  {
1880  return (Node *) makeGroupingSet(gset->kind, result_set, gset->location);
1881  }
1882  else
1883  return (Node *) result_set;
1884  }
1885  case T_List:
1886  {
1887  List *result = NIL;
1888  ListCell *l;
1889 
1890  foreach(l, (List *) expr)
1891  {
1892  Node *n = flatten_grouping_sets(lfirst(l), toplevel, hasGroupingSets);
1893 
1894  if (n != (Node *) NIL)
1895  {
1896  if (IsA(n, List))
1897  result = list_concat(result, (List *) n);
1898  else
1899  result = lappend(result, n);
1900  }
1901  }
1902 
1903  return (Node *) result;
1904  }
1905  default:
1906  break;
1907  }
1908 
1909  return expr;
1910 }
#define NIL
Definition: pg_list.h:69
List * args
Definition: primnodes.h:962
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
List * content
Definition: parsenodes.h:1172
Definition: nodes.h:508
List * list_concat(List *list1, List *list2)
Definition: list.c:321
GroupingSetKind kind
Definition: parsenodes.h:1171
NodeTag type
Definition: nodes.h:510
void check_stack_depth(void)
Definition: postgres.c:3096
static Node * flatten_grouping_sets(Node *expr, bool toplevel, bool *hasGroupingSets)
Definition: nodes.h:295
List * lappend(List *list, void *datum)
Definition: list.c:128
#define NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
GroupingSet * makeGroupingSet(GroupingSetKind kind, List *content, int location)
Definition: makefuncs.c:604
CoercionForm row_format
Definition: primnodes.h:974
Definition: pg_list.h:45
static int get_matching_location ( int  sortgroupref,
List sortgrouprefs,
List exprs 
)
static

Definition at line 2692 of file parse_clause.c.

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

Referenced by transformDistinctOnClause().

2693 {
2694  ListCell *lcs;
2695  ListCell *lce;
2696 
2697  forboth(lcs, sortgrouprefs, lce, exprs)
2698  {
2699  if (lfirst_int(lcs) == sortgroupref)
2700  return exprLocation((Node *) lfirst(lce));
2701  }
2702  /* if no match, caller blew it */
2703  elog(ERROR, "get_matching_location: no matching sortgroupref");
2704  return -1; /* keep compiler quiet */
2705 }
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:174
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1204
Definition: nodes.h:508
#define ERROR
Definition: elog.h:43
#define lfirst_int(lc)
Definition: pg_list.h:107
#define lfirst(lc)
Definition: pg_list.h:106
#define elog
Definition: elog.h:219
bool interpretOidsOption ( List defList,
bool  allowOids 
)

Definition at line 241 of file parse_clause.c.

References default_with_oids, defGetBoolean(), DefElem::defname, DefElem::defnamespace, ereport, errcode(), errmsg(), ERROR, lfirst, NULL, and pg_strcasecmp().

Referenced by DefineRelation(), GetIntoRelEFlags(), and transformCreateStmt().

242 {
243  ListCell *cell;
244 
245  /* Scan list to see if OIDS was included */
246  foreach(cell, defList)
247  {
248  DefElem *def = (DefElem *) lfirst(cell);
249 
250  if (def->defnamespace == NULL &&
251  pg_strcasecmp(def->defname, "oids") == 0)
252  {
253  if (!allowOids)
254  ereport(ERROR,
255  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
256  errmsg("unrecognized parameter \"%s\"",
257  def->defname)));
258  return defGetBoolean(def);
259  }
260  }
261 
262  /* Force no-OIDS result if caller disallows OIDS. */
263  if (!allowOids)
264  return false;
265 
266  /* OIDS option was not specified, so use default. */
267  return default_with_oids;
268 }
char * defnamespace
Definition: parsenodes.h:674
int errcode(int sqlerrcode)
Definition: elog.c:575
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
bool default_with_oids
Definition: guc.c:450
bool defGetBoolean(DefElem *def)
Definition: define.c:111
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
#define NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * defname
Definition: parsenodes.h:675
static ParseNamespaceItem * makeNamespaceItem ( RangeTblEntry rte,
bool  rel_visible,
bool  cols_visible,
bool  lateral_only,
bool  lateral_ok 
)
static

Definition at line 1371 of file parse_clause.c.

References ParseNamespaceItem::p_cols_visible, ParseNamespaceItem::p_lateral_ok, ParseNamespaceItem::p_lateral_only, ParseNamespaceItem::p_rel_visible, ParseNamespaceItem::p_rte, and palloc().

1373 {
1374  ParseNamespaceItem *nsitem;
1375 
1376  nsitem = (ParseNamespaceItem *) palloc(sizeof(ParseNamespaceItem));
1377  nsitem->p_rte = rte;
1378  nsitem->p_rel_visible = rel_visible;
1379  nsitem->p_cols_visible = cols_visible;
1380  nsitem->p_lateral_only = lateral_only;
1381  nsitem->p_lateral_ok = lateral_ok;
1382  return nsitem;
1383 }
RangeTblEntry * p_rte
Definition: parse_node.h:238
void * palloc(Size size)
Definition: mcxt.c:891
static List * resolve_unique_index_expr ( ParseState pstate,
InferClause infer,
Relation  heapRel 
)
static

Definition at line 2717 of file parse_clause.c.

References BTREE_AM_OID, 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, InferClause::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().

2719 {
2720  List *result = NIL;
2721  ListCell *l;
2722 
2723  foreach(l, infer->indexElems)
2724  {
2725  IndexElem *ielem = (IndexElem *) lfirst(l);
2727  Node *parse;
2728 
2729  /*
2730  * Raw grammar re-uses CREATE INDEX infrastructure for unique index
2731  * inference clause, and so will accept opclasses by name and so on.
2732  *
2733  * Make no attempt to match ASC or DESC ordering or NULLS FIRST/NULLS
2734  * LAST ordering, since those are not significant for inference
2735  * purposes (any unique index matching the inference specification in
2736  * other regards is accepted indifferently). Actively reject this as
2737  * wrong-headed.
2738  */
2739  if (ielem->ordering != SORTBY_DEFAULT)
2740  ereport(ERROR,
2741  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2742  errmsg("ASC/DESC is not allowed in ON CONFLICT clause"),
2743  parser_errposition(pstate,
2744  exprLocation((Node *) infer))));
2745  if (ielem->nulls_ordering != SORTBY_NULLS_DEFAULT)
2746  ereport(ERROR,
2747  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2748  errmsg("NULLS FIRST/LAST is not allowed in ON CONFLICT clause"),
2749  parser_errposition(pstate,
2750  exprLocation((Node *) infer))));
2751 
2752  if (!ielem->expr)
2753  {
2754  /* Simple index attribute */
2755  ColumnRef *n;
2756 
2757  /*
2758  * Grammar won't have built raw expression for us in event of
2759  * plain column reference. Create one directly, and perform
2760  * expression transformation. Planner expects this, and performs
2761  * its own normalization for the purposes of matching against
2762  * pg_index.
2763  */
2764  n = makeNode(ColumnRef);
2765  n->fields = list_make1(makeString(ielem->name));
2766  /* Location is approximately that of inference specification */
2767  n->location = infer->location;
2768  parse = (Node *) n;
2769  }
2770  else
2771  {
2772  /* Do parse transformation of the raw expression */
2773  parse = (Node *) ielem->expr;
2774  }
2775 
2776  /*
2777  * transformExpr() should have already rejected subqueries,
2778  * aggregates, and window functions, based on the EXPR_KIND_ for an
2779  * index expression. Expressions returning sets won't have been
2780  * rejected, but don't bother doing so here; there should be no
2781  * available expression unique index to match any such expression
2782  * against anyway.
2783  */
2784  pInfer->expr = transformExpr(pstate, parse, EXPR_KIND_INDEX_EXPRESSION);
2785 
2786  /* Perform lookup of collation and operator class as required */
2787  if (!ielem->collation)
2788  pInfer->infercollid = InvalidOid;
2789  else
2790  pInfer->infercollid = LookupCollation(pstate, ielem->collation,
2791  exprLocation(pInfer->expr));
2792 
2793  if (!ielem->opclass)
2794  pInfer->inferopclass = InvalidOid;
2795  else
2797  ielem->opclass, false);
2798 
2799  result = lappend(result, pInfer);
2800  }
2801 
2802  return result;
2803 }
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:69
SortByDir ordering
Definition: parsenodes.h:649
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1204
#define BTREE_AM_OID
Definition: pg_am.h:70
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:147
List * indexElems
Definition: parsenodes.h:1249
Definition: nodes.h:508
int errcode(int sqlerrcode)
Definition: elog.c:575
Oid get_opclass_oid(Oid amID, List *opclassname, bool missing_ok)
Definition: opclasscmds.c:220
int location
Definition: parsenodes.h:227
#define list_make1(x1)
Definition: pg_list.h:133
Node * expr
Definition: parsenodes.h:645
SortByNulls nulls_ordering
Definition: parsenodes.h:650
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
Oid LookupCollation(ParseState *pstate, List *collnames, int location)
Definition: parse_type.c:496
#define InvalidOid
Definition: postgres_ext.h:36
List * opclass
Definition: parsenodes.h:648
#define makeNode(_type_)
Definition: nodes.h:556
#define lfirst(lc)
Definition: pg_list.h:106
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:109
char * name
Definition: parsenodes.h:644
int errmsg(const char *fmt,...)
Definition: elog.c:797
List * collation
Definition: parsenodes.h:647
Definition: pg_list.h:45
List * fields
Definition: parsenodes.h:226
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:651
static void setNamespaceColumnVisibility ( List namespace,
bool  cols_visible 
)
static

Definition at line 1390 of file parse_clause.c.

References lfirst, and ParseNamespaceItem::p_cols_visible.

Referenced by transformFromClauseItem().

1391 {
1392  ListCell *lc;
1393 
1394  foreach(lc, namespace)
1395  {
1396  ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(lc);
1397 
1398  nsitem->p_cols_visible = cols_visible;
1399  }
1400 }
#define lfirst(lc)
Definition: pg_list.h:106
static void setNamespaceLateralState ( List namespace,
bool  lateral_only,
bool  lateral_ok 
)
static

Definition at line 1407 of file parse_clause.c.

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

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

1408 {
1409  ListCell *lc;
1410 
1411  foreach(lc, namespace)
1412  {
1413  ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(lc);
1414 
1415  nsitem->p_lateral_only = lateral_only;
1416  nsitem->p_lateral_ok = lateral_ok;
1417  }
1418 }
#define lfirst(lc)
Definition: pg_list.h:106
int setTargetTable ( ParseState pstate,
RangeVar relation,
bool  inh,
bool  alsoSource,
AclMode  requiredPerms 
)

Definition at line 175 of file parse_clause.c.

References addRangeTableEntryForRelation(), addRTEtoQuery(), RangeVar::alias, Assert, heap_close, list_length(), NoLock, NULL, ParseState::p_rtable, ParseState::p_target_rangetblentry, ParseState::p_target_relation, parserOpenTable(), RangeTblEntry::requiredPerms, RowExclusiveLock, and rt_fetch.

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

177 {
178  RangeTblEntry *rte;
179  int rtindex;
180 
181  /* Close old target; this could only happen for multi-action rules */
182  if (pstate->p_target_relation != NULL)
184 
185  /*
186  * Open target rel and grab suitable lock (which we will hold till end of
187  * transaction).
188  *
189  * free_parsestate() will eventually do the corresponding heap_close(),
190  * but *not* release the lock.
191  */
192  pstate->p_target_relation = parserOpenTable(pstate, relation,
194 
195  /*
196  * Now build an RTE.
197  */
198  rte = addRangeTableEntryForRelation(pstate, pstate->p_target_relation,
199  relation->alias, inh, false);
200  pstate->p_target_rangetblentry = rte;
201 
202  /* assume new rte is at end */
203  rtindex = list_length(pstate->p_rtable);
204  Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
205 
206  /*
207  * Override addRangeTableEntry's default ACL_SELECT permissions check, and
208  * instead mark target table as requiring exactly the specified
209  * permissions.
210  *
211  * If we find an explicit reference to the rel later during parse
212  * analysis, we will add the ACL_SELECT bit back again; see
213  * markVarForSelectPriv and its callers.
214  */
215  rte->requiredPerms = requiredPerms;
216 
217  /*
218  * If UPDATE/DELETE, add table to joinlist and namespace.
219  *
220  * Note: some callers know that they can find the new ParseNamespaceItem
221  * at the end of the pstate->p_namespace list. This is a bit ugly but not
222  * worth complicating this function's signature for.
223  */
224  if (alsoSource)
225  addRTEtoQuery(pstate, rte, true, true, true);
226 
227  return rtindex;
228 }
Relation parserOpenTable(ParseState *pstate, const RangeVar *relation, int lockmode)
AclMode requiredPerms
Definition: parsenodes.h:965
#define heap_close(r, l)
Definition: heapam.h:97
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
void addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
RangeTblEntry * p_target_rangetblentry
Definition: parse_node.h:179
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
static int list_length(const List *l)
Definition: pg_list.h:89
RangeTblEntry * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, Alias *alias, bool inh, bool inFromCl)
Relation p_target_relation
Definition: parse_node.h:178
Alias * alias
Definition: primnodes.h:71
List * p_rtable
Definition: parse_node.h:168
bool targetIsInSortList ( TargetEntry tle,
Oid  sortop,
List sortList 
)

Definition at line 3144 of file parse_clause.c.

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

3145 {
3146  Index ref = tle->ressortgroupref;
3147  ListCell *l;
3148 
3149  /* no need to scan list if tle has no marker */
3150  if (ref == 0)
3151  return false;
3152 
3153  foreach(l, sortList)
3154  {
3155  SortGroupClause *scl = (SortGroupClause *) lfirst(l);
3156 
3157  if (scl->tleSortGroupRef == ref &&
3158  (sortop == InvalidOid ||
3159  sortop == scl->sortop ||
3160  sortop == get_commutator(scl->sortop)))
3161  return true;
3162  }
3163  return false;
3164 }
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1281
Index tleSortGroupRef
Definition: parsenodes.h:1102
unsigned int Index
Definition: c.h:362
#define InvalidOid
Definition: postgres_ext.h:36
#define lfirst(lc)
Definition: pg_list.h:106
Index ressortgroupref
Definition: primnodes.h:1333
static RangeTblEntry * transformCTEReference ( ParseState pstate,
RangeVar r,
CommonTableExpr cte,
Index  levelsup 
)
static

Definition at line 424 of file parse_clause.c.

References addRangeTableEntryForCTE().

Referenced by transformFromClauseItem().

426 {
427  RangeTblEntry *rte;
428 
429  rte = addRangeTableEntryForCTE(pstate, cte, levelsup, r, true);
430 
431  return rte;
432 }
RangeTblEntry * addRangeTableEntryForCTE(ParseState *pstate, CommonTableExpr *cte, Index levelsup, RangeVar *rv, bool inFromCl)
List* transformDistinctClause ( ParseState pstate,
List **  targetlist,
List sortClause,
bool  is_agg 
)

Definition at line 2501 of file parse_clause.c.

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

Referenced by transformAggregateCall(), and transformSelectStmt().

2503 {
2504  List *result = NIL;
2505  ListCell *slitem;
2506  ListCell *tlitem;
2507 
2508  /*
2509  * The distinctClause should consist of all ORDER BY items followed by all
2510  * other non-resjunk targetlist items. There must not be any resjunk
2511  * ORDER BY items --- that would imply that we are sorting by a value that
2512  * isn't necessarily unique within a DISTINCT group, so the results
2513  * wouldn't be well-defined. This construction ensures we follow the rule
2514  * that sortClause and distinctClause match; in fact the sortClause will
2515  * always be a prefix of distinctClause.
2516  *
2517  * Note a corner case: the same TLE could be in the ORDER BY list multiple
2518  * times with different sortops. We have to include it in the
2519  * distinctClause the same way to preserve the prefix property. The net
2520  * effect will be that the TLE value will be made unique according to both
2521  * sortops.
2522  */
2523  foreach(slitem, sortClause)
2524  {
2525  SortGroupClause *scl = (SortGroupClause *) lfirst(slitem);
2526  TargetEntry *tle = get_sortgroupclause_tle(scl, *targetlist);
2527 
2528  if (tle->resjunk)
2529  ereport(ERROR,
2530  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2531  is_agg ?
2532  errmsg("in an aggregate with DISTINCT, ORDER BY expressions must appear in argument list") :
2533  errmsg("for SELECT DISTINCT, ORDER BY expressions must appear in select list"),
2534  parser_errposition(pstate,
2535  exprLocation((Node *) tle->expr))));
2536  result = lappend(result, copyObject(scl));
2537  }
2538 
2539  /*
2540  * Now add any remaining non-resjunk tlist items, using default sort/group
2541  * semantics for their data types.
2542  */
2543  foreach(tlitem, *targetlist)
2544  {
2545  TargetEntry *tle = (TargetEntry *) lfirst(tlitem);
2546 
2547  if (tle->resjunk)
2548  continue; /* ignore junk */
2549  result = addTargetToGroupList(pstate, tle,
2550  result, *targetlist,
2551  exprLocation((Node *) tle->expr));
2552  }
2553 
2554  /*
2555  * Complain if we found nothing to make DISTINCT. Returning an empty list
2556  * would cause the parsed Query to look like it didn't have DISTINCT, with
2557  * results that would probably surprise the user. Note: this case is
2558  * presently impossible for aggregates because of grammar restrictions,
2559  * but we check anyway.
2560  */
2561  if (result == NIL)
2562  ereport(ERROR,
2563  (errcode(ERRCODE_SYNTAX_ERROR),
2564  is_agg ?
2565  errmsg("an aggregate with DISTINCT must have at least one argument") :
2566  errmsg("SELECT DISTINCT must have at least one column")));
2567 
2568  return result;
2569 }
#define NIL
Definition: pg_list.h:69
static List * addTargetToGroupList(ParseState *pstate, TargetEntry *tle, List *grouplist, List *targetlist, int location)
TargetEntry * get_sortgroupclause_tle(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:370
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1204
Definition: nodes.h:508
int errcode(int sqlerrcode)
Definition: elog.c:575
void * copyObject(const void *from)
Definition: copyfuncs.c:4475
bool resjunk
Definition: primnodes.h:1337
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
#define lfirst(lc)
Definition: pg_list.h:106
Expr * expr
Definition: primnodes.h:1330
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:109
int errmsg(const char *fmt,...)
Definition: elog.c:797
Definition: pg_list.h:45
List* transformDistinctOnClause ( ParseState pstate,
List distinctlist,
List **  targetlist,
List sortClause 
)

Definition at line 2585 of file parse_clause.c.

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

2587 {
2588  List *result = NIL;
2589  List *sortgrouprefs = NIL;
2590  bool skipped_sortitem;
2591  ListCell *lc;
2592  ListCell *lc2;
2593 
2594  /*
2595  * Add all the DISTINCT ON expressions to the tlist (if not already
2596  * present, they are added as resjunk items). Assign sortgroupref numbers
2597  * to them, and make a list of these numbers. (NB: we rely below on the
2598  * sortgrouprefs list being one-for-one with the original distinctlist.
2599  * Also notice that we could have duplicate DISTINCT ON expressions and
2600  * hence duplicate entries in sortgrouprefs.)
2601  */
2602  foreach(lc, distinctlist)
2603  {
2604  Node *dexpr = (Node *) lfirst(lc);
2605  int sortgroupref;
2606  TargetEntry *tle;
2607 
2608  tle = findTargetlistEntrySQL92(pstate, dexpr, targetlist,
2610  sortgroupref = assignSortGroupRef(tle, *targetlist);
2611  sortgrouprefs = lappend_int(sortgrouprefs, sortgroupref);
2612  }
2613 
2614  /*
2615  * If the user writes both DISTINCT ON and ORDER BY, adopt the sorting
2616  * semantics from ORDER BY items that match DISTINCT ON items, and also
2617  * adopt their column sort order. We insist that the distinctClause and
2618  * sortClause match, so throw error if we find the need to add any more
2619  * distinctClause items after we've skipped an ORDER BY item that wasn't
2620  * in DISTINCT ON.
2621  */
2622  skipped_sortitem = false;
2623  foreach(lc, sortClause)
2624  {
2625  SortGroupClause *scl = (SortGroupClause *) lfirst(lc);
2626 
2627  if (list_member_int(sortgrouprefs, scl->tleSortGroupRef))
2628  {
2629  if (skipped_sortitem)
2630  ereport(ERROR,
2631  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2632  errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
2633  parser_errposition(pstate,
2635  sortgrouprefs,
2636  distinctlist))));
2637  else
2638  result = lappend(result, copyObject(scl));
2639  }
2640  else
2641  skipped_sortitem = true;
2642  }
2643 
2644  /*
2645  * Now add any remaining DISTINCT ON items, using default sort/group
2646  * semantics for their data types. (Note: this is pretty questionable; if
2647  * the ORDER BY list doesn't include all the DISTINCT ON items and more
2648  * besides, you certainly aren't using DISTINCT ON in the intended way,
2649  * and you probably aren't going to get consistent results. It might be
2650  * better to throw an error or warning here. But historically we've
2651  * allowed it, so keep doing so.)
2652  */
2653  forboth(lc, distinctlist, lc2, sortgrouprefs)
2654  {
2655  Node *dexpr = (Node *) lfirst(lc);
2656  int sortgroupref = lfirst_int(lc2);
2657  TargetEntry *tle = get_sortgroupref_tle(sortgroupref, *targetlist);
2658 
2659  if (targetIsInSortList(tle, InvalidOid, result))
2660  continue; /* already in list (with some semantics) */
2661  if (skipped_sortitem)
2662  ereport(ERROR,
2663  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2664  errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
2665  parser_errposition(pstate, exprLocation(dexpr))));
2666  result = addTargetToGroupList(pstate, tle,
2667  result, *targetlist,
2668  exprLocation(dexpr));
2669  }
2670 
2671  /*
2672  * An empty result list is impossible here because of grammar
2673  * restrictions.
2674  */
2675  Assert(result != NIL);
2676 
2677  return result;
2678 }
#define NIL
Definition: pg_list.h:69
static List * addTargetToGroupList(ParseState *pstate, TargetEntry *tle, List *grouplist, List *targetlist, int location)
Index assignSortGroupRef(TargetEntry *tle, List *tlist)
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:174
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1204
Index tleSortGroupRef
Definition: parsenodes.h:1102
Definition: nodes.h:508
int errcode(int sqlerrcode)
Definition: elog.c:575
void * copyObject(const void *from)
Definition: copyfuncs.c:4475
static int get_matching_location(int sortgroupref, List *sortgrouprefs, List *exprs)
#define ERROR
Definition: elog.h:43
#define lfirst_int(lc)
Definition: pg_list.h:107
bool list_member_int(const List *list, int datum)
Definition: list.c:485
#define ereport(elevel, rest)
Definition: elog.h:122
TargetEntry * get_sortgroupref_tle(Index sortref, List *targetList)
Definition: tlist.c:348
List * lappend_int(List *list, int datum)
Definition: list.c:146
List * lappend(List *list, void *datum)
Definition: list.c:128
#define InvalidOid
Definition: postgres_ext.h:36
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
#define Assert(condition)
Definition: c.h:671
#define lfirst(lc)
Definition: pg_list.h:106
static TargetEntry * findTargetlistEntrySQL92(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:109
int errmsg(const char *fmt,...)
Definition: elog.c:797
Definition: pg_list.h:45
static Node * transformFrameOffset ( ParseState pstate,
int  frameOptions,
Node clause 
)
static

Definition at line 3191 of file parse_clause.c.

References Assert, checkExprIsVarFree(), coerce_to_specific_type(), elog, ERROR, EXPR_KIND_WINDOW_FRAME_RANGE, EXPR_KIND_WINDOW_FRAME_ROWS, FRAMEOPTION_RANGE, FRAMEOPTION_ROWS, INT8OID, NULL, and transformExpr().

Referenced by transformWindowDefinitions().

3192 {
3193  const char *constructName = NULL;
3194  Node *node;
3195 
3196  /* Quick exit if no offset expression */
3197  if (clause == NULL)
3198  return NULL;
3199 
3200  if (frameOptions & FRAMEOPTION_ROWS)
3201  {
3202  /* Transform the raw expression tree */
3203  node = transformExpr(pstate, clause, EXPR_KIND_WINDOW_FRAME_ROWS);
3204 
3205  /*
3206  * Like LIMIT clause, simply coerce to int8
3207  */
3208  constructName = "ROWS";
3209  node = coerce_to_specific_type(pstate, node, INT8OID, constructName);
3210  }
3211  else if (frameOptions & FRAMEOPTION_RANGE)
3212  {
3213  /* Transform the raw expression tree */
3214  node = transformExpr(pstate, clause, EXPR_KIND_WINDOW_FRAME_RANGE);
3215 
3216  /*
3217  * this needs a lot of thought to decide how to support in the context
3218  * of Postgres' extensible datatype framework
3219  */
3220  constructName = "RANGE";
3221  /* error was already thrown by gram.y, this is just a backstop */
3222  elog(ERROR, "window frame with value offset is not implemented");
3223  }
3224  else
3225  {
3226  Assert(false);
3227  node = NULL;
3228  }
3229 
3230  /* Disallow variables in frame offsets */
3231  checkExprIsVarFree(pstate, node, constructName);
3232 
3233  return node;
3234 }
static void checkExprIsVarFree(ParseState *pstate, Node *n, const char *constructName)
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:147
Definition: nodes.h:508
#define ERROR
Definition: elog.h:43
#define INT8OID
Definition: pg_type.h:304
#define NULL
Definition: c.h:226
#define FRAMEOPTION_RANGE
Definition: parsenodes.h:497
#define Assert(condition)
Definition: c.h:671
#define FRAMEOPTION_ROWS
Definition: parsenodes.h:498
Node * coerce_to_specific_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *constructName)
#define elog
Definition: elog.h:219
void transformFromClause ( ParseState pstate,
List frmList 
)

Definition at line 109 of file parse_clause.c.

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

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

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

Definition at line 821 of file parse_clause.c.

References addRangeTableEntryForJoin(), JoinExpr::alias, Alias::aliasname, Assert, buildMergedJoinVar(), castNode, checkNameSpaceConflicts(), Alias::colnames, elog, ereport, errcode(), errmsg(), ERROR, expandRTE(), exprLocation(), extractRemainingColumns(), IsA, JoinExpr::isNatural, JOIN_INNER, JOIN_LEFT, JoinExpr::jointype, lappend(), JoinExpr::larg, lfirst, list_concat(), list_length(), list_make1, list_nth(), list_truncate(), makeNode, makeString(), NIL, nodeTag, NULL, ParseState::p_joinexprs, ParseState::p_namespace, ParseState::p_rtable, parser_errposition(), JoinExpr::quals, JoinExpr::rarg, RangeTableSample::relation, RangeTblEntry::relkind, RELKIND_MATVIEW, RELKIND_PARTITIONED_TABLE, RELKIND_RELATION, RangeVar::relname, rt_fetch, RangeTblRef::rtindex, JoinExpr::rtindex, scanNameSpaceForCTE(), RangeVar::schemaname, setNamespaceColumnVisibility(), setNamespaceLateralState(), strVal, RangeTblEntry::tablesample, transformCTEReference(), transformJoinOnClause(), transformJoinUsingClause(), transformRangeFunction(), transformRangeSubselect(), transformRangeTableSample(), transformTableEntry(), and JoinExpr::usingClause.

Referenced by transformFromClause().

824 {
825  if (IsA(n, RangeVar))
826  {
827  /* Plain relation reference, or perhaps a CTE reference */
828  RangeVar *rv = (RangeVar *) n;
829  RangeTblRef *rtr;
830  RangeTblEntry *rte = NULL;
831  int rtindex;
832 
833  /* if it is an unqualified name, it might be a CTE reference */
834  if (!rv->schemaname)
835  {
836  CommonTableExpr *cte;
837  Index levelsup;
838 
839  cte = scanNameSpaceForCTE(pstate, rv->relname, &levelsup);
840  if (cte)
841  rte = transformCTEReference(pstate, rv, cte, levelsup);
842  }
843 
844  /* if not found as a CTE, must be a table reference */
845  if (!rte)
846  rte = transformTableEntry(pstate, rv);
847 
848  /* assume new rte is at end */
849  rtindex = list_length(pstate->p_rtable);
850  Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
851  *top_rte = rte;
852  *top_rti = rtindex;
853  *namespace = list_make1(makeDefaultNSItem(rte));
854  rtr = makeNode(RangeTblRef);
855  rtr->rtindex = rtindex;
856  return (Node *) rtr;
857  }
858  else if (IsA(n, RangeSubselect))
859  {
860  /* sub-SELECT is like a plain relation */
861  RangeTblRef *rtr;
862  RangeTblEntry *rte;
863  int rtindex;
864 
865  rte = transformRangeSubselect(pstate, (RangeSubselect *) n);
866  /* assume new rte is at end */
867  rtindex = list_length(pstate->p_rtable);
868  Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
869  *top_rte = rte;
870  *top_rti = rtindex;
871  *namespace = list_make1(makeDefaultNSItem(rte));
872  rtr = makeNode(RangeTblRef);
873  rtr->rtindex = rtindex;
874  return (Node *) rtr;
875  }
876  else if (IsA(n, RangeFunction))
877  {
878  /* function is like a plain relation */
879  RangeTblRef *rtr;
880  RangeTblEntry *rte;
881  int rtindex;
882 
883  rte = transformRangeFunction(pstate, (RangeFunction *) n);
884  /* assume new rte is at end */
885  rtindex = list_length(pstate->p_rtable);
886  Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
887  *top_rte = rte;
888  *top_rti = rtindex;
889  *namespace = list_make1(makeDefaultNSItem(rte));
890  rtr = makeNode(RangeTblRef);
891  rtr->rtindex = rtindex;
892  return (Node *) rtr;
893  }
894  else if (IsA(n, RangeTableSample))
895  {
896  /* TABLESAMPLE clause (wrapping some other valid FROM node) */
897  RangeTableSample *rts = (RangeTableSample *) n;
898  Node *rel;
899  RangeTblRef *rtr;
900  RangeTblEntry *rte;
901 
902  /* Recursively transform the contained relation */
903  rel = transformFromClauseItem(pstate, rts->relation,
904  top_rte, top_rti, namespace);
905  /* Currently, grammar could only return a RangeVar as contained rel */
906  rtr = castNode(RangeTblRef, rel);
907  rte = rt_fetch(rtr->rtindex, pstate->p_rtable);
908  /* We only support this on plain relations and matviews */
909  if (rte->relkind != RELKIND_RELATION &&
910  rte->relkind != RELKIND_MATVIEW &&
912  ereport(ERROR,
913  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
914  errmsg("TABLESAMPLE clause can only be applied to tables and materialized views"),
915  parser_errposition(pstate, exprLocation(rts->relation))));
916 
917  /* Transform TABLESAMPLE details and attach to the RTE */
918  rte->tablesample = transformRangeTableSample(pstate, rts);
919  return (Node *) rtr;
920  }
921  else if (IsA(n, JoinExpr))
922  {
923  /* A newfangled join expression */
924  JoinExpr *j = (JoinExpr *) n;
925  RangeTblEntry *l_rte;
926  RangeTblEntry *r_rte;
927  int l_rtindex;
928  int r_rtindex;
929  List *l_namespace,
930  *r_namespace,
931  *my_namespace,
932  *l_colnames,
933  *r_colnames,
934  *res_colnames,
935  *l_colvars,
936  *r_colvars,
937  *res_colvars;
938  bool lateral_ok;
939  int sv_namespace_length;
940  RangeTblEntry *rte;
941  int k;
942 
943  /*
944  * Recursively process the left subtree, then the right. We must do
945  * it in this order for correct visibility of LATERAL references.
946  */
947  j->larg = transformFromClauseItem(pstate, j->larg,
948  &l_rte,
949  &l_rtindex,
950  &l_namespace);
951 
952  /*
953  * Make the left-side RTEs available for LATERAL access within the
954  * right side, by temporarily adding them to the pstate's namespace
955  * list. Per SQL:2008, if the join type is not INNER or LEFT then the
956  * left-side names must still be exposed, but it's an error to
957  * reference them. (Stupid design, but that's what it says.) Hence,
958  * we always push them into the namespace, but mark them as not
959  * lateral_ok if the jointype is wrong.
960  *
961  * Notice that we don't require the merged namespace list to be
962  * conflict-free. See the comments for scanNameSpaceForRefname().
963  *
964  * NB: this coding relies on the fact that list_concat is not
965  * destructive to its second argument.
966  */
967  lateral_ok = (j->jointype == JOIN_INNER || j->jointype == JOIN_LEFT);
968  setNamespaceLateralState(l_namespace, true, lateral_ok);
969 
970  sv_namespace_length = list_length(pstate->p_namespace);
971  pstate->p_namespace = list_concat(pstate->p_namespace, l_namespace);
972 
973  /* And now we can process the RHS */
974  j->rarg = transformFromClauseItem(pstate, j->rarg,
975  &r_rte,
976  &r_rtindex,
977  &r_namespace);
978 
979  /* Remove the left-side RTEs from the namespace list again */
980  pstate->p_namespace = list_truncate(pstate->p_namespace,
981  sv_namespace_length);
982 
983  /*
984  * Check for conflicting refnames in left and right subtrees. Must do
985  * this because higher levels will assume I hand back a self-
986  * consistent namespace list.
987  */
988  checkNameSpaceConflicts(pstate, l_namespace, r_namespace);
989 
990  /*
991  * Generate combined namespace info for possible use below.
992  */
993  my_namespace = list_concat(l_namespace, r_namespace);
994 
995  /*
996  * Extract column name and var lists from both subtrees
997  *
998  * Note: expandRTE returns new lists, safe for me to modify
999  */
1000  expandRTE(l_rte, l_rtindex, 0, -1, false,
1001  &l_colnames, &l_colvars);
1002  expandRTE(r_rte, r_rtindex, 0, -1, false,
1003  &r_colnames, &r_colvars);
1004 
1005  /*
1006  * Natural join does not explicitly specify columns; must generate
1007  * columns to join. Need to run through the list of columns from each
1008  * table or join result and match up the column names. Use the first
1009  * table, and check every column in the second table for a match.
1010  * (We'll check that the matches were unique later on.) The result of
1011  * this step is a list of column names just like an explicitly-written
1012  * USING list.
1013  */
1014  if (j->isNatural)
1015  {
1016  List *rlist = NIL;
1017  ListCell *lx,
1018  *rx;
1019 
1020  Assert(j->usingClause == NIL); /* shouldn't have USING() too */
1021 
1022  foreach(lx, l_colnames)
1023  {
1024  char *l_colname = strVal(lfirst(lx));
1025  Value *m_name = NULL;
1026 
1027  foreach(rx, r_colnames)
1028  {
1029  char *r_colname = strVal(lfirst(rx));
1030 
1031  if (strcmp(l_colname, r_colname) == 0)
1032  {
1033  m_name = makeString(l_colname);
1034  break;
1035  }
1036  }
1037 
1038  /* matched a right column? then keep as join column... */
1039  if (m_name != NULL)
1040  rlist = lappend(rlist, m_name);
1041  }
1042 
1043  j->usingClause = rlist;
1044  }
1045 
1046  /*
1047  * Now transform the join qualifications, if any.
1048  */
1049  res_colnames = NIL;
1050  res_colvars = NIL;
1051 
1052  if (j->usingClause)
1053  {
1054  /*
1055  * JOIN/USING (or NATURAL JOIN, as transformed above). Transform
1056  * the list into an explicit ON-condition, and generate a list of
1057  * merged result columns.
1058  */
1059  List *ucols = j->usingClause;
1060  List *l_usingvars = NIL;
1061  List *r_usingvars = NIL;
1062  ListCell *ucol;
1063 
1064  Assert(j->quals == NULL); /* shouldn't have ON() too */
1065 
1066  foreach(ucol, ucols)
1067  {
1068  char *u_colname = strVal(lfirst(ucol));
1069  ListCell *col;
1070  int ndx;
1071  int l_index = -1;
1072  int r_index = -1;
1073  Var *l_colvar,
1074  *r_colvar;
1075 
1076  /* Check for USING(foo,foo) */
1077  foreach(col, res_colnames)
1078  {
1079  char *res_colname = strVal(lfirst(col));
1080 
1081  if (strcmp(res_colname, u_colname) == 0)
1082  ereport(ERROR,
1083  (errcode(ERRCODE_DUPLICATE_COLUMN),
1084  errmsg("column name \"%s\" appears more than once in USING clause",
1085  u_colname)));
1086  }
1087 
1088  /* Find it in left input */
1089  ndx = 0;
1090  foreach(col, l_colnames)
1091  {
1092  char *l_colname = strVal(lfirst(col));
1093 
1094  if (strcmp(l_colname, u_colname) == 0)
1095  {
1096  if (l_index >= 0)
1097  ereport(ERROR,
1098  (errcode(ERRCODE_AMBIGUOUS_COLUMN),
1099  errmsg("common column name \"%s\" appears more than once in left table",
1100  u_colname)));
1101  l_index = ndx;
1102  }
1103  ndx++;
1104  }
1105  if (l_index < 0)
1106  ereport(ERROR,
1107  (errcode(ERRCODE_UNDEFINED_COLUMN),
1108  errmsg("column \"%s\" specified in USING clause does not exist in left table",
1109  u_colname)));
1110 
1111  /* Find it in right input */
1112  ndx = 0;
1113  foreach(col, r_colnames)
1114  {
1115  char *r_colname = strVal(lfirst(col));
1116 
1117  if (strcmp(r_colname, u_colname) == 0)
1118  {
1119  if (r_index >= 0)
1120  ereport(ERROR,
1121  (errcode(ERRCODE_AMBIGUOUS_COLUMN),
1122  errmsg("common column name \"%s\" appears more than once in right table",
1123  u_colname)));
1124  r_index = ndx;
1125  }
1126  ndx++;
1127  }
1128  if (r_index < 0)
1129  ereport(ERROR,
1130  (errcode(ERRCODE_UNDEFINED_COLUMN),
1131  errmsg("column \"%s\" specified in USING clause does not exist in right table",
1132  u_colname)));
1133 
1134  l_colvar = list_nth(l_colvars, l_index);
1135  l_usingvars = lappend(l_usingvars, l_colvar);
1136  r_colvar = list_nth(r_colvars, r_index);
1137  r_usingvars = lappend(r_usingvars, r_colvar);
1138 
1139  res_colnames = lappend(res_colnames, lfirst(ucol));
1140  res_colvars = lappend(res_colvars,
1141  buildMergedJoinVar(pstate,
1142  j->jointype,
1143  l_colvar,
1144  r_colvar));
1145  }
1146 
1147  j->quals = transformJoinUsingClause(pstate,
1148  l_rte,
1149  r_rte,
1150  l_usingvars,
1151  r_usingvars);
1152  }
1153  else if (j->quals)
1154  {
1155  /* User-written ON-condition; transform it */
1156  j->quals = transformJoinOnClause(pstate, j, my_namespace);
1157  }
1158  else
1159  {
1160  /* CROSS JOIN: no quals */
1161  }
1162 
1163  /* Add remaining columns from each side to the output columns */
1164  extractRemainingColumns(res_colnames,
1165  l_colnames, l_colvars,
1166  &l_colnames, &l_colvars);
1167  extractRemainingColumns(res_colnames,
1168  r_colnames, r_colvars,
1169  &r_colnames, &r_colvars);
1170  res_colnames = list_concat(res_colnames, l_colnames);
1171  res_colvars = list_concat(res_colvars, l_colvars);
1172  res_colnames = list_concat(res_colnames, r_colnames);
1173  res_colvars = list_concat(res_colvars, r_colvars);
1174 
1175  /*
1176  * Check alias (AS clause), if any.
1177  */
1178  if (j->alias)
1179  {
1180  if (j->alias->colnames != NIL)
1181  {
1182  if (list_length(j->alias->colnames) > list_length(res_colnames))
1183  ereport(ERROR,
1184  (errcode(ERRCODE_SYNTAX_ERROR),
1185  errmsg("column alias list for \"%s\" has too many entries",
1186  j->alias->aliasname)));
1187  }
1188  }
1189 
1190  /*
1191  * Now build an RTE for the result of the join
1192  */
1193  rte = addRangeTableEntryForJoin(pstate,
1194  res_colnames,
1195  j->jointype,
1196  res_colvars,
1197  j->alias,
1198  true);
1199 
1200  /* assume new rte is at end */
1201  j->rtindex = list_length(pstate->p_rtable);
1202  Assert(rte == rt_fetch(j->rtindex, pstate->p_rtable));
1203 
1204  *top_rte = rte;
1205  *top_rti = j->rtindex;
1206 
1207  /* make a matching link to the JoinExpr for later use */
1208  for (k = list_length(pstate->p_joinexprs) + 1; k < j->rtindex; k++)
1209  pstate->p_joinexprs = lappend(pstate->p_joinexprs, NULL);
1210  pstate->p_joinexprs = lappend(pstate->p_joinexprs, j);
1211  Assert(list_length(pstate->p_joinexprs) == j->rtindex);
1212 
1213  /*
1214  * Prepare returned namespace list. If the JOIN has an alias then it
1215  * hides the contained RTEs completely; otherwise, the contained RTEs
1216  * are still visible as table names, but are not visible for
1217  * unqualified column-name access.
1218  *
1219  * Note: if there are nested alias-less JOINs, the lower-level ones
1220  * will remain in the list although they have neither p_rel_visible
1221  * nor p_cols_visible set. We could delete such list items, but it's
1222  * unclear that it's worth expending cycles to do so.
1223  */
1224  if (j->alias != NULL)
1225  my_namespace = NIL;
1226  else
1227  setNamespaceColumnVisibility(my_namespace, false);
1228 
1229  /*
1230  * The join RTE itself is always made visible for unqualified column
1231  * names. It's visible as a relation name only if it has an alias.
1232  */
1233  *namespace = lappend(my_namespace,
1234  makeNamespaceItem(rte,
1235  (j->alias != NULL),
1236  true,
1237  false,
1238  true));
1239 
1240  return (Node *) j;
1241  }
1242  else
1243  elog(ERROR, "unrecognized node type: %d", (int) nodeTag(n));
1244  return NULL; /* can't get here, keep compiler quiet */
1245 }
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1204
RangeTblEntry * addRangeTableEntryForJoin(ParseState *pstate, List *colnames, JoinType jointype, List *aliasvars, Alias *alias, bool inFromCl)
List * colnames
Definition: primnodes.h:42
#define castNode(_type_, nodeptr)
Definition: nodes.h:577
#define RELKIND_MATVIEW
Definition: pg_class.h:167
List * list_truncate(List *list, int new_size)
Definition: list.c:350
static Node * transformJoinUsingClause(ParseState *pstate, RangeTblEntry *leftRTE, RangeTblEntry *rightRTE, List *leftVars, List *rightVars)
Definition: parse_clause.c:319
Definition: nodes.h:508
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:575
List * list_concat(List *list1, List *list2)
Definition: list.c:321
Definition: primnodes.h:141
static void extractRemainingColumns(List *common_colnames, List *src_colnames, List *src_colvars, List **res_colnames, List **res_colvars)
Definition: parse_clause.c:274
char * schemaname
Definition: primnodes.h:66
Node * larg
Definition: primnodes.h:1413
#define list_make1(x1)
Definition: pg_list.h:133
char * relname
Definition: primnodes.h:67
#define ERROR
Definition: elog.h:43
static RangeTblEntry * transformRangeSubselect(ParseState *pstate, RangeSubselect *r)
Definition: parse_clause.c:438
static RangeTblEntry * transformTableEntry(ParseState *pstate, RangeVar *r)
Definition: parse_clause.c:409
List * p_namespace
Definition: parse_node.h:172
static void setNamespaceLateralState(List *namespace, bool lateral_only, bool lateral_ok)
void * list_nth(const List *list, int n)
Definition: list.c:410
#define makeDefaultNSItem(rte)
Definition: parse_clause.c:51
void checkNameSpaceConflicts(ParseState *pstate, List *namespace1, List *namespace2)
#define ereport(elevel, rest)
Definition: elog.h:122
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
List * lappend(List *list, void *datum)
Definition: list.c:128
bool isNatural
Definition: primnodes.h:1412
static Node * buildMergedJoinVar(ParseState *pstate, JoinType jointype, Var *l_colvar, Var *r_colvar)
List * usingClause
Definition: primnodes.h:1415
void expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up, int location, bool include_dropped, List **colnames, List **colvars)
static TableSampleClause * transformRangeTableSample(ParseState *pstate, RangeTableSample *rts)
Definition: parse_clause.c:702
static void setNamespaceColumnVisibility(List *namespace, bool cols_visible)
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
Node * quals
Definition: primnodes.h:1416
static RangeTblEntry * transformCTEReference(ParseState *pstate, RangeVar *r, CommonTableExpr *cte, Index levelsup)
Definition: parse_clause.c:424
unsigned int Index
Definition: c.h:362
CommonTableExpr * scanNameSpaceForCTE(ParseState *pstate, const char *refname, Index *ctelevelsup)
#define makeNode(_type_)
Definition: nodes.h:556
Node * rarg
Definition: primnodes.h:1414
Alias * alias
Definition: primnodes.h:1417
#define NULL
Definition: c.h:226
JoinType jointype
Definition: primnodes.h:1411
#define Assert(condition)
Definition: c.h:671
static RangeTblEntry * transformRangeFunction(ParseState *pstate, RangeFunction *r)
Definition: parse_clause.c:505
#define lfirst(lc)
Definition: pg_list.h:106
static Node * transformFromClauseItem(ParseState *pstate, Node *n, RangeTblEntry **top_rte, int *top_rti, List **namespace)
Definition: parse_clause.c:821
char * aliasname
Definition: primnodes.h:41
Definition: value.h:42
static int list_length(const List *l)
Definition: pg_list.h:89
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:109
#define nodeTag(nodeptr)
Definition: nodes.h:513
static ParseNamespaceItem * makeNamespaceItem(RangeTblEntry *rte, bool rel_visible, bool cols_visible, bool lateral_only, bool lateral_ok)
int errmsg(const char *fmt,...)
Definition: elog.c:797
static Node * transformJoinOnClause(ParseState *pstate, JoinExpr *j, List *namespace)
Definition: parse_clause.c:379
#define elog
Definition: elog.h:219
#define RELKIND_RELATION
Definition: pg_class.h:160
int rtindex
Definition: primnodes.h:1418
Definition: pg_list.h:45
struct TableSampleClause * tablesample
Definition: parsenodes.h:895
List * p_joinexprs
Definition: parse_node.h:169
List * p_rtable
Definition: parse_node.h:168
List* transformGroupClause ( ParseState pstate,
List grouplist,
List **  groupingSets,
List **  targetlist,
List sortClause,
ParseExprKind  exprKind,
bool  useSQL99 
)

Definition at line 2197 of file parse_clause.c.

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, NULL, transformGroupClauseExpr(), and transformGroupingSet().

Referenced by transformSelectStmt(), and transformWindowDefinitions().

2200 {
2201  List *result = NIL;
2202  List *flat_grouplist;
2203  List *gsets = NIL;
2204  ListCell *gl;
2205  bool hasGroupingSets = false;
2206  Bitmapset *seen_local = NULL;
2207 
2208  /*
2209  * Recursively flatten implicit RowExprs. (Technically this is only needed
2210  * for GROUP BY, per the syntax rules for grouping sets, but we do it
2211  * anyway.)
2212  */
2213  flat_grouplist = (List *) flatten_grouping_sets((Node *) grouplist,
2214  true,
2215  &hasGroupingSets);
2216 
2217  /*
2218  * If the list is now empty, but hasGroupingSets is true, it's because we
2219  * elided redundant empty grouping sets. Restore a single empty grouping
2220  * set to leave a canonical form: GROUP BY ()
2221  */
2222 
2223  if (flat_grouplist == NIL && hasGroupingSets)
2224  {
2226  NIL,
2227  exprLocation((Node *) grouplist)));
2228  }
2229 
2230  foreach(gl, flat_grouplist)
2231  {
2232  Node *gexpr = (Node *) lfirst(gl);
2233 
2234  if (IsA(gexpr, GroupingSet))
2235  {
2236  GroupingSet *gset = (GroupingSet *) gexpr;
2237 
2238  switch (gset->kind)
2239  {
2240  case GROUPING_SET_EMPTY:
2241  gsets = lappend(gsets, gset);
2242  break;
2243  case GROUPING_SET_SIMPLE:
2244  /* can't happen */
2245  Assert(false);
2246  break;
2247  case GROUPING_SET_SETS:
2248  case GROUPING_SET_CUBE:
2249  case GROUPING_SET_ROLLUP:
2250  gsets = lappend(gsets,
2251  transformGroupingSet(&result,
2252  pstate, gset,
2253  targetlist, sortClause,
2254  exprKind, useSQL99, true));
2255  break;
2256  }
2257  }
2258  else
2259  {
2260  Index ref = transformGroupClauseExpr(&result, seen_local,
2261  pstate, gexpr,
2262  targetlist, sortClause,
2263  exprKind, useSQL99, true);
2264 
2265  if (ref > 0)
2266  {
2267  seen_local = bms_add_member(seen_local, ref);
2268  if (hasGroupingSets)
2269  gsets = lappend(gsets,
2271  list_make1_int(ref),
2272  exprLocation(gexpr)));
2273  }
2274  }
2275  }
2276 
2277  /* parser should prevent this */
2278  Assert(gsets == NIL || groupingSets != NULL);
2279 
2280  if (groupingSets)
2281  *groupingSets = gsets;
2282 
2283  return result;
2284 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1204
Definition: nodes.h:508
static Node * transformGroupingSet(List **flatresult, ParseState *pstate, GroupingSet *gset, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
GroupingSetKind kind
Definition: parsenodes.h:1171
#define list_make1(x1)
Definition: pg_list.h:133
static Node * flatten_grouping_sets(Node *expr, bool toplevel, bool *hasGroupingSets)
#define list_make1_int(x1)
Definition: pg_list.h:139
List * lappend(List *list, void *datum)
Definition: list.c:128
unsigned int Index
Definition: c.h:362
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#define lfirst(lc)
Definition: pg_list.h:106
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:668
GroupingSet * makeGroupingSet(GroupingSetKind kind, List *content, int location)
Definition: makefuncs.c:604
Definition: pg_list.h:45
static Index transformGroupClauseExpr(List **flatresult, Bitmapset *seen_local, ParseState *pstate, Node *gexpr, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
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 1932 of file parse_clause.c.

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

1936 {
1937  TargetEntry *tle;
1938  bool found = false;
1939 
1940  if (useSQL99)
1941  tle = findTargetlistEntrySQL99(pstate, gexpr,
1942  targetlist, exprKind);
1943  else
1944  tle = findTargetlistEntrySQL92(pstate, gexpr,
1945  targetlist, exprKind);
1946 
1947  if (tle->ressortgroupref > 0)
1948  {
1949  ListCell *sl;
1950 
1951  /*
1952  * Eliminate duplicates (GROUP BY x, x) but only at local level.
1953  * (Duplicates in grouping sets can affect the number of returned
1954  * rows, so can't be dropped indiscriminately.)
1955  *
1956  * Since we don't care about anything except the sortgroupref, we can
1957  * use a bitmapset rather than scanning lists.
1958  */
1959  if (bms_is_member(tle->ressortgroupref, seen_local))
1960  return 0;
1961 
1962  /*
1963  * If we're already in the flat clause list, we don't need to consider
1964  * adding ourselves again.
1965  */
1966  found = targetIsInSortList(tle, InvalidOid, *flatresult);
1967  if (found)
1968  return tle->ressortgroupref;
1969 
1970  /*
1971  * If the GROUP BY tlist entry also appears in ORDER BY, copy operator
1972  * info from the (first) matching ORDER BY item. This means that if
1973  * you write something like "GROUP BY foo ORDER BY foo USING <<<", the
1974  * GROUP BY operation silently takes on the equality semantics implied
1975  * by the ORDER BY. There are two reasons to do this: it improves the
1976  * odds that we can implement both GROUP BY and ORDER BY with a single
1977  * sort step, and it allows the user to choose the equality semantics
1978  * used by GROUP BY, should she be working with a datatype that has
1979  * more than one equality operator.
1980  *
1981  * If we're in a grouping set, though, we force our requested ordering
1982  * to be NULLS LAST, because if we have any hope of using a sorted agg
1983  * for the job, we're going to be tacking on generated NULL values
1984  * after the corresponding groups. If the user demands nulls first,
1985  * another sort step is going to be inevitable, but that's the
1986  * planner's problem.
1987  */
1988 
1989  foreach(sl, sortClause)
1990  {
1991  SortGroupClause *sc = (SortGroupClause *) lfirst(sl);
1992 
1993  if (sc->tleSortGroupRef == tle->ressortgroupref)
1994  {
1995  SortGroupClause *grpc = copyObject(sc);
1996 
1997  if (!toplevel)
1998  grpc->nulls_first = false;
1999  *flatresult = lappend(*flatresult, grpc);
2000  found = true;
2001  break;
2002  }
2003  }
2004  }
2005 
2006  /*
2007  * If no match in ORDER BY, just add it to the result using default
2008  * sort/group semantics.
2009  */
2010  if (!found)
2011  *flatresult = addTargetToGroupList(pstate, tle,
2012  *flatresult, *targetlist,
2013  exprLocation(gexpr));
2014 
2015  /*
2016  * _something_ must have assigned us a sortgroupref by now...
2017  */
2018 
2019  return tle->ressortgroupref;
2020 }
static List * addTargetToGroupList(ParseState *pstate, TargetEntry *tle, List *grouplist, List *targetlist, int location)
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1204
static TargetEntry * findTargetlistEntrySQL99(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
Index tleSortGroupRef
Definition: parsenodes.h:1102
void * copyObject(const void *from)
Definition: copyfuncs.c:4475
List * lappend(List *list, void *datum)
Definition: list.c:128
#define InvalidOid
Definition: postgres_ext.h:36
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
#define lfirst(lc)
Definition: pg_list.h:106
static TargetEntry * findTargetlistEntrySQL92(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
Index ressortgroupref
Definition: primnodes.h:1333
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:419
static List* transformGroupClauseList ( List **  flatresult,
ParseState pstate,
List list,
List **  targetlist,
List sortClause,
ParseExprKind  exprKind,
bool  useSQL99,
bool  toplevel 
)
static

Definition at line 2040 of file parse_clause.c.

References bms_add_member(), lappend_int(), lfirst, NIL, NULL, and transformGroupClauseExpr().

Referenced by transformGroupingSet().

2044 {
2045  Bitmapset *seen_local = NULL;
2046  List *result = NIL;
2047  ListCell *gl;
2048 
2049  foreach(gl, list)
2050  {
2051  Node *gexpr = (Node *) lfirst(gl);
2052 
2053  Index ref = transformGroupClauseExpr(flatresult,
2054  seen_local,
2055  pstate,
2056  gexpr,
2057  targetlist,
2058  sortClause,
2059  exprKind,
2060  useSQL99,
2061  toplevel);
2062 
2063  if (ref > 0)
2064  {
2065  seen_local = bms_add_member(seen_local, ref);
2066  result = lappend_int(result, ref);
2067  }
2068  }
2069 
2070  return result;
2071 }
#define NIL
Definition: pg_list.h:69
Definition: nodes.h:508
List * lappend_int(List *list, int datum)
Definition: list.c:146
unsigned int Index
Definition: c.h:362
#define NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:668
Definition: pg_list.h:45
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 
)
static

Definition at line 2093 of file parse_clause.c.

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

Referenced by transformGroupClause().

2097 {
2098  ListCell *gl;
2099  List *content = NIL;
2100 
2101  Assert(toplevel || gset->kind != GROUPING_SET_SETS);
2102 
2103  foreach(gl, gset->content)
2104  {
2105  Node *n = lfirst(gl);
2106 
2107  if (IsA(n, List))
2108  {
2109  List *l = transformGroupClauseList(flatresult,
2110  pstate, (List *) n,
2111  targetlist, sortClause,
2112  exprKind, useSQL99, false);
2113 
2114  content = lappend(content, makeGroupingSet(GROUPING_SET_SIMPLE,
2115  l,
2116  exprLocation(n)));
2117  }
2118  else if (IsA(n, GroupingSet))
2119  {
2120  GroupingSet *gset2 = (GroupingSet *) lfirst(gl);
2121 
2122  content = lappend(content, transformGroupingSet(flatresult,
2123  pstate, gset2,
2124  targetlist, sortClause,
2125  exprKind, useSQL99, false));
2126  }
2127  else
2128  {
2129  Index ref = transformGroupClauseExpr(flatresult,
2130  NULL,
2131  pstate,
2132  n,
2133  targetlist,
2134  sortClause,
2135  exprKind,
2136  useSQL99,
2137  false);
2138 
2139  content = lappend(content, makeGroupingSet(GROUPING_SET_SIMPLE,
2140  list_make1_int(ref),
2141  exprLocation(n)));
2142  }
2143  }
2144 
2145  /* Arbitrarily cap the size of CUBE, which has exponential growth */
2146  if (gset->kind == GROUPING_SET_CUBE)
2147  {
2148  if (list_length(content) > 12)
2149  ereport(ERROR,
2150  (errcode(ERRCODE_TOO_MANY_COLUMNS),
2151  errmsg("CUBE is limited to 12 elements"),
2152  parser_errposition(pstate, gset->location)));
2153  }
2154 
2155  return (Node *) makeGroupingSet(gset->kind, content, gset->location);
2156 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
List * content
Definition: parsenodes.h:1172
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1204
Definition: nodes.h:508
int errcode(int sqlerrcode)
Definition: elog.c:575
static Node * transformGroupingSet(List **flatresult, ParseState *pstate, GroupingSet *gset, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
GroupingSetKind kind
Definition: parsenodes.h:1171
#define ERROR
Definition: elog.h:43
static List * transformGroupClauseList(List **flatresult, ParseState *pstate, List *list, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
#define list_make1_int(x1)
Definition: pg_list.h:139
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
unsigned int Index
Definition: c.h:362
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:109
int errmsg(const char *fmt,...)
Definition: elog.c:797
GroupingSet * makeGroupingSet(GroupingSetKind kind, List *content, int location)
Definition: makefuncs.c:604
Definition: pg_list.h:45
static Index transformGroupClauseExpr(List **flatresult, Bitmapset *seen_local, ParseState *pstate, Node *gexpr, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
static Node * transformJoinOnClause ( ParseState pstate,
JoinExpr j,
List namespace 
)
static

Definition at line 379 of file parse_clause.c.

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

Referenced by transformFromClauseItem().

380 {
381  Node *result;
382  List *save_namespace;
383 
384  /*
385  * The namespace that the join expression should see is just the two
386  * subtrees of the JOIN plus any outer references from upper pstate
387  * levels. Temporarily set this pstate's namespace accordingly. (We need
388  * not check for refname conflicts, because transformFromClauseItem()
389  * already did.) All namespace items are marked visible regardless of
390  * LATERAL state.
391  */
392  setNamespaceLateralState(namespace, false, true);
393 
394  save_namespace = pstate->p_namespace;
395  pstate->p_namespace = namespace;
396 
397  result = transformWhereClause(pstate, j->quals,
398  EXPR_KIND_JOIN_ON, "JOIN/ON");
399 
400  pstate->p_namespace = save_namespace;
401 
402  return result;
403 }
Definition: nodes.h:508
List * p_namespace
Definition: parse_node.h:172
static void setNamespaceLateralState(List *namespace, bool lateral_only, bool lateral_ok)
Node * quals
Definition: primnodes.h:1416
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
Definition: pg_list.h:45
static Node * transformJoinUsingClause ( ParseState pstate,
RangeTblEntry leftRTE,
RangeTblEntry rightRTE,
List leftVars,
List rightVars 
)
static

Definition at line 319 of file parse_clause.c.

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

322 {
323  Node *result;
324  List *andargs = NIL;
325  ListCell *lvars,
326  *rvars;
327 
328  /*
329  * We cheat a little bit here by building an untransformed operator tree
330  * whose leaves are the already-transformed Vars. This requires collusion
331  * from transformExpr(), which normally could be expected to complain
332  * about already-transformed subnodes. However, this does mean that we
333  * have to mark the columns as requiring SELECT privilege for ourselves;
334  * transformExpr() won't do it.
335  */
336  forboth(lvars, leftVars, rvars, rightVars)
337  {
338  Var *lvar = (Var *) lfirst(lvars);
339  Var *rvar = (Var *) lfirst(rvars);
340  A_Expr *e;
341 
342  /* Require read access to the join variables */
343  markVarForSelectPriv(pstate, lvar, leftRTE);
344  markVarForSelectPriv(pstate, rvar, rightRTE);
345 
346  /* Now create the lvar = rvar join condition */
347  e = makeSimpleA_Expr(AEXPR_OP, "=",
348  copyObject(lvar), copyObject(rvar),
349  -1);
350 
351  /* Prepare to combine into an AND clause, if multiple join columns */
352  andargs = lappend(andargs, e);
353  }
354 
355  /* Only need an AND if there's more than one join column */
356  if (list_length(andargs) == 1)
357  result = (Node *) linitial(andargs);
358  else
359  result = (Node *) makeBoolExpr(AND_EXPR, andargs, -1);
360 
361  /*
362  * Since the references are already Vars, and are certainly from the input
363  * relations, we don't have to go through the same pushups that
364  * transformJoinOnClause() does. Just invoke transformExpr() to fix up
365  * the operators, and we're done.
366  */
367  result = transformExpr(pstate, result, EXPR_KIND_JOIN_USING);
368 
369  result = coerce_to_boolean(pstate, result, "JOIN/USING");
370 
371  return result;
372 }
#define NIL
Definition: pg_list.h:69
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:174
void markVarForSelectPriv(ParseState *pstate, Var *var, RangeTblEntry *rte)
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:147
Definition: nodes.h:508
A_Expr * makeSimpleA_Expr(A_Expr_Kind kind, char *name, Node *lexpr, Node *rexpr, int location)
Definition: makefuncs.c:49
Definition: primnodes.h:141
Expr * makeBoolExpr(BoolExprType boolop, List *args, int location)
Definition: makefuncs.c:366
void * copyObject(const void *from)
Definition: copyfuncs.c:4475
#define linitial(l)
Definition: pg_list.h:110
List * lappend(List *list, void *datum)
Definition: list.c:128
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
e
Definition: preproc-init.c:82
Definition: pg_list.h:45
Node * coerce_to_boolean(ParseState *pstate, Node *node, const char *constructName)
Node* transformLimitClause ( ParseState pstate,
Node clause,
ParseExprKind  exprKind,
const char *  constructName 
)

Definition at line 1456 of file parse_clause.c.

References checkExprIsVarFree(), coerce_to_specific_type(), INT8OID, NULL, and transformExpr().

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

1458 {
1459  Node *qual;
1460 
1461  if (clause == NULL)
1462  return NULL;
1463 
1464  qual = transformExpr(pstate, clause, exprKind);
1465 
1466  qual = coerce_to_specific_type(pstate, qual, INT8OID, constructName);
1467 
1468  /* LIMIT can't refer to any variables of the current query */
1469  checkExprIsVarFree(pstate, qual, constructName);
1470 
1471  return qual;
1472 }
static void checkExprIsVarFree(ParseState *pstate, Node *n, const char *constructName)
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:147
Definition: nodes.h:508
#define INT8OID
Definition: pg_type.h:304
#define NULL
Definition: c.h:226
Node * coerce_to_specific_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *constructName)
void transformOnConflictArbiter ( ParseState pstate,
OnConflictClause onConflictClause,
List **  arbiterExpr,
Node **  arbiterWhere,
Oid constraint 
)

Definition at line 2814 of file parse_clause.c.

References OnConflictClause::action, addRTEtoQuery(), InferClause::conname, ereport, errcode(), errhint(), errmsg(), ERROR, EXPR_KIND_INDEX_PREDICATE, exprLocation(), get_relation_constraint_oid(), InferClause::indexElems, OnConflictClause::infer, InvalidOid, IsCatalogRelation(), NIL, NULL, ONCONFLICT_UPDATE, ParseState::p_namespace, ParseState::p_target_rangetblentry, ParseState::p_target_relation, parser_errposition(), RelationGetRelationName, RelationGetRelid, RelationIsUsedAsCatalogTable, resolve_unique_index_expr(), transformExpr(), and InferClause::whereClause.

Referenced by transformOnConflictClause().

2818 {
2819  InferClause *infer = onConflictClause->infer;
2820 
2821  *arbiterExpr = NIL;
2822  *arbiterWhere = NULL;
2823  *constraint = InvalidOid;
2824 
2825  if (onConflictClause->action == ONCONFLICT_UPDATE && !infer)
2826  ereport(ERROR,
2827  (errcode(ERRCODE_SYNTAX_ERROR),
2828  errmsg("ON CONFLICT DO UPDATE requires inference specification or constraint name"),
2829  errhint("For example, ON CONFLICT (column_name)."),
2830  parser_errposition(pstate,
2831  exprLocation((Node *) onConflictClause))));
2832 
2833  /*
2834  * To simplify certain aspects of its design, speculative insertion into
2835  * system catalogs is disallowed
2836  */
2837  if (IsCatalogRelation(pstate->p_target_relation))
2838  ereport(ERROR,
2839  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2840  errmsg("ON CONFLICT is not supported with system catalog tables"),
2841  parser_errposition(pstate,
2842  exprLocation((Node *) onConflictClause))));
2843 
2844  /* Same applies to table used by logical decoding as catalog table */
2846  ereport(ERROR,
2847  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2848  errmsg("ON CONFLICT is not supported on table \"%s\" used as a catalog table",
2850  parser_errposition(pstate,
2851  exprLocation((Node *) onConflictClause))));
2852 
2853  /* ON CONFLICT DO NOTHING does not require an inference clause */
2854  if (infer)
2855  {
2856  List *save_namespace;
2857 
2858  /*
2859  * While we process the arbiter expressions, accept only non-qualified
2860  * references to the target table. Hide any other relations.
2861  */
2862  save_namespace = pstate->p_namespace;
2863  pstate->p_namespace = NIL;
2864  addRTEtoQuery(pstate, pstate->p_target_rangetblentry,
2865  false, false, true);
2866 
2867  if (infer->indexElems)
2868  *arbiterExpr = resolve_unique_index_expr(pstate, infer,
2869  pstate->p_target_relation);
2870 
2871  /*
2872  * Handling inference WHERE clause (for partial unique index
2873  * inference)
2874  */
2875  if (infer->whereClause)
2876  *arbiterWhere = transformExpr(pstate, infer->whereClause,
2878 
2879  pstate->p_namespace = save_namespace;
2880 
2881  if (infer->conname)
2883  infer->conname, false);
2884  }
2885 
2886  /*
2887  * It's convenient to form a list of expressions based on the
2888  * representation used by CREATE INDEX, since the same restrictions are
2889  * appropriate (e.g. on subqueries). However, from here on, a dedicated
2890  * primnode representation is used for inference elements, and so
2891  * assign_query_collations() can be trusted to do the right thing with the
2892  * post parse analysis query tree inference clause representation.
2893  */
2894 }
#define NIL
Definition: pg_list.h:69
bool IsCatalogRelation(Relation relation)
Definition: catalog.c:91
int errhint(const char *fmt,...)
Definition: elog.c:987
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1204
Oid get_relation_constraint_oid(Oid relid, const char *conname, bool missing_ok)
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:147
List * indexElems
Definition: parsenodes.h:1249
Definition: nodes.h:508
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
List * p_namespace
Definition: parse_node.h:172
char * conname
Definition: parsenodes.h:1251
#define RelationGetRelationName(relation)
Definition: rel.h:433
#define ereport(elevel, rest)
Definition: elog.h:122
void addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
RangeTblEntry * p_target_rangetblentry
Definition: parse_node.h:179
InferClause * infer
Definition: parsenodes.h:1265
#define RelationIsUsedAsCatalogTable(relation)
Definition: rel.h:312
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:226
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:109
Node * whereClause
Definition: parsenodes.h:1250
int errmsg(const char *fmt,...)
Definition: elog.c:797
Relation p_target_relation
Definition: parse_node.h:178
OnConflictAction action
Definition: parsenodes.h:1264
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:413
static List * resolve_unique_index_expr(ParseState *pstate, InferClause *infer, Relation heapRel)
static RangeTblEntry * transformRangeFunction ( ParseState pstate,
RangeFunction r 
)
static

Definition at line 505 of file parse_clause.c.

References addRangeTableEntryForFunction(), FuncCall::agg_distinct, FuncCall::agg_filter, FuncCall::agg_order, FuncCall::agg_star, arg, FuncCall::args, Assert, assign_list_collations(), RangeFunction::coldeflist, contain_vars_of_level(), ereport, errcode(), errhint(), errmsg(), ERROR, EXPR_KIND_FROM_FUNCTION, exprLocation(), fc(), FigureColname(), FuncCall::func_variadic, FuncCall::funcname, RangeFunction::functions, RangeFunction::is_rowsfrom, IsA, lappend(), RangeFunction::lateral, lfirst, linitial, list_length(), list_make1, FuncCall::location, lsecond, makeFuncCall(), NIL, NULL, RangeFunction::ordinality, FuncCall::over, ParseState::p_lateral_active, parser_errposition(), strVal, SystemFuncName(), and transformExpr().

Referenced by transformFromClauseItem().

506 {
507  List *funcexprs = NIL;
508  List *funcnames = NIL;
509  List *coldeflists = NIL;
510  bool is_lateral;
511  RangeTblEntry *rte;
512  ListCell *lc;
513 
514  /*
515  * We make lateral_only names of this level visible, whether or not the
516  * RangeFunction is explicitly marked LATERAL. This is needed for SQL
517  * spec compliance in the case of UNNEST(), and seems useful on
518  * convenience grounds for all functions in FROM.
519  *
520  * (LATERAL can't nest within a single pstate level, so we don't need
521  * save/restore logic here.)
522  */
523  Assert(!pstate->p_lateral_active);
524  pstate->p_lateral_active = true;
525 
526  /*
527  * Transform the raw expressions.
528  *
529  * While transforming, also save function names for possible use as alias
530  * and column names. We use the same transformation rules as for a SELECT
531  * output expression. For a FuncCall node, the result will be the
532  * function name, but it is possible for the grammar to hand back other
533  * node types.
534  *
535  * We have to get this info now, because FigureColname only works on raw
536  * parsetrees. Actually deciding what to do with the names is left up to
537  * addRangeTableEntryForFunction.
538  *
539  * Likewise, collect column definition lists if there were any. But
540  * complain if we find one here and the RangeFunction has one too.
541  */
542  foreach(lc, r->functions)
543  {
544  List *pair = (List *) lfirst(lc);
545  Node *fexpr;
546  List *coldeflist;
547 
548  /* Disassemble the function-call/column-def-list pairs */
549  Assert(list_length(pair) == 2);
550  fexpr = (Node *) linitial(pair);
551  coldeflist = (List *) lsecond(pair);
552 
553  /*
554  * If we find a function call unnest() with more than one argument and
555  * no special decoration, transform it into separate unnest() calls on
556  * each argument. This is a kluge, for sure, but it's less nasty than
557  * other ways of implementing the SQL-standard UNNEST() syntax.
558  *
559  * If there is any decoration (including a coldeflist), we don't
560  * transform, which probably means a no-such-function error later. We
561  * could alternatively throw an error right now, but that doesn't seem
562  * tremendously helpful. If someone is using any such decoration,
563  * then they're not using the SQL-standard syntax, and they're more
564  * likely expecting an un-tweaked function call.
565  *
566  * Note: the transformation changes a non-schema-qualified unnest()
567  * function name into schema-qualified pg_catalog.unnest(). This
568  * choice is also a bit debatable, but it seems reasonable to force
569  * use of built-in unnest() when we make this transformation.
570  */
571  if (IsA(fexpr, FuncCall))
572  {
573  FuncCall *fc = (FuncCall *) fexpr;
574 
575  if (list_length(fc->funcname) == 1 &&
576  strcmp(strVal(linitial(fc->funcname)), "unnest") == 0 &&
577  list_length(fc->args) > 1 &&
578  fc->agg_order == NIL &&
579  fc->agg_filter == NULL &&
580  !fc->agg_star &&
581  !fc->agg_distinct &&
582  !fc->func_variadic &&
583  fc->over == NULL &&
584  coldeflist == NIL)
585  {
586  ListCell *lc;
587 
588  foreach(lc, fc->args)
589  {
590  Node *arg = (Node *) lfirst(lc);
591  FuncCall *newfc;
592 
593  newfc = makeFuncCall(SystemFuncName("unnest"),
594  list_make1(arg),
595  fc->location);
596 
597  funcexprs = lappend(funcexprs,
598  transformExpr(pstate, (Node *) newfc,
600 
601  funcnames = lappend(funcnames,
602  FigureColname((Node *) newfc));
603 
604  /* coldeflist is empty, so no error is possible */
605 
606  coldeflists = lappend(coldeflists, coldeflist);
607  }
608  continue; /* done with this function item */
609  }
610  }
611 
612  /* normal case ... */
613  funcexprs = lappend(funcexprs,
614  transformExpr(pstate, fexpr,
616 
617  funcnames = lappend(funcnames,
618  FigureColname(fexpr));
619 
620  if (coldeflist && r->coldeflist)
621  ereport(ERROR,
622  (errcode(ERRCODE_SYNTAX_ERROR),
623  errmsg("multiple column definition lists are not allowed for the same function"),
624  parser_errposition(pstate,
625  exprLocation((Node *) r->coldeflist))));
626 
627  coldeflists = lappend(coldeflists, coldeflist);
628  }
629 
630  pstate->p_lateral_active = false;
631 
632  /*
633  * We must assign collations now so that the RTE exposes correct collation
634  * info for Vars created from it.
635  */
636  assign_list_collations(pstate, funcexprs);
637 
638  /*
639  * Install the top-level coldeflist if there was one (we already checked
640  * that there was no conflicting per-function coldeflist).
641  *
642  * We only allow this when there's a single function (even after UNNEST
643  * expansion) and no WITH ORDINALITY. The reason for the latter
644  * restriction is that it's not real clear whether the ordinality column
645  * should be in the coldeflist, and users are too likely to make mistakes
646  * in one direction or the other. Putting the coldeflist inside ROWS
647  * FROM() is much clearer in this case.
648  */
649  if (r->coldeflist)
650  {
651  if (list_length(funcexprs) != 1)
652  {
653  if (r->is_rowsfrom)
654  ereport(ERROR,
655  (errcode(ERRCODE_SYNTAX_ERROR),
656  errmsg("ROWS FROM() with multiple functions cannot have a column definition list"),
657  errhint("Put a separate column definition list for each function inside ROWS FROM()."),
658  parser_errposition(pstate,
659  exprLocation((Node *) r->coldeflist))));
660  else
661  ereport(ERROR,
662  (errcode(ERRCODE_SYNTAX_ERROR),
663  errmsg("UNNEST() with multiple arguments cannot have a column definition list"),
664  errhint("Use separate UNNEST() calls inside ROWS FROM(), and attach a column definition list to each one."),
665  parser_errposition(pstate,
666  exprLocation((Node *) r->coldeflist))));
667  }
668  if (r->ordinality)
669  ereport(ERROR,
670  (errcode(ERRCODE_SYNTAX_ERROR),
671  errmsg("WITH ORDINALITY cannot be used with a column definition list"),
672  errhint("Put the column definition list inside ROWS FROM()."),
673  parser_errposition(pstate,
674  exprLocation((Node *) r->coldeflist))));
675 
676  coldeflists = list_make1(r->coldeflist);
677  }
678 
679  /*
680  * Mark the RTE as LATERAL if the user said LATERAL explicitly, or if
681  * there are any lateral cross-references in it.
682  */
683  is_lateral = r->lateral || contain_vars_of_level((Node *) funcexprs, 0);
684 
685  /*
686  * OK, build an RTE for the function.
687  */
688  rte = addRangeTableEntryForFunction(pstate,
689  funcnames, funcexprs, coldeflists,
690  r, is_lateral, true);
691 
692  return rte;
693 }
#define NIL
Definition: pg_list.h:69
List * SystemFuncName(char *name)
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
int errhint(const char *fmt,...)
Definition: elog.c:987
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1204
Node * agg_filter
Definition: parsenodes.h:344
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:147
Definition: nodes.h:508
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:575
static int fc(const char *x)
Definition: preproc-init.c:99
int location
Definition: parsenodes.h:350
List * agg_order
Definition: parsenodes.h:343
#define lsecond(l)
Definition: pg_list.h:114
#define list_make1(x1)
Definition: pg_list.h:133
#define linitial(l)
Definition: pg_list.h:110
#define ERROR
Definition: elog.h:43
struct WindowDef * over
Definition: parsenodes.h:349
List * coldeflist
Definition: parsenodes.h:553
char * FigureColname(Node *node)
void assign_list_collations(ParseState *pstate, List *exprs)
List * functions
Definition: parsenodes.h:551
#define ereport(elevel, rest)
Definition: elog.h:122
bool is_rowsfrom
Definition: parsenodes.h:550
List * lappend(List *list, void *datum)
Definition: list.c:128
bool func_variadic
Definition: parsenodes.h:348
FuncCall * makeFuncCall(List *name, List *args, int location)
Definition: makefuncs.c:582
bool p_lateral_active
Definition: parse_node.h:174
RangeTblEntry * addRangeTableEntryForFunction(ParseState *pstate, List *funcnames, List *funcexprs, List *coldeflists, RangeFunction *rangefunc, bool lateral, bool inFromCl)
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#define lfirst(lc)
Definition: pg_list.h:106
bool contain_vars_of_level(Node *node, int levelsup)
Definition: var.c:369
List * args
Definition: parsenodes.h:342
static int list_length(const List *l)
Definition: pg_list.h:89
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:109
int errmsg(const char *fmt,...)
Definition: elog.c:797
void * arg
List * funcname
Definition: parsenodes.h:341
bool agg_distinct
Definition: parsenodes.h:347
bool agg_star
Definition: parsenodes.h:346
Definition: pg_list.h:45
static RangeTblEntry * transformRangeSubselect ( ParseState pstate,
RangeSubselect r 
)
static

Definition at line 438 of file parse_clause.c.

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

Referenced by transformFromClauseItem().

439 {
440  Query *query;
441  RangeTblEntry *rte;
442 
443  /*
444  * We require user to supply an alias for a subselect, per SQL92. To relax
445  * this, we'd have to be prepared to gin up a unique alias for an
446  * unlabeled subselect. (This is just elog, not ereport, because the
447  * grammar should have enforced it already. It'd probably be better to
448  * report the error here, but we don't have a good error location here.)
449  */
450  if (r->alias == NULL)
451  elog(ERROR, "subquery in FROM must have an alias");
452 
453  /*
454  * Set p_expr_kind to show this parse level is recursing to a subselect.
455  * We can't be nested within any expression, so don't need save-restore
456  * logic here.
457  */
458  Assert(pstate->p_expr_kind == EXPR_KIND_NONE);
460 
461  /*
462  * If the subselect is LATERAL, make lateral_only names of this level
463  * visible to it. (LATERAL can't nest within a single pstate level, so we
464  * don't need save/restore logic here.)
465  */
466  Assert(!pstate->p_lateral_active);
467  pstate->p_lateral_active = r->lateral;
468 
469  /*
470  * Analyze and transform the subquery.
471  */
472  query = parse_sub_analyze(r->subquery, pstate, NULL,
473  isLockedRefname(pstate, r->alias->aliasname),
474  true);
475 
476  /* Restore state */
477  pstate->p_lateral_active = false;
478  pstate->p_expr_kind = EXPR_KIND_NONE;
479 
480  /*
481  * Check that we got a SELECT. Anything else should be impossible given
482  * restrictions of the grammar, but check anyway.
483  */
484  if (!IsA(query, Query) ||
485  query->commandType != CMD_SELECT)
486  elog(ERROR, "unexpected non-SELECT command in subquery in FROM");
487 
488  /*
489  * OK, build an RTE for the subquery.
490  */
491  rte = addRangeTableEntryForSubquery(pstate,
492  query,
493  r->alias,
494  r->lateral,
495  true);
496 
497  return rte;
498 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
Node * subquery
Definition: parsenodes.h:527
#define ERROR
Definition: elog.h:43
RangeTblEntry * addRangeTableEntryForSubquery(ParseState *pstate, Query *subquery, Alias *alias, bool lateral, bool inFromCl)
ParseExprKind p_expr_kind
Definition: parse_node.h:182
Query * parse_sub_analyze(Node *parseTree, ParseState *parentParseState, CommonTableExpr *parentCTE, bool locked_from_parent, bool resolve_unknowns)
Definition: analyze.c:157
bool p_lateral_active
Definition: parse_node.h:174
CmdType commandType
Definition: parsenodes.h:103
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
char * aliasname
Definition: primnodes.h:41
Alias * alias
Definition: parsenodes.h:528
bool isLockedRefname(ParseState *pstate, const char *refname)
#define elog
Definition: elog.h:219
static TableSampleClause * transformRangeTableSample ( ParseState pstate,
RangeTableSample rts 
)
static

Definition at line 702 of file parse_clause.c.

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

Referenced by transformFromClauseItem().

703 {
704  TableSampleClause *tablesample;
705  Oid handlerOid;
706  Oid funcargtypes[1];
707  TsmRoutine *tsm;
708  List *fargs;
709  ListCell *larg,
710  *ltyp;
711 
712  /*
713  * To validate the sample method name, look up the handler function, which
714  * has the same name, one dummy INTERNAL argument, and a result type of
715  * tsm_handler. (Note: tablesample method names are not schema-qualified
716  * in the SQL standard; but since they are just functions to us, we allow
717  * schema qualification to resolve any potential ambiguity.)
718  */
719  funcargtypes[0] = INTERNALOID;
720 
721  handlerOid = LookupFuncName(rts->method, 1, funcargtypes, true);
722 
723  /* we want error to complain about no-such-method, not no-such-function */
724  if (!OidIsValid(handlerOid))
725  ereport(ERROR,
726  (errcode(ERRCODE_UNDEFINED_OBJECT),
727  errmsg("tablesample method %s does not exist",
728  NameListToString(rts->method)),
729  parser_errposition(pstate, rts->location)));
730 
731  /* check that handler has correct return type */
732  if (get_func_rettype(handlerOid) != TSM_HANDLEROID)
733  ereport(ERROR,
734  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
735  errmsg("function %s must return type %s",
736  NameListToString(rts->method), "tsm_handler"),
737  parser_errposition(pstate, rts->location)));
738 
739  /* OK, run the handler to get TsmRoutine, for argument type info */
740  tsm = GetTsmRoutine(handlerOid);
741 
742  tablesample = makeNode(TableSampleClause);
743  tablesample->tsmhandler = handlerOid;
744 
745  /* check user provided the expected number of arguments */
746  if (list_length(rts->args) != list_length(tsm->parameterTypes))
747  ereport(ERROR,
748  (errcode(ERRCODE_INVALID_TABLESAMPLE_ARGUMENT),
749  errmsg_plural("tablesample method %s requires %d argument, not %d",
750  "tablesample method %s requires %d arguments, not %d",
752  NameListToString(rts->method),
754  list_length(rts->args)),
755  parser_errposition(pstate, rts->location)));
756 
757  /*
758  * Transform the arguments, typecasting them as needed. Note we must also
759  * assign collations now, because assign_query_collations() doesn't
760  * examine any substructure of RTEs.
761  */
762  fargs = NIL;
763  forboth(larg, rts->args, ltyp, tsm->parameterTypes)
764  {
765  Node *arg = (Node *) lfirst(larg);
766  Oid argtype = lfirst_oid(ltyp);
767 
768  arg = transformExpr(pstate, arg, EXPR_KIND_FROM_FUNCTION);
769  arg = coerce_to_specific_type(pstate, arg, argtype, "TABLESAMPLE");
770  assign_expr_collations(pstate, arg);
771  fargs = lappend(fargs, arg);
772  }
773  tablesample->args = fargs;
774 
775  /* Process REPEATABLE (seed) */
776  if (rts->repeatable != NULL)
777  {
778  Node *arg;
779 
780  if (!tsm->repeatable_across_queries)
781  ereport(ERROR,
782  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
783  errmsg("tablesample method %s does not support REPEATABLE",
784  NameListToString(rts->method)),
785  parser_errposition(pstate, rts->location)));
786 
787  arg = transformExpr(pstate, rts->repeatable, EXPR_KIND_FROM_FUNCTION);
788  arg = coerce_to_specific_type(pstate, arg, FLOAT8OID, "REPEATABLE");
789  assign_expr_collations(pstate, arg);
790  tablesample->repeatable = (Expr *) arg;
791  }
792  else
793  tablesample->repeatable = NULL;
794 
795  return tablesample;
796 }
#define NIL
Definition: pg_list.h:69
bool repeatable_across_queries
Definition: tsmapi.h:63
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:174
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:850
#define TSM_HANDLEROID
Definition: pg_type.h:700
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:147
Definition: nodes.h:508
int errcode(int sqlerrcode)
Definition: elog.c:575
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:534
Oid get_func_rettype(Oid funcid)
Definition: lsyscache.c:1427
void assign_expr_collations(ParseState *pstate, Node *expr)
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
char * NameListToString(List *names)
Definition: namespace.c:2897
#define INTERNALOID
Definition: pg_type.h:686
TsmRoutine * GetTsmRoutine(Oid tsmhandler)
Definition: tablesample.c:27
#define makeNode(_type_)
Definition: nodes.h:556
#define NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:109
#define FLOAT8OID
Definition: pg_type.h:411
Oid LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool noError)
Definition: parse_func.c:1908
int errmsg(const char *fmt,...)
Definition: elog.c:797
Node * coerce_to_specific_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *constructName)
void * arg
List * parameterTypes
Definition: tsmapi.h:60
Definition: pg_list.h:45
#define lfirst_oid(lc)
Definition: pg_list.h:108
List* transformSortClause ( ParseState pstate,
List orderlist,
List **  targetlist,
ParseExprKind  exprKind,
bool  useSQL99 
)

Definition at line 2297 of file parse_clause.c.

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

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

2302 {
2303  List *sortlist = NIL;
2304  ListCell *olitem;
2305 
2306  foreach(olitem, orderlist)
2307  {
2308  SortBy *sortby = (SortBy *) lfirst(olitem);
2309  TargetEntry *tle;
2310 
2311  if (useSQL99)
2312  tle = findTargetlistEntrySQL99(pstate, sortby->node,
2313  targetlist, exprKind);
2314  else
2315  tle = findTargetlistEntrySQL92(pstate, sortby->node,
2316  targetlist, exprKind);
2317 
2318  sortlist = addTargetToSortList(pstate, tle,
2319  sortlist, *targetlist, sortby);
2320  }
2321 
2322  return sortlist;
2323 }
#define NIL
Definition: pg_list.h:69
List * addTargetToSortList(ParseState *pstate, TargetEntry *tle, List *sortlist, List *targetlist, SortBy *sortby)
static TargetEntry * findTargetlistEntrySQL99(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
#define lfirst(lc)
Definition: pg_list.h:106
static TargetEntry * findTargetlistEntrySQL92(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
Node * node
Definition: parsenodes.h:460
Definition: pg_list.h:45
static RangeTblEntry * transformTableEntry ( ParseState pstate,
RangeVar r 
)
static

Definition at line 409 of file parse_clause.c.

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

Referenced by transformFromClauseItem().

410 {
411  RangeTblEntry *rte;
412 
413  /* We need only build a range table entry */
414  rte = addRangeTableEntry(pstate, r, r->alias, r->inh, true);
415 
416  return rte;
417 }
RangeTblEntry * addRangeTableEntry(ParseState *pstate, RangeVar *relation, Alias *alias, bool inh, bool inFromCl)
bool inh
Definition: primnodes.h:68
Alias * alias
Definition: primnodes.h:71
Node* transformWhereClause ( ParseState pstate,
Node clause,
ParseExprKind  exprKind,
const char *  constructName 
)

Definition at line 1429 of file parse_clause.c.

References coerce_to_boolean(), NULL, and transformExpr().

Referenced by AlterPolicy(), CreatePolicy(), CreateTrigger(), ParseFuncOrColumn(), test_rls_hooks_permissive(), test_rls_hooks_restrictive(), transformDeleteStmt(), transformIndexStmt(), transformJoinOnClause(), transformOnConflictClause(), transformRuleStmt(), transformSelectStmt(), and transformUpdateStmt().

1431 {
1432  Node *qual;
1433 
1434  if (clause == NULL)
1435  return NULL;
1436 
1437  qual = transformExpr(pstate, clause, exprKind);
1438 
1439  qual = coerce_to_boolean(pstate, qual, constructName);
1440 
1441  return qual;
1442 }
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:147
Definition: nodes.h:508
#define NULL
Definition: c.h:226
Node * coerce_to_boolean(ParseState *pstate, Node *node, const char *constructName)
List* transformWindowDefinitions ( ParseState pstate,
List windowdefs,
List **  targetlist 
)

Definition at line 2330 of file parse_clause.c.

References WindowClause::copiedOrder, copyObject(), WindowDef::endOffset, WindowClause::endOffset, ereport, errcode(), errhint(), errmsg(), ERROR, EXPR_KIND_WINDOW_ORDER, EXPR_KIND_WINDOW_PARTITION, findWindowClause(), FRAMEOPTION_DEFAULTS, WindowDef::frameOptions, WindowClause::frameOptions, lappend(), lfirst, WindowDef::location, makeNode, WindowDef::name, WindowClause::name, NIL, NULL, WindowDef::orderClause, WindowClause::orderClause, parser_errposition(), WindowDef::partitionClause, WindowClause::partitionClause, WindowDef::refname, WindowClause::refname, WindowDef::startOffset, WindowClause::startOffset, transformFrameOffset(), transformGroupClause(), transformSortClause(), and WindowClause::winref.

Referenced by transformSelectStmt().

2333 {
2334  List *result = NIL;
2335  Index winref = 0;
2336  ListCell *lc;
2337 
2338  foreach(lc, windowdefs)
2339  {
2340  WindowDef *windef = (WindowDef *) lfirst(lc);
2341  WindowClause *refwc = NULL;
2342  List *partitionClause;
2343  List *orderClause;
2344  WindowClause *wc;
2345 
2346  winref++;
2347 
2348  /*
2349  * Check for duplicate window names.
2350  */
2351  if (windef->name &&
2352  findWindowClause(result, windef->name) != NULL)
2353  ereport(ERROR,
2354  (errcode(ERRCODE_WINDOWING_ERROR),
2355  errmsg("window \"%s\" is already defined", windef->name),
2356  parser_errposition(pstate, windef->location)));
2357 
2358  /*
2359  * If it references a previous window, look that up.
2360  */
2361  if (windef->refname)
2362  {
2363  refwc = findWindowClause(result, windef->refname);
2364  if (refwc == NULL)
2365  ereport(ERROR,
2366  (errcode(ERRCODE_UNDEFINED_OBJECT),
2367  errmsg("window \"%s\" does not exist",
2368  windef->refname),
2369  parser_errposition(pstate, windef->location)));
2370  }
2371 
2372  /*
2373  * Transform PARTITION and ORDER specs, if any. These are treated
2374  * almost exactly like top-level GROUP BY and ORDER BY clauses,
2375  * including the special handling of nondefault operator semantics.
2376  */
2377  orderClause = transformSortClause(pstate,
2378  windef->orderClause,
2379  targetlist,
2381  true /* force SQL99 rules */ );
2382  partitionClause = transformGroupClause(pstate,
2383  windef->partitionClause,
2384  NULL,
2385  targetlist,
2386  orderClause,
2388  true /* force SQL99 rules */ );
2389 
2390  /*
2391  * And prepare the new WindowClause.
2392  */
2393  wc = makeNode(WindowClause);
2394  wc->name = windef->name;
2395  wc->refname = windef->refname;
2396 
2397  /*
2398  * Per spec, a windowdef that references a previous one copies the
2399  * previous partition clause (and mustn't specify its own). It can
2400  * specify its own ordering clause, but only if the previous one had
2401  * none. It always specifies its own frame clause, and the previous
2402  * one must not have a frame clause. Yeah, it's bizarre that each of
2403  * these cases works differently, but SQL:2008 says so; see 7.11
2404  * <window clause> syntax rule 10 and general rule 1. The frame
2405  * clause rule is especially bizarre because it makes "OVER foo"
2406  * different from "OVER (foo)", and requires the latter to throw an
2407  * error if foo has a nondefault frame clause. Well, ours not to
2408  * reason why, but we do go out of our way to throw a useful error
2409  * message for such cases.
2410  */
2411  if (refwc)
2412  {
2413  if (partitionClause)
2414  ereport(ERROR,
2415  (errcode(ERRCODE_WINDOWING_ERROR),
2416  errmsg("cannot override PARTITION BY clause of window \"%s\"",
2417  windef->refname),
2418  parser_errposition(pstate, windef->location)));
2420  }
2421  else
2422  wc->partitionClause = partitionClause;
2423  if (refwc)
2424  {
2425  if (orderClause && refwc->orderClause)
2426  ereport(ERROR,
2427  (errcode(ERRCODE_WINDOWING_ERROR),
2428  errmsg("cannot override ORDER BY clause of window \"%s\"",
2429  windef->refname),
2430  parser_errposition(pstate, windef->location)));
2431  if (orderClause)
2432  {
2433  wc->orderClause = orderClause;
2434  wc->copiedOrder = false;
2435  }
2436  else
2437  {
2438  wc->orderClause = copyObject(refwc->orderClause);
2439  wc->copiedOrder = true;
2440  }
2441  }
2442  else
2443  {
2444  wc->orderClause = orderClause;
2445  wc->copiedOrder = false;
2446  }
2447  if (refwc && refwc->frameOptions != FRAMEOPTION_DEFAULTS)
2448  {
2449  /*
2450  * Use this message if this is a WINDOW clause, or if it's an OVER
2451  * clause that includes ORDER BY or framing clauses. (We already
2452  * rejected PARTITION BY above, so no need to check that.)
2453  */
2454  if (windef->name ||
2455  orderClause || windef->frameOptions != FRAMEOPTION_DEFAULTS)
2456  ereport(ERROR,
2457  (errcode(ERRCODE_WINDOWING_ERROR),
2458  errmsg("cannot copy window \"%s\" because it has a frame clause",
2459  windef->refname),
2460  parser_errposition(pstate, windef->location)));
2461  /* Else this clause is just OVER (foo), so say this: */
2462  ereport(ERROR,
2463  (errcode(ERRCODE_WINDOWING_ERROR),
2464  errmsg("cannot copy window \"%s\" because it has a frame clause",
2465  windef->refname),
2466  errhint("Omit the parentheses in this OVER clause."),
2467  parser_errposition(pstate, windef->location)));
2468  }
2469  wc->frameOptions = windef->frameOptions;
2470  /* Process frame offset expressions */
2471  wc->startOffset = transformFrameOffset(pstate, wc->frameOptions,
2472  windef->startOffset);
2473  wc->endOffset = transformFrameOffset(pstate, wc->frameOptions,
2474  windef->endOffset);
2475  wc->winref = winref;
2476 
2477  result = lappend(result, wc);
2478  }
2479 
2480  return result;
2481 }
List * partitionClause
Definition: parsenodes.h:480
char * refname
Definition: parsenodes.h:1194
#define NIL
Definition: pg_list.h:69
bool copiedOrder
Definition: parsenodes.h:1201
int errhint(const char *fmt,...)
Definition: elog.c:987
#define FRAMEOPTION_DEFAULTS
Definition: parsenodes.h:516
int frameOptions
Definition: parsenodes.h:482
List * transformSortClause(ParseState *pstate, List *orderlist, List **targetlist, ParseExprKind exprKind, bool useSQL99)
char * name
Definition: parsenodes.h:478
int errcode(int sqlerrcode)
Definition: elog.c:575
static Node * transformFrameOffset(ParseState *pstate, int frameOptions, Node *clause)
void * copyObject(const void *from)
Definition: copyfuncs.c:4475
Node * startOffset
Definition: parsenodes.h:483
#define ERROR
Definition: elog.h:43
List * partitionClause
Definition: parsenodes.h:1195
int location
Definition: parsenodes.h:485
Node * endOffset
Definition: parsenodes.h:484
List * transformGroupClause(ParseState *pstate, List *grouplist, List **groupingSets, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99)
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
Node * startOffset
Definition: parsenodes.h:1198
List * orderClause
Definition: parsenodes.h:481
unsigned int Index
Definition: c.h:362
#define makeNode(_type_)
Definition: nodes.h:556
#define NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
Node * endOffset
Definition: parsenodes.h:1199
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:109
List * orderClause
Definition: parsenodes.h:1196
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * refname
Definition: parsenodes.h:479
Definition: pg_list.h:45
static WindowClause * findWindowClause(List *wclist, const char *name)