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