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