/src/postgres/src/backend/parser/parse_clause.c
Line | Count | Source |
1 | | /*------------------------------------------------------------------------- |
2 | | * |
3 | | * parse_clause.c |
4 | | * handle clauses 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_clause.c |
12 | | * |
13 | | *------------------------------------------------------------------------- |
14 | | */ |
15 | | |
16 | | #include "postgres.h" |
17 | | |
18 | | #include "access/htup_details.h" |
19 | | #include "access/nbtree.h" |
20 | | #include "access/table.h" |
21 | | #include "access/tsmapi.h" |
22 | | #include "catalog/catalog.h" |
23 | | #include "catalog/pg_am.h" |
24 | | #include "catalog/pg_amproc.h" |
25 | | #include "catalog/pg_constraint.h" |
26 | | #include "catalog/pg_type.h" |
27 | | #include "commands/defrem.h" |
28 | | #include "miscadmin.h" |
29 | | #include "nodes/makefuncs.h" |
30 | | #include "nodes/nodeFuncs.h" |
31 | | #include "optimizer/optimizer.h" |
32 | | #include "parser/analyze.h" |
33 | | #include "parser/parse_clause.h" |
34 | | #include "parser/parse_coerce.h" |
35 | | #include "parser/parse_collate.h" |
36 | | #include "parser/parse_expr.h" |
37 | | #include "parser/parse_func.h" |
38 | | #include "parser/parse_oper.h" |
39 | | #include "parser/parse_relation.h" |
40 | | #include "parser/parse_target.h" |
41 | | #include "parser/parse_type.h" |
42 | | #include "parser/parser.h" |
43 | | #include "rewrite/rewriteManip.h" |
44 | | #include "utils/builtins.h" |
45 | | #include "utils/catcache.h" |
46 | | #include "utils/lsyscache.h" |
47 | | #include "utils/rel.h" |
48 | | #include "utils/syscache.h" |
49 | | |
50 | | |
51 | | static int extractRemainingColumns(ParseState *pstate, |
52 | | ParseNamespaceColumn *src_nscolumns, |
53 | | List *src_colnames, |
54 | | List **src_colnos, |
55 | | List **res_colnames, List **res_colvars, |
56 | | ParseNamespaceColumn *res_nscolumns); |
57 | | static Node *transformJoinUsingClause(ParseState *pstate, |
58 | | List *leftVars, List *rightVars); |
59 | | static Node *transformJoinOnClause(ParseState *pstate, JoinExpr *j, |
60 | | List *namespace); |
61 | | static ParseNamespaceItem *transformTableEntry(ParseState *pstate, RangeVar *r); |
62 | | static ParseNamespaceItem *transformRangeSubselect(ParseState *pstate, |
63 | | RangeSubselect *r); |
64 | | static ParseNamespaceItem *transformRangeFunction(ParseState *pstate, |
65 | | RangeFunction *r); |
66 | | static ParseNamespaceItem *transformRangeTableFunc(ParseState *pstate, |
67 | | RangeTableFunc *rtf); |
68 | | static TableSampleClause *transformRangeTableSample(ParseState *pstate, |
69 | | RangeTableSample *rts); |
70 | | static ParseNamespaceItem *getNSItemForSpecialRelationTypes(ParseState *pstate, |
71 | | RangeVar *rv); |
72 | | static Node *transformFromClauseItem(ParseState *pstate, Node *n, |
73 | | ParseNamespaceItem **top_nsitem, |
74 | | List **namespace); |
75 | | static Var *buildVarFromNSColumn(ParseState *pstate, |
76 | | ParseNamespaceColumn *nscol); |
77 | | static Node *buildMergedJoinVar(ParseState *pstate, JoinType jointype, |
78 | | Var *l_colvar, Var *r_colvar); |
79 | | static void markRelsAsNulledBy(ParseState *pstate, Node *n, int jindex); |
80 | | static void setNamespaceColumnVisibility(List *namespace, bool cols_visible); |
81 | | static void setNamespaceLateralState(List *namespace, |
82 | | bool lateral_only, bool lateral_ok); |
83 | | static void checkExprIsVarFree(ParseState *pstate, Node *n, |
84 | | const char *constructName); |
85 | | static TargetEntry *findTargetlistEntrySQL92(ParseState *pstate, Node *node, |
86 | | List **tlist, ParseExprKind exprKind); |
87 | | static TargetEntry *findTargetlistEntrySQL99(ParseState *pstate, Node *node, |
88 | | List **tlist, ParseExprKind exprKind); |
89 | | static int get_matching_location(int sortgroupref, |
90 | | List *sortgrouprefs, List *exprs); |
91 | | static List *resolve_unique_index_expr(ParseState *pstate, InferClause *infer, |
92 | | Relation heapRel); |
93 | | static List *addTargetToGroupList(ParseState *pstate, TargetEntry *tle, |
94 | | List *grouplist, List *targetlist, int location); |
95 | | static WindowClause *findWindowClause(List *wclist, const char *name); |
96 | | static Node *transformFrameOffset(ParseState *pstate, int frameOptions, |
97 | | Oid rangeopfamily, Oid rangeopcintype, Oid *inRangeFunc, |
98 | | Node *clause); |
99 | | |
100 | | |
101 | | /* |
102 | | * transformFromClause - |
103 | | * Process the FROM clause and add items to the query's range table, |
104 | | * joinlist, and namespace. |
105 | | * |
106 | | * Note: we assume that the pstate's p_rtable, p_joinlist, and p_namespace |
107 | | * lists were initialized to NIL when the pstate was created. |
108 | | * We will add onto any entries already present --- this is needed for rule |
109 | | * processing, as well as for UPDATE and DELETE. |
110 | | */ |
111 | | void |
112 | | transformFromClause(ParseState *pstate, List *frmList) |
113 | 0 | { |
114 | 0 | ListCell *fl; |
115 | | |
116 | | /* |
117 | | * The grammar will have produced a list of RangeVars, RangeSubselects, |
118 | | * RangeFunctions, and/or JoinExprs. Transform each one (possibly adding |
119 | | * entries to the rtable), check for duplicate refnames, and then add it |
120 | | * to the joinlist and namespace. |
121 | | * |
122 | | * Note we must process the items left-to-right for proper handling of |
123 | | * LATERAL references. |
124 | | */ |
125 | 0 | foreach(fl, frmList) |
126 | 0 | { |
127 | 0 | Node *n = lfirst(fl); |
128 | 0 | ParseNamespaceItem *nsitem; |
129 | 0 | List *namespace; |
130 | |
|
131 | 0 | n = transformFromClauseItem(pstate, n, |
132 | 0 | &nsitem, |
133 | 0 | &namespace); |
134 | |
|
135 | 0 | checkNameSpaceConflicts(pstate, pstate->p_namespace, namespace); |
136 | | |
137 | | /* Mark the new namespace items as visible only to LATERAL */ |
138 | 0 | setNamespaceLateralState(namespace, true, true); |
139 | |
|
140 | 0 | pstate->p_joinlist = lappend(pstate->p_joinlist, n); |
141 | 0 | pstate->p_namespace = list_concat(pstate->p_namespace, namespace); |
142 | 0 | } |
143 | | |
144 | | /* |
145 | | * We're done parsing the FROM list, so make all namespace items |
146 | | * unconditionally visible. Note that this will also reset lateral_only |
147 | | * for any namespace items that were already present when we were called; |
148 | | * but those should have been that way already. |
149 | | */ |
150 | 0 | setNamespaceLateralState(pstate->p_namespace, false, true); |
151 | 0 | } |
152 | | |
153 | | /* |
154 | | * setTargetTable |
155 | | * Add the target relation of INSERT/UPDATE/DELETE/MERGE to the range table, |
156 | | * and make the special links to it in the ParseState. |
157 | | * |
158 | | * We also open the target relation and acquire a write lock on it. |
159 | | * This must be done before processing the FROM list, in case the target |
160 | | * is also mentioned as a source relation --- we want to be sure to grab |
161 | | * the write lock before any read lock. |
162 | | * |
163 | | * If alsoSource is true, add the target to the query's joinlist and |
164 | | * namespace. For INSERT, we don't want the target to be joined to; |
165 | | * it's a destination of tuples, not a source. MERGE is actually |
166 | | * both, but we'll add it separately to joinlist and namespace, so |
167 | | * doing nothing (like INSERT) is correct here. For UPDATE/DELETE, |
168 | | * we do need to scan or join the target. (NOTE: we do not bother |
169 | | * to check for namespace conflict; we assume that the namespace was |
170 | | * initially empty in these cases.) |
171 | | * |
172 | | * Finally, we mark the relation as requiring the permissions specified |
173 | | * by requiredPerms. |
174 | | * |
175 | | * Returns the rangetable index of the target relation. |
176 | | */ |
177 | | int |
178 | | setTargetTable(ParseState *pstate, RangeVar *relation, |
179 | | bool inh, bool alsoSource, AclMode requiredPerms) |
180 | 0 | { |
181 | 0 | ParseNamespaceItem *nsitem; |
182 | | |
183 | | /* |
184 | | * ENRs hide tables of the same name, so we need to check for them first. |
185 | | * In contrast, CTEs don't hide tables (for this purpose). |
186 | | */ |
187 | 0 | if (relation->schemaname == NULL && |
188 | 0 | scanNameSpaceForENR(pstate, relation->relname)) |
189 | 0 | ereport(ERROR, |
190 | 0 | (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
191 | 0 | errmsg("relation \"%s\" cannot be the target of a modifying statement", |
192 | 0 | relation->relname))); |
193 | | |
194 | | /* Close old target; this could only happen for multi-action rules */ |
195 | 0 | if (pstate->p_target_relation != NULL) |
196 | 0 | table_close(pstate->p_target_relation, NoLock); |
197 | | |
198 | | /* |
199 | | * Open target rel and grab suitable lock (which we will hold till end of |
200 | | * transaction). |
201 | | * |
202 | | * free_parsestate() will eventually do the corresponding table_close(), |
203 | | * but *not* release the lock. |
204 | | */ |
205 | 0 | pstate->p_target_relation = parserOpenTable(pstate, relation, |
206 | 0 | RowExclusiveLock); |
207 | | |
208 | | /* |
209 | | * Now build an RTE and a ParseNamespaceItem. |
210 | | */ |
211 | 0 | nsitem = addRangeTableEntryForRelation(pstate, pstate->p_target_relation, |
212 | 0 | RowExclusiveLock, |
213 | 0 | relation->alias, inh, false); |
214 | | |
215 | | /* remember the RTE/nsitem as being the query target */ |
216 | 0 | pstate->p_target_nsitem = nsitem; |
217 | | |
218 | | /* |
219 | | * Override addRangeTableEntry's default ACL_SELECT permissions check, and |
220 | | * instead mark target table as requiring exactly the specified |
221 | | * permissions. |
222 | | * |
223 | | * If we find an explicit reference to the rel later during parse |
224 | | * analysis, we will add the ACL_SELECT bit back again; see |
225 | | * markVarForSelectPriv and its callers. |
226 | | */ |
227 | 0 | nsitem->p_perminfo->requiredPerms = requiredPerms; |
228 | | |
229 | | /* |
230 | | * If UPDATE/DELETE, add table to joinlist and namespace. |
231 | | */ |
232 | 0 | if (alsoSource) |
233 | 0 | addNSItemToQuery(pstate, nsitem, true, true, true); |
234 | |
|
235 | 0 | return nsitem->p_rtindex; |
236 | 0 | } |
237 | | |
238 | | /* |
239 | | * Extract all not-in-common columns from column lists of a source table |
240 | | * |
241 | | * src_nscolumns and src_colnames describe the source table. |
242 | | * |
243 | | * *src_colnos initially contains the column numbers of the already-merged |
244 | | * columns. We add to it the column number of each additional column. |
245 | | * Also append to *res_colnames the name of each additional column, |
246 | | * append to *res_colvars a Var for each additional column, and copy the |
247 | | * columns' nscolumns data into res_nscolumns[] (which is caller-allocated |
248 | | * space that had better be big enough). |
249 | | * |
250 | | * Returns the number of columns added. |
251 | | */ |
252 | | static int |
253 | | extractRemainingColumns(ParseState *pstate, |
254 | | ParseNamespaceColumn *src_nscolumns, |
255 | | List *src_colnames, |
256 | | List **src_colnos, |
257 | | List **res_colnames, List **res_colvars, |
258 | | ParseNamespaceColumn *res_nscolumns) |
259 | 0 | { |
260 | 0 | int colcount = 0; |
261 | 0 | Bitmapset *prevcols; |
262 | 0 | int attnum; |
263 | 0 | ListCell *lc; |
264 | | |
265 | | /* |
266 | | * While we could just test "list_member_int(*src_colnos, attnum)" to |
267 | | * detect already-merged columns in the loop below, that would be O(N^2) |
268 | | * for a wide input table. Instead build a bitmapset of just the merged |
269 | | * USING columns, which we won't add to within the main loop. |
270 | | */ |
271 | 0 | prevcols = NULL; |
272 | 0 | foreach(lc, *src_colnos) |
273 | 0 | { |
274 | 0 | prevcols = bms_add_member(prevcols, lfirst_int(lc)); |
275 | 0 | } |
276 | |
|
277 | 0 | attnum = 0; |
278 | 0 | foreach(lc, src_colnames) |
279 | 0 | { |
280 | 0 | char *colname = strVal(lfirst(lc)); |
281 | |
|
282 | 0 | attnum++; |
283 | | /* Non-dropped and not already merged? */ |
284 | 0 | if (colname[0] != '\0' && !bms_is_member(attnum, prevcols)) |
285 | 0 | { |
286 | | /* Yes, so emit it as next output column */ |
287 | 0 | *src_colnos = lappend_int(*src_colnos, attnum); |
288 | 0 | *res_colnames = lappend(*res_colnames, lfirst(lc)); |
289 | 0 | *res_colvars = lappend(*res_colvars, |
290 | 0 | buildVarFromNSColumn(pstate, |
291 | 0 | src_nscolumns + attnum - 1)); |
292 | | /* Copy the input relation's nscolumn data for this column */ |
293 | 0 | res_nscolumns[colcount] = src_nscolumns[attnum - 1]; |
294 | 0 | colcount++; |
295 | 0 | } |
296 | 0 | } |
297 | 0 | return colcount; |
298 | 0 | } |
299 | | |
300 | | /* |
301 | | * transformJoinUsingClause() |
302 | | * Build a complete ON clause from a partially-transformed USING list. |
303 | | * We are given lists of nodes representing left and right match columns. |
304 | | * Result is a transformed qualification expression. |
305 | | */ |
306 | | static Node * |
307 | | transformJoinUsingClause(ParseState *pstate, |
308 | | List *leftVars, List *rightVars) |
309 | 0 | { |
310 | 0 | Node *result; |
311 | 0 | List *andargs = NIL; |
312 | 0 | ListCell *lvars, |
313 | 0 | *rvars; |
314 | | |
315 | | /* |
316 | | * We cheat a little bit here by building an untransformed operator tree |
317 | | * whose leaves are the already-transformed Vars. This requires collusion |
318 | | * from transformExpr(), which normally could be expected to complain |
319 | | * about already-transformed subnodes. However, this does mean that we |
320 | | * have to mark the columns as requiring SELECT privilege for ourselves; |
321 | | * transformExpr() won't do it. |
322 | | */ |
323 | 0 | forboth(lvars, leftVars, rvars, rightVars) |
324 | 0 | { |
325 | 0 | Var *lvar = (Var *) lfirst(lvars); |
326 | 0 | Var *rvar = (Var *) lfirst(rvars); |
327 | 0 | A_Expr *e; |
328 | | |
329 | | /* Require read access to the join variables */ |
330 | 0 | markVarForSelectPriv(pstate, lvar); |
331 | 0 | markVarForSelectPriv(pstate, rvar); |
332 | | |
333 | | /* Now create the lvar = rvar join condition */ |
334 | 0 | e = makeSimpleA_Expr(AEXPR_OP, "=", |
335 | 0 | (Node *) copyObject(lvar), (Node *) copyObject(rvar), |
336 | 0 | -1); |
337 | | |
338 | | /* Prepare to combine into an AND clause, if multiple join columns */ |
339 | 0 | andargs = lappend(andargs, e); |
340 | 0 | } |
341 | | |
342 | | /* Only need an AND if there's more than one join column */ |
343 | 0 | if (list_length(andargs) == 1) |
344 | 0 | result = (Node *) linitial(andargs); |
345 | 0 | else |
346 | 0 | result = (Node *) makeBoolExpr(AND_EXPR, andargs, -1); |
347 | | |
348 | | /* |
349 | | * Since the references are already Vars, and are certainly from the input |
350 | | * relations, we don't have to go through the same pushups that |
351 | | * transformJoinOnClause() does. Just invoke transformExpr() to fix up |
352 | | * the operators, and we're done. |
353 | | */ |
354 | 0 | result = transformExpr(pstate, result, EXPR_KIND_JOIN_USING); |
355 | |
|
356 | 0 | result = coerce_to_boolean(pstate, result, "JOIN/USING"); |
357 | |
|
358 | 0 | return result; |
359 | 0 | } |
360 | | |
361 | | /* |
362 | | * transformJoinOnClause() |
363 | | * Transform the qual conditions for JOIN/ON. |
364 | | * Result is a transformed qualification expression. |
365 | | */ |
366 | | static Node * |
367 | | transformJoinOnClause(ParseState *pstate, JoinExpr *j, List *namespace) |
368 | 0 | { |
369 | 0 | Node *result; |
370 | 0 | List *save_namespace; |
371 | | |
372 | | /* |
373 | | * The namespace that the join expression should see is just the two |
374 | | * subtrees of the JOIN plus any outer references from upper pstate |
375 | | * levels. Temporarily set this pstate's namespace accordingly. (We need |
376 | | * not check for refname conflicts, because transformFromClauseItem() |
377 | | * already did.) All namespace items are marked visible regardless of |
378 | | * LATERAL state. |
379 | | */ |
380 | 0 | setNamespaceLateralState(namespace, false, true); |
381 | |
|
382 | 0 | save_namespace = pstate->p_namespace; |
383 | 0 | pstate->p_namespace = namespace; |
384 | |
|
385 | 0 | result = transformWhereClause(pstate, j->quals, |
386 | 0 | EXPR_KIND_JOIN_ON, "JOIN/ON"); |
387 | |
|
388 | 0 | pstate->p_namespace = save_namespace; |
389 | |
|
390 | 0 | return result; |
391 | 0 | } |
392 | | |
393 | | /* |
394 | | * transformTableEntry --- transform a RangeVar (simple relation reference) |
395 | | */ |
396 | | static ParseNamespaceItem * |
397 | | transformTableEntry(ParseState *pstate, RangeVar *r) |
398 | 0 | { |
399 | | /* addRangeTableEntry does all the work */ |
400 | 0 | return addRangeTableEntry(pstate, r, r->alias, r->inh, true); |
401 | 0 | } |
402 | | |
403 | | /* |
404 | | * transformRangeSubselect --- transform a sub-SELECT appearing in FROM |
405 | | */ |
406 | | static ParseNamespaceItem * |
407 | | transformRangeSubselect(ParseState *pstate, RangeSubselect *r) |
408 | 0 | { |
409 | 0 | Query *query; |
410 | | |
411 | | /* |
412 | | * Set p_expr_kind to show this parse level is recursing to a subselect. |
413 | | * We can't be nested within any expression, so don't need save-restore |
414 | | * logic here. |
415 | | */ |
416 | 0 | Assert(pstate->p_expr_kind == EXPR_KIND_NONE); |
417 | 0 | pstate->p_expr_kind = EXPR_KIND_FROM_SUBSELECT; |
418 | | |
419 | | /* |
420 | | * If the subselect is LATERAL, make lateral_only names of this level |
421 | | * visible to it. (LATERAL can't nest within a single pstate level, so we |
422 | | * don't need save/restore logic here.) |
423 | | */ |
424 | 0 | Assert(!pstate->p_lateral_active); |
425 | 0 | pstate->p_lateral_active = r->lateral; |
426 | | |
427 | | /* |
428 | | * Analyze and transform the subquery. Note that if the subquery doesn't |
429 | | * have an alias, it can't be explicitly selected for locking, but locking |
430 | | * might still be required (if there is an all-tables locking clause). |
431 | | */ |
432 | 0 | query = parse_sub_analyze(r->subquery, pstate, NULL, |
433 | 0 | isLockedRefname(pstate, |
434 | 0 | r->alias == NULL ? NULL : |
435 | 0 | r->alias->aliasname), |
436 | 0 | true); |
437 | | |
438 | | /* Restore state */ |
439 | 0 | pstate->p_lateral_active = false; |
440 | 0 | pstate->p_expr_kind = EXPR_KIND_NONE; |
441 | | |
442 | | /* |
443 | | * Check that we got a SELECT. Anything else should be impossible given |
444 | | * restrictions of the grammar, but check anyway. |
445 | | */ |
446 | 0 | if (!IsA(query, Query) || |
447 | 0 | query->commandType != CMD_SELECT) |
448 | 0 | elog(ERROR, "unexpected non-SELECT command in subquery in FROM"); |
449 | | |
450 | | /* |
451 | | * OK, build an RTE and nsitem for the subquery. |
452 | | */ |
453 | 0 | return addRangeTableEntryForSubquery(pstate, |
454 | 0 | query, |
455 | 0 | r->alias, |
456 | 0 | r->lateral, |
457 | 0 | true); |
458 | 0 | } |
459 | | |
460 | | |
461 | | /* |
462 | | * transformRangeFunction --- transform a function call appearing in FROM |
463 | | */ |
464 | | static ParseNamespaceItem * |
465 | | transformRangeFunction(ParseState *pstate, RangeFunction *r) |
466 | 0 | { |
467 | 0 | List *funcexprs = NIL; |
468 | 0 | List *funcnames = NIL; |
469 | 0 | List *coldeflists = NIL; |
470 | 0 | bool is_lateral; |
471 | 0 | ListCell *lc; |
472 | | |
473 | | /* |
474 | | * We make lateral_only names of this level visible, whether or not the |
475 | | * RangeFunction is explicitly marked LATERAL. This is needed for SQL |
476 | | * spec compliance in the case of UNNEST(), and seems useful on |
477 | | * convenience grounds for all functions in FROM. |
478 | | * |
479 | | * (LATERAL can't nest within a single pstate level, so we don't need |
480 | | * save/restore logic here.) |
481 | | */ |
482 | 0 | Assert(!pstate->p_lateral_active); |
483 | 0 | pstate->p_lateral_active = true; |
484 | | |
485 | | /* |
486 | | * Transform the raw expressions. |
487 | | * |
488 | | * While transforming, also save function names for possible use as alias |
489 | | * and column names. We use the same transformation rules as for a SELECT |
490 | | * output expression. For a FuncCall node, the result will be the |
491 | | * function name, but it is possible for the grammar to hand back other |
492 | | * node types. |
493 | | * |
494 | | * We have to get this info now, because FigureColname only works on raw |
495 | | * parsetrees. Actually deciding what to do with the names is left up to |
496 | | * addRangeTableEntryForFunction. |
497 | | * |
498 | | * Likewise, collect column definition lists if there were any. But |
499 | | * complain if we find one here and the RangeFunction has one too. |
500 | | */ |
501 | 0 | foreach(lc, r->functions) |
502 | 0 | { |
503 | 0 | List *pair = (List *) lfirst(lc); |
504 | 0 | Node *fexpr; |
505 | 0 | List *coldeflist; |
506 | 0 | Node *newfexpr; |
507 | 0 | Node *last_srf; |
508 | | |
509 | | /* Disassemble the function-call/column-def-list pairs */ |
510 | 0 | Assert(list_length(pair) == 2); |
511 | 0 | fexpr = (Node *) linitial(pair); |
512 | 0 | coldeflist = (List *) lsecond(pair); |
513 | | |
514 | | /* |
515 | | * If we find a function call unnest() with more than one argument and |
516 | | * no special decoration, transform it into separate unnest() calls on |
517 | | * each argument. This is a kluge, for sure, but it's less nasty than |
518 | | * other ways of implementing the SQL-standard UNNEST() syntax. |
519 | | * |
520 | | * If there is any decoration (including a coldeflist), we don't |
521 | | * transform, which probably means a no-such-function error later. We |
522 | | * could alternatively throw an error right now, but that doesn't seem |
523 | | * tremendously helpful. If someone is using any such decoration, |
524 | | * then they're not using the SQL-standard syntax, and they're more |
525 | | * likely expecting an un-tweaked function call. |
526 | | * |
527 | | * Note: the transformation changes a non-schema-qualified unnest() |
528 | | * function name into schema-qualified pg_catalog.unnest(). This |
529 | | * choice is also a bit debatable, but it seems reasonable to force |
530 | | * use of built-in unnest() when we make this transformation. |
531 | | */ |
532 | 0 | if (IsA(fexpr, FuncCall)) |
533 | 0 | { |
534 | 0 | FuncCall *fc = (FuncCall *) fexpr; |
535 | |
|
536 | 0 | if (list_length(fc->funcname) == 1 && |
537 | 0 | strcmp(strVal(linitial(fc->funcname)), "unnest") == 0 && |
538 | 0 | list_length(fc->args) > 1 && |
539 | 0 | fc->agg_order == NIL && |
540 | 0 | fc->agg_filter == NULL && |
541 | 0 | fc->over == NULL && |
542 | 0 | !fc->agg_star && |
543 | 0 | !fc->agg_distinct && |
544 | 0 | !fc->func_variadic && |
545 | 0 | coldeflist == NIL) |
546 | 0 | { |
547 | 0 | ListCell *lc2; |
548 | |
|
549 | 0 | foreach(lc2, fc->args) |
550 | 0 | { |
551 | 0 | Node *arg = (Node *) lfirst(lc2); |
552 | 0 | FuncCall *newfc; |
553 | |
|
554 | 0 | last_srf = pstate->p_last_srf; |
555 | |
|
556 | 0 | newfc = makeFuncCall(SystemFuncName("unnest"), |
557 | 0 | list_make1(arg), |
558 | 0 | COERCE_EXPLICIT_CALL, |
559 | 0 | fc->location); |
560 | |
|
561 | 0 | newfexpr = transformExpr(pstate, (Node *) newfc, |
562 | 0 | EXPR_KIND_FROM_FUNCTION); |
563 | | |
564 | | /* nodeFunctionscan.c requires SRFs to be at top level */ |
565 | 0 | if (pstate->p_last_srf != last_srf && |
566 | 0 | pstate->p_last_srf != newfexpr) |
567 | 0 | ereport(ERROR, |
568 | 0 | (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
569 | 0 | errmsg("set-returning functions must appear at top level of FROM"), |
570 | 0 | parser_errposition(pstate, |
571 | 0 | exprLocation(pstate->p_last_srf)))); |
572 | | |
573 | 0 | funcexprs = lappend(funcexprs, newfexpr); |
574 | |
|
575 | 0 | funcnames = lappend(funcnames, |
576 | 0 | FigureColname((Node *) newfc)); |
577 | | |
578 | | /* coldeflist is empty, so no error is possible */ |
579 | |
|
580 | 0 | coldeflists = lappend(coldeflists, coldeflist); |
581 | 0 | } |
582 | 0 | continue; /* done with this function item */ |
583 | 0 | } |
584 | 0 | } |
585 | | |
586 | | /* normal case ... */ |
587 | 0 | last_srf = pstate->p_last_srf; |
588 | |
|
589 | 0 | newfexpr = transformExpr(pstate, fexpr, |
590 | 0 | EXPR_KIND_FROM_FUNCTION); |
591 | | |
592 | | /* nodeFunctionscan.c requires SRFs to be at top level */ |
593 | 0 | if (pstate->p_last_srf != last_srf && |
594 | 0 | pstate->p_last_srf != newfexpr) |
595 | 0 | ereport(ERROR, |
596 | 0 | (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
597 | 0 | errmsg("set-returning functions must appear at top level of FROM"), |
598 | 0 | parser_errposition(pstate, |
599 | 0 | exprLocation(pstate->p_last_srf)))); |
600 | | |
601 | 0 | funcexprs = lappend(funcexprs, newfexpr); |
602 | |
|
603 | 0 | funcnames = lappend(funcnames, |
604 | 0 | FigureColname(fexpr)); |
605 | |
|
606 | 0 | if (coldeflist && r->coldeflist) |
607 | 0 | ereport(ERROR, |
608 | 0 | (errcode(ERRCODE_SYNTAX_ERROR), |
609 | 0 | errmsg("multiple column definition lists are not allowed for the same function"), |
610 | 0 | parser_errposition(pstate, |
611 | 0 | exprLocation((Node *) r->coldeflist)))); |
612 | | |
613 | 0 | coldeflists = lappend(coldeflists, coldeflist); |
614 | 0 | } |
615 | | |
616 | 0 | pstate->p_lateral_active = false; |
617 | | |
618 | | /* |
619 | | * We must assign collations now so that the RTE exposes correct collation |
620 | | * info for Vars created from it. |
621 | | */ |
622 | 0 | assign_list_collations(pstate, funcexprs); |
623 | | |
624 | | /* |
625 | | * Install the top-level coldeflist if there was one (we already checked |
626 | | * that there was no conflicting per-function coldeflist). |
627 | | * |
628 | | * We only allow this when there's a single function (even after UNNEST |
629 | | * expansion) and no WITH ORDINALITY. The reason for the latter |
630 | | * restriction is that it's not real clear whether the ordinality column |
631 | | * should be in the coldeflist, and users are too likely to make mistakes |
632 | | * in one direction or the other. Putting the coldeflist inside ROWS |
633 | | * FROM() is much clearer in this case. |
634 | | */ |
635 | 0 | if (r->coldeflist) |
636 | 0 | { |
637 | 0 | if (list_length(funcexprs) != 1) |
638 | 0 | { |
639 | 0 | if (r->is_rowsfrom) |
640 | 0 | ereport(ERROR, |
641 | 0 | (errcode(ERRCODE_SYNTAX_ERROR), |
642 | 0 | errmsg("ROWS FROM() with multiple functions cannot have a column definition list"), |
643 | 0 | errhint("Put a separate column definition list for each function inside ROWS FROM()."), |
644 | 0 | parser_errposition(pstate, |
645 | 0 | exprLocation((Node *) r->coldeflist)))); |
646 | 0 | else |
647 | 0 | ereport(ERROR, |
648 | 0 | (errcode(ERRCODE_SYNTAX_ERROR), |
649 | 0 | errmsg("UNNEST() with multiple arguments cannot have a column definition list"), |
650 | 0 | errhint("Use separate UNNEST() calls inside ROWS FROM(), and attach a column definition list to each one."), |
651 | 0 | parser_errposition(pstate, |
652 | 0 | exprLocation((Node *) r->coldeflist)))); |
653 | 0 | } |
654 | 0 | if (r->ordinality) |
655 | 0 | ereport(ERROR, |
656 | 0 | (errcode(ERRCODE_SYNTAX_ERROR), |
657 | 0 | errmsg("WITH ORDINALITY cannot be used with a column definition list"), |
658 | 0 | errhint("Put the column definition list inside ROWS FROM()."), |
659 | 0 | parser_errposition(pstate, |
660 | 0 | exprLocation((Node *) r->coldeflist)))); |
661 | | |
662 | 0 | coldeflists = list_make1(r->coldeflist); |
663 | 0 | } |
664 | | |
665 | | /* |
666 | | * Mark the RTE as LATERAL if the user said LATERAL explicitly, or if |
667 | | * there are any lateral cross-references in it. |
668 | | */ |
669 | 0 | is_lateral = r->lateral || contain_vars_of_level((Node *) funcexprs, 0); |
670 | | |
671 | | /* |
672 | | * OK, build an RTE and nsitem for the function. |
673 | | */ |
674 | 0 | return addRangeTableEntryForFunction(pstate, |
675 | 0 | funcnames, funcexprs, coldeflists, |
676 | 0 | r, is_lateral, true); |
677 | 0 | } |
678 | | |
679 | | /* |
680 | | * transformRangeTableFunc - |
681 | | * Transform a raw RangeTableFunc into TableFunc. |
682 | | * |
683 | | * Transform the namespace clauses, the document-generating expression, the |
684 | | * row-generating expression, the column-generating expressions, and the |
685 | | * default value expressions. |
686 | | */ |
687 | | static ParseNamespaceItem * |
688 | | transformRangeTableFunc(ParseState *pstate, RangeTableFunc *rtf) |
689 | 0 | { |
690 | 0 | TableFunc *tf = makeNode(TableFunc); |
691 | 0 | const char *constructName; |
692 | 0 | Oid docType; |
693 | 0 | bool is_lateral; |
694 | 0 | ListCell *col; |
695 | 0 | char **names; |
696 | 0 | int colno; |
697 | | |
698 | | /* |
699 | | * Currently we only support XMLTABLE here. See transformJsonTable() for |
700 | | * JSON_TABLE support. |
701 | | */ |
702 | 0 | tf->functype = TFT_XMLTABLE; |
703 | 0 | constructName = "XMLTABLE"; |
704 | 0 | docType = XMLOID; |
705 | | |
706 | | /* |
707 | | * We make lateral_only names of this level visible, whether or not the |
708 | | * RangeTableFunc is explicitly marked LATERAL. This is needed for SQL |
709 | | * spec compliance and seems useful on convenience grounds for all |
710 | | * functions in FROM. |
711 | | * |
712 | | * (LATERAL can't nest within a single pstate level, so we don't need |
713 | | * save/restore logic here.) |
714 | | */ |
715 | 0 | Assert(!pstate->p_lateral_active); |
716 | 0 | pstate->p_lateral_active = true; |
717 | | |
718 | | /* Transform and apply typecast to the row-generating expression ... */ |
719 | 0 | Assert(rtf->rowexpr != NULL); |
720 | 0 | tf->rowexpr = coerce_to_specific_type(pstate, |
721 | 0 | transformExpr(pstate, rtf->rowexpr, EXPR_KIND_FROM_FUNCTION), |
722 | 0 | TEXTOID, |
723 | 0 | constructName); |
724 | 0 | assign_expr_collations(pstate, tf->rowexpr); |
725 | | |
726 | | /* ... and to the document itself */ |
727 | 0 | Assert(rtf->docexpr != NULL); |
728 | 0 | tf->docexpr = coerce_to_specific_type(pstate, |
729 | 0 | transformExpr(pstate, rtf->docexpr, EXPR_KIND_FROM_FUNCTION), |
730 | 0 | docType, |
731 | 0 | constructName); |
732 | 0 | assign_expr_collations(pstate, tf->docexpr); |
733 | | |
734 | | /* undef ordinality column number */ |
735 | 0 | tf->ordinalitycol = -1; |
736 | | |
737 | | /* Process column specs */ |
738 | 0 | names = palloc_array(char *, list_length(rtf->columns)); |
739 | |
|
740 | 0 | colno = 0; |
741 | 0 | foreach(col, rtf->columns) |
742 | 0 | { |
743 | 0 | RangeTableFuncCol *rawc = (RangeTableFuncCol *) lfirst(col); |
744 | 0 | Oid typid; |
745 | 0 | int32 typmod; |
746 | 0 | Node *colexpr; |
747 | 0 | Node *coldefexpr; |
748 | 0 | int j; |
749 | |
|
750 | 0 | tf->colnames = lappend(tf->colnames, |
751 | 0 | makeString(pstrdup(rawc->colname))); |
752 | | |
753 | | /* |
754 | | * Determine the type and typmod for the new column. FOR ORDINALITY |
755 | | * columns are INTEGER per spec; the others are user-specified. |
756 | | */ |
757 | 0 | if (rawc->for_ordinality) |
758 | 0 | { |
759 | 0 | if (tf->ordinalitycol != -1) |
760 | 0 | ereport(ERROR, |
761 | 0 | (errcode(ERRCODE_SYNTAX_ERROR), |
762 | 0 | errmsg("only one FOR ORDINALITY column is allowed"), |
763 | 0 | parser_errposition(pstate, rawc->location))); |
764 | | |
765 | 0 | typid = INT4OID; |
766 | 0 | typmod = -1; |
767 | 0 | tf->ordinalitycol = colno; |
768 | 0 | } |
769 | 0 | else |
770 | 0 | { |
771 | 0 | if (rawc->typeName->setof) |
772 | 0 | ereport(ERROR, |
773 | 0 | (errcode(ERRCODE_INVALID_TABLE_DEFINITION), |
774 | 0 | errmsg("column \"%s\" cannot be declared SETOF", |
775 | 0 | rawc->colname), |
776 | 0 | parser_errposition(pstate, rawc->location))); |
777 | | |
778 | 0 | typenameTypeIdAndMod(pstate, rawc->typeName, |
779 | 0 | &typid, &typmod); |
780 | 0 | } |
781 | | |
782 | 0 | tf->coltypes = lappend_oid(tf->coltypes, typid); |
783 | 0 | tf->coltypmods = lappend_int(tf->coltypmods, typmod); |
784 | 0 | tf->colcollations = lappend_oid(tf->colcollations, |
785 | 0 | get_typcollation(typid)); |
786 | | |
787 | | /* Transform the PATH and DEFAULT expressions */ |
788 | 0 | if (rawc->colexpr) |
789 | 0 | { |
790 | 0 | colexpr = coerce_to_specific_type(pstate, |
791 | 0 | transformExpr(pstate, rawc->colexpr, |
792 | 0 | EXPR_KIND_FROM_FUNCTION), |
793 | 0 | TEXTOID, |
794 | 0 | constructName); |
795 | 0 | assign_expr_collations(pstate, colexpr); |
796 | 0 | } |
797 | 0 | else |
798 | 0 | colexpr = NULL; |
799 | |
|
800 | 0 | if (rawc->coldefexpr) |
801 | 0 | { |
802 | 0 | coldefexpr = coerce_to_specific_type_typmod(pstate, |
803 | 0 | transformExpr(pstate, rawc->coldefexpr, |
804 | 0 | EXPR_KIND_FROM_FUNCTION), |
805 | 0 | typid, typmod, |
806 | 0 | constructName); |
807 | 0 | assign_expr_collations(pstate, coldefexpr); |
808 | 0 | } |
809 | 0 | else |
810 | 0 | coldefexpr = NULL; |
811 | |
|
812 | 0 | tf->colexprs = lappend(tf->colexprs, colexpr); |
813 | 0 | tf->coldefexprs = lappend(tf->coldefexprs, coldefexpr); |
814 | |
|
815 | 0 | if (rawc->is_not_null) |
816 | 0 | tf->notnulls = bms_add_member(tf->notnulls, colno); |
817 | | |
818 | | /* make sure column names are unique */ |
819 | 0 | for (j = 0; j < colno; j++) |
820 | 0 | if (strcmp(names[j], rawc->colname) == 0) |
821 | 0 | ereport(ERROR, |
822 | 0 | (errcode(ERRCODE_SYNTAX_ERROR), |
823 | 0 | errmsg("column name \"%s\" is not unique", |
824 | 0 | rawc->colname), |
825 | 0 | parser_errposition(pstate, rawc->location))); |
826 | 0 | names[colno] = rawc->colname; |
827 | |
|
828 | 0 | colno++; |
829 | 0 | } |
830 | 0 | pfree(names); |
831 | | |
832 | | /* Namespaces, if any, also need to be transformed */ |
833 | 0 | if (rtf->namespaces != NIL) |
834 | 0 | { |
835 | 0 | ListCell *ns; |
836 | 0 | ListCell *lc2; |
837 | 0 | List *ns_uris = NIL; |
838 | 0 | List *ns_names = NIL; |
839 | 0 | bool default_ns_seen = false; |
840 | |
|
841 | 0 | foreach(ns, rtf->namespaces) |
842 | 0 | { |
843 | 0 | ResTarget *r = (ResTarget *) lfirst(ns); |
844 | 0 | Node *ns_uri; |
845 | |
|
846 | 0 | Assert(IsA(r, ResTarget)); |
847 | 0 | ns_uri = transformExpr(pstate, r->val, EXPR_KIND_FROM_FUNCTION); |
848 | 0 | ns_uri = coerce_to_specific_type(pstate, ns_uri, |
849 | 0 | TEXTOID, constructName); |
850 | 0 | assign_expr_collations(pstate, ns_uri); |
851 | 0 | ns_uris = lappend(ns_uris, ns_uri); |
852 | | |
853 | | /* Verify consistency of name list: no dupes, only one DEFAULT */ |
854 | 0 | if (r->name != NULL) |
855 | 0 | { |
856 | 0 | foreach(lc2, ns_names) |
857 | 0 | { |
858 | 0 | String *ns_node = lfirst_node(String, lc2); |
859 | |
|
860 | 0 | if (ns_node == NULL) |
861 | 0 | continue; |
862 | 0 | if (strcmp(strVal(ns_node), r->name) == 0) |
863 | 0 | ereport(ERROR, |
864 | 0 | (errcode(ERRCODE_SYNTAX_ERROR), |
865 | 0 | errmsg("namespace name \"%s\" is not unique", |
866 | 0 | r->name), |
867 | 0 | parser_errposition(pstate, r->location))); |
868 | 0 | } |
869 | 0 | } |
870 | 0 | else |
871 | 0 | { |
872 | 0 | if (default_ns_seen) |
873 | 0 | ereport(ERROR, |
874 | 0 | (errcode(ERRCODE_SYNTAX_ERROR), |
875 | 0 | errmsg("only one default namespace is allowed"), |
876 | 0 | parser_errposition(pstate, r->location))); |
877 | 0 | default_ns_seen = true; |
878 | 0 | } |
879 | | |
880 | | /* We represent DEFAULT by a null pointer */ |
881 | 0 | ns_names = lappend(ns_names, |
882 | 0 | r->name ? makeString(r->name) : NULL); |
883 | 0 | } |
884 | | |
885 | 0 | tf->ns_uris = ns_uris; |
886 | 0 | tf->ns_names = ns_names; |
887 | 0 | } |
888 | | |
889 | 0 | tf->location = rtf->location; |
890 | |
|
891 | 0 | pstate->p_lateral_active = false; |
892 | | |
893 | | /* |
894 | | * Mark the RTE as LATERAL if the user said LATERAL explicitly, or if |
895 | | * there are any lateral cross-references in it. |
896 | | */ |
897 | 0 | is_lateral = rtf->lateral || contain_vars_of_level((Node *) tf, 0); |
898 | |
|
899 | 0 | return addRangeTableEntryForTableFunc(pstate, |
900 | 0 | tf, rtf->alias, is_lateral, true); |
901 | 0 | } |
902 | | |
903 | | /* |
904 | | * transformRangeTableSample --- transform a TABLESAMPLE clause |
905 | | * |
906 | | * Caller has already transformed rts->relation, we just have to validate |
907 | | * the remaining fields and create a TableSampleClause node. |
908 | | */ |
909 | | static TableSampleClause * |
910 | | transformRangeTableSample(ParseState *pstate, RangeTableSample *rts) |
911 | 0 | { |
912 | 0 | TableSampleClause *tablesample; |
913 | 0 | Oid handlerOid; |
914 | 0 | Oid funcargtypes[1]; |
915 | 0 | TsmRoutine *tsm; |
916 | 0 | List *fargs; |
917 | 0 | ListCell *larg, |
918 | 0 | *ltyp; |
919 | | |
920 | | /* |
921 | | * To validate the sample method name, look up the handler function, which |
922 | | * has the same name, one dummy INTERNAL argument, and a result type of |
923 | | * tsm_handler. (Note: tablesample method names are not schema-qualified |
924 | | * in the SQL standard; but since they are just functions to us, we allow |
925 | | * schema qualification to resolve any potential ambiguity.) |
926 | | */ |
927 | 0 | funcargtypes[0] = INTERNALOID; |
928 | |
|
929 | 0 | handlerOid = LookupFuncName(rts->method, 1, funcargtypes, true); |
930 | | |
931 | | /* we want error to complain about no-such-method, not no-such-function */ |
932 | 0 | if (!OidIsValid(handlerOid)) |
933 | 0 | ereport(ERROR, |
934 | 0 | (errcode(ERRCODE_UNDEFINED_OBJECT), |
935 | 0 | errmsg("tablesample method %s does not exist", |
936 | 0 | NameListToString(rts->method)), |
937 | 0 | parser_errposition(pstate, rts->location))); |
938 | | |
939 | | /* check that handler has correct return type */ |
940 | 0 | if (get_func_rettype(handlerOid) != TSM_HANDLEROID) |
941 | 0 | ereport(ERROR, |
942 | 0 | (errcode(ERRCODE_WRONG_OBJECT_TYPE), |
943 | 0 | errmsg("function %s must return type %s", |
944 | 0 | NameListToString(rts->method), "tsm_handler"), |
945 | 0 | parser_errposition(pstate, rts->location))); |
946 | | |
947 | | /* OK, run the handler to get TsmRoutine, for argument type info */ |
948 | 0 | tsm = GetTsmRoutine(handlerOid); |
949 | |
|
950 | 0 | tablesample = makeNode(TableSampleClause); |
951 | 0 | tablesample->tsmhandler = handlerOid; |
952 | | |
953 | | /* check user provided the expected number of arguments */ |
954 | 0 | if (list_length(rts->args) != list_length(tsm->parameterTypes)) |
955 | 0 | ereport(ERROR, |
956 | 0 | (errcode(ERRCODE_INVALID_TABLESAMPLE_ARGUMENT), |
957 | 0 | errmsg_plural("tablesample method %s requires %d argument, not %d", |
958 | 0 | "tablesample method %s requires %d arguments, not %d", |
959 | 0 | list_length(tsm->parameterTypes), |
960 | 0 | NameListToString(rts->method), |
961 | 0 | list_length(tsm->parameterTypes), |
962 | 0 | list_length(rts->args)), |
963 | 0 | parser_errposition(pstate, rts->location))); |
964 | | |
965 | | /* |
966 | | * Transform the arguments, typecasting them as needed. Note we must also |
967 | | * assign collations now, because assign_query_collations() doesn't |
968 | | * examine any substructure of RTEs. |
969 | | */ |
970 | 0 | fargs = NIL; |
971 | 0 | forboth(larg, rts->args, ltyp, tsm->parameterTypes) |
972 | 0 | { |
973 | 0 | Node *arg = (Node *) lfirst(larg); |
974 | 0 | Oid argtype = lfirst_oid(ltyp); |
975 | |
|
976 | 0 | arg = transformExpr(pstate, arg, EXPR_KIND_FROM_FUNCTION); |
977 | 0 | arg = coerce_to_specific_type(pstate, arg, argtype, "TABLESAMPLE"); |
978 | 0 | assign_expr_collations(pstate, arg); |
979 | 0 | fargs = lappend(fargs, arg); |
980 | 0 | } |
981 | 0 | tablesample->args = fargs; |
982 | | |
983 | | /* Process REPEATABLE (seed) */ |
984 | 0 | if (rts->repeatable != NULL) |
985 | 0 | { |
986 | 0 | Node *arg; |
987 | |
|
988 | 0 | if (!tsm->repeatable_across_queries) |
989 | 0 | ereport(ERROR, |
990 | 0 | (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
991 | 0 | errmsg("tablesample method %s does not support REPEATABLE", |
992 | 0 | NameListToString(rts->method)), |
993 | 0 | parser_errposition(pstate, rts->location))); |
994 | | |
995 | 0 | arg = transformExpr(pstate, rts->repeatable, EXPR_KIND_FROM_FUNCTION); |
996 | 0 | arg = coerce_to_specific_type(pstate, arg, FLOAT8OID, "REPEATABLE"); |
997 | 0 | assign_expr_collations(pstate, arg); |
998 | 0 | tablesample->repeatable = (Expr *) arg; |
999 | 0 | } |
1000 | 0 | else |
1001 | 0 | tablesample->repeatable = NULL; |
1002 | | |
1003 | 0 | return tablesample; |
1004 | 0 | } |
1005 | | |
1006 | | /* |
1007 | | * getNSItemForSpecialRelationTypes |
1008 | | * |
1009 | | * If given RangeVar refers to a CTE or an EphemeralNamedRelation, |
1010 | | * build and return an appropriate ParseNamespaceItem, otherwise return NULL |
1011 | | */ |
1012 | | static ParseNamespaceItem * |
1013 | | getNSItemForSpecialRelationTypes(ParseState *pstate, RangeVar *rv) |
1014 | 0 | { |
1015 | 0 | ParseNamespaceItem *nsitem; |
1016 | 0 | CommonTableExpr *cte; |
1017 | 0 | Index levelsup; |
1018 | | |
1019 | | /* |
1020 | | * if it is a qualified name, it can't be a CTE or tuplestore reference |
1021 | | */ |
1022 | 0 | if (rv->schemaname) |
1023 | 0 | return NULL; |
1024 | | |
1025 | 0 | cte = scanNameSpaceForCTE(pstate, rv->relname, &levelsup); |
1026 | 0 | if (cte) |
1027 | 0 | nsitem = addRangeTableEntryForCTE(pstate, cte, levelsup, rv, true); |
1028 | 0 | else if (scanNameSpaceForENR(pstate, rv->relname)) |
1029 | 0 | nsitem = addRangeTableEntryForENR(pstate, rv, true); |
1030 | 0 | else |
1031 | 0 | nsitem = NULL; |
1032 | |
|
1033 | 0 | return nsitem; |
1034 | 0 | } |
1035 | | |
1036 | | /* |
1037 | | * transformFromClauseItem - |
1038 | | * Transform a FROM-clause item, adding any required entries to the |
1039 | | * range table list being built in the ParseState, and return the |
1040 | | * transformed item ready to include in the joinlist. Also build a |
1041 | | * ParseNamespaceItem list describing the names exposed by this item. |
1042 | | * This routine can recurse to handle SQL92 JOIN expressions. |
1043 | | * |
1044 | | * The function return value is the node to add to the jointree (a |
1045 | | * RangeTblRef or JoinExpr). Additional output parameters are: |
1046 | | * |
1047 | | * *top_nsitem: receives the ParseNamespaceItem directly corresponding to the |
1048 | | * jointree item. (This is only used during internal recursion, not by |
1049 | | * outside callers.) |
1050 | | * |
1051 | | * *namespace: receives a List of ParseNamespaceItems for the RTEs exposed |
1052 | | * as table/column names by this item. (The lateral_only flags in these items |
1053 | | * are indeterminate and should be explicitly set by the caller before use.) |
1054 | | */ |
1055 | | static Node * |
1056 | | transformFromClauseItem(ParseState *pstate, Node *n, |
1057 | | ParseNamespaceItem **top_nsitem, |
1058 | | List **namespace) |
1059 | 0 | { |
1060 | | /* Guard against stack overflow due to overly deep subtree */ |
1061 | 0 | check_stack_depth(); |
1062 | |
|
1063 | 0 | if (IsA(n, RangeVar)) |
1064 | 0 | { |
1065 | | /* Plain relation reference, or perhaps a CTE reference */ |
1066 | 0 | RangeVar *rv = (RangeVar *) n; |
1067 | 0 | RangeTblRef *rtr; |
1068 | 0 | ParseNamespaceItem *nsitem; |
1069 | | |
1070 | | /* Check if it's a CTE or tuplestore reference */ |
1071 | 0 | nsitem = getNSItemForSpecialRelationTypes(pstate, rv); |
1072 | | |
1073 | | /* if not found above, must be a table reference */ |
1074 | 0 | if (!nsitem) |
1075 | 0 | nsitem = transformTableEntry(pstate, rv); |
1076 | |
|
1077 | 0 | *top_nsitem = nsitem; |
1078 | 0 | *namespace = list_make1(nsitem); |
1079 | 0 | rtr = makeNode(RangeTblRef); |
1080 | 0 | rtr->rtindex = nsitem->p_rtindex; |
1081 | 0 | return (Node *) rtr; |
1082 | 0 | } |
1083 | 0 | else if (IsA(n, RangeSubselect)) |
1084 | 0 | { |
1085 | | /* sub-SELECT is like a plain relation */ |
1086 | 0 | RangeTblRef *rtr; |
1087 | 0 | ParseNamespaceItem *nsitem; |
1088 | |
|
1089 | 0 | nsitem = transformRangeSubselect(pstate, (RangeSubselect *) n); |
1090 | 0 | *top_nsitem = nsitem; |
1091 | 0 | *namespace = list_make1(nsitem); |
1092 | 0 | rtr = makeNode(RangeTblRef); |
1093 | 0 | rtr->rtindex = nsitem->p_rtindex; |
1094 | 0 | return (Node *) rtr; |
1095 | 0 | } |
1096 | 0 | else if (IsA(n, RangeFunction)) |
1097 | 0 | { |
1098 | | /* function is like a plain relation */ |
1099 | 0 | RangeTblRef *rtr; |
1100 | 0 | ParseNamespaceItem *nsitem; |
1101 | |
|
1102 | 0 | nsitem = transformRangeFunction(pstate, (RangeFunction *) n); |
1103 | 0 | *top_nsitem = nsitem; |
1104 | 0 | *namespace = list_make1(nsitem); |
1105 | 0 | rtr = makeNode(RangeTblRef); |
1106 | 0 | rtr->rtindex = nsitem->p_rtindex; |
1107 | 0 | return (Node *) rtr; |
1108 | 0 | } |
1109 | 0 | else if (IsA(n, RangeTableFunc) || IsA(n, JsonTable)) |
1110 | 0 | { |
1111 | | /* table function is like a plain relation */ |
1112 | 0 | RangeTblRef *rtr; |
1113 | 0 | ParseNamespaceItem *nsitem; |
1114 | |
|
1115 | 0 | if (IsA(n, JsonTable)) |
1116 | 0 | nsitem = transformJsonTable(pstate, (JsonTable *) n); |
1117 | 0 | else |
1118 | 0 | nsitem = transformRangeTableFunc(pstate, (RangeTableFunc *) n); |
1119 | |
|
1120 | 0 | *top_nsitem = nsitem; |
1121 | 0 | *namespace = list_make1(nsitem); |
1122 | 0 | rtr = makeNode(RangeTblRef); |
1123 | 0 | rtr->rtindex = nsitem->p_rtindex; |
1124 | 0 | return (Node *) rtr; |
1125 | 0 | } |
1126 | 0 | else if (IsA(n, RangeTableSample)) |
1127 | 0 | { |
1128 | | /* TABLESAMPLE clause (wrapping some other valid FROM node) */ |
1129 | 0 | RangeTableSample *rts = (RangeTableSample *) n; |
1130 | 0 | Node *rel; |
1131 | 0 | RangeTblEntry *rte; |
1132 | | |
1133 | | /* Recursively transform the contained relation */ |
1134 | 0 | rel = transformFromClauseItem(pstate, rts->relation, |
1135 | 0 | top_nsitem, namespace); |
1136 | 0 | rte = (*top_nsitem)->p_rte; |
1137 | | /* We only support this on plain relations and matviews */ |
1138 | 0 | if (rte->rtekind != RTE_RELATION || |
1139 | 0 | (rte->relkind != RELKIND_RELATION && |
1140 | 0 | rte->relkind != RELKIND_MATVIEW && |
1141 | 0 | rte->relkind != RELKIND_PARTITIONED_TABLE)) |
1142 | 0 | ereport(ERROR, |
1143 | 0 | (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
1144 | 0 | errmsg("TABLESAMPLE clause can only be applied to tables and materialized views"), |
1145 | 0 | parser_errposition(pstate, exprLocation(rts->relation)))); |
1146 | | |
1147 | | /* Transform TABLESAMPLE details and attach to the RTE */ |
1148 | 0 | rte->tablesample = transformRangeTableSample(pstate, rts); |
1149 | 0 | return rel; |
1150 | 0 | } |
1151 | 0 | else if (IsA(n, JoinExpr)) |
1152 | 0 | { |
1153 | | /* A newfangled join expression */ |
1154 | 0 | JoinExpr *j = (JoinExpr *) n; |
1155 | 0 | ParseNamespaceItem *nsitem; |
1156 | 0 | ParseNamespaceItem *l_nsitem; |
1157 | 0 | ParseNamespaceItem *r_nsitem; |
1158 | 0 | List *l_namespace, |
1159 | 0 | *r_namespace, |
1160 | 0 | *my_namespace, |
1161 | 0 | *l_colnames, |
1162 | 0 | *r_colnames, |
1163 | 0 | *res_colnames, |
1164 | 0 | *l_colnos, |
1165 | 0 | *r_colnos, |
1166 | 0 | *res_colvars; |
1167 | 0 | ParseNamespaceColumn *l_nscolumns, |
1168 | 0 | *r_nscolumns, |
1169 | 0 | *res_nscolumns; |
1170 | 0 | int res_colindex; |
1171 | 0 | bool lateral_ok; |
1172 | 0 | int sv_namespace_length; |
1173 | 0 | int k; |
1174 | | |
1175 | | /* |
1176 | | * Recursively process the left subtree, then the right. We must do |
1177 | | * it in this order for correct visibility of LATERAL references. |
1178 | | */ |
1179 | 0 | j->larg = transformFromClauseItem(pstate, j->larg, |
1180 | 0 | &l_nsitem, |
1181 | 0 | &l_namespace); |
1182 | | |
1183 | | /* |
1184 | | * Make the left-side RTEs available for LATERAL access within the |
1185 | | * right side, by temporarily adding them to the pstate's namespace |
1186 | | * list. Per SQL:2008, if the join type is not INNER or LEFT then the |
1187 | | * left-side names must still be exposed, but it's an error to |
1188 | | * reference them. (Stupid design, but that's what it says.) Hence, |
1189 | | * we always push them into the namespace, but mark them as not |
1190 | | * lateral_ok if the jointype is wrong. |
1191 | | * |
1192 | | * Notice that we don't require the merged namespace list to be |
1193 | | * conflict-free. See the comments for scanNameSpaceForRefname(). |
1194 | | */ |
1195 | 0 | lateral_ok = (j->jointype == JOIN_INNER || j->jointype == JOIN_LEFT); |
1196 | 0 | setNamespaceLateralState(l_namespace, true, lateral_ok); |
1197 | |
|
1198 | 0 | sv_namespace_length = list_length(pstate->p_namespace); |
1199 | 0 | pstate->p_namespace = list_concat(pstate->p_namespace, l_namespace); |
1200 | | |
1201 | | /* And now we can process the RHS */ |
1202 | 0 | j->rarg = transformFromClauseItem(pstate, j->rarg, |
1203 | 0 | &r_nsitem, |
1204 | 0 | &r_namespace); |
1205 | | |
1206 | | /* Remove the left-side RTEs from the namespace list again */ |
1207 | 0 | pstate->p_namespace = list_truncate(pstate->p_namespace, |
1208 | 0 | sv_namespace_length); |
1209 | | |
1210 | | /* |
1211 | | * Check for conflicting refnames in left and right subtrees. Must do |
1212 | | * this because higher levels will assume I hand back a self- |
1213 | | * consistent namespace list. |
1214 | | */ |
1215 | 0 | checkNameSpaceConflicts(pstate, l_namespace, r_namespace); |
1216 | | |
1217 | | /* |
1218 | | * Generate combined namespace info for possible use below. |
1219 | | */ |
1220 | 0 | my_namespace = list_concat(l_namespace, r_namespace); |
1221 | | |
1222 | | /* |
1223 | | * We'll work from the nscolumns data and eref alias column names for |
1224 | | * each of the input nsitems. Note that these include dropped |
1225 | | * columns, which is helpful because we can keep track of physical |
1226 | | * input column numbers more easily. |
1227 | | */ |
1228 | 0 | l_nscolumns = l_nsitem->p_nscolumns; |
1229 | 0 | l_colnames = l_nsitem->p_names->colnames; |
1230 | 0 | r_nscolumns = r_nsitem->p_nscolumns; |
1231 | 0 | r_colnames = r_nsitem->p_names->colnames; |
1232 | | |
1233 | | /* |
1234 | | * Natural join does not explicitly specify columns; must generate |
1235 | | * columns to join. Need to run through the list of columns from each |
1236 | | * table or join result and match up the column names. Use the first |
1237 | | * table, and check every column in the second table for a match. |
1238 | | * (We'll check that the matches were unique later on.) The result of |
1239 | | * this step is a list of column names just like an explicitly-written |
1240 | | * USING list. |
1241 | | */ |
1242 | 0 | if (j->isNatural) |
1243 | 0 | { |
1244 | 0 | List *rlist = NIL; |
1245 | 0 | ListCell *lx, |
1246 | 0 | *rx; |
1247 | |
|
1248 | 0 | Assert(j->usingClause == NIL); /* shouldn't have USING() too */ |
1249 | |
|
1250 | 0 | foreach(lx, l_colnames) |
1251 | 0 | { |
1252 | 0 | char *l_colname = strVal(lfirst(lx)); |
1253 | 0 | String *m_name = NULL; |
1254 | |
|
1255 | 0 | if (l_colname[0] == '\0') |
1256 | 0 | continue; /* ignore dropped columns */ |
1257 | | |
1258 | 0 | foreach(rx, r_colnames) |
1259 | 0 | { |
1260 | 0 | char *r_colname = strVal(lfirst(rx)); |
1261 | |
|
1262 | 0 | if (strcmp(l_colname, r_colname) == 0) |
1263 | 0 | { |
1264 | 0 | m_name = makeString(l_colname); |
1265 | 0 | break; |
1266 | 0 | } |
1267 | 0 | } |
1268 | | |
1269 | | /* matched a right column? then keep as join column... */ |
1270 | 0 | if (m_name != NULL) |
1271 | 0 | rlist = lappend(rlist, m_name); |
1272 | 0 | } |
1273 | |
|
1274 | 0 | j->usingClause = rlist; |
1275 | 0 | } |
1276 | | |
1277 | | /* |
1278 | | * If a USING clause alias was specified, save the USING columns as |
1279 | | * its column list. |
1280 | | */ |
1281 | 0 | if (j->join_using_alias) |
1282 | 0 | j->join_using_alias->colnames = j->usingClause; |
1283 | | |
1284 | | /* |
1285 | | * Now transform the join qualifications, if any. |
1286 | | */ |
1287 | 0 | l_colnos = NIL; |
1288 | 0 | r_colnos = NIL; |
1289 | 0 | res_colnames = NIL; |
1290 | 0 | res_colvars = NIL; |
1291 | | |
1292 | | /* this may be larger than needed, but it's not worth being exact */ |
1293 | 0 | res_nscolumns = palloc0_array(ParseNamespaceColumn, |
1294 | 0 | list_length(l_colnames) + list_length(r_colnames)); |
1295 | 0 | res_colindex = 0; |
1296 | |
|
1297 | 0 | if (j->usingClause) |
1298 | 0 | { |
1299 | | /* |
1300 | | * JOIN/USING (or NATURAL JOIN, as transformed above). Transform |
1301 | | * the list into an explicit ON-condition. |
1302 | | */ |
1303 | 0 | List *ucols = j->usingClause; |
1304 | 0 | List *l_usingvars = NIL; |
1305 | 0 | List *r_usingvars = NIL; |
1306 | 0 | ListCell *ucol; |
1307 | |
|
1308 | 0 | Assert(j->quals == NULL); /* shouldn't have ON() too */ |
1309 | |
|
1310 | 0 | foreach(ucol, ucols) |
1311 | 0 | { |
1312 | 0 | char *u_colname = strVal(lfirst(ucol)); |
1313 | 0 | ListCell *col; |
1314 | 0 | int ndx; |
1315 | 0 | int l_index = -1; |
1316 | 0 | int r_index = -1; |
1317 | 0 | Var *l_colvar, |
1318 | 0 | *r_colvar; |
1319 | |
|
1320 | 0 | Assert(u_colname[0] != '\0'); |
1321 | | |
1322 | | /* Check for USING(foo,foo) */ |
1323 | 0 | foreach(col, res_colnames) |
1324 | 0 | { |
1325 | 0 | char *res_colname = strVal(lfirst(col)); |
1326 | |
|
1327 | 0 | if (strcmp(res_colname, u_colname) == 0) |
1328 | 0 | ereport(ERROR, |
1329 | 0 | (errcode(ERRCODE_DUPLICATE_COLUMN), |
1330 | 0 | errmsg("column name \"%s\" appears more than once in USING clause", |
1331 | 0 | u_colname))); |
1332 | 0 | } |
1333 | | |
1334 | | /* Find it in left input */ |
1335 | 0 | ndx = 0; |
1336 | 0 | foreach(col, l_colnames) |
1337 | 0 | { |
1338 | 0 | char *l_colname = strVal(lfirst(col)); |
1339 | |
|
1340 | 0 | if (strcmp(l_colname, u_colname) == 0) |
1341 | 0 | { |
1342 | 0 | if (l_index >= 0) |
1343 | 0 | ereport(ERROR, |
1344 | 0 | (errcode(ERRCODE_AMBIGUOUS_COLUMN), |
1345 | 0 | errmsg("common column name \"%s\" appears more than once in left table", |
1346 | 0 | u_colname))); |
1347 | 0 | l_index = ndx; |
1348 | 0 | } |
1349 | 0 | ndx++; |
1350 | 0 | } |
1351 | 0 | if (l_index < 0) |
1352 | 0 | ereport(ERROR, |
1353 | 0 | (errcode(ERRCODE_UNDEFINED_COLUMN), |
1354 | 0 | errmsg("column \"%s\" specified in USING clause does not exist in left table", |
1355 | 0 | u_colname))); |
1356 | 0 | l_colnos = lappend_int(l_colnos, l_index + 1); |
1357 | | |
1358 | | /* Find it in right input */ |
1359 | 0 | ndx = 0; |
1360 | 0 | foreach(col, r_colnames) |
1361 | 0 | { |
1362 | 0 | char *r_colname = strVal(lfirst(col)); |
1363 | |
|
1364 | 0 | if (strcmp(r_colname, u_colname) == 0) |
1365 | 0 | { |
1366 | 0 | if (r_index >= 0) |
1367 | 0 | ereport(ERROR, |
1368 | 0 | (errcode(ERRCODE_AMBIGUOUS_COLUMN), |
1369 | 0 | errmsg("common column name \"%s\" appears more than once in right table", |
1370 | 0 | u_colname))); |
1371 | 0 | r_index = ndx; |
1372 | 0 | } |
1373 | 0 | ndx++; |
1374 | 0 | } |
1375 | 0 | if (r_index < 0) |
1376 | 0 | ereport(ERROR, |
1377 | 0 | (errcode(ERRCODE_UNDEFINED_COLUMN), |
1378 | 0 | errmsg("column \"%s\" specified in USING clause does not exist in right table", |
1379 | 0 | u_colname))); |
1380 | 0 | r_colnos = lappend_int(r_colnos, r_index + 1); |
1381 | | |
1382 | | /* Build Vars to use in the generated JOIN ON clause */ |
1383 | 0 | l_colvar = buildVarFromNSColumn(pstate, l_nscolumns + l_index); |
1384 | 0 | l_usingvars = lappend(l_usingvars, l_colvar); |
1385 | 0 | r_colvar = buildVarFromNSColumn(pstate, r_nscolumns + r_index); |
1386 | 0 | r_usingvars = lappend(r_usingvars, r_colvar); |
1387 | | |
1388 | | /* |
1389 | | * While we're here, add column names to the res_colnames |
1390 | | * list. It's a bit ugly to do this here while the |
1391 | | * corresponding res_colvars entries are not made till later, |
1392 | | * but doing this later would require an additional traversal |
1393 | | * of the usingClause list. |
1394 | | */ |
1395 | 0 | res_colnames = lappend(res_colnames, lfirst(ucol)); |
1396 | 0 | } |
1397 | | |
1398 | | /* Construct the generated JOIN ON clause */ |
1399 | 0 | j->quals = transformJoinUsingClause(pstate, |
1400 | 0 | l_usingvars, |
1401 | 0 | r_usingvars); |
1402 | 0 | } |
1403 | 0 | else if (j->quals) |
1404 | 0 | { |
1405 | | /* User-written ON-condition; transform it */ |
1406 | 0 | j->quals = transformJoinOnClause(pstate, j, my_namespace); |
1407 | 0 | } |
1408 | 0 | else |
1409 | 0 | { |
1410 | | /* CROSS JOIN: no quals */ |
1411 | 0 | } |
1412 | | |
1413 | | /* |
1414 | | * If this is an outer join, now mark the appropriate child RTEs as |
1415 | | * being nulled by this join. We have finished processing the child |
1416 | | * join expressions as well as the current join's quals, which deal in |
1417 | | * non-nulled input columns. All future references to those RTEs will |
1418 | | * see possibly-nulled values, and we should mark generated Vars to |
1419 | | * account for that. In particular, the join alias Vars that we're |
1420 | | * about to build should reflect the nulling effects of this join. |
1421 | | * |
1422 | | * A difficulty with doing this is that we need the join's RT index, |
1423 | | * which we don't officially have yet. However, no other RTE can get |
1424 | | * made between here and the addRangeTableEntryForJoin call, so we can |
1425 | | * predict what the assignment will be. (Alternatively, we could call |
1426 | | * addRangeTableEntryForJoin before we have all the data computed, but |
1427 | | * this seems less ugly.) |
1428 | | */ |
1429 | 0 | j->rtindex = list_length(pstate->p_rtable) + 1; |
1430 | |
|
1431 | 0 | switch (j->jointype) |
1432 | 0 | { |
1433 | 0 | case JOIN_INNER: |
1434 | 0 | break; |
1435 | 0 | case JOIN_LEFT: |
1436 | 0 | markRelsAsNulledBy(pstate, j->rarg, j->rtindex); |
1437 | 0 | break; |
1438 | 0 | case JOIN_FULL: |
1439 | 0 | markRelsAsNulledBy(pstate, j->larg, j->rtindex); |
1440 | 0 | markRelsAsNulledBy(pstate, j->rarg, j->rtindex); |
1441 | 0 | break; |
1442 | 0 | case JOIN_RIGHT: |
1443 | 0 | markRelsAsNulledBy(pstate, j->larg, j->rtindex); |
1444 | 0 | break; |
1445 | 0 | default: |
1446 | | /* shouldn't see any other types here */ |
1447 | 0 | elog(ERROR, "unrecognized join type: %d", |
1448 | 0 | (int) j->jointype); |
1449 | 0 | break; |
1450 | 0 | } |
1451 | | |
1452 | | /* |
1453 | | * Now we can construct join alias expressions for the USING columns. |
1454 | | */ |
1455 | 0 | if (j->usingClause) |
1456 | 0 | { |
1457 | 0 | ListCell *lc1, |
1458 | 0 | *lc2; |
1459 | | |
1460 | | /* Scan the colnos lists to recover info from the previous loop */ |
1461 | 0 | forboth(lc1, l_colnos, lc2, r_colnos) |
1462 | 0 | { |
1463 | 0 | int l_index = lfirst_int(lc1) - 1; |
1464 | 0 | int r_index = lfirst_int(lc2) - 1; |
1465 | 0 | Var *l_colvar, |
1466 | 0 | *r_colvar; |
1467 | 0 | Node *u_colvar; |
1468 | 0 | ParseNamespaceColumn *res_nscolumn; |
1469 | | |
1470 | | /* |
1471 | | * Note we re-build these Vars: they might have different |
1472 | | * varnullingrels than the ones made in the previous loop. |
1473 | | */ |
1474 | 0 | l_colvar = buildVarFromNSColumn(pstate, l_nscolumns + l_index); |
1475 | 0 | r_colvar = buildVarFromNSColumn(pstate, r_nscolumns + r_index); |
1476 | | |
1477 | | /* Construct the join alias Var for this column */ |
1478 | 0 | u_colvar = buildMergedJoinVar(pstate, |
1479 | 0 | j->jointype, |
1480 | 0 | l_colvar, |
1481 | 0 | r_colvar); |
1482 | 0 | res_colvars = lappend(res_colvars, u_colvar); |
1483 | | |
1484 | | /* Construct column's res_nscolumns[] entry */ |
1485 | 0 | res_nscolumn = res_nscolumns + res_colindex; |
1486 | 0 | res_colindex++; |
1487 | 0 | if (u_colvar == (Node *) l_colvar) |
1488 | 0 | { |
1489 | | /* Merged column is equivalent to left input */ |
1490 | 0 | *res_nscolumn = l_nscolumns[l_index]; |
1491 | 0 | } |
1492 | 0 | else if (u_colvar == (Node *) r_colvar) |
1493 | 0 | { |
1494 | | /* Merged column is equivalent to right input */ |
1495 | 0 | *res_nscolumn = r_nscolumns[r_index]; |
1496 | 0 | } |
1497 | 0 | else |
1498 | 0 | { |
1499 | | /* |
1500 | | * Merged column is not semantically equivalent to either |
1501 | | * input, so it needs to be referenced as the join output |
1502 | | * column. |
1503 | | */ |
1504 | 0 | res_nscolumn->p_varno = j->rtindex; |
1505 | 0 | res_nscolumn->p_varattno = res_colindex; |
1506 | 0 | res_nscolumn->p_vartype = exprType(u_colvar); |
1507 | 0 | res_nscolumn->p_vartypmod = exprTypmod(u_colvar); |
1508 | 0 | res_nscolumn->p_varcollid = exprCollation(u_colvar); |
1509 | 0 | res_nscolumn->p_varnosyn = j->rtindex; |
1510 | 0 | res_nscolumn->p_varattnosyn = res_colindex; |
1511 | 0 | } |
1512 | 0 | } |
1513 | 0 | } |
1514 | | |
1515 | | /* Add remaining columns from each side to the output columns */ |
1516 | 0 | res_colindex += |
1517 | 0 | extractRemainingColumns(pstate, |
1518 | 0 | l_nscolumns, l_colnames, &l_colnos, |
1519 | 0 | &res_colnames, &res_colvars, |
1520 | 0 | res_nscolumns + res_colindex); |
1521 | 0 | res_colindex += |
1522 | 0 | extractRemainingColumns(pstate, |
1523 | 0 | r_nscolumns, r_colnames, &r_colnos, |
1524 | 0 | &res_colnames, &res_colvars, |
1525 | 0 | res_nscolumns + res_colindex); |
1526 | | |
1527 | | /* If join has an alias, it syntactically hides all inputs */ |
1528 | 0 | if (j->alias) |
1529 | 0 | { |
1530 | 0 | for (k = 0; k < res_colindex; k++) |
1531 | 0 | { |
1532 | 0 | ParseNamespaceColumn *nscol = res_nscolumns + k; |
1533 | |
|
1534 | 0 | nscol->p_varnosyn = j->rtindex; |
1535 | 0 | nscol->p_varattnosyn = k + 1; |
1536 | 0 | } |
1537 | 0 | } |
1538 | | |
1539 | | /* |
1540 | | * Now build an RTE and nsitem for the result of the join. |
1541 | | */ |
1542 | 0 | nsitem = addRangeTableEntryForJoin(pstate, |
1543 | 0 | res_colnames, |
1544 | 0 | res_nscolumns, |
1545 | 0 | j->jointype, |
1546 | 0 | list_length(j->usingClause), |
1547 | 0 | res_colvars, |
1548 | 0 | l_colnos, |
1549 | 0 | r_colnos, |
1550 | 0 | j->join_using_alias, |
1551 | 0 | j->alias, |
1552 | 0 | true); |
1553 | | |
1554 | | /* Verify that we correctly predicted the join's RT index */ |
1555 | 0 | Assert(j->rtindex == nsitem->p_rtindex); |
1556 | | /* Cross-check number of columns, too */ |
1557 | 0 | Assert(res_colindex == list_length(nsitem->p_names->colnames)); |
1558 | | |
1559 | | /* |
1560 | | * Save a link to the JoinExpr in the proper element of p_joinexprs. |
1561 | | * Since we maintain that list lazily, it may be necessary to fill in |
1562 | | * empty entries before we can add the JoinExpr in the right place. |
1563 | | */ |
1564 | 0 | for (k = list_length(pstate->p_joinexprs) + 1; k < j->rtindex; k++) |
1565 | 0 | pstate->p_joinexprs = lappend(pstate->p_joinexprs, NULL); |
1566 | 0 | pstate->p_joinexprs = lappend(pstate->p_joinexprs, j); |
1567 | 0 | Assert(list_length(pstate->p_joinexprs) == j->rtindex); |
1568 | | |
1569 | | /* |
1570 | | * If the join has a USING alias, build a ParseNamespaceItem for that |
1571 | | * and add it to the list of nsitems in the join's input. |
1572 | | */ |
1573 | 0 | if (j->join_using_alias) |
1574 | 0 | { |
1575 | 0 | ParseNamespaceItem *jnsitem; |
1576 | |
|
1577 | 0 | jnsitem = palloc_object(ParseNamespaceItem); |
1578 | 0 | jnsitem->p_names = j->join_using_alias; |
1579 | 0 | jnsitem->p_rte = nsitem->p_rte; |
1580 | 0 | jnsitem->p_rtindex = nsitem->p_rtindex; |
1581 | 0 | jnsitem->p_perminfo = NULL; |
1582 | | /* no need to copy the first N columns, just use res_nscolumns */ |
1583 | 0 | jnsitem->p_nscolumns = res_nscolumns; |
1584 | | /* set default visibility flags; might get changed later */ |
1585 | 0 | jnsitem->p_rel_visible = true; |
1586 | 0 | jnsitem->p_cols_visible = true; |
1587 | 0 | jnsitem->p_lateral_only = false; |
1588 | 0 | jnsitem->p_lateral_ok = true; |
1589 | 0 | jnsitem->p_returning_type = VAR_RETURNING_DEFAULT; |
1590 | | /* Per SQL, we must check for alias conflicts */ |
1591 | 0 | checkNameSpaceConflicts(pstate, list_make1(jnsitem), my_namespace); |
1592 | 0 | my_namespace = lappend(my_namespace, jnsitem); |
1593 | 0 | } |
1594 | | |
1595 | | /* |
1596 | | * Prepare returned namespace list. If the JOIN has an alias then it |
1597 | | * hides the contained RTEs completely; otherwise, the contained RTEs |
1598 | | * are still visible as table names, but are not visible for |
1599 | | * unqualified column-name access. |
1600 | | * |
1601 | | * Note: if there are nested alias-less JOINs, the lower-level ones |
1602 | | * will remain in the list although they have neither p_rel_visible |
1603 | | * nor p_cols_visible set. We could delete such list items, but it's |
1604 | | * unclear that it's worth expending cycles to do so. |
1605 | | */ |
1606 | 0 | if (j->alias != NULL) |
1607 | 0 | my_namespace = NIL; |
1608 | 0 | else |
1609 | 0 | setNamespaceColumnVisibility(my_namespace, false); |
1610 | | |
1611 | | /* |
1612 | | * The join RTE itself is always made visible for unqualified column |
1613 | | * names. It's visible as a relation name only if it has an alias. |
1614 | | */ |
1615 | 0 | nsitem->p_rel_visible = (j->alias != NULL); |
1616 | 0 | nsitem->p_cols_visible = true; |
1617 | 0 | nsitem->p_lateral_only = false; |
1618 | 0 | nsitem->p_lateral_ok = true; |
1619 | |
|
1620 | 0 | *top_nsitem = nsitem; |
1621 | 0 | *namespace = lappend(my_namespace, nsitem); |
1622 | |
|
1623 | 0 | return (Node *) j; |
1624 | 0 | } |
1625 | 0 | else |
1626 | 0 | elog(ERROR, "unrecognized node type: %d", (int) nodeTag(n)); |
1627 | 0 | return NULL; /* can't get here, keep compiler quiet */ |
1628 | 0 | } |
1629 | | |
1630 | | /* |
1631 | | * buildVarFromNSColumn - |
1632 | | * build a Var node using ParseNamespaceColumn data |
1633 | | * |
1634 | | * This is used to construct joinaliasvars entries. |
1635 | | * We can assume varlevelsup should be 0, and no location is specified. |
1636 | | * Note also that no column SELECT privilege is requested here; that would |
1637 | | * happen only if the column is actually referenced in the query. |
1638 | | */ |
1639 | | static Var * |
1640 | | buildVarFromNSColumn(ParseState *pstate, ParseNamespaceColumn *nscol) |
1641 | 0 | { |
1642 | 0 | Var *var; |
1643 | |
|
1644 | 0 | Assert(nscol->p_varno > 0); /* i.e., not deleted column */ |
1645 | 0 | var = makeVar(nscol->p_varno, |
1646 | 0 | nscol->p_varattno, |
1647 | 0 | nscol->p_vartype, |
1648 | 0 | nscol->p_vartypmod, |
1649 | 0 | nscol->p_varcollid, |
1650 | 0 | 0); |
1651 | | /* makeVar doesn't offer parameters for these, so set by hand: */ |
1652 | 0 | var->varreturningtype = nscol->p_varreturningtype; |
1653 | 0 | var->varnosyn = nscol->p_varnosyn; |
1654 | 0 | var->varattnosyn = nscol->p_varattnosyn; |
1655 | | |
1656 | | /* ... and update varnullingrels */ |
1657 | 0 | markNullableIfNeeded(pstate, var); |
1658 | |
|
1659 | 0 | return var; |
1660 | 0 | } |
1661 | | |
1662 | | /* |
1663 | | * buildMergedJoinVar - |
1664 | | * generate a suitable replacement expression for a merged join column |
1665 | | */ |
1666 | | static Node * |
1667 | | buildMergedJoinVar(ParseState *pstate, JoinType jointype, |
1668 | | Var *l_colvar, Var *r_colvar) |
1669 | 0 | { |
1670 | 0 | Oid outcoltype; |
1671 | 0 | int32 outcoltypmod; |
1672 | 0 | Node *l_node, |
1673 | 0 | *r_node, |
1674 | 0 | *res_node; |
1675 | |
|
1676 | 0 | outcoltype = select_common_type(pstate, |
1677 | 0 | list_make2(l_colvar, r_colvar), |
1678 | 0 | "JOIN/USING", |
1679 | 0 | NULL); |
1680 | 0 | outcoltypmod = select_common_typmod(pstate, |
1681 | 0 | list_make2(l_colvar, r_colvar), |
1682 | 0 | outcoltype); |
1683 | | |
1684 | | /* |
1685 | | * Insert coercion functions if needed. Note that a difference in typmod |
1686 | | * can only happen if input has typmod but outcoltypmod is -1. In that |
1687 | | * case we insert a RelabelType to clearly mark that result's typmod is |
1688 | | * not same as input. We never need coerce_type_typmod. |
1689 | | */ |
1690 | 0 | if (l_colvar->vartype != outcoltype) |
1691 | 0 | l_node = coerce_type(pstate, (Node *) l_colvar, l_colvar->vartype, |
1692 | 0 | outcoltype, outcoltypmod, |
1693 | 0 | COERCION_IMPLICIT, COERCE_IMPLICIT_CAST, -1); |
1694 | 0 | else if (l_colvar->vartypmod != outcoltypmod) |
1695 | 0 | l_node = (Node *) makeRelabelType((Expr *) l_colvar, |
1696 | 0 | outcoltype, outcoltypmod, |
1697 | 0 | InvalidOid, /* fixed below */ |
1698 | 0 | COERCE_IMPLICIT_CAST); |
1699 | 0 | else |
1700 | 0 | l_node = (Node *) l_colvar; |
1701 | |
|
1702 | 0 | if (r_colvar->vartype != outcoltype) |
1703 | 0 | r_node = coerce_type(pstate, (Node *) r_colvar, r_colvar->vartype, |
1704 | 0 | outcoltype, outcoltypmod, |
1705 | 0 | COERCION_IMPLICIT, COERCE_IMPLICIT_CAST, -1); |
1706 | 0 | else if (r_colvar->vartypmod != outcoltypmod) |
1707 | 0 | r_node = (Node *) makeRelabelType((Expr *) r_colvar, |
1708 | 0 | outcoltype, outcoltypmod, |
1709 | 0 | InvalidOid, /* fixed below */ |
1710 | 0 | COERCE_IMPLICIT_CAST); |
1711 | 0 | else |
1712 | 0 | r_node = (Node *) r_colvar; |
1713 | | |
1714 | | /* |
1715 | | * Choose what to emit |
1716 | | */ |
1717 | 0 | switch (jointype) |
1718 | 0 | { |
1719 | 0 | case JOIN_INNER: |
1720 | | |
1721 | | /* |
1722 | | * We can use either var; prefer non-coerced one if available. |
1723 | | */ |
1724 | 0 | if (IsA(l_node, Var)) |
1725 | 0 | res_node = l_node; |
1726 | 0 | else if (IsA(r_node, Var)) |
1727 | 0 | res_node = r_node; |
1728 | 0 | else |
1729 | 0 | res_node = l_node; |
1730 | 0 | break; |
1731 | 0 | case JOIN_LEFT: |
1732 | | /* Always use left var */ |
1733 | 0 | res_node = l_node; |
1734 | 0 | break; |
1735 | 0 | case JOIN_RIGHT: |
1736 | | /* Always use right var */ |
1737 | 0 | res_node = r_node; |
1738 | 0 | break; |
1739 | 0 | case JOIN_FULL: |
1740 | 0 | { |
1741 | | /* |
1742 | | * Here we must build a COALESCE expression to ensure that the |
1743 | | * join output is non-null if either input is. |
1744 | | */ |
1745 | 0 | CoalesceExpr *c = makeNode(CoalesceExpr); |
1746 | |
|
1747 | 0 | c->coalescetype = outcoltype; |
1748 | | /* coalescecollid will get set below */ |
1749 | 0 | c->args = list_make2(l_node, r_node); |
1750 | 0 | c->location = -1; |
1751 | 0 | res_node = (Node *) c; |
1752 | 0 | break; |
1753 | 0 | } |
1754 | 0 | default: |
1755 | 0 | elog(ERROR, "unrecognized join type: %d", (int) jointype); |
1756 | 0 | res_node = NULL; /* keep compiler quiet */ |
1757 | 0 | break; |
1758 | 0 | } |
1759 | | |
1760 | | /* |
1761 | | * Apply assign_expr_collations to fix up the collation info in the |
1762 | | * coercion and CoalesceExpr nodes, if we made any. This must be done now |
1763 | | * so that the join node's alias vars show correct collation info. |
1764 | | */ |
1765 | 0 | assign_expr_collations(pstate, res_node); |
1766 | |
|
1767 | 0 | return res_node; |
1768 | 0 | } |
1769 | | |
1770 | | /* |
1771 | | * markRelsAsNulledBy - |
1772 | | * Mark the given jointree node and its children as nulled by join jindex |
1773 | | */ |
1774 | | static void |
1775 | | markRelsAsNulledBy(ParseState *pstate, Node *n, int jindex) |
1776 | 0 | { |
1777 | 0 | int varno; |
1778 | 0 | ListCell *lc; |
1779 | | |
1780 | | /* Note: we can't see FromExpr here */ |
1781 | 0 | if (IsA(n, RangeTblRef)) |
1782 | 0 | { |
1783 | 0 | varno = ((RangeTblRef *) n)->rtindex; |
1784 | 0 | } |
1785 | 0 | else if (IsA(n, JoinExpr)) |
1786 | 0 | { |
1787 | 0 | JoinExpr *j = (JoinExpr *) n; |
1788 | | |
1789 | | /* recurse to children */ |
1790 | 0 | markRelsAsNulledBy(pstate, j->larg, jindex); |
1791 | 0 | markRelsAsNulledBy(pstate, j->rarg, jindex); |
1792 | 0 | varno = j->rtindex; |
1793 | 0 | } |
1794 | 0 | else |
1795 | 0 | { |
1796 | 0 | elog(ERROR, "unrecognized node type: %d", (int) nodeTag(n)); |
1797 | 0 | varno = 0; /* keep compiler quiet */ |
1798 | 0 | } |
1799 | | |
1800 | | /* |
1801 | | * Now add jindex to the p_nullingrels set for relation varno. Since we |
1802 | | * maintain the p_nullingrels list lazily, we might need to extend it to |
1803 | | * make the varno'th entry exist. |
1804 | | */ |
1805 | 0 | while (list_length(pstate->p_nullingrels) < varno) |
1806 | 0 | pstate->p_nullingrels = lappend(pstate->p_nullingrels, NULL); |
1807 | 0 | lc = list_nth_cell(pstate->p_nullingrels, varno - 1); |
1808 | 0 | lfirst(lc) = bms_add_member((Bitmapset *) lfirst(lc), jindex); |
1809 | 0 | } |
1810 | | |
1811 | | /* |
1812 | | * setNamespaceColumnVisibility - |
1813 | | * Convenience subroutine to update cols_visible flags in a namespace list. |
1814 | | */ |
1815 | | static void |
1816 | | setNamespaceColumnVisibility(List *namespace, bool cols_visible) |
1817 | 0 | { |
1818 | 0 | ListCell *lc; |
1819 | |
|
1820 | 0 | foreach(lc, namespace) |
1821 | 0 | { |
1822 | 0 | ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(lc); |
1823 | |
|
1824 | 0 | nsitem->p_cols_visible = cols_visible; |
1825 | 0 | } |
1826 | 0 | } |
1827 | | |
1828 | | /* |
1829 | | * setNamespaceLateralState - |
1830 | | * Convenience subroutine to update LATERAL flags in a namespace list. |
1831 | | */ |
1832 | | static void |
1833 | | setNamespaceLateralState(List *namespace, bool lateral_only, bool lateral_ok) |
1834 | 0 | { |
1835 | 0 | ListCell *lc; |
1836 | |
|
1837 | 0 | foreach(lc, namespace) |
1838 | 0 | { |
1839 | 0 | ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(lc); |
1840 | |
|
1841 | 0 | nsitem->p_lateral_only = lateral_only; |
1842 | 0 | nsitem->p_lateral_ok = lateral_ok; |
1843 | 0 | } |
1844 | 0 | } |
1845 | | |
1846 | | |
1847 | | /* |
1848 | | * transformWhereClause - |
1849 | | * Transform the qualification and make sure it is of type boolean. |
1850 | | * Used for WHERE and allied clauses. |
1851 | | * |
1852 | | * constructName does not affect the semantics, but is used in error messages |
1853 | | */ |
1854 | | Node * |
1855 | | transformWhereClause(ParseState *pstate, Node *clause, |
1856 | | ParseExprKind exprKind, const char *constructName) |
1857 | 0 | { |
1858 | 0 | Node *qual; |
1859 | |
|
1860 | 0 | if (clause == NULL) |
1861 | 0 | return NULL; |
1862 | | |
1863 | 0 | qual = transformExpr(pstate, clause, exprKind); |
1864 | |
|
1865 | 0 | qual = coerce_to_boolean(pstate, qual, constructName); |
1866 | |
|
1867 | 0 | return qual; |
1868 | 0 | } |
1869 | | |
1870 | | |
1871 | | /* |
1872 | | * transformLimitClause - |
1873 | | * Transform the expression and make sure it is of type bigint. |
1874 | | * Used for LIMIT and allied clauses. |
1875 | | * |
1876 | | * Note: as of Postgres 8.2, LIMIT expressions are expected to yield int8, |
1877 | | * rather than int4 as before. |
1878 | | * |
1879 | | * constructName does not affect the semantics, but is used in error messages |
1880 | | */ |
1881 | | Node * |
1882 | | transformLimitClause(ParseState *pstate, Node *clause, |
1883 | | ParseExprKind exprKind, const char *constructName, |
1884 | | LimitOption limitOption) |
1885 | 0 | { |
1886 | 0 | Node *qual; |
1887 | |
|
1888 | 0 | if (clause == NULL) |
1889 | 0 | return NULL; |
1890 | | |
1891 | 0 | qual = transformExpr(pstate, clause, exprKind); |
1892 | |
|
1893 | 0 | qual = coerce_to_specific_type(pstate, qual, INT8OID, constructName); |
1894 | | |
1895 | | /* LIMIT can't refer to any variables of the current query */ |
1896 | 0 | checkExprIsVarFree(pstate, qual, constructName); |
1897 | | |
1898 | | /* |
1899 | | * Don't allow NULLs in FETCH FIRST .. WITH TIES. This test is ugly and |
1900 | | * extremely simplistic, in that you can pass a NULL anyway by hiding it |
1901 | | * inside an expression -- but this protects ruleutils against emitting an |
1902 | | * unadorned NULL that's not accepted back by the grammar. |
1903 | | */ |
1904 | 0 | if (exprKind == EXPR_KIND_LIMIT && limitOption == LIMIT_OPTION_WITH_TIES && |
1905 | 0 | IsA(clause, A_Const) && castNode(A_Const, clause)->isnull) |
1906 | 0 | ereport(ERROR, |
1907 | 0 | (errcode(ERRCODE_INVALID_ROW_COUNT_IN_LIMIT_CLAUSE), |
1908 | 0 | errmsg("row count cannot be null in FETCH FIRST ... WITH TIES clause"))); |
1909 | | |
1910 | 0 | return qual; |
1911 | 0 | } |
1912 | | |
1913 | | /* |
1914 | | * checkExprIsVarFree |
1915 | | * Check that given expr has no Vars of the current query level |
1916 | | * (aggregates and window functions should have been rejected already). |
1917 | | * |
1918 | | * This is used to check expressions that have to have a consistent value |
1919 | | * across all rows of the query, such as a LIMIT. Arguably it should reject |
1920 | | * volatile functions, too, but we don't do that --- whatever value the |
1921 | | * function gives on first execution is what you get. |
1922 | | * |
1923 | | * constructName does not affect the semantics, but is used in error messages |
1924 | | */ |
1925 | | static void |
1926 | | checkExprIsVarFree(ParseState *pstate, Node *n, const char *constructName) |
1927 | 0 | { |
1928 | 0 | if (contain_vars_of_level(n, 0)) |
1929 | 0 | { |
1930 | 0 | ereport(ERROR, |
1931 | 0 | (errcode(ERRCODE_INVALID_COLUMN_REFERENCE), |
1932 | | /* translator: %s is name of a SQL construct, eg LIMIT */ |
1933 | 0 | errmsg("argument of %s must not contain variables", |
1934 | 0 | constructName), |
1935 | 0 | parser_errposition(pstate, |
1936 | 0 | locate_var_of_level(n, 0)))); |
1937 | 0 | } |
1938 | 0 | } |
1939 | | |
1940 | | |
1941 | | /* |
1942 | | * checkTargetlistEntrySQL92 - |
1943 | | * Validate a targetlist entry found by findTargetlistEntrySQL92 |
1944 | | * |
1945 | | * When we select a pre-existing tlist entry as a result of syntax such |
1946 | | * as "GROUP BY 1", we have to make sure it is acceptable for use in the |
1947 | | * indicated clause type; transformExpr() will have treated it as a regular |
1948 | | * targetlist item. |
1949 | | */ |
1950 | | static void |
1951 | | checkTargetlistEntrySQL92(ParseState *pstate, TargetEntry *tle, |
1952 | | ParseExprKind exprKind) |
1953 | 0 | { |
1954 | 0 | switch (exprKind) |
1955 | 0 | { |
1956 | 0 | case EXPR_KIND_GROUP_BY: |
1957 | | /* reject aggregates and window functions */ |
1958 | 0 | if (pstate->p_hasAggs && |
1959 | 0 | contain_aggs_of_level((Node *) tle->expr, 0)) |
1960 | 0 | ereport(ERROR, |
1961 | 0 | (errcode(ERRCODE_GROUPING_ERROR), |
1962 | | /* translator: %s is name of a SQL construct, eg GROUP BY */ |
1963 | 0 | errmsg("aggregate functions are not allowed in %s", |
1964 | 0 | ParseExprKindName(exprKind)), |
1965 | 0 | parser_errposition(pstate, |
1966 | 0 | locate_agg_of_level((Node *) tle->expr, 0)))); |
1967 | 0 | if (pstate->p_hasWindowFuncs && |
1968 | 0 | contain_windowfuncs((Node *) tle->expr)) |
1969 | 0 | ereport(ERROR, |
1970 | 0 | (errcode(ERRCODE_WINDOWING_ERROR), |
1971 | | /* translator: %s is name of a SQL construct, eg GROUP BY */ |
1972 | 0 | errmsg("window functions are not allowed in %s", |
1973 | 0 | ParseExprKindName(exprKind)), |
1974 | 0 | parser_errposition(pstate, |
1975 | 0 | locate_windowfunc((Node *) tle->expr)))); |
1976 | 0 | break; |
1977 | 0 | case EXPR_KIND_ORDER_BY: |
1978 | | /* no extra checks needed */ |
1979 | 0 | break; |
1980 | 0 | case EXPR_KIND_DISTINCT_ON: |
1981 | | /* no extra checks needed */ |
1982 | 0 | break; |
1983 | 0 | default: |
1984 | 0 | elog(ERROR, "unexpected exprKind in checkTargetlistEntrySQL92"); |
1985 | 0 | break; |
1986 | 0 | } |
1987 | 0 | } |
1988 | | |
1989 | | /* |
1990 | | * findTargetlistEntrySQL92 - |
1991 | | * Returns the targetlist entry matching the given (untransformed) node. |
1992 | | * If no matching entry exists, one is created and appended to the target |
1993 | | * list as a "resjunk" node. |
1994 | | * |
1995 | | * This function supports the old SQL92 ORDER BY interpretation, where the |
1996 | | * expression is an output column name or number. If we fail to find a |
1997 | | * match of that sort, we fall through to the SQL99 rules. For historical |
1998 | | * reasons, Postgres also allows this interpretation for GROUP BY, though |
1999 | | * the standard never did. However, for GROUP BY we prefer a SQL99 match. |
2000 | | * This function is *not* used for WINDOW definitions. |
2001 | | * |
2002 | | * node the ORDER BY, GROUP BY, or DISTINCT ON expression to be matched |
2003 | | * tlist the target list (passed by reference so we can append to it) |
2004 | | * exprKind identifies clause type being processed |
2005 | | */ |
2006 | | static TargetEntry * |
2007 | | findTargetlistEntrySQL92(ParseState *pstate, Node *node, List **tlist, |
2008 | | ParseExprKind exprKind) |
2009 | 0 | { |
2010 | 0 | ListCell *tl; |
2011 | | |
2012 | | /*---------- |
2013 | | * Handle two special cases as mandated by the SQL92 spec: |
2014 | | * |
2015 | | * 1. Bare ColumnName (no qualifier or subscripts) |
2016 | | * For a bare identifier, we search for a matching column name |
2017 | | * in the existing target list. Multiple matches are an error |
2018 | | * unless they refer to identical values; for example, |
2019 | | * we allow SELECT a, a FROM table ORDER BY a |
2020 | | * but not SELECT a AS b, b FROM table ORDER BY b |
2021 | | * If no match is found, we fall through and treat the identifier |
2022 | | * as an expression. |
2023 | | * For GROUP BY, it is incorrect to match the grouping item against |
2024 | | * targetlist entries: according to SQL92, an identifier in GROUP BY |
2025 | | * is a reference to a column name exposed by FROM, not to a target |
2026 | | * list column. However, many implementations (including pre-7.0 |
2027 | | * PostgreSQL) accept this anyway. So for GROUP BY, we look first |
2028 | | * to see if the identifier matches any FROM column name, and only |
2029 | | * try for a targetlist name if it doesn't. This ensures that we |
2030 | | * adhere to the spec in the case where the name could be both. |
2031 | | * DISTINCT ON isn't in the standard, so we can do what we like there; |
2032 | | * we choose to make it work like ORDER BY, on the rather flimsy |
2033 | | * grounds that ordinary DISTINCT works on targetlist entries. |
2034 | | * |
2035 | | * 2. IntegerConstant |
2036 | | * This means to use the n'th item in the existing target list. |
2037 | | * Note that it would make no sense to order/group/distinct by an |
2038 | | * actual constant, so this does not create a conflict with SQL99. |
2039 | | * GROUP BY column-number is not allowed by SQL92, but since |
2040 | | * the standard has no other behavior defined for this syntax, |
2041 | | * we may as well accept this common extension. |
2042 | | * |
2043 | | * Note that pre-existing resjunk targets must not be used in either case, |
2044 | | * since the user didn't write them in his SELECT list. |
2045 | | * |
2046 | | * If neither special case applies, fall through to treat the item as |
2047 | | * an expression per SQL99. |
2048 | | *---------- |
2049 | | */ |
2050 | 0 | if (IsA(node, ColumnRef) && |
2051 | 0 | list_length(((ColumnRef *) node)->fields) == 1 && |
2052 | 0 | IsA(linitial(((ColumnRef *) node)->fields), String)) |
2053 | 0 | { |
2054 | 0 | char *name = strVal(linitial(((ColumnRef *) node)->fields)); |
2055 | 0 | int location = ((ColumnRef *) node)->location; |
2056 | |
|
2057 | 0 | if (exprKind == EXPR_KIND_GROUP_BY) |
2058 | 0 | { |
2059 | | /* |
2060 | | * In GROUP BY, we must prefer a match against a FROM-clause |
2061 | | * column to one against the targetlist. Look to see if there is |
2062 | | * a matching column. If so, fall through to use SQL99 rules. |
2063 | | * NOTE: if name could refer ambiguously to more than one column |
2064 | | * name exposed by FROM, colNameToVar will ereport(ERROR). That's |
2065 | | * just what we want here. |
2066 | | * |
2067 | | * Small tweak for 7.4.3: ignore matches in upper query levels. |
2068 | | * This effectively changes the search order for bare names to (1) |
2069 | | * local FROM variables, (2) local targetlist aliases, (3) outer |
2070 | | * FROM variables, whereas before it was (1) (3) (2). SQL92 and |
2071 | | * SQL99 do not allow GROUPing BY an outer reference, so this |
2072 | | * breaks no cases that are legal per spec, and it seems a more |
2073 | | * self-consistent behavior. |
2074 | | */ |
2075 | 0 | if (colNameToVar(pstate, name, true, location) != NULL) |
2076 | 0 | name = NULL; |
2077 | 0 | } |
2078 | |
|
2079 | 0 | if (name != NULL) |
2080 | 0 | { |
2081 | 0 | TargetEntry *target_result = NULL; |
2082 | |
|
2083 | 0 | foreach(tl, *tlist) |
2084 | 0 | { |
2085 | 0 | TargetEntry *tle = (TargetEntry *) lfirst(tl); |
2086 | |
|
2087 | 0 | if (!tle->resjunk && |
2088 | 0 | strcmp(tle->resname, name) == 0) |
2089 | 0 | { |
2090 | 0 | if (target_result != NULL) |
2091 | 0 | { |
2092 | 0 | if (!equal(target_result->expr, tle->expr)) |
2093 | 0 | ereport(ERROR, |
2094 | 0 | (errcode(ERRCODE_AMBIGUOUS_COLUMN), |
2095 | | |
2096 | | /*------ |
2097 | | translator: first %s is name of a SQL construct, eg ORDER BY */ |
2098 | 0 | errmsg("%s \"%s\" is ambiguous", |
2099 | 0 | ParseExprKindName(exprKind), |
2100 | 0 | name), |
2101 | 0 | parser_errposition(pstate, location))); |
2102 | 0 | } |
2103 | 0 | else |
2104 | 0 | target_result = tle; |
2105 | | /* Stay in loop to check for ambiguity */ |
2106 | 0 | } |
2107 | 0 | } |
2108 | 0 | if (target_result != NULL) |
2109 | 0 | { |
2110 | | /* return the first match, after suitable validation */ |
2111 | 0 | checkTargetlistEntrySQL92(pstate, target_result, exprKind); |
2112 | 0 | return target_result; |
2113 | 0 | } |
2114 | 0 | } |
2115 | 0 | } |
2116 | 0 | if (IsA(node, A_Const)) |
2117 | 0 | { |
2118 | 0 | A_Const *aconst = castNode(A_Const, node); |
2119 | 0 | int targetlist_pos = 0; |
2120 | 0 | int target_pos; |
2121 | |
|
2122 | 0 | if (!IsA(&aconst->val, Integer)) |
2123 | 0 | ereport(ERROR, |
2124 | 0 | (errcode(ERRCODE_SYNTAX_ERROR), |
2125 | | /* translator: %s is name of a SQL construct, eg ORDER BY */ |
2126 | 0 | errmsg("non-integer constant in %s", |
2127 | 0 | ParseExprKindName(exprKind)), |
2128 | 0 | parser_errposition(pstate, aconst->location))); |
2129 | | |
2130 | 0 | target_pos = intVal(&aconst->val); |
2131 | 0 | foreach(tl, *tlist) |
2132 | 0 | { |
2133 | 0 | TargetEntry *tle = (TargetEntry *) lfirst(tl); |
2134 | |
|
2135 | 0 | if (!tle->resjunk) |
2136 | 0 | { |
2137 | 0 | if (++targetlist_pos == target_pos) |
2138 | 0 | { |
2139 | | /* return the unique match, after suitable validation */ |
2140 | 0 | checkTargetlistEntrySQL92(pstate, tle, exprKind); |
2141 | 0 | return tle; |
2142 | 0 | } |
2143 | 0 | } |
2144 | 0 | } |
2145 | 0 | ereport(ERROR, |
2146 | 0 | (errcode(ERRCODE_INVALID_COLUMN_REFERENCE), |
2147 | | /* translator: %s is name of a SQL construct, eg ORDER BY */ |
2148 | 0 | errmsg("%s position %d is not in select list", |
2149 | 0 | ParseExprKindName(exprKind), target_pos), |
2150 | 0 | parser_errposition(pstate, aconst->location))); |
2151 | 0 | } |
2152 | | |
2153 | | /* |
2154 | | * Otherwise, we have an expression, so process it per SQL99 rules. |
2155 | | */ |
2156 | 0 | return findTargetlistEntrySQL99(pstate, node, tlist, exprKind); |
2157 | 0 | } |
2158 | | |
2159 | | /* |
2160 | | * findTargetlistEntrySQL99 - |
2161 | | * Returns the targetlist entry matching the given (untransformed) node. |
2162 | | * If no matching entry exists, one is created and appended to the target |
2163 | | * list as a "resjunk" node. |
2164 | | * |
2165 | | * This function supports the SQL99 interpretation, wherein the expression |
2166 | | * is just an ordinary expression referencing input column names. |
2167 | | * |
2168 | | * node the ORDER BY, GROUP BY, etc expression to be matched |
2169 | | * tlist the target list (passed by reference so we can append to it) |
2170 | | * exprKind identifies clause type being processed |
2171 | | */ |
2172 | | static TargetEntry * |
2173 | | findTargetlistEntrySQL99(ParseState *pstate, Node *node, List **tlist, |
2174 | | ParseExprKind exprKind) |
2175 | 0 | { |
2176 | 0 | TargetEntry *target_result; |
2177 | 0 | ListCell *tl; |
2178 | 0 | Node *expr; |
2179 | | |
2180 | | /* |
2181 | | * Convert the untransformed node to a transformed expression, and search |
2182 | | * for a match in the tlist. NOTE: it doesn't really matter whether there |
2183 | | * is more than one match. Also, we are willing to match an existing |
2184 | | * resjunk target here, though the SQL92 cases above must ignore resjunk |
2185 | | * targets. |
2186 | | */ |
2187 | 0 | expr = transformExpr(pstate, node, exprKind); |
2188 | |
|
2189 | 0 | foreach(tl, *tlist) |
2190 | 0 | { |
2191 | 0 | TargetEntry *tle = (TargetEntry *) lfirst(tl); |
2192 | 0 | Node *texpr; |
2193 | | |
2194 | | /* |
2195 | | * Ignore any implicit cast on the existing tlist expression. |
2196 | | * |
2197 | | * This essentially allows the ORDER/GROUP/etc item to adopt the same |
2198 | | * datatype previously selected for a textually-equivalent tlist item. |
2199 | | * There can't be any implicit cast at top level in an ordinary SELECT |
2200 | | * tlist at this stage, but the case does arise with ORDER BY in an |
2201 | | * aggregate function. |
2202 | | */ |
2203 | 0 | texpr = strip_implicit_coercions((Node *) tle->expr); |
2204 | |
|
2205 | 0 | if (equal(expr, texpr)) |
2206 | 0 | return tle; |
2207 | 0 | } |
2208 | | |
2209 | | /* |
2210 | | * If no matches, construct a new target entry which is appended to the |
2211 | | * end of the target list. This target is given resjunk = true so that it |
2212 | | * will not be projected into the final tuple. |
2213 | | */ |
2214 | 0 | target_result = transformTargetEntry(pstate, node, expr, exprKind, |
2215 | 0 | NULL, true); |
2216 | |
|
2217 | 0 | *tlist = lappend(*tlist, target_result); |
2218 | |
|
2219 | 0 | return target_result; |
2220 | 0 | } |
2221 | | |
2222 | | /*------------------------------------------------------------------------- |
2223 | | * Flatten out parenthesized sublists in grouping lists, and some cases |
2224 | | * of nested grouping sets. |
2225 | | * |
2226 | | * Inside a grouping set (ROLLUP, CUBE, or GROUPING SETS), we expect the |
2227 | | * content to be nested no more than 2 deep: i.e. ROLLUP((a,b),(c,d)) is |
2228 | | * ok, but ROLLUP((a,(b,c)),d) is flattened to ((a,b,c),d), which we then |
2229 | | * (later) normalize to ((a,b,c),(d)). |
2230 | | * |
2231 | | * CUBE or ROLLUP can be nested inside GROUPING SETS (but not the reverse), |
2232 | | * and we leave that alone if we find it. But if we see GROUPING SETS inside |
2233 | | * GROUPING SETS, we can flatten and normalize as follows: |
2234 | | * GROUPING SETS (a, (b,c), GROUPING SETS ((c,d),(e)), (f,g)) |
2235 | | * becomes |
2236 | | * GROUPING SETS ((a), (b,c), (c,d), (e), (f,g)) |
2237 | | * |
2238 | | * This is per the spec's syntax transformations, but these are the only such |
2239 | | * transformations we do in parse analysis, so that queries retain the |
2240 | | * originally specified grouping set syntax for CUBE and ROLLUP as much as |
2241 | | * possible when deparsed. (Full expansion of the result into a list of |
2242 | | * grouping sets is left to the planner.) |
2243 | | * |
2244 | | * When we're done, the resulting list should contain only these possible |
2245 | | * elements: |
2246 | | * - an expression |
2247 | | * - a CUBE or ROLLUP with a list of expressions nested 2 deep |
2248 | | * - a GROUPING SET containing any of: |
2249 | | * - expression lists |
2250 | | * - empty grouping sets |
2251 | | * - CUBE or ROLLUP nodes with lists nested 2 deep |
2252 | | * The return is a new list, but doesn't deep-copy the old nodes except for |
2253 | | * GroupingSet nodes. |
2254 | | * |
2255 | | * As a side effect, flag whether the list has any GroupingSet nodes. |
2256 | | *------------------------------------------------------------------------- |
2257 | | */ |
2258 | | static Node * |
2259 | | flatten_grouping_sets(Node *expr, bool toplevel, bool *hasGroupingSets) |
2260 | 0 | { |
2261 | | /* just in case of pathological input */ |
2262 | 0 | check_stack_depth(); |
2263 | |
|
2264 | 0 | if (expr == (Node *) NIL) |
2265 | 0 | return (Node *) NIL; |
2266 | | |
2267 | 0 | switch (expr->type) |
2268 | 0 | { |
2269 | 0 | case T_RowExpr: |
2270 | 0 | { |
2271 | 0 | RowExpr *r = (RowExpr *) expr; |
2272 | |
|
2273 | 0 | if (r->row_format == COERCE_IMPLICIT_CAST) |
2274 | 0 | return flatten_grouping_sets((Node *) r->args, |
2275 | 0 | false, NULL); |
2276 | 0 | } |
2277 | 0 | break; |
2278 | 0 | case T_GroupingSet: |
2279 | 0 | { |
2280 | 0 | GroupingSet *gset = (GroupingSet *) expr; |
2281 | 0 | ListCell *l2; |
2282 | 0 | List *result_set = NIL; |
2283 | |
|
2284 | 0 | if (hasGroupingSets) |
2285 | 0 | *hasGroupingSets = true; |
2286 | | |
2287 | | /* |
2288 | | * at the top level, we skip over all empty grouping sets; the |
2289 | | * caller can supply the canonical GROUP BY () if nothing is |
2290 | | * left. |
2291 | | */ |
2292 | |
|
2293 | 0 | if (toplevel && gset->kind == GROUPING_SET_EMPTY) |
2294 | 0 | return (Node *) NIL; |
2295 | | |
2296 | 0 | foreach(l2, gset->content) |
2297 | 0 | { |
2298 | 0 | Node *n1 = lfirst(l2); |
2299 | 0 | Node *n2 = flatten_grouping_sets(n1, false, NULL); |
2300 | |
|
2301 | 0 | if (IsA(n1, GroupingSet) && |
2302 | 0 | ((GroupingSet *) n1)->kind == GROUPING_SET_SETS) |
2303 | 0 | result_set = list_concat(result_set, (List *) n2); |
2304 | 0 | else |
2305 | 0 | result_set = lappend(result_set, n2); |
2306 | 0 | } |
2307 | | |
2308 | | /* |
2309 | | * At top level, keep the grouping set node; but if we're in a |
2310 | | * nested grouping set, then we need to concat the flattened |
2311 | | * result into the outer list if it's simply nested. |
2312 | | */ |
2313 | |
|
2314 | 0 | if (toplevel || (gset->kind != GROUPING_SET_SETS)) |
2315 | 0 | { |
2316 | 0 | return (Node *) makeGroupingSet(gset->kind, result_set, gset->location); |
2317 | 0 | } |
2318 | 0 | else |
2319 | 0 | return (Node *) result_set; |
2320 | 0 | } |
2321 | 0 | case T_List: |
2322 | 0 | { |
2323 | 0 | List *result = NIL; |
2324 | 0 | ListCell *l; |
2325 | |
|
2326 | 0 | foreach(l, (List *) expr) |
2327 | 0 | { |
2328 | 0 | Node *n = flatten_grouping_sets(lfirst(l), toplevel, hasGroupingSets); |
2329 | |
|
2330 | 0 | if (n != (Node *) NIL) |
2331 | 0 | { |
2332 | 0 | if (IsA(n, List)) |
2333 | 0 | result = list_concat(result, (List *) n); |
2334 | 0 | else |
2335 | 0 | result = lappend(result, n); |
2336 | 0 | } |
2337 | 0 | } |
2338 | |
|
2339 | 0 | return (Node *) result; |
2340 | 0 | } |
2341 | 0 | default: |
2342 | 0 | break; |
2343 | 0 | } |
2344 | | |
2345 | 0 | return expr; |
2346 | 0 | } |
2347 | | |
2348 | | /* |
2349 | | * Transform a single expression within a GROUP BY clause or grouping set. |
2350 | | * |
2351 | | * The expression is added to the targetlist if not already present, and to the |
2352 | | * flatresult list (which will become the groupClause) if not already present |
2353 | | * there. The sortClause is consulted for operator and sort order hints. |
2354 | | * |
2355 | | * Returns the ressortgroupref of the expression. |
2356 | | * |
2357 | | * flatresult reference to flat list of SortGroupClause nodes |
2358 | | * seen_local bitmapset of sortgrouprefs already seen at the local level |
2359 | | * pstate ParseState |
2360 | | * gexpr node to transform |
2361 | | * targetlist reference to TargetEntry list |
2362 | | * sortClause ORDER BY clause (SortGroupClause nodes) |
2363 | | * exprKind expression kind |
2364 | | * useSQL99 SQL99 rather than SQL92 syntax |
2365 | | * toplevel false if within any grouping set |
2366 | | */ |
2367 | | static Index |
2368 | | transformGroupClauseExpr(List **flatresult, Bitmapset *seen_local, |
2369 | | ParseState *pstate, Node *gexpr, |
2370 | | List **targetlist, List *sortClause, |
2371 | | ParseExprKind exprKind, bool useSQL99, bool toplevel) |
2372 | 0 | { |
2373 | 0 | TargetEntry *tle; |
2374 | 0 | bool found = false; |
2375 | |
|
2376 | 0 | if (useSQL99) |
2377 | 0 | tle = findTargetlistEntrySQL99(pstate, gexpr, |
2378 | 0 | targetlist, exprKind); |
2379 | 0 | else |
2380 | 0 | tle = findTargetlistEntrySQL92(pstate, gexpr, |
2381 | 0 | targetlist, exprKind); |
2382 | |
|
2383 | 0 | if (tle->ressortgroupref > 0) |
2384 | 0 | { |
2385 | 0 | ListCell *sl; |
2386 | | |
2387 | | /* |
2388 | | * Eliminate duplicates (GROUP BY x, x) but only at local level. |
2389 | | * (Duplicates in grouping sets can affect the number of returned |
2390 | | * rows, so can't be dropped indiscriminately.) |
2391 | | * |
2392 | | * Since we don't care about anything except the sortgroupref, we can |
2393 | | * use a bitmapset rather than scanning lists. |
2394 | | */ |
2395 | 0 | if (bms_is_member(tle->ressortgroupref, seen_local)) |
2396 | 0 | return 0; |
2397 | | |
2398 | | /* |
2399 | | * If we're already in the flat clause list, we don't need to consider |
2400 | | * adding ourselves again. |
2401 | | */ |
2402 | 0 | found = targetIsInSortList(tle, InvalidOid, *flatresult); |
2403 | 0 | if (found) |
2404 | 0 | return tle->ressortgroupref; |
2405 | | |
2406 | | /* |
2407 | | * If the GROUP BY tlist entry also appears in ORDER BY, copy operator |
2408 | | * info from the (first) matching ORDER BY item. This means that if |
2409 | | * you write something like "GROUP BY foo ORDER BY foo USING <<<", the |
2410 | | * GROUP BY operation silently takes on the equality semantics implied |
2411 | | * by the ORDER BY. There are two reasons to do this: it improves the |
2412 | | * odds that we can implement both GROUP BY and ORDER BY with a single |
2413 | | * sort step, and it allows the user to choose the equality semantics |
2414 | | * used by GROUP BY, should she be working with a datatype that has |
2415 | | * more than one equality operator. |
2416 | | * |
2417 | | * If we're in a grouping set, though, we force our requested ordering |
2418 | | * to be NULLS LAST, because if we have any hope of using a sorted agg |
2419 | | * for the job, we're going to be tacking on generated NULL values |
2420 | | * after the corresponding groups. If the user demands nulls first, |
2421 | | * another sort step is going to be inevitable, but that's the |
2422 | | * planner's problem. |
2423 | | */ |
2424 | | |
2425 | 0 | foreach(sl, sortClause) |
2426 | 0 | { |
2427 | 0 | SortGroupClause *sc = (SortGroupClause *) lfirst(sl); |
2428 | |
|
2429 | 0 | if (sc->tleSortGroupRef == tle->ressortgroupref) |
2430 | 0 | { |
2431 | 0 | SortGroupClause *grpc = copyObject(sc); |
2432 | |
|
2433 | 0 | if (!toplevel) |
2434 | 0 | grpc->nulls_first = false; |
2435 | 0 | *flatresult = lappend(*flatresult, grpc); |
2436 | 0 | found = true; |
2437 | 0 | break; |
2438 | 0 | } |
2439 | 0 | } |
2440 | 0 | } |
2441 | | |
2442 | | /* |
2443 | | * If no match in ORDER BY, just add it to the result using default |
2444 | | * sort/group semantics. |
2445 | | */ |
2446 | 0 | if (!found) |
2447 | 0 | *flatresult = addTargetToGroupList(pstate, tle, |
2448 | 0 | *flatresult, *targetlist, |
2449 | 0 | exprLocation(gexpr)); |
2450 | | |
2451 | | /* |
2452 | | * _something_ must have assigned us a sortgroupref by now... |
2453 | | */ |
2454 | |
|
2455 | 0 | return tle->ressortgroupref; |
2456 | 0 | } |
2457 | | |
2458 | | /* |
2459 | | * Transform a list of expressions within a GROUP BY clause or grouping set. |
2460 | | * |
2461 | | * The list of expressions belongs to a single clause within which duplicates |
2462 | | * can be safely eliminated. |
2463 | | * |
2464 | | * Returns an integer list of ressortgroupref values. |
2465 | | * |
2466 | | * flatresult reference to flat list of SortGroupClause nodes |
2467 | | * pstate ParseState |
2468 | | * list nodes to transform |
2469 | | * targetlist reference to TargetEntry list |
2470 | | * sortClause ORDER BY clause (SortGroupClause nodes) |
2471 | | * exprKind expression kind |
2472 | | * useSQL99 SQL99 rather than SQL92 syntax |
2473 | | * toplevel false if within any grouping set |
2474 | | */ |
2475 | | static List * |
2476 | | transformGroupClauseList(List **flatresult, |
2477 | | ParseState *pstate, List *list, |
2478 | | List **targetlist, List *sortClause, |
2479 | | ParseExprKind exprKind, bool useSQL99, bool toplevel) |
2480 | 0 | { |
2481 | 0 | Bitmapset *seen_local = NULL; |
2482 | 0 | List *result = NIL; |
2483 | 0 | ListCell *gl; |
2484 | |
|
2485 | 0 | foreach(gl, list) |
2486 | 0 | { |
2487 | 0 | Node *gexpr = (Node *) lfirst(gl); |
2488 | |
|
2489 | 0 | Index ref = transformGroupClauseExpr(flatresult, |
2490 | 0 | seen_local, |
2491 | 0 | pstate, |
2492 | 0 | gexpr, |
2493 | 0 | targetlist, |
2494 | 0 | sortClause, |
2495 | 0 | exprKind, |
2496 | 0 | useSQL99, |
2497 | 0 | toplevel); |
2498 | |
|
2499 | 0 | if (ref > 0) |
2500 | 0 | { |
2501 | 0 | seen_local = bms_add_member(seen_local, ref); |
2502 | 0 | result = lappend_int(result, ref); |
2503 | 0 | } |
2504 | 0 | } |
2505 | |
|
2506 | 0 | return result; |
2507 | 0 | } |
2508 | | |
2509 | | /* |
2510 | | * Transform a grouping set and (recursively) its content. |
2511 | | * |
2512 | | * The grouping set might be a GROUPING SETS node with other grouping sets |
2513 | | * inside it, but SETS within SETS have already been flattened out before |
2514 | | * reaching here. |
2515 | | * |
2516 | | * Returns the transformed node, which now contains SIMPLE nodes with lists |
2517 | | * of ressortgrouprefs rather than expressions. |
2518 | | * |
2519 | | * flatresult reference to flat list of SortGroupClause nodes |
2520 | | * pstate ParseState |
2521 | | * gset grouping set to transform |
2522 | | * targetlist reference to TargetEntry list |
2523 | | * sortClause ORDER BY clause (SortGroupClause nodes) |
2524 | | * exprKind expression kind |
2525 | | * useSQL99 SQL99 rather than SQL92 syntax |
2526 | | * toplevel false if within any grouping set |
2527 | | */ |
2528 | | static Node * |
2529 | | transformGroupingSet(List **flatresult, |
2530 | | ParseState *pstate, GroupingSet *gset, |
2531 | | List **targetlist, List *sortClause, |
2532 | | ParseExprKind exprKind, bool useSQL99, bool toplevel) |
2533 | 0 | { |
2534 | 0 | ListCell *gl; |
2535 | 0 | List *content = NIL; |
2536 | |
|
2537 | 0 | Assert(toplevel || gset->kind != GROUPING_SET_SETS); |
2538 | |
|
2539 | 0 | foreach(gl, gset->content) |
2540 | 0 | { |
2541 | 0 | Node *n = lfirst(gl); |
2542 | |
|
2543 | 0 | if (IsA(n, List)) |
2544 | 0 | { |
2545 | 0 | List *l = transformGroupClauseList(flatresult, |
2546 | 0 | pstate, (List *) n, |
2547 | 0 | targetlist, sortClause, |
2548 | 0 | exprKind, useSQL99, false); |
2549 | |
|
2550 | 0 | content = lappend(content, makeGroupingSet(GROUPING_SET_SIMPLE, |
2551 | 0 | l, |
2552 | 0 | exprLocation(n))); |
2553 | 0 | } |
2554 | 0 | else if (IsA(n, GroupingSet)) |
2555 | 0 | { |
2556 | 0 | GroupingSet *gset2 = (GroupingSet *) lfirst(gl); |
2557 | |
|
2558 | 0 | content = lappend(content, transformGroupingSet(flatresult, |
2559 | 0 | pstate, gset2, |
2560 | 0 | targetlist, sortClause, |
2561 | 0 | exprKind, useSQL99, false)); |
2562 | 0 | } |
2563 | 0 | else |
2564 | 0 | { |
2565 | 0 | Index ref = transformGroupClauseExpr(flatresult, |
2566 | 0 | NULL, |
2567 | 0 | pstate, |
2568 | 0 | n, |
2569 | 0 | targetlist, |
2570 | 0 | sortClause, |
2571 | 0 | exprKind, |
2572 | 0 | useSQL99, |
2573 | 0 | false); |
2574 | |
|
2575 | 0 | content = lappend(content, makeGroupingSet(GROUPING_SET_SIMPLE, |
2576 | 0 | list_make1_int(ref), |
2577 | 0 | exprLocation(n))); |
2578 | 0 | } |
2579 | 0 | } |
2580 | | |
2581 | | /* Arbitrarily cap the size of CUBE, which has exponential growth */ |
2582 | 0 | if (gset->kind == GROUPING_SET_CUBE) |
2583 | 0 | { |
2584 | 0 | if (list_length(content) > 12) |
2585 | 0 | ereport(ERROR, |
2586 | 0 | (errcode(ERRCODE_TOO_MANY_COLUMNS), |
2587 | 0 | errmsg("CUBE is limited to 12 elements"), |
2588 | 0 | parser_errposition(pstate, gset->location))); |
2589 | 0 | } |
2590 | | |
2591 | 0 | return (Node *) makeGroupingSet(gset->kind, content, gset->location); |
2592 | 0 | } |
2593 | | |
2594 | | |
2595 | | /* |
2596 | | * transformGroupClause - |
2597 | | * transform a GROUP BY clause |
2598 | | * |
2599 | | * GROUP BY items will be added to the targetlist (as resjunk columns) |
2600 | | * if not already present, so the targetlist must be passed by reference. |
2601 | | * |
2602 | | * This is also used for window PARTITION BY clauses (which act almost the |
2603 | | * same, but are always interpreted per SQL99 rules). |
2604 | | * |
2605 | | * Grouping sets make this a lot more complex than it was. Our goal here is |
2606 | | * twofold: we make a flat list of SortGroupClause nodes referencing each |
2607 | | * distinct expression used for grouping, with those expressions added to the |
2608 | | * targetlist if needed. At the same time, we build the groupingSets tree, |
2609 | | * which stores only ressortgrouprefs as integer lists inside GroupingSet nodes |
2610 | | * (possibly nested, but limited in depth: a GROUPING_SET_SETS node can contain |
2611 | | * nested SIMPLE, CUBE or ROLLUP nodes, but not more sets - we flatten that |
2612 | | * out; while CUBE and ROLLUP can contain only SIMPLE nodes). |
2613 | | * |
2614 | | * We skip much of the hard work if there are no grouping sets. |
2615 | | * |
2616 | | * One subtlety is that the groupClause list can end up empty while the |
2617 | | * groupingSets list is not; this happens if there are only empty grouping |
2618 | | * sets, or an explicit GROUP BY (). This has the same effect as specifying |
2619 | | * aggregates or a HAVING clause with no GROUP BY; the output is one row per |
2620 | | * grouping set even if the input is empty. |
2621 | | * |
2622 | | * Returns the transformed (flat) groupClause. |
2623 | | * |
2624 | | * pstate ParseState |
2625 | | * grouplist clause to transform |
2626 | | * groupingSets reference to list to contain the grouping set tree |
2627 | | * targetlist reference to TargetEntry list |
2628 | | * sortClause ORDER BY clause (SortGroupClause nodes) |
2629 | | * exprKind expression kind |
2630 | | * useSQL99 SQL99 rather than SQL92 syntax |
2631 | | */ |
2632 | | List * |
2633 | | transformGroupClause(ParseState *pstate, List *grouplist, List **groupingSets, |
2634 | | List **targetlist, List *sortClause, |
2635 | | ParseExprKind exprKind, bool useSQL99) |
2636 | 0 | { |
2637 | 0 | List *result = NIL; |
2638 | 0 | List *flat_grouplist; |
2639 | 0 | List *gsets = NIL; |
2640 | 0 | ListCell *gl; |
2641 | 0 | bool hasGroupingSets = false; |
2642 | 0 | Bitmapset *seen_local = NULL; |
2643 | | |
2644 | | /* |
2645 | | * Recursively flatten implicit RowExprs. (Technically this is only needed |
2646 | | * for GROUP BY, per the syntax rules for grouping sets, but we do it |
2647 | | * anyway.) |
2648 | | */ |
2649 | 0 | flat_grouplist = (List *) flatten_grouping_sets((Node *) grouplist, |
2650 | 0 | true, |
2651 | 0 | &hasGroupingSets); |
2652 | | |
2653 | | /* |
2654 | | * If the list is now empty, but hasGroupingSets is true, it's because we |
2655 | | * elided redundant empty grouping sets. Restore a single empty grouping |
2656 | | * set to leave a canonical form: GROUP BY () |
2657 | | */ |
2658 | |
|
2659 | 0 | if (flat_grouplist == NIL && hasGroupingSets) |
2660 | 0 | { |
2661 | 0 | flat_grouplist = list_make1(makeGroupingSet(GROUPING_SET_EMPTY, |
2662 | 0 | NIL, |
2663 | 0 | exprLocation((Node *) grouplist))); |
2664 | 0 | } |
2665 | |
|
2666 | 0 | foreach(gl, flat_grouplist) |
2667 | 0 | { |
2668 | 0 | Node *gexpr = (Node *) lfirst(gl); |
2669 | |
|
2670 | 0 | if (IsA(gexpr, GroupingSet)) |
2671 | 0 | { |
2672 | 0 | GroupingSet *gset = (GroupingSet *) gexpr; |
2673 | |
|
2674 | 0 | switch (gset->kind) |
2675 | 0 | { |
2676 | 0 | case GROUPING_SET_EMPTY: |
2677 | 0 | gsets = lappend(gsets, gset); |
2678 | 0 | break; |
2679 | 0 | case GROUPING_SET_SIMPLE: |
2680 | | /* can't happen */ |
2681 | 0 | Assert(false); |
2682 | 0 | break; |
2683 | 0 | case GROUPING_SET_SETS: |
2684 | 0 | case GROUPING_SET_CUBE: |
2685 | 0 | case GROUPING_SET_ROLLUP: |
2686 | 0 | gsets = lappend(gsets, |
2687 | 0 | transformGroupingSet(&result, |
2688 | 0 | pstate, gset, |
2689 | 0 | targetlist, sortClause, |
2690 | 0 | exprKind, useSQL99, true)); |
2691 | 0 | break; |
2692 | 0 | } |
2693 | 0 | } |
2694 | 0 | else |
2695 | 0 | { |
2696 | 0 | Index ref = transformGroupClauseExpr(&result, seen_local, |
2697 | 0 | pstate, gexpr, |
2698 | 0 | targetlist, sortClause, |
2699 | 0 | exprKind, useSQL99, true); |
2700 | |
|
2701 | 0 | if (ref > 0) |
2702 | 0 | { |
2703 | 0 | seen_local = bms_add_member(seen_local, ref); |
2704 | 0 | if (hasGroupingSets) |
2705 | 0 | gsets = lappend(gsets, |
2706 | 0 | makeGroupingSet(GROUPING_SET_SIMPLE, |
2707 | 0 | list_make1_int(ref), |
2708 | 0 | exprLocation(gexpr))); |
2709 | 0 | } |
2710 | 0 | } |
2711 | 0 | } |
2712 | | |
2713 | | /* parser should prevent this */ |
2714 | 0 | Assert(gsets == NIL || groupingSets != NULL); |
2715 | |
|
2716 | 0 | if (groupingSets) |
2717 | 0 | *groupingSets = gsets; |
2718 | |
|
2719 | 0 | return result; |
2720 | 0 | } |
2721 | | |
2722 | | /* |
2723 | | * transformSortClause - |
2724 | | * transform an ORDER BY clause |
2725 | | * |
2726 | | * ORDER BY items will be added to the targetlist (as resjunk columns) |
2727 | | * if not already present, so the targetlist must be passed by reference. |
2728 | | * |
2729 | | * This is also used for window and aggregate ORDER BY clauses (which act |
2730 | | * almost the same, but are always interpreted per SQL99 rules). |
2731 | | */ |
2732 | | List * |
2733 | | transformSortClause(ParseState *pstate, |
2734 | | List *orderlist, |
2735 | | List **targetlist, |
2736 | | ParseExprKind exprKind, |
2737 | | bool useSQL99) |
2738 | 0 | { |
2739 | 0 | List *sortlist = NIL; |
2740 | 0 | ListCell *olitem; |
2741 | |
|
2742 | 0 | foreach(olitem, orderlist) |
2743 | 0 | { |
2744 | 0 | SortBy *sortby = (SortBy *) lfirst(olitem); |
2745 | 0 | TargetEntry *tle; |
2746 | |
|
2747 | 0 | if (useSQL99) |
2748 | 0 | tle = findTargetlistEntrySQL99(pstate, sortby->node, |
2749 | 0 | targetlist, exprKind); |
2750 | 0 | else |
2751 | 0 | tle = findTargetlistEntrySQL92(pstate, sortby->node, |
2752 | 0 | targetlist, exprKind); |
2753 | |
|
2754 | 0 | sortlist = addTargetToSortList(pstate, tle, |
2755 | 0 | sortlist, *targetlist, sortby); |
2756 | 0 | } |
2757 | |
|
2758 | 0 | return sortlist; |
2759 | 0 | } |
2760 | | |
2761 | | /* |
2762 | | * transformWindowDefinitions - |
2763 | | * transform window definitions (WindowDef to WindowClause) |
2764 | | */ |
2765 | | List * |
2766 | | transformWindowDefinitions(ParseState *pstate, |
2767 | | List *windowdefs, |
2768 | | List **targetlist) |
2769 | 0 | { |
2770 | 0 | List *result = NIL; |
2771 | 0 | Index winref = 0; |
2772 | 0 | ListCell *lc; |
2773 | |
|
2774 | 0 | foreach(lc, windowdefs) |
2775 | 0 | { |
2776 | 0 | WindowDef *windef = (WindowDef *) lfirst(lc); |
2777 | 0 | WindowClause *refwc = NULL; |
2778 | 0 | List *partitionClause; |
2779 | 0 | List *orderClause; |
2780 | 0 | Oid rangeopfamily = InvalidOid; |
2781 | 0 | Oid rangeopcintype = InvalidOid; |
2782 | 0 | WindowClause *wc; |
2783 | |
|
2784 | 0 | winref++; |
2785 | | |
2786 | | /* |
2787 | | * Check for duplicate window names. |
2788 | | */ |
2789 | 0 | if (windef->name && |
2790 | 0 | findWindowClause(result, windef->name) != NULL) |
2791 | 0 | ereport(ERROR, |
2792 | 0 | (errcode(ERRCODE_WINDOWING_ERROR), |
2793 | 0 | errmsg("window \"%s\" is already defined", windef->name), |
2794 | 0 | parser_errposition(pstate, windef->location))); |
2795 | | |
2796 | | /* |
2797 | | * If it references a previous window, look that up. |
2798 | | */ |
2799 | 0 | if (windef->refname) |
2800 | 0 | { |
2801 | 0 | refwc = findWindowClause(result, windef->refname); |
2802 | 0 | if (refwc == NULL) |
2803 | 0 | ereport(ERROR, |
2804 | 0 | (errcode(ERRCODE_UNDEFINED_OBJECT), |
2805 | 0 | errmsg("window \"%s\" does not exist", |
2806 | 0 | windef->refname), |
2807 | 0 | parser_errposition(pstate, windef->location))); |
2808 | 0 | } |
2809 | | |
2810 | | /* |
2811 | | * Transform PARTITION and ORDER specs, if any. These are treated |
2812 | | * almost exactly like top-level GROUP BY and ORDER BY clauses, |
2813 | | * including the special handling of nondefault operator semantics. |
2814 | | */ |
2815 | 0 | orderClause = transformSortClause(pstate, |
2816 | 0 | windef->orderClause, |
2817 | 0 | targetlist, |
2818 | 0 | EXPR_KIND_WINDOW_ORDER, |
2819 | 0 | true /* force SQL99 rules */ ); |
2820 | 0 | partitionClause = transformGroupClause(pstate, |
2821 | 0 | windef->partitionClause, |
2822 | 0 | NULL, |
2823 | 0 | targetlist, |
2824 | 0 | orderClause, |
2825 | 0 | EXPR_KIND_WINDOW_PARTITION, |
2826 | 0 | true /* force SQL99 rules */ ); |
2827 | | |
2828 | | /* |
2829 | | * And prepare the new WindowClause. |
2830 | | */ |
2831 | 0 | wc = makeNode(WindowClause); |
2832 | 0 | wc->name = windef->name; |
2833 | 0 | wc->refname = windef->refname; |
2834 | | |
2835 | | /* |
2836 | | * Per spec, a windowdef that references a previous one copies the |
2837 | | * previous partition clause (and mustn't specify its own). It can |
2838 | | * specify its own ordering clause, but only if the previous one had |
2839 | | * none. It always specifies its own frame clause, and the previous |
2840 | | * one must not have a frame clause. Yeah, it's bizarre that each of |
2841 | | * these cases works differently, but SQL:2008 says so; see 7.11 |
2842 | | * <window clause> syntax rule 10 and general rule 1. The frame |
2843 | | * clause rule is especially bizarre because it makes "OVER foo" |
2844 | | * different from "OVER (foo)", and requires the latter to throw an |
2845 | | * error if foo has a nondefault frame clause. Well, ours not to |
2846 | | * reason why, but we do go out of our way to throw a useful error |
2847 | | * message for such cases. |
2848 | | */ |
2849 | 0 | if (refwc) |
2850 | 0 | { |
2851 | 0 | if (partitionClause) |
2852 | 0 | ereport(ERROR, |
2853 | 0 | (errcode(ERRCODE_WINDOWING_ERROR), |
2854 | 0 | errmsg("cannot override PARTITION BY clause of window \"%s\"", |
2855 | 0 | windef->refname), |
2856 | 0 | parser_errposition(pstate, windef->location))); |
2857 | 0 | wc->partitionClause = copyObject(refwc->partitionClause); |
2858 | 0 | } |
2859 | 0 | else |
2860 | 0 | wc->partitionClause = partitionClause; |
2861 | 0 | if (refwc) |
2862 | 0 | { |
2863 | 0 | if (orderClause && refwc->orderClause) |
2864 | 0 | ereport(ERROR, |
2865 | 0 | (errcode(ERRCODE_WINDOWING_ERROR), |
2866 | 0 | errmsg("cannot override ORDER BY clause of window \"%s\"", |
2867 | 0 | windef->refname), |
2868 | 0 | parser_errposition(pstate, windef->location))); |
2869 | 0 | if (orderClause) |
2870 | 0 | { |
2871 | 0 | wc->orderClause = orderClause; |
2872 | 0 | wc->copiedOrder = false; |
2873 | 0 | } |
2874 | 0 | else |
2875 | 0 | { |
2876 | 0 | wc->orderClause = copyObject(refwc->orderClause); |
2877 | 0 | wc->copiedOrder = true; |
2878 | 0 | } |
2879 | 0 | } |
2880 | 0 | else |
2881 | 0 | { |
2882 | 0 | wc->orderClause = orderClause; |
2883 | 0 | wc->copiedOrder = false; |
2884 | 0 | } |
2885 | 0 | if (refwc && refwc->frameOptions != FRAMEOPTION_DEFAULTS) |
2886 | 0 | { |
2887 | | /* |
2888 | | * Use this message if this is a WINDOW clause, or if it's an OVER |
2889 | | * clause that includes ORDER BY or framing clauses. (We already |
2890 | | * rejected PARTITION BY above, so no need to check that.) |
2891 | | */ |
2892 | 0 | if (windef->name || |
2893 | 0 | orderClause || windef->frameOptions != FRAMEOPTION_DEFAULTS) |
2894 | 0 | ereport(ERROR, |
2895 | 0 | (errcode(ERRCODE_WINDOWING_ERROR), |
2896 | 0 | errmsg("cannot copy window \"%s\" because it has a frame clause", |
2897 | 0 | windef->refname), |
2898 | 0 | parser_errposition(pstate, windef->location))); |
2899 | | /* Else this clause is just OVER (foo), so say this: */ |
2900 | 0 | ereport(ERROR, |
2901 | 0 | (errcode(ERRCODE_WINDOWING_ERROR), |
2902 | 0 | errmsg("cannot copy window \"%s\" because it has a frame clause", |
2903 | 0 | windef->refname), |
2904 | 0 | errhint("Omit the parentheses in this OVER clause."), |
2905 | 0 | parser_errposition(pstate, windef->location))); |
2906 | 0 | } |
2907 | 0 | wc->frameOptions = windef->frameOptions; |
2908 | | |
2909 | | /* |
2910 | | * RANGE offset PRECEDING/FOLLOWING requires exactly one ORDER BY |
2911 | | * column; check that and get its sort opfamily info. |
2912 | | */ |
2913 | 0 | if ((wc->frameOptions & FRAMEOPTION_RANGE) && |
2914 | 0 | (wc->frameOptions & (FRAMEOPTION_START_OFFSET | |
2915 | 0 | FRAMEOPTION_END_OFFSET))) |
2916 | 0 | { |
2917 | 0 | SortGroupClause *sortcl; |
2918 | 0 | Node *sortkey; |
2919 | 0 | CompareType rangecmptype; |
2920 | |
|
2921 | 0 | if (list_length(wc->orderClause) != 1) |
2922 | 0 | ereport(ERROR, |
2923 | 0 | (errcode(ERRCODE_WINDOWING_ERROR), |
2924 | 0 | errmsg("RANGE with offset PRECEDING/FOLLOWING requires exactly one ORDER BY column"), |
2925 | 0 | parser_errposition(pstate, windef->location))); |
2926 | 0 | sortcl = linitial_node(SortGroupClause, wc->orderClause); |
2927 | 0 | sortkey = get_sortgroupclause_expr(sortcl, *targetlist); |
2928 | | /* Find the sort operator in pg_amop */ |
2929 | 0 | if (!get_ordering_op_properties(sortcl->sortop, |
2930 | 0 | &rangeopfamily, |
2931 | 0 | &rangeopcintype, |
2932 | 0 | &rangecmptype)) |
2933 | 0 | elog(ERROR, "operator %u is not a valid ordering operator", |
2934 | 0 | sortcl->sortop); |
2935 | | /* Record properties of sort ordering */ |
2936 | 0 | wc->inRangeColl = exprCollation(sortkey); |
2937 | 0 | wc->inRangeAsc = !sortcl->reverse_sort; |
2938 | 0 | wc->inRangeNullsFirst = sortcl->nulls_first; |
2939 | 0 | } |
2940 | | |
2941 | | /* Per spec, GROUPS mode requires an ORDER BY clause */ |
2942 | 0 | if (wc->frameOptions & FRAMEOPTION_GROUPS) |
2943 | 0 | { |
2944 | 0 | if (wc->orderClause == NIL) |
2945 | 0 | ereport(ERROR, |
2946 | 0 | (errcode(ERRCODE_WINDOWING_ERROR), |
2947 | 0 | errmsg("GROUPS mode requires an ORDER BY clause"), |
2948 | 0 | parser_errposition(pstate, windef->location))); |
2949 | 0 | } |
2950 | | |
2951 | | /* Process frame offset expressions */ |
2952 | 0 | wc->startOffset = transformFrameOffset(pstate, wc->frameOptions, |
2953 | 0 | rangeopfamily, rangeopcintype, |
2954 | 0 | &wc->startInRangeFunc, |
2955 | 0 | windef->startOffset); |
2956 | 0 | wc->endOffset = transformFrameOffset(pstate, wc->frameOptions, |
2957 | 0 | rangeopfamily, rangeopcintype, |
2958 | 0 | &wc->endInRangeFunc, |
2959 | 0 | windef->endOffset); |
2960 | 0 | wc->winref = winref; |
2961 | |
|
2962 | 0 | result = lappend(result, wc); |
2963 | 0 | } |
2964 | | |
2965 | 0 | return result; |
2966 | 0 | } |
2967 | | |
2968 | | /* |
2969 | | * transformDistinctClause - |
2970 | | * transform a DISTINCT clause |
2971 | | * |
2972 | | * Since we may need to add items to the query's targetlist, that list |
2973 | | * is passed by reference. |
2974 | | * |
2975 | | * As with GROUP BY, we absorb the sorting semantics of ORDER BY as much as |
2976 | | * possible into the distinctClause. This avoids a possible need to re-sort, |
2977 | | * and allows the user to choose the equality semantics used by DISTINCT, |
2978 | | * should she be working with a datatype that has more than one equality |
2979 | | * operator. |
2980 | | * |
2981 | | * is_agg is true if we are transforming an aggregate(DISTINCT ...) |
2982 | | * function call. This does not affect any behavior, only the phrasing |
2983 | | * of error messages. |
2984 | | */ |
2985 | | List * |
2986 | | transformDistinctClause(ParseState *pstate, |
2987 | | List **targetlist, List *sortClause, bool is_agg) |
2988 | 0 | { |
2989 | 0 | List *result = NIL; |
2990 | 0 | ListCell *slitem; |
2991 | 0 | ListCell *tlitem; |
2992 | | |
2993 | | /* |
2994 | | * The distinctClause should consist of all ORDER BY items followed by all |
2995 | | * other non-resjunk targetlist items. There must not be any resjunk |
2996 | | * ORDER BY items --- that would imply that we are sorting by a value that |
2997 | | * isn't necessarily unique within a DISTINCT group, so the results |
2998 | | * wouldn't be well-defined. This construction ensures we follow the rule |
2999 | | * that sortClause and distinctClause match; in fact the sortClause will |
3000 | | * always be a prefix of distinctClause. |
3001 | | * |
3002 | | * Note a corner case: the same TLE could be in the ORDER BY list multiple |
3003 | | * times with different sortops. We have to include it in the |
3004 | | * distinctClause the same way to preserve the prefix property. The net |
3005 | | * effect will be that the TLE value will be made unique according to both |
3006 | | * sortops. |
3007 | | */ |
3008 | 0 | foreach(slitem, sortClause) |
3009 | 0 | { |
3010 | 0 | SortGroupClause *scl = (SortGroupClause *) lfirst(slitem); |
3011 | 0 | TargetEntry *tle = get_sortgroupclause_tle(scl, *targetlist); |
3012 | |
|
3013 | 0 | if (tle->resjunk) |
3014 | 0 | ereport(ERROR, |
3015 | 0 | (errcode(ERRCODE_INVALID_COLUMN_REFERENCE), |
3016 | 0 | is_agg ? |
3017 | 0 | errmsg("in an aggregate with DISTINCT, ORDER BY expressions must appear in argument list") : |
3018 | 0 | errmsg("for SELECT DISTINCT, ORDER BY expressions must appear in select list"), |
3019 | 0 | parser_errposition(pstate, |
3020 | 0 | exprLocation((Node *) tle->expr)))); |
3021 | 0 | result = lappend(result, copyObject(scl)); |
3022 | 0 | } |
3023 | | |
3024 | | /* |
3025 | | * Now add any remaining non-resjunk tlist items, using default sort/group |
3026 | | * semantics for their data types. |
3027 | | */ |
3028 | 0 | foreach(tlitem, *targetlist) |
3029 | 0 | { |
3030 | 0 | TargetEntry *tle = (TargetEntry *) lfirst(tlitem); |
3031 | |
|
3032 | 0 | if (tle->resjunk) |
3033 | 0 | continue; /* ignore junk */ |
3034 | 0 | result = addTargetToGroupList(pstate, tle, |
3035 | 0 | result, *targetlist, |
3036 | 0 | exprLocation((Node *) tle->expr)); |
3037 | 0 | } |
3038 | | |
3039 | | /* |
3040 | | * Complain if we found nothing to make DISTINCT. Returning an empty list |
3041 | | * would cause the parsed Query to look like it didn't have DISTINCT, with |
3042 | | * results that would probably surprise the user. Note: this case is |
3043 | | * presently impossible for aggregates because of grammar restrictions, |
3044 | | * but we check anyway. |
3045 | | */ |
3046 | 0 | if (result == NIL) |
3047 | 0 | ereport(ERROR, |
3048 | 0 | (errcode(ERRCODE_SYNTAX_ERROR), |
3049 | 0 | is_agg ? |
3050 | 0 | errmsg("an aggregate with DISTINCT must have at least one argument") : |
3051 | 0 | errmsg("SELECT DISTINCT must have at least one column"))); |
3052 | | |
3053 | 0 | return result; |
3054 | 0 | } |
3055 | | |
3056 | | /* |
3057 | | * transformDistinctOnClause - |
3058 | | * transform a DISTINCT ON clause |
3059 | | * |
3060 | | * Since we may need to add items to the query's targetlist, that list |
3061 | | * is passed by reference. |
3062 | | * |
3063 | | * As with GROUP BY, we absorb the sorting semantics of ORDER BY as much as |
3064 | | * possible into the distinctClause. This avoids a possible need to re-sort, |
3065 | | * and allows the user to choose the equality semantics used by DISTINCT, |
3066 | | * should she be working with a datatype that has more than one equality |
3067 | | * operator. |
3068 | | */ |
3069 | | List * |
3070 | | transformDistinctOnClause(ParseState *pstate, List *distinctlist, |
3071 | | List **targetlist, List *sortClause) |
3072 | 0 | { |
3073 | 0 | List *result = NIL; |
3074 | 0 | List *sortgrouprefs = NIL; |
3075 | 0 | bool skipped_sortitem; |
3076 | 0 | ListCell *lc; |
3077 | 0 | ListCell *lc2; |
3078 | | |
3079 | | /* |
3080 | | * Add all the DISTINCT ON expressions to the tlist (if not already |
3081 | | * present, they are added as resjunk items). Assign sortgroupref numbers |
3082 | | * to them, and make a list of these numbers. (NB: we rely below on the |
3083 | | * sortgrouprefs list being one-for-one with the original distinctlist. |
3084 | | * Also notice that we could have duplicate DISTINCT ON expressions and |
3085 | | * hence duplicate entries in sortgrouprefs.) |
3086 | | */ |
3087 | 0 | foreach(lc, distinctlist) |
3088 | 0 | { |
3089 | 0 | Node *dexpr = (Node *) lfirst(lc); |
3090 | 0 | int sortgroupref; |
3091 | 0 | TargetEntry *tle; |
3092 | |
|
3093 | 0 | tle = findTargetlistEntrySQL92(pstate, dexpr, targetlist, |
3094 | 0 | EXPR_KIND_DISTINCT_ON); |
3095 | 0 | sortgroupref = assignSortGroupRef(tle, *targetlist); |
3096 | 0 | sortgrouprefs = lappend_int(sortgrouprefs, sortgroupref); |
3097 | 0 | } |
3098 | | |
3099 | | /* |
3100 | | * If the user writes both DISTINCT ON and ORDER BY, adopt the sorting |
3101 | | * semantics from ORDER BY items that match DISTINCT ON items, and also |
3102 | | * adopt their column sort order. We insist that the distinctClause and |
3103 | | * sortClause match, so throw error if we find the need to add any more |
3104 | | * distinctClause items after we've skipped an ORDER BY item that wasn't |
3105 | | * in DISTINCT ON. |
3106 | | */ |
3107 | 0 | skipped_sortitem = false; |
3108 | 0 | foreach(lc, sortClause) |
3109 | 0 | { |
3110 | 0 | SortGroupClause *scl = (SortGroupClause *) lfirst(lc); |
3111 | |
|
3112 | 0 | if (list_member_int(sortgrouprefs, scl->tleSortGroupRef)) |
3113 | 0 | { |
3114 | 0 | if (skipped_sortitem) |
3115 | 0 | ereport(ERROR, |
3116 | 0 | (errcode(ERRCODE_INVALID_COLUMN_REFERENCE), |
3117 | 0 | errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"), |
3118 | 0 | parser_errposition(pstate, |
3119 | 0 | get_matching_location(scl->tleSortGroupRef, |
3120 | 0 | sortgrouprefs, |
3121 | 0 | distinctlist)))); |
3122 | 0 | else |
3123 | 0 | result = lappend(result, copyObject(scl)); |
3124 | 0 | } |
3125 | 0 | else |
3126 | 0 | skipped_sortitem = true; |
3127 | 0 | } |
3128 | | |
3129 | | /* |
3130 | | * Now add any remaining DISTINCT ON items, using default sort/group |
3131 | | * semantics for their data types. (Note: this is pretty questionable; if |
3132 | | * the ORDER BY list doesn't include all the DISTINCT ON items and more |
3133 | | * besides, you certainly aren't using DISTINCT ON in the intended way, |
3134 | | * and you probably aren't going to get consistent results. It might be |
3135 | | * better to throw an error or warning here. But historically we've |
3136 | | * allowed it, so keep doing so.) |
3137 | | */ |
3138 | 0 | forboth(lc, distinctlist, lc2, sortgrouprefs) |
3139 | 0 | { |
3140 | 0 | Node *dexpr = (Node *) lfirst(lc); |
3141 | 0 | int sortgroupref = lfirst_int(lc2); |
3142 | 0 | TargetEntry *tle = get_sortgroupref_tle(sortgroupref, *targetlist); |
3143 | |
|
3144 | 0 | if (targetIsInSortList(tle, InvalidOid, result)) |
3145 | 0 | continue; /* already in list (with some semantics) */ |
3146 | 0 | if (skipped_sortitem) |
3147 | 0 | ereport(ERROR, |
3148 | 0 | (errcode(ERRCODE_INVALID_COLUMN_REFERENCE), |
3149 | 0 | errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"), |
3150 | 0 | parser_errposition(pstate, exprLocation(dexpr)))); |
3151 | 0 | result = addTargetToGroupList(pstate, tle, |
3152 | 0 | result, *targetlist, |
3153 | 0 | exprLocation(dexpr)); |
3154 | 0 | } |
3155 | | |
3156 | | /* |
3157 | | * An empty result list is impossible here because of grammar |
3158 | | * restrictions. |
3159 | | */ |
3160 | 0 | Assert(result != NIL); |
3161 | |
|
3162 | 0 | return result; |
3163 | 0 | } |
3164 | | |
3165 | | /* |
3166 | | * get_matching_location |
3167 | | * Get the exprLocation of the exprs member corresponding to the |
3168 | | * (first) member of sortgrouprefs that equals sortgroupref. |
3169 | | * |
3170 | | * This is used so that we can point at a troublesome DISTINCT ON entry. |
3171 | | * (Note that we need to use the original untransformed DISTINCT ON list |
3172 | | * item, as whatever TLE it corresponds to will very possibly have a |
3173 | | * parse location pointing to some matching entry in the SELECT list |
3174 | | * or ORDER BY list.) |
3175 | | */ |
3176 | | static int |
3177 | | get_matching_location(int sortgroupref, List *sortgrouprefs, List *exprs) |
3178 | 0 | { |
3179 | 0 | ListCell *lcs; |
3180 | 0 | ListCell *lce; |
3181 | |
|
3182 | 0 | forboth(lcs, sortgrouprefs, lce, exprs) |
3183 | 0 | { |
3184 | 0 | if (lfirst_int(lcs) == sortgroupref) |
3185 | 0 | return exprLocation((Node *) lfirst(lce)); |
3186 | 0 | } |
3187 | | /* if no match, caller blew it */ |
3188 | 0 | elog(ERROR, "get_matching_location: no matching sortgroupref"); |
3189 | 0 | return -1; /* keep compiler quiet */ |
3190 | 0 | } |
3191 | | |
3192 | | /* |
3193 | | * resolve_unique_index_expr |
3194 | | * Infer a unique index from a list of indexElems, for ON |
3195 | | * CONFLICT clause |
3196 | | * |
3197 | | * Perform parse analysis of expressions and columns appearing within ON |
3198 | | * CONFLICT clause. During planning, the returned list of expressions is used |
3199 | | * to infer which unique index to use. |
3200 | | */ |
3201 | | static List * |
3202 | | resolve_unique_index_expr(ParseState *pstate, InferClause *infer, |
3203 | | Relation heapRel) |
3204 | 0 | { |
3205 | 0 | List *result = NIL; |
3206 | 0 | ListCell *l; |
3207 | |
|
3208 | 0 | foreach(l, infer->indexElems) |
3209 | 0 | { |
3210 | 0 | IndexElem *ielem = (IndexElem *) lfirst(l); |
3211 | 0 | InferenceElem *pInfer = makeNode(InferenceElem); |
3212 | 0 | Node *parse; |
3213 | | |
3214 | | /* |
3215 | | * Raw grammar re-uses CREATE INDEX infrastructure for unique index |
3216 | | * inference clause, and so will accept opclasses by name and so on. |
3217 | | * |
3218 | | * Make no attempt to match ASC or DESC ordering, NULLS FIRST/NULLS |
3219 | | * LAST ordering or opclass options, since those are not significant |
3220 | | * for inference purposes (any unique index matching the inference |
3221 | | * specification in other regards is accepted indifferently). Actively |
3222 | | * reject this as wrong-headed. |
3223 | | */ |
3224 | 0 | if (ielem->ordering != SORTBY_DEFAULT) |
3225 | 0 | ereport(ERROR, |
3226 | 0 | (errcode(ERRCODE_INVALID_COLUMN_REFERENCE), |
3227 | 0 | errmsg("%s is not allowed in ON CONFLICT clause", |
3228 | 0 | "ASC/DESC"), |
3229 | 0 | parser_errposition(pstate, ielem->location))); |
3230 | 0 | if (ielem->nulls_ordering != SORTBY_NULLS_DEFAULT) |
3231 | 0 | ereport(ERROR, |
3232 | 0 | (errcode(ERRCODE_INVALID_COLUMN_REFERENCE), |
3233 | 0 | errmsg("%s is not allowed in ON CONFLICT clause", |
3234 | 0 | "NULLS FIRST/LAST"), |
3235 | 0 | parser_errposition(pstate, ielem->location))); |
3236 | 0 | if (ielem->opclassopts) |
3237 | 0 | ereport(ERROR, |
3238 | 0 | errcode(ERRCODE_INVALID_COLUMN_REFERENCE), |
3239 | 0 | errmsg("operator class options are not allowed in ON CONFLICT clause"), |
3240 | 0 | parser_errposition(pstate, ielem->location)); |
3241 | | |
3242 | 0 | if (!ielem->expr) |
3243 | 0 | { |
3244 | | /* Simple index attribute */ |
3245 | 0 | ColumnRef *n; |
3246 | | |
3247 | | /* |
3248 | | * Grammar won't have built raw expression for us in event of |
3249 | | * plain column reference. Create one directly, and perform |
3250 | | * expression transformation. Planner expects this, and performs |
3251 | | * its own normalization for the purposes of matching against |
3252 | | * pg_index. |
3253 | | */ |
3254 | 0 | n = makeNode(ColumnRef); |
3255 | 0 | n->fields = list_make1(makeString(ielem->name)); |
3256 | | /* Location is approximately that of inference specification */ |
3257 | 0 | n->location = infer->location; |
3258 | 0 | parse = (Node *) n; |
3259 | 0 | } |
3260 | 0 | else |
3261 | 0 | { |
3262 | | /* Do parse transformation of the raw expression */ |
3263 | 0 | parse = (Node *) ielem->expr; |
3264 | 0 | } |
3265 | | |
3266 | | /* |
3267 | | * transformExpr() will reject subqueries, aggregates, window |
3268 | | * functions, and SRFs, based on being passed |
3269 | | * EXPR_KIND_INDEX_EXPRESSION. So we needn't worry about those |
3270 | | * further ... not that they would match any available index |
3271 | | * expression anyway. |
3272 | | */ |
3273 | 0 | pInfer->expr = transformExpr(pstate, parse, EXPR_KIND_INDEX_EXPRESSION); |
3274 | | |
3275 | | /* Perform lookup of collation and operator class as required */ |
3276 | 0 | if (!ielem->collation) |
3277 | 0 | pInfer->infercollid = InvalidOid; |
3278 | 0 | else |
3279 | 0 | pInfer->infercollid = LookupCollation(pstate, ielem->collation, |
3280 | 0 | ielem->location); |
3281 | |
|
3282 | 0 | if (!ielem->opclass) |
3283 | 0 | pInfer->inferopclass = InvalidOid; |
3284 | 0 | else |
3285 | 0 | pInfer->inferopclass = get_opclass_oid(BTREE_AM_OID, |
3286 | 0 | ielem->opclass, false); |
3287 | |
|
3288 | 0 | result = lappend(result, pInfer); |
3289 | 0 | } |
3290 | | |
3291 | 0 | return result; |
3292 | 0 | } |
3293 | | |
3294 | | /* |
3295 | | * transformOnConflictArbiter - |
3296 | | * transform arbiter expressions in an ON CONFLICT clause. |
3297 | | * |
3298 | | * Transformed expressions used to infer one unique index relation to serve as |
3299 | | * an ON CONFLICT arbiter. Partial unique indexes may be inferred using WHERE |
3300 | | * clause from inference specification clause. |
3301 | | */ |
3302 | | void |
3303 | | transformOnConflictArbiter(ParseState *pstate, |
3304 | | OnConflictClause *onConflictClause, |
3305 | | List **arbiterExpr, Node **arbiterWhere, |
3306 | | Oid *constraint) |
3307 | 0 | { |
3308 | 0 | InferClause *infer = onConflictClause->infer; |
3309 | |
|
3310 | 0 | *arbiterExpr = NIL; |
3311 | 0 | *arbiterWhere = NULL; |
3312 | 0 | *constraint = InvalidOid; |
3313 | |
|
3314 | 0 | if ((onConflictClause->action == ONCONFLICT_UPDATE || |
3315 | 0 | onConflictClause->action == ONCONFLICT_SELECT) && !infer) |
3316 | 0 | ereport(ERROR, |
3317 | 0 | errcode(ERRCODE_SYNTAX_ERROR), |
3318 | 0 | errmsg("ON CONFLICT DO %s requires inference specification or constraint name", |
3319 | 0 | onConflictClause->action == ONCONFLICT_UPDATE ? "UPDATE" : "SELECT"), |
3320 | 0 | errhint("For example, ON CONFLICT (column_name)."), |
3321 | 0 | parser_errposition(pstate, |
3322 | 0 | exprLocation((Node *) onConflictClause))); |
3323 | | |
3324 | | /* |
3325 | | * To simplify certain aspects of its design, speculative insertion into |
3326 | | * system catalogs is disallowed |
3327 | | */ |
3328 | 0 | if (IsCatalogRelation(pstate->p_target_relation)) |
3329 | 0 | ereport(ERROR, |
3330 | 0 | (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
3331 | 0 | errmsg("ON CONFLICT is not supported with system catalog tables"), |
3332 | 0 | parser_errposition(pstate, |
3333 | 0 | exprLocation((Node *) onConflictClause)))); |
3334 | | |
3335 | | /* Same applies to table used by logical decoding as catalog table */ |
3336 | 0 | if (RelationIsUsedAsCatalogTable(pstate->p_target_relation)) |
3337 | 0 | ereport(ERROR, |
3338 | 0 | (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
3339 | 0 | errmsg("ON CONFLICT is not supported on table \"%s\" used as a catalog table", |
3340 | 0 | RelationGetRelationName(pstate->p_target_relation)), |
3341 | 0 | parser_errposition(pstate, |
3342 | 0 | exprLocation((Node *) onConflictClause)))); |
3343 | | |
3344 | | /* ON CONFLICT DO NOTHING does not require an inference clause */ |
3345 | 0 | if (infer) |
3346 | 0 | { |
3347 | 0 | if (infer->indexElems) |
3348 | 0 | *arbiterExpr = resolve_unique_index_expr(pstate, infer, |
3349 | 0 | pstate->p_target_relation); |
3350 | | |
3351 | | /* |
3352 | | * Handling inference WHERE clause (for partial unique index |
3353 | | * inference) |
3354 | | */ |
3355 | 0 | if (infer->whereClause) |
3356 | 0 | *arbiterWhere = transformExpr(pstate, infer->whereClause, |
3357 | 0 | EXPR_KIND_INDEX_PREDICATE); |
3358 | | |
3359 | | /* |
3360 | | * If the arbiter is specified by constraint name, get the constraint |
3361 | | * OID and mark the constrained columns as requiring SELECT privilege, |
3362 | | * in the same way as would have happened if the arbiter had been |
3363 | | * specified by explicit reference to the constraint's index columns. |
3364 | | */ |
3365 | 0 | if (infer->conname) |
3366 | 0 | { |
3367 | 0 | Oid relid = RelationGetRelid(pstate->p_target_relation); |
3368 | 0 | RTEPermissionInfo *perminfo = pstate->p_target_nsitem->p_perminfo; |
3369 | 0 | Bitmapset *conattnos; |
3370 | |
|
3371 | 0 | conattnos = get_relation_constraint_attnos(relid, infer->conname, |
3372 | 0 | false, constraint); |
3373 | | |
3374 | | /* Make sure the rel as a whole is marked for SELECT access */ |
3375 | 0 | perminfo->requiredPerms |= ACL_SELECT; |
3376 | | /* Mark the constrained columns as requiring SELECT access */ |
3377 | 0 | perminfo->selectedCols = bms_add_members(perminfo->selectedCols, |
3378 | 0 | conattnos); |
3379 | 0 | } |
3380 | 0 | } |
3381 | | |
3382 | | /* |
3383 | | * It's convenient to form a list of expressions based on the |
3384 | | * representation used by CREATE INDEX, since the same restrictions are |
3385 | | * appropriate (e.g. on subqueries). However, from here on, a dedicated |
3386 | | * primnode representation is used for inference elements, and so |
3387 | | * assign_query_collations() can be trusted to do the right thing with the |
3388 | | * post parse analysis query tree inference clause representation. |
3389 | | */ |
3390 | 0 | } |
3391 | | |
3392 | | /* |
3393 | | * addTargetToSortList |
3394 | | * If the given targetlist entry isn't already in the SortGroupClause |
3395 | | * list, add it to the end of the list, using the given sort ordering |
3396 | | * info. |
3397 | | * |
3398 | | * Returns the updated SortGroupClause list. |
3399 | | */ |
3400 | | List * |
3401 | | addTargetToSortList(ParseState *pstate, TargetEntry *tle, |
3402 | | List *sortlist, List *targetlist, SortBy *sortby) |
3403 | 0 | { |
3404 | 0 | Oid restype = exprType((Node *) tle->expr); |
3405 | 0 | Oid sortop; |
3406 | 0 | Oid eqop; |
3407 | 0 | bool hashable; |
3408 | 0 | bool reverse; |
3409 | 0 | int location; |
3410 | 0 | ParseCallbackState pcbstate; |
3411 | | |
3412 | | /* if tlist item is an UNKNOWN literal, change it to TEXT */ |
3413 | 0 | if (restype == UNKNOWNOID) |
3414 | 0 | { |
3415 | 0 | tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr, |
3416 | 0 | restype, TEXTOID, -1, |
3417 | 0 | COERCION_IMPLICIT, |
3418 | 0 | COERCE_IMPLICIT_CAST, |
3419 | 0 | -1); |
3420 | 0 | restype = TEXTOID; |
3421 | 0 | } |
3422 | | |
3423 | | /* |
3424 | | * Rather than clutter the API of get_sort_group_operators and the other |
3425 | | * functions we're about to use, make use of error context callback to |
3426 | | * mark any error reports with a parse position. We point to the operator |
3427 | | * location if present, else to the expression being sorted. (NB: use the |
3428 | | * original untransformed expression here; the TLE entry might well point |
3429 | | * at a duplicate expression in the regular SELECT list.) |
3430 | | */ |
3431 | 0 | location = sortby->location; |
3432 | 0 | if (location < 0) |
3433 | 0 | location = exprLocation(sortby->node); |
3434 | 0 | setup_parser_errposition_callback(&pcbstate, pstate, location); |
3435 | | |
3436 | | /* determine the sortop, eqop, and directionality */ |
3437 | 0 | switch (sortby->sortby_dir) |
3438 | 0 | { |
3439 | 0 | case SORTBY_DEFAULT: |
3440 | 0 | case SORTBY_ASC: |
3441 | 0 | get_sort_group_operators(restype, |
3442 | 0 | true, true, false, |
3443 | 0 | &sortop, &eqop, NULL, |
3444 | 0 | &hashable); |
3445 | 0 | reverse = false; |
3446 | 0 | break; |
3447 | 0 | case SORTBY_DESC: |
3448 | 0 | get_sort_group_operators(restype, |
3449 | 0 | false, true, true, |
3450 | 0 | NULL, &eqop, &sortop, |
3451 | 0 | &hashable); |
3452 | 0 | reverse = true; |
3453 | 0 | break; |
3454 | 0 | case SORTBY_USING: |
3455 | 0 | Assert(sortby->useOp != NIL); |
3456 | 0 | sortop = compatible_oper_opid(sortby->useOp, |
3457 | 0 | restype, |
3458 | 0 | restype, |
3459 | 0 | false); |
3460 | | |
3461 | | /* |
3462 | | * Verify it's a valid ordering operator, fetch the corresponding |
3463 | | * equality operator, and determine whether to consider it like |
3464 | | * ASC or DESC. |
3465 | | */ |
3466 | 0 | eqop = get_equality_op_for_ordering_op(sortop, &reverse); |
3467 | 0 | if (!OidIsValid(eqop)) |
3468 | 0 | ereport(ERROR, |
3469 | 0 | (errcode(ERRCODE_WRONG_OBJECT_TYPE), |
3470 | 0 | errmsg("operator %s is not a valid ordering operator", |
3471 | 0 | strVal(llast(sortby->useOp))), |
3472 | 0 | errhint("Ordering operators must be \"<\" or \">\" members of btree operator families."))); |
3473 | | |
3474 | | /* |
3475 | | * Also see if the equality operator is hashable. |
3476 | | */ |
3477 | 0 | hashable = op_hashjoinable(eqop, restype); |
3478 | 0 | break; |
3479 | 0 | default: |
3480 | 0 | elog(ERROR, "unrecognized sortby_dir: %d", sortby->sortby_dir); |
3481 | 0 | sortop = InvalidOid; /* keep compiler quiet */ |
3482 | 0 | eqop = InvalidOid; |
3483 | 0 | hashable = false; |
3484 | 0 | reverse = false; |
3485 | 0 | break; |
3486 | 0 | } |
3487 | | |
3488 | 0 | cancel_parser_errposition_callback(&pcbstate); |
3489 | | |
3490 | | /* avoid making duplicate sortlist entries */ |
3491 | 0 | if (!targetIsInSortList(tle, sortop, sortlist)) |
3492 | 0 | { |
3493 | 0 | SortGroupClause *sortcl = makeNode(SortGroupClause); |
3494 | |
|
3495 | 0 | sortcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist); |
3496 | |
|
3497 | 0 | sortcl->eqop = eqop; |
3498 | 0 | sortcl->sortop = sortop; |
3499 | 0 | sortcl->hashable = hashable; |
3500 | 0 | sortcl->reverse_sort = reverse; |
3501 | |
|
3502 | 0 | switch (sortby->sortby_nulls) |
3503 | 0 | { |
3504 | 0 | case SORTBY_NULLS_DEFAULT: |
3505 | | /* NULLS FIRST is default for DESC; other way for ASC */ |
3506 | 0 | sortcl->nulls_first = reverse; |
3507 | 0 | break; |
3508 | 0 | case SORTBY_NULLS_FIRST: |
3509 | 0 | sortcl->nulls_first = true; |
3510 | 0 | break; |
3511 | 0 | case SORTBY_NULLS_LAST: |
3512 | 0 | sortcl->nulls_first = false; |
3513 | 0 | break; |
3514 | 0 | default: |
3515 | 0 | elog(ERROR, "unrecognized sortby_nulls: %d", |
3516 | 0 | sortby->sortby_nulls); |
3517 | 0 | break; |
3518 | 0 | } |
3519 | | |
3520 | 0 | sortlist = lappend(sortlist, sortcl); |
3521 | 0 | } |
3522 | | |
3523 | 0 | return sortlist; |
3524 | 0 | } |
3525 | | |
3526 | | /* |
3527 | | * addTargetToGroupList |
3528 | | * If the given targetlist entry isn't already in the SortGroupClause |
3529 | | * list, add it to the end of the list, using default sort/group |
3530 | | * semantics. |
3531 | | * |
3532 | | * This is very similar to addTargetToSortList, except that we allow the |
3533 | | * case where only a grouping (equality) operator can be found, and that |
3534 | | * the TLE is considered "already in the list" if it appears there with any |
3535 | | * sorting semantics. |
3536 | | * |
3537 | | * location is the parse location to be fingered in event of trouble. Note |
3538 | | * that we can't rely on exprLocation(tle->expr), because that might point |
3539 | | * to a SELECT item that matches the GROUP BY item; it'd be pretty confusing |
3540 | | * to report such a location. |
3541 | | * |
3542 | | * Returns the updated SortGroupClause list. |
3543 | | */ |
3544 | | static List * |
3545 | | addTargetToGroupList(ParseState *pstate, TargetEntry *tle, |
3546 | | List *grouplist, List *targetlist, int location) |
3547 | 0 | { |
3548 | 0 | Oid restype = exprType((Node *) tle->expr); |
3549 | | |
3550 | | /* if tlist item is an UNKNOWN literal, change it to TEXT */ |
3551 | 0 | if (restype == UNKNOWNOID) |
3552 | 0 | { |
3553 | 0 | tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr, |
3554 | 0 | restype, TEXTOID, -1, |
3555 | 0 | COERCION_IMPLICIT, |
3556 | 0 | COERCE_IMPLICIT_CAST, |
3557 | 0 | -1); |
3558 | 0 | restype = TEXTOID; |
3559 | 0 | } |
3560 | | |
3561 | | /* avoid making duplicate grouplist entries */ |
3562 | 0 | if (!targetIsInSortList(tle, InvalidOid, grouplist)) |
3563 | 0 | { |
3564 | 0 | SortGroupClause *grpcl = makeNode(SortGroupClause); |
3565 | 0 | Oid sortop; |
3566 | 0 | Oid eqop; |
3567 | 0 | bool hashable; |
3568 | 0 | ParseCallbackState pcbstate; |
3569 | |
|
3570 | 0 | setup_parser_errposition_callback(&pcbstate, pstate, location); |
3571 | | |
3572 | | /* determine the eqop and optional sortop */ |
3573 | 0 | get_sort_group_operators(restype, |
3574 | 0 | false, true, false, |
3575 | 0 | &sortop, &eqop, NULL, |
3576 | 0 | &hashable); |
3577 | |
|
3578 | 0 | cancel_parser_errposition_callback(&pcbstate); |
3579 | |
|
3580 | 0 | grpcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist); |
3581 | 0 | grpcl->eqop = eqop; |
3582 | 0 | grpcl->sortop = sortop; |
3583 | 0 | grpcl->reverse_sort = false; /* sortop is "less than", or |
3584 | | * InvalidOid */ |
3585 | 0 | grpcl->nulls_first = false; /* OK with or without sortop */ |
3586 | 0 | grpcl->hashable = hashable; |
3587 | |
|
3588 | 0 | grouplist = lappend(grouplist, grpcl); |
3589 | 0 | } |
3590 | |
|
3591 | 0 | return grouplist; |
3592 | 0 | } |
3593 | | |
3594 | | /* |
3595 | | * assignSortGroupRef |
3596 | | * Assign the targetentry an unused ressortgroupref, if it doesn't |
3597 | | * already have one. Return the assigned or pre-existing refnumber. |
3598 | | * |
3599 | | * 'tlist' is the targetlist containing (or to contain) the given targetentry. |
3600 | | */ |
3601 | | Index |
3602 | | assignSortGroupRef(TargetEntry *tle, List *tlist) |
3603 | 0 | { |
3604 | 0 | Index maxRef; |
3605 | 0 | ListCell *l; |
3606 | |
|
3607 | 0 | if (tle->ressortgroupref) /* already has one? */ |
3608 | 0 | return tle->ressortgroupref; |
3609 | | |
3610 | | /* easiest way to pick an unused refnumber: max used + 1 */ |
3611 | 0 | maxRef = 0; |
3612 | 0 | foreach(l, tlist) |
3613 | 0 | { |
3614 | 0 | Index ref = ((TargetEntry *) lfirst(l))->ressortgroupref; |
3615 | |
|
3616 | 0 | if (ref > maxRef) |
3617 | 0 | maxRef = ref; |
3618 | 0 | } |
3619 | 0 | tle->ressortgroupref = maxRef + 1; |
3620 | 0 | return tle->ressortgroupref; |
3621 | 0 | } |
3622 | | |
3623 | | /* |
3624 | | * targetIsInSortList |
3625 | | * Is the given target item already in the sortlist? |
3626 | | * If sortop is not InvalidOid, also test for a match to the sortop. |
3627 | | * |
3628 | | * It is not an oversight that this function ignores the nulls_first flag. |
3629 | | * We check sortop when determining if an ORDER BY item is redundant with |
3630 | | * earlier ORDER BY items, because it's conceivable that "ORDER BY |
3631 | | * foo USING <, foo USING <<<" is not redundant, if <<< distinguishes |
3632 | | * values that < considers equal. We need not check nulls_first |
3633 | | * however, because a lower-order column with the same sortop but |
3634 | | * opposite nulls direction is redundant. Also, we can consider |
3635 | | * ORDER BY foo ASC, foo DESC redundant, so check for a commutator match. |
3636 | | * |
3637 | | * Works for both ordering and grouping lists (sortop would normally be |
3638 | | * InvalidOid when considering grouping). Note that the main reason we need |
3639 | | * this routine (and not just a quick test for nonzeroness of ressortgroupref) |
3640 | | * is that a TLE might be in only one of the lists. |
3641 | | */ |
3642 | | bool |
3643 | | targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList) |
3644 | 0 | { |
3645 | 0 | Index ref = tle->ressortgroupref; |
3646 | 0 | ListCell *l; |
3647 | | |
3648 | | /* no need to scan list if tle has no marker */ |
3649 | 0 | if (ref == 0) |
3650 | 0 | return false; |
3651 | | |
3652 | 0 | foreach(l, sortList) |
3653 | 0 | { |
3654 | 0 | SortGroupClause *scl = (SortGroupClause *) lfirst(l); |
3655 | |
|
3656 | 0 | if (scl->tleSortGroupRef == ref && |
3657 | 0 | (sortop == InvalidOid || |
3658 | 0 | sortop == scl->sortop || |
3659 | 0 | sortop == get_commutator(scl->sortop))) |
3660 | 0 | return true; |
3661 | 0 | } |
3662 | 0 | return false; |
3663 | 0 | } |
3664 | | |
3665 | | /* |
3666 | | * findWindowClause |
3667 | | * Find the named WindowClause in the list, or return NULL if not there |
3668 | | */ |
3669 | | static WindowClause * |
3670 | | findWindowClause(List *wclist, const char *name) |
3671 | 0 | { |
3672 | 0 | ListCell *l; |
3673 | |
|
3674 | 0 | foreach(l, wclist) |
3675 | 0 | { |
3676 | 0 | WindowClause *wc = (WindowClause *) lfirst(l); |
3677 | |
|
3678 | 0 | if (wc->name && strcmp(wc->name, name) == 0) |
3679 | 0 | return wc; |
3680 | 0 | } |
3681 | | |
3682 | 0 | return NULL; |
3683 | 0 | } |
3684 | | |
3685 | | /* |
3686 | | * transformFrameOffset |
3687 | | * Process a window frame offset expression |
3688 | | * |
3689 | | * In RANGE mode, rangeopfamily is the sort opfamily for the input ORDER BY |
3690 | | * column, and rangeopcintype is the input data type the sort operator is |
3691 | | * registered with. We expect the in_range function to be registered with |
3692 | | * that same type. (In binary-compatible cases, it might be different from |
3693 | | * the input column's actual type, so we can't use that for the lookups.) |
3694 | | * We'll return the OID of the in_range function to *inRangeFunc. |
3695 | | */ |
3696 | | static Node * |
3697 | | transformFrameOffset(ParseState *pstate, int frameOptions, |
3698 | | Oid rangeopfamily, Oid rangeopcintype, Oid *inRangeFunc, |
3699 | | Node *clause) |
3700 | 0 | { |
3701 | 0 | const char *constructName = NULL; |
3702 | 0 | Node *node; |
3703 | |
|
3704 | 0 | *inRangeFunc = InvalidOid; /* default result */ |
3705 | | |
3706 | | /* Quick exit if no offset expression */ |
3707 | 0 | if (clause == NULL) |
3708 | 0 | return NULL; |
3709 | | |
3710 | 0 | if (frameOptions & FRAMEOPTION_ROWS) |
3711 | 0 | { |
3712 | | /* Transform the raw expression tree */ |
3713 | 0 | node = transformExpr(pstate, clause, EXPR_KIND_WINDOW_FRAME_ROWS); |
3714 | | |
3715 | | /* |
3716 | | * Like LIMIT clause, simply coerce to int8 |
3717 | | */ |
3718 | 0 | constructName = "ROWS"; |
3719 | 0 | node = coerce_to_specific_type(pstate, node, INT8OID, constructName); |
3720 | 0 | } |
3721 | 0 | else if (frameOptions & FRAMEOPTION_RANGE) |
3722 | 0 | { |
3723 | | /* |
3724 | | * We must look up the in_range support function that's to be used, |
3725 | | * possibly choosing one of several, and coerce the "offset" value to |
3726 | | * the appropriate input type. |
3727 | | */ |
3728 | 0 | Oid nodeType; |
3729 | 0 | Oid preferredType; |
3730 | 0 | int nfuncs = 0; |
3731 | 0 | int nmatches = 0; |
3732 | 0 | Oid selectedType = InvalidOid; |
3733 | 0 | Oid selectedFunc = InvalidOid; |
3734 | 0 | CatCList *proclist; |
3735 | 0 | int i; |
3736 | | |
3737 | | /* Transform the raw expression tree */ |
3738 | 0 | node = transformExpr(pstate, clause, EXPR_KIND_WINDOW_FRAME_RANGE); |
3739 | 0 | nodeType = exprType(node); |
3740 | | |
3741 | | /* |
3742 | | * If there are multiple candidates, we'll prefer the one that exactly |
3743 | | * matches nodeType; or if nodeType is as yet unknown, prefer the one |
3744 | | * that exactly matches the sort column type. (The second rule is |
3745 | | * like what we do for "known_type operator unknown".) |
3746 | | */ |
3747 | 0 | preferredType = (nodeType != UNKNOWNOID) ? nodeType : rangeopcintype; |
3748 | | |
3749 | | /* Find the in_range support functions applicable to this case */ |
3750 | 0 | proclist = SearchSysCacheList2(AMPROCNUM, |
3751 | 0 | ObjectIdGetDatum(rangeopfamily), |
3752 | 0 | ObjectIdGetDatum(rangeopcintype)); |
3753 | 0 | for (i = 0; i < proclist->n_members; i++) |
3754 | 0 | { |
3755 | 0 | HeapTuple proctup = &proclist->members[i]->tuple; |
3756 | 0 | Form_pg_amproc procform = (Form_pg_amproc) GETSTRUCT(proctup); |
3757 | | |
3758 | | /* The search will find all support proc types; ignore others */ |
3759 | 0 | if (procform->amprocnum != BTINRANGE_PROC) |
3760 | 0 | continue; |
3761 | 0 | nfuncs++; |
3762 | | |
3763 | | /* Ignore function if given value can't be coerced to that type */ |
3764 | 0 | if (!can_coerce_type(1, &nodeType, &procform->amprocrighttype, |
3765 | 0 | COERCION_IMPLICIT)) |
3766 | 0 | continue; |
3767 | 0 | nmatches++; |
3768 | | |
3769 | | /* Remember preferred match, or any match if didn't find that */ |
3770 | 0 | if (selectedType != preferredType) |
3771 | 0 | { |
3772 | 0 | selectedType = procform->amprocrighttype; |
3773 | 0 | selectedFunc = procform->amproc; |
3774 | 0 | } |
3775 | 0 | } |
3776 | 0 | ReleaseCatCacheList(proclist); |
3777 | | |
3778 | | /* |
3779 | | * Throw error if needed. It seems worth taking the trouble to |
3780 | | * distinguish "no support at all" from "you didn't match any |
3781 | | * available offset type". |
3782 | | */ |
3783 | 0 | if (nfuncs == 0) |
3784 | 0 | ereport(ERROR, |
3785 | 0 | (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
3786 | 0 | errmsg("RANGE with offset PRECEDING/FOLLOWING is not supported for column type %s", |
3787 | 0 | format_type_be(rangeopcintype)), |
3788 | 0 | parser_errposition(pstate, exprLocation(node)))); |
3789 | 0 | if (nmatches == 0) |
3790 | 0 | ereport(ERROR, |
3791 | 0 | (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
3792 | 0 | errmsg("RANGE with offset PRECEDING/FOLLOWING is not supported for column type %s and offset type %s", |
3793 | 0 | format_type_be(rangeopcintype), |
3794 | 0 | format_type_be(nodeType)), |
3795 | 0 | errhint("Cast the offset value to an appropriate type."), |
3796 | 0 | parser_errposition(pstate, exprLocation(node)))); |
3797 | 0 | if (nmatches != 1 && selectedType != preferredType) |
3798 | 0 | ereport(ERROR, |
3799 | 0 | (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
3800 | 0 | errmsg("RANGE with offset PRECEDING/FOLLOWING has multiple interpretations for column type %s and offset type %s", |
3801 | 0 | format_type_be(rangeopcintype), |
3802 | 0 | format_type_be(nodeType)), |
3803 | 0 | errhint("Cast the offset value to the exact intended type."), |
3804 | 0 | parser_errposition(pstate, exprLocation(node)))); |
3805 | | |
3806 | | /* OK, coerce the offset to the right type */ |
3807 | 0 | constructName = "RANGE"; |
3808 | 0 | node = coerce_to_specific_type(pstate, node, |
3809 | 0 | selectedType, constructName); |
3810 | 0 | *inRangeFunc = selectedFunc; |
3811 | 0 | } |
3812 | 0 | else if (frameOptions & FRAMEOPTION_GROUPS) |
3813 | 0 | { |
3814 | | /* Transform the raw expression tree */ |
3815 | 0 | node = transformExpr(pstate, clause, EXPR_KIND_WINDOW_FRAME_GROUPS); |
3816 | | |
3817 | | /* |
3818 | | * Like LIMIT clause, simply coerce to int8 |
3819 | | */ |
3820 | 0 | constructName = "GROUPS"; |
3821 | 0 | node = coerce_to_specific_type(pstate, node, INT8OID, constructName); |
3822 | 0 | } |
3823 | 0 | else |
3824 | 0 | { |
3825 | 0 | Assert(false); |
3826 | 0 | node = NULL; |
3827 | 0 | } |
3828 | | |
3829 | | /* Disallow variables in frame offsets */ |
3830 | 0 | checkExprIsVarFree(pstate, node, constructName); |
3831 | |
|
3832 | 0 | return node; |
3833 | 0 | } |