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