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