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