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