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