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