1 | /*------------------------------------------------------------------------- |
2 | * |
3 | * parse_target.c |
4 | * handle target lists |
5 | * |
6 | * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group |
7 | * Portions Copyright (c) 1994, Regents of the University of California |
8 | * |
9 | * |
10 | * IDENTIFICATION |
11 | * src/backend/parser/parse_target.c |
12 | * |
13 | *------------------------------------------------------------------------- |
14 | */ |
15 | #include "postgres.h" |
16 | |
17 | #include "catalog/pg_type.h" |
18 | #include "commands/dbcommands.h" |
19 | #include "funcapi.h" |
20 | #include "miscadmin.h" |
21 | #include "nodes/makefuncs.h" |
22 | #include "nodes/nodeFuncs.h" |
23 | #include "parser/parsetree.h" |
24 | #include "parser/parse_coerce.h" |
25 | #include "parser/parse_expr.h" |
26 | #include "parser/parse_func.h" |
27 | #include "parser/parse_relation.h" |
28 | #include "parser/parse_target.h" |
29 | #include "parser/parse_type.h" |
30 | #include "utils/builtins.h" |
31 | #include "utils/lsyscache.h" |
32 | #include "utils/rel.h" |
33 | #include "utils/typcache.h" |
34 | |
35 | |
36 | static void markTargetListOrigin(ParseState *pstate, TargetEntry *tle, |
37 | Var *var, int levelsup); |
38 | static Node *transformAssignmentIndirection(ParseState *pstate, |
39 | Node *basenode, |
40 | const char *targetName, |
41 | bool targetIsSubscripting, |
42 | Oid targetTypeId, |
43 | int32 targetTypMod, |
44 | Oid targetCollation, |
45 | ListCell *indirection, |
46 | Node *rhs, |
47 | int location); |
48 | static Node *transformAssignmentSubscripts(ParseState *pstate, |
49 | Node *basenode, |
50 | const char *targetName, |
51 | Oid targetTypeId, |
52 | int32 targetTypMod, |
53 | Oid targetCollation, |
54 | List *subscripts, |
55 | bool isSlice, |
56 | ListCell *next_indirection, |
57 | Node *rhs, |
58 | int location); |
59 | static List *ExpandColumnRefStar(ParseState *pstate, ColumnRef *cref, |
60 | bool make_target_entry); |
61 | static List *ExpandAllTables(ParseState *pstate, int location); |
62 | static List *ExpandIndirectionStar(ParseState *pstate, A_Indirection *ind, |
63 | bool make_target_entry, ParseExprKind exprKind); |
64 | static List *ExpandSingleTable(ParseState *pstate, RangeTblEntry *rte, |
65 | int location, bool make_target_entry); |
66 | static List *ExpandRowReference(ParseState *pstate, Node *expr, |
67 | bool make_target_entry); |
68 | static int FigureColnameInternal(Node *node, char **name); |
69 | |
70 | |
71 | /* |
72 | * transformTargetEntry() |
73 | * Transform any ordinary "expression-type" node into a targetlist entry. |
74 | * This is exported so that parse_clause.c can generate targetlist entries |
75 | * for ORDER/GROUP BY items that are not already in the targetlist. |
76 | * |
77 | * node the (untransformed) parse tree for the value expression. |
78 | * expr the transformed expression, or NULL if caller didn't do it yet. |
79 | * exprKind expression kind (EXPR_KIND_SELECT_TARGET, etc) |
80 | * colname the column name to be assigned, or NULL if none yet set. |
81 | * resjunk true if the target should be marked resjunk, ie, it is not |
82 | * wanted in the final projected tuple. |
83 | */ |
84 | TargetEntry * |
85 | transformTargetEntry(ParseState *pstate, |
86 | Node *node, |
87 | Node *expr, |
88 | ParseExprKind exprKind, |
89 | char *colname, |
90 | bool resjunk) |
91 | { |
92 | /* Transform the node if caller didn't do it already */ |
93 | if (expr == NULL) |
94 | { |
95 | /* |
96 | * If it's a SetToDefault node and we should allow that, pass it |
97 | * through unmodified. (transformExpr will throw the appropriate |
98 | * error if we're disallowing it.) |
99 | */ |
100 | if (exprKind == EXPR_KIND_UPDATE_SOURCE && IsA(node, SetToDefault)) |
101 | expr = node; |
102 | else |
103 | expr = transformExpr(pstate, node, exprKind); |
104 | } |
105 | |
106 | if (colname == NULL && !resjunk) |
107 | { |
108 | /* |
109 | * Generate a suitable column name for a column without any explicit |
110 | * 'AS ColumnName' clause. |
111 | */ |
112 | colname = FigureColname(node); |
113 | } |
114 | |
115 | return makeTargetEntry((Expr *) expr, |
116 | (AttrNumber) pstate->p_next_resno++, |
117 | colname, |
118 | resjunk); |
119 | } |
120 | |
121 | |
122 | /* |
123 | * transformTargetList() |
124 | * Turns a list of ResTarget's into a list of TargetEntry's. |
125 | * |
126 | * This code acts mostly the same for SELECT, UPDATE, or RETURNING lists; |
127 | * the main thing is to transform the given expressions (the "val" fields). |
128 | * The exprKind parameter distinguishes these cases when necessary. |
129 | */ |
130 | List * |
131 | transformTargetList(ParseState *pstate, List *targetlist, |
132 | ParseExprKind exprKind) |
133 | { |
134 | List *p_target = NIL; |
135 | bool expand_star; |
136 | ListCell *o_target; |
137 | |
138 | /* Shouldn't have any leftover multiassign items at start */ |
139 | Assert(pstate->p_multiassign_exprs == NIL); |
140 | |
141 | /* Expand "something.*" in SELECT and RETURNING, but not UPDATE */ |
142 | expand_star = (exprKind != EXPR_KIND_UPDATE_SOURCE); |
143 | |
144 | foreach(o_target, targetlist) |
145 | { |
146 | ResTarget *res = (ResTarget *) lfirst(o_target); |
147 | |
148 | /* |
149 | * Check for "something.*". Depending on the complexity of the |
150 | * "something", the star could appear as the last field in ColumnRef, |
151 | * or as the last indirection item in A_Indirection. |
152 | */ |
153 | if (expand_star) |
154 | { |
155 | if (IsA(res->val, ColumnRef)) |
156 | { |
157 | ColumnRef *cref = (ColumnRef *) res->val; |
158 | |
159 | if (IsA(llast(cref->fields), A_Star)) |
160 | { |
161 | /* It is something.*, expand into multiple items */ |
162 | p_target = list_concat(p_target, |
163 | ExpandColumnRefStar(pstate, |
164 | cref, |
165 | true)); |
166 | continue; |
167 | } |
168 | } |
169 | else if (IsA(res->val, A_Indirection)) |
170 | { |
171 | A_Indirection *ind = (A_Indirection *) res->val; |
172 | |
173 | if (IsA(llast(ind->indirection), A_Star)) |
174 | { |
175 | /* It is something.*, expand into multiple items */ |
176 | p_target = list_concat(p_target, |
177 | ExpandIndirectionStar(pstate, |
178 | ind, |
179 | true, |
180 | exprKind)); |
181 | continue; |
182 | } |
183 | } |
184 | } |
185 | |
186 | /* |
187 | * Not "something.*", or we want to treat that as a plain whole-row |
188 | * variable, so transform as a single expression |
189 | */ |
190 | p_target = lappend(p_target, |
191 | transformTargetEntry(pstate, |
192 | res->val, |
193 | NULL, |
194 | exprKind, |
195 | res->name, |
196 | false)); |
197 | } |
198 | |
199 | /* |
200 | * If any multiassign resjunk items were created, attach them to the end |
201 | * of the targetlist. This should only happen in an UPDATE tlist. We |
202 | * don't need to worry about numbering of these items; transformUpdateStmt |
203 | * will set their resnos. |
204 | */ |
205 | if (pstate->p_multiassign_exprs) |
206 | { |
207 | Assert(exprKind == EXPR_KIND_UPDATE_SOURCE); |
208 | p_target = list_concat(p_target, pstate->p_multiassign_exprs); |
209 | pstate->p_multiassign_exprs = NIL; |
210 | } |
211 | |
212 | return p_target; |
213 | } |
214 | |
215 | |
216 | /* |
217 | * transformExpressionList() |
218 | * |
219 | * This is the identical transformation to transformTargetList, except that |
220 | * the input list elements are bare expressions without ResTarget decoration, |
221 | * and the output elements are likewise just expressions without TargetEntry |
222 | * decoration. We use this for ROW() and VALUES() constructs. |
223 | * |
224 | * exprKind is not enough to tell us whether to allow SetToDefault, so |
225 | * an additional flag is needed for that. |
226 | */ |
227 | List * |
228 | transformExpressionList(ParseState *pstate, List *exprlist, |
229 | ParseExprKind exprKind, bool allowDefault) |
230 | { |
231 | List *result = NIL; |
232 | ListCell *lc; |
233 | |
234 | foreach(lc, exprlist) |
235 | { |
236 | Node *e = (Node *) lfirst(lc); |
237 | |
238 | /* |
239 | * Check for "something.*". Depending on the complexity of the |
240 | * "something", the star could appear as the last field in ColumnRef, |
241 | * or as the last indirection item in A_Indirection. |
242 | */ |
243 | if (IsA(e, ColumnRef)) |
244 | { |
245 | ColumnRef *cref = (ColumnRef *) e; |
246 | |
247 | if (IsA(llast(cref->fields), A_Star)) |
248 | { |
249 | /* It is something.*, expand into multiple items */ |
250 | result = list_concat(result, |
251 | ExpandColumnRefStar(pstate, cref, |
252 | false)); |
253 | continue; |
254 | } |
255 | } |
256 | else if (IsA(e, A_Indirection)) |
257 | { |
258 | A_Indirection *ind = (A_Indirection *) e; |
259 | |
260 | if (IsA(llast(ind->indirection), A_Star)) |
261 | { |
262 | /* It is something.*, expand into multiple items */ |
263 | result = list_concat(result, |
264 | ExpandIndirectionStar(pstate, ind, |
265 | false, exprKind)); |
266 | continue; |
267 | } |
268 | } |
269 | |
270 | /* |
271 | * Not "something.*", so transform as a single expression. If it's a |
272 | * SetToDefault node and we should allow that, pass it through |
273 | * unmodified. (transformExpr will throw the appropriate error if |
274 | * we're disallowing it.) |
275 | */ |
276 | if (allowDefault && IsA(e, SetToDefault)) |
277 | /* do nothing */ ; |
278 | else |
279 | e = transformExpr(pstate, e, exprKind); |
280 | |
281 | result = lappend(result, e); |
282 | } |
283 | |
284 | /* Shouldn't have any multiassign items here */ |
285 | Assert(pstate->p_multiassign_exprs == NIL); |
286 | |
287 | return result; |
288 | } |
289 | |
290 | |
291 | /* |
292 | * resolveTargetListUnknowns() |
293 | * Convert any unknown-type targetlist entries to type TEXT. |
294 | * |
295 | * We do this after we've exhausted all other ways of identifying the output |
296 | * column types of a query. |
297 | */ |
298 | void |
299 | resolveTargetListUnknowns(ParseState *pstate, List *targetlist) |
300 | { |
301 | ListCell *l; |
302 | |
303 | foreach(l, targetlist) |
304 | { |
305 | TargetEntry *tle = (TargetEntry *) lfirst(l); |
306 | Oid restype = exprType((Node *) tle->expr); |
307 | |
308 | if (restype == UNKNOWNOID) |
309 | { |
310 | tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr, |
311 | restype, TEXTOID, -1, |
312 | COERCION_IMPLICIT, |
313 | COERCE_IMPLICIT_CAST, |
314 | -1); |
315 | } |
316 | } |
317 | } |
318 | |
319 | |
320 | /* |
321 | * markTargetListOrigins() |
322 | * Mark targetlist columns that are simple Vars with the source |
323 | * table's OID and column number. |
324 | * |
325 | * Currently, this is done only for SELECT targetlists and RETURNING lists, |
326 | * since we only need the info if we are going to send it to the frontend. |
327 | */ |
328 | void |
329 | markTargetListOrigins(ParseState *pstate, List *targetlist) |
330 | { |
331 | ListCell *l; |
332 | |
333 | foreach(l, targetlist) |
334 | { |
335 | TargetEntry *tle = (TargetEntry *) lfirst(l); |
336 | |
337 | markTargetListOrigin(pstate, tle, (Var *) tle->expr, 0); |
338 | } |
339 | } |
340 | |
341 | /* |
342 | * markTargetListOrigin() |
343 | * If 'var' is a Var of a plain relation, mark 'tle' with its origin |
344 | * |
345 | * levelsup is an extra offset to interpret the Var's varlevelsup correctly. |
346 | * |
347 | * This is split out so it can recurse for join references. Note that we |
348 | * do not drill down into views, but report the view as the column owner. |
349 | */ |
350 | static void |
351 | markTargetListOrigin(ParseState *pstate, TargetEntry *tle, |
352 | Var *var, int levelsup) |
353 | { |
354 | int netlevelsup; |
355 | RangeTblEntry *rte; |
356 | AttrNumber attnum; |
357 | |
358 | if (var == NULL || !IsA(var, Var)) |
359 | return; |
360 | netlevelsup = var->varlevelsup + levelsup; |
361 | rte = GetRTEByRangeTablePosn(pstate, var->varno, netlevelsup); |
362 | attnum = var->varattno; |
363 | |
364 | switch (rte->rtekind) |
365 | { |
366 | case RTE_RELATION: |
367 | /* It's a table or view, report it */ |
368 | tle->resorigtbl = rte->relid; |
369 | tle->resorigcol = attnum; |
370 | break; |
371 | case RTE_SUBQUERY: |
372 | /* Subselect-in-FROM: copy up from the subselect */ |
373 | if (attnum != InvalidAttrNumber) |
374 | { |
375 | TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList, |
376 | attnum); |
377 | |
378 | if (ste == NULL || ste->resjunk) |
379 | elog(ERROR, "subquery %s does not have attribute %d" , |
380 | rte->eref->aliasname, attnum); |
381 | tle->resorigtbl = ste->resorigtbl; |
382 | tle->resorigcol = ste->resorigcol; |
383 | } |
384 | break; |
385 | case RTE_JOIN: |
386 | /* Join RTE --- recursively inspect the alias variable */ |
387 | if (attnum != InvalidAttrNumber) |
388 | { |
389 | Var *aliasvar; |
390 | |
391 | Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars)); |
392 | aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1); |
393 | /* We intentionally don't strip implicit coercions here */ |
394 | markTargetListOrigin(pstate, tle, aliasvar, netlevelsup); |
395 | } |
396 | break; |
397 | case RTE_FUNCTION: |
398 | case RTE_VALUES: |
399 | case RTE_TABLEFUNC: |
400 | case RTE_NAMEDTUPLESTORE: |
401 | case RTE_RESULT: |
402 | /* not a simple relation, leave it unmarked */ |
403 | break; |
404 | case RTE_CTE: |
405 | |
406 | /* |
407 | * CTE reference: copy up from the subquery, if possible. If the |
408 | * RTE is a recursive self-reference then we can't do anything |
409 | * because we haven't finished analyzing it yet. However, it's no |
410 | * big loss because we must be down inside the recursive term of a |
411 | * recursive CTE, and so any markings on the current targetlist |
412 | * are not going to affect the results anyway. |
413 | */ |
414 | if (attnum != InvalidAttrNumber && !rte->self_reference) |
415 | { |
416 | CommonTableExpr *cte = GetCTEForRTE(pstate, rte, netlevelsup); |
417 | TargetEntry *ste; |
418 | |
419 | ste = get_tle_by_resno(GetCTETargetList(cte), attnum); |
420 | if (ste == NULL || ste->resjunk) |
421 | elog(ERROR, "subquery %s does not have attribute %d" , |
422 | rte->eref->aliasname, attnum); |
423 | tle->resorigtbl = ste->resorigtbl; |
424 | tle->resorigcol = ste->resorigcol; |
425 | } |
426 | break; |
427 | } |
428 | } |
429 | |
430 | |
431 | /* |
432 | * transformAssignedExpr() |
433 | * This is used in INSERT and UPDATE statements only. It prepares an |
434 | * expression for assignment to a column of the target table. |
435 | * This includes coercing the given value to the target column's type |
436 | * (if necessary), and dealing with any subfield names or subscripts |
437 | * attached to the target column itself. The input expression has |
438 | * already been through transformExpr(). |
439 | * |
440 | * pstate parse state |
441 | * expr expression to be modified |
442 | * exprKind indicates which type of statement we're dealing with |
443 | * colname target column name (ie, name of attribute to be assigned to) |
444 | * attrno target attribute number |
445 | * indirection subscripts/field names for target column, if any |
446 | * location error cursor position for the target column, or -1 |
447 | * |
448 | * Returns the modified expression. |
449 | * |
450 | * Note: location points at the target column name (SET target or INSERT |
451 | * column name list entry), and must therefore be -1 in an INSERT that |
452 | * omits the column name list. So we should usually prefer to use |
453 | * exprLocation(expr) for errors that can happen in a default INSERT. |
454 | */ |
455 | Expr * |
456 | transformAssignedExpr(ParseState *pstate, |
457 | Expr *expr, |
458 | ParseExprKind exprKind, |
459 | const char *colname, |
460 | int attrno, |
461 | List *indirection, |
462 | int location) |
463 | { |
464 | Relation rd = pstate->p_target_relation; |
465 | Oid type_id; /* type of value provided */ |
466 | Oid attrtype; /* type of target column */ |
467 | int32 attrtypmod; |
468 | Oid attrcollation; /* collation of target column */ |
469 | ParseExprKind sv_expr_kind; |
470 | |
471 | /* |
472 | * Save and restore identity of expression type we're parsing. We must |
473 | * set p_expr_kind here because we can parse subscripts without going |
474 | * through transformExpr(). |
475 | */ |
476 | Assert(exprKind != EXPR_KIND_NONE); |
477 | sv_expr_kind = pstate->p_expr_kind; |
478 | pstate->p_expr_kind = exprKind; |
479 | |
480 | Assert(rd != NULL); |
481 | if (attrno <= 0) |
482 | ereport(ERROR, |
483 | (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
484 | errmsg("cannot assign to system column \"%s\"" , |
485 | colname), |
486 | parser_errposition(pstate, location))); |
487 | attrtype = attnumTypeId(rd, attrno); |
488 | attrtypmod = TupleDescAttr(rd->rd_att, attrno - 1)->atttypmod; |
489 | attrcollation = TupleDescAttr(rd->rd_att, attrno - 1)->attcollation; |
490 | |
491 | /* |
492 | * If the expression is a DEFAULT placeholder, insert the attribute's |
493 | * type/typmod/collation into it so that exprType etc will report the |
494 | * right things. (We expect that the eventually substituted default |
495 | * expression will in fact have this type and typmod. The collation |
496 | * likely doesn't matter, but let's set it correctly anyway.) Also, |
497 | * reject trying to update a subfield or array element with DEFAULT, since |
498 | * there can't be any default for portions of a column. |
499 | */ |
500 | if (expr && IsA(expr, SetToDefault)) |
501 | { |
502 | SetToDefault *def = (SetToDefault *) expr; |
503 | |
504 | def->typeId = attrtype; |
505 | def->typeMod = attrtypmod; |
506 | def->collation = attrcollation; |
507 | if (indirection) |
508 | { |
509 | if (IsA(linitial(indirection), A_Indices)) |
510 | ereport(ERROR, |
511 | (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
512 | errmsg("cannot set an array element to DEFAULT" ), |
513 | parser_errposition(pstate, location))); |
514 | else |
515 | ereport(ERROR, |
516 | (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
517 | errmsg("cannot set a subfield to DEFAULT" ), |
518 | parser_errposition(pstate, location))); |
519 | } |
520 | } |
521 | |
522 | /* Now we can use exprType() safely. */ |
523 | type_id = exprType((Node *) expr); |
524 | |
525 | /* |
526 | * If there is indirection on the target column, prepare an array or |
527 | * subfield assignment expression. This will generate a new column value |
528 | * that the source value has been inserted into, which can then be placed |
529 | * in the new tuple constructed by INSERT or UPDATE. |
530 | */ |
531 | if (indirection) |
532 | { |
533 | Node *colVar; |
534 | |
535 | if (pstate->p_is_insert) |
536 | { |
537 | /* |
538 | * The command is INSERT INTO table (col.something) ... so there |
539 | * is not really a source value to work with. Insert a NULL |
540 | * constant as the source value. |
541 | */ |
542 | colVar = (Node *) makeNullConst(attrtype, attrtypmod, |
543 | attrcollation); |
544 | } |
545 | else |
546 | { |
547 | /* |
548 | * Build a Var for the column to be updated. |
549 | */ |
550 | colVar = (Node *) make_var(pstate, |
551 | pstate->p_target_rangetblentry, |
552 | attrno, |
553 | location); |
554 | } |
555 | |
556 | expr = (Expr *) |
557 | transformAssignmentIndirection(pstate, |
558 | colVar, |
559 | colname, |
560 | false, |
561 | attrtype, |
562 | attrtypmod, |
563 | attrcollation, |
564 | list_head(indirection), |
565 | (Node *) expr, |
566 | location); |
567 | } |
568 | else |
569 | { |
570 | /* |
571 | * For normal non-qualified target column, do type checking and |
572 | * coercion. |
573 | */ |
574 | Node *orig_expr = (Node *) expr; |
575 | |
576 | expr = (Expr *) |
577 | coerce_to_target_type(pstate, |
578 | orig_expr, type_id, |
579 | attrtype, attrtypmod, |
580 | COERCION_ASSIGNMENT, |
581 | COERCE_IMPLICIT_CAST, |
582 | -1); |
583 | if (expr == NULL) |
584 | ereport(ERROR, |
585 | (errcode(ERRCODE_DATATYPE_MISMATCH), |
586 | errmsg("column \"%s\" is of type %s" |
587 | " but expression is of type %s" , |
588 | colname, |
589 | format_type_be(attrtype), |
590 | format_type_be(type_id)), |
591 | errhint("You will need to rewrite or cast the expression." ), |
592 | parser_errposition(pstate, exprLocation(orig_expr)))); |
593 | } |
594 | |
595 | pstate->p_expr_kind = sv_expr_kind; |
596 | |
597 | return expr; |
598 | } |
599 | |
600 | |
601 | /* |
602 | * updateTargetListEntry() |
603 | * This is used in UPDATE statements (and ON CONFLICT DO UPDATE) |
604 | * only. It prepares an UPDATE TargetEntry for assignment to a |
605 | * column of the target table. This includes coercing the given |
606 | * value to the target column's type (if necessary), and dealing with |
607 | * any subfield names or subscripts attached to the target column |
608 | * itself. |
609 | * |
610 | * pstate parse state |
611 | * tle target list entry to be modified |
612 | * colname target column name (ie, name of attribute to be assigned to) |
613 | * attrno target attribute number |
614 | * indirection subscripts/field names for target column, if any |
615 | * location error cursor position (should point at column name), or -1 |
616 | */ |
617 | void |
618 | updateTargetListEntry(ParseState *pstate, |
619 | TargetEntry *tle, |
620 | char *colname, |
621 | int attrno, |
622 | List *indirection, |
623 | int location) |
624 | { |
625 | /* Fix up expression as needed */ |
626 | tle->expr = transformAssignedExpr(pstate, |
627 | tle->expr, |
628 | EXPR_KIND_UPDATE_TARGET, |
629 | colname, |
630 | attrno, |
631 | indirection, |
632 | location); |
633 | |
634 | /* |
635 | * Set the resno to identify the target column --- the rewriter and |
636 | * planner depend on this. We also set the resname to identify the target |
637 | * column, but this is only for debugging purposes; it should not be |
638 | * relied on. (In particular, it might be out of date in a stored rule.) |
639 | */ |
640 | tle->resno = (AttrNumber) attrno; |
641 | tle->resname = colname; |
642 | } |
643 | |
644 | |
645 | /* |
646 | * Process indirection (field selection or subscripting) of the target |
647 | * column in INSERT/UPDATE. This routine recurses for multiple levels |
648 | * of indirection --- but note that several adjacent A_Indices nodes in |
649 | * the indirection list are treated as a single multidimensional subscript |
650 | * operation. |
651 | * |
652 | * In the initial call, basenode is a Var for the target column in UPDATE, |
653 | * or a null Const of the target's type in INSERT. In recursive calls, |
654 | * basenode is NULL, indicating that a substitute node should be consed up if |
655 | * needed. |
656 | * |
657 | * targetName is the name of the field or subfield we're assigning to, and |
658 | * targetIsSubscripting is true if we're subscripting it. These are just for |
659 | * error reporting. |
660 | * |
661 | * targetTypeId, targetTypMod, targetCollation indicate the datatype and |
662 | * collation of the object to be assigned to (initially the target column, |
663 | * later some subobject). |
664 | * |
665 | * indirection is the sublist remaining to process. When it's NULL, we're |
666 | * done recursing and can just coerce and return the RHS. |
667 | * |
668 | * rhs is the already-transformed value to be assigned; note it has not been |
669 | * coerced to any particular type. |
670 | * |
671 | * location is the cursor error position for any errors. (Note: this points |
672 | * to the head of the target clause, eg "foo" in "foo.bar[baz]". Later we |
673 | * might want to decorate indirection cells with their own location info, |
674 | * in which case the location argument could probably be dropped.) |
675 | */ |
676 | static Node * |
677 | transformAssignmentIndirection(ParseState *pstate, |
678 | Node *basenode, |
679 | const char *targetName, |
680 | bool targetIsSubscripting, |
681 | Oid targetTypeId, |
682 | int32 targetTypMod, |
683 | Oid targetCollation, |
684 | ListCell *indirection, |
685 | Node *rhs, |
686 | int location) |
687 | { |
688 | Node *result; |
689 | List *subscripts = NIL; |
690 | bool isSlice = false; |
691 | ListCell *i; |
692 | |
693 | if (indirection && !basenode) |
694 | { |
695 | /* |
696 | * Set up a substitution. We abuse CaseTestExpr for this. It's safe |
697 | * to do so because the only nodes that will be above the CaseTestExpr |
698 | * in the finished expression will be FieldStore and SubscriptingRef |
699 | * nodes. (There could be other stuff in the tree, but it will be |
700 | * within other child fields of those node types.) |
701 | */ |
702 | CaseTestExpr *ctest = makeNode(CaseTestExpr); |
703 | |
704 | ctest->typeId = targetTypeId; |
705 | ctest->typeMod = targetTypMod; |
706 | ctest->collation = targetCollation; |
707 | basenode = (Node *) ctest; |
708 | } |
709 | |
710 | /* |
711 | * We have to split any field-selection operations apart from |
712 | * subscripting. Adjacent A_Indices nodes have to be treated as a single |
713 | * multidimensional subscript operation. |
714 | */ |
715 | for_each_cell(i, indirection) |
716 | { |
717 | Node *n = lfirst(i); |
718 | |
719 | if (IsA(n, A_Indices)) |
720 | { |
721 | subscripts = lappend(subscripts, n); |
722 | if (((A_Indices *) n)->is_slice) |
723 | isSlice = true; |
724 | } |
725 | else if (IsA(n, A_Star)) |
726 | { |
727 | ereport(ERROR, |
728 | (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
729 | errmsg("row expansion via \"*\" is not supported here" ), |
730 | parser_errposition(pstate, location))); |
731 | } |
732 | else |
733 | { |
734 | FieldStore *fstore; |
735 | Oid baseTypeId; |
736 | int32 baseTypeMod; |
737 | Oid typrelid; |
738 | AttrNumber attnum; |
739 | Oid fieldTypeId; |
740 | int32 fieldTypMod; |
741 | Oid fieldCollation; |
742 | |
743 | Assert(IsA(n, String)); |
744 | |
745 | /* process subscripts before this field selection */ |
746 | if (subscripts) |
747 | { |
748 | /* recurse, and then return because we're done */ |
749 | return transformAssignmentSubscripts(pstate, |
750 | basenode, |
751 | targetName, |
752 | targetTypeId, |
753 | targetTypMod, |
754 | targetCollation, |
755 | subscripts, |
756 | isSlice, |
757 | i, |
758 | rhs, |
759 | location); |
760 | } |
761 | |
762 | /* No subscripts, so can process field selection here */ |
763 | |
764 | /* |
765 | * Look up the composite type, accounting for possibility that |
766 | * what we are given is a domain over composite. |
767 | */ |
768 | baseTypeMod = targetTypMod; |
769 | baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod); |
770 | |
771 | typrelid = typeidTypeRelid(baseTypeId); |
772 | if (!typrelid) |
773 | ereport(ERROR, |
774 | (errcode(ERRCODE_DATATYPE_MISMATCH), |
775 | errmsg("cannot assign to field \"%s\" of column \"%s\" because its type %s is not a composite type" , |
776 | strVal(n), targetName, |
777 | format_type_be(targetTypeId)), |
778 | parser_errposition(pstate, location))); |
779 | |
780 | attnum = get_attnum(typrelid, strVal(n)); |
781 | if (attnum == InvalidAttrNumber) |
782 | ereport(ERROR, |
783 | (errcode(ERRCODE_UNDEFINED_COLUMN), |
784 | errmsg("cannot assign to field \"%s\" of column \"%s\" because there is no such column in data type %s" , |
785 | strVal(n), targetName, |
786 | format_type_be(targetTypeId)), |
787 | parser_errposition(pstate, location))); |
788 | if (attnum < 0) |
789 | ereport(ERROR, |
790 | (errcode(ERRCODE_UNDEFINED_COLUMN), |
791 | errmsg("cannot assign to system column \"%s\"" , |
792 | strVal(n)), |
793 | parser_errposition(pstate, location))); |
794 | |
795 | get_atttypetypmodcoll(typrelid, attnum, |
796 | &fieldTypeId, &fieldTypMod, &fieldCollation); |
797 | |
798 | /* recurse to create appropriate RHS for field assign */ |
799 | rhs = transformAssignmentIndirection(pstate, |
800 | NULL, |
801 | strVal(n), |
802 | false, |
803 | fieldTypeId, |
804 | fieldTypMod, |
805 | fieldCollation, |
806 | lnext(i), |
807 | rhs, |
808 | location); |
809 | |
810 | /* and build a FieldStore node */ |
811 | fstore = makeNode(FieldStore); |
812 | fstore->arg = (Expr *) basenode; |
813 | fstore->newvals = list_make1(rhs); |
814 | fstore->fieldnums = list_make1_int(attnum); |
815 | fstore->resulttype = baseTypeId; |
816 | |
817 | /* If target is a domain, apply constraints */ |
818 | if (baseTypeId != targetTypeId) |
819 | return coerce_to_domain((Node *) fstore, |
820 | baseTypeId, baseTypeMod, |
821 | targetTypeId, |
822 | COERCION_IMPLICIT, |
823 | COERCE_IMPLICIT_CAST, |
824 | location, |
825 | false); |
826 | |
827 | return (Node *) fstore; |
828 | } |
829 | } |
830 | |
831 | /* process trailing subscripts, if any */ |
832 | if (subscripts) |
833 | { |
834 | /* recurse, and then return because we're done */ |
835 | return transformAssignmentSubscripts(pstate, |
836 | basenode, |
837 | targetName, |
838 | targetTypeId, |
839 | targetTypMod, |
840 | targetCollation, |
841 | subscripts, |
842 | isSlice, |
843 | NULL, |
844 | rhs, |
845 | location); |
846 | } |
847 | |
848 | /* base case: just coerce RHS to match target type ID */ |
849 | |
850 | result = coerce_to_target_type(pstate, |
851 | rhs, exprType(rhs), |
852 | targetTypeId, targetTypMod, |
853 | COERCION_ASSIGNMENT, |
854 | COERCE_IMPLICIT_CAST, |
855 | -1); |
856 | if (result == NULL) |
857 | { |
858 | if (targetIsSubscripting) |
859 | ereport(ERROR, |
860 | (errcode(ERRCODE_DATATYPE_MISMATCH), |
861 | errmsg("array assignment to \"%s\" requires type %s" |
862 | " but expression is of type %s" , |
863 | targetName, |
864 | format_type_be(targetTypeId), |
865 | format_type_be(exprType(rhs))), |
866 | errhint("You will need to rewrite or cast the expression." ), |
867 | parser_errposition(pstate, location))); |
868 | else |
869 | ereport(ERROR, |
870 | (errcode(ERRCODE_DATATYPE_MISMATCH), |
871 | errmsg("subfield \"%s\" is of type %s" |
872 | " but expression is of type %s" , |
873 | targetName, |
874 | format_type_be(targetTypeId), |
875 | format_type_be(exprType(rhs))), |
876 | errhint("You will need to rewrite or cast the expression." ), |
877 | parser_errposition(pstate, location))); |
878 | } |
879 | |
880 | return result; |
881 | } |
882 | |
883 | /* |
884 | * helper for transformAssignmentIndirection: process container assignment |
885 | */ |
886 | static Node * |
887 | transformAssignmentSubscripts(ParseState *pstate, |
888 | Node *basenode, |
889 | const char *targetName, |
890 | Oid targetTypeId, |
891 | int32 targetTypMod, |
892 | Oid targetCollation, |
893 | List *subscripts, |
894 | bool isSlice, |
895 | ListCell *next_indirection, |
896 | Node *rhs, |
897 | int location) |
898 | { |
899 | Node *result; |
900 | Oid containerType; |
901 | int32 containerTypMod; |
902 | Oid elementTypeId; |
903 | Oid typeNeeded; |
904 | Oid collationNeeded; |
905 | |
906 | Assert(subscripts != NIL); |
907 | |
908 | /* Identify the actual array type and element type involved */ |
909 | containerType = targetTypeId; |
910 | containerTypMod = targetTypMod; |
911 | elementTypeId = transformContainerType(&containerType, &containerTypMod); |
912 | |
913 | /* Identify type that RHS must provide */ |
914 | typeNeeded = isSlice ? containerType : elementTypeId; |
915 | |
916 | /* |
917 | * container normally has same collation as elements, but there's an |
918 | * exception: we might be subscripting a domain over a container type. In |
919 | * that case use collation of the base type. |
920 | */ |
921 | if (containerType == targetTypeId) |
922 | collationNeeded = targetCollation; |
923 | else |
924 | collationNeeded = get_typcollation(containerType); |
925 | |
926 | /* recurse to create appropriate RHS for container assign */ |
927 | rhs = transformAssignmentIndirection(pstate, |
928 | NULL, |
929 | targetName, |
930 | true, |
931 | typeNeeded, |
932 | containerTypMod, |
933 | collationNeeded, |
934 | next_indirection, |
935 | rhs, |
936 | location); |
937 | |
938 | /* process subscripts */ |
939 | result = (Node *) transformContainerSubscripts(pstate, |
940 | basenode, |
941 | containerType, |
942 | elementTypeId, |
943 | containerTypMod, |
944 | subscripts, |
945 | rhs); |
946 | |
947 | /* If target was a domain over container, need to coerce up to the domain */ |
948 | if (containerType != targetTypeId) |
949 | { |
950 | Oid resulttype = exprType(result); |
951 | |
952 | result = coerce_to_target_type(pstate, |
953 | result, resulttype, |
954 | targetTypeId, targetTypMod, |
955 | COERCION_ASSIGNMENT, |
956 | COERCE_IMPLICIT_CAST, |
957 | -1); |
958 | /* can fail if we had int2vector/oidvector, but not for true domains */ |
959 | if (result == NULL) |
960 | ereport(ERROR, |
961 | (errcode(ERRCODE_CANNOT_COERCE), |
962 | errmsg("cannot cast type %s to %s" , |
963 | format_type_be(resulttype), |
964 | format_type_be(targetTypeId)), |
965 | parser_errposition(pstate, location))); |
966 | } |
967 | |
968 | return result; |
969 | } |
970 | |
971 | |
972 | /* |
973 | * checkInsertTargets - |
974 | * generate a list of INSERT column targets if not supplied, or |
975 | * test supplied column names to make sure they are in target table. |
976 | * Also return an integer list of the columns' attribute numbers. |
977 | */ |
978 | List * |
979 | checkInsertTargets(ParseState *pstate, List *cols, List **attrnos) |
980 | { |
981 | *attrnos = NIL; |
982 | |
983 | if (cols == NIL) |
984 | { |
985 | /* |
986 | * Generate default column list for INSERT. |
987 | */ |
988 | int numcol = RelationGetNumberOfAttributes(pstate->p_target_relation); |
989 | |
990 | int i; |
991 | |
992 | for (i = 0; i < numcol; i++) |
993 | { |
994 | ResTarget *col; |
995 | Form_pg_attribute attr; |
996 | |
997 | attr = TupleDescAttr(pstate->p_target_relation->rd_att, i); |
998 | |
999 | if (attr->attisdropped) |
1000 | continue; |
1001 | |
1002 | col = makeNode(ResTarget); |
1003 | col->name = pstrdup(NameStr(attr->attname)); |
1004 | col->indirection = NIL; |
1005 | col->val = NULL; |
1006 | col->location = -1; |
1007 | cols = lappend(cols, col); |
1008 | *attrnos = lappend_int(*attrnos, i + 1); |
1009 | } |
1010 | } |
1011 | else |
1012 | { |
1013 | /* |
1014 | * Do initial validation of user-supplied INSERT column list. |
1015 | */ |
1016 | Bitmapset *wholecols = NULL; |
1017 | Bitmapset *partialcols = NULL; |
1018 | ListCell *tl; |
1019 | |
1020 | foreach(tl, cols) |
1021 | { |
1022 | ResTarget *col = (ResTarget *) lfirst(tl); |
1023 | char *name = col->name; |
1024 | int attrno; |
1025 | |
1026 | /* Lookup column name, ereport on failure */ |
1027 | attrno = attnameAttNum(pstate->p_target_relation, name, false); |
1028 | if (attrno == InvalidAttrNumber) |
1029 | ereport(ERROR, |
1030 | (errcode(ERRCODE_UNDEFINED_COLUMN), |
1031 | errmsg("column \"%s\" of relation \"%s\" does not exist" , |
1032 | name, |
1033 | RelationGetRelationName(pstate->p_target_relation)), |
1034 | parser_errposition(pstate, col->location))); |
1035 | |
1036 | /* |
1037 | * Check for duplicates, but only of whole columns --- we allow |
1038 | * INSERT INTO foo (col.subcol1, col.subcol2) |
1039 | */ |
1040 | if (col->indirection == NIL) |
1041 | { |
1042 | /* whole column; must not have any other assignment */ |
1043 | if (bms_is_member(attrno, wholecols) || |
1044 | bms_is_member(attrno, partialcols)) |
1045 | ereport(ERROR, |
1046 | (errcode(ERRCODE_DUPLICATE_COLUMN), |
1047 | errmsg("column \"%s\" specified more than once" , |
1048 | name), |
1049 | parser_errposition(pstate, col->location))); |
1050 | wholecols = bms_add_member(wholecols, attrno); |
1051 | } |
1052 | else |
1053 | { |
1054 | /* partial column; must not have any whole assignment */ |
1055 | if (bms_is_member(attrno, wholecols)) |
1056 | ereport(ERROR, |
1057 | (errcode(ERRCODE_DUPLICATE_COLUMN), |
1058 | errmsg("column \"%s\" specified more than once" , |
1059 | name), |
1060 | parser_errposition(pstate, col->location))); |
1061 | partialcols = bms_add_member(partialcols, attrno); |
1062 | } |
1063 | |
1064 | *attrnos = lappend_int(*attrnos, attrno); |
1065 | } |
1066 | } |
1067 | |
1068 | return cols; |
1069 | } |
1070 | |
1071 | /* |
1072 | * ExpandColumnRefStar() |
1073 | * Transforms foo.* into a list of expressions or targetlist entries. |
1074 | * |
1075 | * This handles the case where '*' appears as the last or only item in a |
1076 | * ColumnRef. The code is shared between the case of foo.* at the top level |
1077 | * in a SELECT target list (where we want TargetEntry nodes in the result) |
1078 | * and foo.* in a ROW() or VALUES() construct (where we want just bare |
1079 | * expressions). |
1080 | * |
1081 | * The referenced columns are marked as requiring SELECT access. |
1082 | */ |
1083 | static List * |
1084 | ExpandColumnRefStar(ParseState *pstate, ColumnRef *cref, |
1085 | bool make_target_entry) |
1086 | { |
1087 | List *fields = cref->fields; |
1088 | int numnames = list_length(fields); |
1089 | |
1090 | if (numnames == 1) |
1091 | { |
1092 | /* |
1093 | * Target item is a bare '*', expand all tables |
1094 | * |
1095 | * (e.g., SELECT * FROM emp, dept) |
1096 | * |
1097 | * Since the grammar only accepts bare '*' at top level of SELECT, we |
1098 | * need not handle the make_target_entry==false case here. |
1099 | */ |
1100 | Assert(make_target_entry); |
1101 | return ExpandAllTables(pstate, cref->location); |
1102 | } |
1103 | else |
1104 | { |
1105 | /* |
1106 | * Target item is relation.*, expand that table |
1107 | * |
1108 | * (e.g., SELECT emp.*, dname FROM emp, dept) |
1109 | * |
1110 | * Note: this code is a lot like transformColumnRef; it's tempting to |
1111 | * call that instead and then replace the resulting whole-row Var with |
1112 | * a list of Vars. However, that would leave us with the RTE's |
1113 | * selectedCols bitmap showing the whole row as needing select |
1114 | * permission, as well as the individual columns. That would be |
1115 | * incorrect (since columns added later shouldn't need select |
1116 | * permissions). We could try to remove the whole-row permission bit |
1117 | * after the fact, but duplicating code is less messy. |
1118 | */ |
1119 | char *nspname = NULL; |
1120 | char *relname = NULL; |
1121 | RangeTblEntry *rte = NULL; |
1122 | int levels_up; |
1123 | enum |
1124 | { |
1125 | CRSERR_NO_RTE, |
1126 | CRSERR_WRONG_DB, |
1127 | CRSERR_TOO_MANY |
1128 | } crserr = CRSERR_NO_RTE; |
1129 | |
1130 | /* |
1131 | * Give the PreParseColumnRefHook, if any, first shot. If it returns |
1132 | * non-null then we should use that expression. |
1133 | */ |
1134 | if (pstate->p_pre_columnref_hook != NULL) |
1135 | { |
1136 | Node *node; |
1137 | |
1138 | node = pstate->p_pre_columnref_hook(pstate, cref); |
1139 | if (node != NULL) |
1140 | return ExpandRowReference(pstate, node, make_target_entry); |
1141 | } |
1142 | |
1143 | switch (numnames) |
1144 | { |
1145 | case 2: |
1146 | relname = strVal(linitial(fields)); |
1147 | rte = refnameRangeTblEntry(pstate, nspname, relname, |
1148 | cref->location, |
1149 | &levels_up); |
1150 | break; |
1151 | case 3: |
1152 | nspname = strVal(linitial(fields)); |
1153 | relname = strVal(lsecond(fields)); |
1154 | rte = refnameRangeTblEntry(pstate, nspname, relname, |
1155 | cref->location, |
1156 | &levels_up); |
1157 | break; |
1158 | case 4: |
1159 | { |
1160 | char *catname = strVal(linitial(fields)); |
1161 | |
1162 | /* |
1163 | * We check the catalog name and then ignore it. |
1164 | */ |
1165 | if (strcmp(catname, get_database_name(MyDatabaseId)) != 0) |
1166 | { |
1167 | crserr = CRSERR_WRONG_DB; |
1168 | break; |
1169 | } |
1170 | nspname = strVal(lsecond(fields)); |
1171 | relname = strVal(lthird(fields)); |
1172 | rte = refnameRangeTblEntry(pstate, nspname, relname, |
1173 | cref->location, |
1174 | &levels_up); |
1175 | break; |
1176 | } |
1177 | default: |
1178 | crserr = CRSERR_TOO_MANY; |
1179 | break; |
1180 | } |
1181 | |
1182 | /* |
1183 | * Now give the PostParseColumnRefHook, if any, a chance. We cheat a |
1184 | * bit by passing the RangeTblEntry, not a Var, as the planned |
1185 | * translation. (A single Var wouldn't be strictly correct anyway. |
1186 | * This convention allows hooks that really care to know what is |
1187 | * happening.) |
1188 | */ |
1189 | if (pstate->p_post_columnref_hook != NULL) |
1190 | { |
1191 | Node *node; |
1192 | |
1193 | node = pstate->p_post_columnref_hook(pstate, cref, |
1194 | (Node *) rte); |
1195 | if (node != NULL) |
1196 | { |
1197 | if (rte != NULL) |
1198 | ereport(ERROR, |
1199 | (errcode(ERRCODE_AMBIGUOUS_COLUMN), |
1200 | errmsg("column reference \"%s\" is ambiguous" , |
1201 | NameListToString(cref->fields)), |
1202 | parser_errposition(pstate, cref->location))); |
1203 | return ExpandRowReference(pstate, node, make_target_entry); |
1204 | } |
1205 | } |
1206 | |
1207 | /* |
1208 | * Throw error if no translation found. |
1209 | */ |
1210 | if (rte == NULL) |
1211 | { |
1212 | switch (crserr) |
1213 | { |
1214 | case CRSERR_NO_RTE: |
1215 | errorMissingRTE(pstate, makeRangeVar(nspname, relname, |
1216 | cref->location)); |
1217 | break; |
1218 | case CRSERR_WRONG_DB: |
1219 | ereport(ERROR, |
1220 | (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
1221 | errmsg("cross-database references are not implemented: %s" , |
1222 | NameListToString(cref->fields)), |
1223 | parser_errposition(pstate, cref->location))); |
1224 | break; |
1225 | case CRSERR_TOO_MANY: |
1226 | ereport(ERROR, |
1227 | (errcode(ERRCODE_SYNTAX_ERROR), |
1228 | errmsg("improper qualified name (too many dotted names): %s" , |
1229 | NameListToString(cref->fields)), |
1230 | parser_errposition(pstate, cref->location))); |
1231 | break; |
1232 | } |
1233 | } |
1234 | |
1235 | /* |
1236 | * OK, expand the RTE into fields. |
1237 | */ |
1238 | return ExpandSingleTable(pstate, rte, cref->location, make_target_entry); |
1239 | } |
1240 | } |
1241 | |
1242 | /* |
1243 | * ExpandAllTables() |
1244 | * Transforms '*' (in the target list) into a list of targetlist entries. |
1245 | * |
1246 | * tlist entries are generated for each relation visible for unqualified |
1247 | * column name access. We do not consider qualified-name-only entries because |
1248 | * that would include input tables of aliasless JOINs, NEW/OLD pseudo-entries, |
1249 | * etc. |
1250 | * |
1251 | * The referenced relations/columns are marked as requiring SELECT access. |
1252 | */ |
1253 | static List * |
1254 | ExpandAllTables(ParseState *pstate, int location) |
1255 | { |
1256 | List *target = NIL; |
1257 | bool found_table = false; |
1258 | ListCell *l; |
1259 | |
1260 | foreach(l, pstate->p_namespace) |
1261 | { |
1262 | ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(l); |
1263 | RangeTblEntry *rte = nsitem->p_rte; |
1264 | |
1265 | /* Ignore table-only items */ |
1266 | if (!nsitem->p_cols_visible) |
1267 | continue; |
1268 | /* Should not have any lateral-only items when parsing targetlist */ |
1269 | Assert(!nsitem->p_lateral_only); |
1270 | /* Remember we found a p_cols_visible item */ |
1271 | found_table = true; |
1272 | |
1273 | target = list_concat(target, |
1274 | expandRelAttrs(pstate, |
1275 | rte, |
1276 | RTERangeTablePosn(pstate, rte, |
1277 | NULL), |
1278 | 0, |
1279 | location)); |
1280 | } |
1281 | |
1282 | /* |
1283 | * Check for "SELECT *;". We do it this way, rather than checking for |
1284 | * target == NIL, because we want to allow SELECT * FROM a zero_column |
1285 | * table. |
1286 | */ |
1287 | if (!found_table) |
1288 | ereport(ERROR, |
1289 | (errcode(ERRCODE_SYNTAX_ERROR), |
1290 | errmsg("SELECT * with no tables specified is not valid" ), |
1291 | parser_errposition(pstate, location))); |
1292 | |
1293 | return target; |
1294 | } |
1295 | |
1296 | /* |
1297 | * ExpandIndirectionStar() |
1298 | * Transforms foo.* into a list of expressions or targetlist entries. |
1299 | * |
1300 | * This handles the case where '*' appears as the last item in A_Indirection. |
1301 | * The code is shared between the case of foo.* at the top level in a SELECT |
1302 | * target list (where we want TargetEntry nodes in the result) and foo.* in |
1303 | * a ROW() or VALUES() construct (where we want just bare expressions). |
1304 | * For robustness, we use a separate "make_target_entry" flag to control |
1305 | * this rather than relying on exprKind. |
1306 | */ |
1307 | static List * |
1308 | ExpandIndirectionStar(ParseState *pstate, A_Indirection *ind, |
1309 | bool make_target_entry, ParseExprKind exprKind) |
1310 | { |
1311 | Node *expr; |
1312 | |
1313 | /* Strip off the '*' to create a reference to the rowtype object */ |
1314 | ind = copyObject(ind); |
1315 | ind->indirection = list_truncate(ind->indirection, |
1316 | list_length(ind->indirection) - 1); |
1317 | |
1318 | /* And transform that */ |
1319 | expr = transformExpr(pstate, (Node *) ind, exprKind); |
1320 | |
1321 | /* Expand the rowtype expression into individual fields */ |
1322 | return ExpandRowReference(pstate, expr, make_target_entry); |
1323 | } |
1324 | |
1325 | /* |
1326 | * ExpandSingleTable() |
1327 | * Transforms foo.* into a list of expressions or targetlist entries. |
1328 | * |
1329 | * This handles the case where foo has been determined to be a simple |
1330 | * reference to an RTE, so we can just generate Vars for the expressions. |
1331 | * |
1332 | * The referenced columns are marked as requiring SELECT access. |
1333 | */ |
1334 | static List * |
1335 | ExpandSingleTable(ParseState *pstate, RangeTblEntry *rte, |
1336 | int location, bool make_target_entry) |
1337 | { |
1338 | int sublevels_up; |
1339 | int rtindex; |
1340 | |
1341 | rtindex = RTERangeTablePosn(pstate, rte, &sublevels_up); |
1342 | |
1343 | if (make_target_entry) |
1344 | { |
1345 | /* expandRelAttrs handles permissions marking */ |
1346 | return expandRelAttrs(pstate, rte, rtindex, sublevels_up, |
1347 | location); |
1348 | } |
1349 | else |
1350 | { |
1351 | List *vars; |
1352 | ListCell *l; |
1353 | |
1354 | expandRTE(rte, rtindex, sublevels_up, location, false, |
1355 | NULL, &vars); |
1356 | |
1357 | /* |
1358 | * Require read access to the table. This is normally redundant with |
1359 | * the markVarForSelectPriv calls below, but not if the table has zero |
1360 | * columns. |
1361 | */ |
1362 | rte->requiredPerms |= ACL_SELECT; |
1363 | |
1364 | /* Require read access to each column */ |
1365 | foreach(l, vars) |
1366 | { |
1367 | Var *var = (Var *) lfirst(l); |
1368 | |
1369 | markVarForSelectPriv(pstate, var, rte); |
1370 | } |
1371 | |
1372 | return vars; |
1373 | } |
1374 | } |
1375 | |
1376 | /* |
1377 | * ExpandRowReference() |
1378 | * Transforms foo.* into a list of expressions or targetlist entries. |
1379 | * |
1380 | * This handles the case where foo is an arbitrary expression of composite |
1381 | * type. |
1382 | */ |
1383 | static List * |
1384 | ExpandRowReference(ParseState *pstate, Node *expr, |
1385 | bool make_target_entry) |
1386 | { |
1387 | List *result = NIL; |
1388 | TupleDesc tupleDesc; |
1389 | int numAttrs; |
1390 | int i; |
1391 | |
1392 | /* |
1393 | * If the rowtype expression is a whole-row Var, we can expand the fields |
1394 | * as simple Vars. Note: if the RTE is a relation, this case leaves us |
1395 | * with the RTE's selectedCols bitmap showing the whole row as needing |
1396 | * select permission, as well as the individual columns. However, we can |
1397 | * only get here for weird notations like (table.*).*, so it's not worth |
1398 | * trying to clean up --- arguably, the permissions marking is correct |
1399 | * anyway for such cases. |
1400 | */ |
1401 | if (IsA(expr, Var) && |
1402 | ((Var *) expr)->varattno == InvalidAttrNumber) |
1403 | { |
1404 | Var *var = (Var *) expr; |
1405 | RangeTblEntry *rte; |
1406 | |
1407 | rte = GetRTEByRangeTablePosn(pstate, var->varno, var->varlevelsup); |
1408 | return ExpandSingleTable(pstate, rte, var->location, make_target_entry); |
1409 | } |
1410 | |
1411 | /* |
1412 | * Otherwise we have to do it the hard way. Our current implementation is |
1413 | * to generate multiple copies of the expression and do FieldSelects. |
1414 | * (This can be pretty inefficient if the expression involves nontrivial |
1415 | * computation :-(.) |
1416 | * |
1417 | * Verify it's a composite type, and get the tupdesc. |
1418 | * get_expr_result_tupdesc() handles this conveniently. |
1419 | * |
1420 | * If it's a Var of type RECORD, we have to work even harder: we have to |
1421 | * find what the Var refers to, and pass that to get_expr_result_tupdesc. |
1422 | * That task is handled by expandRecordVariable(). |
1423 | */ |
1424 | if (IsA(expr, Var) && |
1425 | ((Var *) expr)->vartype == RECORDOID) |
1426 | tupleDesc = expandRecordVariable(pstate, (Var *) expr, 0); |
1427 | else |
1428 | tupleDesc = get_expr_result_tupdesc(expr, false); |
1429 | Assert(tupleDesc); |
1430 | |
1431 | /* Generate a list of references to the individual fields */ |
1432 | numAttrs = tupleDesc->natts; |
1433 | for (i = 0; i < numAttrs; i++) |
1434 | { |
1435 | Form_pg_attribute att = TupleDescAttr(tupleDesc, i); |
1436 | FieldSelect *fselect; |
1437 | |
1438 | if (att->attisdropped) |
1439 | continue; |
1440 | |
1441 | fselect = makeNode(FieldSelect); |
1442 | fselect->arg = (Expr *) copyObject(expr); |
1443 | fselect->fieldnum = i + 1; |
1444 | fselect->resulttype = att->atttypid; |
1445 | fselect->resulttypmod = att->atttypmod; |
1446 | /* save attribute's collation for parse_collate.c */ |
1447 | fselect->resultcollid = att->attcollation; |
1448 | |
1449 | if (make_target_entry) |
1450 | { |
1451 | /* add TargetEntry decoration */ |
1452 | TargetEntry *te; |
1453 | |
1454 | te = makeTargetEntry((Expr *) fselect, |
1455 | (AttrNumber) pstate->p_next_resno++, |
1456 | pstrdup(NameStr(att->attname)), |
1457 | false); |
1458 | result = lappend(result, te); |
1459 | } |
1460 | else |
1461 | result = lappend(result, fselect); |
1462 | } |
1463 | |
1464 | return result; |
1465 | } |
1466 | |
1467 | /* |
1468 | * expandRecordVariable |
1469 | * Get the tuple descriptor for a Var of type RECORD, if possible. |
1470 | * |
1471 | * Since no actual table or view column is allowed to have type RECORD, such |
1472 | * a Var must refer to a JOIN or FUNCTION RTE or to a subquery output. We |
1473 | * drill down to find the ultimate defining expression and attempt to infer |
1474 | * the tupdesc from it. We ereport if we can't determine the tupdesc. |
1475 | * |
1476 | * levelsup is an extra offset to interpret the Var's varlevelsup correctly. |
1477 | */ |
1478 | TupleDesc |
1479 | expandRecordVariable(ParseState *pstate, Var *var, int levelsup) |
1480 | { |
1481 | TupleDesc tupleDesc; |
1482 | int netlevelsup; |
1483 | RangeTblEntry *rte; |
1484 | AttrNumber attnum; |
1485 | Node *expr; |
1486 | |
1487 | /* Check my caller didn't mess up */ |
1488 | Assert(IsA(var, Var)); |
1489 | Assert(var->vartype == RECORDOID); |
1490 | |
1491 | netlevelsup = var->varlevelsup + levelsup; |
1492 | rte = GetRTEByRangeTablePosn(pstate, var->varno, netlevelsup); |
1493 | attnum = var->varattno; |
1494 | |
1495 | if (attnum == InvalidAttrNumber) |
1496 | { |
1497 | /* Whole-row reference to an RTE, so expand the known fields */ |
1498 | List *names, |
1499 | *vars; |
1500 | ListCell *lname, |
1501 | *lvar; |
1502 | int i; |
1503 | |
1504 | expandRTE(rte, var->varno, 0, var->location, false, |
1505 | &names, &vars); |
1506 | |
1507 | tupleDesc = CreateTemplateTupleDesc(list_length(vars)); |
1508 | i = 1; |
1509 | forboth(lname, names, lvar, vars) |
1510 | { |
1511 | char *label = strVal(lfirst(lname)); |
1512 | Node *varnode = (Node *) lfirst(lvar); |
1513 | |
1514 | TupleDescInitEntry(tupleDesc, i, |
1515 | label, |
1516 | exprType(varnode), |
1517 | exprTypmod(varnode), |
1518 | 0); |
1519 | TupleDescInitEntryCollation(tupleDesc, i, |
1520 | exprCollation(varnode)); |
1521 | i++; |
1522 | } |
1523 | Assert(lname == NULL && lvar == NULL); /* lists same length? */ |
1524 | |
1525 | return tupleDesc; |
1526 | } |
1527 | |
1528 | expr = (Node *) var; /* default if we can't drill down */ |
1529 | |
1530 | switch (rte->rtekind) |
1531 | { |
1532 | case RTE_RELATION: |
1533 | case RTE_VALUES: |
1534 | case RTE_NAMEDTUPLESTORE: |
1535 | case RTE_RESULT: |
1536 | |
1537 | /* |
1538 | * This case should not occur: a column of a table, values list, |
1539 | * or ENR shouldn't have type RECORD. Fall through and fail (most |
1540 | * likely) at the bottom. |
1541 | */ |
1542 | break; |
1543 | case RTE_SUBQUERY: |
1544 | { |
1545 | /* Subselect-in-FROM: examine sub-select's output expr */ |
1546 | TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList, |
1547 | attnum); |
1548 | |
1549 | if (ste == NULL || ste->resjunk) |
1550 | elog(ERROR, "subquery %s does not have attribute %d" , |
1551 | rte->eref->aliasname, attnum); |
1552 | expr = (Node *) ste->expr; |
1553 | if (IsA(expr, Var)) |
1554 | { |
1555 | /* |
1556 | * Recurse into the sub-select to see what its Var refers |
1557 | * to. We have to build an additional level of ParseState |
1558 | * to keep in step with varlevelsup in the subselect. |
1559 | */ |
1560 | ParseState mypstate; |
1561 | |
1562 | MemSet(&mypstate, 0, sizeof(mypstate)); |
1563 | mypstate.parentParseState = pstate; |
1564 | mypstate.p_rtable = rte->subquery->rtable; |
1565 | /* don't bother filling the rest of the fake pstate */ |
1566 | |
1567 | return expandRecordVariable(&mypstate, (Var *) expr, 0); |
1568 | } |
1569 | /* else fall through to inspect the expression */ |
1570 | } |
1571 | break; |
1572 | case RTE_JOIN: |
1573 | /* Join RTE --- recursively inspect the alias variable */ |
1574 | Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars)); |
1575 | expr = (Node *) list_nth(rte->joinaliasvars, attnum - 1); |
1576 | Assert(expr != NULL); |
1577 | /* We intentionally don't strip implicit coercions here */ |
1578 | if (IsA(expr, Var)) |
1579 | return expandRecordVariable(pstate, (Var *) expr, netlevelsup); |
1580 | /* else fall through to inspect the expression */ |
1581 | break; |
1582 | case RTE_FUNCTION: |
1583 | |
1584 | /* |
1585 | * We couldn't get here unless a function is declared with one of |
1586 | * its result columns as RECORD, which is not allowed. |
1587 | */ |
1588 | break; |
1589 | case RTE_TABLEFUNC: |
1590 | |
1591 | /* |
1592 | * Table function cannot have columns with RECORD type. |
1593 | */ |
1594 | break; |
1595 | case RTE_CTE: |
1596 | /* CTE reference: examine subquery's output expr */ |
1597 | if (!rte->self_reference) |
1598 | { |
1599 | CommonTableExpr *cte = GetCTEForRTE(pstate, rte, netlevelsup); |
1600 | TargetEntry *ste; |
1601 | |
1602 | ste = get_tle_by_resno(GetCTETargetList(cte), attnum); |
1603 | if (ste == NULL || ste->resjunk) |
1604 | elog(ERROR, "subquery %s does not have attribute %d" , |
1605 | rte->eref->aliasname, attnum); |
1606 | expr = (Node *) ste->expr; |
1607 | if (IsA(expr, Var)) |
1608 | { |
1609 | /* |
1610 | * Recurse into the CTE to see what its Var refers to. We |
1611 | * have to build an additional level of ParseState to keep |
1612 | * in step with varlevelsup in the CTE; furthermore it |
1613 | * could be an outer CTE. |
1614 | */ |
1615 | ParseState mypstate; |
1616 | Index levelsup; |
1617 | |
1618 | MemSet(&mypstate, 0, sizeof(mypstate)); |
1619 | /* this loop must work, since GetCTEForRTE did */ |
1620 | for (levelsup = 0; |
1621 | levelsup < rte->ctelevelsup + netlevelsup; |
1622 | levelsup++) |
1623 | pstate = pstate->parentParseState; |
1624 | mypstate.parentParseState = pstate; |
1625 | mypstate.p_rtable = ((Query *) cte->ctequery)->rtable; |
1626 | /* don't bother filling the rest of the fake pstate */ |
1627 | |
1628 | return expandRecordVariable(&mypstate, (Var *) expr, 0); |
1629 | } |
1630 | /* else fall through to inspect the expression */ |
1631 | } |
1632 | break; |
1633 | } |
1634 | |
1635 | /* |
1636 | * We now have an expression we can't expand any more, so see if |
1637 | * get_expr_result_tupdesc() can do anything with it. |
1638 | */ |
1639 | return get_expr_result_tupdesc(expr, false); |
1640 | } |
1641 | |
1642 | |
1643 | /* |
1644 | * FigureColname - |
1645 | * if the name of the resulting column is not specified in the target |
1646 | * list, we have to guess a suitable name. The SQL spec provides some |
1647 | * guidance, but not much... |
1648 | * |
1649 | * Note that the argument is the *untransformed* parse tree for the target |
1650 | * item. This is a shade easier to work with than the transformed tree. |
1651 | */ |
1652 | char * |
1653 | FigureColname(Node *node) |
1654 | { |
1655 | char *name = NULL; |
1656 | |
1657 | (void) FigureColnameInternal(node, &name); |
1658 | if (name != NULL) |
1659 | return name; |
1660 | /* default result if we can't guess anything */ |
1661 | return "?column?" ; |
1662 | } |
1663 | |
1664 | /* |
1665 | * FigureIndexColname - |
1666 | * choose the name for an expression column in an index |
1667 | * |
1668 | * This is actually just like FigureColname, except we return NULL if |
1669 | * we can't pick a good name. |
1670 | */ |
1671 | char * |
1672 | FigureIndexColname(Node *node) |
1673 | { |
1674 | char *name = NULL; |
1675 | |
1676 | (void) FigureColnameInternal(node, &name); |
1677 | return name; |
1678 | } |
1679 | |
1680 | /* |
1681 | * FigureColnameInternal - |
1682 | * internal workhorse for FigureColname |
1683 | * |
1684 | * Return value indicates strength of confidence in result: |
1685 | * 0 - no information |
1686 | * 1 - second-best name choice |
1687 | * 2 - good name choice |
1688 | * The return value is actually only used internally. |
1689 | * If the result isn't zero, *name is set to the chosen name. |
1690 | */ |
1691 | static int |
1692 | FigureColnameInternal(Node *node, char **name) |
1693 | { |
1694 | int strength = 0; |
1695 | |
1696 | if (node == NULL) |
1697 | return strength; |
1698 | |
1699 | switch (nodeTag(node)) |
1700 | { |
1701 | case T_ColumnRef: |
1702 | { |
1703 | char *fname = NULL; |
1704 | ListCell *l; |
1705 | |
1706 | /* find last field name, if any, ignoring "*" */ |
1707 | foreach(l, ((ColumnRef *) node)->fields) |
1708 | { |
1709 | Node *i = lfirst(l); |
1710 | |
1711 | if (IsA(i, String)) |
1712 | fname = strVal(i); |
1713 | } |
1714 | if (fname) |
1715 | { |
1716 | *name = fname; |
1717 | return 2; |
1718 | } |
1719 | } |
1720 | break; |
1721 | case T_A_Indirection: |
1722 | { |
1723 | A_Indirection *ind = (A_Indirection *) node; |
1724 | char *fname = NULL; |
1725 | ListCell *l; |
1726 | |
1727 | /* find last field name, if any, ignoring "*" and subscripts */ |
1728 | foreach(l, ind->indirection) |
1729 | { |
1730 | Node *i = lfirst(l); |
1731 | |
1732 | if (IsA(i, String)) |
1733 | fname = strVal(i); |
1734 | } |
1735 | if (fname) |
1736 | { |
1737 | *name = fname; |
1738 | return 2; |
1739 | } |
1740 | return FigureColnameInternal(ind->arg, name); |
1741 | } |
1742 | break; |
1743 | case T_FuncCall: |
1744 | *name = strVal(llast(((FuncCall *) node)->funcname)); |
1745 | return 2; |
1746 | case T_A_Expr: |
1747 | if (((A_Expr *) node)->kind == AEXPR_NULLIF) |
1748 | { |
1749 | /* make nullif() act like a regular function */ |
1750 | *name = "nullif" ; |
1751 | return 2; |
1752 | } |
1753 | if (((A_Expr *) node)->kind == AEXPR_PAREN) |
1754 | { |
1755 | /* look through dummy parenthesis node */ |
1756 | return FigureColnameInternal(((A_Expr *) node)->lexpr, name); |
1757 | } |
1758 | break; |
1759 | case T_TypeCast: |
1760 | strength = FigureColnameInternal(((TypeCast *) node)->arg, |
1761 | name); |
1762 | if (strength <= 1) |
1763 | { |
1764 | if (((TypeCast *) node)->typeName != NULL) |
1765 | { |
1766 | *name = strVal(llast(((TypeCast *) node)->typeName->names)); |
1767 | return 1; |
1768 | } |
1769 | } |
1770 | break; |
1771 | case T_CollateClause: |
1772 | return FigureColnameInternal(((CollateClause *) node)->arg, name); |
1773 | case T_GroupingFunc: |
1774 | /* make GROUPING() act like a regular function */ |
1775 | *name = "grouping" ; |
1776 | return 2; |
1777 | case T_SubLink: |
1778 | switch (((SubLink *) node)->subLinkType) |
1779 | { |
1780 | case EXISTS_SUBLINK: |
1781 | *name = "exists" ; |
1782 | return 2; |
1783 | case ARRAY_SUBLINK: |
1784 | *name = "array" ; |
1785 | return 2; |
1786 | case EXPR_SUBLINK: |
1787 | { |
1788 | /* Get column name of the subquery's single target */ |
1789 | SubLink *sublink = (SubLink *) node; |
1790 | Query *query = (Query *) sublink->subselect; |
1791 | |
1792 | /* |
1793 | * The subquery has probably already been transformed, |
1794 | * but let's be careful and check that. (The reason |
1795 | * we can see a transformed subquery here is that |
1796 | * transformSubLink is lazy and modifies the SubLink |
1797 | * node in-place.) |
1798 | */ |
1799 | if (IsA(query, Query)) |
1800 | { |
1801 | TargetEntry *te = (TargetEntry *) linitial(query->targetList); |
1802 | |
1803 | if (te->resname) |
1804 | { |
1805 | *name = te->resname; |
1806 | return 2; |
1807 | } |
1808 | } |
1809 | } |
1810 | break; |
1811 | /* As with other operator-like nodes, these have no names */ |
1812 | case MULTIEXPR_SUBLINK: |
1813 | case ALL_SUBLINK: |
1814 | case ANY_SUBLINK: |
1815 | case ROWCOMPARE_SUBLINK: |
1816 | case CTE_SUBLINK: |
1817 | break; |
1818 | } |
1819 | break; |
1820 | case T_CaseExpr: |
1821 | strength = FigureColnameInternal((Node *) ((CaseExpr *) node)->defresult, |
1822 | name); |
1823 | if (strength <= 1) |
1824 | { |
1825 | *name = "case" ; |
1826 | return 1; |
1827 | } |
1828 | break; |
1829 | case T_A_ArrayExpr: |
1830 | /* make ARRAY[] act like a function */ |
1831 | *name = "array" ; |
1832 | return 2; |
1833 | case T_RowExpr: |
1834 | /* make ROW() act like a function */ |
1835 | *name = "row" ; |
1836 | return 2; |
1837 | case T_CoalesceExpr: |
1838 | /* make coalesce() act like a regular function */ |
1839 | *name = "coalesce" ; |
1840 | return 2; |
1841 | case T_MinMaxExpr: |
1842 | /* make greatest/least act like a regular function */ |
1843 | switch (((MinMaxExpr *) node)->op) |
1844 | { |
1845 | case IS_GREATEST: |
1846 | *name = "greatest" ; |
1847 | return 2; |
1848 | case IS_LEAST: |
1849 | *name = "least" ; |
1850 | return 2; |
1851 | } |
1852 | break; |
1853 | case T_SQLValueFunction: |
1854 | /* make these act like a function or variable */ |
1855 | switch (((SQLValueFunction *) node)->op) |
1856 | { |
1857 | case SVFOP_CURRENT_DATE: |
1858 | *name = "current_date" ; |
1859 | return 2; |
1860 | case SVFOP_CURRENT_TIME: |
1861 | case SVFOP_CURRENT_TIME_N: |
1862 | *name = "current_time" ; |
1863 | return 2; |
1864 | case SVFOP_CURRENT_TIMESTAMP: |
1865 | case SVFOP_CURRENT_TIMESTAMP_N: |
1866 | *name = "current_timestamp" ; |
1867 | return 2; |
1868 | case SVFOP_LOCALTIME: |
1869 | case SVFOP_LOCALTIME_N: |
1870 | *name = "localtime" ; |
1871 | return 2; |
1872 | case SVFOP_LOCALTIMESTAMP: |
1873 | case SVFOP_LOCALTIMESTAMP_N: |
1874 | *name = "localtimestamp" ; |
1875 | return 2; |
1876 | case SVFOP_CURRENT_ROLE: |
1877 | *name = "current_role" ; |
1878 | return 2; |
1879 | case SVFOP_CURRENT_USER: |
1880 | *name = "current_user" ; |
1881 | return 2; |
1882 | case SVFOP_USER: |
1883 | *name = "user" ; |
1884 | return 2; |
1885 | case SVFOP_SESSION_USER: |
1886 | *name = "session_user" ; |
1887 | return 2; |
1888 | case SVFOP_CURRENT_CATALOG: |
1889 | *name = "current_catalog" ; |
1890 | return 2; |
1891 | case SVFOP_CURRENT_SCHEMA: |
1892 | *name = "current_schema" ; |
1893 | return 2; |
1894 | } |
1895 | break; |
1896 | case T_XmlExpr: |
1897 | /* make SQL/XML functions act like a regular function */ |
1898 | switch (((XmlExpr *) node)->op) |
1899 | { |
1900 | case IS_XMLCONCAT: |
1901 | *name = "xmlconcat" ; |
1902 | return 2; |
1903 | case IS_XMLELEMENT: |
1904 | *name = "xmlelement" ; |
1905 | return 2; |
1906 | case IS_XMLFOREST: |
1907 | *name = "xmlforest" ; |
1908 | return 2; |
1909 | case IS_XMLPARSE: |
1910 | *name = "xmlparse" ; |
1911 | return 2; |
1912 | case IS_XMLPI: |
1913 | *name = "xmlpi" ; |
1914 | return 2; |
1915 | case IS_XMLROOT: |
1916 | *name = "xmlroot" ; |
1917 | return 2; |
1918 | case IS_XMLSERIALIZE: |
1919 | *name = "xmlserialize" ; |
1920 | return 2; |
1921 | case IS_DOCUMENT: |
1922 | /* nothing */ |
1923 | break; |
1924 | } |
1925 | break; |
1926 | case T_XmlSerialize: |
1927 | *name = "xmlserialize" ; |
1928 | return 2; |
1929 | default: |
1930 | break; |
1931 | } |
1932 | |
1933 | return strength; |
1934 | } |
1935 | |