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