PostgreSQL Source Code  git master
parse_expr.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * parse_expr.c
4  * handle expressions in parser
5  *
6  * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/backend/parser/parse_expr.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 
16 #include "postgres.h"
17 
18 #include "catalog/pg_aggregate.h"
19 #include "catalog/pg_proc.h"
20 #include "catalog/pg_type.h"
21 #include "commands/dbcommands.h"
22 #include "miscadmin.h"
23 #include "nodes/makefuncs.h"
24 #include "nodes/nodeFuncs.h"
25 #include "optimizer/optimizer.h"
26 #include "parser/analyze.h"
27 #include "parser/parse_agg.h"
28 #include "parser/parse_clause.h"
29 #include "parser/parse_coerce.h"
30 #include "parser/parse_collate.h"
31 #include "parser/parse_expr.h"
32 #include "parser/parse_func.h"
33 #include "parser/parse_oper.h"
34 #include "parser/parse_relation.h"
35 #include "parser/parse_target.h"
36 #include "parser/parse_type.h"
37 #include "utils/builtins.h"
38 #include "utils/date.h"
39 #include "utils/fmgroids.h"
40 #include "utils/lsyscache.h"
41 #include "utils/timestamp.h"
42 #include "utils/xml.h"
43 
44 /* GUC parameters */
45 bool Transform_null_equals = false;
46 
47 
48 static Node *transformExprRecurse(ParseState *pstate, Node *expr);
49 static Node *transformParamRef(ParseState *pstate, ParamRef *pref);
50 static Node *transformAExprOp(ParseState *pstate, A_Expr *a);
51 static Node *transformAExprOpAny(ParseState *pstate, A_Expr *a);
52 static Node *transformAExprOpAll(ParseState *pstate, A_Expr *a);
53 static Node *transformAExprDistinct(ParseState *pstate, A_Expr *a);
54 static Node *transformAExprNullIf(ParseState *pstate, A_Expr *a);
55 static Node *transformAExprIn(ParseState *pstate, A_Expr *a);
56 static Node *transformAExprBetween(ParseState *pstate, A_Expr *a);
57 static Node *transformBoolExpr(ParseState *pstate, BoolExpr *a);
58 static Node *transformFuncCall(ParseState *pstate, FuncCall *fn);
59 static Node *transformMultiAssignRef(ParseState *pstate, MultiAssignRef *maref);
60 static Node *transformCaseExpr(ParseState *pstate, CaseExpr *c);
61 static Node *transformSubLink(ParseState *pstate, SubLink *sublink);
63  Oid array_type, Oid element_type, int32 typmod);
64 static Node *transformRowExpr(ParseState *pstate, RowExpr *r, bool allowDefault);
66 static Node *transformMinMaxExpr(ParseState *pstate, MinMaxExpr *m);
68  SQLValueFunction *svf);
69 static Node *transformXmlExpr(ParseState *pstate, XmlExpr *x);
72 static Node *transformCurrentOfExpr(ParseState *pstate, CurrentOfExpr *cexpr);
73 static Node *transformColumnRef(ParseState *pstate, ColumnRef *cref);
74 static Node *transformWholeRowRef(ParseState *pstate,
75  ParseNamespaceItem *nsitem,
76  int sublevels_up, int location);
78 static Node *transformTypeCast(ParseState *pstate, TypeCast *tc);
81  JsonObjectConstructor *ctor);
83  JsonArrayConstructor *ctor);
87 static Node *transformJsonArrayAgg(ParseState *pstate, JsonArrayAgg *agg);
89 static Node *transformJsonParseExpr(ParseState *pstate, JsonParseExpr *expr);
92  JsonSerializeExpr *expr);
93 static Node *make_row_comparison_op(ParseState *pstate, List *opname,
94  List *largs, List *rargs, int location);
95 static Node *make_row_distinct_op(ParseState *pstate, List *opname,
96  RowExpr *lrow, RowExpr *rrow, int location);
97 static Expr *make_distinct_op(ParseState *pstate, List *opname,
98  Node *ltree, Node *rtree, int location);
100  A_Expr *distincta, Node *arg);
101 
102 
103 /*
104  * transformExpr -
105  * Analyze and transform expressions. Type checking and type casting is
106  * done here. This processing converts the raw grammar output into
107  * expression trees with fully determined semantics.
108  */
109 Node *
110 transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
111 {
112  Node *result;
113  ParseExprKind sv_expr_kind;
114 
115  /* Save and restore identity of expression type we're parsing */
116  Assert(exprKind != EXPR_KIND_NONE);
117  sv_expr_kind = pstate->p_expr_kind;
118  pstate->p_expr_kind = exprKind;
119 
120  result = transformExprRecurse(pstate, expr);
121 
122  pstate->p_expr_kind = sv_expr_kind;
123 
124  return result;
125 }
126 
127 static Node *
129 {
130  Node *result;
131 
132  if (expr == NULL)
133  return NULL;
134 
135  /* Guard against stack overflow due to overly complex expressions */
137 
138  switch (nodeTag(expr))
139  {
140  case T_ColumnRef:
141  result = transformColumnRef(pstate, (ColumnRef *) expr);
142  break;
143 
144  case T_ParamRef:
145  result = transformParamRef(pstate, (ParamRef *) expr);
146  break;
147 
148  case T_A_Const:
149  result = (Node *) make_const(pstate, (A_Const *) expr);
150  break;
151 
152  case T_A_Indirection:
153  result = transformIndirection(pstate, (A_Indirection *) expr);
154  break;
155 
156  case T_A_ArrayExpr:
157  result = transformArrayExpr(pstate, (A_ArrayExpr *) expr,
158  InvalidOid, InvalidOid, -1);
159  break;
160 
161  case T_TypeCast:
162  result = transformTypeCast(pstate, (TypeCast *) expr);
163  break;
164 
165  case T_CollateClause:
166  result = transformCollateClause(pstate, (CollateClause *) expr);
167  break;
168 
169  case T_A_Expr:
170  {
171  A_Expr *a = (A_Expr *) expr;
172 
173  switch (a->kind)
174  {
175  case AEXPR_OP:
176  result = transformAExprOp(pstate, a);
177  break;
178  case AEXPR_OP_ANY:
179  result = transformAExprOpAny(pstate, a);
180  break;
181  case AEXPR_OP_ALL:
182  result = transformAExprOpAll(pstate, a);
183  break;
184  case AEXPR_DISTINCT:
185  case AEXPR_NOT_DISTINCT:
186  result = transformAExprDistinct(pstate, a);
187  break;
188  case AEXPR_NULLIF:
189  result = transformAExprNullIf(pstate, a);
190  break;
191  case AEXPR_IN:
192  result = transformAExprIn(pstate, a);
193  break;
194  case AEXPR_LIKE:
195  case AEXPR_ILIKE:
196  case AEXPR_SIMILAR:
197  /* we can transform these just like AEXPR_OP */
198  result = transformAExprOp(pstate, a);
199  break;
200  case AEXPR_BETWEEN:
201  case AEXPR_NOT_BETWEEN:
202  case AEXPR_BETWEEN_SYM:
204  result = transformAExprBetween(pstate, a);
205  break;
206  default:
207  elog(ERROR, "unrecognized A_Expr kind: %d", a->kind);
208  result = NULL; /* keep compiler quiet */
209  break;
210  }
211  break;
212  }
213 
214  case T_BoolExpr:
215  result = transformBoolExpr(pstate, (BoolExpr *) expr);
216  break;
217 
218  case T_FuncCall:
219  result = transformFuncCall(pstate, (FuncCall *) expr);
220  break;
221 
222  case T_MultiAssignRef:
223  result = transformMultiAssignRef(pstate, (MultiAssignRef *) expr);
224  break;
225 
226  case T_GroupingFunc:
227  result = transformGroupingFunc(pstate, (GroupingFunc *) expr);
228  break;
229 
230  case T_NamedArgExpr:
231  {
232  NamedArgExpr *na = (NamedArgExpr *) expr;
233 
234  na->arg = (Expr *) transformExprRecurse(pstate, (Node *) na->arg);
235  result = expr;
236  break;
237  }
238 
239  case T_SubLink:
240  result = transformSubLink(pstate, (SubLink *) expr);
241  break;
242 
243  case T_CaseExpr:
244  result = transformCaseExpr(pstate, (CaseExpr *) expr);
245  break;
246 
247  case T_RowExpr:
248  result = transformRowExpr(pstate, (RowExpr *) expr, false);
249  break;
250 
251  case T_CoalesceExpr:
252  result = transformCoalesceExpr(pstate, (CoalesceExpr *) expr);
253  break;
254 
255  case T_MinMaxExpr:
256  result = transformMinMaxExpr(pstate, (MinMaxExpr *) expr);
257  break;
258 
259  case T_SQLValueFunction:
260  result = transformSQLValueFunction(pstate,
261  (SQLValueFunction *) expr);
262  break;
263 
264  case T_XmlExpr:
265  result = transformXmlExpr(pstate, (XmlExpr *) expr);
266  break;
267 
268  case T_XmlSerialize:
269  result = transformXmlSerialize(pstate, (XmlSerialize *) expr);
270  break;
271 
272  case T_NullTest:
273  {
274  NullTest *n = (NullTest *) expr;
275 
276  n->arg = (Expr *) transformExprRecurse(pstate, (Node *) n->arg);
277  /* the argument can be any type, so don't coerce it */
278  n->argisrow = type_is_rowtype(exprType((Node *) n->arg));
279  result = expr;
280  break;
281  }
282 
283  case T_BooleanTest:
284  result = transformBooleanTest(pstate, (BooleanTest *) expr);
285  break;
286 
287  case T_CurrentOfExpr:
288  result = transformCurrentOfExpr(pstate, (CurrentOfExpr *) expr);
289  break;
290 
291  /*
292  * In all places where DEFAULT is legal, the caller should have
293  * processed it rather than passing it to transformExpr().
294  */
295  case T_SetToDefault:
296  ereport(ERROR,
297  (errcode(ERRCODE_SYNTAX_ERROR),
298  errmsg("DEFAULT is not allowed in this context"),
299  parser_errposition(pstate,
300  ((SetToDefault *) expr)->location)));
301  break;
302 
303  /*
304  * CaseTestExpr doesn't require any processing; it is only
305  * injected into parse trees in a fully-formed state.
306  *
307  * Ordinarily we should not see a Var here, but it is convenient
308  * for transformJoinUsingClause() to create untransformed operator
309  * trees containing already-transformed Vars. The best
310  * alternative would be to deconstruct and reconstruct column
311  * references, which seems expensively pointless. So allow it.
312  */
313  case T_CaseTestExpr:
314  case T_Var:
315  {
316  result = (Node *) expr;
317  break;
318  }
319 
320  case T_JsonObjectConstructor:
321  result = transformJsonObjectConstructor(pstate, (JsonObjectConstructor *) expr);
322  break;
323 
324  case T_JsonArrayConstructor:
325  result = transformJsonArrayConstructor(pstate, (JsonArrayConstructor *) expr);
326  break;
327 
328  case T_JsonArrayQueryConstructor:
330  break;
331 
332  case T_JsonObjectAgg:
333  result = transformJsonObjectAgg(pstate, (JsonObjectAgg *) expr);
334  break;
335 
336  case T_JsonArrayAgg:
337  result = transformJsonArrayAgg(pstate, (JsonArrayAgg *) expr);
338  break;
339 
340  case T_JsonIsPredicate:
341  result = transformJsonIsPredicate(pstate, (JsonIsPredicate *) expr);
342  break;
343 
344  case T_JsonParseExpr:
345  result = transformJsonParseExpr(pstate, (JsonParseExpr *) expr);
346  break;
347 
348  case T_JsonScalarExpr:
349  result = transformJsonScalarExpr(pstate, (JsonScalarExpr *) expr);
350  break;
351 
352  case T_JsonSerializeExpr:
353  result = transformJsonSerializeExpr(pstate, (JsonSerializeExpr *) expr);
354  break;
355 
356  default:
357  /* should not reach here */
358  elog(ERROR, "unrecognized node type: %d", (int) nodeTag(expr));
359  result = NULL; /* keep compiler quiet */
360  break;
361  }
362 
363  return result;
364 }
365 
366 /*
367  * helper routine for delivering "column does not exist" error message
368  *
369  * (Usually we don't have to work this hard, but the general case of field
370  * selection from an arbitrary node needs it.)
371  */
372 static void
373 unknown_attribute(ParseState *pstate, Node *relref, const char *attname,
374  int location)
375 {
376  RangeTblEntry *rte;
377 
378  if (IsA(relref, Var) &&
379  ((Var *) relref)->varattno == InvalidAttrNumber)
380  {
381  /* Reference the RTE by alias not by actual table name */
382  rte = GetRTEByRangeTablePosn(pstate,
383  ((Var *) relref)->varno,
384  ((Var *) relref)->varlevelsup);
385  ereport(ERROR,
386  (errcode(ERRCODE_UNDEFINED_COLUMN),
387  errmsg("column %s.%s does not exist",
388  rte->eref->aliasname, attname),
389  parser_errposition(pstate, location)));
390  }
391  else
392  {
393  /* Have to do it by reference to the type of the expression */
394  Oid relTypeId = exprType(relref);
395 
396  if (ISCOMPLEX(relTypeId))
397  ereport(ERROR,
398  (errcode(ERRCODE_UNDEFINED_COLUMN),
399  errmsg("column \"%s\" not found in data type %s",
400  attname, format_type_be(relTypeId)),
401  parser_errposition(pstate, location)));
402  else if (relTypeId == RECORDOID)
403  ereport(ERROR,
404  (errcode(ERRCODE_UNDEFINED_COLUMN),
405  errmsg("could not identify column \"%s\" in record data type",
406  attname),
407  parser_errposition(pstate, location)));
408  else
409  ereport(ERROR,
410  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
411  errmsg("column notation .%s applied to type %s, "
412  "which is not a composite type",
413  attname, format_type_be(relTypeId)),
414  parser_errposition(pstate, location)));
415  }
416 }
417 
418 static Node *
420 {
421  Node *last_srf = pstate->p_last_srf;
422  Node *result = transformExprRecurse(pstate, ind->arg);
423  List *subscripts = NIL;
424  int location = exprLocation(result);
425  ListCell *i;
426 
427  /*
428  * We have to split any field-selection operations apart from
429  * subscripting. Adjacent A_Indices nodes have to be treated as a single
430  * multidimensional subscript operation.
431  */
432  foreach(i, ind->indirection)
433  {
434  Node *n = lfirst(i);
435 
436  if (IsA(n, A_Indices))
437  subscripts = lappend(subscripts, n);
438  else if (IsA(n, A_Star))
439  {
440  ereport(ERROR,
441  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
442  errmsg("row expansion via \"*\" is not supported here"),
443  parser_errposition(pstate, location)));
444  }
445  else
446  {
447  Node *newresult;
448 
449  Assert(IsA(n, String));
450 
451  /* process subscripts before this field selection */
452  if (subscripts)
453  result = (Node *) transformContainerSubscripts(pstate,
454  result,
455  exprType(result),
456  exprTypmod(result),
457  subscripts,
458  false);
459  subscripts = NIL;
460 
461  newresult = ParseFuncOrColumn(pstate,
462  list_make1(n),
463  list_make1(result),
464  last_srf,
465  NULL,
466  false,
467  location);
468  if (newresult == NULL)
469  unknown_attribute(pstate, result, strVal(n), location);
470  result = newresult;
471  }
472  }
473  /* process trailing subscripts, if any */
474  if (subscripts)
475  result = (Node *) transformContainerSubscripts(pstate,
476  result,
477  exprType(result),
478  exprTypmod(result),
479  subscripts,
480  false);
481 
482  return result;
483 }
484 
485 /*
486  * Transform a ColumnRef.
487  *
488  * If you find yourself changing this code, see also ExpandColumnRefStar.
489  */
490 static Node *
492 {
493  Node *node = NULL;
494  char *nspname = NULL;
495  char *relname = NULL;
496  char *colname = NULL;
497  ParseNamespaceItem *nsitem;
498  int levels_up;
499  enum
500  {
501  CRERR_NO_COLUMN,
502  CRERR_NO_RTE,
503  CRERR_WRONG_DB,
504  CRERR_TOO_MANY
505  } crerr = CRERR_NO_COLUMN;
506  const char *err;
507 
508  /*
509  * Check to see if the column reference is in an invalid place within the
510  * query. We allow column references in most places, except in default
511  * expressions and partition bound expressions.
512  */
513  err = NULL;
514  switch (pstate->p_expr_kind)
515  {
516  case EXPR_KIND_NONE:
517  Assert(false); /* can't happen */
518  break;
519  case EXPR_KIND_OTHER:
520  case EXPR_KIND_JOIN_ON:
524  case EXPR_KIND_WHERE:
525  case EXPR_KIND_POLICY:
526  case EXPR_KIND_HAVING:
527  case EXPR_KIND_FILTER:
538  case EXPR_KIND_GROUP_BY:
539  case EXPR_KIND_ORDER_BY:
541  case EXPR_KIND_LIMIT:
542  case EXPR_KIND_OFFSET:
543  case EXPR_KIND_RETURNING:
544  case EXPR_KIND_VALUES:
560  /* okay */
561  break;
562 
564  err = _("cannot use column reference in DEFAULT expression");
565  break;
567  err = _("cannot use column reference in partition bound expression");
568  break;
569 
570  /*
571  * There is intentionally no default: case here, so that the
572  * compiler will warn if we add a new ParseExprKind without
573  * extending this switch. If we do see an unrecognized value at
574  * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
575  * which is sane anyway.
576  */
577  }
578  if (err)
579  ereport(ERROR,
580  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
581  errmsg_internal("%s", err),
582  parser_errposition(pstate, cref->location)));
583 
584  /*
585  * Give the PreParseColumnRefHook, if any, first shot. If it returns
586  * non-null then that's all, folks.
587  */
588  if (pstate->p_pre_columnref_hook != NULL)
589  {
590  node = pstate->p_pre_columnref_hook(pstate, cref);
591  if (node != NULL)
592  return node;
593  }
594 
595  /*----------
596  * The allowed syntaxes are:
597  *
598  * A First try to resolve as unqualified column name;
599  * if no luck, try to resolve as unqualified table name (A.*).
600  * A.B A is an unqualified table name; B is either a
601  * column or function name (trying column name first).
602  * A.B.C schema A, table B, col or func name C.
603  * A.B.C.D catalog A, schema B, table C, col or func D.
604  * A.* A is an unqualified table name; means whole-row value.
605  * A.B.* whole-row value of table B in schema A.
606  * A.B.C.* whole-row value of table C in schema B in catalog A.
607  *
608  * We do not need to cope with bare "*"; that will only be accepted by
609  * the grammar at the top level of a SELECT list, and transformTargetList
610  * will take care of it before it ever gets here. Also, "A.*" etc will
611  * be expanded by transformTargetList if they appear at SELECT top level,
612  * so here we are only going to see them as function or operator inputs.
613  *
614  * Currently, if a catalog name is given then it must equal the current
615  * database name; we check it here and then discard it.
616  *----------
617  */
618  switch (list_length(cref->fields))
619  {
620  case 1:
621  {
622  Node *field1 = (Node *) linitial(cref->fields);
623 
624  colname = strVal(field1);
625 
626  /* Try to identify as an unqualified column */
627  node = colNameToVar(pstate, colname, false, cref->location);
628 
629  if (node == NULL)
630  {
631  /*
632  * Not known as a column of any range-table entry.
633  *
634  * Try to find the name as a relation. Note that only
635  * relations already entered into the rangetable will be
636  * recognized.
637  *
638  * This is a hack for backwards compatibility with
639  * PostQUEL-inspired syntax. The preferred form now is
640  * "rel.*".
641  */
642  nsitem = refnameNamespaceItem(pstate, NULL, colname,
643  cref->location,
644  &levels_up);
645  if (nsitem)
646  node = transformWholeRowRef(pstate, nsitem, levels_up,
647  cref->location);
648  }
649  break;
650  }
651  case 2:
652  {
653  Node *field1 = (Node *) linitial(cref->fields);
654  Node *field2 = (Node *) lsecond(cref->fields);
655 
656  relname = strVal(field1);
657 
658  /* Locate the referenced nsitem */
659  nsitem = refnameNamespaceItem(pstate, nspname, relname,
660  cref->location,
661  &levels_up);
662  if (nsitem == NULL)
663  {
664  crerr = CRERR_NO_RTE;
665  break;
666  }
667 
668  /* Whole-row reference? */
669  if (IsA(field2, A_Star))
670  {
671  node = transformWholeRowRef(pstate, nsitem, levels_up,
672  cref->location);
673  break;
674  }
675 
676  colname = strVal(field2);
677 
678  /* Try to identify as a column of the nsitem */
679  node = scanNSItemForColumn(pstate, nsitem, levels_up, colname,
680  cref->location);
681  if (node == NULL)
682  {
683  /* Try it as a function call on the whole row */
684  node = transformWholeRowRef(pstate, nsitem, levels_up,
685  cref->location);
686  node = ParseFuncOrColumn(pstate,
687  list_make1(makeString(colname)),
688  list_make1(node),
689  pstate->p_last_srf,
690  NULL,
691  false,
692  cref->location);
693  }
694  break;
695  }
696  case 3:
697  {
698  Node *field1 = (Node *) linitial(cref->fields);
699  Node *field2 = (Node *) lsecond(cref->fields);
700  Node *field3 = (Node *) lthird(cref->fields);
701 
702  nspname = strVal(field1);
703  relname = strVal(field2);
704 
705  /* Locate the referenced nsitem */
706  nsitem = refnameNamespaceItem(pstate, nspname, relname,
707  cref->location,
708  &levels_up);
709  if (nsitem == NULL)
710  {
711  crerr = CRERR_NO_RTE;
712  break;
713  }
714 
715  /* Whole-row reference? */
716  if (IsA(field3, A_Star))
717  {
718  node = transformWholeRowRef(pstate, nsitem, levels_up,
719  cref->location);
720  break;
721  }
722 
723  colname = strVal(field3);
724 
725  /* Try to identify as a column of the nsitem */
726  node = scanNSItemForColumn(pstate, nsitem, levels_up, colname,
727  cref->location);
728  if (node == NULL)
729  {
730  /* Try it as a function call on the whole row */
731  node = transformWholeRowRef(pstate, nsitem, levels_up,
732  cref->location);
733  node = ParseFuncOrColumn(pstate,
734  list_make1(makeString(colname)),
735  list_make1(node),
736  pstate->p_last_srf,
737  NULL,
738  false,
739  cref->location);
740  }
741  break;
742  }
743  case 4:
744  {
745  Node *field1 = (Node *) linitial(cref->fields);
746  Node *field2 = (Node *) lsecond(cref->fields);
747  Node *field3 = (Node *) lthird(cref->fields);
748  Node *field4 = (Node *) lfourth(cref->fields);
749  char *catname;
750 
751  catname = strVal(field1);
752  nspname = strVal(field2);
753  relname = strVal(field3);
754 
755  /*
756  * We check the catalog name and then ignore it.
757  */
758  if (strcmp(catname, get_database_name(MyDatabaseId)) != 0)
759  {
760  crerr = CRERR_WRONG_DB;
761  break;
762  }
763 
764  /* Locate the referenced nsitem */
765  nsitem = refnameNamespaceItem(pstate, nspname, relname,
766  cref->location,
767  &levels_up);
768  if (nsitem == NULL)
769  {
770  crerr = CRERR_NO_RTE;
771  break;
772  }
773 
774  /* Whole-row reference? */
775  if (IsA(field4, A_Star))
776  {
777  node = transformWholeRowRef(pstate, nsitem, levels_up,
778  cref->location);
779  break;
780  }
781 
782  colname = strVal(field4);
783 
784  /* Try to identify as a column of the nsitem */
785  node = scanNSItemForColumn(pstate, nsitem, levels_up, colname,
786  cref->location);
787  if (node == NULL)
788  {
789  /* Try it as a function call on the whole row */
790  node = transformWholeRowRef(pstate, nsitem, levels_up,
791  cref->location);
792  node = ParseFuncOrColumn(pstate,
793  list_make1(makeString(colname)),
794  list_make1(node),
795  pstate->p_last_srf,
796  NULL,
797  false,
798  cref->location);
799  }
800  break;
801  }
802  default:
803  crerr = CRERR_TOO_MANY; /* too many dotted names */
804  break;
805  }
806 
807  /*
808  * Now give the PostParseColumnRefHook, if any, a chance. We pass the
809  * translation-so-far so that it can throw an error if it wishes in the
810  * case that it has a conflicting interpretation of the ColumnRef. (If it
811  * just translates anyway, we'll throw an error, because we can't undo
812  * whatever effects the preceding steps may have had on the pstate.) If it
813  * returns NULL, use the standard translation, or throw a suitable error
814  * if there is none.
815  */
816  if (pstate->p_post_columnref_hook != NULL)
817  {
818  Node *hookresult;
819 
820  hookresult = pstate->p_post_columnref_hook(pstate, cref, node);
821  if (node == NULL)
822  node = hookresult;
823  else if (hookresult != NULL)
824  ereport(ERROR,
825  (errcode(ERRCODE_AMBIGUOUS_COLUMN),
826  errmsg("column reference \"%s\" is ambiguous",
827  NameListToString(cref->fields)),
828  parser_errposition(pstate, cref->location)));
829  }
830 
831  /*
832  * Throw error if no translation found.
833  */
834  if (node == NULL)
835  {
836  switch (crerr)
837  {
838  case CRERR_NO_COLUMN:
839  errorMissingColumn(pstate, relname, colname, cref->location);
840  break;
841  case CRERR_NO_RTE:
842  errorMissingRTE(pstate, makeRangeVar(nspname, relname,
843  cref->location));
844  break;
845  case CRERR_WRONG_DB:
846  ereport(ERROR,
847  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
848  errmsg("cross-database references are not implemented: %s",
849  NameListToString(cref->fields)),
850  parser_errposition(pstate, cref->location)));
851  break;
852  case CRERR_TOO_MANY:
853  ereport(ERROR,
854  (errcode(ERRCODE_SYNTAX_ERROR),
855  errmsg("improper qualified name (too many dotted names): %s",
856  NameListToString(cref->fields)),
857  parser_errposition(pstate, cref->location)));
858  break;
859  }
860  }
861 
862  return node;
863 }
864 
865 static Node *
867 {
868  Node *result;
869 
870  /*
871  * The core parser knows nothing about Params. If a hook is supplied,
872  * call it. If not, or if the hook returns NULL, throw a generic error.
873  */
874  if (pstate->p_paramref_hook != NULL)
875  result = pstate->p_paramref_hook(pstate, pref);
876  else
877  result = NULL;
878 
879  if (result == NULL)
880  ereport(ERROR,
881  (errcode(ERRCODE_UNDEFINED_PARAMETER),
882  errmsg("there is no parameter $%d", pref->number),
883  parser_errposition(pstate, pref->location)));
884 
885  return result;
886 }
887 
888 /* Test whether an a_expr is a plain NULL constant or not */
889 static bool
891 {
892  if (arg && IsA(arg, A_Const))
893  {
894  A_Const *con = (A_Const *) arg;
895 
896  if (con->isnull)
897  return true;
898  }
899  return false;
900 }
901 
902 static Node *
904 {
905  Node *lexpr = a->lexpr;
906  Node *rexpr = a->rexpr;
907  Node *result;
908 
909  /*
910  * Special-case "foo = NULL" and "NULL = foo" for compatibility with
911  * standards-broken products (like Microsoft's). Turn these into IS NULL
912  * exprs. (If either side is a CaseTestExpr, then the expression was
913  * generated internally from a CASE-WHEN expression, and
914  * transform_null_equals does not apply.)
915  */
916  if (Transform_null_equals &&
917  list_length(a->name) == 1 &&
918  strcmp(strVal(linitial(a->name)), "=") == 0 &&
919  (exprIsNullConstant(lexpr) || exprIsNullConstant(rexpr)) &&
920  (!IsA(lexpr, CaseTestExpr) && !IsA(rexpr, CaseTestExpr)))
921  {
922  NullTest *n = makeNode(NullTest);
923 
924  n->nulltesttype = IS_NULL;
925  n->location = a->location;
926 
927  if (exprIsNullConstant(lexpr))
928  n->arg = (Expr *) rexpr;
929  else
930  n->arg = (Expr *) lexpr;
931 
932  result = transformExprRecurse(pstate, (Node *) n);
933  }
934  else if (lexpr && IsA(lexpr, RowExpr) &&
935  rexpr && IsA(rexpr, SubLink) &&
936  ((SubLink *) rexpr)->subLinkType == EXPR_SUBLINK)
937  {
938  /*
939  * Convert "row op subselect" into a ROWCOMPARE sublink. Formerly the
940  * grammar did this, but now that a row construct is allowed anywhere
941  * in expressions, it's easier to do it here.
942  */
943  SubLink *s = (SubLink *) rexpr;
944 
946  s->testexpr = lexpr;
947  s->operName = a->name;
948  s->location = a->location;
949  result = transformExprRecurse(pstate, (Node *) s);
950  }
951  else if (lexpr && IsA(lexpr, RowExpr) &&
952  rexpr && IsA(rexpr, RowExpr))
953  {
954  /* ROW() op ROW() is handled specially */
955  lexpr = transformExprRecurse(pstate, lexpr);
956  rexpr = transformExprRecurse(pstate, rexpr);
957 
958  result = make_row_comparison_op(pstate,
959  a->name,
960  castNode(RowExpr, lexpr)->args,
961  castNode(RowExpr, rexpr)->args,
962  a->location);
963  }
964  else
965  {
966  /* Ordinary scalar operator */
967  Node *last_srf = pstate->p_last_srf;
968 
969  lexpr = transformExprRecurse(pstate, lexpr);
970  rexpr = transformExprRecurse(pstate, rexpr);
971 
972  result = (Node *) make_op(pstate,
973  a->name,
974  lexpr,
975  rexpr,
976  last_srf,
977  a->location);
978  }
979 
980  return result;
981 }
982 
983 static Node *
985 {
986  Node *lexpr = transformExprRecurse(pstate, a->lexpr);
987  Node *rexpr = transformExprRecurse(pstate, a->rexpr);
988 
989  return (Node *) make_scalar_array_op(pstate,
990  a->name,
991  true,
992  lexpr,
993  rexpr,
994  a->location);
995 }
996 
997 static Node *
999 {
1000  Node *lexpr = transformExprRecurse(pstate, a->lexpr);
1001  Node *rexpr = transformExprRecurse(pstate, a->rexpr);
1002 
1003  return (Node *) make_scalar_array_op(pstate,
1004  a->name,
1005  false,
1006  lexpr,
1007  rexpr,
1008  a->location);
1009 }
1010 
1011 static Node *
1013 {
1014  Node *lexpr = a->lexpr;
1015  Node *rexpr = a->rexpr;
1016  Node *result;
1017 
1018  /*
1019  * If either input is an undecorated NULL literal, transform to a NullTest
1020  * on the other input. That's simpler to process than a full DistinctExpr,
1021  * and it avoids needing to require that the datatype have an = operator.
1022  */
1023  if (exprIsNullConstant(rexpr))
1024  return make_nulltest_from_distinct(pstate, a, lexpr);
1025  if (exprIsNullConstant(lexpr))
1026  return make_nulltest_from_distinct(pstate, a, rexpr);
1027 
1028  lexpr = transformExprRecurse(pstate, lexpr);
1029  rexpr = transformExprRecurse(pstate, rexpr);
1030 
1031  if (lexpr && IsA(lexpr, RowExpr) &&
1032  rexpr && IsA(rexpr, RowExpr))
1033  {
1034  /* ROW() op ROW() is handled specially */
1035  result = make_row_distinct_op(pstate, a->name,
1036  (RowExpr *) lexpr,
1037  (RowExpr *) rexpr,
1038  a->location);
1039  }
1040  else
1041  {
1042  /* Ordinary scalar operator */
1043  result = (Node *) make_distinct_op(pstate,
1044  a->name,
1045  lexpr,
1046  rexpr,
1047  a->location);
1048  }
1049 
1050  /*
1051  * If it's NOT DISTINCT, we first build a DistinctExpr and then stick a
1052  * NOT on top.
1053  */
1054  if (a->kind == AEXPR_NOT_DISTINCT)
1055  result = (Node *) makeBoolExpr(NOT_EXPR,
1056  list_make1(result),
1057  a->location);
1058 
1059  return result;
1060 }
1061 
1062 static Node *
1064 {
1065  Node *lexpr = transformExprRecurse(pstate, a->lexpr);
1066  Node *rexpr = transformExprRecurse(pstate, a->rexpr);
1067  OpExpr *result;
1068 
1069  result = (OpExpr *) make_op(pstate,
1070  a->name,
1071  lexpr,
1072  rexpr,
1073  pstate->p_last_srf,
1074  a->location);
1075 
1076  /*
1077  * The comparison operator itself should yield boolean ...
1078  */
1079  if (result->opresulttype != BOOLOID)
1080  ereport(ERROR,
1081  (errcode(ERRCODE_DATATYPE_MISMATCH),
1082  errmsg("NULLIF requires = operator to yield boolean"),
1083  parser_errposition(pstate, a->location)));
1084  if (result->opretset)
1085  ereport(ERROR,
1086  (errcode(ERRCODE_DATATYPE_MISMATCH),
1087  /* translator: %s is name of a SQL construct, eg NULLIF */
1088  errmsg("%s must not return a set", "NULLIF"),
1089  parser_errposition(pstate, a->location)));
1090 
1091  /*
1092  * ... but the NullIfExpr will yield the first operand's type.
1093  */
1094  result->opresulttype = exprType((Node *) linitial(result->args));
1095 
1096  /*
1097  * We rely on NullIfExpr and OpExpr being the same struct
1098  */
1099  NodeSetTag(result, T_NullIfExpr);
1100 
1101  return (Node *) result;
1102 }
1103 
1104 static Node *
1106 {
1107  Node *result = NULL;
1108  Node *lexpr;
1109  List *rexprs;
1110  List *rvars;
1111  List *rnonvars;
1112  bool useOr;
1113  ListCell *l;
1114 
1115  /*
1116  * If the operator is <>, combine with AND not OR.
1117  */
1118  if (strcmp(strVal(linitial(a->name)), "<>") == 0)
1119  useOr = false;
1120  else
1121  useOr = true;
1122 
1123  /*
1124  * We try to generate a ScalarArrayOpExpr from IN/NOT IN, but this is only
1125  * possible if there is a suitable array type available. If not, we fall
1126  * back to a boolean condition tree with multiple copies of the lefthand
1127  * expression. Also, any IN-list items that contain Vars are handled as
1128  * separate boolean conditions, because that gives the planner more scope
1129  * for optimization on such clauses.
1130  *
1131  * First step: transform all the inputs, and detect whether any contain
1132  * Vars.
1133  */
1134  lexpr = transformExprRecurse(pstate, a->lexpr);
1135  rexprs = rvars = rnonvars = NIL;
1136  foreach(l, (List *) a->rexpr)
1137  {
1138  Node *rexpr = transformExprRecurse(pstate, lfirst(l));
1139 
1140  rexprs = lappend(rexprs, rexpr);
1141  if (contain_vars_of_level(rexpr, 0))
1142  rvars = lappend(rvars, rexpr);
1143  else
1144  rnonvars = lappend(rnonvars, rexpr);
1145  }
1146 
1147  /*
1148  * ScalarArrayOpExpr is only going to be useful if there's more than one
1149  * non-Var righthand item.
1150  */
1151  if (list_length(rnonvars) > 1)
1152  {
1153  List *allexprs;
1154  Oid scalar_type;
1155  Oid array_type;
1156 
1157  /*
1158  * Try to select a common type for the array elements. Note that
1159  * since the LHS' type is first in the list, it will be preferred when
1160  * there is doubt (eg, when all the RHS items are unknown literals).
1161  *
1162  * Note: use list_concat here not lcons, to avoid damaging rnonvars.
1163  */
1164  allexprs = list_concat(list_make1(lexpr), rnonvars);
1165  scalar_type = select_common_type(pstate, allexprs, NULL, NULL);
1166 
1167  /* We have to verify that the selected type actually works */
1168  if (OidIsValid(scalar_type) &&
1169  !verify_common_type(scalar_type, allexprs))
1170  scalar_type = InvalidOid;
1171 
1172  /*
1173  * Do we have an array type to use? Aside from the case where there
1174  * isn't one, we don't risk using ScalarArrayOpExpr when the common
1175  * type is RECORD, because the RowExpr comparison logic below can cope
1176  * with some cases of non-identical row types.
1177  */
1178  if (OidIsValid(scalar_type) && scalar_type != RECORDOID)
1179  array_type = get_array_type(scalar_type);
1180  else
1181  array_type = InvalidOid;
1182  if (array_type != InvalidOid)
1183  {
1184  /*
1185  * OK: coerce all the right-hand non-Var inputs to the common type
1186  * and build an ArrayExpr for them.
1187  */
1188  List *aexprs;
1189  ArrayExpr *newa;
1190 
1191  aexprs = NIL;
1192  foreach(l, rnonvars)
1193  {
1194  Node *rexpr = (Node *) lfirst(l);
1195 
1196  rexpr = coerce_to_common_type(pstate, rexpr,
1197  scalar_type,
1198  "IN");
1199  aexprs = lappend(aexprs, rexpr);
1200  }
1201  newa = makeNode(ArrayExpr);
1202  newa->array_typeid = array_type;
1203  /* array_collid will be set by parse_collate.c */
1204  newa->element_typeid = scalar_type;
1205  newa->elements = aexprs;
1206  newa->multidims = false;
1207  newa->location = -1;
1208 
1209  result = (Node *) make_scalar_array_op(pstate,
1210  a->name,
1211  useOr,
1212  lexpr,
1213  (Node *) newa,
1214  a->location);
1215 
1216  /* Consider only the Vars (if any) in the loop below */
1217  rexprs = rvars;
1218  }
1219  }
1220 
1221  /*
1222  * Must do it the hard way, ie, with a boolean expression tree.
1223  */
1224  foreach(l, rexprs)
1225  {
1226  Node *rexpr = (Node *) lfirst(l);
1227  Node *cmp;
1228 
1229  if (IsA(lexpr, RowExpr) &&
1230  IsA(rexpr, RowExpr))
1231  {
1232  /* ROW() op ROW() is handled specially */
1233  cmp = make_row_comparison_op(pstate,
1234  a->name,
1235  copyObject(((RowExpr *) lexpr)->args),
1236  ((RowExpr *) rexpr)->args,
1237  a->location);
1238  }
1239  else
1240  {
1241  /* Ordinary scalar operator */
1242  cmp = (Node *) make_op(pstate,
1243  a->name,
1244  copyObject(lexpr),
1245  rexpr,
1246  pstate->p_last_srf,
1247  a->location);
1248  }
1249 
1250  cmp = coerce_to_boolean(pstate, cmp, "IN");
1251  if (result == NULL)
1252  result = cmp;
1253  else
1254  result = (Node *) makeBoolExpr(useOr ? OR_EXPR : AND_EXPR,
1255  list_make2(result, cmp),
1256  a->location);
1257  }
1258 
1259  return result;
1260 }
1261 
1262 static Node *
1264 {
1265  Node *aexpr;
1266  Node *bexpr;
1267  Node *cexpr;
1268  Node *result;
1269  Node *sub1;
1270  Node *sub2;
1271  List *args;
1272 
1273  /* Deconstruct A_Expr into three subexprs */
1274  aexpr = a->lexpr;
1275  args = castNode(List, a->rexpr);
1276  Assert(list_length(args) == 2);
1277  bexpr = (Node *) linitial(args);
1278  cexpr = (Node *) lsecond(args);
1279 
1280  /*
1281  * Build the equivalent comparison expression. Make copies of
1282  * multiply-referenced subexpressions for safety. (XXX this is really
1283  * wrong since it results in multiple runtime evaluations of what may be
1284  * volatile expressions ...)
1285  *
1286  * Ideally we would not use hard-wired operators here but instead use
1287  * opclasses. However, mixed data types and other issues make this
1288  * difficult:
1289  * http://archives.postgresql.org/pgsql-hackers/2008-08/msg01142.php
1290  */
1291  switch (a->kind)
1292  {
1293  case AEXPR_BETWEEN:
1295  aexpr, bexpr,
1296  a->location),
1297  makeSimpleA_Expr(AEXPR_OP, "<=",
1298  copyObject(aexpr), cexpr,
1299  a->location));
1300  result = (Node *) makeBoolExpr(AND_EXPR, args, a->location);
1301  break;
1302  case AEXPR_NOT_BETWEEN:
1304  aexpr, bexpr,
1305  a->location),
1307  copyObject(aexpr), cexpr,
1308  a->location));
1309  result = (Node *) makeBoolExpr(OR_EXPR, args, a->location);
1310  break;
1311  case AEXPR_BETWEEN_SYM:
1313  aexpr, bexpr,
1314  a->location),
1315  makeSimpleA_Expr(AEXPR_OP, "<=",
1316  copyObject(aexpr), cexpr,
1317  a->location));
1318  sub1 = (Node *) makeBoolExpr(AND_EXPR, args, a->location);
1320  copyObject(aexpr), copyObject(cexpr),
1321  a->location),
1322  makeSimpleA_Expr(AEXPR_OP, "<=",
1323  copyObject(aexpr), copyObject(bexpr),
1324  a->location));
1325  sub2 = (Node *) makeBoolExpr(AND_EXPR, args, a->location);
1326  args = list_make2(sub1, sub2);
1327  result = (Node *) makeBoolExpr(OR_EXPR, args, a->location);
1328  break;
1329  case AEXPR_NOT_BETWEEN_SYM:
1331  aexpr, bexpr,
1332  a->location),
1334  copyObject(aexpr), cexpr,
1335  a->location));
1336  sub1 = (Node *) makeBoolExpr(OR_EXPR, args, a->location);
1338  copyObject(aexpr), copyObject(cexpr),
1339  a->location),
1341  copyObject(aexpr), copyObject(bexpr),
1342  a->location));
1343  sub2 = (Node *) makeBoolExpr(OR_EXPR, args, a->location);
1344  args = list_make2(sub1, sub2);
1345  result = (Node *) makeBoolExpr(AND_EXPR, args, a->location);
1346  break;
1347  default:
1348  elog(ERROR, "unrecognized A_Expr kind: %d", a->kind);
1349  result = NULL; /* keep compiler quiet */
1350  break;
1351  }
1352 
1353  return transformExprRecurse(pstate, result);
1354 }
1355 
1356 static Node *
1358 {
1359  List *args = NIL;
1360  const char *opname;
1361  ListCell *lc;
1362 
1363  switch (a->boolop)
1364  {
1365  case AND_EXPR:
1366  opname = "AND";
1367  break;
1368  case OR_EXPR:
1369  opname = "OR";
1370  break;
1371  case NOT_EXPR:
1372  opname = "NOT";
1373  break;
1374  default:
1375  elog(ERROR, "unrecognized boolop: %d", (int) a->boolop);
1376  opname = NULL; /* keep compiler quiet */
1377  break;
1378  }
1379 
1380  foreach(lc, a->args)
1381  {
1382  Node *arg = (Node *) lfirst(lc);
1383 
1384  arg = transformExprRecurse(pstate, arg);
1385  arg = coerce_to_boolean(pstate, arg, opname);
1386  args = lappend(args, arg);
1387  }
1388 
1389  return (Node *) makeBoolExpr(a->boolop, args, a->location);
1390 }
1391 
1392 static Node *
1394 {
1395  Node *last_srf = pstate->p_last_srf;
1396  List *targs;
1397  ListCell *args;
1398 
1399  /* Transform the list of arguments ... */
1400  targs = NIL;
1401  foreach(args, fn->args)
1402  {
1403  targs = lappend(targs, transformExprRecurse(pstate,
1404  (Node *) lfirst(args)));
1405  }
1406 
1407  /*
1408  * When WITHIN GROUP is used, we treat its ORDER BY expressions as
1409  * additional arguments to the function, for purposes of function lookup
1410  * and argument type coercion. So, transform each such expression and add
1411  * them to the targs list. We don't explicitly mark where each argument
1412  * came from, but ParseFuncOrColumn can tell what's what by reference to
1413  * list_length(fn->agg_order).
1414  */
1415  if (fn->agg_within_group)
1416  {
1417  Assert(fn->agg_order != NIL);
1418  foreach(args, fn->agg_order)
1419  {
1420  SortBy *arg = (SortBy *) lfirst(args);
1421 
1422  targs = lappend(targs, transformExpr(pstate, arg->node,
1424  }
1425  }
1426 
1427  /* ... and hand off to ParseFuncOrColumn */
1428  return ParseFuncOrColumn(pstate,
1429  fn->funcname,
1430  targs,
1431  last_srf,
1432  fn,
1433  false,
1434  fn->location);
1435 }
1436 
1437 static Node *
1439 {
1440  SubLink *sublink;
1441  RowExpr *rexpr;
1442  Query *qtree;
1443  TargetEntry *tle;
1444 
1445  /* We should only see this in first-stage processing of UPDATE tlists */
1447 
1448  /* We only need to transform the source if this is the first column */
1449  if (maref->colno == 1)
1450  {
1451  /*
1452  * For now, we only allow EXPR SubLinks and RowExprs as the source of
1453  * an UPDATE multiassignment. This is sufficient to cover interesting
1454  * cases; at worst, someone would have to write (SELECT * FROM expr)
1455  * to expand a composite-returning expression of another form.
1456  */
1457  if (IsA(maref->source, SubLink) &&
1458  ((SubLink *) maref->source)->subLinkType == EXPR_SUBLINK)
1459  {
1460  /* Relabel it as a MULTIEXPR_SUBLINK */
1461  sublink = (SubLink *) maref->source;
1462  sublink->subLinkType = MULTIEXPR_SUBLINK;
1463  /* And transform it */
1464  sublink = (SubLink *) transformExprRecurse(pstate,
1465  (Node *) sublink);
1466 
1467  qtree = castNode(Query, sublink->subselect);
1468 
1469  /* Check subquery returns required number of columns */
1470  if (count_nonjunk_tlist_entries(qtree->targetList) != maref->ncolumns)
1471  ereport(ERROR,
1472  (errcode(ERRCODE_SYNTAX_ERROR),
1473  errmsg("number of columns does not match number of values"),
1474  parser_errposition(pstate, sublink->location)));
1475 
1476  /*
1477  * Build a resjunk tlist item containing the MULTIEXPR SubLink,
1478  * and add it to pstate->p_multiassign_exprs, whence it will later
1479  * get appended to the completed targetlist. We needn't worry
1480  * about selecting a resno for it; transformUpdateStmt will do
1481  * that.
1482  */
1483  tle = makeTargetEntry((Expr *) sublink, 0, NULL, true);
1485  tle);
1486 
1487  /*
1488  * Assign a unique-within-this-targetlist ID to the MULTIEXPR
1489  * SubLink. We can just use its position in the
1490  * p_multiassign_exprs list.
1491  */
1492  sublink->subLinkId = list_length(pstate->p_multiassign_exprs);
1493  }
1494  else if (IsA(maref->source, RowExpr))
1495  {
1496  /* Transform the RowExpr, allowing SetToDefault items */
1497  rexpr = (RowExpr *) transformRowExpr(pstate,
1498  (RowExpr *) maref->source,
1499  true);
1500 
1501  /* Check it returns required number of columns */
1502  if (list_length(rexpr->args) != maref->ncolumns)
1503  ereport(ERROR,
1504  (errcode(ERRCODE_SYNTAX_ERROR),
1505  errmsg("number of columns does not match number of values"),
1506  parser_errposition(pstate, rexpr->location)));
1507 
1508  /*
1509  * Temporarily append it to p_multiassign_exprs, so we can get it
1510  * back when we come back here for additional columns.
1511  */
1512  tle = makeTargetEntry((Expr *) rexpr, 0, NULL, true);
1514  tle);
1515  }
1516  else
1517  ereport(ERROR,
1518  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1519  errmsg("source for a multiple-column UPDATE item must be a sub-SELECT or ROW() expression"),
1520  parser_errposition(pstate, exprLocation(maref->source))));
1521  }
1522  else
1523  {
1524  /*
1525  * Second or later column in a multiassignment. Re-fetch the
1526  * transformed SubLink or RowExpr, which we assume is still the last
1527  * entry in p_multiassign_exprs.
1528  */
1529  Assert(pstate->p_multiassign_exprs != NIL);
1530  tle = (TargetEntry *) llast(pstate->p_multiassign_exprs);
1531  }
1532 
1533  /*
1534  * Emit the appropriate output expression for the current column
1535  */
1536  if (IsA(tle->expr, SubLink))
1537  {
1538  Param *param;
1539 
1540  sublink = (SubLink *) tle->expr;
1541  Assert(sublink->subLinkType == MULTIEXPR_SUBLINK);
1542  qtree = castNode(Query, sublink->subselect);
1543 
1544  /* Build a Param representing the current subquery output column */
1545  tle = (TargetEntry *) list_nth(qtree->targetList, maref->colno - 1);
1546  Assert(!tle->resjunk);
1547 
1548  param = makeNode(Param);
1549  param->paramkind = PARAM_MULTIEXPR;
1550  param->paramid = (sublink->subLinkId << 16) | maref->colno;
1551  param->paramtype = exprType((Node *) tle->expr);
1552  param->paramtypmod = exprTypmod((Node *) tle->expr);
1553  param->paramcollid = exprCollation((Node *) tle->expr);
1554  param->location = exprLocation((Node *) tle->expr);
1555 
1556  return (Node *) param;
1557  }
1558 
1559  if (IsA(tle->expr, RowExpr))
1560  {
1561  Node *result;
1562 
1563  rexpr = (RowExpr *) tle->expr;
1564 
1565  /* Just extract and return the next element of the RowExpr */
1566  result = (Node *) list_nth(rexpr->args, maref->colno - 1);
1567 
1568  /*
1569  * If we're at the last column, delete the RowExpr from
1570  * p_multiassign_exprs; we don't need it anymore, and don't want it in
1571  * the finished UPDATE tlist. We assume this is still the last entry
1572  * in p_multiassign_exprs.
1573  */
1574  if (maref->colno == maref->ncolumns)
1575  pstate->p_multiassign_exprs =
1577 
1578  return result;
1579  }
1580 
1581  elog(ERROR, "unexpected expr type in multiassign list");
1582  return NULL; /* keep compiler quiet */
1583 }
1584 
1585 static Node *
1587 {
1588  CaseExpr *newc = makeNode(CaseExpr);
1589  Node *last_srf = pstate->p_last_srf;
1590  Node *arg;
1591  CaseTestExpr *placeholder;
1592  List *newargs;
1593  List *resultexprs;
1594  ListCell *l;
1595  Node *defresult;
1596  Oid ptype;
1597 
1598  /* transform the test expression, if any */
1599  arg = transformExprRecurse(pstate, (Node *) c->arg);
1600 
1601  /* generate placeholder for test expression */
1602  if (arg)
1603  {
1604  /*
1605  * If test expression is an untyped literal, force it to text. We have
1606  * to do something now because we won't be able to do this coercion on
1607  * the placeholder. This is not as flexible as what was done in 7.4
1608  * and before, but it's good enough to handle the sort of silly coding
1609  * commonly seen.
1610  */
1611  if (exprType(arg) == UNKNOWNOID)
1612  arg = coerce_to_common_type(pstate, arg, TEXTOID, "CASE");
1613 
1614  /*
1615  * Run collation assignment on the test expression so that we know
1616  * what collation to mark the placeholder with. In principle we could
1617  * leave it to parse_collate.c to do that later, but propagating the
1618  * result to the CaseTestExpr would be unnecessarily complicated.
1619  */
1620  assign_expr_collations(pstate, arg);
1621 
1622  placeholder = makeNode(CaseTestExpr);
1623  placeholder->typeId = exprType(arg);
1624  placeholder->typeMod = exprTypmod(arg);
1625  placeholder->collation = exprCollation(arg);
1626  }
1627  else
1628  placeholder = NULL;
1629 
1630  newc->arg = (Expr *) arg;
1631 
1632  /* transform the list of arguments */
1633  newargs = NIL;
1634  resultexprs = NIL;
1635  foreach(l, c->args)
1636  {
1637  CaseWhen *w = lfirst_node(CaseWhen, l);
1638  CaseWhen *neww = makeNode(CaseWhen);
1639  Node *warg;
1640 
1641  warg = (Node *) w->expr;
1642  if (placeholder)
1643  {
1644  /* shorthand form was specified, so expand... */
1645  warg = (Node *) makeSimpleA_Expr(AEXPR_OP, "=",
1646  (Node *) placeholder,
1647  warg,
1648  w->location);
1649  }
1650  neww->expr = (Expr *) transformExprRecurse(pstate, warg);
1651 
1652  neww->expr = (Expr *) coerce_to_boolean(pstate,
1653  (Node *) neww->expr,
1654  "CASE/WHEN");
1655 
1656  warg = (Node *) w->result;
1657  neww->result = (Expr *) transformExprRecurse(pstate, warg);
1658  neww->location = w->location;
1659 
1660  newargs = lappend(newargs, neww);
1661  resultexprs = lappend(resultexprs, neww->result);
1662  }
1663 
1664  newc->args = newargs;
1665 
1666  /* transform the default clause */
1667  defresult = (Node *) c->defresult;
1668  if (defresult == NULL)
1669  {
1670  A_Const *n = makeNode(A_Const);
1671 
1672  n->isnull = true;
1673  n->location = -1;
1674  defresult = (Node *) n;
1675  }
1676  newc->defresult = (Expr *) transformExprRecurse(pstate, defresult);
1677 
1678  /*
1679  * Note: default result is considered the most significant type in
1680  * determining preferred type. This is how the code worked before, but it
1681  * seems a little bogus to me --- tgl
1682  */
1683  resultexprs = lcons(newc->defresult, resultexprs);
1684 
1685  ptype = select_common_type(pstate, resultexprs, "CASE", NULL);
1686  Assert(OidIsValid(ptype));
1687  newc->casetype = ptype;
1688  /* casecollid will be set by parse_collate.c */
1689 
1690  /* Convert default result clause, if necessary */
1691  newc->defresult = (Expr *)
1692  coerce_to_common_type(pstate,
1693  (Node *) newc->defresult,
1694  ptype,
1695  "CASE/ELSE");
1696 
1697  /* Convert when-clause results, if necessary */
1698  foreach(l, newc->args)
1699  {
1700  CaseWhen *w = (CaseWhen *) lfirst(l);
1701 
1702  w->result = (Expr *)
1703  coerce_to_common_type(pstate,
1704  (Node *) w->result,
1705  ptype,
1706  "CASE/WHEN");
1707  }
1708 
1709  /* if any subexpression contained a SRF, complain */
1710  if (pstate->p_last_srf != last_srf)
1711  ereport(ERROR,
1712  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1713  /* translator: %s is name of a SQL construct, eg GROUP BY */
1714  errmsg("set-returning functions are not allowed in %s",
1715  "CASE"),
1716  errhint("You might be able to move the set-returning function into a LATERAL FROM item."),
1717  parser_errposition(pstate,
1718  exprLocation(pstate->p_last_srf))));
1719 
1720  newc->location = c->location;
1721 
1722  return (Node *) newc;
1723 }
1724 
1725 static Node *
1727 {
1728  Node *result = (Node *) sublink;
1729  Query *qtree;
1730  const char *err;
1731 
1732  /*
1733  * Check to see if the sublink is in an invalid place within the query. We
1734  * allow sublinks everywhere in SELECT/INSERT/UPDATE/DELETE/MERGE, but
1735  * generally not in utility statements.
1736  */
1737  err = NULL;
1738  switch (pstate->p_expr_kind)
1739  {
1740  case EXPR_KIND_NONE:
1741  Assert(false); /* can't happen */
1742  break;
1743  case EXPR_KIND_OTHER:
1744  /* Accept sublink here; caller must throw error if wanted */
1745  break;
1746  case EXPR_KIND_JOIN_ON:
1747  case EXPR_KIND_JOIN_USING:
1750  case EXPR_KIND_WHERE:
1751  case EXPR_KIND_POLICY:
1752  case EXPR_KIND_HAVING:
1753  case EXPR_KIND_FILTER:
1763  case EXPR_KIND_MERGE_WHEN:
1764  case EXPR_KIND_GROUP_BY:
1765  case EXPR_KIND_ORDER_BY:
1766  case EXPR_KIND_DISTINCT_ON:
1767  case EXPR_KIND_LIMIT:
1768  case EXPR_KIND_OFFSET:
1769  case EXPR_KIND_RETURNING:
1770  case EXPR_KIND_VALUES:
1772  case EXPR_KIND_CYCLE_MARK:
1773  /* okay */
1774  break;
1777  err = _("cannot use subquery in check constraint");
1778  break;
1781  err = _("cannot use subquery in DEFAULT expression");
1782  break;
1784  err = _("cannot use subquery in index expression");
1785  break;
1787  err = _("cannot use subquery in index predicate");
1788  break;
1790  err = _("cannot use subquery in statistics expression");
1791  break;
1793  err = _("cannot use subquery in transform expression");
1794  break;
1796  err = _("cannot use subquery in EXECUTE parameter");
1797  break;
1799  err = _("cannot use subquery in trigger WHEN condition");
1800  break;
1802  err = _("cannot use subquery in partition bound");
1803  break;
1805  err = _("cannot use subquery in partition key expression");
1806  break;
1808  err = _("cannot use subquery in CALL argument");
1809  break;
1810  case EXPR_KIND_COPY_WHERE:
1811  err = _("cannot use subquery in COPY FROM WHERE condition");
1812  break;
1814  err = _("cannot use subquery in column generation expression");
1815  break;
1816 
1817  /*
1818  * There is intentionally no default: case here, so that the
1819  * compiler will warn if we add a new ParseExprKind without
1820  * extending this switch. If we do see an unrecognized value at
1821  * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
1822  * which is sane anyway.
1823  */
1824  }
1825  if (err)
1826  ereport(ERROR,
1827  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1828  errmsg_internal("%s", err),
1829  parser_errposition(pstate, sublink->location)));
1830 
1831  pstate->p_hasSubLinks = true;
1832 
1833  /*
1834  * OK, let's transform the sub-SELECT.
1835  */
1836  qtree = parse_sub_analyze(sublink->subselect, pstate, NULL, false, true);
1837 
1838  /*
1839  * Check that we got a SELECT. Anything else should be impossible given
1840  * restrictions of the grammar, but check anyway.
1841  */
1842  if (!IsA(qtree, Query) ||
1843  qtree->commandType != CMD_SELECT)
1844  elog(ERROR, "unexpected non-SELECT command in SubLink");
1845 
1846  sublink->subselect = (Node *) qtree;
1847 
1848  if (sublink->subLinkType == EXISTS_SUBLINK)
1849  {
1850  /*
1851  * EXISTS needs no test expression or combining operator. These fields
1852  * should be null already, but make sure.
1853  */
1854  sublink->testexpr = NULL;
1855  sublink->operName = NIL;
1856  }
1857  else if (sublink->subLinkType == EXPR_SUBLINK ||
1858  sublink->subLinkType == ARRAY_SUBLINK)
1859  {
1860  /*
1861  * Make sure the subselect delivers a single column (ignoring resjunk
1862  * targets).
1863  */
1864  if (count_nonjunk_tlist_entries(qtree->targetList) != 1)
1865  ereport(ERROR,
1866  (errcode(ERRCODE_SYNTAX_ERROR),
1867  errmsg("subquery must return only one column"),
1868  parser_errposition(pstate, sublink->location)));
1869 
1870  /*
1871  * EXPR and ARRAY need no test expression or combining operator. These
1872  * fields should be null already, but make sure.
1873  */
1874  sublink->testexpr = NULL;
1875  sublink->operName = NIL;
1876  }
1877  else if (sublink->subLinkType == MULTIEXPR_SUBLINK)
1878  {
1879  /* Same as EXPR case, except no restriction on number of columns */
1880  sublink->testexpr = NULL;
1881  sublink->operName = NIL;
1882  }
1883  else
1884  {
1885  /* ALL, ANY, or ROWCOMPARE: generate row-comparing expression */
1886  Node *lefthand;
1887  List *left_list;
1888  List *right_list;
1889  ListCell *l;
1890 
1891  /*
1892  * If the source was "x IN (select)", convert to "x = ANY (select)".
1893  */
1894  if (sublink->operName == NIL)
1895  sublink->operName = list_make1(makeString("="));
1896 
1897  /*
1898  * Transform lefthand expression, and convert to a list
1899  */
1900  lefthand = transformExprRecurse(pstate, sublink->testexpr);
1901  if (lefthand && IsA(lefthand, RowExpr))
1902  left_list = ((RowExpr *) lefthand)->args;
1903  else
1904  left_list = list_make1(lefthand);
1905 
1906  /*
1907  * Build a list of PARAM_SUBLINK nodes representing the output columns
1908  * of the subquery.
1909  */
1910  right_list = NIL;
1911  foreach(l, qtree->targetList)
1912  {
1913  TargetEntry *tent = (TargetEntry *) lfirst(l);
1914  Param *param;
1915 
1916  if (tent->resjunk)
1917  continue;
1918 
1919  param = makeNode(Param);
1920  param->paramkind = PARAM_SUBLINK;
1921  param->paramid = tent->resno;
1922  param->paramtype = exprType((Node *) tent->expr);
1923  param->paramtypmod = exprTypmod((Node *) tent->expr);
1924  param->paramcollid = exprCollation((Node *) tent->expr);
1925  param->location = -1;
1926 
1927  right_list = lappend(right_list, param);
1928  }
1929 
1930  /*
1931  * We could rely on make_row_comparison_op to complain if the list
1932  * lengths differ, but we prefer to generate a more specific error
1933  * message.
1934  */
1935  if (list_length(left_list) < list_length(right_list))
1936  ereport(ERROR,
1937  (errcode(ERRCODE_SYNTAX_ERROR),
1938  errmsg("subquery has too many columns"),
1939  parser_errposition(pstate, sublink->location)));
1940  if (list_length(left_list) > list_length(right_list))
1941  ereport(ERROR,
1942  (errcode(ERRCODE_SYNTAX_ERROR),
1943  errmsg("subquery has too few columns"),
1944  parser_errposition(pstate, sublink->location)));
1945 
1946  /*
1947  * Identify the combining operator(s) and generate a suitable
1948  * row-comparison expression.
1949  */
1950  sublink->testexpr = make_row_comparison_op(pstate,
1951  sublink->operName,
1952  left_list,
1953  right_list,
1954  sublink->location);
1955  }
1956 
1957  return result;
1958 }
1959 
1960 /*
1961  * transformArrayExpr
1962  *
1963  * If the caller specifies the target type, the resulting array will
1964  * be of exactly that type. Otherwise we try to infer a common type
1965  * for the elements using select_common_type().
1966  */
1967 static Node *
1969  Oid array_type, Oid element_type, int32 typmod)
1970 {
1971  ArrayExpr *newa = makeNode(ArrayExpr);
1972  List *newelems = NIL;
1973  List *newcoercedelems = NIL;
1974  ListCell *element;
1975  Oid coerce_type;
1976  bool coerce_hard;
1977 
1978  /*
1979  * Transform the element expressions
1980  *
1981  * Assume that the array is one-dimensional unless we find an array-type
1982  * element expression.
1983  */
1984  newa->multidims = false;
1985  foreach(element, a->elements)
1986  {
1987  Node *e = (Node *) lfirst(element);
1988  Node *newe;
1989 
1990  /*
1991  * If an element is itself an A_ArrayExpr, recurse directly so that we
1992  * can pass down any target type we were given.
1993  */
1994  if (IsA(e, A_ArrayExpr))
1995  {
1996  newe = transformArrayExpr(pstate,
1997  (A_ArrayExpr *) e,
1998  array_type,
1999  element_type,
2000  typmod);
2001  /* we certainly have an array here */
2002  Assert(array_type == InvalidOid || array_type == exprType(newe));
2003  newa->multidims = true;
2004  }
2005  else
2006  {
2007  newe = transformExprRecurse(pstate, e);
2008 
2009  /*
2010  * Check for sub-array expressions, if we haven't already found
2011  * one.
2012  */
2013  if (!newa->multidims && type_is_array(exprType(newe)))
2014  newa->multidims = true;
2015  }
2016 
2017  newelems = lappend(newelems, newe);
2018  }
2019 
2020  /*
2021  * Select a target type for the elements.
2022  *
2023  * If we haven't been given a target array type, we must try to deduce a
2024  * common type based on the types of the individual elements present.
2025  */
2026  if (OidIsValid(array_type))
2027  {
2028  /* Caller must ensure array_type matches element_type */
2029  Assert(OidIsValid(element_type));
2030  coerce_type = (newa->multidims ? array_type : element_type);
2031  coerce_hard = true;
2032  }
2033  else
2034  {
2035  /* Can't handle an empty array without a target type */
2036  if (newelems == NIL)
2037  ereport(ERROR,
2038  (errcode(ERRCODE_INDETERMINATE_DATATYPE),
2039  errmsg("cannot determine type of empty array"),
2040  errhint("Explicitly cast to the desired type, "
2041  "for example ARRAY[]::integer[]."),
2042  parser_errposition(pstate, a->location)));
2043 
2044  /* Select a common type for the elements */
2045  coerce_type = select_common_type(pstate, newelems, "ARRAY", NULL);
2046 
2047  if (newa->multidims)
2048  {
2049  array_type = coerce_type;
2050  element_type = get_element_type(array_type);
2051  if (!OidIsValid(element_type))
2052  ereport(ERROR,
2053  (errcode(ERRCODE_UNDEFINED_OBJECT),
2054  errmsg("could not find element type for data type %s",
2055  format_type_be(array_type)),
2056  parser_errposition(pstate, a->location)));
2057  }
2058  else
2059  {
2060  element_type = coerce_type;
2061  array_type = get_array_type(element_type);
2062  if (!OidIsValid(array_type))
2063  ereport(ERROR,
2064  (errcode(ERRCODE_UNDEFINED_OBJECT),
2065  errmsg("could not find array type for data type %s",
2066  format_type_be(element_type)),
2067  parser_errposition(pstate, a->location)));
2068  }
2069  coerce_hard = false;
2070  }
2071 
2072  /*
2073  * Coerce elements to target type
2074  *
2075  * If the array has been explicitly cast, then the elements are in turn
2076  * explicitly coerced.
2077  *
2078  * If the array's type was merely derived from the common type of its
2079  * elements, then the elements are implicitly coerced to the common type.
2080  * This is consistent with other uses of select_common_type().
2081  */
2082  foreach(element, newelems)
2083  {
2084  Node *e = (Node *) lfirst(element);
2085  Node *newe;
2086 
2087  if (coerce_hard)
2088  {
2089  newe = coerce_to_target_type(pstate, e,
2090  exprType(e),
2091  coerce_type,
2092  typmod,
2095  -1);
2096  if (newe == NULL)
2097  ereport(ERROR,
2098  (errcode(ERRCODE_CANNOT_COERCE),
2099  errmsg("cannot cast type %s to %s",
2102  parser_errposition(pstate, exprLocation(e))));
2103  }
2104  else
2105  newe = coerce_to_common_type(pstate, e,
2106  coerce_type,
2107  "ARRAY");
2108  newcoercedelems = lappend(newcoercedelems, newe);
2109  }
2110 
2111  newa->array_typeid = array_type;
2112  /* array_collid will be set by parse_collate.c */
2113  newa->element_typeid = element_type;
2114  newa->elements = newcoercedelems;
2115  newa->location = a->location;
2116 
2117  return (Node *) newa;
2118 }
2119 
2120 static Node *
2121 transformRowExpr(ParseState *pstate, RowExpr *r, bool allowDefault)
2122 {
2123  RowExpr *newr;
2124  char fname[16];
2125  int fnum;
2126 
2127  newr = makeNode(RowExpr);
2128 
2129  /* Transform the field expressions */
2130  newr->args = transformExpressionList(pstate, r->args,
2131  pstate->p_expr_kind, allowDefault);
2132 
2133  /* Disallow more columns than will fit in a tuple */
2135  ereport(ERROR,
2136  (errcode(ERRCODE_TOO_MANY_COLUMNS),
2137  errmsg("ROW expressions can have at most %d entries",
2139  parser_errposition(pstate, r->location)));
2140 
2141  /* Barring later casting, we consider the type RECORD */
2142  newr->row_typeid = RECORDOID;
2143  newr->row_format = COERCE_IMPLICIT_CAST;
2144 
2145  /* ROW() has anonymous columns, so invent some field names */
2146  newr->colnames = NIL;
2147  for (fnum = 1; fnum <= list_length(newr->args); fnum++)
2148  {
2149  snprintf(fname, sizeof(fname), "f%d", fnum);
2150  newr->colnames = lappend(newr->colnames, makeString(pstrdup(fname)));
2151  }
2152 
2153  newr->location = r->location;
2154 
2155  return (Node *) newr;
2156 }
2157 
2158 static Node *
2160 {
2162  Node *last_srf = pstate->p_last_srf;
2163  List *newargs = NIL;
2164  List *newcoercedargs = NIL;
2165  ListCell *args;
2166 
2167  foreach(args, c->args)
2168  {
2169  Node *e = (Node *) lfirst(args);
2170  Node *newe;
2171 
2172  newe = transformExprRecurse(pstate, e);
2173  newargs = lappend(newargs, newe);
2174  }
2175 
2176  newc->coalescetype = select_common_type(pstate, newargs, "COALESCE", NULL);
2177  /* coalescecollid will be set by parse_collate.c */
2178 
2179  /* Convert arguments if necessary */
2180  foreach(args, newargs)
2181  {
2182  Node *e = (Node *) lfirst(args);
2183  Node *newe;
2184 
2185  newe = coerce_to_common_type(pstate, e,
2186  newc->coalescetype,
2187  "COALESCE");
2188  newcoercedargs = lappend(newcoercedargs, newe);
2189  }
2190 
2191  /* if any subexpression contained a SRF, complain */
2192  if (pstate->p_last_srf != last_srf)
2193  ereport(ERROR,
2194  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2195  /* translator: %s is name of a SQL construct, eg GROUP BY */
2196  errmsg("set-returning functions are not allowed in %s",
2197  "COALESCE"),
2198  errhint("You might be able to move the set-returning function into a LATERAL FROM item."),
2199  parser_errposition(pstate,
2200  exprLocation(pstate->p_last_srf))));
2201 
2202  newc->args = newcoercedargs;
2203  newc->location = c->location;
2204  return (Node *) newc;
2205 }
2206 
2207 static Node *
2209 {
2210  MinMaxExpr *newm = makeNode(MinMaxExpr);
2211  List *newargs = NIL;
2212  List *newcoercedargs = NIL;
2213  const char *funcname = (m->op == IS_GREATEST) ? "GREATEST" : "LEAST";
2214  ListCell *args;
2215 
2216  newm->op = m->op;
2217  foreach(args, m->args)
2218  {
2219  Node *e = (Node *) lfirst(args);
2220  Node *newe;
2221 
2222  newe = transformExprRecurse(pstate, e);
2223  newargs = lappend(newargs, newe);
2224  }
2225 
2226  newm->minmaxtype = select_common_type(pstate, newargs, funcname, NULL);
2227  /* minmaxcollid and inputcollid will be set by parse_collate.c */
2228 
2229  /* Convert arguments if necessary */
2230  foreach(args, newargs)
2231  {
2232  Node *e = (Node *) lfirst(args);
2233  Node *newe;
2234 
2235  newe = coerce_to_common_type(pstate, e,
2236  newm->minmaxtype,
2237  funcname);
2238  newcoercedargs = lappend(newcoercedargs, newe);
2239  }
2240 
2241  newm->args = newcoercedargs;
2242  newm->location = m->location;
2243  return (Node *) newm;
2244 }
2245 
2246 static Node *
2248 {
2249  /*
2250  * All we need to do is insert the correct result type and (where needed)
2251  * validate the typmod, so we just modify the node in-place.
2252  */
2253  switch (svf->op)
2254  {
2255  case SVFOP_CURRENT_DATE:
2256  svf->type = DATEOID;
2257  break;
2258  case SVFOP_CURRENT_TIME:
2259  svf->type = TIMETZOID;
2260  break;
2261  case SVFOP_CURRENT_TIME_N:
2262  svf->type = TIMETZOID;
2263  svf->typmod = anytime_typmod_check(true, svf->typmod);
2264  break;
2266  svf->type = TIMESTAMPTZOID;
2267  break;
2269  svf->type = TIMESTAMPTZOID;
2270  svf->typmod = anytimestamp_typmod_check(true, svf->typmod);
2271  break;
2272  case SVFOP_LOCALTIME:
2273  svf->type = TIMEOID;
2274  break;
2275  case SVFOP_LOCALTIME_N:
2276  svf->type = TIMEOID;
2277  svf->typmod = anytime_typmod_check(false, svf->typmod);
2278  break;
2279  case SVFOP_LOCALTIMESTAMP:
2280  svf->type = TIMESTAMPOID;
2281  break;
2283  svf->type = TIMESTAMPOID;
2284  svf->typmod = anytimestamp_typmod_check(false, svf->typmod);
2285  break;
2286  case SVFOP_CURRENT_ROLE:
2287  case SVFOP_CURRENT_USER:
2288  case SVFOP_USER:
2289  case SVFOP_SESSION_USER:
2290  case SVFOP_CURRENT_CATALOG:
2291  case SVFOP_CURRENT_SCHEMA:
2292  svf->type = NAMEOID;
2293  break;
2294  }
2295 
2296  return (Node *) svf;
2297 }
2298 
2299 static Node *
2301 {
2302  XmlExpr *newx;
2303  ListCell *lc;
2304  int i;
2305 
2306  newx = makeNode(XmlExpr);
2307  newx->op = x->op;
2308  if (x->name)
2309  newx->name = map_sql_identifier_to_xml_name(x->name, false, false);
2310  else
2311  newx->name = NULL;
2312  newx->xmloption = x->xmloption;
2313  newx->type = XMLOID; /* this just marks the node as transformed */
2314  newx->typmod = -1;
2315  newx->location = x->location;
2316 
2317  /*
2318  * gram.y built the named args as a list of ResTarget. Transform each,
2319  * and break the names out as a separate list.
2320  */
2321  newx->named_args = NIL;
2322  newx->arg_names = NIL;
2323 
2324  foreach(lc, x->named_args)
2325  {
2326  ResTarget *r = lfirst_node(ResTarget, lc);
2327  Node *expr;
2328  char *argname;
2329 
2330  expr = transformExprRecurse(pstate, r->val);
2331 
2332  if (r->name)
2333  argname = map_sql_identifier_to_xml_name(r->name, false, false);
2334  else if (IsA(r->val, ColumnRef))
2336  true, false);
2337  else
2338  {
2339  ereport(ERROR,
2340  (errcode(ERRCODE_SYNTAX_ERROR),
2341  x->op == IS_XMLELEMENT
2342  ? errmsg("unnamed XML attribute value must be a column reference")
2343  : errmsg("unnamed XML element value must be a column reference"),
2344  parser_errposition(pstate, r->location)));
2345  argname = NULL; /* keep compiler quiet */
2346  }
2347 
2348  /* reject duplicate argnames in XMLELEMENT only */
2349  if (x->op == IS_XMLELEMENT)
2350  {
2351  ListCell *lc2;
2352 
2353  foreach(lc2, newx->arg_names)
2354  {
2355  if (strcmp(argname, strVal(lfirst(lc2))) == 0)
2356  ereport(ERROR,
2357  (errcode(ERRCODE_SYNTAX_ERROR),
2358  errmsg("XML attribute name \"%s\" appears more than once",
2359  argname),
2360  parser_errposition(pstate, r->location)));
2361  }
2362  }
2363 
2364  newx->named_args = lappend(newx->named_args, expr);
2365  newx->arg_names = lappend(newx->arg_names, makeString(argname));
2366  }
2367 
2368  /* The other arguments are of varying types depending on the function */
2369  newx->args = NIL;
2370  i = 0;
2371  foreach(lc, x->args)
2372  {
2373  Node *e = (Node *) lfirst(lc);
2374  Node *newe;
2375 
2376  newe = transformExprRecurse(pstate, e);
2377  switch (x->op)
2378  {
2379  case IS_XMLCONCAT:
2380  newe = coerce_to_specific_type(pstate, newe, XMLOID,
2381  "XMLCONCAT");
2382  break;
2383  case IS_XMLELEMENT:
2384  /* no coercion necessary */
2385  break;
2386  case IS_XMLFOREST:
2387  newe = coerce_to_specific_type(pstate, newe, XMLOID,
2388  "XMLFOREST");
2389  break;
2390  case IS_XMLPARSE:
2391  if (i == 0)
2392  newe = coerce_to_specific_type(pstate, newe, TEXTOID,
2393  "XMLPARSE");
2394  else
2395  newe = coerce_to_boolean(pstate, newe, "XMLPARSE");
2396  break;
2397  case IS_XMLPI:
2398  newe = coerce_to_specific_type(pstate, newe, TEXTOID,
2399  "XMLPI");
2400  break;
2401  case IS_XMLROOT:
2402  if (i == 0)
2403  newe = coerce_to_specific_type(pstate, newe, XMLOID,
2404  "XMLROOT");
2405  else if (i == 1)
2406  newe = coerce_to_specific_type(pstate, newe, TEXTOID,
2407  "XMLROOT");
2408  else
2409  newe = coerce_to_specific_type(pstate, newe, INT4OID,
2410  "XMLROOT");
2411  break;
2412  case IS_XMLSERIALIZE:
2413  /* not handled here */
2414  Assert(false);
2415  break;
2416  case IS_DOCUMENT:
2417  newe = coerce_to_specific_type(pstate, newe, XMLOID,
2418  "IS DOCUMENT");
2419  break;
2420  }
2421  newx->args = lappend(newx->args, newe);
2422  i++;
2423  }
2424 
2425  return (Node *) newx;
2426 }
2427 
2428 static Node *
2430 {
2431  Node *result;
2432  XmlExpr *xexpr;
2433  Oid targetType;
2434  int32 targetTypmod;
2435 
2436  xexpr = makeNode(XmlExpr);
2437  xexpr->op = IS_XMLSERIALIZE;
2438  xexpr->args = list_make1(coerce_to_specific_type(pstate,
2439  transformExprRecurse(pstate, xs->expr),
2440  XMLOID,
2441  "XMLSERIALIZE"));
2442 
2443  typenameTypeIdAndMod(pstate, xs->typeName, &targetType, &targetTypmod);
2444 
2445  xexpr->xmloption = xs->xmloption;
2446  xexpr->indent = xs->indent;
2447  xexpr->location = xs->location;
2448  /* We actually only need these to be able to parse back the expression. */
2449  xexpr->type = targetType;
2450  xexpr->typmod = targetTypmod;
2451 
2452  /*
2453  * The actual target type is determined this way. SQL allows char and
2454  * varchar as target types. We allow anything that can be cast implicitly
2455  * from text. This way, user-defined text-like data types automatically
2456  * fit in.
2457  */
2458  result = coerce_to_target_type(pstate, (Node *) xexpr,
2459  TEXTOID, targetType, targetTypmod,
2462  -1);
2463  if (result == NULL)
2464  ereport(ERROR,
2465  (errcode(ERRCODE_CANNOT_COERCE),
2466  errmsg("cannot cast XMLSERIALIZE result to %s",
2467  format_type_be(targetType)),
2468  parser_errposition(pstate, xexpr->location)));
2469  return result;
2470 }
2471 
2472 static Node *
2474 {
2475  const char *clausename;
2476 
2477  switch (b->booltesttype)
2478  {
2479  case IS_TRUE:
2480  clausename = "IS TRUE";
2481  break;
2482  case IS_NOT_TRUE:
2483  clausename = "IS NOT TRUE";
2484  break;
2485  case IS_FALSE:
2486  clausename = "IS FALSE";
2487  break;
2488  case IS_NOT_FALSE:
2489  clausename = "IS NOT FALSE";
2490  break;
2491  case IS_UNKNOWN:
2492  clausename = "IS UNKNOWN";
2493  break;
2494  case IS_NOT_UNKNOWN:
2495  clausename = "IS NOT UNKNOWN";
2496  break;
2497  default:
2498  elog(ERROR, "unrecognized booltesttype: %d",
2499  (int) b->booltesttype);
2500  clausename = NULL; /* keep compiler quiet */
2501  }
2502 
2503  b->arg = (Expr *) transformExprRecurse(pstate, (Node *) b->arg);
2504 
2505  b->arg = (Expr *) coerce_to_boolean(pstate,
2506  (Node *) b->arg,
2507  clausename);
2508 
2509  return (Node *) b;
2510 }
2511 
2512 static Node *
2514 {
2515  /* CURRENT OF can only appear at top level of UPDATE/DELETE */
2516  Assert(pstate->p_target_nsitem != NULL);
2517  cexpr->cvarno = pstate->p_target_nsitem->p_rtindex;
2518 
2519  /*
2520  * Check to see if the cursor name matches a parameter of type REFCURSOR.
2521  * If so, replace the raw name reference with a parameter reference. (This
2522  * is a hack for the convenience of plpgsql.)
2523  */
2524  if (cexpr->cursor_name != NULL) /* in case already transformed */
2525  {
2526  ColumnRef *cref = makeNode(ColumnRef);
2527  Node *node = NULL;
2528 
2529  /* Build an unqualified ColumnRef with the given name */
2530  cref->fields = list_make1(makeString(cexpr->cursor_name));
2531  cref->location = -1;
2532 
2533  /* See if there is a translation available from a parser hook */
2534  if (pstate->p_pre_columnref_hook != NULL)
2535  node = pstate->p_pre_columnref_hook(pstate, cref);
2536  if (node == NULL && pstate->p_post_columnref_hook != NULL)
2537  node = pstate->p_post_columnref_hook(pstate, cref, NULL);
2538 
2539  /*
2540  * XXX Should we throw an error if we get a translation that isn't a
2541  * refcursor Param? For now it seems best to silently ignore false
2542  * matches.
2543  */
2544  if (node != NULL && IsA(node, Param))
2545  {
2546  Param *p = (Param *) node;
2547 
2548  if (p->paramkind == PARAM_EXTERN &&
2549  p->paramtype == REFCURSOROID)
2550  {
2551  /* Matches, so convert CURRENT OF to a param reference */
2552  cexpr->cursor_name = NULL;
2553  cexpr->cursor_param = p->paramid;
2554  }
2555  }
2556  }
2557 
2558  return (Node *) cexpr;
2559 }
2560 
2561 /*
2562  * Construct a whole-row reference to represent the notation "relation.*".
2563  */
2564 static Node *
2566  int sublevels_up, int location)
2567 {
2568  /*
2569  * Build the appropriate referencing node. Normally this can be a
2570  * whole-row Var, but if the nsitem is a JOIN USING alias then it contains
2571  * only a subset of the columns of the underlying join RTE, so that will
2572  * not work. Instead we immediately expand the reference into a RowExpr.
2573  * Since the JOIN USING's common columns are fully determined at this
2574  * point, there seems no harm in expanding it now rather than during
2575  * planning.
2576  *
2577  * Note that if the RTE is a function returning scalar, we create just a
2578  * plain reference to the function value, not a composite containing a
2579  * single column. This is pretty inconsistent at first sight, but it's
2580  * what we've done historically. One argument for it is that "rel" and
2581  * "rel.*" mean the same thing for composite relations, so why not for
2582  * scalar functions...
2583  */
2584  if (nsitem->p_names == nsitem->p_rte->eref)
2585  {
2586  Var *result;
2587 
2588  result = makeWholeRowVar(nsitem->p_rte, nsitem->p_rtindex,
2589  sublevels_up, true);
2590 
2591  /* location is not filled in by makeWholeRowVar */
2592  result->location = location;
2593 
2594  /* mark Var if it's nulled by any outer joins */
2595  markNullableIfNeeded(pstate, result);
2596 
2597  /* mark relation as requiring whole-row SELECT access */
2598  markVarForSelectPriv(pstate, result);
2599 
2600  return (Node *) result;
2601  }
2602  else
2603  {
2604  RowExpr *rowexpr;
2605  List *fields;
2606 
2607  /*
2608  * We want only as many columns as are listed in p_names->colnames,
2609  * and we should use those names not whatever possibly-aliased names
2610  * are in the RTE. We needn't worry about marking the RTE for SELECT
2611  * access, as the common columns are surely so marked already.
2612  */
2613  expandRTE(nsitem->p_rte, nsitem->p_rtindex,
2614  sublevels_up, location, false,
2615  NULL, &fields);
2616  rowexpr = makeNode(RowExpr);
2617  rowexpr->args = list_truncate(fields,
2618  list_length(nsitem->p_names->colnames));
2619  rowexpr->row_typeid = RECORDOID;
2620  rowexpr->row_format = COERCE_IMPLICIT_CAST;
2621  rowexpr->colnames = copyObject(nsitem->p_names->colnames);
2622  rowexpr->location = location;
2623 
2624  /* XXX we ought to mark the row as possibly nullable */
2625 
2626  return (Node *) rowexpr;
2627  }
2628 }
2629 
2630 /*
2631  * Handle an explicit CAST construct.
2632  *
2633  * Transform the argument, look up the type name, and apply any necessary
2634  * coercion function(s).
2635  */
2636 static Node *
2638 {
2639  Node *result;
2640  Node *arg = tc->arg;
2641  Node *expr;
2642  Oid inputType;
2643  Oid targetType;
2644  int32 targetTypmod;
2645  int location;
2646 
2647  /* Look up the type name first */
2648  typenameTypeIdAndMod(pstate, tc->typeName, &targetType, &targetTypmod);
2649 
2650  /*
2651  * If the subject of the typecast is an ARRAY[] construct and the target
2652  * type is an array type, we invoke transformArrayExpr() directly so that
2653  * we can pass down the type information. This avoids some cases where
2654  * transformArrayExpr() might not infer the correct type. Otherwise, just
2655  * transform the argument normally.
2656  */
2657  if (IsA(arg, A_ArrayExpr))
2658  {
2659  Oid targetBaseType;
2660  int32 targetBaseTypmod;
2661  Oid elementType;
2662 
2663  /*
2664  * If target is a domain over array, work with the base array type
2665  * here. Below, we'll cast the array type to the domain. In the
2666  * usual case that the target is not a domain, the remaining steps
2667  * will be a no-op.
2668  */
2669  targetBaseTypmod = targetTypmod;
2670  targetBaseType = getBaseTypeAndTypmod(targetType, &targetBaseTypmod);
2671  elementType = get_element_type(targetBaseType);
2672  if (OidIsValid(elementType))
2673  {
2674  expr = transformArrayExpr(pstate,
2675  (A_ArrayExpr *) arg,
2676  targetBaseType,
2677  elementType,
2678  targetBaseTypmod);
2679  }
2680  else
2681  expr = transformExprRecurse(pstate, arg);
2682  }
2683  else
2684  expr = transformExprRecurse(pstate, arg);
2685 
2686  inputType = exprType(expr);
2687  if (inputType == InvalidOid)
2688  return expr; /* do nothing if NULL input */
2689 
2690  /*
2691  * Location of the coercion is preferentially the location of the :: or
2692  * CAST symbol, but if there is none then use the location of the type
2693  * name (this can happen in TypeName 'string' syntax, for instance).
2694  */
2695  location = tc->location;
2696  if (location < 0)
2697  location = tc->typeName->location;
2698 
2699  result = coerce_to_target_type(pstate, expr, inputType,
2700  targetType, targetTypmod,
2703  location);
2704  if (result == NULL)
2705  ereport(ERROR,
2706  (errcode(ERRCODE_CANNOT_COERCE),
2707  errmsg("cannot cast type %s to %s",
2708  format_type_be(inputType),
2709  format_type_be(targetType)),
2710  parser_coercion_errposition(pstate, location, expr)));
2711 
2712  return result;
2713 }
2714 
2715 /*
2716  * Handle an explicit COLLATE clause.
2717  *
2718  * Transform the argument, and look up the collation name.
2719  */
2720 static Node *
2722 {
2723  CollateExpr *newc;
2724  Oid argtype;
2725 
2726  newc = makeNode(CollateExpr);
2727  newc->arg = (Expr *) transformExprRecurse(pstate, c->arg);
2728 
2729  argtype = exprType((Node *) newc->arg);
2730 
2731  /*
2732  * The unknown type is not collatable, but coerce_type() takes care of it
2733  * separately, so we'll let it go here.
2734  */
2735  if (!type_is_collatable(argtype) && argtype != UNKNOWNOID)
2736  ereport(ERROR,
2737  (errcode(ERRCODE_DATATYPE_MISMATCH),
2738  errmsg("collations are not supported by type %s",
2739  format_type_be(argtype)),
2740  parser_errposition(pstate, c->location)));
2741 
2742  newc->collOid = LookupCollation(pstate, c->collname, c->location);
2743  newc->location = c->location;
2744 
2745  return (Node *) newc;
2746 }
2747 
2748 /*
2749  * Transform a "row compare-op row" construct
2750  *
2751  * The inputs are lists of already-transformed expressions.
2752  * As with coerce_type, pstate may be NULL if no special unknown-Param
2753  * processing is wanted.
2754  *
2755  * The output may be a single OpExpr, an AND or OR combination of OpExprs,
2756  * or a RowCompareExpr. In all cases it is guaranteed to return boolean.
2757  * The AND, OR, and RowCompareExpr cases further imply things about the
2758  * behavior of the operators (ie, they behave as =, <>, or < <= > >=).
2759  */
2760 static Node *
2762  List *largs, List *rargs, int location)
2763 {
2764  RowCompareExpr *rcexpr;
2765  RowCompareType rctype;
2766  List *opexprs;
2767  List *opnos;
2768  List *opfamilies;
2769  ListCell *l,
2770  *r;
2771  List **opinfo_lists;
2772  Bitmapset *strats;
2773  int nopers;
2774  int i;
2775 
2776  nopers = list_length(largs);
2777  if (nopers != list_length(rargs))
2778  ereport(ERROR,
2779  (errcode(ERRCODE_SYNTAX_ERROR),
2780  errmsg("unequal number of entries in row expressions"),
2781  parser_errposition(pstate, location)));
2782 
2783  /*
2784  * We can't compare zero-length rows because there is no principled basis
2785  * for figuring out what the operator is.
2786  */
2787  if (nopers == 0)
2788  ereport(ERROR,
2789  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2790  errmsg("cannot compare rows of zero length"),
2791  parser_errposition(pstate, location)));
2792 
2793  /*
2794  * Identify all the pairwise operators, using make_op so that behavior is
2795  * the same as in the simple scalar case.
2796  */
2797  opexprs = NIL;
2798  forboth(l, largs, r, rargs)
2799  {
2800  Node *larg = (Node *) lfirst(l);
2801  Node *rarg = (Node *) lfirst(r);
2802  OpExpr *cmp;
2803 
2804  cmp = castNode(OpExpr, make_op(pstate, opname, larg, rarg,
2805  pstate->p_last_srf, location));
2806 
2807  /*
2808  * We don't use coerce_to_boolean here because we insist on the
2809  * operator yielding boolean directly, not via coercion. If it
2810  * doesn't yield bool it won't be in any index opfamilies...
2811  */
2812  if (cmp->opresulttype != BOOLOID)
2813  ereport(ERROR,
2814  (errcode(ERRCODE_DATATYPE_MISMATCH),
2815  errmsg("row comparison operator must yield type boolean, "
2816  "not type %s",
2817  format_type_be(cmp->opresulttype)),
2818  parser_errposition(pstate, location)));
2819  if (expression_returns_set((Node *) cmp))
2820  ereport(ERROR,
2821  (errcode(ERRCODE_DATATYPE_MISMATCH),
2822  errmsg("row comparison operator must not return a set"),
2823  parser_errposition(pstate, location)));
2824  opexprs = lappend(opexprs, cmp);
2825  }
2826 
2827  /*
2828  * If rows are length 1, just return the single operator. In this case we
2829  * don't insist on identifying btree semantics for the operator (but we
2830  * still require it to return boolean).
2831  */
2832  if (nopers == 1)
2833  return (Node *) linitial(opexprs);
2834 
2835  /*
2836  * Now we must determine which row comparison semantics (= <> < <= > >=)
2837  * apply to this set of operators. We look for btree opfamilies
2838  * containing the operators, and see which interpretations (strategy
2839  * numbers) exist for each operator.
2840  */
2841  opinfo_lists = (List **) palloc(nopers * sizeof(List *));
2842  strats = NULL;
2843  i = 0;
2844  foreach(l, opexprs)
2845  {
2846  Oid opno = ((OpExpr *) lfirst(l))->opno;
2847  Bitmapset *this_strats;
2848  ListCell *j;
2849 
2850  opinfo_lists[i] = get_op_btree_interpretation(opno);
2851 
2852  /*
2853  * convert strategy numbers into a Bitmapset to make the intersection
2854  * calculation easy.
2855  */
2856  this_strats = NULL;
2857  foreach(j, opinfo_lists[i])
2858  {
2859  OpBtreeInterpretation *opinfo = lfirst(j);
2860 
2861  this_strats = bms_add_member(this_strats, opinfo->strategy);
2862  }
2863  if (i == 0)
2864  strats = this_strats;
2865  else
2866  strats = bms_int_members(strats, this_strats);
2867  i++;
2868  }
2869 
2870  /*
2871  * If there are multiple common interpretations, we may use any one of
2872  * them ... this coding arbitrarily picks the lowest btree strategy
2873  * number.
2874  */
2875  i = bms_next_member(strats, -1);
2876  if (i < 0)
2877  {
2878  /* No common interpretation, so fail */
2879  ereport(ERROR,
2880  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2881  errmsg("could not determine interpretation of row comparison operator %s",
2882  strVal(llast(opname))),
2883  errhint("Row comparison operators must be associated with btree operator families."),
2884  parser_errposition(pstate, location)));
2885  }
2886  rctype = (RowCompareType) i;
2887 
2888  /*
2889  * For = and <> cases, we just combine the pairwise operators with AND or
2890  * OR respectively.
2891  */
2892  if (rctype == ROWCOMPARE_EQ)
2893  return (Node *) makeBoolExpr(AND_EXPR, opexprs, location);
2894  if (rctype == ROWCOMPARE_NE)
2895  return (Node *) makeBoolExpr(OR_EXPR, opexprs, location);
2896 
2897  /*
2898  * Otherwise we need to choose exactly which opfamily to associate with
2899  * each operator.
2900  */
2901  opfamilies = NIL;
2902  for (i = 0; i < nopers; i++)
2903  {
2904  Oid opfamily = InvalidOid;
2905  ListCell *j;
2906 
2907  foreach(j, opinfo_lists[i])
2908  {
2909  OpBtreeInterpretation *opinfo = lfirst(j);
2910 
2911  if (opinfo->strategy == rctype)
2912  {
2913  opfamily = opinfo->opfamily_id;
2914  break;
2915  }
2916  }
2917  if (OidIsValid(opfamily))
2918  opfamilies = lappend_oid(opfamilies, opfamily);
2919  else /* should not happen */
2920  ereport(ERROR,
2921  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2922  errmsg("could not determine interpretation of row comparison operator %s",
2923  strVal(llast(opname))),
2924  errdetail("There are multiple equally-plausible candidates."),
2925  parser_errposition(pstate, location)));
2926  }
2927 
2928  /*
2929  * Now deconstruct the OpExprs and create a RowCompareExpr.
2930  *
2931  * Note: can't just reuse the passed largs/rargs lists, because of
2932  * possibility that make_op inserted coercion operations.
2933  */
2934  opnos = NIL;
2935  largs = NIL;
2936  rargs = NIL;
2937  foreach(l, opexprs)
2938  {
2939  OpExpr *cmp = (OpExpr *) lfirst(l);
2940 
2941  opnos = lappend_oid(opnos, cmp->opno);
2942  largs = lappend(largs, linitial(cmp->args));
2943  rargs = lappend(rargs, lsecond(cmp->args));
2944  }
2945 
2946  rcexpr = makeNode(RowCompareExpr);
2947  rcexpr->rctype = rctype;
2948  rcexpr->opnos = opnos;
2949  rcexpr->opfamilies = opfamilies;
2950  rcexpr->inputcollids = NIL; /* assign_expr_collations will fix this */
2951  rcexpr->largs = largs;
2952  rcexpr->rargs = rargs;
2953 
2954  return (Node *) rcexpr;
2955 }
2956 
2957 /*
2958  * Transform a "row IS DISTINCT FROM row" construct
2959  *
2960  * The input RowExprs are already transformed
2961  */
2962 static Node *
2964  RowExpr *lrow, RowExpr *rrow,
2965  int location)
2966 {
2967  Node *result = NULL;
2968  List *largs = lrow->args;
2969  List *rargs = rrow->args;
2970  ListCell *l,
2971  *r;
2972 
2973  if (list_length(largs) != list_length(rargs))
2974  ereport(ERROR,
2975  (errcode(ERRCODE_SYNTAX_ERROR),
2976  errmsg("unequal number of entries in row expressions"),
2977  parser_errposition(pstate, location)));
2978 
2979  forboth(l, largs, r, rargs)
2980  {
2981  Node *larg = (Node *) lfirst(l);
2982  Node *rarg = (Node *) lfirst(r);
2983  Node *cmp;
2984 
2985  cmp = (Node *) make_distinct_op(pstate, opname, larg, rarg, location);
2986  if (result == NULL)
2987  result = cmp;
2988  else
2989  result = (Node *) makeBoolExpr(OR_EXPR,
2990  list_make2(result, cmp),
2991  location);
2992  }
2993 
2994  if (result == NULL)
2995  {
2996  /* zero-length rows? Generate constant FALSE */
2997  result = makeBoolConst(false, false);
2998  }
2999 
3000  return result;
3001 }
3002 
3003 /*
3004  * make the node for an IS DISTINCT FROM operator
3005  */
3006 static Expr *
3007 make_distinct_op(ParseState *pstate, List *opname, Node *ltree, Node *rtree,
3008  int location)
3009 {
3010  Expr *result;
3011 
3012  result = make_op(pstate, opname, ltree, rtree,
3013  pstate->p_last_srf, location);
3014  if (((OpExpr *) result)->opresulttype != BOOLOID)
3015  ereport(ERROR,
3016  (errcode(ERRCODE_DATATYPE_MISMATCH),
3017  errmsg("IS DISTINCT FROM requires = operator to yield boolean"),
3018  parser_errposition(pstate, location)));
3019  if (((OpExpr *) result)->opretset)
3020  ereport(ERROR,
3021  (errcode(ERRCODE_DATATYPE_MISMATCH),
3022  /* translator: %s is name of a SQL construct, eg NULLIF */
3023  errmsg("%s must not return a set", "IS DISTINCT FROM"),
3024  parser_errposition(pstate, location)));
3025 
3026  /*
3027  * We rely on DistinctExpr and OpExpr being same struct
3028  */
3029  NodeSetTag(result, T_DistinctExpr);
3030 
3031  return result;
3032 }
3033 
3034 /*
3035  * Produce a NullTest node from an IS [NOT] DISTINCT FROM NULL construct
3036  *
3037  * "arg" is the untransformed other argument
3038  */
3039 static Node *
3041 {
3042  NullTest *nt = makeNode(NullTest);
3043 
3044  nt->arg = (Expr *) transformExprRecurse(pstate, arg);
3045  /* the argument can be any type, so don't coerce it */
3046  if (distincta->kind == AEXPR_NOT_DISTINCT)
3047  nt->nulltesttype = IS_NULL;
3048  else
3049  nt->nulltesttype = IS_NOT_NULL;
3050  /* argisrow = false is correct whether or not arg is composite */
3051  nt->argisrow = false;
3052  nt->location = distincta->location;
3053  return (Node *) nt;
3054 }
3055 
3056 /*
3057  * Produce a string identifying an expression by kind.
3058  *
3059  * Note: when practical, use a simple SQL keyword for the result. If that
3060  * doesn't work well, check call sites to see whether custom error message
3061  * strings are required.
3062  */
3063 const char *
3065 {
3066  switch (exprKind)
3067  {
3068  case EXPR_KIND_NONE:
3069  return "invalid expression context";
3070  case EXPR_KIND_OTHER:
3071  return "extension expression";
3072  case EXPR_KIND_JOIN_ON:
3073  return "JOIN/ON";
3074  case EXPR_KIND_JOIN_USING:
3075  return "JOIN/USING";
3077  return "sub-SELECT in FROM";
3079  return "function in FROM";
3080  case EXPR_KIND_WHERE:
3081  return "WHERE";
3082  case EXPR_KIND_POLICY:
3083  return "POLICY";
3084  case EXPR_KIND_HAVING:
3085  return "HAVING";
3086  case EXPR_KIND_FILTER:
3087  return "FILTER";
3089  return "window PARTITION BY";
3091  return "window ORDER BY";
3093  return "window RANGE";
3095  return "window ROWS";
3097  return "window GROUPS";
3099  return "SELECT";
3101  return "INSERT";
3104  return "UPDATE";
3105  case EXPR_KIND_MERGE_WHEN:
3106  return "MERGE WHEN";
3107  case EXPR_KIND_GROUP_BY:
3108  return "GROUP BY";
3109  case EXPR_KIND_ORDER_BY:
3110  return "ORDER BY";
3111  case EXPR_KIND_DISTINCT_ON:
3112  return "DISTINCT ON";
3113  case EXPR_KIND_LIMIT:
3114  return "LIMIT";
3115  case EXPR_KIND_OFFSET:
3116  return "OFFSET";
3117  case EXPR_KIND_RETURNING:
3118  return "RETURNING";
3119  case EXPR_KIND_VALUES:
3121  return "VALUES";
3124  return "CHECK";
3127  return "DEFAULT";
3129  return "index expression";
3131  return "index predicate";
3133  return "statistics expression";
3135  return "USING";
3137  return "EXECUTE";
3139  return "WHEN";
3141  return "partition bound";
3143  return "PARTITION BY";
3145  return "CALL";
3146  case EXPR_KIND_COPY_WHERE:
3147  return "WHERE";
3149  return "GENERATED AS";
3150  case EXPR_KIND_CYCLE_MARK:
3151  return "CYCLE";
3152 
3153  /*
3154  * There is intentionally no default: case here, so that the
3155  * compiler will warn if we add a new ParseExprKind without
3156  * extending this switch. If we do see an unrecognized value at
3157  * runtime, we'll fall through to the "unrecognized" return.
3158  */
3159  }
3160  return "unrecognized expression kind";
3161 }
3162 
3163 /*
3164  * Make string Const node from JSON encoding name.
3165  *
3166  * UTF8 is default encoding.
3167  */
3168 static Const *
3170 {
3172  const char *enc;
3173  Name encname = palloc(sizeof(NameData));
3174 
3175  if (!format ||
3176  format->format_type == JS_FORMAT_DEFAULT ||
3177  format->encoding == JS_ENC_DEFAULT)
3179  else
3180  encoding = format->encoding;
3181 
3182  switch (encoding)
3183  {
3184  case JS_ENC_UTF16:
3185  enc = "UTF16";
3186  break;
3187  case JS_ENC_UTF32:
3188  enc = "UTF32";
3189  break;
3190  case JS_ENC_UTF8:
3191  enc = "UTF8";
3192  break;
3193  default:
3194  elog(ERROR, "invalid JSON encoding: %d", encoding);
3195  break;
3196  }
3197 
3198  namestrcpy(encname, enc);
3199 
3200  return makeConst(NAMEOID, -1, InvalidOid, NAMEDATALEN,
3201  NameGetDatum(encname), false, false);
3202 }
3203 
3204 /*
3205  * Make bytea => text conversion using specified JSON format encoding.
3206  */
3207 static Node *
3209 {
3211  FuncExpr *fexpr = makeFuncExpr(F_CONVERT_FROM, TEXTOID,
3212  list_make2(expr, encoding),
3215 
3216  fexpr->location = location;
3217 
3218  return (Node *) fexpr;
3219 }
3220 
3221 /*
3222  * Transform JSON value expression using specified input JSON format or
3223  * default format otherwise, coercing to the targettype if needed.
3224  *
3225  * Returned expression is either ve->raw_expr coerced to text (if needed) or
3226  * a JsonValueExpr with formatted_expr set to the coerced copy of raw_expr
3227  * if the specified format and the targettype requires it.
3228  */
3229 static Node *
3230 transformJsonValueExpr(ParseState *pstate, const char *constructName,
3231  JsonValueExpr *ve, JsonFormatType default_format,
3232  Oid targettype)
3233 {
3234  Node *expr = transformExprRecurse(pstate, (Node *) ve->raw_expr);
3235  Node *rawexpr;
3237  Oid exprtype;
3238  int location;
3239  char typcategory;
3240  bool typispreferred;
3241 
3242  if (exprType(expr) == UNKNOWNOID)
3243  expr = coerce_to_specific_type(pstate, expr, TEXTOID, constructName);
3244 
3245  rawexpr = expr;
3246  exprtype = exprType(expr);
3247  location = exprLocation(expr);
3248 
3249  get_type_category_preferred(exprtype, &typcategory, &typispreferred);
3250 
3251  if (ve->format->format_type != JS_FORMAT_DEFAULT)
3252  {
3253  if (ve->format->encoding != JS_ENC_DEFAULT && exprtype != BYTEAOID)
3254  ereport(ERROR,
3255  errcode(ERRCODE_DATATYPE_MISMATCH),
3256  errmsg("JSON ENCODING clause is only allowed for bytea input type"),
3257  parser_errposition(pstate, ve->format->location));
3258 
3259  if (exprtype == JSONOID || exprtype == JSONBOID)
3260  format = JS_FORMAT_DEFAULT; /* do not format json[b] types */
3261  else
3262  format = ve->format->format_type;
3263  }
3264  else if (exprtype == JSONOID || exprtype == JSONBOID)
3265  format = JS_FORMAT_DEFAULT; /* do not format json[b] types */
3266  else
3267  format = default_format;
3268 
3269  if (format != JS_FORMAT_DEFAULT ||
3270  (OidIsValid(targettype) && exprtype != targettype))
3271  {
3272  Node *coerced;
3273  bool only_allow_cast = OidIsValid(targettype);
3274 
3275  if (!only_allow_cast &&
3276  exprtype != BYTEAOID && typcategory != TYPCATEGORY_STRING)
3277  ereport(ERROR,
3278  errcode(ERRCODE_DATATYPE_MISMATCH),
3280  errmsg("cannot use non-string types with implicit FORMAT JSON clause") :
3281  errmsg("cannot use non-string types with explicit FORMAT JSON clause"),
3282  parser_errposition(pstate, ve->format->location >= 0 ?
3283  ve->format->location : location));
3284 
3285  /* Convert encoded JSON text from bytea. */
3286  if (format == JS_FORMAT_JSON && exprtype == BYTEAOID)
3287  {
3288  expr = makeJsonByteaToTextConversion(expr, ve->format, location);
3289  exprtype = TEXTOID;
3290  }
3291 
3292  if (!OidIsValid(targettype))
3293  targettype = format == JS_FORMAT_JSONB ? JSONBOID : JSONOID;
3294 
3295  /* Try to coerce to the target type. */
3296  coerced = coerce_to_target_type(pstate, expr, exprtype,
3297  targettype, -1,
3300  location);
3301 
3302  if (!coerced)
3303  {
3304  /* If coercion failed, use to_json()/to_jsonb() functions. */
3305  FuncExpr *fexpr;
3306  Oid fnoid;
3307 
3308  /*
3309  * Though only allow a cast when the target type is specified by
3310  * the caller.
3311  */
3312  if (only_allow_cast)
3313  ereport(ERROR,
3314  (errcode(ERRCODE_CANNOT_COERCE),
3315  errmsg("cannot cast type %s to %s",
3316  format_type_be(exprtype),
3317  format_type_be(targettype)),
3318  parser_errposition(pstate, location)));
3319 
3320  fnoid = targettype == JSONOID ? F_TO_JSON : F_TO_JSONB;
3321  fexpr = makeFuncExpr(fnoid, targettype, list_make1(expr),
3323 
3324  fexpr->location = location;
3325 
3326  coerced = (Node *) fexpr;
3327  }
3328 
3329  if (coerced == expr)
3330  expr = rawexpr;
3331  else
3332  {
3333  ve = copyObject(ve);
3334  ve->raw_expr = (Expr *) rawexpr;
3335  ve->formatted_expr = (Expr *) coerced;
3336 
3337  expr = (Node *) ve;
3338  }
3339  }
3340 
3341  /* If returning a JsonValueExpr, formatted_expr must have been set. */
3342  Assert(!IsA(expr, JsonValueExpr) ||
3343  ((JsonValueExpr *) expr)->formatted_expr != NULL);
3344 
3345  return expr;
3346 }
3347 
3348 /*
3349  * Checks specified output format for its applicability to the target type.
3350  */
3351 static void
3353  Oid targettype, bool allow_format_for_non_strings)
3354 {
3355  if (!allow_format_for_non_strings &&
3356  format->format_type != JS_FORMAT_DEFAULT &&
3357  (targettype != BYTEAOID &&
3358  targettype != JSONOID &&
3359  targettype != JSONBOID))
3360  {
3361  char typcategory;
3362  bool typispreferred;
3363 
3364  get_type_category_preferred(targettype, &typcategory, &typispreferred);
3365 
3366  if (typcategory != TYPCATEGORY_STRING)
3367  ereport(ERROR,
3368  errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3369  parser_errposition(pstate, format->location),
3370  errmsg("cannot use JSON format with non-string output types"));
3371  }
3372 
3373  if (format->format_type == JS_FORMAT_JSON)
3374  {
3375  JsonEncoding enc = format->encoding != JS_ENC_DEFAULT ?
3376  format->encoding : JS_ENC_UTF8;
3377 
3378  if (targettype != BYTEAOID &&
3379  format->encoding != JS_ENC_DEFAULT)
3380  ereport(ERROR,
3381  errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3382  parser_errposition(pstate, format->location),
3383  errmsg("cannot set JSON encoding for non-bytea output types"));
3384 
3385  if (enc != JS_ENC_UTF8)
3386  ereport(ERROR,
3387  errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3388  errmsg("unsupported JSON encoding"),
3389  errhint("Only UTF8 JSON encoding is supported."),
3390  parser_errposition(pstate, format->location));
3391  }
3392 }
3393 
3394 /*
3395  * Transform JSON output clause.
3396  *
3397  * Assigns target type oid and modifier.
3398  * Assigns default format or checks specified format for its applicability to
3399  * the target type.
3400  */
3401 static JsonReturning *
3403  bool allow_format)
3404 {
3405  JsonReturning *ret;
3406 
3407  /* if output clause is not specified, make default clause value */
3408  if (!output)
3409  {
3410  ret = makeNode(JsonReturning);
3411 
3413  ret->typid = InvalidOid;
3414  ret->typmod = -1;
3415 
3416  return ret;
3417  }
3418 
3419  ret = copyObject(output->returning);
3420 
3421  typenameTypeIdAndMod(pstate, output->typeName, &ret->typid, &ret->typmod);
3422 
3423  if (output->typeName->setof)
3424  ereport(ERROR,
3425  errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3426  errmsg("returning SETOF types is not supported in SQL/JSON functions"));
3427 
3428  if (ret->format->format_type == JS_FORMAT_DEFAULT)
3429  /* assign JSONB format when returning jsonb, or JSON format otherwise */
3430  ret->format->format_type =
3431  ret->typid == JSONBOID ? JS_FORMAT_JSONB : JS_FORMAT_JSON;
3432  else
3433  checkJsonOutputFormat(pstate, ret->format, ret->typid, allow_format);
3434 
3435  return ret;
3436 }
3437 
3438 /*
3439  * Transform JSON output clause of JSON constructor functions.
3440  *
3441  * Derive RETURNING type, if not specified, from argument types.
3442  */
3443 static JsonReturning *
3445  List *args)
3446 {
3447  JsonReturning *returning = transformJsonOutput(pstate, output, true);
3448 
3449  if (!OidIsValid(returning->typid))
3450  {
3451  ListCell *lc;
3452  bool have_jsonb = false;
3453 
3454  foreach(lc, args)
3455  {
3456  Node *expr = lfirst(lc);
3457  Oid typid = exprType(expr);
3458 
3459  have_jsonb |= typid == JSONBOID;
3460 
3461  if (have_jsonb)
3462  break;
3463  }
3464 
3465  if (have_jsonb)
3466  {
3467  returning->typid = JSONBOID;
3468  returning->format->format_type = JS_FORMAT_JSONB;
3469  }
3470  else
3471  {
3472  /* XXX TEXT is default by the standard, but we return JSON */
3473  returning->typid = JSONOID;
3474  returning->format->format_type = JS_FORMAT_JSON;
3475  }
3476 
3477  returning->typmod = -1;
3478  }
3479 
3480  return returning;
3481 }
3482 
3483 /*
3484  * Coerce json[b]-valued function expression to the output type.
3485  */
3486 static Node *
3488  const JsonReturning *returning, bool report_error)
3489 {
3490  Node *res;
3491  int location;
3492  Oid exprtype = exprType(expr);
3493 
3494  /* if output type is not specified or equals to function type, return */
3495  if (!OidIsValid(returning->typid) || returning->typid == exprtype)
3496  return expr;
3497 
3498  location = exprLocation(expr);
3499 
3500  if (location < 0)
3501  location = returning->format->location;
3502 
3503  /* special case for RETURNING bytea FORMAT json */
3504  if (returning->format->format_type == JS_FORMAT_JSON &&
3505  returning->typid == BYTEAOID)
3506  {
3507  /* encode json text into bytea using pg_convert_to() */
3508  Node *texpr = coerce_to_specific_type(pstate, expr, TEXTOID,
3509  "JSON_FUNCTION");
3510  Const *enc = getJsonEncodingConst(returning->format);
3511  FuncExpr *fexpr = makeFuncExpr(F_CONVERT_TO, BYTEAOID,
3512  list_make2(texpr, enc),
3515 
3516  fexpr->location = location;
3517 
3518  return (Node *) fexpr;
3519  }
3520 
3521  /* try to coerce expression to the output type */
3522  res = coerce_to_target_type(pstate, expr, exprtype,
3523  returning->typid, returning->typmod,
3524  /* XXX throwing errors when casting to char(N) */
3527  location);
3528 
3529  if (!res && report_error)
3530  ereport(ERROR,
3531  errcode(ERRCODE_CANNOT_COERCE),
3532  errmsg("cannot cast type %s to %s",
3533  format_type_be(exprtype),
3534  format_type_be(returning->typid)),
3535  parser_coercion_errposition(pstate, location, expr));
3536 
3537  return res;
3538 }
3539 
3540 /*
3541  * Make a JsonConstructorExpr node.
3542  */
3543 static Node *
3545  List *args, Expr *fexpr, JsonReturning *returning,
3546  bool unique, bool absent_on_null, int location)
3547 {
3549  Node *placeholder;
3550  Node *coercion;
3551 
3552  jsctor->args = args;
3553  jsctor->func = fexpr;
3554  jsctor->type = type;
3555  jsctor->returning = returning;
3556  jsctor->unique = unique;
3557  jsctor->absent_on_null = absent_on_null;
3558  jsctor->location = location;
3559 
3560  /*
3561  * Coerce to the RETURNING type and format, if needed. We abuse
3562  * CaseTestExpr here as placeholder to pass the result of either
3563  * evaluating 'fexpr' or whatever is produced by ExecEvalJsonConstructor()
3564  * that is of type JSON or JSONB to the coercion function.
3565  */
3566  if (fexpr)
3567  {
3569 
3570  cte->typeId = exprType((Node *) fexpr);
3571  cte->typeMod = exprTypmod((Node *) fexpr);
3572  cte->collation = exprCollation((Node *) fexpr);
3573 
3574  placeholder = (Node *) cte;
3575  }
3576  else
3577  {
3579 
3580  cte->typeId = returning->format->format_type == JS_FORMAT_JSONB ?
3581  JSONBOID : JSONOID;
3582  cte->typeMod = -1;
3583  cte->collation = InvalidOid;
3584 
3585  placeholder = (Node *) cte;
3586  }
3587 
3588  coercion = coerceJsonFuncExpr(pstate, placeholder, returning, true);
3589 
3590  if (coercion != placeholder)
3591  jsctor->coercion = (Expr *) coercion;
3592 
3593  return (Node *) jsctor;
3594 }
3595 
3596 /*
3597  * Transform JSON_OBJECT() constructor.
3598  *
3599  * JSON_OBJECT() is transformed into json[b]_build_object[_ext]() call
3600  * depending on the output JSON format. The first two arguments of
3601  * json[b]_build_object_ext() are absent_on_null and check_unique.
3602  *
3603  * Then function call result is coerced to the target type.
3604  */
3605 static Node *
3607 {
3608  JsonReturning *returning;
3609  List *args = NIL;
3610 
3611  /* transform key-value pairs, if any */
3612  if (ctor->exprs)
3613  {
3614  ListCell *lc;
3615 
3616  /* transform and append key-value arguments */
3617  foreach(lc, ctor->exprs)
3618  {
3620  Node *key = transformExprRecurse(pstate, (Node *) kv->key);
3621  Node *val = transformJsonValueExpr(pstate, "JSON_OBJECT()",
3622  kv->value,
3624  InvalidOid);
3625 
3626  args = lappend(args, key);
3627  args = lappend(args, val);
3628  }
3629  }
3630 
3631  returning = transformJsonConstructorOutput(pstate, ctor->output, args);
3632 
3633  return makeJsonConstructorExpr(pstate, JSCTOR_JSON_OBJECT, args, NULL,
3634  returning, ctor->unique,
3635  ctor->absent_on_null, ctor->location);
3636 }
3637 
3638 /*
3639  * Transform JSON_ARRAY(query [FORMAT] [RETURNING] [ON NULL]) into
3640  * (SELECT JSON_ARRAYAGG(a [FORMAT] [RETURNING] [ON NULL]) FROM (query) q(a))
3641  */
3642 static Node *
3645 {
3646  SubLink *sublink = makeNode(SubLink);
3649  Alias *alias = makeNode(Alias);
3650  ResTarget *target = makeNode(ResTarget);
3652  ColumnRef *colref = makeNode(ColumnRef);
3653  Query *query;
3654  ParseState *qpstate;
3655 
3656  /* Transform query only for counting target list entries. */
3657  qpstate = make_parsestate(pstate);
3658 
3659  query = transformStmt(qpstate, ctor->query);
3660 
3661  if (count_nonjunk_tlist_entries(query->targetList) != 1)
3662  ereport(ERROR,
3663  errcode(ERRCODE_SYNTAX_ERROR),
3664  errmsg("subquery must return only one column"),
3665  parser_errposition(pstate, ctor->location));
3666 
3667  free_parsestate(qpstate);
3668 
3669  colref->fields = list_make2(makeString(pstrdup("q")),
3670  makeString(pstrdup("a")));
3671  colref->location = ctor->location;
3672 
3673  /*
3674  * No formatting necessary, so set formatted_expr to be the same as
3675  * raw_expr.
3676  */
3677  agg->arg = makeJsonValueExpr((Expr *) colref, (Expr *) colref,
3678  ctor->format);
3679  agg->absent_on_null = ctor->absent_on_null;
3681  agg->constructor->agg_order = NIL;
3682  agg->constructor->output = ctor->output;
3683  agg->constructor->location = ctor->location;
3684 
3685  target->name = NULL;
3686  target->indirection = NIL;
3687  target->val = (Node *) agg;
3688  target->location = ctor->location;
3689 
3690  alias->aliasname = pstrdup("q");
3691  alias->colnames = list_make1(makeString(pstrdup("a")));
3692 
3693  range->lateral = false;
3694  range->subquery = ctor->query;
3695  range->alias = alias;
3696 
3697  select->targetList = list_make1(target);
3698  select->fromClause = list_make1(range);
3699 
3700  sublink->subLinkType = EXPR_SUBLINK;
3701  sublink->subLinkId = 0;
3702  sublink->testexpr = NULL;
3703  sublink->operName = NIL;
3704  sublink->subselect = (Node *) select;
3705  sublink->location = ctor->location;
3706 
3707  return transformExprRecurse(pstate, (Node *) sublink);
3708 }
3709 
3710 /*
3711  * Common code for JSON_OBJECTAGG and JSON_ARRAYAGG transformation.
3712  */
3713 static Node *
3715  JsonReturning *returning, List *args,
3716  Oid aggfnoid, Oid aggtype,
3717  JsonConstructorType ctor_type,
3718  bool unique, bool absent_on_null)
3719 {
3720  Node *node;
3721  Expr *aggfilter;
3722 
3723  aggfilter = agg_ctor->agg_filter ? (Expr *)
3724  transformWhereClause(pstate, agg_ctor->agg_filter,
3725  EXPR_KIND_FILTER, "FILTER") : NULL;
3726 
3727  if (agg_ctor->over)
3728  {
3729  /* window function */
3730  WindowFunc *wfunc = makeNode(WindowFunc);
3731 
3732  wfunc->winfnoid = aggfnoid;
3733  wfunc->wintype = aggtype;
3734  /* wincollid and inputcollid will be set by parse_collate.c */
3735  wfunc->args = args;
3736  wfunc->aggfilter = aggfilter;
3737  /* winref will be set by transformWindowFuncCall */
3738  wfunc->winstar = false;
3739  wfunc->winagg = true;
3740  wfunc->location = agg_ctor->location;
3741 
3742  /*
3743  * ordered aggs not allowed in windows yet
3744  */
3745  if (agg_ctor->agg_order != NIL)
3746  ereport(ERROR,
3747  errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3748  errmsg("aggregate ORDER BY is not implemented for window functions"),
3749  parser_errposition(pstate, agg_ctor->location));
3750 
3751  /* parse_agg.c does additional window-func-specific processing */
3752  transformWindowFuncCall(pstate, wfunc, agg_ctor->over);
3753 
3754  node = (Node *) wfunc;
3755  }
3756  else
3757  {
3758  Aggref *aggref = makeNode(Aggref);
3759 
3760  aggref->aggfnoid = aggfnoid;
3761  aggref->aggtype = aggtype;
3762 
3763  /* aggcollid and inputcollid will be set by parse_collate.c */
3764  /* aggtranstype will be set by planner */
3765  /* aggargtypes will be set by transformAggregateCall */
3766  /* aggdirectargs and args will be set by transformAggregateCall */
3767  /* aggorder and aggdistinct will be set by transformAggregateCall */
3768  aggref->aggfilter = aggfilter;
3769  aggref->aggstar = false;
3770  aggref->aggvariadic = false;
3771  aggref->aggkind = AGGKIND_NORMAL;
3772  aggref->aggpresorted = false;
3773  /* agglevelsup will be set by transformAggregateCall */
3774  aggref->aggsplit = AGGSPLIT_SIMPLE; /* planner might change this */
3775  aggref->aggno = -1; /* planner will set aggno and aggtransno */
3776  aggref->aggtransno = -1;
3777  aggref->location = agg_ctor->location;
3778 
3779  transformAggregateCall(pstate, aggref, args, agg_ctor->agg_order, false);
3780 
3781  node = (Node *) aggref;
3782  }
3783 
3784  return makeJsonConstructorExpr(pstate, ctor_type, NIL, (Expr *) node,
3785  returning, unique, absent_on_null,
3786  agg_ctor->location);
3787 }
3788 
3789 /*
3790  * Transform JSON_OBJECTAGG() aggregate function.
3791  *
3792  * JSON_OBJECTAGG() is transformed into
3793  * json[b]_objectagg[_unique][_strict](key, value) call depending on
3794  * the output JSON format. Then the function call result is coerced to the
3795  * target output type.
3796  */
3797 static Node *
3799 {
3800  JsonReturning *returning;
3801  Node *key;
3802  Node *val;
3803  List *args;
3804  Oid aggfnoid;
3805  Oid aggtype;
3806 
3807  key = transformExprRecurse(pstate, (Node *) agg->arg->key);
3808  val = transformJsonValueExpr(pstate, "JSON_OBJECTAGG()",
3809  agg->arg->value,
3811  InvalidOid);
3812  args = list_make2(key, val);
3813 
3814  returning = transformJsonConstructorOutput(pstate, agg->constructor->output,
3815  args);
3816 
3817  if (returning->format->format_type == JS_FORMAT_JSONB)
3818  {
3819  if (agg->absent_on_null)
3820  if (agg->unique)
3821  aggfnoid = F_JSONB_OBJECT_AGG_UNIQUE_STRICT;
3822  else
3823  aggfnoid = F_JSONB_OBJECT_AGG_STRICT;
3824  else if (agg->unique)
3825  aggfnoid = F_JSONB_OBJECT_AGG_UNIQUE;
3826  else
3827  aggfnoid = F_JSONB_OBJECT_AGG;
3828 
3829  aggtype = JSONBOID;
3830  }
3831  else
3832  {
3833  if (agg->absent_on_null)
3834  if (agg->unique)
3835  aggfnoid = F_JSON_OBJECT_AGG_UNIQUE_STRICT;
3836  else
3837  aggfnoid = F_JSON_OBJECT_AGG_STRICT;
3838  else if (agg->unique)
3839  aggfnoid = F_JSON_OBJECT_AGG_UNIQUE;
3840  else
3841  aggfnoid = F_JSON_OBJECT_AGG;
3842 
3843  aggtype = JSONOID;
3844  }
3845 
3846  return transformJsonAggConstructor(pstate, agg->constructor, returning,
3847  args, aggfnoid, aggtype,
3849  agg->unique, agg->absent_on_null);
3850 }
3851 
3852 /*
3853  * Transform JSON_ARRAYAGG() aggregate function.
3854  *
3855  * JSON_ARRAYAGG() is transformed into json[b]_agg[_strict]() call depending
3856  * on the output JSON format and absent_on_null. Then the function call result
3857  * is coerced to the target output type.
3858  */
3859 static Node *
3861 {
3862  JsonReturning *returning;
3863  Node *arg;
3864  Oid aggfnoid;
3865  Oid aggtype;
3866 
3867  arg = transformJsonValueExpr(pstate, "JSON_ARRAYAGG()",
3868  agg->arg,
3870 
3871  returning = transformJsonConstructorOutput(pstate, agg->constructor->output,
3872  list_make1(arg));
3873 
3874  if (returning->format->format_type == JS_FORMAT_JSONB)
3875  {
3876  aggfnoid = agg->absent_on_null ? F_JSONB_AGG_STRICT : F_JSONB_AGG;
3877  aggtype = JSONBOID;
3878  }
3879  else
3880  {
3881  aggfnoid = agg->absent_on_null ? F_JSON_AGG_STRICT : F_JSON_AGG;
3882  aggtype = JSONOID;
3883  }
3884 
3885  return transformJsonAggConstructor(pstate, agg->constructor, returning,
3886  list_make1(arg), aggfnoid, aggtype,
3888  false, agg->absent_on_null);
3889 }
3890 
3891 /*
3892  * Transform JSON_ARRAY() constructor.
3893  *
3894  * JSON_ARRAY() is transformed into json[b]_build_array[_ext]() call
3895  * depending on the output JSON format. The first argument of
3896  * json[b]_build_array_ext() is absent_on_null.
3897  *
3898  * Then function call result is coerced to the target type.
3899  */
3900 static Node *
3902 {
3903  JsonReturning *returning;
3904  List *args = NIL;
3905 
3906  /* transform element expressions, if any */
3907  if (ctor->exprs)
3908  {
3909  ListCell *lc;
3910 
3911  /* transform and append element arguments */
3912  foreach(lc, ctor->exprs)
3913  {
3914  JsonValueExpr *jsval = castNode(JsonValueExpr, lfirst(lc));
3915  Node *val = transformJsonValueExpr(pstate, "JSON_ARRAY()",
3916  jsval,
3918  InvalidOid);
3919 
3920  args = lappend(args, val);
3921  }
3922  }
3923 
3924  returning = transformJsonConstructorOutput(pstate, ctor->output, args);
3925 
3926  return makeJsonConstructorExpr(pstate, JSCTOR_JSON_ARRAY, args, NULL,
3927  returning, false, ctor->absent_on_null,
3928  ctor->location);
3929 }
3930 
3931 static Node *
3933  Oid *exprtype)
3934 {
3935  Node *raw_expr = transformExprRecurse(pstate, jsexpr);
3936  Node *expr = raw_expr;
3937 
3938  *exprtype = exprType(expr);
3939 
3940  /* prepare input document */
3941  if (*exprtype == BYTEAOID)
3942  {
3943  JsonValueExpr *jve;
3944 
3945  expr = raw_expr;
3946  expr = makeJsonByteaToTextConversion(expr, format, exprLocation(expr));
3947  *exprtype = TEXTOID;
3948 
3949  jve = makeJsonValueExpr((Expr *) raw_expr, (Expr *) expr, format);
3950  expr = (Node *) jve;
3951  }
3952  else
3953  {
3954  char typcategory;
3955  bool typispreferred;
3956 
3957  get_type_category_preferred(*exprtype, &typcategory, &typispreferred);
3958 
3959  if (*exprtype == UNKNOWNOID || typcategory == TYPCATEGORY_STRING)
3960  {
3961  expr = coerce_to_target_type(pstate, (Node *) expr, *exprtype,
3962  TEXTOID, -1,
3964  COERCE_IMPLICIT_CAST, -1);
3965  *exprtype = TEXTOID;
3966  }
3967 
3968  if (format->encoding != JS_ENC_DEFAULT)
3969  ereport(ERROR,
3970  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3971  parser_errposition(pstate, format->location),
3972  errmsg("cannot use JSON FORMAT ENCODING clause for non-bytea input types")));
3973  }
3974 
3975  return expr;
3976 }
3977 
3978 /*
3979  * Transform IS JSON predicate.
3980  */
3981 static Node *
3983 {
3984  Oid exprtype;
3985  Node *expr = transformJsonParseArg(pstate, pred->expr, pred->format,
3986  &exprtype);
3987 
3988  /* make resulting expression */
3989  if (exprtype != TEXTOID && exprtype != JSONOID && exprtype != JSONBOID)
3990  ereport(ERROR,
3991  (errcode(ERRCODE_DATATYPE_MISMATCH),
3992  errmsg("cannot use type %s in IS JSON predicate",
3993  format_type_be(exprtype))));
3994 
3995  /* This intentionally(?) drops the format clause. */
3996  return makeJsonIsPredicate(expr, NULL, pred->item_type,
3997  pred->unique_keys, pred->location);
3998 }
3999 
4000 /*
4001  * Transform the RETURNING clause of a JSON_*() expression if there is one and
4002  * create one if not.
4003  */
4004 static JsonReturning *
4006 {
4007  JsonReturning *returning;
4008 
4009  if (output)
4010  {
4011  returning = transformJsonOutput(pstate, output, false);
4012 
4013  Assert(OidIsValid(returning->typid));
4014 
4015  if (returning->typid != JSONOID && returning->typid != JSONBOID)
4016  ereport(ERROR,
4017  (errcode(ERRCODE_DATATYPE_MISMATCH),
4018  errmsg("cannot use RETURNING type %s in %s",
4019  format_type_be(returning->typid), fname),
4020  parser_errposition(pstate, output->typeName->location)));
4021  }
4022  else
4023  {
4024  /* Output type is JSON by default. */
4025  Oid targettype = JSONOID;
4027 
4028  returning = makeNode(JsonReturning);
4029  returning->format = makeJsonFormat(format, JS_ENC_DEFAULT, -1);
4030  returning->typid = targettype;
4031  returning->typmod = -1;
4032  }
4033 
4034  return returning;
4035 }
4036 
4037 /*
4038  * Transform a JSON() expression.
4039  *
4040  * JSON() is transformed into a JsonConstructorExpr of type JSCTOR_JSON_PARSE,
4041  * which validates the input expression value as JSON.
4042  */
4043 static Node *
4045 {
4046  JsonOutput *output = jsexpr->output;
4047  JsonReturning *returning;
4048  Node *arg;
4049 
4050  returning = transformJsonReturning(pstate, output, "JSON()");
4051 
4052  if (jsexpr->unique_keys)
4053  {
4054  /*
4055  * Coerce string argument to text and then to json[b] in the executor
4056  * node with key uniqueness check.
4057  */
4058  JsonValueExpr *jve = jsexpr->expr;
4059  Oid arg_type;
4060 
4061  arg = transformJsonParseArg(pstate, (Node *) jve->raw_expr, jve->format,
4062  &arg_type);
4063 
4064  if (arg_type != TEXTOID)
4065  ereport(ERROR,
4066  (errcode(ERRCODE_DATATYPE_MISMATCH),
4067  errmsg("cannot use non-string types with WITH UNIQUE KEYS clause"),
4068  parser_errposition(pstate, jsexpr->location)));
4069  }
4070  else
4071  {
4072  /*
4073  * Coerce argument to target type using CAST for compatibility with PG
4074  * function-like CASTs.
4075  */
4076  arg = transformJsonValueExpr(pstate, "JSON()", jsexpr->expr,
4077  JS_FORMAT_JSON, returning->typid);
4078  }
4079 
4081  returning, jsexpr->unique_keys, false,
4082  jsexpr->location);
4083 }
4084 
4085 /*
4086  * Transform a JSON_SCALAR() expression.
4087  *
4088  * JSON_SCALAR() is transformed into a JsonConstructorExpr of type
4089  * JSCTOR_JSON_SCALAR, which converts the input SQL scalar value into
4090  * a json[b] value.
4091  */
4092 static Node *
4094 {
4095  Node *arg = transformExprRecurse(pstate, (Node *) jsexpr->expr);
4096  JsonOutput *output = jsexpr->output;
4097  JsonReturning *returning;
4098 
4099  returning = transformJsonReturning(pstate, output, "JSON_SCALAR()");
4100 
4101  if (exprType(arg) == UNKNOWNOID)
4102  arg = coerce_to_specific_type(pstate, arg, TEXTOID, "JSON_SCALAR");
4103 
4105  returning, false, false, jsexpr->location);
4106 }
4107 
4108 /*
4109  * Transform a JSON_SERIALIZE() expression.
4110  *
4111  * JSON_SERIALIZE() is transformed into a JsonConstructorExpr of type
4112  * JSCTOR_JSON_SERIALIZE which converts the input JSON value into a character
4113  * or bytea string.
4114  */
4115 static Node *
4117 {
4118  JsonReturning *returning;
4119  Node *arg = transformJsonValueExpr(pstate, "JSON_SERIALIZE()",
4120  expr->expr,
4122  InvalidOid);
4123 
4124  if (expr->output)
4125  {
4126  returning = transformJsonOutput(pstate, expr->output, true);
4127 
4128  if (returning->typid != BYTEAOID)
4129  {
4130  char typcategory;
4131  bool typispreferred;
4132 
4133  get_type_category_preferred(returning->typid, &typcategory,
4134  &typispreferred);
4135  if (typcategory != TYPCATEGORY_STRING)
4136  ereport(ERROR,
4137  (errcode(ERRCODE_DATATYPE_MISMATCH),
4138  errmsg("cannot use RETURNING type %s in %s",
4139  format_type_be(returning->typid),
4140  "JSON_SERIALIZE()"),
4141  errhint("Try returning a string type or bytea.")));
4142  }
4143  }
4144  else
4145  {
4146  /* RETURNING TEXT FORMAT JSON is by default */
4147  returning = makeNode(JsonReturning);
4149  returning->typid = TEXTOID;
4150  returning->typmod = -1;
4151  }
4152 
4154  NULL, returning, false, false, expr->location);
4155 }
#define InvalidAttrNumber
Definition: attnum.h:23
int32 anytimestamp_typmod_check(bool istz, int32 typmod)
Definition: timestamp.c:124
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1319
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:828
Bitmapset * bms_int_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:1122
signed int int32
Definition: c.h:483
#define OidIsValid(objectId)
Definition: c.h:764
enc
int32 anytime_typmod_check(bool istz, int32 typmod)
Definition: date.c:71
char * get_database_name(Oid dbid)
Definition: dbcommands.c:3089
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1162
int errdetail(const char *fmt,...)
Definition: elog.c:1208
int errhint(const char *fmt,...)
Definition: elog.c:1322
int errcode(int sqlerrcode)
Definition: elog.c:860
int errmsg(const char *fmt,...)
Definition: elog.c:1075
#define _(x)
Definition: elog.c:91
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
void err(int eval, const char *fmt,...)
Definition: err.c:43
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
Oid MyDatabaseId
Definition: globals.c:90
#define MaxTupleAttributeNumber
Definition: htup_details.h:34
#define funcname
Definition: indent_codes.h:69
FILE * output
long val
Definition: informix.c:664
int b
Definition: isn.c:70
int x
Definition: isn.c:71
int a
Definition: isn.c:69
int j
Definition: isn.c:74
int i
Definition: isn.c:73
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
Assert(fmt[strlen(fmt) - 1] !='\n')
List * list_truncate(List *list, int new_size)
Definition: list.c:631
List * lappend(List *list, void *datum)
Definition: list.c:339
List * lappend_oid(List *list, Oid datum)
Definition: list.c:375
List * list_concat(List *list1, const List *list2)
Definition: list.c:561
List * lcons(void *datum, List *list)
Definition: list.c:495
List * list_delete_last(List *list)
Definition: list.c:957
Oid get_element_type(Oid typid)
Definition: lsyscache.c:2714
bool type_is_rowtype(Oid typid)
Definition: lsyscache.c:2610
List * get_op_btree_interpretation(Oid opno)
Definition: lsyscache.c:600
bool type_is_collatable(Oid typid)
Definition: lsyscache.c:3036
Oid getBaseTypeAndTypmod(Oid typid, int32 *typmod)
Definition: lsyscache.c:2493
Oid get_array_type(Oid typid)
Definition: lsyscache.c:2742
void get_type_category_preferred(Oid typid, char *typcategory, bool *typispreferred)
Definition: lsyscache.c:2665
#define type_is_array(typid)
Definition: lsyscache.h:206
Var * makeWholeRowVar(RangeTblEntry *rte, int varno, Index varlevelsup, bool allowScalar)
Definition: makefuncs.c:136
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Definition: makefuncs.c:522
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:241
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
Definition: makefuncs.c:302
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:425
JsonFormat * makeJsonFormat(JsonFormatType type, JsonEncoding encoding, int location)
Definition: makefuncs.c:832
Expr * makeBoolExpr(BoolExprType boolop, List *args, int location)
Definition: makefuncs.c:372
Node * makeBoolConst(bool value, bool isnull)
Definition: makefuncs.c:360
JsonValueExpr * makeJsonValueExpr(Expr *raw_expr, Expr *formatted_expr, JsonFormat *format)
Definition: makefuncs.c:848
Node * makeJsonIsPredicate(Node *expr, JsonFormat *format, JsonValueType item_type, bool unique_keys, int location)
Definition: makefuncs.c:880
A_Expr * makeSimpleA_Expr(A_Expr_Kind kind, char *name, Node *lexpr, Node *rexpr, int location)
Definition: makefuncs.c:49
char * pstrdup(const char *in)
Definition: mcxt.c:1619
void * palloc(Size size)
Definition: mcxt.c:1201
void namestrcpy(Name name, const char *str)
Definition: name.c:233
char * NameListToString(const List *names)
Definition: namespace.c:3579
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:43
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:282
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:786
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1312
bool expression_returns_set(Node *clause)
Definition: nodeFuncs.c:728
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
#define copyObject(obj)
Definition: nodes.h:223
#define nodeTag(nodeptr)
Definition: nodes.h:133
@ CMD_SELECT
Definition: nodes.h:255
@ AGGSPLIT_SIMPLE
Definition: nodes.h:366
#define NodeSetTag(nodeptr, t)
Definition: nodes.h:156
#define makeNode(_type_)
Definition: nodes.h:155
#define castNode(_type_, nodeptr)
Definition: nodes.h:176
Node * transformGroupingFunc(ParseState *pstate, GroupingFunc *p)
Definition: parse_agg.c:260
void transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc, WindowDef *windef)
Definition: parse_agg.c:821
void transformAggregateCall(ParseState *pstate, Aggref *agg, List *args, List *aggorder, bool agg_distinct)
Definition: parse_agg.c:104
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
Node * coerce_to_common_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *context)
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:157
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:78
bool verify_common_type(Oid common_type, List *exprs)
Node * coerce_to_boolean(ParseState *pstate, Node *node, const char *constructName)
int parser_coercion_errposition(ParseState *pstate, int coerce_location, Node *input_expr)
Node * coerce_to_specific_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *constructName)
Oid select_common_type(ParseState *pstate, List *exprs, const char *context, Node **which_expr)
void assign_expr_collations(ParseState *pstate, Node *expr)
static JsonReturning * transformJsonOutput(ParseState *pstate, const JsonOutput *output, bool allow_format)
Definition: parse_expr.c:3402
static Node * make_nulltest_from_distinct(ParseState *pstate, A_Expr *distincta, Node *arg)
Definition: parse_expr.c:3040
static void unknown_attribute(ParseState *pstate, Node *relref, const char *attname, int location)
Definition: parse_expr.c:373
static Node * makeJsonByteaToTextConversion(Node *expr, JsonFormat *format, int location)
Definition: parse_expr.c:3208
static Node * transformJsonArrayConstructor(ParseState *pstate, JsonArrayConstructor *ctor)
Definition: parse_expr.c:3901
static Node * transformJsonScalarExpr(ParseState *pstate, JsonScalarExpr *expr)
Definition: parse_expr.c:4093
static Node * transformJsonValueExpr(ParseState *pstate, const char *constructName, JsonValueExpr *ve, JsonFormatType default_format, Oid targettype)
Definition: parse_expr.c:3230
static Node * transformCurrentOfExpr(ParseState *pstate, CurrentOfExpr *cexpr)
Definition: parse_expr.c:2513
static Node * transformAExprOpAll(ParseState *pstate, A_Expr *a)
Definition: parse_expr.c:998
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:110
static Node * transformAExprIn(ParseState *pstate, A_Expr *a)
Definition: parse_expr.c:1105
static JsonReturning * transformJsonConstructorOutput(ParseState *pstate, JsonOutput *output, List *args)
Definition: parse_expr.c:3444
static void checkJsonOutputFormat(ParseState *pstate, const JsonFormat *format, Oid targettype, bool allow_format_for_non_strings)
Definition: parse_expr.c:3352
static Node * transformAExprOpAny(ParseState *pstate, A_Expr *a)
Definition: parse_expr.c:984
static Node * transformXmlSerialize(ParseState *pstate, XmlSerialize *xs)
Definition: parse_expr.c:2429
static Node * transformExprRecurse(ParseState *pstate, Node *expr)
Definition: parse_expr.c:128
static JsonReturning * transformJsonReturning(ParseState *pstate, JsonOutput *output, const char *fname)
Definition: parse_expr.c:4005
static Node * transformAExprNullIf(ParseState *pstate, A_Expr *a)
Definition: parse_expr.c:1063
static Node * transformJsonAggConstructor(ParseState *pstate, JsonAggConstructor *agg_ctor, JsonReturning *returning, List *args, Oid aggfnoid, Oid aggtype, JsonConstructorType ctor_type, bool unique, bool absent_on_null)
Definition: parse_expr.c:3714
static bool exprIsNullConstant(Node *arg)
Definition: parse_expr.c:890
static Expr * make_distinct_op(ParseState *pstate, List *opname, Node *ltree, Node *rtree, int location)
Definition: parse_expr.c:3007
static Node * transformJsonArrayQueryConstructor(ParseState *pstate, JsonArrayQueryConstructor *ctor)
Definition: parse_expr.c:3643
static Node * transformSQLValueFunction(ParseState *pstate, SQLValueFunction *svf)
Definition: parse_expr.c:2247
static Node * transformColumnRef(ParseState *pstate, ColumnRef *cref)
Definition: parse_expr.c:491
static Node * transformCollateClause(ParseState *pstate, CollateClause *c)
Definition: parse_expr.c:2721
static Node * transformBoolExpr(ParseState *pstate, BoolExpr *a)
Definition: parse_expr.c:1357
static Node * transformFuncCall(ParseState *pstate, FuncCall *fn)
Definition: parse_expr.c:1393
static Node * makeJsonConstructorExpr(ParseState *pstate, JsonConstructorType type, List *args, Expr *fexpr, JsonReturning *returning, bool unique, bool absent_on_null, int location)
Definition: parse_expr.c:3544
static Node * transformMinMaxExpr(ParseState *pstate, MinMaxExpr *m)
Definition: parse_expr.c:2208
static Node * transformCoalesceExpr(ParseState *pstate, CoalesceExpr *c)
Definition: parse_expr.c:2159
bool Transform_null_equals
Definition: parse_expr.c:45
static Node * transformSubLink(ParseState *pstate, SubLink *sublink)
Definition: parse_expr.c:1726
static Node * transformJsonObjectConstructor(ParseState *pstate, JsonObjectConstructor *ctor)
Definition: parse_expr.c:3606
static Node * make_row_comparison_op(ParseState *pstate, List *opname, List *largs, List *rargs, int location)
Definition: parse_expr.c:2761
static Node * transformAExprOp(ParseState *pstate, A_Expr *a)
Definition: parse_expr.c:903
static Node * transformJsonArrayAgg(ParseState *pstate, JsonArrayAgg *agg)
Definition: parse_expr.c:3860
static Node * transformArrayExpr(ParseState *pstate, A_ArrayExpr *a, Oid array_type, Oid element_type, int32 typmod)
Definition: parse_expr.c:1968
static Node * transformMultiAssignRef(ParseState *pstate, MultiAssignRef *maref)
Definition: parse_expr.c:1438
static Node * coerceJsonFuncExpr(ParseState *pstate, Node *expr, const JsonReturning *returning, bool report_error)
Definition: parse_expr.c:3487
static Node * transformBooleanTest(ParseState *pstate, BooleanTest *b)
Definition: parse_expr.c:2473
static Node * make_row_distinct_op(ParseState *pstate, List *opname, RowExpr *lrow, RowExpr *rrow, int location)
Definition: parse_expr.c:2963
static Node * transformTypeCast(ParseState *pstate, TypeCast *tc)
Definition: parse_expr.c:2637
static Node * transformParamRef(ParseState *pstate, ParamRef *pref)
Definition: parse_expr.c:866
static Node * transformCaseExpr(ParseState *pstate, CaseExpr *c)
Definition: parse_expr.c:1586
static Node * transformJsonParseExpr(ParseState *pstate, JsonParseExpr *expr)
Definition: parse_expr.c:4044
static Node * transformIndirection(ParseState *pstate, A_Indirection *ind)
Definition: parse_expr.c:419
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:3064
static Node * transformJsonParseArg(ParseState *pstate, Node *jsexpr, JsonFormat *format, Oid *exprtype)
Definition: parse_expr.c:3932
static Node * transformJsonSerializeExpr(ParseState *pstate, JsonSerializeExpr *expr)
Definition: parse_expr.c:4116
static Node * transformRowExpr(ParseState *pstate, RowExpr *r, bool allowDefault)
Definition: parse_expr.c:2121
static Node * transformXmlExpr(ParseState *pstate, XmlExpr *x)
Definition: parse_expr.c:2300
static Node * transformAExprBetween(ParseState *pstate, A_Expr *a)
Definition: parse_expr.c:1263
static Node * transformWholeRowRef(ParseState *pstate, ParseNamespaceItem *nsitem, int sublevels_up, int location)
Definition: parse_expr.c:2565
static Const * getJsonEncodingConst(JsonFormat *format)
Definition: parse_expr.c:3169
static Node * transformJsonIsPredicate(ParseState *pstate, JsonIsPredicate *pred)
Definition: parse_expr.c:3982
static Node * transformJsonObjectAgg(ParseState *pstate, JsonObjectAgg *agg)
Definition: parse_expr.c:3798
static Node * transformAExprDistinct(ParseState *pstate, A_Expr *a)
Definition: parse_expr.c:1012
Node * ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs, Node *last_srf, FuncCall *fn, bool proc_call, int location)
Definition: parse_func.c:90
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:77
SubscriptingRef * transformContainerSubscripts(ParseState *pstate, Node *containerBase, Oid containerType, int32 containerTypMod, List *indirection, bool isAssignment)
Definition: parse_node.c:248
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
Const * make_const(ParseState *pstate, A_Const *aconst)
Definition: parse_node.c:352
ParseExprKind
Definition: parse_node.h:39
@ EXPR_KIND_EXECUTE_PARAMETER
Definition: parse_node.h:75
@ EXPR_KIND_DOMAIN_CHECK
Definition: parse_node.h:68
@ EXPR_KIND_COPY_WHERE
Definition: parse_node.h:81
@ EXPR_KIND_COLUMN_DEFAULT
Definition: parse_node.h:69
@ EXPR_KIND_DISTINCT_ON
Definition: parse_node.h:61
@ EXPR_KIND_MERGE_WHEN
Definition: parse_node.h:58
@ EXPR_KIND_STATS_EXPRESSION
Definition: parse_node.h:73
@ EXPR_KIND_INDEX_EXPRESSION
Definition: parse_node.h:71
@ EXPR_KIND_PARTITION_BOUND
Definition: parse_node.h:78
@ EXPR_KIND_FUNCTION_DEFAULT
Definition: parse_node.h:70
@ EXPR_KIND_WINDOW_FRAME_RANGE
Definition: parse_node.h:51
@ EXPR_KIND_VALUES
Definition: parse_node.h:65
@ EXPR_KIND_FROM_SUBSELECT
Definition: parse_node.h:44
@ EXPR_KIND_POLICY
Definition: parse_node.h:77
@ EXPR_KIND_WINDOW_FRAME_GROUPS
Definition: parse_node.h:53
@ EXPR_KIND_PARTITION_EXPRESSION
Definition: parse_node.h:79
@ EXPR_KIND_JOIN_USING
Definition: parse_node.h:43
@ EXPR_KIND_INDEX_PREDICATE
Definition: parse_node.h:72
@ EXPR_KIND_ORDER_BY
Definition: parse_node.h:60
@ EXPR_KIND_OFFSET
Definition: parse_node.h:63
@ EXPR_KIND_JOIN_ON
Definition: parse_node.h:42
@ EXPR_KIND_HAVING
Definition: parse_node.h:47
@ EXPR_KIND_INSERT_TARGET
Definition: parse_node.h:55
@ EXPR_KIND_ALTER_COL_TRANSFORM
Definition: parse_node.h:74
@ EXPR_KIND_LIMIT
Definition: parse_node.h:62
@ EXPR_KIND_WHERE
Definition: parse_node.h:46
@ EXPR_KIND_UPDATE_TARGET
Definition: parse_node.h:57
@ EXPR_KIND_SELECT_TARGET
Definition: parse_node.h:54
@ EXPR_KIND_RETURNING
Definition: parse_node.h:64
@ EXPR_KIND_GENERATED_COLUMN
Definition: parse_node.h:82
@ EXPR_KIND_NONE
Definition: parse_node.h:40
@ EXPR_KIND_CALL_ARGUMENT
Definition: parse_node.h:80
@ EXPR_KIND_GROUP_BY
Definition: parse_node.h:59
@ EXPR_KIND_OTHER
Definition: parse_node.h:41
@ EXPR_KIND_FROM_FUNCTION
Definition: parse_node.h:45
@ EXPR_KIND_TRIGGER_WHEN
Definition: parse_node.h:76
@ EXPR_KIND_FILTER
Definition: parse_node.h:48
@ EXPR_KIND_UPDATE_SOURCE
Definition: parse_node.h:56
@ EXPR_KIND_CHECK_CONSTRAINT
Definition: parse_node.h:67
@ EXPR_KIND_WINDOW_PARTITION
Definition: parse_node.h:49
@ EXPR_KIND_CYCLE_MARK
Definition: parse_node.h:83
@ EXPR_KIND_WINDOW_FRAME_ROWS
Definition: parse_node.h:52
@ EXPR_KIND_WINDOW_ORDER
Definition: parse_node.h:50
@ EXPR_KIND_VALUES_SINGLE
Definition: parse_node.h:66
Expr * make_op(ParseState *pstate, List *opname, Node *ltree, Node *rtree, Node *last_srf, int location)
Definition: parse_oper.c:660
Expr * make_scalar_array_op(ParseState *pstate, List *opname, bool useOr, Node *ltree, Node *rtree, int location)
Definition: parse_oper.c:770
void markNullableIfNeeded(ParseState *pstate, Var *var)
RangeTblEntry * GetRTEByRangeTablePosn(ParseState *pstate, int varno, int sublevels_up)
void errorMissingColumn(ParseState *pstate, const char *relname, const char *colname, int location)
void markVarForSelectPriv(ParseState *pstate, Var *var)
void errorMissingRTE(ParseState *pstate, RangeVar *relation)
Node * scanNSItemForColumn(ParseState *pstate, ParseNamespaceItem *nsitem, int sublevels_up, const char *colname, int location)
ParseNamespaceItem * refnameNamespaceItem(ParseState *pstate, const char *schemaname, const char *refname, int location, int *sublevels_up)
Node * colNameToVar(ParseState *pstate, const char *colname, bool localonly, int location)
void expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up, int location, bool include_dropped, List **colnames, List **colvars)
List * transformExpressionList(ParseState *pstate, List *exprlist, ParseExprKind exprKind, bool allowDefault)
Definition: parse_target.c:221
char * FigureColname(Node *node)
Oid LookupCollation(ParseState *pstate, List *collnames, int location)
Definition: parse_type.c:515
void typenameTypeIdAndMod(ParseState *pstate, const TypeName *typeName, Oid *typeid_p, int32 *typmod_p)
Definition: parse_type.c:310
#define ISCOMPLEX(typeid)
Definition: parse_type.h:59
@ AEXPR_BETWEEN
Definition: parsenodes.h:313
@ AEXPR_NULLIF
Definition: parsenodes.h:308
@ AEXPR_NOT_DISTINCT
Definition: parsenodes.h:307
@ AEXPR_BETWEEN_SYM
Definition: parsenodes.h:315
@ AEXPR_NOT_BETWEEN_SYM
Definition: parsenodes.h:316
@ AEXPR_ILIKE
Definition: parsenodes.h:311
@ AEXPR_IN
Definition: parsenodes.h:309
@ AEXPR_NOT_BETWEEN
Definition: parsenodes.h:314
@ AEXPR_DISTINCT
Definition: parsenodes.h:306
@ AEXPR_SIMILAR
Definition: parsenodes.h:312
@ AEXPR_LIKE
Definition: parsenodes.h:310
@ AEXPR_OP
Definition: parsenodes.h:303
@ AEXPR_OP_ANY
Definition: parsenodes.h:304
@ AEXPR_OP_ALL
Definition: parsenodes.h:305
Query * parse_sub_analyze(Node *parseTree, ParseState *parentParseState, CommonTableExpr *parentCTE, bool locked_from_parent, bool resolve_unknowns)
Definition: analyze.c:224
Query * transformStmt(ParseState *pstate, Node *parseTree)
Definition: analyze.c:314
NameData attname
Definition: pg_attribute.h:41
void * arg
static char format
NameData relname
Definition: pg_class.h:38
#define NAMEDATALEN
int32 encoding
Definition: pg_database.h:41
#define lfirst(lc)
Definition: pg_list.h:172
#define llast(l)
Definition: pg_list.h:198
#define lfirst_node(type, lc)
Definition: pg_list.h:176
static int list_length(const List *l)
Definition: pg_list.h:152
#define NIL
Definition: pg_list.h:68
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:518
#define lthird(l)
Definition: pg_list.h:188
#define list_make1(x1)
Definition: pg_list.h:212
#define linitial(l)
Definition: pg_list.h:178
#define lsecond(l)
Definition: pg_list.h:183
static void * list_nth(const List *list, int n)
Definition: pg_list.h:299
#define lfourth(l)
Definition: pg_list.h:193
#define list_make2(x1, x2)
Definition: pg_list.h:214
#define snprintf
Definition: port.h:238
void check_stack_depth(void)
Definition: postgres.c:3523
static Datum NameGetDatum(const NameData *X)
Definition: postgres.h:373
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
char * c
e
Definition: preproc-init.c:82
@ IS_NOT_TRUE
Definition: primnodes.h:1718
@ IS_NOT_FALSE
Definition: primnodes.h:1718
@ IS_NOT_UNKNOWN
Definition: primnodes.h:1718
@ IS_TRUE
Definition: primnodes.h:1718
@ IS_UNKNOWN
Definition: primnodes.h:1718
@ IS_FALSE
Definition: primnodes.h:1718
@ ARRAY_SUBLINK
Definition: primnodes.h:938
@ MULTIEXPR_SUBLINK
Definition: primnodes.h:937
@ EXPR_SUBLINK
Definition: primnodes.h:936
@ ROWCOMPARE_SUBLINK
Definition: primnodes.h:935
@ EXISTS_SUBLINK
Definition: primnodes.h:932
JsonFormatType
Definition: primnodes.h:1572
@ JS_FORMAT_JSONB
Definition: primnodes.h:1575
@ JS_FORMAT_DEFAULT
Definition: primnodes.h:1573
@ JS_FORMAT_JSON
Definition: primnodes.h:1574
@ IS_GREATEST
Definition: primnodes.h:1437
@ AND_EXPR
Definition: primnodes.h:866
@ OR_EXPR
Definition: primnodes.h:866
@ NOT_EXPR
Definition: primnodes.h:866
JsonEncoding
Definition: primnodes.h:1560
@ JS_ENC_DEFAULT
Definition: primnodes.h:1561
@ JS_ENC_UTF32
Definition: primnodes.h:1564
@ JS_ENC_UTF8
Definition: primnodes.h:1562
@ JS_ENC_UTF16
Definition: primnodes.h:1563
@ SVFOP_CURRENT_CATALOG
Definition: primnodes.h:1484
@ SVFOP_LOCALTIME_N
Definition: primnodes.h:1477
@ SVFOP_CURRENT_TIMESTAMP
Definition: primnodes.h:1474
@ SVFOP_LOCALTIME
Definition: primnodes.h:1476
@ SVFOP_CURRENT_TIMESTAMP_N
Definition: primnodes.h:1475
@ SVFOP_CURRENT_ROLE
Definition: primnodes.h:1480
@ SVFOP_USER
Definition: primnodes.h:1482
@ SVFOP_CURRENT_SCHEMA
Definition: primnodes.h:1485
@ SVFOP_LOCALTIMESTAMP_N
Definition: primnodes.h:1479
@ SVFOP_CURRENT_DATE
Definition: primnodes.h:1471
@ SVFOP_CURRENT_TIME_N
Definition: primnodes.h:1473
@ SVFOP_CURRENT_TIME
Definition: primnodes.h:1472
@ SVFOP_LOCALTIMESTAMP
Definition: primnodes.h:1478
@ SVFOP_CURRENT_USER
Definition: primnodes.h:1481
@ SVFOP_SESSION_USER
Definition: primnodes.h:1483
@ PARAM_MULTIEXPR
Definition: primnodes.h:356
@ PARAM_EXTERN
Definition: primnodes.h:353
@ PARAM_SUBLINK
Definition: primnodes.h:355
@ IS_DOCUMENT
Definition: primnodes.h:1522
@ IS_XMLFOREST
Definition: primnodes.h:1517
@ IS_XMLCONCAT
Definition: primnodes.h:1515
@ IS_XMLPI
Definition: primnodes.h:1519
@ IS_XMLPARSE
Definition: primnodes.h:1518
@ IS_XMLSERIALIZE
Definition: primnodes.h:1521
@ IS_XMLROOT
Definition: primnodes.h:1520
@ IS_XMLELEMENT
Definition: primnodes.h:1516
RowCompareType
Definition: primnodes.h:1388
@ ROWCOMPARE_NE
Definition: primnodes.h:1395
@ ROWCOMPARE_EQ
Definition: primnodes.h:1392
@ COERCE_IMPLICIT_CAST
Definition: primnodes.h:671
@ COERCE_EXPLICIT_CAST
Definition: primnodes.h:670
@ COERCE_EXPLICIT_CALL
Definition: primnodes.h:669
@ IS_NULL
Definition: primnodes.h:1694
@ IS_NOT_NULL
Definition: primnodes.h:1694
@ COERCION_EXPLICIT
Definition: primnodes.h:652
@ COERCION_IMPLICIT
Definition: primnodes.h:649
JsonConstructorType
Definition: primnodes.h:1620
@ JSCTOR_JSON_SERIALIZE
Definition: primnodes.h:1627
@ JSCTOR_JSON_ARRAYAGG
Definition: primnodes.h:1624
@ JSCTOR_JSON_PARSE
Definition: primnodes.h:1625
@ JSCTOR_JSON_OBJECT
Definition: primnodes.h:1621
@ JSCTOR_JSON_SCALAR
Definition: primnodes.h:1626
@ JSCTOR_JSON_ARRAY
Definition: primnodes.h:1622
@ JSCTOR_JSON_OBJECTAGG
Definition: primnodes.h:1623
static struct cvec * range(struct vars *v, chr a, chr b, int cases)
Definition: regc_locale.c:412
static int cmp(const chr *x, const chr *y, size_t len)
Definition: regc_locale.c:743
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:376
bool isnull
Definition: parsenodes.h:353
int location
Definition: parsenodes.h:354
int location
Definition: parsenodes.h:328
A_Expr_Kind kind
Definition: parsenodes.h:324
Oid aggfnoid
Definition: primnodes.h:430
Expr * aggfilter
Definition: primnodes.h:463
int location
Definition: primnodes.h:493
char * aliasname
Definition: primnodes.h:50
List * colnames
Definition: primnodes.h:51
int location
Definition: primnodes.h:1319
List * elements
Definition: primnodes.h:1315
Expr * arg
Definition: primnodes.h:1248
int location
Definition: primnodes.h:1251
Expr * defresult
Definition: primnodes.h:1250
List * args
Definition: primnodes.h:1249
Expr * result
Definition: primnodes.h:1261
Expr * expr
Definition: primnodes.h:1260
int location
Definition: primnodes.h:1262
List * args
Definition: primnodes.h:1427
Expr * arg
Definition: primnodes.h:1214
int location
Definition: parsenodes.h:285
List * fields
Definition: parsenodes.h:284
char * cursor_name
Definition: primnodes.h:1830
int location
Definition: primnodes.h:705
struct WindowDef * over
Definition: parsenodes.h:1807
JsonOutput * output
Definition: parsenodes.h:1804
bool absent_on_null
Definition: parsenodes.h:1833
JsonValueExpr * arg
Definition: parsenodes.h:1832
JsonAggConstructor * constructor
Definition: parsenodes.h:1831
JsonOutput * output
Definition: parsenodes.h:1777
JsonReturning * returning
Definition: primnodes.h:1641
JsonConstructorType type
Definition: primnodes.h:1637
int location
Definition: primnodes.h:1588
JsonEncoding encoding
Definition: primnodes.h:1587
JsonFormatType format_type
Definition: primnodes.h:1586
JsonFormat * format
Definition: primnodes.h:1667
JsonValueType item_type
Definition: primnodes.h:1668
JsonValueExpr * value
Definition: parsenodes.h:1715
JsonAggConstructor * constructor
Definition: parsenodes.h:1818
JsonKeyValue * arg
Definition: parsenodes.h:1819
bool absent_on_null
Definition: parsenodes.h:1820
JsonOutput * output
Definition: parsenodes.h:1763
JsonValueExpr * expr
Definition: parsenodes.h:1725
JsonOutput * output
Definition: parsenodes.h:1726
JsonFormat * format
Definition: primnodes.h:1598
JsonOutput * output
Definition: parsenodes.h:1739
JsonOutput * output
Definition: parsenodes.h:1751
JsonValueExpr * expr
Definition: parsenodes.h:1750
Expr * formatted_expr
Definition: primnodes.h:1615
JsonFormat * format
Definition: primnodes.h:1616
Expr * raw_expr
Definition: primnodes.h:1614
Definition: pg_list.h:54
List * args
Definition: primnodes.h:1453
int location
Definition: primnodes.h:1455
MinMaxOp op
Definition: primnodes.h:1451
Expr * arg
Definition: primnodes.h:726
Definition: nodes.h:129
NullTestType nulltesttype
Definition: primnodes.h:1701
int location
Definition: primnodes.h:1704
Expr * arg
Definition: primnodes.h:1700
List * args
Definition: primnodes.h:771
int location
Definition: parsenodes.h:295
int number
Definition: parsenodes.h:294
int paramid
Definition: primnodes.h:363
Oid paramtype
Definition: primnodes.h:364
ParamKind paramkind
Definition: primnodes.h:362
int location
Definition: primnodes.h:370
RangeTblEntry * p_rte
Definition: parse_node.h:286
ParseNamespaceItem * p_target_nsitem
Definition: parse_node.h:207
ParseExprKind p_expr_kind
Definition: parse_node.h:210
List * p_multiassign_exprs
Definition: parse_node.h:212
ParseParamRefHook p_paramref_hook
Definition: parse_node.h:236
PreParseColumnRefHook p_pre_columnref_hook
Definition: parse_node.h:234
bool p_hasSubLinks
Definition: parse_node.h:225
Node * p_last_srf
Definition: parse_node.h:228
PostParseColumnRefHook p_post_columnref_hook
Definition: parse_node.h:235
CmdType commandType
Definition: parsenodes.h:120
List * targetList
Definition: parsenodes.h:181
Alias * eref
Definition: parsenodes.h:1192
int location
Definition: parsenodes.h:510
Node * val
Definition: parsenodes.h:509
List * indirection
Definition: parsenodes.h:508
char * name
Definition: parsenodes.h:507
RowCompareType rctype
Definition: primnodes.h:1403
int location
Definition: primnodes.h:1370
List * args
Definition: primnodes.h:1346
SQLValueFunctionOp op
Definition: primnodes.h:1491
Definition: value.h:64
Expr * expr
Definition: primnodes.h:1922
AttrNumber resno
Definition: primnodes.h:1924
TypeName * typeName
Definition: parsenodes.h:364
int location
Definition: parsenodes.h:365
Node * arg
Definition: parsenodes.h:363
int location
Definition: parsenodes.h:265
Definition: primnodes.h:234
int location
Definition: primnodes.h:279
List * args
Definition: primnodes.h:561
Expr * aggfilter
Definition: primnodes.h:563
int location
Definition: primnodes.h:571
Oid winfnoid
Definition: primnodes.h:553
List * args
Definition: primnodes.h:1543
bool indent
Definition: primnodes.h:1547
int location
Definition: primnodes.h:1552
List * named_args
Definition: primnodes.h:1539
XmlExprOp op
Definition: primnodes.h:1535
TypeName * typeName
Definition: parsenodes.h:834
Node * expr
Definition: parsenodes.h:833
XmlOptionType xmloption
Definition: parsenodes.h:832
Definition: ltree.h:43
Definition: c.h:730
static void * fn(void *arg)
Definition: thread-alloc.c:119
int count_nonjunk_tlist_entries(List *tlist)
Definition: tlist.c:186
String * makeString(char *str)
Definition: value.c:63
#define strVal(v)
Definition: value.h:82
bool contain_vars_of_level(Node *node, int levelsup)
Definition: var.c:441
const char * type
#define select(n, r, w, e, timeout)
Definition: win32_port.h:495
char * map_sql_identifier_to_xml_name(const char *ident, bool fully_escaped, bool escape_period)
Definition: xml.c:2318