Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * parse_relation.c
4 : : * parser support routines dealing with relations
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_relation.c
12 : : *
13 : : *-------------------------------------------------------------------------
14 : : */
15 : : #include "postgres.h"
16 : :
17 : : #include <ctype.h>
18 : :
19 : : #include "access/htup_details.h"
20 : : #include "access/relation.h"
21 : : #include "access/table.h"
22 : : #include "catalog/heap.h"
23 : : #include "catalog/namespace.h"
24 : : #include "funcapi.h"
25 : : #include "nodes/makefuncs.h"
26 : : #include "nodes/nodeFuncs.h"
27 : : #include "parser/parse_enr.h"
28 : : #include "parser/parse_relation.h"
29 : : #include "parser/parse_type.h"
30 : : #include "parser/parsetree.h"
31 : : #include "storage/lmgr.h"
32 : : #include "utils/builtins.h"
33 : : #include "utils/lsyscache.h"
34 : : #include "utils/syscache.h"
35 : : #include "utils/varlena.h"
36 : :
37 : :
38 : : /*
39 : : * Support for fuzzily matching columns.
40 : : *
41 : : * This is for building diagnostic messages, where multiple or non-exact
42 : : * matching attributes are of interest.
43 : : *
44 : : * "distance" is the current best fuzzy-match distance if rfirst isn't NULL,
45 : : * otherwise it is the maximum acceptable distance plus 1.
46 : : *
47 : : * rfirst/first record the closest non-exact match so far, and distance
48 : : * is its distance from the target name. If we have found a second non-exact
49 : : * match of exactly the same distance, rsecond/second record that. (If
50 : : * we find three of the same distance, we conclude that "distance" is not
51 : : * a tight enough bound for a useful hint and clear rfirst/rsecond again.
52 : : * Only if we later find something closer will we re-populate rfirst.)
53 : : *
54 : : * rexact1/exact1 record the location of the first exactly-matching column,
55 : : * if any. If we find multiple exact matches then rexact2/exact2 record
56 : : * another one (we don't especially care which). Currently, these get
57 : : * populated independently of the fuzzy-match fields.
58 : : */
59 : : typedef struct
60 : : {
61 : : int distance; /* Current or limit distance */
62 : : RangeTblEntry *rfirst; /* RTE of closest non-exact match, or NULL */
63 : : AttrNumber first; /* Col index in rfirst */
64 : : RangeTblEntry *rsecond; /* RTE of another non-exact match w/same dist */
65 : : AttrNumber second; /* Col index in rsecond */
66 : : RangeTblEntry *rexact1; /* RTE of first exact match, or NULL */
67 : : AttrNumber exact1; /* Col index in rexact1 */
68 : : RangeTblEntry *rexact2; /* RTE of second exact match, or NULL */
69 : : AttrNumber exact2; /* Col index in rexact2 */
70 : : } FuzzyAttrMatchState;
71 : :
72 : : #define MAX_FUZZY_DISTANCE 3
73 : :
74 : :
75 : : static ParseNamespaceItem *scanNameSpaceForRefname(ParseState *pstate,
76 : : const char *refname,
77 : : int location);
78 : : static ParseNamespaceItem *scanNameSpaceForRelid(ParseState *pstate, Oid relid,
79 : : int location);
80 : : static void check_lateral_ref_ok(ParseState *pstate, ParseNamespaceItem *nsitem,
81 : : int location);
82 : : static int scanRTEForColumn(ParseState *pstate, RangeTblEntry *rte,
83 : : Alias *eref,
84 : : const char *colname, int location,
85 : : int fuzzy_rte_penalty,
86 : : FuzzyAttrMatchState *fuzzystate);
87 : : static void markRTEForSelectPriv(ParseState *pstate,
88 : : int rtindex, AttrNumber col);
89 : : static void expandRelation(Oid relid, Alias *eref,
90 : : int rtindex, int sublevels_up,
91 : : VarReturningType returning_type,
92 : : int location, bool include_dropped,
93 : : List **colnames, List **colvars);
94 : : static void expandTupleDesc(TupleDesc tupdesc, Alias *eref,
95 : : int count, int offset,
96 : : int rtindex, int sublevels_up,
97 : : VarReturningType returning_type,
98 : : int location, bool include_dropped,
99 : : List **colnames, List **colvars);
100 : : static int specialAttNum(const char *attname);
101 : : static bool rte_visible_if_lateral(ParseState *pstate, RangeTblEntry *rte);
102 : : static bool rte_visible_if_qualified(ParseState *pstate, RangeTblEntry *rte);
103 : :
104 : :
105 : : /*
106 : : * refnameNamespaceItem
107 : : * Given a possibly-qualified refname, look to see if it matches any visible
108 : : * namespace item. If so, return a pointer to the nsitem; else return NULL.
109 : : *
110 : : * Optionally get nsitem's nesting depth (0 = current) into *sublevels_up.
111 : : * If sublevels_up is NULL, only consider items at the current nesting
112 : : * level.
113 : : *
114 : : * An unqualified refname (schemaname == NULL) can match any item with matching
115 : : * alias, or matching unqualified relname in the case of alias-less relation
116 : : * items. It is possible that such a refname matches multiple items in the
117 : : * nearest nesting level that has a match; if so, we report an error via
118 : : * ereport().
119 : : *
120 : : * A qualified refname (schemaname != NULL) can only match a relation item
121 : : * that (a) has no alias and (b) is for the same relation identified by
122 : : * schemaname.refname. In this case we convert schemaname.refname to a
123 : : * relation OID and search by relid, rather than by alias name. This is
124 : : * peculiar, but it's what SQL says to do. While processing a query's
125 : : * RETURNING list, there may be additional namespace items for OLD and NEW,
126 : : * with the same relation OID as the target namespace item. These are
127 : : * ignored in the search, since they don't match by schemaname.refname.
128 : : */
129 : : ParseNamespaceItem *
2460 tgl@sss.pgh.pa.us 130 :CBC 710609 : refnameNamespaceItem(ParseState *pstate,
131 : : const char *schemaname,
132 : : const char *refname,
133 : : int location,
134 : : int *sublevels_up)
135 : : {
8809 136 : 710609 : Oid relId = InvalidOid;
137 : :
9504 138 [ + + ]: 710609 : if (sublevels_up)
139 : 705897 : *sublevels_up = 0;
140 : :
8809 141 [ + + ]: 710609 : if (schemaname != NULL)
142 : : {
143 : : Oid namespaceId;
144 : :
145 : : /*
146 : : * We can use LookupNamespaceNoError() here because we are only
147 : : * interested in finding existing RTEs. Checking USAGE permission on
148 : : * the schema is unnecessary since it would have already been checked
149 : : * when the RTE was made. Furthermore, we want to report "RTE not
150 : : * found", not "no permissions for schema", if the name happens to
151 : : * match a schema name the user hasn't got access to.
152 : : */
6168 153 : 53 : namespaceId = LookupNamespaceNoError(schemaname);
5989 154 [ + + ]: 53 : if (!OidIsValid(namespaceId))
6168 155 : 41 : return NULL;
8809 156 : 12 : relId = get_relname_relid(refname, namespaceId);
157 [ - + ]: 12 : if (!OidIsValid(relId))
8809 tgl@sss.pgh.pa.us 158 :UBC 0 : return NULL;
159 : : }
160 : :
9714 lockhart@fourpalms.o 161 [ + + ]:CBC 772725 : while (pstate != NULL)
162 : : {
163 : : ParseNamespaceItem *result;
164 : :
8809 tgl@sss.pgh.pa.us 165 [ + + ]: 750312 : if (OidIsValid(relId))
6593 166 : 16 : result = scanNameSpaceForRelid(pstate, relId, location);
167 : : else
168 : 750296 : result = scanNameSpaceForRefname(pstate, refname, location);
169 : :
7777 170 [ + + ]: 750296 : if (result)
171 : 683515 : return result;
172 : :
9504 173 [ + + ]: 66781 : if (sublevels_up)
174 : 62157 : (*sublevels_up)++;
175 : : else
176 : 4624 : break;
177 : :
7777 178 : 62157 : pstate = pstate->parentParseState;
179 : : }
9504 180 : 27037 : return NULL;
181 : : }
182 : :
183 : : /*
184 : : * Search the query's table namespace for an item matching the
185 : : * given unqualified refname. Return the nsitem if a unique match, or NULL
186 : : * if no match. Raise error if multiple matches.
187 : : *
188 : : * Note: it might seem that we shouldn't have to worry about the possibility
189 : : * of multiple matches; after all, the SQL standard disallows duplicate table
190 : : * aliases within a given SELECT level. Historically, however, Postgres has
191 : : * been laxer than that. For example, we allow
192 : : * SELECT ... FROM tab1 x CROSS JOIN (tab2 x CROSS JOIN tab3 y) z
193 : : * on the grounds that the aliased join (z) hides the aliases within it,
194 : : * therefore there is no conflict between the two RTEs named "x". However,
195 : : * if tab3 is a LATERAL subquery, then from within the subquery both "x"es
196 : : * are visible. Rather than rejecting queries that used to work, we allow
197 : : * this situation, and complain only if there's actually an ambiguous
198 : : * reference to "x".
199 : : */
200 : : static ParseNamespaceItem *
6593 201 : 750296 : scanNameSpaceForRefname(ParseState *pstate, const char *refname, int location)
202 : : {
2460 203 : 750296 : ParseNamespaceItem *result = NULL;
204 : : ListCell *l;
205 : :
5156 206 [ + + + + : 3176736 : foreach(l, pstate->p_namespace)
+ + ]
207 : : {
5157 208 : 2426456 : ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(l);
209 : :
210 : : /* Ignore columns-only items */
5156 211 [ + + ]: 2426456 : if (!nsitem->p_rel_visible)
212 : 619724 : continue;
213 : : /* If not inside LATERAL, ignore lateral-only items */
5157 214 [ + + + + ]: 1806732 : if (nsitem->p_lateral_only && !pstate->p_lateral_active)
215 : 40 : continue;
216 : :
1999 peter@eisentraut.org 217 [ + + ]: 1806692 : if (strcmp(nsitem->p_names->aliasname, refname) == 0)
218 : : {
7777 tgl@sss.pgh.pa.us 219 [ + + ]: 683527 : if (result)
8464 220 [ + - ]: 8 : ereport(ERROR,
221 : : (errcode(ERRCODE_AMBIGUOUS_ALIAS),
222 : : errmsg("table reference \"%s\" is ambiguous",
223 : : refname),
224 : : parser_errposition(pstate, location)));
4635 225 : 683519 : check_lateral_ref_ok(pstate, nsitem, location);
2460 226 : 683511 : result = nsitem;
227 : : }
228 : : }
9504 229 : 750280 : return result;
230 : : }
231 : :
232 : : /*
233 : : * Search the query's table namespace for a relation item matching the
234 : : * given relation OID. Return the nsitem if a unique match, or NULL
235 : : * if no match. Raise error if multiple matches.
236 : : *
237 : : * See the comments for refnameNamespaceItem to understand why this
238 : : * acts the way it does.
239 : : */
240 : : static ParseNamespaceItem *
6593 241 : 16 : scanNameSpaceForRelid(ParseState *pstate, Oid relid, int location)
242 : : {
2460 243 : 16 : ParseNamespaceItem *result = NULL;
244 : : ListCell *l;
245 : :
5156 246 [ + - + + : 40 : foreach(l, pstate->p_namespace)
+ + ]
247 : : {
5157 248 : 24 : ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(l);
249 : 24 : RangeTblEntry *rte = nsitem->p_rte;
250 : :
251 : : /* Ignore columns-only items */
5156 252 [ - + ]: 24 : if (!nsitem->p_rel_visible)
5156 tgl@sss.pgh.pa.us 253 :UBC 0 : continue;
254 : : /* If not inside LATERAL, ignore lateral-only items */
5157 tgl@sss.pgh.pa.us 255 [ - + - - ]:CBC 24 : if (nsitem->p_lateral_only && !pstate->p_lateral_active)
5157 tgl@sss.pgh.pa.us 256 :UBC 0 : continue;
257 : : /* Ignore OLD/NEW namespace items that can appear in RETURNING */
611 dean.a.rasheed@gmail 258 [ + + ]:CBC 24 : if (nsitem->p_returning_type != VAR_RETURNING_DEFAULT)
259 : 8 : continue;
260 : :
261 : : /* yes, the test for alias == NULL should be there... */
8809 tgl@sss.pgh.pa.us 262 [ + - ]: 16 : if (rte->rtekind == RTE_RELATION &&
263 [ + + ]: 16 : rte->relid == relid &&
264 [ + - ]: 12 : rte->alias == NULL)
265 : : {
7777 266 [ - + ]: 12 : if (result)
8464 tgl@sss.pgh.pa.us 267 [ # # ]:UBC 0 : ereport(ERROR,
268 : : (errcode(ERRCODE_AMBIGUOUS_ALIAS),
269 : : errmsg("table reference %u is ambiguous",
270 : : relid),
271 : : parser_errposition(pstate, location)));
4635 tgl@sss.pgh.pa.us 272 :CBC 12 : check_lateral_ref_ok(pstate, nsitem, location);
2460 273 : 12 : result = nsitem;
274 : : }
275 : : }
8809 276 : 16 : return result;
277 : : }
278 : :
279 : : /*
280 : : * Search the query's CTE namespace for a CTE matching the given unqualified
281 : : * refname. Return the CTE (and its levelsup count) if a match, or NULL
282 : : * if no match. We need not worry about multiple matches, since parse_cte.c
283 : : * rejects WITH lists containing duplicate CTE names.
284 : : */
285 : : CommonTableExpr *
6558 286 : 127753 : scanNameSpaceForCTE(ParseState *pstate, const char *refname,
287 : : Index *ctelevelsup)
288 : : {
289 : : Index levelsup;
290 : :
291 : 127753 : for (levelsup = 0;
292 [ + + ]: 293154 : pstate != NULL;
293 : 165401 : pstate = pstate->parentParseState, levelsup++)
294 : : {
295 : : ListCell *lc;
296 : :
297 [ + + + + : 173531 : foreach(lc, pstate->p_ctenamespace)
+ + ]
298 : : {
299 : 8130 : CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
300 : :
301 [ + + ]: 8130 : if (strcmp(cte->ctename, refname) == 0)
302 : : {
303 : 4463 : *ctelevelsup = levelsup;
304 : 4463 : return cte;
305 : : }
306 : : }
307 : : }
308 : 123290 : return NULL;
309 : : }
310 : :
311 : : /*
312 : : * Search for a possible "future CTE", that is one that is not yet in scope
313 : : * according to the WITH scoping rules. This has nothing to do with valid
314 : : * SQL semantics, but it's important for error reporting purposes.
315 : : */
316 : : static bool
6556 317 : 108 : isFutureCTE(ParseState *pstate, const char *refname)
318 : : {
319 [ + + ]: 224 : for (; pstate != NULL; pstate = pstate->parentParseState)
320 : : {
321 : : ListCell *lc;
322 : :
323 [ + + + - : 120 : foreach(lc, pstate->p_future_ctes)
+ + ]
324 : : {
325 : 4 : CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
326 : :
327 [ + - ]: 4 : if (strcmp(cte->ctename, refname) == 0)
328 : 4 : return true;
329 : : }
330 : : }
331 : 104 : return false;
332 : : }
333 : :
334 : : /*
335 : : * Search the query's ephemeral named relation namespace for a relation
336 : : * matching the given unqualified refname.
337 : : */
338 : : bool
3460 kgrittn@postgresql.o 339 : 174111 : scanNameSpaceForENR(ParseState *pstate, const char *refname)
340 : : {
341 : 174111 : return name_matches_visible_ENR(pstate, refname);
342 : : }
343 : :
344 : : /*
345 : : * searchRangeTableForRel
346 : : * See if any RangeTblEntry could possibly match the RangeVar.
347 : : * If so, return a pointer to the RangeTblEntry; else return NULL.
348 : : *
349 : : * This is different from refnameNamespaceItem in that it considers every
350 : : * entry in the ParseState's rangetable(s), not only those that are currently
351 : : * visible in the p_namespace list(s). This behavior is invalid per the SQL
352 : : * spec, and it may give ambiguous results (there might be multiple equally
353 : : * valid matches, but only one will be returned). This must be used ONLY
354 : : * as a heuristic in giving suitable error messages. See errorMissingRTE.
355 : : *
356 : : * Notice that we consider both matches on actual relation (or CTE) name
357 : : * and matches on alias.
358 : : */
359 : : static RangeTblEntry *
5157 tgl@sss.pgh.pa.us 360 : 76 : searchRangeTableForRel(ParseState *pstate, RangeVar *relation)
361 : : {
6558 362 : 76 : const char *refname = relation->relname;
363 : 76 : Oid relId = InvalidOid;
364 : 76 : CommonTableExpr *cte = NULL;
3460 kgrittn@postgresql.o 365 : 76 : bool isenr = false;
6558 tgl@sss.pgh.pa.us 366 : 76 : Index ctelevelsup = 0;
367 : : Index levelsup;
368 : :
369 : : /*
370 : : * If it's an unqualified name, check for possible CTE matches. A CTE
371 : : * hides any real relation matches. If no CTE, look for a matching
372 : : * relation.
373 : : *
374 : : * NB: It's not critical that RangeVarGetRelid return the correct answer
375 : : * here in the face of concurrent DDL. If it doesn't, the worst case
376 : : * scenario is a less-clear error message. Also, the tables involved in
377 : : * the query are already locked, which reduces the number of cases in
378 : : * which surprising behavior can occur. So we do the name lookup
379 : : * unlocked.
380 : : */
381 [ + - ]: 76 : if (!relation->schemaname)
382 : : {
383 : 76 : cte = scanNameSpaceForCTE(pstate, refname, &ctelevelsup);
3460 kgrittn@postgresql.o 384 [ + - ]: 76 : if (!cte)
385 : 76 : isenr = scanNameSpaceForENR(pstate, refname);
386 : : }
387 : :
388 [ + - + - ]: 76 : if (!cte && !isenr)
5408 rhaas@postgresql.org 389 : 76 : relId = RangeVarGetRelid(relation, NoLock, true);
390 : :
391 : : /* Now look for RTEs matching either the relation/CTE/ENR or the alias */
6558 tgl@sss.pgh.pa.us 392 : 76 : for (levelsup = 0;
393 [ + + ]: 108 : pstate != NULL;
394 : 32 : pstate = pstate->parentParseState, levelsup++)
395 : : {
396 : : ListCell *l;
397 : :
7558 398 [ + + + + : 144 : foreach(l, pstate->p_rtable)
+ + ]
399 : : {
400 : 112 : RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
401 : :
6558 402 [ + + + + ]: 112 : if (rte->rtekind == RTE_RELATION &&
403 : 74 : OidIsValid(relId) &&
7558 404 [ + + ]: 74 : rte->relid == relId)
405 : 64 : return rte;
6558 406 [ - + - - ]: 84 : if (rte->rtekind == RTE_CTE &&
6558 tgl@sss.pgh.pa.us 407 :UBC 0 : cte != NULL &&
408 [ # # ]: 0 : rte->ctelevelsup + levelsup == ctelevelsup &&
409 [ # # ]: 0 : strcmp(rte->ctename, refname) == 0)
410 : 0 : return rte;
3460 kgrittn@postgresql.o 411 [ - + - - ]:CBC 84 : if (rte->rtekind == RTE_NAMEDTUPLESTORE &&
3460 kgrittn@postgresql.o 412 :UBC 0 : isenr &&
413 [ # # ]: 0 : strcmp(rte->enrname, refname) == 0)
414 : 0 : return rte;
7558 tgl@sss.pgh.pa.us 415 [ + + ]:CBC 84 : if (strcmp(rte->eref->aliasname, refname) == 0)
416 : 36 : return rte;
417 : : }
418 : : }
419 : 12 : return NULL;
420 : : }
421 : :
422 : : /*
423 : : * Check for relation-name conflicts between two namespace lists.
424 : : * Raise an error if any is found.
425 : : *
426 : : * Note: we assume that each given argument does not contain conflicts
427 : : * itself; we just want to know if the two can be merged together.
428 : : *
429 : : * Per SQL, two alias-less plain relation RTEs do not conflict even if
430 : : * they have the same eref->aliasname (ie, same relation name), if they
431 : : * are for different relation OIDs (implying they are in different schemas).
432 : : *
433 : : * We ignore the lateral-only flags in the namespace items: the lists must
434 : : * not conflict, even when all items are considered visible. However,
435 : : * columns-only items should be ignored.
436 : : */
437 : : void
7777 438 : 300742 : checkNameSpaceConflicts(ParseState *pstate, List *namespace1,
439 : : List *namespace2)
440 : : {
441 : : ListCell *l1;
442 : :
443 [ + + + + : 466384 : foreach(l1, namespace1)
+ + ]
444 : : {
5157 445 : 165650 : ParseNamespaceItem *nsitem1 = (ParseNamespaceItem *) lfirst(l1);
446 : 165650 : RangeTblEntry *rte1 = nsitem1->p_rte;
1999 peter@eisentraut.org 447 : 165650 : const char *aliasname1 = nsitem1->p_names->aliasname;
448 : : ListCell *l2;
449 : :
5156 tgl@sss.pgh.pa.us 450 [ + + ]: 165650 : if (!nsitem1->p_rel_visible)
451 : 30509 : continue;
452 : :
7777 453 [ + - + + : 283384 : foreach(l2, namespace2)
+ + ]
454 : : {
5157 455 : 148251 : ParseNamespaceItem *nsitem2 = (ParseNamespaceItem *) lfirst(l2);
456 : 148251 : RangeTblEntry *rte2 = nsitem2->p_rte;
1999 peter@eisentraut.org 457 : 148251 : const char *aliasname2 = nsitem2->p_names->aliasname;
458 : :
5156 tgl@sss.pgh.pa.us 459 [ + + ]: 148251 : if (!nsitem2->p_rel_visible)
460 : 6566 : continue;
1999 peter@eisentraut.org 461 [ + + ]: 141685 : if (strcmp(aliasname2, aliasname1) != 0)
7777 tgl@sss.pgh.pa.us 462 : 141677 : continue; /* definitely no conflict */
463 [ + + + - ]: 8 : if (rte1->rtekind == RTE_RELATION && rte1->alias == NULL &&
464 [ + - + - ]: 4 : rte2->rtekind == RTE_RELATION && rte2->alias == NULL &&
465 [ - + ]: 4 : rte1->relid != rte2->relid)
4901 peter_e@gmx.net 466 :UBC 0 : continue; /* no conflict per SQL rule */
7777 tgl@sss.pgh.pa.us 467 [ + - ]:CBC 8 : ereport(ERROR,
468 : : (errcode(ERRCODE_DUPLICATE_ALIAS),
469 : : errmsg("table name \"%s\" specified more than once",
470 : : aliasname1)));
471 : : }
472 : : }
8809 473 : 300734 : }
474 : :
475 : : /*
476 : : * Complain if a namespace item is currently disallowed as a LATERAL reference.
477 : : * This enforces both SQL:2008's rather odd idea of what to do with a LATERAL
478 : : * reference to the wrong side of an outer join, and our own prohibition on
479 : : * referencing the target table of an UPDATE or DELETE as a lateral reference
480 : : * in a FROM/USING clause.
481 : : *
482 : : * Note: the pstate should be the same query level the nsitem was found in.
483 : : *
484 : : * Convenience subroutine to avoid multiple copies of a rather ugly ereport.
485 : : */
486 : : static void
4635 487 : 1105360 : check_lateral_ref_ok(ParseState *pstate, ParseNamespaceItem *nsitem,
488 : : int location)
489 : : {
490 [ + + + + ]: 1105360 : if (nsitem->p_lateral_only && !nsitem->p_lateral_ok)
491 : : {
492 : : /* SQL:2008 demands this be an error, not an invisible item */
493 : 16 : RangeTblEntry *rte = nsitem->p_rte;
1999 peter@eisentraut.org 494 : 16 : char *refname = nsitem->p_names->aliasname;
495 : :
4635 tgl@sss.pgh.pa.us 496 [ + - + + : 16 : ereport(ERROR,
+ - ]
497 : : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
498 : : errmsg("invalid reference to FROM-clause entry for table \"%s\"",
499 : : refname),
500 : : (pstate->p_target_nsitem != NULL &&
501 : : rte == pstate->p_target_nsitem->p_rte) ?
502 : : errhint("There is an entry for table \"%s\", but it cannot be referenced from this part of the query.",
503 : : refname) :
504 : : errdetail("The combining JOIN type must be INNER or LEFT for a LATERAL reference."),
505 : : parser_errposition(pstate, location)));
506 : : }
507 : 1105344 : }
508 : :
509 : : /*
510 : : * Given an RT index and nesting depth, find the corresponding
511 : : * ParseNamespaceItem (there must be one).
512 : : *
513 : : * NB: Callers starting from a Var should consider using GetNSItemByVar()
514 : : * instead, to find the namespace item with matching varreturningtype.
515 : : */
516 : : ParseNamespaceItem *
2460 517 : 1370 : GetNSItemByRangeTablePosn(ParseState *pstate,
518 : : int varno,
519 : : int sublevels_up)
520 : : {
521 : : ListCell *lc;
522 : :
523 [ - + ]: 1370 : while (sublevels_up-- > 0)
524 : : {
9504 tgl@sss.pgh.pa.us 525 :UBC 0 : pstate = pstate->parentParseState;
2460 526 [ # # ]: 0 : Assert(pstate != NULL);
527 : : }
2460 tgl@sss.pgh.pa.us 528 [ + - + - :CBC 1482 : foreach(lc, pstate->p_namespace)
+ - ]
529 : : {
530 : 1482 : ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(lc);
531 : :
532 [ + + ]: 1482 : if (nsitem->p_rtindex == varno)
533 : 1370 : return nsitem;
534 : : }
2460 tgl@sss.pgh.pa.us 535 [ # # ]:UBC 0 : elog(ERROR, "nsitem not found (internal error)");
536 : : return NULL; /* keep compiler quiet */
537 : : }
538 : :
539 : : /*
540 : : * Given a Var, find the corresponding ParseNamespaceItem (there must be one).
541 : : *
542 : : * Like GetNSItemByRangeTablePosn(), but uses the Var's varreturningtype in
543 : : * addition to its varno and varlevelsup to find the namespace item.
544 : : */
545 : : ParseNamespaceItem *
101 dean.a.rasheed@gmail 546 :CBC 192 : GetNSItemByVar(ParseState *pstate, Var *var)
547 : : {
548 : 192 : int sublevels_up = var->varlevelsup;
549 : : ListCell *lc;
550 : :
551 [ - + ]: 192 : while (sublevels_up-- > 0)
552 : : {
101 dean.a.rasheed@gmail 553 :UBC 0 : pstate = pstate->parentParseState;
554 [ # # ]: 0 : Assert(pstate != NULL);
555 : : }
101 dean.a.rasheed@gmail 556 [ + - + - :CBC 296 : foreach(lc, pstate->p_namespace)
+ - ]
557 : : {
558 : 296 : ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(lc);
559 : :
560 [ + + ]: 296 : if (nsitem->p_rtindex == var->varno &&
561 [ + + ]: 268 : nsitem->p_returning_type == var->varreturningtype)
562 : 192 : return nsitem;
563 : : }
101 dean.a.rasheed@gmail 564 [ # # ]:UBC 0 : elog(ERROR, "nsitem not found (internal error)");
565 : : return NULL; /* keep compiler quiet */
566 : : }
567 : :
568 : : /*
569 : : * Given an RT index and nesting depth, find the corresponding RTE.
570 : : * (Note that the RTE need not be in the query's namespace.)
571 : : */
572 : : RangeTblEntry *
8206 tgl@sss.pgh.pa.us 573 :CBC 490300 : GetRTEByRangeTablePosn(ParseState *pstate,
574 : : int varno,
575 : : int sublevels_up)
576 : : {
577 [ + + ]: 491374 : while (sublevels_up-- > 0)
578 : : {
579 : 1074 : pstate = pstate->parentParseState;
580 [ - + ]: 1074 : Assert(pstate != NULL);
581 : : }
8148 neilc@samurai.com 582 [ + - - + ]: 490300 : Assert(varno > 0 && varno <= list_length(pstate->p_rtable));
8206 tgl@sss.pgh.pa.us 583 : 490300 : return rt_fetch(varno, pstate->p_rtable);
584 : : }
585 : :
586 : : /*
587 : : * Fetch the CTE for a CTE-reference RTE.
588 : : *
589 : : * rtelevelsup is the number of query levels above the given pstate that the
590 : : * RTE came from.
591 : : */
592 : : CommonTableExpr *
6558 593 : 6119 : GetCTEForRTE(ParseState *pstate, RangeTblEntry *rte, int rtelevelsup)
594 : : {
595 : : Index levelsup;
596 : : ListCell *lc;
597 : :
6560 598 [ - + ]: 6119 : Assert(rte->rtekind == RTE_CTE);
6558 599 : 6119 : levelsup = rte->ctelevelsup + rtelevelsup;
6560 600 [ + + ]: 14669 : while (levelsup-- > 0)
601 : : {
602 : 8550 : pstate = pstate->parentParseState;
603 [ - + ]: 8550 : if (!pstate) /* shouldn't happen */
6560 tgl@sss.pgh.pa.us 604 [ # # ]:UBC 0 : elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
605 : : }
6560 tgl@sss.pgh.pa.us 606 [ + - + - :CBC 10671 : foreach(lc, pstate->p_ctenamespace)
+ - ]
607 : : {
608 : 10671 : CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
609 : :
610 [ + + ]: 10671 : if (strcmp(cte->ctename, rte->ctename) == 0)
611 : 6119 : return cte;
612 : : }
613 : : /* shouldn't happen */
6560 tgl@sss.pgh.pa.us 614 [ # # ]:UBC 0 : elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
615 : : return NULL; /* keep compiler quiet */
616 : : }
617 : :
618 : : /*
619 : : * updateFuzzyAttrMatchState
620 : : * Using Levenshtein distance, consider if column is best fuzzy match.
621 : : */
622 : : static void
4211 rhaas@postgresql.org 623 :CBC 1544 : updateFuzzyAttrMatchState(int fuzzy_rte_penalty,
624 : : FuzzyAttrMatchState *fuzzystate, RangeTblEntry *rte,
625 : : const char *actual, const char *match, int attnum)
626 : : {
627 : : int columndistance;
628 : : int matchlen;
629 : :
630 : : /* Bail before computing the Levenshtein distance if there's no hope. */
631 [ + + ]: 1544 : if (fuzzy_rte_penalty > fuzzystate->distance)
632 : 36 : return;
633 : :
634 : : /*
635 : : * Outright reject dropped columns, which can appear here with apparent
636 : : * empty actual names, per remarks within scanRTEForColumn().
637 : : */
638 [ + + ]: 1508 : if (actual[0] == '\0')
639 : 88 : return;
640 : :
641 : : /* Use Levenshtein to compute match distance. */
642 : 1420 : matchlen = strlen(match);
643 : : columndistance =
644 : 1420 : varstr_levenshtein_less_equal(actual, strlen(actual), match, matchlen,
645 : : 1, 1, 1,
646 : 1420 : fuzzystate->distance + 1
3894 tgl@sss.pgh.pa.us 647 : 1420 : - fuzzy_rte_penalty,
648 : : true);
649 : :
650 : : /*
651 : : * If more than half the characters are different, don't treat it as a
652 : : * match, to avoid making ridiculous suggestions.
653 : : */
4211 rhaas@postgresql.org 654 [ + + ]: 1420 : if (columndistance > matchlen / 2)
655 : 832 : return;
656 : :
657 : : /*
658 : : * From this point on, we can ignore the distinction between the RTE-name
659 : : * distance and the column-name distance.
660 : : */
661 : 588 : columndistance += fuzzy_rte_penalty;
662 : :
663 : : /*
664 : : * If the new distance is less than or equal to that of the best match
665 : : * found so far, update fuzzystate.
666 : : */
667 [ + + ]: 588 : if (columndistance < fuzzystate->distance)
668 : : {
669 : : /* Store new lowest observed distance as first/only match */
670 : 80 : fuzzystate->distance = columndistance;
671 : 80 : fuzzystate->rfirst = rte;
672 : 80 : fuzzystate->first = attnum;
673 : 80 : fuzzystate->rsecond = NULL;
674 : : }
675 [ + + ]: 508 : else if (columndistance == fuzzystate->distance)
676 : : {
677 : : /* If we already have a match of this distance, update state */
1398 tgl@sss.pgh.pa.us 678 [ + + ]: 28 : if (fuzzystate->rsecond != NULL)
679 : : {
680 : : /*
681 : : * Too many matches at same distance. Clearly, this value of
682 : : * distance is too low a bar, so drop these entries while keeping
683 : : * the current distance value, so that only smaller distances will
684 : : * be considered interesting. Only if we find something of lower
685 : : * distance will we re-populate rfirst (via the stanza above).
686 : : */
4211 rhaas@postgresql.org 687 : 4 : fuzzystate->rfirst = NULL;
688 : 4 : fuzzystate->rsecond = NULL;
689 : : }
1398 tgl@sss.pgh.pa.us 690 [ + + ]: 24 : else if (fuzzystate->rfirst != NULL)
691 : : {
692 : : /* Record as provisional second match */
4211 rhaas@postgresql.org 693 : 12 : fuzzystate->rsecond = rte;
694 : 12 : fuzzystate->second = attnum;
695 : : }
696 : : else
697 : : {
698 : : /*
699 : : * Do nothing. When rfirst is NULL, distance is more than what we
700 : : * want to consider acceptable, so we should ignore this match.
701 : : */
702 : : }
703 : : }
704 : : }
705 : :
706 : : /*
707 : : * scanNSItemForColumn
708 : : * Search the column names of a single namespace item for the given name.
709 : : * If found, return an appropriate Var node, else return NULL.
710 : : * If the name proves ambiguous within this nsitem, raise error.
711 : : *
712 : : * Side effect: if we find a match, mark the corresponding RTE as requiring
713 : : * read access for the column.
714 : : */
715 : : Node *
2460 tgl@sss.pgh.pa.us 716 : 1175125 : scanNSItemForColumn(ParseState *pstate, ParseNamespaceItem *nsitem,
717 : : int sublevels_up, const char *colname, int location)
718 : : {
719 : 1175125 : RangeTblEntry *rte = nsitem->p_rte;
720 : : int attnum;
721 : : Var *var;
722 : :
723 : : /*
724 : : * Scan the nsitem's column names (or aliases) for a match. Complain if
725 : : * multiple matches.
726 : : */
1999 peter@eisentraut.org 727 : 1175125 : attnum = scanRTEForColumn(pstate, rte, nsitem->p_names,
728 : : colname, location,
729 : : 0, NULL);
730 : :
2460 tgl@sss.pgh.pa.us 731 [ + + ]: 1175117 : if (attnum == InvalidAttrNumber)
732 : 78241 : return NULL; /* Return NULL if no match */
733 : :
734 : : /* In constraint check, no system column is allowed except tableOid */
735 [ + + + + ]: 1096876 : if (pstate->p_expr_kind == EXPR_KIND_CHECK_CONSTRAINT &&
736 [ + + ]: 8 : attnum < InvalidAttrNumber && attnum != TableOidAttributeNumber)
737 [ + - ]: 4 : ereport(ERROR,
738 : : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
739 : : errmsg("system column \"%s\" reference in check constraint is invalid",
740 : : colname),
741 : : parser_errposition(pstate, location)));
742 : :
743 : : /*
744 : : * In generated column, no system column is allowed except tableOid.
745 : : * (Required for stored generated, but we also do it for virtual generated
746 : : * for now for consistency.)
747 : : */
748 [ + + + + ]: 1096872 : if (pstate->p_expr_kind == EXPR_KIND_GENERATED_COLUMN &&
749 [ + + ]: 32 : attnum < InvalidAttrNumber && attnum != TableOidAttributeNumber)
750 [ + - ]: 8 : ereport(ERROR,
751 : : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
752 : : errmsg("cannot use system column \"%s\" in column generation expression",
753 : : colname),
754 : : parser_errposition(pstate, location)));
755 : :
756 : : /*
757 : : * In a MERGE WHEN condition, no system column is allowed except tableOid
758 : : */
1637 alvherre@alvh.no-ip. 759 [ + + + + ]: 1096864 : if (pstate->p_expr_kind == EXPR_KIND_MERGE_WHEN &&
760 [ + + ]: 8 : attnum < InvalidAttrNumber && attnum != TableOidAttributeNumber)
761 [ + - ]: 4 : ereport(ERROR,
762 : : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
763 : : errmsg("cannot use system column \"%s\" in MERGE WHEN condition",
764 : : colname),
765 : : parser_errposition(pstate, location)));
766 : :
767 : : /* Found a valid match, so build a Var */
2453 tgl@sss.pgh.pa.us 768 [ + + ]: 1096860 : if (attnum > InvalidAttrNumber)
769 : : {
770 : : /* Get attribute data from the ParseNamespaceColumn array */
771 : 1076165 : ParseNamespaceColumn *nscol = &nsitem->p_nscolumns[attnum - 1];
772 : :
773 : : /* Complain if dropped column. See notes in scanRTEForColumn. */
774 [ - + ]: 1076165 : if (nscol->p_varno == 0)
2453 tgl@sss.pgh.pa.us 775 [ # # ]:UBC 0 : ereport(ERROR,
776 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
777 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
778 : : colname,
779 : : nsitem->p_names->aliasname)));
780 : :
2446 tgl@sss.pgh.pa.us 781 :CBC 1076165 : var = makeVar(nscol->p_varno,
782 : 1076165 : nscol->p_varattno,
783 : : nscol->p_vartype,
784 : : nscol->p_vartypmod,
785 : : nscol->p_varcollid,
786 : : sublevels_up);
787 : : /* makeVar doesn't offer parameters for these, so set them by hand: */
788 : 1076165 : var->varnosyn = nscol->p_varnosyn;
789 : 1076165 : var->varattnosyn = nscol->p_varattnosyn;
790 : : }
791 : : else
792 : : {
793 : : /* System column, so use predetermined type data */
794 : : const FormData_pg_attribute *sysatt;
795 : :
2453 796 : 20695 : sysatt = SystemAttributeDefinition(attnum);
797 : 20695 : var = makeVar(nsitem->p_rtindex,
798 : : attnum,
799 : 20695 : sysatt->atttypid,
800 : 20695 : sysatt->atttypmod,
801 : 20695 : sysatt->attcollation,
802 : : sublevels_up);
803 : : }
2460 804 : 1096860 : var->location = location;
805 : :
806 : : /* Mark Var for RETURNING OLD/NEW, as necessary */
612 dean.a.rasheed@gmail 807 : 1096860 : var->varreturningtype = nsitem->p_returning_type;
808 : :
809 : : /* Mark Var if it's nulled by any outer joins */
1329 tgl@sss.pgh.pa.us 810 : 1096860 : markNullableIfNeeded(pstate, var);
811 : :
812 : : /* Require read access to the column */
2047 813 : 1096860 : markVarForSelectPriv(pstate, var);
814 : :
2460 815 : 1096860 : return (Node *) var;
816 : : }
817 : :
818 : : /*
819 : : * scanRTEForColumn
820 : : * Search the column names of a single RTE for the given name.
821 : : * If found, return the attnum (possibly negative, for a system column);
822 : : * else return InvalidAttrNumber.
823 : : * If the name proves ambiguous within this RTE, raise error.
824 : : *
825 : : * Actually, we only search the names listed in "eref". This can be either
826 : : * rte->eref, in which case we are indeed searching all the column names,
827 : : * or for a join it can be rte->join_using_alias, in which case we are only
828 : : * considering the common column names (which are the first N columns of the
829 : : * join, so everything works).
830 : : *
831 : : * pstate and location are passed only for error-reporting purposes.
832 : : *
833 : : * Side effect: if fuzzystate is non-NULL, check non-system columns
834 : : * for an approximate match and update fuzzystate accordingly.
835 : : *
836 : : * Note: this is factored out of scanNSItemForColumn because error message
837 : : * creation may want to check RTEs that are not in the namespace. To support
838 : : * that usage, minimize the number of validity checks performed here. It's
839 : : * okay to complain about ambiguous-name cases, though, since if we are
840 : : * working to complain about an invalid name, we've already eliminated that.
841 : : */
842 : : static int
843 : 1175397 : scanRTEForColumn(ParseState *pstate, RangeTblEntry *rte,
844 : : Alias *eref,
845 : : const char *colname, int location,
846 : : int fuzzy_rte_penalty,
847 : : FuzzyAttrMatchState *fuzzystate)
848 : : {
849 : 1175397 : int result = InvalidAttrNumber;
9504 850 : 1175397 : int attnum = 0;
851 : : ListCell *c;
852 : :
853 : : /*
854 : : * Scan the user column names (or aliases) for a match. Complain if
855 : : * multiple matches.
856 : : *
857 : : * Note: eref->colnames may include entries for dropped columns, but those
858 : : * will be empty strings that cannot match any legal SQL identifier, so we
859 : : * don't bother to test for that case here.
860 : : *
861 : : * Should this somehow go wrong and we try to access a dropped column,
862 : : * we'll still catch it by virtue of the check in scanNSItemForColumn().
863 : : * Callers interested in finding match with shortest distance need to
864 : : * defend against this directly, though.
865 : : */
1999 peter@eisentraut.org 866 [ + + + + : 21265669 : foreach(c, eref->colnames)
+ + ]
867 : : {
4211 rhaas@postgresql.org 868 : 20090280 : const char *attcolname = strVal(lfirst(c));
869 : :
9504 tgl@sss.pgh.pa.us 870 : 20090280 : attnum++;
4211 rhaas@postgresql.org 871 [ + + ]: 20090280 : if (strcmp(attcolname, colname) == 0)
872 : : {
9504 tgl@sss.pgh.pa.us 873 [ + + ]: 1076221 : if (result)
8464 874 [ + - ]: 8 : ereport(ERROR,
875 : : (errcode(ERRCODE_AMBIGUOUS_COLUMN),
876 : : errmsg("column reference \"%s\" is ambiguous",
877 : : colname),
878 : : parser_errposition(pstate, location)));
2460 879 : 1076213 : result = attnum;
880 : : }
881 : :
882 : : /* Update fuzzy match state, if provided. */
4211 rhaas@postgresql.org 883 [ + + ]: 20090272 : if (fuzzystate != NULL)
884 : 1544 : updateFuzzyAttrMatchState(fuzzy_rte_penalty, fuzzystate,
885 : : rte, attcolname, colname, attnum);
886 : : }
887 : :
888 : : /*
889 : : * If we have a unique match, return it. Note that this allows a user
890 : : * alias to override a system column name (such as OID) without error.
891 : : */
9504 tgl@sss.pgh.pa.us 892 [ + + ]: 1175389 : if (result)
893 : 1076205 : return result;
894 : :
895 : : /*
896 : : * If the RTE represents a real relation, consider system column names.
897 : : * Composites are only used for pseudo-relations like ON CONFLICT's
898 : : * excluded.
899 : : */
4005 andres@anarazel.de 900 [ + + ]: 99184 : if (rte->rtekind == RTE_RELATION &&
901 [ + + ]: 74739 : rte->relkind != RELKIND_COMPOSITE_TYPE)
902 : : {
903 : : /* quick check to see if name could be a system column */
9504 tgl@sss.pgh.pa.us 904 : 74703 : attnum = specialAttNum(colname);
905 [ + + ]: 74703 : if (attnum != InvalidAttrNumber)
906 : : {
907 : : /* now check to see if column actually is defined */
6062 rhaas@postgresql.org 908 [ + - ]: 20723 : if (SearchSysCacheExists2(ATTNUM,
909 : : ObjectIdGetDatum(rte->relid),
910 : : Int16GetDatum(attnum)))
2460 tgl@sss.pgh.pa.us 911 : 20723 : result = attnum;
912 : : }
913 : : }
914 : :
9504 915 : 99184 : return result;
916 : : }
917 : :
918 : : /*
919 : : * colNameToVar
920 : : * Search for an unqualified column name.
921 : : * If found, return the appropriate Var node (or expression).
922 : : * If not found, return NULL. If the name proves ambiguous, raise error.
923 : : * If localonly is true, only names in the innermost query are considered.
924 : : */
925 : : Node *
3246 peter_e@gmx.net 926 : 445328 : colNameToVar(ParseState *pstate, const char *colname, bool localonly,
927 : : int location)
928 : : {
9504 tgl@sss.pgh.pa.us 929 : 445328 : Node *result = NULL;
2460 930 : 445328 : int sublevels_up = 0;
9504 931 : 445328 : ParseState *orig_pstate = pstate;
932 : :
933 [ + + ]: 475815 : while (pstate != NULL)
934 : : {
935 : : ListCell *l;
936 : :
5156 937 [ + + + + : 1190956 : foreach(l, pstate->p_namespace)
+ + ]
938 : : {
5157 939 : 738576 : ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(l);
940 : : Node *newresult;
941 : :
942 : : /* Ignore table-only items */
5156 943 [ + + ]: 738576 : if (!nsitem->p_cols_visible)
944 : 238664 : continue;
945 : : /* If not inside LATERAL, ignore lateral-only items */
5157 946 [ + + + + ]: 499912 : if (nsitem->p_lateral_only && !pstate->p_lateral_active)
947 : 30 : continue;
948 : :
949 : : /* use orig_pstate here for consistency with other callers */
2460 950 : 499882 : newresult = scanNSItemForColumn(orig_pstate, nsitem, sublevels_up,
951 : : colname, location);
952 : :
9504 953 [ + + ]: 499862 : if (newresult)
954 : : {
955 [ + + ]: 421845 : if (result)
8464 956 [ + - ]: 16 : ereport(ERROR,
957 : : (errcode(ERRCODE_AMBIGUOUS_COLUMN),
958 : : errmsg("column reference \"%s\" is ambiguous",
959 : : colname),
960 : : parser_errposition(pstate, location)));
4635 961 : 421829 : check_lateral_ref_ok(pstate, nsitem, location);
9504 962 : 421821 : result = newresult;
963 : : }
964 : : }
965 : :
8190 966 [ + + + + ]: 452380 : if (result != NULL || localonly)
967 : : break; /* found, or don't want to look at parent */
968 : :
9677 969 : 30487 : pstate = pstate->parentParseState;
2460 970 : 30487 : sublevels_up++;
971 : : }
972 : :
9504 973 : 445284 : return result;
974 : : }
975 : :
976 : : /*
977 : : * searchRangeTableForCol
978 : : * See if any RangeTblEntry could possibly provide the given column name (or
979 : : * find the best match available). Returns state with relevant details.
980 : : *
981 : : * This is different from colNameToVar in that it considers every entry in
982 : : * the ParseState's rangetable(s), not only those that are currently visible
983 : : * in the p_namespace list(s). This behavior is invalid per the SQL spec,
984 : : * and it may give ambiguous results (since there might be multiple equally
985 : : * valid matches). This must be used ONLY as a heuristic in giving suitable
986 : : * error messages. See errorMissingColumn.
987 : : *
988 : : * This function is also different in that it will consider approximate
989 : : * matches -- if the user entered an alias/column pair that is only slightly
990 : : * different from a valid pair, we may be able to infer what they meant to
991 : : * type and provide a reasonable hint. We return a FuzzyAttrMatchState
992 : : * struct providing information about both exact and approximate matches.
993 : : */
994 : : static FuzzyAttrMatchState *
3246 peter_e@gmx.net 995 : 245 : searchRangeTableForCol(ParseState *pstate, const char *alias, const char *colname,
996 : : int location)
997 : : {
5157 tgl@sss.pgh.pa.us 998 : 245 : ParseState *orig_pstate = pstate;
284 michael@paquier.xyz 999 : 245 : FuzzyAttrMatchState *fuzzystate = palloc_object(FuzzyAttrMatchState);
1000 : :
4211 rhaas@postgresql.org 1001 : 245 : fuzzystate->distance = MAX_FUZZY_DISTANCE + 1;
1002 : 245 : fuzzystate->rfirst = NULL;
1003 : 245 : fuzzystate->rsecond = NULL;
1398 tgl@sss.pgh.pa.us 1004 : 245 : fuzzystate->rexact1 = NULL;
1005 : 245 : fuzzystate->rexact2 = NULL;
1006 : :
5157 1007 [ + + ]: 510 : while (pstate != NULL)
1008 : : {
1009 : : ListCell *l;
1010 : :
1011 [ + + + + : 573 : foreach(l, pstate->p_rtable)
+ + ]
1012 : : {
4138 bruce@momjian.us 1013 : 308 : RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
1014 : 308 : int fuzzy_rte_penalty = 0;
1015 : : int attnum;
1016 : :
1017 : : /*
1018 : : * Typically, it is not useful to look for matches within join
1019 : : * RTEs; they effectively duplicate other RTEs for our purposes,
1020 : : * and if a match is chosen from a join RTE, an unhelpful alias is
1021 : : * displayed in the final diagnostic message.
1022 : : */
4211 rhaas@postgresql.org 1023 [ + + ]: 308 : if (rte->rtekind == RTE_JOIN)
1024 : 36 : continue;
1025 : :
1026 : : /*
1027 : : * If the user didn't specify an alias, then matches against one
1028 : : * RTE are as good as another. But if the user did specify an
1029 : : * alias, then we want at least a fuzzy - and preferably an exact
1030 : : * - match for the range table entry.
1031 : : */
1032 [ + + ]: 272 : if (alias != NULL)
1033 : : fuzzy_rte_penalty =
3894 tgl@sss.pgh.pa.us 1034 : 76 : varstr_levenshtein_less_equal(alias, strlen(alias),
1035 : 76 : rte->eref->aliasname,
3378 1036 : 76 : strlen(rte->eref->aliasname),
1037 : : 1, 1, 1,
1038 : : MAX_FUZZY_DISTANCE + 1,
1039 : : true);
1040 : :
1041 : : /*
1042 : : * Scan for a matching column, and update fuzzystate. Non-exact
1043 : : * matches are dealt with inside scanRTEForColumn, but exact
1044 : : * matches are handled here. (There won't be more than one exact
1045 : : * match in the same RTE, else we'd have thrown error earlier.)
1046 : : */
1398 1047 : 272 : attnum = scanRTEForColumn(orig_pstate, rte, rte->eref,
1048 : : colname, location,
1049 : : fuzzy_rte_penalty, fuzzystate);
1050 [ + + + + ]: 272 : if (attnum != InvalidAttrNumber && fuzzy_rte_penalty == 0)
1051 : : {
1052 [ + + ]: 40 : if (fuzzystate->rexact1 == NULL)
1053 : : {
1054 : 28 : fuzzystate->rexact1 = rte;
1055 : 28 : fuzzystate->exact1 = attnum;
1056 : : }
1057 : : else
1058 : : {
1059 : : /* Needn't worry about overwriting previous rexact2 */
1060 : 12 : fuzzystate->rexact2 = rte;
1061 : 12 : fuzzystate->exact2 = attnum;
1062 : : }
1063 : : }
1064 : : }
1065 : :
5157 1066 : 265 : pstate = pstate->parentParseState;
1067 : : }
1068 : :
4211 rhaas@postgresql.org 1069 : 245 : return fuzzystate;
1070 : : }
1071 : :
1072 : : /*
1073 : : * markNullableIfNeeded
1074 : : * If the RTE referenced by the Var is nullable by outer join(s)
1075 : : * at this point in the query, set var->varnullingrels to show that.
1076 : : */
1077 : : void
1329 tgl@sss.pgh.pa.us 1078 : 3314332 : markNullableIfNeeded(ParseState *pstate, Var *var)
1079 : : {
1080 : 3314332 : int rtindex = var->varno;
1081 : : Bitmapset *relids;
1082 : :
1083 : : /* Find the appropriate pstate */
71 peter@eisentraut.org 1084 [ + + ]:GNC 3360210 : for (Index lv = 0; lv < var->varlevelsup; lv++)
1329 tgl@sss.pgh.pa.us 1085 :CBC 45878 : pstate = pstate->parentParseState;
1086 : :
1087 : : /* Find currently-relevant join relids for the Var's rel */
1088 [ + - + + ]: 3314332 : if (rtindex > 0 && rtindex <= list_length(pstate->p_nullingrels))
1089 : 1409402 : relids = (Bitmapset *) list_nth(pstate->p_nullingrels, rtindex - 1);
1090 : : else
1091 : 1904930 : relids = NULL;
1092 : :
1093 : : /*
1094 : : * Merge with any already-declared nulling rels. (Typically there won't
1095 : : * be any, but let's get it right if there are.)
1096 : : */
1097 [ + + ]: 3314332 : if (relids != NULL)
1098 : 535033 : var->varnullingrels = bms_union(var->varnullingrels, relids);
1099 : 3314332 : }
1100 : :
1101 : : /*
1102 : : * markRTEForSelectPriv
1103 : : * Mark the specified column of the RTE with index rtindex
1104 : : * as requiring SELECT privilege
1105 : : *
1106 : : * col == InvalidAttrNumber means a "whole row" reference
1107 : : */
1108 : : static void
2050 1109 : 1256884 : markRTEForSelectPriv(ParseState *pstate, int rtindex, AttrNumber col)
1110 : : {
1111 : 1256884 : RangeTblEntry *rte = rt_fetch(rtindex, pstate->p_rtable);
1112 : :
6450 1113 [ + + ]: 1256884 : if (rte->rtekind == RTE_RELATION)
1114 : : {
1115 : : RTEPermissionInfo *perminfo;
1116 : :
1117 : : /* Make sure the rel as a whole is marked for SELECT access */
1384 alvherre@alvh.no-ip. 1118 : 1108606 : perminfo = getRTEPermissionInfo(pstate->p_rteperminfos, rte);
1119 : 1108606 : perminfo->requiredPerms |= ACL_SELECT;
1120 : : /* Must offset the attnum to fit in a bitmapset */
1121 : 1108606 : perminfo->selectedCols =
1122 : 1108606 : bms_add_member(perminfo->selectedCols,
1123 : : col - FirstLowInvalidHeapAttributeNumber);
1124 : : }
6450 tgl@sss.pgh.pa.us 1125 [ + + ]: 148278 : else if (rte->rtekind == RTE_JOIN)
1126 : : {
1127 [ + + ]: 396 : if (col == InvalidAttrNumber)
1128 : : {
1129 : : /*
1130 : : * A whole-row reference to a join has to be treated as whole-row
1131 : : * references to the two inputs.
1132 : : */
1133 : : JoinExpr *j;
1134 : :
1135 [ + - + - ]: 4 : if (rtindex > 0 && rtindex <= list_length(pstate->p_joinexprs))
3450 1136 : 4 : j = list_nth_node(JoinExpr, pstate->p_joinexprs, rtindex - 1);
1137 : : else
6450 tgl@sss.pgh.pa.us 1138 :UBC 0 : j = NULL;
6450 tgl@sss.pgh.pa.us 1139 [ - + ]:CBC 4 : if (j == NULL)
6450 tgl@sss.pgh.pa.us 1140 [ # # ]:UBC 0 : elog(ERROR, "could not find JoinExpr for whole-row reference");
1141 : :
1142 : : /* Note: we can't see FromExpr here */
6450 tgl@sss.pgh.pa.us 1143 [ + - ]:CBC 4 : if (IsA(j->larg, RangeTblRef))
1144 : : {
6310 bruce@momjian.us 1145 : 4 : int varno = ((RangeTblRef *) j->larg)->rtindex;
1146 : :
2050 tgl@sss.pgh.pa.us 1147 : 4 : markRTEForSelectPriv(pstate, varno, InvalidAttrNumber);
1148 : : }
6450 tgl@sss.pgh.pa.us 1149 [ # # ]:UBC 0 : else if (IsA(j->larg, JoinExpr))
1150 : : {
6310 bruce@momjian.us 1151 : 0 : int varno = ((JoinExpr *) j->larg)->rtindex;
1152 : :
2050 tgl@sss.pgh.pa.us 1153 : 0 : markRTEForSelectPriv(pstate, varno, InvalidAttrNumber);
1154 : : }
1155 : : else
6450 1156 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
1157 : : (int) nodeTag(j->larg));
6450 tgl@sss.pgh.pa.us 1158 [ + - ]:CBC 4 : if (IsA(j->rarg, RangeTblRef))
1159 : : {
6310 bruce@momjian.us 1160 : 4 : int varno = ((RangeTblRef *) j->rarg)->rtindex;
1161 : :
2050 tgl@sss.pgh.pa.us 1162 : 4 : markRTEForSelectPriv(pstate, varno, InvalidAttrNumber);
1163 : : }
6450 tgl@sss.pgh.pa.us 1164 [ # # ]:UBC 0 : else if (IsA(j->rarg, JoinExpr))
1165 : : {
6310 bruce@momjian.us 1166 : 0 : int varno = ((JoinExpr *) j->rarg)->rtindex;
1167 : :
2050 tgl@sss.pgh.pa.us 1168 : 0 : markRTEForSelectPriv(pstate, varno, InvalidAttrNumber);
1169 : : }
1170 : : else
6450 1171 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
1172 : : (int) nodeTag(j->rarg));
1173 : : }
1174 : : else
1175 : : {
1176 : : /*
1177 : : * Join alias Vars for ordinary columns must refer to merged JOIN
1178 : : * USING columns. We don't need to do anything here, because the
1179 : : * join input columns will also be referenced in the join's qual
1180 : : * clause, and will get marked for select privilege there.
1181 : : */
1182 : : }
1183 : : }
1184 : : /* other RTE types don't require privilege marking */
6450 tgl@sss.pgh.pa.us 1185 :CBC 1256884 : }
1186 : :
1187 : : /*
1188 : : * markVarForSelectPriv
1189 : : * Mark the RTE referenced by the Var as requiring SELECT privilege
1190 : : * for the Var's column (the Var could be a whole-row Var, too)
1191 : : */
1192 : : void
2047 1193 : 1256876 : markVarForSelectPriv(ParseState *pstate, Var *var)
1194 : : {
1195 : : Index lv;
1196 : :
6450 1197 [ - + ]: 1256876 : Assert(IsA(var, Var));
1198 : : /* Find the appropriate pstate if it's an uplevel Var */
1199 [ + + ]: 1302754 : for (lv = 0; lv < var->varlevelsup; lv++)
1200 : 45878 : pstate = pstate->parentParseState;
2050 1201 : 1256876 : markRTEForSelectPriv(pstate, var->varno, var->varattno);
6450 1202 : 1256876 : }
1203 : :
1204 : : /*
1205 : : * buildRelationAliases
1206 : : * Construct the eref column name list for a relation RTE.
1207 : : * This code is also used for function RTEs.
1208 : : *
1209 : : * tupdesc: the physical column information
1210 : : * alias: the user-supplied alias, or NULL if none
1211 : : * eref: the eref Alias to store column names in
1212 : : *
1213 : : * eref->colnames is filled in. Also, alias->colnames is rebuilt to insert
1214 : : * empty strings for any dropped columns, so that it will be one-to-one with
1215 : : * physical column numbers.
1216 : : *
1217 : : * It is an error for there to be more aliases present than required.
1218 : : */
1219 : : static void
4686 1220 : 402856 : buildRelationAliases(TupleDesc tupdesc, Alias *alias, Alias *eref)
1221 : : {
8067 1222 : 402856 : int maxattrs = tupdesc->natts;
1223 : : List *aliaslist;
1224 : : ListCell *aliaslc;
1225 : : int numaliases;
1226 : : int varattno;
1227 : 402856 : int numdropped = 0;
1228 : :
1229 [ - + ]: 402856 : Assert(eref->colnames == NIL);
1230 : :
1231 [ + + ]: 402856 : if (alias)
1232 : : {
2624 1233 : 180915 : aliaslist = alias->colnames;
1234 : 180915 : aliaslc = list_head(aliaslist);
1235 : 180915 : numaliases = list_length(aliaslist);
1236 : : /* We'll rebuild the alias colname list */
8067 1237 : 180915 : alias->colnames = NIL;
1238 : : }
1239 : : else
1240 : : {
2624 1241 : 221941 : aliaslist = NIL;
8067 1242 : 221941 : aliaslc = NULL;
1243 : 221941 : numaliases = 0;
1244 : : }
1245 : :
1246 [ + + ]: 4405619 : for (varattno = 0; varattno < maxattrs; varattno++)
1247 : : {
3318 andres@anarazel.de 1248 : 4002763 : Form_pg_attribute attr = TupleDescAttr(tupdesc, varattno);
1249 : : String *attrname;
1250 : :
8067 tgl@sss.pgh.pa.us 1251 [ + + ]: 4002763 : if (attr->attisdropped)
1252 : : {
1253 : : /* Always insert an empty string for a dropped column */
1254 : 3570 : attrname = makeString(pstrdup(""));
1255 [ + + ]: 3570 : if (aliaslc)
1256 : 3 : alias->colnames = lappend(alias->colnames, attrname);
1257 : 3570 : numdropped++;
1258 : : }
1259 [ + + ]: 3999193 : else if (aliaslc)
1260 : : {
1261 : : /* Use the next user-supplied alias */
1837 peter@eisentraut.org 1262 : 4730 : attrname = lfirst_node(String, aliaslc);
2624 tgl@sss.pgh.pa.us 1263 : 4730 : aliaslc = lnext(aliaslist, aliaslc);
8067 1264 : 4730 : alias->colnames = lappend(alias->colnames, attrname);
1265 : : }
1266 : : else
1267 : : {
1268 : 3994463 : attrname = makeString(pstrdup(NameStr(attr->attname)));
1269 : : /* we're done with the alias if any */
1270 : : }
1271 : :
1272 : 4002763 : eref->colnames = lappend(eref->colnames, attrname);
1273 : : }
1274 : :
1275 : : /* Too many user-supplied aliases? */
1276 [ + + ]: 402856 : if (aliaslc)
1277 [ + - ]: 4 : ereport(ERROR,
1278 : : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1279 : : errmsg("table \"%s\" has %d columns available but %d columns specified",
1280 : : eref->aliasname, maxattrs - numdropped, numaliases)));
1281 : 402852 : }
1282 : :
1283 : : /*
1284 : : * chooseScalarFunctionAlias
1285 : : * Select the column alias for a function in a function RTE,
1286 : : * when the function returns a scalar type (not composite or RECORD).
1287 : : *
1288 : : * funcexpr: transformed expression tree for the function call
1289 : : * funcname: function name (as determined by FigureColname)
1290 : : * alias: the user-supplied alias for the RTE, or NULL if none
1291 : : * nfuncs: the number of functions appearing in the function RTE
1292 : : *
1293 : : * Note that the name we choose might be overridden later, if the user-given
1294 : : * alias includes column alias names. That's of no concern here.
1295 : : */
1296 : : static char *
4686 1297 : 15063 : chooseScalarFunctionAlias(Node *funcexpr, char *funcname,
1298 : : Alias *alias, int nfuncs)
1299 : : {
1300 : : char *pname;
1301 : :
1302 : : /*
1303 : : * If the expression is a simple function call, and the function has a
1304 : : * single OUT parameter that is named, use the parameter's name.
1305 : : */
1306 [ + - + + ]: 15063 : if (funcexpr && IsA(funcexpr, FuncExpr))
1307 : : {
1308 : 14987 : pname = get_func_result_name(((FuncExpr *) funcexpr)->funcid);
1309 [ + + ]: 14987 : if (pname)
1310 : 957 : return pname;
1311 : : }
1312 : :
1313 : : /*
1314 : : * If there's just one function in the RTE, and the user gave an RTE alias
1315 : : * name, use that name. (This makes FROM func() AS foo use "foo" as the
1316 : : * column name as well as the table alias.)
1317 : : */
1318 [ + + + + ]: 14106 : if (nfuncs == 1 && alias)
1319 : 9954 : return alias->aliasname;
1320 : :
1321 : : /*
1322 : : * Otherwise use the function name.
1323 : : */
1324 : 4152 : return funcname;
1325 : : }
1326 : :
1327 : : /*
1328 : : * buildNSItemFromTupleDesc
1329 : : * Build a ParseNamespaceItem, given a tupdesc describing the columns.
1330 : : *
1331 : : * rte: the new RangeTblEntry for the rel
1332 : : * rtindex: its index in the rangetable list
1333 : : * perminfo: permission list entry for the rel
1334 : : * tupdesc: the physical column information
1335 : : */
1336 : : static ParseNamespaceItem *
1384 alvherre@alvh.no-ip. 1337 : 402852 : buildNSItemFromTupleDesc(RangeTblEntry *rte, Index rtindex,
1338 : : RTEPermissionInfo *perminfo,
1339 : : TupleDesc tupdesc)
1340 : : {
1341 : : ParseNamespaceItem *nsitem;
1342 : : ParseNamespaceColumn *nscolumns;
2453 tgl@sss.pgh.pa.us 1343 : 402852 : int maxattrs = tupdesc->natts;
1344 : : int varattno;
1345 : :
1346 : : /* colnames must have the same number of entries as the nsitem */
1347 [ - + ]: 402852 : Assert(maxattrs == list_length(rte->eref->colnames));
1348 : :
1349 : : /* extract per-column data from the tupdesc */
34 michael@paquier.xyz 1350 :GNC 402852 : nscolumns = palloc0_array(ParseNamespaceColumn, maxattrs);
1351 : :
2453 tgl@sss.pgh.pa.us 1352 [ + + ]:CBC 4405611 : for (varattno = 0; varattno < maxattrs; varattno++)
1353 : : {
1354 : 4002759 : Form_pg_attribute attr = TupleDescAttr(tupdesc, varattno);
1355 : :
1356 : : /* For a dropped column, just leave the entry as zeroes */
1357 [ + + ]: 4002759 : if (attr->attisdropped)
1358 : 3570 : continue;
1359 : :
1360 : 3999189 : nscolumns[varattno].p_varno = rtindex;
1361 : 3999189 : nscolumns[varattno].p_varattno = varattno + 1;
1362 : 3999189 : nscolumns[varattno].p_vartype = attr->atttypid;
1363 : 3999189 : nscolumns[varattno].p_vartypmod = attr->atttypmod;
1364 : 3999189 : nscolumns[varattno].p_varcollid = attr->attcollation;
1365 : 3999189 : nscolumns[varattno].p_varnosyn = rtindex;
1366 : 3999189 : nscolumns[varattno].p_varattnosyn = varattno + 1;
1367 : : }
1368 : :
1369 : : /* ... and build the nsitem */
284 michael@paquier.xyz 1370 : 402852 : nsitem = palloc_object(ParseNamespaceItem);
1999 peter@eisentraut.org 1371 : 402852 : nsitem->p_names = rte->eref;
2453 tgl@sss.pgh.pa.us 1372 : 402852 : nsitem->p_rte = rte;
1373 : 402852 : nsitem->p_rtindex = rtindex;
1384 alvherre@alvh.no-ip. 1374 : 402852 : nsitem->p_perminfo = perminfo;
2453 tgl@sss.pgh.pa.us 1375 : 402852 : nsitem->p_nscolumns = nscolumns;
1376 : : /* set default visibility flags; might get changed later */
1377 : 402852 : nsitem->p_rel_visible = true;
1378 : 402852 : nsitem->p_cols_visible = true;
1379 : 402852 : nsitem->p_lateral_only = false;
1380 : 402852 : nsitem->p_lateral_ok = true;
612 dean.a.rasheed@gmail 1381 : 402852 : nsitem->p_returning_type = VAR_RETURNING_DEFAULT;
1382 : :
2453 tgl@sss.pgh.pa.us 1383 : 402852 : return nsitem;
1384 : : }
1385 : :
1386 : : /*
1387 : : * buildNSItemFromLists
1388 : : * Build a ParseNamespaceItem, given column type information in lists.
1389 : : *
1390 : : * rte: the new RangeTblEntry for the rel
1391 : : * rtindex: its index in the rangetable list
1392 : : * coltypes: per-column datatype OIDs
1393 : : * coltypmods: per-column type modifiers
1394 : : * colcollation: per-column collation OIDs
1395 : : */
1396 : : static ParseNamespaceItem *
1397 : 60764 : buildNSItemFromLists(RangeTblEntry *rte, Index rtindex,
1398 : : List *coltypes, List *coltypmods, List *colcollations)
1399 : : {
1400 : : ParseNamespaceItem *nsitem;
1401 : : ParseNamespaceColumn *nscolumns;
1402 : 60764 : int maxattrs = list_length(coltypes);
1403 : : int varattno;
1404 : : ListCell *lct;
1405 : : ListCell *lcm;
1406 : : ListCell *lcc;
1407 : :
1408 : : /* colnames must have the same number of entries as the nsitem */
1409 [ - + ]: 60764 : Assert(maxattrs == list_length(rte->eref->colnames));
1410 : :
1411 [ - + ]: 60764 : Assert(maxattrs == list_length(coltypmods));
1412 [ - + ]: 60764 : Assert(maxattrs == list_length(colcollations));
1413 : :
1414 : : /* extract per-column data from the lists */
34 michael@paquier.xyz 1415 :GNC 60764 : nscolumns = palloc0_array(ParseNamespaceColumn, maxattrs);
1416 : :
2453 tgl@sss.pgh.pa.us 1417 :CBC 60764 : varattno = 0;
1418 [ + + + + : 199983 : forthree(lct, coltypes,
+ + + + +
+ + + + +
+ - + - +
+ ]
1419 : : lcm, coltypmods,
1420 : : lcc, colcollations)
1421 : : {
1422 : 139219 : nscolumns[varattno].p_varno = rtindex;
1423 : 139219 : nscolumns[varattno].p_varattno = varattno + 1;
1424 : 139219 : nscolumns[varattno].p_vartype = lfirst_oid(lct);
1425 : 139219 : nscolumns[varattno].p_vartypmod = lfirst_int(lcm);
1426 : 139219 : nscolumns[varattno].p_varcollid = lfirst_oid(lcc);
1427 : 139219 : nscolumns[varattno].p_varnosyn = rtindex;
1428 : 139219 : nscolumns[varattno].p_varattnosyn = varattno + 1;
1429 : 139219 : varattno++;
1430 : : }
1431 : :
1432 : : /* ... and build the nsitem */
284 michael@paquier.xyz 1433 : 60764 : nsitem = palloc_object(ParseNamespaceItem);
1999 peter@eisentraut.org 1434 : 60764 : nsitem->p_names = rte->eref;
2453 tgl@sss.pgh.pa.us 1435 : 60764 : nsitem->p_rte = rte;
1436 : 60764 : nsitem->p_rtindex = rtindex;
1164 amitlan@postgresql.o 1437 : 60764 : nsitem->p_perminfo = NULL;
2453 tgl@sss.pgh.pa.us 1438 : 60764 : nsitem->p_nscolumns = nscolumns;
1439 : : /* set default visibility flags; might get changed later */
1440 : 60764 : nsitem->p_rel_visible = true;
1441 : 60764 : nsitem->p_cols_visible = true;
1442 : 60764 : nsitem->p_lateral_only = false;
1443 : 60764 : nsitem->p_lateral_ok = true;
612 dean.a.rasheed@gmail 1444 : 60764 : nsitem->p_returning_type = VAR_RETURNING_DEFAULT;
1445 : :
2453 tgl@sss.pgh.pa.us 1446 : 60764 : return nsitem;
1447 : : }
1448 : :
1449 : : /*
1450 : : * Open a table during parse analysis
1451 : : *
1452 : : * This is essentially just the same as table_openrv(), except that it caters
1453 : : * to some parser-specific error reporting needs, notably that it arranges
1454 : : * to include the RangeVar's parse location in any resulting error.
1455 : : */
1456 : : Relation
209 peter@eisentraut.org 1457 : 308847 : parserOpenTable(ParseState *pstate, const RangeVar *relation, LOCKMODE lockmode)
1458 : : {
1459 : : Relation rel;
1460 : : ParseCallbackState pcbstate;
1461 : :
6593 tgl@sss.pgh.pa.us 1462 : 308847 : setup_parser_errposition_callback(&pcbstate, pstate, relation->location);
2799 andres@anarazel.de 1463 : 308847 : rel = table_openrv_extended(relation, lockmode, true);
6556 tgl@sss.pgh.pa.us 1464 [ + + ]: 308846 : if (rel == NULL)
1465 : : {
1466 [ + + ]: 109 : if (relation->schemaname)
1467 [ + - ]: 1 : ereport(ERROR,
1468 : : (errcode(ERRCODE_UNDEFINED_TABLE),
1469 : : errmsg("relation \"%s.%s\" does not exist",
1470 : : relation->schemaname, relation->relname)));
1471 : : else
1472 : : {
1473 : : /*
1474 : : * An unqualified name might have been meant as a reference to
1475 : : * some not-yet-in-scope CTE. The bare "does not exist" message
1476 : : * has proven remarkably unhelpful for figuring out such problems,
1477 : : * so we take pains to offer a specific hint.
1478 : : */
3261 1479 [ + + ]: 108 : if (isFutureCTE(pstate, relation->relname))
6556 1480 [ + - ]: 4 : ereport(ERROR,
1481 : : (errcode(ERRCODE_UNDEFINED_TABLE),
1482 : : errmsg("relation \"%s\" does not exist",
1483 : : relation->relname),
1484 : : errdetail("There is a WITH item named \"%s\", but it cannot be referenced from this part of the query.",
1485 : : relation->relname),
1486 : : errhint("Use WITH RECURSIVE, or re-order the WITH items to remove forward references.")));
1487 : : else
1488 [ + - ]: 104 : ereport(ERROR,
1489 : : (errcode(ERRCODE_UNDEFINED_TABLE),
1490 : : errmsg("relation \"%s\" does not exist",
1491 : : relation->relname)));
1492 : : }
1493 : : }
6593 1494 : 308737 : cancel_parser_errposition_callback(&pcbstate);
1495 : 308737 : return rel;
1496 : : }
1497 : :
1498 : : /*
1499 : : * Add an entry for a relation to the pstate's range table (p_rtable).
1500 : : * Then, construct and return a ParseNamespaceItem for the new RTE.
1501 : : *
1502 : : * We do not link the ParseNamespaceItem into the pstate here; it's the
1503 : : * caller's job to do that in the appropriate way.
1504 : : *
1505 : : * Note: formerly this checked for refname conflicts, but that's wrong.
1506 : : * Caller is responsible for checking for conflicts in the appropriate scope.
1507 : : */
1508 : : ParseNamespaceItem *
10526 bruce@momjian.us 1509 : 252083 : addRangeTableEntry(ParseState *pstate,
1510 : : RangeVar *relation,
1511 : : Alias *alias,
1512 : : bool inh,
1513 : : bool inFromCl)
1514 : : {
9349 tgl@sss.pgh.pa.us 1515 : 252083 : RangeTblEntry *rte = makeNode(RangeTblEntry);
1516 : : RTEPermissionInfo *perminfo;
8948 1517 [ + + ]: 252083 : char *refname = alias ? alias->aliasname : relation->relname;
1518 : : LOCKMODE lockmode;
1519 : : Relation rel;
1520 : : ParseNamespaceItem *nsitem;
1521 : :
4219 rhaas@postgresql.org 1522 [ - + ]: 252083 : Assert(pstate != NULL);
1523 : :
8958 tgl@sss.pgh.pa.us 1524 : 252083 : rte->rtekind = RTE_RELATION;
9504 1525 : 252083 : rte->alias = alias;
1526 : :
1527 : : /*
1528 : : * Identify the type of lock we'll need on this relation. It's not the
1529 : : * query's target table (that case is handled elsewhere), so we need
1530 : : * either RowShareLock if it's locked by FOR UPDATE/SHARE, or plain
1531 : : * AccessShareLock otherwise.
1532 : : */
2912 1533 [ + + ]: 252083 : lockmode = isLockedRefname(pstate, refname) ? RowShareLock : AccessShareLock;
1534 : :
1535 : : /*
1536 : : * Get the rel's OID. This access also ensures that we have an up-to-date
1537 : : * relcache entry for the rel. Since this is typically the first access
1538 : : * to a rel in a statement, we must open the rel with the proper lockmode.
1539 : : */
6593 1540 : 252083 : rel = parserOpenTable(pstate, relation, lockmode);
9714 lockhart@fourpalms.o 1541 : 251986 : rte->relid = RelationGetRelid(rel);
927 peter@eisentraut.org 1542 : 251986 : rte->inh = inh;
5689 tgl@sss.pgh.pa.us 1543 : 251986 : rte->relkind = rel->rd_rel->relkind;
2912 1544 : 251986 : rte->rellockmode = lockmode;
1545 : :
1546 : : /*
1547 : : * Build the list of effective column names using user-supplied aliases
1548 : : * and/or actual column names.
1549 : : */
8067 1550 : 251986 : rte->eref = makeAlias(refname, NIL);
4686 1551 : 251986 : buildRelationAliases(rel->rd_att, alias, rte->eref);
1552 : :
1553 : : /*
1554 : : * Set flags and initialize access permissions.
1555 : : *
1556 : : * The initial default on access checks is always check-for-READ-access,
1557 : : * which is the right thing for all except target tables.
1558 : : */
5157 1559 : 251982 : rte->lateral = false;
8948 1560 : 251982 : rte->inFromCl = inFromCl;
1561 : :
1384 alvherre@alvh.no-ip. 1562 : 251982 : perminfo = addRTEPermissionInfo(&pstate->p_rteperminfos, rte);
1563 : 251982 : perminfo->requiredPerms = ACL_SELECT;
1564 : :
1565 : : /*
1566 : : * Add completed RTE to pstate's range table list, so that we know its
1567 : : * index. But we don't add it to the join list --- caller must do that if
1568 : : * appropriate.
1569 : : */
4219 rhaas@postgresql.org 1570 : 251982 : pstate->p_rtable = lappend(pstate->p_rtable, rte);
1571 : :
1572 : : /*
1573 : : * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
1574 : : * list --- caller must do that if appropriate.
1575 : : */
2453 tgl@sss.pgh.pa.us 1576 : 251982 : nsitem = buildNSItemFromTupleDesc(rte, list_length(pstate->p_rtable),
1577 : : perminfo, rel->rd_att);
1578 : :
1579 : : /*
1580 : : * Drop the rel refcount, but keep the access lock till end of transaction
1581 : : * so that the table can't be deleted or have its schema modified
1582 : : * underneath us.
1583 : : */
1584 : 251982 : table_close(rel, NoLock);
1585 : :
1586 : 251982 : return nsitem;
1587 : : }
1588 : :
1589 : : /*
1590 : : * Add an entry for a relation to the pstate's range table (p_rtable).
1591 : : * Then, construct and return a ParseNamespaceItem for the new RTE.
1592 : : *
1593 : : * This is just like addRangeTableEntry() except that it makes an RTE
1594 : : * given an already-open relation instead of a RangeVar reference.
1595 : : *
1596 : : * lockmode is the lock type required for query execution; it must be one
1597 : : * of AccessShareLock, RowShareLock, or RowExclusiveLock depending on the
1598 : : * RTE's role within the query. The caller must hold that lock mode
1599 : : * or a stronger one.
1600 : : */
1601 : : ParseNamespaceItem *
8948 1602 : 120967 : addRangeTableEntryForRelation(ParseState *pstate,
1603 : : Relation rel,
1604 : : LOCKMODE lockmode,
1605 : : Alias *alias,
1606 : : bool inh,
1607 : : bool inFromCl)
1608 : : {
1609 : 120967 : RangeTblEntry *rte = makeNode(RangeTblEntry);
1610 : : RTEPermissionInfo *perminfo;
7830 1611 [ + + ]: 120967 : char *refname = alias ? alias->aliasname : RelationGetRelationName(rel);
1612 : :
4211 rhaas@postgresql.org 1613 [ - + ]: 120967 : Assert(pstate != NULL);
1614 : :
2912 tgl@sss.pgh.pa.us 1615 [ + + + - : 120967 : Assert(lockmode == AccessShareLock ||
- + ]
1616 : : lockmode == RowShareLock ||
1617 : : lockmode == RowExclusiveLock);
2911 1618 [ - + ]: 120967 : Assert(CheckRelationLockedByMe(rel, lockmode, true));
1619 : :
8948 1620 : 120967 : rte->rtekind = RTE_RELATION;
1621 : 120967 : rte->alias = alias;
7830 1622 : 120967 : rte->relid = RelationGetRelid(rel);
927 peter@eisentraut.org 1623 : 120967 : rte->inh = inh;
5689 tgl@sss.pgh.pa.us 1624 : 120967 : rte->relkind = rel->rd_rel->relkind;
2912 1625 : 120967 : rte->rellockmode = lockmode;
1626 : :
1627 : : /*
1628 : : * Build the list of effective column names using user-supplied aliases
1629 : : * and/or actual column names.
1630 : : */
8067 1631 : 120967 : rte->eref = makeAlias(refname, NIL);
4686 1632 : 120967 : buildRelationAliases(rel->rd_att, alias, rte->eref);
1633 : :
1634 : : /*
1635 : : * Set flags and initialize access permissions.
1636 : : *
1637 : : * The initial default on access checks is always check-for-READ-access,
1638 : : * which is the right thing for all except target tables.
1639 : : */
5157 1640 : 120967 : rte->lateral = false;
10526 bruce@momjian.us 1641 : 120967 : rte->inFromCl = inFromCl;
1642 : :
1384 alvherre@alvh.no-ip. 1643 : 120967 : perminfo = addRTEPermissionInfo(&pstate->p_rteperminfos, rte);
1644 : 120967 : perminfo->requiredPerms = ACL_SELECT;
1645 : :
1646 : : /*
1647 : : * Add completed RTE to pstate's range table list, so that we know its
1648 : : * index. But we don't add it to the join list --- caller must do that if
1649 : : * appropriate.
1650 : : */
4211 rhaas@postgresql.org 1651 : 120967 : pstate->p_rtable = lappend(pstate->p_rtable, rte);
1652 : :
1653 : : /*
1654 : : * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
1655 : : * list --- caller must do that if appropriate.
1656 : : */
2453 tgl@sss.pgh.pa.us 1657 : 120967 : return buildNSItemFromTupleDesc(rte, list_length(pstate->p_rtable),
1658 : : perminfo, rel->rd_att);
1659 : : }
1660 : :
1661 : : /*
1662 : : * Add an entry for a subquery to the pstate's range table (p_rtable).
1663 : : * Then, construct and return a ParseNamespaceItem for the new RTE.
1664 : : *
1665 : : * This is much like addRangeTableEntry() except that it makes a subquery RTE.
1666 : : *
1667 : : * If the subquery does not have an alias, the auto-generated relation name in
1668 : : * the returned ParseNamespaceItem will be marked as not visible, and so only
1669 : : * unqualified references to the subquery columns will be allowed, and the
1670 : : * relation name will not conflict with others in the pstate's namespace list.
1671 : : */
1672 : : ParseNamespaceItem *
9487 1673 : 43278 : addRangeTableEntryForSubquery(ParseState *pstate,
1674 : : Query *subquery,
1675 : : Alias *alias,
1676 : : bool lateral,
1677 : : bool inFromCl)
1678 : : {
9349 1679 : 43278 : RangeTblEntry *rte = makeNode(RangeTblEntry);
1680 : : Alias *eref;
1681 : : int numaliases;
1682 : : List *coltypes,
1683 : : *coltypmods,
1684 : : *colcollations;
1685 : : int varattno;
1686 : : ListCell *tlistitem;
1687 : : ParseNamespaceItem *nsitem;
1688 : :
4211 rhaas@postgresql.org 1689 [ - + ]: 43278 : Assert(pstate != NULL);
1690 : :
8958 tgl@sss.pgh.pa.us 1691 : 43278 : rte->rtekind = RTE_SUBQUERY;
9487 1692 : 43278 : rte->subquery = subquery;
1693 : 43278 : rte->alias = alias;
1694 : :
1523 dean.a.rasheed@gmail 1695 [ + + ]: 43278 : eref = alias ? copyObject(alias) : makeAlias("unnamed_subquery", NIL);
8148 neilc@samurai.com 1696 : 43278 : numaliases = list_length(eref->colnames);
1697 : :
1698 : : /* fill in any unspecified alias columns, and extract column type info */
2453 tgl@sss.pgh.pa.us 1699 : 43278 : coltypes = coltypmods = colcollations = NIL;
9487 1700 : 43278 : varattno = 0;
1701 [ + + + + : 150376 : foreach(tlistitem, subquery->targetList)
+ + ]
1702 : : {
1703 : 107098 : TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
1704 : :
7837 1705 [ + + ]: 107098 : if (te->resjunk)
9487 1706 : 175 : continue;
1707 : 106923 : varattno++;
7837 1708 [ - + ]: 106923 : Assert(varattno == te->resno);
9487 1709 [ + + ]: 106923 : if (varattno > numaliases)
1710 : : {
1711 : : char *attrname;
1712 : :
7837 1713 : 96144 : attrname = pstrdup(te->resname);
8949 1714 : 96144 : eref->colnames = lappend(eref->colnames, makeString(attrname));
1715 : : }
2453 1716 : 106923 : coltypes = lappend_oid(coltypes,
1717 : 106923 : exprType((Node *) te->expr));
1718 : 106923 : coltypmods = lappend_int(coltypmods,
1719 : 106923 : exprTypmod((Node *) te->expr));
1720 : 106923 : colcollations = lappend_oid(colcollations,
1721 : 106923 : exprCollation((Node *) te->expr));
1722 : : }
9487 1723 [ + + ]: 43278 : if (varattno < numaliases)
8464 1724 [ + - ]: 4 : ereport(ERROR,
1725 : : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1726 : : errmsg("table \"%s\" has %d columns available but %d columns specified",
1727 : : eref->aliasname, varattno, numaliases)));
1728 : :
9487 1729 : 43274 : rte->eref = eref;
1730 : :
1731 : : /*
1732 : : * Set flags.
1733 : : *
1734 : : * Subqueries are never checked for access rights, so no need to perform
1735 : : * addRTEPermissionInfo().
1736 : : */
5157 1737 : 43274 : rte->lateral = lateral;
9487 1738 : 43274 : rte->inFromCl = inFromCl;
1739 : :
1740 : : /*
1741 : : * Add completed RTE to pstate's range table list, so that we know its
1742 : : * index. But we don't add it to the join list --- caller must do that if
1743 : : * appropriate.
1744 : : */
4211 rhaas@postgresql.org 1745 : 43274 : pstate->p_rtable = lappend(pstate->p_rtable, rte);
1746 : :
1747 : : /*
1748 : : * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
1749 : : * list --- caller must do that if appropriate.
1750 : : */
1523 dean.a.rasheed@gmail 1751 : 43274 : nsitem = buildNSItemFromLists(rte, list_length(pstate->p_rtable),
1752 : : coltypes, coltypmods, colcollations);
1753 : :
1754 : : /*
1755 : : * Mark it visible as a relation name only if it had a user-written alias.
1756 : : */
1757 : 43274 : nsitem->p_rel_visible = (alias != NULL);
1758 : :
1759 : 43274 : return nsitem;
1760 : : }
1761 : :
1762 : : /*
1763 : : * Add an entry for a function (or functions) to the pstate's range table
1764 : : * (p_rtable). Then, construct and return a ParseNamespaceItem for the new RTE.
1765 : : *
1766 : : * This is much like addRangeTableEntry() except that it makes a function RTE.
1767 : : */
1768 : : ParseNamespaceItem *
8897 tgl@sss.pgh.pa.us 1769 : 29613 : addRangeTableEntryForFunction(ParseState *pstate,
1770 : : List *funcnames,
1771 : : List *funcexprs,
1772 : : List *coldeflists,
1773 : : RangeFunction *rangefunc,
1774 : : bool lateral,
1775 : : bool inFromCl)
1776 : : {
1777 : 29613 : RangeTblEntry *rte = makeNode(RangeTblEntry);
8813 bruce@momjian.us 1778 : 29613 : Alias *alias = rangefunc->alias;
1779 : : Alias *eref;
1780 : : char *aliasname;
4686 tgl@sss.pgh.pa.us 1781 : 29613 : int nfuncs = list_length(funcexprs);
1782 : : TupleDesc *functupdescs;
1783 : : TupleDesc tupdesc;
1784 : : ListCell *lc1,
1785 : : *lc2,
1786 : : *lc3;
1787 : : int i;
1788 : : int j;
1789 : : int funcno;
1790 : : int natts,
1791 : : totalatts;
1792 : :
4211 rhaas@postgresql.org 1793 [ - + ]: 29613 : Assert(pstate != NULL);
1794 : :
8897 tgl@sss.pgh.pa.us 1795 : 29613 : rte->rtekind = RTE_FUNCTION;
1796 : 29613 : rte->relid = InvalidOid;
1797 : 29613 : rte->subquery = NULL;
4686 1798 : 29613 : rte->functions = NIL; /* we'll fill this list below */
1799 : 29613 : rte->funcordinality = rangefunc->ordinality;
8897 1800 : 29613 : rte->alias = alias;
1801 : :
1802 : : /*
1803 : : * Choose the RTE alias name. We default to using the first function's
1804 : : * name even when there's more than one; which is maybe arguable but beats
1805 : : * using something constant like "table".
1806 : : */
4686 1807 [ + + ]: 29613 : if (alias)
1808 : 18041 : aliasname = alias->aliasname;
1809 : : else
1810 : 11572 : aliasname = linitial(funcnames);
1811 : :
1812 : 29613 : eref = makeAlias(aliasname, NIL);
1813 : 29613 : rte->eref = eref;
1814 : :
1815 : : /* Process each function ... */
284 michael@paquier.xyz 1816 : 29613 : functupdescs = palloc_array(TupleDesc, nfuncs);
1817 : :
4686 tgl@sss.pgh.pa.us 1818 : 29613 : totalatts = 0;
1819 : 29613 : funcno = 0;
1820 [ + - + + : 59404 : forthree(lc1, funcexprs, lc2, funcnames, lc3, coldeflists)
+ - + + +
- + + + +
+ - + - +
+ ]
1821 : : {
1822 : 29825 : Node *funcexpr = (Node *) lfirst(lc1);
1823 : 29825 : char *funcname = (char *) lfirst(lc2);
1824 : 29825 : List *coldeflist = (List *) lfirst(lc3);
1825 : 29825 : RangeTblFunction *rtfunc = makeNode(RangeTblFunction);
1826 : : TypeFuncClass functypclass;
1827 : : Oid funcrettype;
1828 : :
1829 : : /* Initialize RangeTblFunction node */
1830 : 29825 : rtfunc->funcexpr = funcexpr;
1831 : 29825 : rtfunc->funccolnames = NIL;
1832 : 29825 : rtfunc->funccoltypes = NIL;
1833 : 29825 : rtfunc->funccoltypmods = NIL;
1834 : 29825 : rtfunc->funccolcollations = NIL;
3378 1835 : 29825 : rtfunc->funcparams = NULL; /* not set until planning */
1836 : :
1837 : : /*
1838 : : * Now determine if the function returns a simple or composite type.
1839 : : */
4686 1840 : 29825 : functypclass = get_expr_result_type(funcexpr,
1841 : : &funcrettype,
1842 : : &tupdesc);
1843 : :
1844 : : /*
1845 : : * A coldeflist is required if the function returns RECORD and hasn't
1846 : : * got a predetermined record type, and is prohibited otherwise. This
1847 : : * can be a bit confusing, so we expend some effort on delivering a
1848 : : * relevant error message.
1849 : : */
1850 [ + + ]: 29825 : if (coldeflist != NIL)
1851 : : {
2189 1852 [ + + + ]: 499 : switch (functypclass)
1853 : : {
1854 : 487 : case TYPEFUNC_RECORD:
1855 : : /* ok */
1856 : 487 : break;
1857 : 8 : case TYPEFUNC_COMPOSITE:
1858 : : case TYPEFUNC_COMPOSITE_DOMAIN:
1859 : :
1860 : : /*
1861 : : * If the function's raw result type is RECORD, we must
1862 : : * have resolved it using its OUT parameters. Otherwise,
1863 : : * it must have a named composite type.
1864 : : */
1865 [ + + ]: 8 : if (exprType(funcexpr) == RECORDOID)
1866 [ + - ]: 4 : ereport(ERROR,
1867 : : (errcode(ERRCODE_SYNTAX_ERROR),
1868 : : errmsg("a column definition list is redundant for a function with OUT parameters"),
1869 : : parser_errposition(pstate,
1870 : : exprLocation((Node *) coldeflist))));
1871 : : else
1872 [ + - ]: 4 : ereport(ERROR,
1873 : : (errcode(ERRCODE_SYNTAX_ERROR),
1874 : : errmsg("a column definition list is redundant for a function returning a named composite type"),
1875 : : parser_errposition(pstate,
1876 : : exprLocation((Node *) coldeflist))));
1877 : : break;
1878 : 4 : default:
1879 [ + - ]: 4 : ereport(ERROR,
1880 : : (errcode(ERRCODE_SYNTAX_ERROR),
1881 : : errmsg("a column definition list is only allowed for functions returning \"record\""),
1882 : : parser_errposition(pstate,
1883 : : exprLocation((Node *) coldeflist))));
1884 : : break;
1885 : : }
1886 : : }
1887 : : else
1888 : : {
4686 1889 [ + + ]: 29326 : if (functypclass == TYPEFUNC_RECORD)
1890 [ + - ]: 18 : ereport(ERROR,
1891 : : (errcode(ERRCODE_SYNTAX_ERROR),
1892 : : errmsg("a column definition list is required for functions returning \"record\""),
1893 : : parser_errposition(pstate, exprLocation(funcexpr))));
1894 : : }
1895 : :
3251 1896 [ + + + + ]: 29795 : if (functypclass == TYPEFUNC_COMPOSITE ||
1897 : : functypclass == TYPEFUNC_COMPOSITE_DOMAIN)
1898 : : {
1899 : : /* Composite data type, e.g. a table's row type */
4686 1900 [ - + ]: 14241 : Assert(tupdesc);
1901 : : }
1902 [ + + ]: 15554 : else if (functypclass == TYPEFUNC_SCALAR)
1903 : : {
1904 : : /* Base data type, i.e. scalar */
2861 andres@anarazel.de 1905 : 15063 : tupdesc = CreateTemplateTupleDesc(1);
4686 tgl@sss.pgh.pa.us 1906 : 30126 : TupleDescInitEntry(tupdesc,
1907 : : (AttrNumber) 1,
1908 : 15063 : chooseScalarFunctionAlias(funcexpr, funcname,
1909 : : alias, nfuncs),
1910 : : funcrettype,
1911 : : exprTypmod(funcexpr),
1912 : : 0);
2453 1913 : 15063 : TupleDescInitEntryCollation(tupdesc,
1914 : : (AttrNumber) 1,
1915 : : exprCollation(funcexpr));
188 drowley@postgresql.o 1916 : 15063 : TupleDescFinalize(tupdesc);
1917 : : }
4686 tgl@sss.pgh.pa.us 1918 [ + + ]: 491 : else if (functypclass == TYPEFUNC_RECORD)
1919 : : {
1920 : : ListCell *col;
1921 : :
1922 : : /*
1923 : : * Use the column definition list to construct a tupdesc and fill
1924 : : * in the RangeTblFunction's lists. Limit number of columns to
1925 : : * MaxHeapAttributeNumber, because CheckAttributeNamesTypes will.
1926 : : */
1511 1927 [ - + ]: 487 : if (list_length(coldeflist) > MaxHeapAttributeNumber)
1511 tgl@sss.pgh.pa.us 1928 [ # # ]:UBC 0 : ereport(ERROR,
1929 : : (errcode(ERRCODE_TOO_MANY_COLUMNS),
1930 : : errmsg("column definition lists can have at most %d entries",
1931 : : MaxHeapAttributeNumber),
1932 : : parser_errposition(pstate,
1933 : : exprLocation((Node *) coldeflist))));
2861 andres@anarazel.de 1934 :CBC 487 : tupdesc = CreateTemplateTupleDesc(list_length(coldeflist));
4686 tgl@sss.pgh.pa.us 1935 : 487 : i = 1;
1936 [ + - + + : 1635 : foreach(col, coldeflist)
+ + ]
1937 : : {
1938 : 1148 : ColumnDef *n = (ColumnDef *) lfirst(col);
1939 : : char *attrname;
1940 : : Oid attrtype;
1941 : : int32 attrtypmod;
1942 : : Oid attrcollation;
1943 : :
1944 : 1148 : attrname = n->colname;
1945 [ - + ]: 1148 : if (n->typeName->setof)
4686 tgl@sss.pgh.pa.us 1946 [ # # ]:UBC 0 : ereport(ERROR,
1947 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1948 : : errmsg("column \"%s\" cannot be declared SETOF",
1949 : : attrname),
1950 : : parser_errposition(pstate, n->location)));
4686 tgl@sss.pgh.pa.us 1951 :CBC 1148 : typenameTypeIdAndMod(pstate, n->typeName,
1952 : : &attrtype, &attrtypmod);
1953 : 1148 : attrcollation = GetColumnDefCollation(pstate, n, attrtype);
1954 : 1148 : TupleDescInitEntry(tupdesc,
1955 : 1148 : (AttrNumber) i,
1956 : : attrname,
1957 : : attrtype,
1958 : : attrtypmod,
1959 : : 0);
1960 : 1148 : TupleDescInitEntryCollation(tupdesc,
1961 : 1148 : (AttrNumber) i,
1962 : : attrcollation);
1963 : 1148 : rtfunc->funccolnames = lappend(rtfunc->funccolnames,
1964 : 1148 : makeString(pstrdup(attrname)));
1965 : 1148 : rtfunc->funccoltypes = lappend_oid(rtfunc->funccoltypes,
1966 : : attrtype);
1967 : 1148 : rtfunc->funccoltypmods = lappend_int(rtfunc->funccoltypmods,
1968 : : attrtypmod);
1969 : 1148 : rtfunc->funccolcollations = lappend_oid(rtfunc->funccolcollations,
1970 : : attrcollation);
1971 : :
1972 : 1148 : i++;
1973 : : }
188 drowley@postgresql.o 1974 : 487 : TupleDescFinalize(tupdesc);
1975 : :
1976 : : /*
1977 : : * Ensure that the coldeflist defines a legal set of names (no
1978 : : * duplicates, but we needn't worry about system column names) and
1979 : : * datatypes. Although we mostly can't allow pseudo-types, it
1980 : : * seems safe to allow RECORD and RECORD[], since values within
1981 : : * those type classes are self-identifying at runtime, and the
1982 : : * coldeflist doesn't represent anything that will be visible to
1983 : : * other sessions.
1984 : : */
2790 tgl@sss.pgh.pa.us 1985 : 487 : CheckAttributeNamesTypes(tupdesc, RELKIND_COMPOSITE_TYPE,
1986 : : CHKATYPE_ANYRECORD);
1987 : : }
1988 : : else
8464 1989 [ + - ]: 4 : ereport(ERROR,
1990 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
1991 : : errmsg("function \"%s\" in FROM has unsupported return type %s",
1992 : : funcname, format_type_be(funcrettype)),
1993 : : parser_errposition(pstate, exprLocation(funcexpr))));
1994 : :
1995 : : /* Finish off the RangeTblFunction and add it to the RTE's list */
4686 1996 : 29791 : rtfunc->funccolcount = tupdesc->natts;
1997 : 29791 : rte->functions = lappend(rte->functions, rtfunc);
1998 : :
1999 : : /* Save the tupdesc for use below */
2000 : 29791 : functupdescs[funcno] = tupdesc;
2001 : 29791 : totalatts += tupdesc->natts;
2002 : 29791 : funcno++;
2003 : : }
2004 : :
2005 : : /*
2006 : : * If there's more than one function, or we want an ordinality column, we
2007 : : * have to produce a merged tupdesc.
2008 : : */
2009 [ + + + + ]: 29579 : if (nfuncs > 1 || rangefunc->ordinality)
2010 : : {
4801 stark@mit.edu 2011 [ + + ]: 601 : if (rangefunc->ordinality)
4686 tgl@sss.pgh.pa.us 2012 : 537 : totalatts++;
2013 : :
2014 : : /* Disallow more columns than will fit in a tuple */
1511 2015 [ - + ]: 601 : if (totalatts > MaxTupleAttributeNumber)
1511 tgl@sss.pgh.pa.us 2016 [ # # ]:UBC 0 : ereport(ERROR,
2017 : : (errcode(ERRCODE_TOO_MANY_COLUMNS),
2018 : : errmsg("functions in FROM can return at most %d columns",
2019 : : MaxTupleAttributeNumber),
2020 : : parser_errposition(pstate,
2021 : : exprLocation((Node *) funcexprs))));
2022 : :
2023 : : /* Merge the tuple descs of each function into a composite one */
2861 andres@anarazel.de 2024 :CBC 601 : tupdesc = CreateTemplateTupleDesc(totalatts);
4686 tgl@sss.pgh.pa.us 2025 : 601 : natts = 0;
2026 [ + + ]: 1414 : for (i = 0; i < nfuncs; i++)
2027 : : {
2028 [ + + ]: 1992 : for (j = 1; j <= functupdescs[i]->natts; j++)
2029 : 1179 : TupleDescCopyEntry(tupdesc, ++natts, functupdescs[i], j);
2030 : : }
2031 : :
2032 : : /* Add the ordinality column if needed */
2033 [ + + ]: 601 : if (rangefunc->ordinality)
2034 : : {
2035 : 537 : TupleDescInitEntry(tupdesc,
2036 : 537 : (AttrNumber) ++natts,
2037 : : "ordinality",
2038 : : INT8OID,
2039 : : -1,
2040 : : 0);
2041 : : /* no need to set collation */
2042 : : }
188 drowley@postgresql.o 2043 : 601 : TupleDescFinalize(tupdesc);
4686 tgl@sss.pgh.pa.us 2044 [ - + ]: 601 : Assert(natts == totalatts);
2045 : : }
2046 : : else
2047 : : {
2048 : : /* We can just use the single function's tupdesc as-is */
2049 : 28978 : tupdesc = functupdescs[0];
2050 : : }
2051 : :
2052 : : /* Use the tupdesc while assigning column aliases for the RTE */
2053 : 29579 : buildRelationAliases(tupdesc, alias, eref);
2054 : :
2055 : : /*
2056 : : * Set flags and access permissions.
2057 : : *
2058 : : * Functions are never checked for access rights (at least, not by
2059 : : * ExecCheckPermissions()), so no need to perform addRTEPermissionInfo().
2060 : : */
5157 2061 : 29579 : rte->lateral = lateral;
8897 2062 : 29579 : rte->inFromCl = inFromCl;
2063 : :
2064 : : /*
2065 : : * Add completed RTE to pstate's range table list, so that we know its
2066 : : * index. But we don't add it to the join list --- caller must do that if
2067 : : * appropriate.
2068 : : */
4211 rhaas@postgresql.org 2069 : 29579 : pstate->p_rtable = lappend(pstate->p_rtable, rte);
2070 : :
2071 : : /*
2072 : : * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
2073 : : * list --- caller must do that if appropriate.
2074 : : */
1384 alvherre@alvh.no-ip. 2075 : 29579 : return buildNSItemFromTupleDesc(rte, list_length(pstate->p_rtable), NULL,
2076 : : tupdesc);
2077 : : }
2078 : :
2079 : : /*
2080 : : * Add an entry for a table function to the pstate's range table (p_rtable).
2081 : : * Then, construct and return a ParseNamespaceItem for the new RTE.
2082 : : *
2083 : : * This is much like addRangeTableEntry() except that it makes a tablefunc RTE.
2084 : : */
2085 : : ParseNamespaceItem *
3483 2086 : 536 : addRangeTableEntryForTableFunc(ParseState *pstate,
2087 : : TableFunc *tf,
2088 : : Alias *alias,
2089 : : bool lateral,
2090 : : bool inFromCl)
2091 : : {
2092 : 536 : RangeTblEntry *rte = makeNode(RangeTblEntry);
2093 : : char *refname;
2094 : : Alias *eref;
2095 : : int numaliases;
2096 : :
1511 tgl@sss.pgh.pa.us 2097 [ - + ]: 536 : Assert(pstate != NULL);
2098 : :
2099 : : /* Disallow more columns than will fit in a tuple */
2100 [ - + ]: 536 : if (list_length(tf->colnames) > MaxTupleAttributeNumber)
1511 tgl@sss.pgh.pa.us 2101 [ # # ]:UBC 0 : ereport(ERROR,
2102 : : (errcode(ERRCODE_TOO_MANY_COLUMNS),
2103 : : errmsg("functions in FROM can return at most %d columns",
2104 : : MaxTupleAttributeNumber),
2105 : : parser_errposition(pstate,
2106 : : exprLocation((Node *) tf))));
1511 tgl@sss.pgh.pa.us 2107 [ - + ]:CBC 536 : Assert(list_length(tf->coltypes) == list_length(tf->colnames));
2108 [ - + ]: 536 : Assert(list_length(tf->coltypmods) == list_length(tf->colnames));
2109 [ - + ]: 536 : Assert(list_length(tf->colcollations) == list_length(tf->colnames));
2110 : :
3483 alvherre@alvh.no-ip. 2111 : 536 : rte->rtekind = RTE_TABLEFUNC;
2112 : 536 : rte->relid = InvalidOid;
2113 : 536 : rte->subquery = NULL;
2114 : 536 : rte->tablefunc = tf;
2115 : 536 : rte->coltypes = tf->coltypes;
2116 : 536 : rte->coltypmods = tf->coltypmods;
2117 : 536 : rte->colcollations = tf->colcollations;
2118 : 536 : rte->alias = alias;
2119 : :
899 amitlan@postgresql.o 2120 [ + + ]: 536 : refname = alias ? alias->aliasname :
2121 [ + + ]: 326 : pstrdup(tf->functype == TFT_XMLTABLE ? "xmltable" : "json_table");
3483 alvherre@alvh.no-ip. 2122 [ + + ]: 536 : eref = alias ? copyObject(alias) : makeAlias(refname, NIL);
2123 : 536 : numaliases = list_length(eref->colnames);
2124 : :
2125 : : /* fill in any unspecified alias columns */
2126 [ + + ]: 536 : if (numaliases < list_length(tf->colnames))
2127 : 526 : eref->colnames = list_concat(eref->colnames,
3378 tgl@sss.pgh.pa.us 2128 : 526 : list_copy_tail(tf->colnames, numaliases));
2129 : :
1586 alvherre@alvh.no-ip. 2130 [ + + ]: 536 : if (numaliases > list_length(tf->colnames))
2131 [ + - + + ]: 8 : ereport(ERROR,
2132 : : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2133 : : errmsg("%s function has %d columns available but %d columns specified",
2134 : : tf->functype == TFT_XMLTABLE ? "XMLTABLE" : "JSON_TABLE",
2135 : : list_length(tf->colnames), numaliases)));
2136 : :
3483 2137 : 528 : rte->eref = eref;
2138 : :
2139 : : /*
2140 : : * Set flags and access permissions.
2141 : : *
2142 : : * Tablefuncs are never checked for access rights (at least, not by
2143 : : * ExecCheckPermissions()), so no need to perform addRTEPermissionInfo().
2144 : : */
2145 : 528 : rte->lateral = lateral;
2146 : 528 : rte->inFromCl = inFromCl;
2147 : :
2148 : : /*
2149 : : * Add completed RTE to pstate's range table list, so that we know its
2150 : : * index. But we don't add it to the join list --- caller must do that if
2151 : : * appropriate.
2152 : : */
2153 : 528 : pstate->p_rtable = lappend(pstate->p_rtable, rte);
2154 : :
2155 : : /*
2156 : : * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
2157 : : * list --- caller must do that if appropriate.
2158 : : */
2453 tgl@sss.pgh.pa.us 2159 : 528 : return buildNSItemFromLists(rte, list_length(pstate->p_rtable),
2160 : : rte->coltypes, rte->coltypmods,
2161 : : rte->colcollations);
2162 : : }
2163 : :
2164 : : /*
2165 : : * Add an entry for a VALUES list to the pstate's range table (p_rtable).
2166 : : * Then, construct and return a ParseNamespaceItem for the new RTE.
2167 : : *
2168 : : * This is much like addRangeTableEntry() except that it makes a values RTE.
2169 : : */
2170 : : ParseNamespaceItem *
7354 mail@joeconway.com 2171 : 8999 : addRangeTableEntryForValues(ParseState *pstate,
2172 : : List *exprs,
2173 : : List *coltypes,
2174 : : List *coltypmods,
2175 : : List *colcollations,
2176 : : Alias *alias,
2177 : : bool lateral,
2178 : : bool inFromCl)
2179 : : {
2180 : 8999 : RangeTblEntry *rte = makeNode(RangeTblEntry);
2181 [ - + ]: 8999 : char *refname = alias ? alias->aliasname : pstrdup("*VALUES*");
2182 : : Alias *eref;
2183 : : int numaliases;
2184 : : int numcolumns;
2185 : :
4211 rhaas@postgresql.org 2186 [ - + ]: 8999 : Assert(pstate != NULL);
2187 : :
7354 mail@joeconway.com 2188 : 8999 : rte->rtekind = RTE_VALUES;
2189 : 8999 : rte->relid = InvalidOid;
2190 : 8999 : rte->subquery = NULL;
2191 : 8999 : rte->values_lists = exprs;
3573 tgl@sss.pgh.pa.us 2192 : 8999 : rte->coltypes = coltypes;
2193 : 8999 : rte->coltypmods = coltypmods;
2194 : 8999 : rte->colcollations = colcollations;
7354 mail@joeconway.com 2195 : 8999 : rte->alias = alias;
2196 : :
2197 [ - + ]: 8999 : eref = alias ? copyObject(alias) : makeAlias(refname, NIL);
2198 : :
2199 : : /* fill in any unspecified alias columns */
2200 : 8999 : numcolumns = list_length((List *) linitial(exprs));
2201 : 8999 : numaliases = list_length(eref->colnames);
2202 [ + + ]: 22338 : while (numaliases < numcolumns)
2203 : : {
2204 : : char attrname[64];
2205 : :
2206 : 13339 : numaliases++;
2207 : 13339 : snprintf(attrname, sizeof(attrname), "column%d", numaliases);
2208 : 13339 : eref->colnames = lappend(eref->colnames,
2209 : 13339 : makeString(pstrdup(attrname)));
2210 : : }
2211 [ - + ]: 8999 : if (numcolumns < numaliases)
7354 mail@joeconway.com 2212 [ # # ]:UBC 0 : ereport(ERROR,
2213 : : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2214 : : errmsg("VALUES lists \"%s\" have %d columns available but %d columns specified",
2215 : : refname, numcolumns, numaliases)));
2216 : :
7354 mail@joeconway.com 2217 :CBC 8999 : rte->eref = eref;
2218 : :
2219 : : /*
2220 : : * Set flags and access permissions.
2221 : : *
2222 : : * Subqueries are never checked for access rights, so no need to perform
2223 : : * addRTEPermissionInfo().
2224 : : */
5145 tgl@sss.pgh.pa.us 2225 : 8999 : rte->lateral = lateral;
7354 mail@joeconway.com 2226 : 8999 : rte->inFromCl = inFromCl;
2227 : :
2228 : : /*
2229 : : * Add completed RTE to pstate's range table list, so that we know its
2230 : : * index. But we don't add it to the join list --- caller must do that if
2231 : : * appropriate.
2232 : : */
4211 rhaas@postgresql.org 2233 : 8999 : pstate->p_rtable = lappend(pstate->p_rtable, rte);
2234 : :
2235 : : /*
2236 : : * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
2237 : : * list --- caller must do that if appropriate.
2238 : : */
2453 tgl@sss.pgh.pa.us 2239 : 8999 : return buildNSItemFromLists(rte, list_length(pstate->p_rtable),
2240 : : rte->coltypes, rte->coltypmods,
2241 : : rte->colcollations);
2242 : : }
2243 : :
2244 : : /*
2245 : : * Add an entry for a join to the pstate's range table (p_rtable).
2246 : : * Then, construct and return a ParseNamespaceItem for the new RTE.
2247 : : *
2248 : : * This is much like addRangeTableEntry() except that it makes a join RTE.
2249 : : * Also, it's more convenient for the caller to construct the
2250 : : * ParseNamespaceColumn array, so we pass that in.
2251 : : */
2252 : : ParseNamespaceItem *
8958 2253 : 63005 : addRangeTableEntryForJoin(ParseState *pstate,
2254 : : List *colnames,
2255 : : ParseNamespaceColumn *nscolumns,
2256 : : JoinType jointype,
2257 : : int nummergedcols,
2258 : : List *aliasvars,
2259 : : List *leftcols,
2260 : : List *rightcols,
2261 : : Alias *join_using_alias,
2262 : : Alias *alias,
2263 : : bool inFromCl)
2264 : : {
2265 : 63005 : RangeTblEntry *rte = makeNode(RangeTblEntry);
2266 : : Alias *eref;
2267 : : int numaliases;
2268 : : ParseNamespaceItem *nsitem;
2269 : :
4211 rhaas@postgresql.org 2270 [ - + ]: 63005 : Assert(pstate != NULL);
2271 : :
2272 : : /*
2273 : : * Fail if join has too many columns --- we must be able to reference any
2274 : : * of the columns with an AttrNumber.
2275 : : */
6742 tgl@sss.pgh.pa.us 2276 [ - + ]: 63005 : if (list_length(aliasvars) > MaxAttrNumber)
6742 tgl@sss.pgh.pa.us 2277 [ # # ]:UBC 0 : ereport(ERROR,
2278 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
2279 : : errmsg("joins can have at most %d columns",
2280 : : MaxAttrNumber)));
2281 : :
8958 tgl@sss.pgh.pa.us 2282 :CBC 63005 : rte->rtekind = RTE_JOIN;
2283 : 63005 : rte->relid = InvalidOid;
2284 : 63005 : rte->subquery = NULL;
2285 : 63005 : rte->jointype = jointype;
2446 2286 : 63005 : rte->joinmergedcols = nummergedcols;
8911 2287 : 63005 : rte->joinaliasvars = aliasvars;
2446 2288 : 63005 : rte->joinleftcols = leftcols;
2289 : 63005 : rte->joinrightcols = rightcols;
1999 peter@eisentraut.org 2290 : 63005 : rte->join_using_alias = join_using_alias;
8958 tgl@sss.pgh.pa.us 2291 : 63005 : rte->alias = alias;
2292 : :
3482 peter_e@gmx.net 2293 [ + + ]: 63005 : eref = alias ? copyObject(alias) : makeAlias("unnamed_join", NIL);
8148 neilc@samurai.com 2294 : 63005 : numaliases = list_length(eref->colnames);
2295 : :
2296 : : /* fill in any unspecified alias columns */
2297 [ + + ]: 63005 : if (numaliases < list_length(colnames))
2298 : 62903 : eref->colnames = list_concat(eref->colnames,
7645 bruce@momjian.us 2299 : 62903 : list_copy_tail(colnames, numaliases));
2300 : :
1586 alvherre@alvh.no-ip. 2301 [ + + ]: 63005 : if (numaliases > list_length(colnames))
2302 [ + - ]: 4 : ereport(ERROR,
2303 : : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2304 : : errmsg("join expression \"%s\" has %d columns available but %d columns specified",
2305 : : eref->aliasname, list_length(colnames), numaliases)));
2306 : :
8958 tgl@sss.pgh.pa.us 2307 : 63001 : rte->eref = eref;
2308 : :
2309 : : /*
2310 : : * Set flags and access permissions.
2311 : : *
2312 : : * Joins are never checked for access rights, so no need to perform
2313 : : * addRTEPermissionInfo().
2314 : : */
5157 2315 : 63001 : rte->lateral = false;
8958 2316 : 63001 : rte->inFromCl = inFromCl;
2317 : :
2318 : : /*
2319 : : * Add completed RTE to pstate's range table list, so that we know its
2320 : : * index. But we don't add it to the join list --- caller must do that if
2321 : : * appropriate.
2322 : : */
4211 rhaas@postgresql.org 2323 : 63001 : pstate->p_rtable = lappend(pstate->p_rtable, rte);
2324 : :
2325 : : /*
2326 : : * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
2327 : : * list --- caller must do that if appropriate.
2328 : : */
284 michael@paquier.xyz 2329 : 63001 : nsitem = palloc_object(ParseNamespaceItem);
1999 peter@eisentraut.org 2330 : 63001 : nsitem->p_names = rte->eref;
2453 tgl@sss.pgh.pa.us 2331 : 63001 : nsitem->p_rte = rte;
1384 alvherre@alvh.no-ip. 2332 : 63001 : nsitem->p_perminfo = NULL;
2453 tgl@sss.pgh.pa.us 2333 : 63001 : nsitem->p_rtindex = list_length(pstate->p_rtable);
2334 : 63001 : nsitem->p_nscolumns = nscolumns;
2335 : : /* set default visibility flags; might get changed later */
2336 : 63001 : nsitem->p_rel_visible = true;
2337 : 63001 : nsitem->p_cols_visible = true;
2338 : 63001 : nsitem->p_lateral_only = false;
2339 : 63001 : nsitem->p_lateral_ok = true;
612 dean.a.rasheed@gmail 2340 : 63001 : nsitem->p_returning_type = VAR_RETURNING_DEFAULT;
2341 : :
2453 tgl@sss.pgh.pa.us 2342 : 63001 : return nsitem;
2343 : : }
2344 : :
2345 : : /*
2346 : : * Add an entry for a CTE reference to the pstate's range table (p_rtable).
2347 : : * Then, construct and return a ParseNamespaceItem for the new RTE.
2348 : : *
2349 : : * This is much like addRangeTableEntry() except that it makes a CTE RTE.
2350 : : */
2351 : : ParseNamespaceItem *
6560 2352 : 4463 : addRangeTableEntryForCTE(ParseState *pstate,
2353 : : CommonTableExpr *cte,
2354 : : Index levelsup,
2355 : : RangeVar *rv,
2356 : : bool inFromCl)
2357 : : {
2358 : 4463 : RangeTblEntry *rte = makeNode(RangeTblEntry);
5686 2359 : 4463 : Alias *alias = rv->alias;
6560 2360 [ + + ]: 4463 : char *refname = alias ? alias->aliasname : cte->ctename;
2361 : : Alias *eref;
2362 : : int numaliases;
2363 : : int varattno;
2364 : : ListCell *lc;
2057 peter@eisentraut.org 2365 : 4463 : int n_dontexpand_columns = 0;
2366 : : ParseNamespaceItem *psi;
2367 : :
4211 rhaas@postgresql.org 2368 [ - + ]: 4463 : Assert(pstate != NULL);
2369 : :
6560 tgl@sss.pgh.pa.us 2370 : 4463 : rte->rtekind = RTE_CTE;
2371 : 4463 : rte->ctename = cte->ctename;
2372 : 4463 : rte->ctelevelsup = levelsup;
2373 : :
2374 : : /* Self-reference if and only if CTE's parse analysis isn't completed */
2375 : 4463 : rte->self_reference = !IsA(cte->ctequery, Query);
2376 [ + + - + ]: 4463 : Assert(cte->cterecursive || !rte->self_reference);
2377 : : /* Bump the CTE's refcount if this isn't a self-reference */
2378 [ + + ]: 4463 : if (!rte->self_reference)
2379 : 3809 : cte->cterefcount++;
2380 : :
2381 : : /*
2382 : : * We throw error if the CTE is INSERT/UPDATE/DELETE/MERGE without
2383 : : * RETURNING. This won't get checked in case of a self-reference, but
2384 : : * that's OK because data-modifying CTEs aren't allowed to be recursive
2385 : : * anyhow.
2386 : : */
5686 2387 [ + + ]: 4463 : if (IsA(cte->ctequery, Query))
2388 : : {
5642 bruce@momjian.us 2389 : 3809 : Query *ctequery = (Query *) cte->ctequery;
2390 : :
5686 tgl@sss.pgh.pa.us 2391 [ + + ]: 3809 : if (ctequery->commandType != CMD_SELECT &&
2392 [ + + ]: 201 : ctequery->returningList == NIL)
2393 [ + - ]: 8 : ereport(ERROR,
2394 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2395 : : errmsg("WITH query \"%s\" does not have a RETURNING clause",
2396 : : cte->ctename),
2397 : : parser_errposition(pstate, rv->location)));
2398 : : }
2399 : :
2057 peter@eisentraut.org 2400 : 4455 : rte->coltypes = list_copy(cte->ctecoltypes);
2401 : 4455 : rte->coltypmods = list_copy(cte->ctecoltypmods);
2402 : 4455 : rte->colcollations = list_copy(cte->ctecolcollations);
2403 : :
6560 tgl@sss.pgh.pa.us 2404 : 4455 : rte->alias = alias;
2405 [ + + ]: 4455 : if (alias)
2406 : 668 : eref = copyObject(alias);
2407 : : else
2408 : 3787 : eref = makeAlias(refname, NIL);
2409 : 4455 : numaliases = list_length(eref->colnames);
2410 : :
2411 : : /* fill in any unspecified alias columns */
2412 : 4455 : varattno = 0;
2413 [ + - + + : 15771 : foreach(lc, cte->ctecolnames)
+ + ]
2414 : : {
2415 : 11316 : varattno++;
2416 [ + + ]: 11316 : if (varattno > numaliases)
2417 : 11284 : eref->colnames = lappend(eref->colnames, lfirst(lc));
2418 : : }
2419 [ - + ]: 4455 : if (varattno < numaliases)
6560 tgl@sss.pgh.pa.us 2420 [ # # ]:UBC 0 : ereport(ERROR,
2421 : : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2422 : : errmsg("table \"%s\" has %d columns available but %d columns specified",
2423 : : refname, varattno, numaliases)));
2424 : :
6560 tgl@sss.pgh.pa.us 2425 :CBC 4455 : rte->eref = eref;
2426 : :
2057 peter@eisentraut.org 2427 [ + + ]: 4455 : if (cte->search_clause)
2428 : : {
2429 : 140 : rte->eref->colnames = lappend(rte->eref->colnames, makeString(cte->search_clause->search_seq_column));
2430 [ + + ]: 140 : if (cte->search_clause->search_breadth_first)
2431 : 48 : rte->coltypes = lappend_oid(rte->coltypes, RECORDOID);
2432 : : else
2433 : 92 : rte->coltypes = lappend_oid(rte->coltypes, RECORDARRAYOID);
2434 : 140 : rte->coltypmods = lappend_int(rte->coltypmods, -1);
2435 : 140 : rte->colcollations = lappend_oid(rte->colcollations, InvalidOid);
2436 : :
2437 : 140 : n_dontexpand_columns += 1;
2438 : : }
2439 : :
2440 [ + + ]: 4455 : if (cte->cycle_clause)
2441 : : {
2442 : 124 : rte->eref->colnames = lappend(rte->eref->colnames, makeString(cte->cycle_clause->cycle_mark_column));
2443 : 124 : rte->coltypes = lappend_oid(rte->coltypes, cte->cycle_clause->cycle_mark_type);
2444 : 124 : rte->coltypmods = lappend_int(rte->coltypmods, cte->cycle_clause->cycle_mark_typmod);
2445 : 124 : rte->colcollations = lappend_oid(rte->colcollations, cte->cycle_clause->cycle_mark_collation);
2446 : :
2447 : 124 : rte->eref->colnames = lappend(rte->eref->colnames, makeString(cte->cycle_clause->cycle_path_column));
2448 : 124 : rte->coltypes = lappend_oid(rte->coltypes, RECORDARRAYOID);
2449 : 124 : rte->coltypmods = lappend_int(rte->coltypmods, -1);
2450 : 124 : rte->colcollations = lappend_oid(rte->colcollations, InvalidOid);
2451 : :
2452 : 124 : n_dontexpand_columns += 2;
2453 : : }
2454 : :
2455 : : /*
2456 : : * Set flags and access permissions.
2457 : : *
2458 : : * Subqueries are never checked for access rights, so no need to perform
2459 : : * addRTEPermissionInfo().
2460 : : */
5157 tgl@sss.pgh.pa.us 2461 : 4455 : rte->lateral = false;
6560 2462 : 4455 : rte->inFromCl = inFromCl;
2463 : :
2464 : : /*
2465 : : * Add completed RTE to pstate's range table list, so that we know its
2466 : : * index. But we don't add it to the join list --- caller must do that if
2467 : : * appropriate.
2468 : : */
4211 rhaas@postgresql.org 2469 : 4455 : pstate->p_rtable = lappend(pstate->p_rtable, rte);
2470 : :
2471 : : /*
2472 : : * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
2473 : : * list --- caller must do that if appropriate.
2474 : : */
2057 peter@eisentraut.org 2475 : 4455 : psi = buildNSItemFromLists(rte, list_length(pstate->p_rtable),
2476 : : rte->coltypes, rte->coltypmods,
2477 : : rte->colcollations);
2478 : :
2479 : : /*
2480 : : * The columns added by search and cycle clauses are not included in star
2481 : : * expansion in queries contained in the CTE.
2482 : : */
2483 [ + + ]: 4455 : if (rte->ctelevelsup > 0)
2484 [ + + ]: 3422 : for (int i = 0; i < n_dontexpand_columns; i++)
1999 2485 : 236 : psi->p_nscolumns[list_length(psi->p_names->colnames) - 1 - i].p_dontexpand = true;
2486 : :
2057 2487 : 4455 : return psi;
2488 : : }
2489 : :
2490 : : /*
2491 : : * Add an entry for an ephemeral named relation reference to the pstate's
2492 : : * range table (p_rtable).
2493 : : * Then, construct and return a ParseNamespaceItem for the new RTE.
2494 : : *
2495 : : * It is expected that the RangeVar, which up until now is only known to be an
2496 : : * ephemeral named relation, will (in conjunction with the QueryEnvironment in
2497 : : * the ParseState), create a RangeTblEntry for a specific *kind* of ephemeral
2498 : : * named relation, based on enrtype.
2499 : : *
2500 : : * This is much like addRangeTableEntry() except that it makes an RTE for an
2501 : : * ephemeral named relation.
2502 : : */
2503 : : ParseNamespaceItem *
3460 kgrittn@postgresql.o 2504 : 324 : addRangeTableEntryForENR(ParseState *pstate,
2505 : : RangeVar *rv,
2506 : : bool inFromCl)
2507 : : {
2508 : 324 : RangeTblEntry *rte = makeNode(RangeTblEntry);
2509 : 324 : Alias *alias = rv->alias;
2510 [ + + ]: 324 : char *refname = alias ? alias->aliasname : rv->relname;
2511 : : EphemeralNamedRelationMetadata enrmd;
2512 : : TupleDesc tupdesc;
2513 : : int attno;
2514 : :
3444 tgl@sss.pgh.pa.us 2515 [ - + ]: 324 : Assert(pstate != NULL);
2516 : 324 : enrmd = get_visible_ENR(pstate, rv->relname);
3460 kgrittn@postgresql.o 2517 [ - + ]: 324 : Assert(enrmd != NULL);
2518 : :
2519 [ + - ]: 324 : switch (enrmd->enrtype)
2520 : : {
2521 : 324 : case ENR_NAMED_TUPLESTORE:
2522 : 324 : rte->rtekind = RTE_NAMEDTUPLESTORE;
2523 : 324 : break;
2524 : :
3460 kgrittn@postgresql.o 2525 :UBC 0 : default:
3444 tgl@sss.pgh.pa.us 2526 [ # # ]: 0 : elog(ERROR, "unexpected enrtype: %d", enrmd->enrtype);
2527 : : return NULL; /* for fussy compilers */
2528 : : }
2529 : :
2530 : : /*
2531 : : * Record dependency on a relation. This allows plans to be invalidated
2532 : : * if they access transition tables linked to a table that is altered.
2533 : : */
3460 kgrittn@postgresql.o 2534 :CBC 324 : rte->relid = enrmd->reliddesc;
2535 : :
2536 : : /*
2537 : : * Build the list of effective column names using user-supplied aliases
2538 : : * and/or actual column names.
2539 : : */
2540 : 324 : tupdesc = ENRMetadataGetTupDesc(enrmd);
2541 : 324 : rte->eref = makeAlias(refname, NIL);
2542 : 324 : buildRelationAliases(tupdesc, alias, rte->eref);
2543 : :
2544 : : /* Record additional data for ENR, including column type info */
2545 : 324 : rte->enrname = enrmd->name;
2546 : 324 : rte->enrtuples = enrmd->enrtuples;
2547 : 324 : rte->coltypes = NIL;
2548 : 324 : rte->coltypmods = NIL;
2549 : 324 : rte->colcollations = NIL;
2550 [ + + ]: 1042 : for (attno = 1; attno <= tupdesc->natts; ++attno)
2551 : : {
3318 andres@anarazel.de 2552 : 718 : Form_pg_attribute att = TupleDescAttr(tupdesc, attno - 1);
2553 : :
3301 tgl@sss.pgh.pa.us 2554 [ + + ]: 718 : if (att->attisdropped)
2555 : : {
2556 : : /* Record zeroes for a dropped column */
2557 : 12 : rte->coltypes = lappend_oid(rte->coltypes, InvalidOid);
2558 : 12 : rte->coltypmods = lappend_int(rte->coltypmods, 0);
2559 : 12 : rte->colcollations = lappend_oid(rte->colcollations, InvalidOid);
2560 : : }
2561 : : else
2562 : : {
2563 : : /* Let's just make sure we can tell this isn't dropped */
2564 [ - + ]: 706 : if (att->atttypid == InvalidOid)
3301 tgl@sss.pgh.pa.us 2565 [ # # ]:UBC 0 : elog(ERROR, "atttypid is invalid for non-dropped column in \"%s\"",
2566 : : rv->relname);
3301 tgl@sss.pgh.pa.us 2567 :CBC 706 : rte->coltypes = lappend_oid(rte->coltypes, att->atttypid);
2568 : 706 : rte->coltypmods = lappend_int(rte->coltypmods, att->atttypmod);
2569 : 706 : rte->colcollations = lappend_oid(rte->colcollations,
2570 : : att->attcollation);
2571 : : }
2572 : : }
2573 : :
2574 : : /*
2575 : : * Set flags and access permissions.
2576 : : *
2577 : : * ENRs are never checked for access rights, so no need to perform
2578 : : * addRTEPermissionInfo().
2579 : : */
3460 kgrittn@postgresql.o 2580 : 324 : rte->lateral = false;
2581 : 324 : rte->inFromCl = inFromCl;
2582 : :
2583 : : /*
2584 : : * Add completed RTE to pstate's range table list, so that we know its
2585 : : * index. But we don't add it to the join list --- caller must do that if
2586 : : * appropriate.
2587 : : */
3444 tgl@sss.pgh.pa.us 2588 : 324 : pstate->p_rtable = lappend(pstate->p_rtable, rte);
2589 : :
2590 : : /*
2591 : : * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
2592 : : * list --- caller must do that if appropriate.
2593 : : */
1384 alvherre@alvh.no-ip. 2594 : 324 : return buildNSItemFromTupleDesc(rte, list_length(pstate->p_rtable), NULL,
2595 : : tupdesc);
2596 : : }
2597 : :
2598 : : /*
2599 : : * Add an entry for grouping step to the pstate's range table (p_rtable).
2600 : : * Then, construct and return a ParseNamespaceItem for the new RTE.
2601 : : */
2602 : : ParseNamespaceItem *
740 rguo@postgresql.org 2603 : 3508 : addRangeTableEntryForGroup(ParseState *pstate,
2604 : : List *groupClauses)
2605 : : {
2606 : 3508 : RangeTblEntry *rte = makeNode(RangeTblEntry);
2607 : : Alias *eref;
2608 : : List *groupexprs;
2609 : : List *coltypes,
2610 : : *coltypmods,
2611 : : *colcollations;
2612 : : ListCell *lc;
2613 : : ParseNamespaceItem *nsitem;
2614 : :
2615 [ - + ]: 3508 : Assert(pstate != NULL);
2616 : :
2617 : 3508 : rte->rtekind = RTE_GROUP;
2618 : 3508 : rte->alias = NULL;
2619 : :
2620 : 3508 : eref = makeAlias("*GROUP*", NIL);
2621 : :
2622 : : /* fill in any unspecified alias columns, and extract column type info */
2623 : 3508 : groupexprs = NIL;
2624 : 3508 : coltypes = coltypmods = colcollations = NIL;
2625 [ + - + + : 9306 : foreach(lc, groupClauses)
+ + ]
2626 : : {
2627 : 5798 : TargetEntry *te = (TargetEntry *) lfirst(lc);
2628 [ + + ]: 5798 : char *colname = te->resname ? pstrdup(te->resname) : "?column?";
2629 : :
2630 : 5798 : eref->colnames = lappend(eref->colnames, makeString(colname));
2631 : :
2632 : 5798 : groupexprs = lappend(groupexprs, copyObject(te->expr));
2633 : :
2634 : 5798 : coltypes = lappend_oid(coltypes,
2635 : 5798 : exprType((Node *) te->expr));
2636 : 5798 : coltypmods = lappend_int(coltypmods,
2637 : 5798 : exprTypmod((Node *) te->expr));
2638 : 5798 : colcollations = lappend_oid(colcollations,
2639 : 5798 : exprCollation((Node *) te->expr));
2640 : : }
2641 : :
2642 : 3508 : rte->eref = eref;
2643 : 3508 : rte->groupexprs = groupexprs;
2644 : :
2645 : : /*
2646 : : * Set flags.
2647 : : *
2648 : : * The grouping step is never checked for access rights, so no need to
2649 : : * perform addRTEPermissionInfo().
2650 : : */
2651 : 3508 : rte->lateral = false;
2652 : 3508 : rte->inFromCl = false;
2653 : :
2654 : : /*
2655 : : * Add completed RTE to pstate's range table list, so that we know its
2656 : : * index. But we don't add it to the join list --- caller must do that if
2657 : : * appropriate.
2658 : : */
2659 : 3508 : pstate->p_rtable = lappend(pstate->p_rtable, rte);
2660 : :
2661 : : /*
2662 : : * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
2663 : : * list --- caller must do that if appropriate.
2664 : : */
2665 : 3508 : nsitem = buildNSItemFromLists(rte, list_length(pstate->p_rtable),
2666 : : coltypes, coltypmods, colcollations);
2667 : :
2668 : 3508 : return nsitem;
2669 : : }
2670 : :
2671 : :
2672 : : /*
2673 : : * Has the specified refname been selected FOR UPDATE/FOR SHARE?
2674 : : *
2675 : : * This is used when we have not yet done transformLockingClause, but need
2676 : : * to know the correct lock to take during initial opening of relations.
2677 : : *
2678 : : * Note that refname may be NULL (for a subquery without an alias), in which
2679 : : * case the relation can't be locked by name, but it might still be locked if
2680 : : * a locking clause requests that all tables be locked.
2681 : : *
2682 : : * Note: we pay no attention to whether it's FOR UPDATE vs FOR SHARE,
2683 : : * since the table-level lock is the same either way.
2684 : : */
2685 : : bool
6172 tgl@sss.pgh.pa.us 2686 : 266035 : isLockedRefname(ParseState *pstate, const char *refname)
2687 : : {
2688 : : ListCell *l;
2689 : :
2690 : : /*
2691 : : * If we are in a subquery specified as locked FOR UPDATE/SHARE from
2692 : : * parent level, then act as though there's a generic FOR UPDATE here.
2693 : : */
2694 [ + + ]: 266035 : if (pstate->p_locked_from_parent)
2695 : 2 : return true;
2696 : :
2697 [ + + + + : 266264 : foreach(l, pstate->p_locking_clause)
+ + ]
2698 : : {
2699 : 5208 : LockingClause *lc = (LockingClause *) lfirst(l);
2700 : :
2701 [ + + ]: 5208 : if (lc->lockedRels == NIL)
2702 : : {
2703 : : /* all tables used in query */
2704 : 4977 : return true;
2705 : : }
1523 dean.a.rasheed@gmail 2706 [ + + ]: 1436 : else if (refname != NULL)
2707 : : {
2708 : : /* just the named tables */
2709 : : ListCell *l2;
2710 : :
6172 tgl@sss.pgh.pa.us 2711 [ + - + + : 1671 : foreach(l2, lc->lockedRels)
+ + ]
2712 : : {
2713 : 1444 : RangeVar *thisrel = (RangeVar *) lfirst(l2);
2714 : :
2715 [ + + ]: 1444 : if (strcmp(refname, thisrel->relname) == 0)
2716 : 1205 : return true;
2717 : : }
2718 : : }
2719 : : }
9447 2720 : 261056 : return false;
2721 : : }
2722 : :
2723 : : /*
2724 : : * Add the given nsitem/RTE as a top-level entry in the pstate's join list
2725 : : * and/or namespace list. (We assume caller has checked for any
2726 : : * namespace conflicts.) The nsitem is always marked as unconditionally
2727 : : * visible, that is, not LATERAL-only.
2728 : : */
2729 : : void
2453 2730 : 99155 : addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem,
2731 : : bool addToJoinList,
2732 : : bool addToRelNameSpace, bool addToVarNameSpace)
2733 : : {
9349 2734 [ + + ]: 99155 : if (addToJoinList)
2735 : : {
7777 2736 : 39198 : RangeTblRef *rtr = makeNode(RangeTblRef);
2737 : :
2453 2738 : 39198 : rtr->rtindex = nsitem->p_rtindex;
9349 2739 : 39198 : pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
2740 : : }
5157 2741 [ + + + + ]: 99155 : if (addToRelNameSpace || addToVarNameSpace)
2742 : : {
2743 : : /* Set the new nsitem's visibility flags correctly */
5156 2744 : 91429 : nsitem->p_rel_visible = addToRelNameSpace;
2745 : 91429 : nsitem->p_cols_visible = addToVarNameSpace;
5157 2746 : 91429 : nsitem->p_lateral_only = false;
2747 : 91429 : nsitem->p_lateral_ok = true;
5156 2748 : 91429 : pstate->p_namespace = lappend(pstate->p_namespace, nsitem);
2749 : : }
9504 2750 : 99155 : }
2751 : :
2752 : : /*
2753 : : * expandRTE -- expand the columns of a rangetable entry
2754 : : *
2755 : : * This creates lists of an RTE's column names (aliases if provided, else
2756 : : * real names) and Vars for each column. Only user columns are considered.
2757 : : * If include_dropped is false then dropped columns are omitted from the
2758 : : * results. If include_dropped is true then empty strings and NULL constants
2759 : : * (not Vars!) are returned for dropped columns.
2760 : : *
2761 : : * rtindex, sublevels_up, returning_type, and location are the varno,
2762 : : * varlevelsup, varreturningtype, and location values to use in the created
2763 : : * Vars. Ordinarily rtindex should match the actual position of the RTE in
2764 : : * its rangetable.
2765 : : *
2766 : : * The output lists go into *colnames and *colvars.
2767 : : * If only one of the two kinds of output list is needed, pass NULL for the
2768 : : * output pointer for the unwanted one.
2769 : : */
2770 : : void
7778 2771 : 16513 : expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up,
2772 : : VarReturningType returning_type,
2773 : : int location, bool include_dropped,
2774 : : List **colnames, List **colvars)
2775 : : {
2776 : : int varattno;
2777 : :
9504 2778 [ + + ]: 16513 : if (colnames)
2779 : 1194 : *colnames = NIL;
2780 [ + + ]: 16513 : if (colvars)
2781 : 15953 : *colvars = NIL;
2782 : :
8897 2783 [ + + + + : 16513 : switch (rte->rtekind)
+ - - ]
2784 : : {
2785 : 141 : case RTE_RELATION:
2786 : : /* Ordinary relation RTE */
6593 2787 : 141 : expandRelation(rte->relid, rte->eref,
2788 : : rtindex, sublevels_up, returning_type, location,
2789 : : include_dropped, colnames, colvars);
8897 2790 : 141 : break;
2791 : 493 : case RTE_SUBQUERY:
2792 : : {
2793 : : /* Subquery RTE */
8057 bruce@momjian.us 2794 : 493 : ListCell *aliasp_item = list_head(rte->eref->colnames);
2795 : : ListCell *tlistitem;
2796 : :
8897 tgl@sss.pgh.pa.us 2797 : 493 : varattno = 0;
2798 [ + - + + : 1753 : foreach(tlistitem, rte->subquery->targetList)
+ + ]
2799 : : {
2800 : 1260 : TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
2801 : :
7837 2802 [ - + ]: 1260 : if (te->resjunk)
8897 tgl@sss.pgh.pa.us 2803 :UBC 0 : continue;
8897 tgl@sss.pgh.pa.us 2804 :CBC 1260 : varattno++;
7837 2805 [ - + ]: 1260 : Assert(varattno == te->resno);
2806 : :
2807 : : /*
2808 : : * Formerly it was possible for the subquery tlist to have
2809 : : * more non-junk entries than the colnames list does (if
2810 : : * this RTE has been expanded from a view that has more
2811 : : * columns than it did when the current query was parsed).
2812 : : * Now that ApplyRetrieveRule cleans up such cases, we
2813 : : * shouldn't see that anymore, but let's just check.
2814 : : */
3250 2815 [ - + ]: 1260 : if (!aliasp_item)
1293 tgl@sss.pgh.pa.us 2816 [ # # ]:UBC 0 : elog(ERROR, "too few column names for subquery %s",
2817 : : rte->eref->aliasname);
2818 : :
8897 tgl@sss.pgh.pa.us 2819 [ + - ]:CBC 1260 : if (colnames)
2820 : : {
8152 neilc@samurai.com 2821 : 1260 : char *label = strVal(lfirst(aliasp_item));
2822 : :
8897 tgl@sss.pgh.pa.us 2823 : 1260 : *colnames = lappend(*colnames, makeString(pstrdup(label)));
2824 : : }
2825 : :
2826 [ + - ]: 1260 : if (colvars)
2827 : : {
2828 : : Var *varnode;
2829 : :
2830 : 1260 : varnode = makeVar(rtindex, varattno,
7837 2831 : 1260 : exprType((Node *) te->expr),
2832 : 1260 : exprTypmod((Node *) te->expr),
5703 peter_e@gmx.net 2833 : 1260 : exprCollation((Node *) te->expr),
2834 : : sublevels_up);
612 dean.a.rasheed@gmail 2835 : 1260 : varnode->varreturningtype = returning_type;
6593 tgl@sss.pgh.pa.us 2836 : 1260 : varnode->location = location;
2837 : :
8897 2838 : 1260 : *colvars = lappend(*colvars, varnode);
2839 : : }
2840 : :
2624 2841 : 1260 : aliasp_item = lnext(rte->eref->colnames, aliasp_item);
2842 : : }
2843 : : }
8897 2844 : 493 : break;
2845 : 13808 : case RTE_FUNCTION:
2846 : : {
2847 : : /* Function RTE */
4686 2848 : 13808 : int atts_done = 0;
2849 : : ListCell *lc;
2850 : :
2851 [ + - + + : 27678 : foreach(lc, rte->functions)
+ + ]
2852 : : {
2853 : 13870 : RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
2854 : : TypeFuncClass functypclass;
888 2855 : 13870 : Oid funcrettype = InvalidOid;
2856 : 13870 : TupleDesc tupdesc = NULL;
2857 : :
2858 : : /* If it has a coldeflist, it returns RECORD */
2859 [ + + ]: 13870 : if (rtfunc->funccolnames != NIL)
2860 : 23 : functypclass = TYPEFUNC_RECORD;
2861 : : else
2862 : 13847 : functypclass = get_expr_result_type(rtfunc->funcexpr,
2863 : : &funcrettype,
2864 : : &tupdesc);
2865 : :
3251 2866 [ + + - + ]: 13870 : if (functypclass == TYPEFUNC_COMPOSITE ||
2867 : : functypclass == TYPEFUNC_COMPOSITE_DOMAIN)
2868 : : {
2869 : : /* Composite data type, e.g. a table's row type */
4686 2870 [ - + ]: 6427 : Assert(tupdesc);
2871 : 6427 : expandTupleDesc(tupdesc, rte->eref,
2872 : : rtfunc->funccolcount, atts_done,
2873 : : rtindex, sublevels_up,
2874 : : returning_type, location,
2875 : : include_dropped, colnames, colvars);
2876 : : }
2877 [ + + ]: 7443 : else if (functypclass == TYPEFUNC_SCALAR)
2878 : : {
2879 : : /* Base data type, i.e. scalar */
2880 [ + + ]: 7420 : if (colnames)
2881 : 198 : *colnames = lappend(*colnames,
2882 : 198 : list_nth(rte->eref->colnames,
2883 : : atts_done));
2884 : :
2885 [ + + ]: 7420 : if (colvars)
2886 : : {
2887 : : Var *varnode;
2888 : :
2889 : 7222 : varnode = makeVar(rtindex, atts_done + 1,
2890 : : funcrettype,
2453 2891 : 7222 : exprTypmod(rtfunc->funcexpr),
4686 2892 : 7222 : exprCollation(rtfunc->funcexpr),
2893 : : sublevels_up);
612 dean.a.rasheed@gmail 2894 : 7222 : varnode->varreturningtype = returning_type;
6593 tgl@sss.pgh.pa.us 2895 : 7222 : varnode->location = location;
2896 : :
8813 bruce@momjian.us 2897 : 7222 : *colvars = lappend(*colvars, varnode);
2898 : : }
2899 : : }
4686 tgl@sss.pgh.pa.us 2900 [ + - ]: 23 : else if (functypclass == TYPEFUNC_RECORD)
2901 : : {
2902 [ + + ]: 23 : if (colnames)
2903 : : {
2904 : : List *namelist;
2905 : :
2906 : : /* extract appropriate subset of column list */
2907 : 4 : namelist = list_copy_tail(rte->eref->colnames,
2908 : : atts_done);
2909 : 4 : namelist = list_truncate(namelist,
2910 : : rtfunc->funccolcount);
2911 : 4 : *colnames = list_concat(*colnames, namelist);
2912 : : }
2913 : :
2914 [ + + ]: 23 : if (colvars)
2915 : : {
2916 : : ListCell *l1;
2917 : : ListCell *l2;
2918 : : ListCell *l3;
2919 : 19 : int attnum = atts_done;
2920 : :
2921 [ + - + + : 61 : forthree(l1, rtfunc->funccoltypes,
+ - + + +
- + + + +
+ - + - +
+ ]
2922 : : l2, rtfunc->funccoltypmods,
2923 : : l3, rtfunc->funccolcollations)
2924 : : {
2925 : 42 : Oid attrtype = lfirst_oid(l1);
2926 : 42 : int32 attrtypmod = lfirst_int(l2);
2927 : 42 : Oid attrcollation = lfirst_oid(l3);
2928 : : Var *varnode;
2929 : :
2930 : 42 : attnum++;
2931 : 42 : varnode = makeVar(rtindex,
2932 : : attnum,
2933 : : attrtype,
2934 : : attrtypmod,
2935 : : attrcollation,
2936 : : sublevels_up);
612 dean.a.rasheed@gmail 2937 : 42 : varnode->varreturningtype = returning_type;
4686 tgl@sss.pgh.pa.us 2938 : 42 : varnode->location = location;
2939 : 42 : *colvars = lappend(*colvars, varnode);
2940 : : }
2941 : : }
2942 : : }
2943 : : else
2944 : : {
2945 : : /* addRangeTableEntryForFunction should've caught this */
4686 tgl@sss.pgh.pa.us 2946 [ # # ]:UBC 0 : elog(ERROR, "function in FROM has unsupported return type");
2947 : : }
4686 tgl@sss.pgh.pa.us 2948 :CBC 13870 : atts_done += rtfunc->funccolcount;
2949 : : }
2950 : :
2951 : : /* Append the ordinality column if any */
4801 stark@mit.edu 2952 [ + + ]: 13808 : if (rte->funcordinality)
2953 : : {
2954 [ + + ]: 473 : if (colnames)
4686 tgl@sss.pgh.pa.us 2955 : 12 : *colnames = lappend(*colnames,
2956 : 12 : llast(rte->eref->colnames));
2957 : :
4801 stark@mit.edu 2958 [ + + ]: 473 : if (colvars)
2959 : : {
4686 tgl@sss.pgh.pa.us 2960 : 461 : Var *varnode = makeVar(rtindex,
2961 : 461 : atts_done + 1,
2962 : : INT8OID,
2963 : : -1,
2964 : : InvalidOid,
2965 : : sublevels_up);
2966 : :
612 dean.a.rasheed@gmail 2967 : 461 : varnode->varreturningtype = returning_type;
4801 stark@mit.edu 2968 : 461 : *colvars = lappend(*colvars, varnode);
2969 : : }
2970 : : }
2971 : : }
8897 tgl@sss.pgh.pa.us 2972 : 13808 : break;
2973 : 8 : case RTE_JOIN:
2974 : : {
2975 : : /* Join RTE */
2976 : : ListCell *colname;
2977 : : ListCell *aliasvar;
2978 : :
8148 neilc@samurai.com 2979 [ - + ]: 8 : Assert(list_length(rte->eref->colnames) == list_length(rte->joinaliasvars));
2980 : :
8897 tgl@sss.pgh.pa.us 2981 : 8 : varattno = 0;
8057 bruce@momjian.us 2982 [ + - + + : 40 : forboth(colname, rte->eref->colnames, aliasvar, rte->joinaliasvars)
+ - + + +
+ + - +
+ ]
2983 : : {
7779 tgl@sss.pgh.pa.us 2984 : 32 : Node *avar = (Node *) lfirst(aliasvar);
2985 : :
8897 2986 : 32 : varattno++;
2987 : :
2988 : : /*
2989 : : * During ordinary parsing, there will never be any
2990 : : * deleted columns in the join. While this function is
2991 : : * also used by the rewriter and planner, they do not
2992 : : * currently call it on any JOIN RTEs. Therefore, this
2993 : : * next bit is dead code, but it seems prudent to handle
2994 : : * the case correctly anyway.
2995 : : */
4807 2996 [ - + ]: 32 : if (avar == NULL)
2997 : : {
8067 tgl@sss.pgh.pa.us 2998 [ # # ]:UBC 0 : if (include_dropped)
2999 : : {
3000 [ # # ]: 0 : if (colnames)
3001 : 0 : *colnames = lappend(*colnames,
7779 3002 : 0 : makeString(pstrdup("")));
8067 3003 [ # # ]: 0 : if (colvars)
3004 : : {
3005 : : /*
3006 : : * Can't use join's column type here (it might
3007 : : * be dropped!); but it doesn't really matter
3008 : : * what type the Const claims to be.
3009 : : */
3010 : 0 : *colvars = lappend(*colvars,
4807 3011 : 0 : makeNullConst(INT4OID, -1,
3012 : : InvalidOid));
3013 : : }
3014 : : }
8067 3015 : 0 : continue;
3016 : : }
3017 : :
8897 tgl@sss.pgh.pa.us 3018 [ - + ]:CBC 32 : if (colnames)
3019 : : {
8152 neilc@samurai.com 3020 :UBC 0 : char *label = strVal(lfirst(colname));
3021 : :
8067 tgl@sss.pgh.pa.us 3022 : 0 : *colnames = lappend(*colnames,
3023 : 0 : makeString(pstrdup(label)));
3024 : : }
3025 : :
8897 tgl@sss.pgh.pa.us 3026 [ + - ]:CBC 32 : if (colvars)
3027 : : {
3028 : : Var *varnode;
3029 : :
3030 : : /*
3031 : : * If the joinaliasvars entry is a simple Var, just
3032 : : * copy it (with adjustment of varlevelsup and
3033 : : * location); otherwise it is a JOIN USING column and
3034 : : * we must generate a join alias Var. This matches
3035 : : * the results that expansion of "join.*" by
3036 : : * expandNSItemVars would have produced, if we had
3037 : : * access to the ParseNamespaceItem for the join.
3038 : : */
2446 3039 [ + - ]: 32 : if (IsA(avar, Var))
3040 : : {
3041 : 32 : varnode = copyObject((Var *) avar);
3042 : 32 : varnode->varlevelsup = sublevels_up;
3043 : : }
3044 : : else
2446 tgl@sss.pgh.pa.us 3045 :UBC 0 : varnode = makeVar(rtindex, varattno,
3046 : : exprType(avar),
3047 : : exprTypmod(avar),
3048 : : exprCollation(avar),
3049 : : sublevels_up);
612 dean.a.rasheed@gmail 3050 :CBC 32 : varnode->varreturningtype = returning_type;
6593 tgl@sss.pgh.pa.us 3051 : 32 : varnode->location = location;
3052 : :
8897 3053 : 32 : *colvars = lappend(*colvars, varnode);
3054 : : }
3055 : : }
3056 : : }
3057 : 8 : break;
3483 alvherre@alvh.no-ip. 3058 : 2063 : case RTE_TABLEFUNC:
3059 : : case RTE_VALUES:
3060 : : case RTE_CTE:
3061 : : case RTE_NAMEDTUPLESTORE:
3062 : : {
3063 : : /* Tablefunc, Values, CTE, or ENR RTE */
6560 tgl@sss.pgh.pa.us 3064 : 2063 : ListCell *aliasp_item = list_head(rte->eref->colnames);
3065 : : ListCell *lct;
3066 : : ListCell *lcm;
3067 : : ListCell *lcc;
3068 : :
3069 : 2063 : varattno = 0;
3573 3070 [ + - + + : 6363 : forthree(lct, rte->coltypes,
+ - + + +
- + + + +
+ - + - +
+ ]
3071 : : lcm, rte->coltypmods,
3072 : : lcc, rte->colcollations)
3073 : : {
6310 bruce@momjian.us 3074 : 4300 : Oid coltype = lfirst_oid(lct);
3075 : 4300 : int32 coltypmod = lfirst_int(lcm);
5703 peter_e@gmx.net 3076 : 4300 : Oid colcoll = lfirst_oid(lcc);
3077 : :
6560 tgl@sss.pgh.pa.us 3078 : 4300 : varattno++;
3079 : :
3080 [ - + ]: 4300 : if (colnames)
3081 : : {
3082 : : /* Assume there is one alias per output column */
3301 tgl@sss.pgh.pa.us 3083 [ # # ]:UBC 0 : if (OidIsValid(coltype))
3084 : : {
3085 : 0 : char *label = strVal(lfirst(aliasp_item));
3086 : :
3087 : 0 : *colnames = lappend(*colnames,
3088 : 0 : makeString(pstrdup(label)));
3089 : : }
3090 [ # # ]: 0 : else if (include_dropped)
3091 : 0 : *colnames = lappend(*colnames,
3092 : 0 : makeString(pstrdup("")));
3093 : :
2624 3094 : 0 : aliasp_item = lnext(rte->eref->colnames, aliasp_item);
3095 : : }
3096 : :
6560 tgl@sss.pgh.pa.us 3097 [ + - ]:CBC 4300 : if (colvars)
3098 : : {
3301 3099 [ + - ]: 4300 : if (OidIsValid(coltype))
3100 : : {
3101 : : Var *varnode;
3102 : :
3103 : 4300 : varnode = makeVar(rtindex, varattno,
3104 : : coltype, coltypmod, colcoll,
3105 : : sublevels_up);
612 dean.a.rasheed@gmail 3106 : 4300 : varnode->varreturningtype = returning_type;
3301 tgl@sss.pgh.pa.us 3107 : 4300 : varnode->location = location;
3108 : :
3109 : 4300 : *colvars = lappend(*colvars, varnode);
3110 : : }
3301 tgl@sss.pgh.pa.us 3111 [ # # ]:UBC 0 : else if (include_dropped)
3112 : : {
3113 : : /*
3114 : : * It doesn't really matter what type the Const
3115 : : * claims to be.
3116 : : */
3117 : 0 : *colvars = lappend(*colvars,
3118 : 0 : makeNullConst(INT4OID, -1,
3119 : : InvalidOid));
3120 : : }
3121 : : }
3122 : : }
3123 : : }
6560 tgl@sss.pgh.pa.us 3124 :CBC 2063 : break;
2792 tgl@sss.pgh.pa.us 3125 :UBC 0 : case RTE_RESULT:
3126 : : case RTE_GROUP:
3127 : : /* These expose no columns, so nothing to do */
3128 : 0 : break;
8897 3129 : 0 : default:
8464 3130 [ # # ]: 0 : elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
3131 : : }
9504 tgl@sss.pgh.pa.us 3132 :CBC 16513 : }
3133 : :
3134 : : /*
3135 : : * expandRelation -- expandRTE subroutine
3136 : : */
3137 : : static void
8067 3138 : 141 : expandRelation(Oid relid, Alias *eref, int rtindex, int sublevels_up,
3139 : : VarReturningType returning_type,
3140 : : int location, bool include_dropped,
3141 : : List **colnames, List **colvars)
3142 : : {
3143 : : Relation rel;
3144 : :
3145 : : /* Get the tupledesc and turn it over to expandTupleDesc */
3146 : 141 : rel = relation_open(relid, AccessShareLock);
4686 3147 : 141 : expandTupleDesc(rel->rd_att, eref, rel->rd_att->natts, 0,
3148 : : rtindex, sublevels_up, returning_type,
3149 : : location, include_dropped,
3150 : : colnames, colvars);
7843 3151 : 141 : relation_close(rel, AccessShareLock);
3152 : 141 : }
3153 : :
3154 : : /*
3155 : : * expandTupleDesc -- expandRTE subroutine
3156 : : *
3157 : : * Generate names and/or Vars for the first "count" attributes of the tupdesc,
3158 : : * and append them to colnames/colvars. "offset" is added to the varattno
3159 : : * that each Var would otherwise have, and we also skip the first "offset"
3160 : : * entries in eref->colnames. (These provisions allow use of this code for
3161 : : * an individual composite-returning function in an RTE_FUNCTION RTE.)
3162 : : */
3163 : : static void
4686 3164 : 6568 : expandTupleDesc(TupleDesc tupdesc, Alias *eref, int count, int offset,
3165 : : int rtindex, int sublevels_up,
3166 : : VarReturningType returning_type,
3167 : : int location, bool include_dropped,
3168 : : List **colnames, List **colvars)
3169 : : {
3170 : : ListCell *aliascell;
3171 : : int varattno;
3172 : :
2624 3173 : 6568 : aliascell = (offset < list_length(eref->colnames)) ?
3174 [ + + ]: 6568 : list_nth_cell(eref->colnames, offset) : NULL;
3175 : :
4686 3176 [ - + ]: 6568 : Assert(count <= tupdesc->natts);
3177 [ + + ]: 57108 : for (varattno = 0; varattno < count; varattno++)
3178 : : {
3318 andres@anarazel.de 3179 : 50540 : Form_pg_attribute attr = TupleDescAttr(tupdesc, varattno);
3180 : :
8067 tgl@sss.pgh.pa.us 3181 [ + + ]: 50540 : if (attr->attisdropped)
3182 : : {
3183 [ + - ]: 28 : if (include_dropped)
3184 : : {
3185 [ + - ]: 28 : if (colnames)
3186 : 28 : *colnames = lappend(*colnames, makeString(pstrdup("")));
3187 [ - + ]: 28 : if (colvars)
3188 : : {
3189 : : /*
3190 : : * can't use atttypid here, but it doesn't really matter
3191 : : * what type the Const claims to be.
3192 : : */
5658 tgl@sss.pgh.pa.us 3193 :UBC 0 : *colvars = lappend(*colvars,
3378 3194 : 0 : makeNullConst(INT4OID, -1, InvalidOid));
3195 : : }
3196 : : }
4686 tgl@sss.pgh.pa.us 3197 [ + - ]:CBC 28 : if (aliascell)
2624 3198 : 28 : aliascell = lnext(eref->colnames, aliascell);
8067 3199 : 28 : continue;
3200 : : }
3201 : :
3202 [ + + ]: 50512 : if (colnames)
3203 : : {
3204 : : char *label;
3205 : :
4686 3206 [ + + ]: 4814 : if (aliascell)
3207 : : {
3208 : 4782 : label = strVal(lfirst(aliascell));
2624 3209 : 4782 : aliascell = lnext(eref->colnames, aliascell);
3210 : : }
3211 : : else
3212 : : {
3213 : : /* If we run out of aliases, use the underlying name */
8067 3214 : 32 : label = NameStr(attr->attname);
3215 : : }
3216 : 4814 : *colnames = lappend(*colnames, makeString(pstrdup(label)));
3217 : : }
3218 : :
3219 [ + + ]: 50512 : if (colvars)
3220 : : {
3221 : : Var *varnode;
3222 : :
4686 3223 : 46120 : varnode = makeVar(rtindex, varattno + offset + 1,
3224 : : attr->atttypid, attr->atttypmod,
3225 : : attr->attcollation,
3226 : : sublevels_up);
612 dean.a.rasheed@gmail 3227 : 46120 : varnode->varreturningtype = returning_type;
6593 tgl@sss.pgh.pa.us 3228 : 46120 : varnode->location = location;
3229 : :
8067 3230 : 46120 : *colvars = lappend(*colvars, varnode);
3231 : : }
3232 : : }
3233 : 6568 : }
3234 : :
3235 : : /*
3236 : : * expandNSItemVars
3237 : : * Produce a list of Vars, and optionally a list of column names,
3238 : : * for the non-dropped columns of the nsitem.
3239 : : *
3240 : : * The emitted Vars are marked with the given sublevels_up and location.
3241 : : *
3242 : : * If colnames isn't NULL, a list of String items for the columns is stored
3243 : : * there; note that it's just a subset of the RTE's eref list, and hence
3244 : : * the list elements mustn't be modified.
3245 : : */
3246 : : List *
1329 3247 : 52456 : expandNSItemVars(ParseState *pstate, ParseNamespaceItem *nsitem,
3248 : : int sublevels_up, int location,
3249 : : List **colnames)
3250 : : {
2453 3251 : 52456 : List *result = NIL;
3252 : : int colindex;
3253 : : ListCell *lc;
3254 : :
3255 [ + + ]: 52456 : if (colnames)
3256 : 49100 : *colnames = NIL;
3257 : 52456 : colindex = 0;
1999 peter@eisentraut.org 3258 [ + + + + : 211181 : foreach(lc, nsitem->p_names->colnames)
+ + ]
3259 : : {
1837 3260 : 158725 : String *colnameval = lfirst(lc);
2453 tgl@sss.pgh.pa.us 3261 : 158725 : const char *colname = strVal(colnameval);
3262 : 158725 : ParseNamespaceColumn *nscol = nsitem->p_nscolumns + colindex;
3263 : :
2057 peter@eisentraut.org 3264 [ + + ]: 158725 : if (nscol->p_dontexpand)
3265 : : {
3266 : : /* skip */
3267 : : }
3268 [ + + ]: 158713 : else if (colname[0])
3269 : : {
3270 : : Var *var;
3271 : :
2453 tgl@sss.pgh.pa.us 3272 [ - + ]: 157969 : Assert(nscol->p_varno > 0);
2446 3273 : 157969 : var = makeVar(nscol->p_varno,
3274 : 157969 : nscol->p_varattno,
3275 : : nscol->p_vartype,
3276 : : nscol->p_vartypmod,
3277 : : nscol->p_varcollid,
3278 : : sublevels_up);
3279 : : /* makeVar doesn't offer parameters for these, so set by hand: */
612 dean.a.rasheed@gmail 3280 : 157969 : var->varreturningtype = nscol->p_varreturningtype;
2446 tgl@sss.pgh.pa.us 3281 : 157969 : var->varnosyn = nscol->p_varnosyn;
3282 : 157969 : var->varattnosyn = nscol->p_varattnosyn;
2453 3283 : 157969 : var->location = location;
3284 : :
3285 : : /* ... and update varnullingrels */
1329 3286 : 157969 : markNullableIfNeeded(pstate, var);
3287 : :
2453 3288 : 157969 : result = lappend(result, var);
3289 [ + + ]: 157969 : if (colnames)
3290 : 151187 : *colnames = lappend(*colnames, colnameval);
3291 : : }
3292 : : else
3293 : : {
3294 : : /* dropped column, ignore */
3295 [ - + ]: 744 : Assert(nscol->p_varno == 0);
3296 : : }
3297 : 158725 : colindex++;
3298 : : }
3299 : 52456 : return result;
3300 : : }
3301 : :
3302 : : /*
3303 : : * expandNSItemAttrs -
3304 : : * Workhorse for "*" expansion: produce a list of targetentries
3305 : : * for the attributes of the nsitem
3306 : : *
3307 : : * pstate->p_next_resno determines the resnos assigned to the TLEs.
3308 : : * The referenced columns are marked as requiring SELECT access, if
3309 : : * caller requests that.
3310 : : */
3311 : : List *
2460 3312 : 49100 : expandNSItemAttrs(ParseState *pstate, ParseNamespaceItem *nsitem,
3313 : : int sublevels_up, bool require_col_privs, int location)
3314 : : {
3315 : 49100 : RangeTblEntry *rte = nsitem->p_rte;
1384 alvherre@alvh.no-ip. 3316 : 49100 : RTEPermissionInfo *perminfo = nsitem->p_perminfo;
3317 : : List *names,
3318 : : *vars;
3319 : : ListCell *name,
3320 : : *var;
9504 tgl@sss.pgh.pa.us 3321 : 49100 : List *te_list = NIL;
3322 : :
1329 3323 : 49100 : vars = expandNSItemVars(pstate, nsitem, sublevels_up, location, &names);
3324 : :
3325 : : /*
3326 : : * Require read access to the table. This is normally redundant with the
3327 : : * markVarForSelectPriv calls below, but not if the table has zero
3328 : : * columns. We need not do anything if the nsitem is for a join: its
3329 : : * component tables will have been marked ACL_SELECT when they were added
3330 : : * to the rangetable. (This step changes things only for the target
3331 : : * relation of UPDATE/DELETE, which cannot be under a join.)
3332 : : */
2050 3333 [ + + ]: 49100 : if (rte->rtekind == RTE_RELATION)
3334 : : {
1384 alvherre@alvh.no-ip. 3335 [ - + ]: 28178 : Assert(perminfo != NULL);
3336 : 28178 : perminfo->requiredPerms |= ACL_SELECT;
3337 : : }
3338 : :
8067 tgl@sss.pgh.pa.us 3339 [ + + + + : 200287 : forboth(name, names, var, vars)
+ + + + +
+ + - +
+ ]
3340 : : {
8152 neilc@samurai.com 3341 : 151187 : char *label = strVal(lfirst(name));
6450 tgl@sss.pgh.pa.us 3342 : 151187 : Var *varnode = (Var *) lfirst(var);
3343 : : TargetEntry *te;
3344 : :
7837 3345 : 151187 : te = makeTargetEntry((Expr *) varnode,
3346 : 151187 : (AttrNumber) pstate->p_next_resno++,
3347 : : label,
3348 : : false);
9925 3349 : 151187 : te_list = lappend(te_list, te);
3350 : :
1637 alvherre@alvh.no-ip. 3351 [ + - ]: 151187 : if (require_col_privs)
3352 : : {
3353 : : /* Require read access to each column */
3354 : 151187 : markVarForSelectPriv(pstate, varnode);
3355 : : }
3356 : : }
3357 : :
3378 tgl@sss.pgh.pa.us 3358 [ + - - + ]: 49100 : Assert(name == NULL && var == NULL); /* lists not the same length? */
3359 : :
9925 3360 : 49100 : return te_list;
3361 : : }
3362 : :
3363 : : /*
3364 : : * get_rte_attribute_name
3365 : : * Get an attribute name from a RangeTblEntry
3366 : : *
3367 : : * This is unlike get_attname() because we use aliases if available.
3368 : : * In particular, it will work on an RTE for a subselect or join, whereas
3369 : : * get_attname() only works on real relations.
3370 : : *
3371 : : * "*" is returned if the given attnum is InvalidAttrNumber --- this case
3372 : : * occurs when a Var represents a whole tuple of a relation.
3373 : : *
3374 : : * It is caller's responsibility to not call this on a dropped attribute.
3375 : : * (You will get some answer for such cases, but it might not be sensible.)
3376 : : */
3377 : : char *
9491 3378 : 1296 : get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum)
3379 : : {
9286 3380 [ - + ]: 1296 : if (attnum == InvalidAttrNumber)
9286 tgl@sss.pgh.pa.us 3381 :UBC 0 : return "*";
3382 : :
3383 : : /*
3384 : : * If there is a user-written column alias, use it.
3385 : : */
8809 tgl@sss.pgh.pa.us 3386 [ + + + + ]:CBC 1296 : if (rte->alias &&
8148 neilc@samurai.com 3387 [ - + ]: 36 : attnum > 0 && attnum <= list_length(rte->alias->colnames))
8148 neilc@samurai.com 3388 :UBC 0 : return strVal(list_nth(rte->alias->colnames, attnum - 1));
3389 : :
3390 : : /*
3391 : : * If the RTE is a relation, go to the system catalogs not the
3392 : : * eref->colnames list. This is a little slower but it will give the
3393 : : * right answer if the column has been renamed since the eref list was
3394 : : * built (which can easily happen for rules).
3395 : : */
8809 tgl@sss.pgh.pa.us 3396 [ + + ]:CBC 1296 : if (rte->rtekind == RTE_RELATION)
3142 alvherre@alvh.no-ip. 3397 : 1276 : return get_attname(rte->relid, attnum, false);
3398 : :
3399 : : /*
3400 : : * Otherwise use the column name from eref. There should always be one.
3401 : : */
8148 neilc@samurai.com 3402 [ + - + - ]: 20 : if (attnum > 0 && attnum <= list_length(rte->eref->colnames))
3403 : 20 : return strVal(list_nth(rte->eref->colnames, attnum - 1));
3404 : :
3405 : : /* else caller gave us a bogus attnum */
8464 tgl@sss.pgh.pa.us 3406 [ # # ]:UBC 0 : elog(ERROR, "invalid attnum %d for rangetable entry %s",
3407 : : attnum, rte->eref->aliasname);
3408 : : return NULL; /* keep compiler quiet */
3409 : : }
3410 : :
3411 : : /*
3412 : : * get_rte_attribute_is_dropped
3413 : : * Check whether attempted attribute ref is to a dropped column
3414 : : */
3415 : : bool
7779 tgl@sss.pgh.pa.us 3416 :CBC 594993 : get_rte_attribute_is_dropped(RangeTblEntry *rte, AttrNumber attnum)
3417 : : {
3418 : : bool result;
3419 : :
8815 3420 [ + + - - : 594993 : switch (rte->rtekind)
+ - - ]
3421 : : {
3422 : 508326 : case RTE_RELATION:
3423 : : {
3424 : : /*
3425 : : * Plain relation RTE --- get the attribute's catalog entry
3426 : : */
3427 : : HeapTuple tp;
3428 : : Form_pg_attribute att_tup;
3429 : :
6062 rhaas@postgresql.org 3430 : 508326 : tp = SearchSysCache2(ATTNUM,
3431 : : ObjectIdGetDatum(rte->relid),
3432 : : Int16GetDatum(attnum));
3378 tgl@sss.pgh.pa.us 3433 [ - + ]: 508326 : if (!HeapTupleIsValid(tp)) /* shouldn't happen */
8464 tgl@sss.pgh.pa.us 3434 [ # # ]:UBC 0 : elog(ERROR, "cache lookup failed for attribute %d of relation %u",
3435 : : attnum, rte->relid);
8815 tgl@sss.pgh.pa.us 3436 :CBC 508326 : att_tup = (Form_pg_attribute) GETSTRUCT(tp);
3437 : 508326 : result = att_tup->attisdropped;
3438 : 508326 : ReleaseSysCache(tp);
3439 : : }
3440 : 508326 : break;
3441 : 1158 : case RTE_SUBQUERY:
3442 : : case RTE_TABLEFUNC:
3443 : : case RTE_VALUES:
3444 : : case RTE_CTE:
3445 : : case RTE_GROUP:
3446 : :
3447 : : /*
3448 : : * Subselect, Table Functions, Values, CTE, GROUP RTEs never have
3449 : : * dropped columns
3450 : : */
3451 : 1158 : result = false;
3452 : 1158 : break;
3460 kgrittn@postgresql.o 3453 :UBC 0 : case RTE_NAMEDTUPLESTORE:
3454 : : {
3455 : : /* Check dropped-ness by testing for valid coltype */
3301 tgl@sss.pgh.pa.us 3456 [ # # # # ]: 0 : if (attnum <= 0 ||
3457 : 0 : attnum > list_length(rte->coltypes))
3458 [ # # ]: 0 : elog(ERROR, "invalid varattno %d", attnum);
3459 : 0 : result = !OidIsValid((list_nth_oid(rte->coltypes, attnum - 1)));
3460 : : }
3460 kgrittn@postgresql.o 3461 : 0 : break;
8067 tgl@sss.pgh.pa.us 3462 : 0 : case RTE_JOIN:
3463 : : {
3464 : : /*
3465 : : * A join RTE would not have dropped columns when constructed,
3466 : : * but one in a stored rule might contain columns that were
3467 : : * dropped from the underlying tables, if said columns are
3468 : : * nowhere explicitly referenced in the rule. This will be
3469 : : * signaled to us by a null pointer in the joinaliasvars list.
3470 : : */
3471 : : Var *aliasvar;
3472 : :
3473 [ # # # # ]: 0 : if (attnum <= 0 ||
3474 : 0 : attnum > list_length(rte->joinaliasvars))
3475 [ # # ]: 0 : elog(ERROR, "invalid varattno %d", attnum);
3476 : 0 : aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
3477 : :
4807 3478 : 0 : result = (aliasvar == NULL);
3479 : : }
8067 3480 : 0 : break;
8815 tgl@sss.pgh.pa.us 3481 :CBC 85509 : case RTE_FUNCTION:
3482 : : {
3483 : : /* Function RTE */
3484 : : ListCell *lc;
4686 3485 : 85509 : int atts_done = 0;
3486 : :
3487 : : /*
3488 : : * Dropped attributes are only possible with functions that
3489 : : * return named composite types. In such a case we have to
3490 : : * look up the result type to see if it currently has this
3491 : : * column dropped. So first, loop over the funcs until we
3492 : : * find the one that covers the requested column.
3493 : : */
3494 [ + - + + : 85549 : foreach(lc, rte->functions)
+ + ]
3495 : : {
3496 : 85533 : RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
3497 : :
3498 [ + - ]: 85533 : if (attnum > atts_done &&
3499 [ + + ]: 85533 : attnum <= atts_done + rtfunc->funccolcount)
3500 : : {
3501 : : TupleDesc tupdesc;
3502 : :
3503 : : /* If it has a coldeflist, it returns RECORD */
888 3504 [ - + ]: 85493 : if (rtfunc->funccolnames != NIL)
3505 : 85493 : return false; /* can't have any dropped columns */
3506 : :
3251 3507 : 85493 : tupdesc = get_expr_result_tupdesc(rtfunc->funcexpr,
3508 : : true);
3509 [ + + ]: 85493 : if (tupdesc)
3510 : : {
3511 : : /* Composite data type, e.g. a table's row type */
3512 : : CompactAttribute *att;
3513 : :
4686 3514 [ - + ]: 85358 : Assert(tupdesc);
3515 [ - + ]: 85358 : Assert(attnum - atts_done <= tupdesc->natts);
333 drowley@postgresql.o 3516 : 85358 : att = TupleDescCompactAttr(tupdesc,
3517 : 85358 : attnum - atts_done - 1);
3518 : 85358 : return att->attisdropped;
3519 : : }
3520 : : /* Otherwise, it can't have any dropped columns */
4686 tgl@sss.pgh.pa.us 3521 : 135 : return false;
3522 : : }
3523 : 40 : atts_done += rtfunc->funccolcount;
3524 : : }
3525 : :
3526 : : /* If we get here, must be looking for the ordinality column */
3527 [ + - + - ]: 16 : if (rte->funcordinality && attnum == atts_done + 1)
3528 : 16 : return false;
3529 : :
3530 : : /* this probably can't happen ... */
4686 tgl@sss.pgh.pa.us 3531 [ # # ]:UBC 0 : ereport(ERROR,
3532 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
3533 : : errmsg("column %d of relation \"%s\" does not exist",
3534 : : attnum,
3535 : : rte->eref->aliasname)));
3536 : : result = false; /* keep compiler quiet */
3537 : : }
3538 : : break;
2792 3539 : 0 : case RTE_RESULT:
3540 : : /* this probably can't happen ... */
3541 [ # # ]: 0 : ereport(ERROR,
3542 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
3543 : : errmsg("column %d of relation \"%s\" does not exist",
3544 : : attnum,
3545 : : rte->eref->aliasname)));
3546 : : result = false; /* keep compiler quiet */
3547 : : break;
8815 3548 : 0 : default:
8464 3549 [ # # ]: 0 : elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
3550 : : result = false; /* keep compiler quiet */
3551 : : }
3552 : :
8815 tgl@sss.pgh.pa.us 3553 :CBC 509484 : return result;
3554 : : }
3555 : :
3556 : : /*
3557 : : * Given a targetlist and a resno, return the matching TargetEntry
3558 : : *
3559 : : * Returns NULL if resno is not present in list.
3560 : : *
3561 : : * Note: we need to search, rather than just indexing with list_nth(),
3562 : : * because not all tlists are sorted by resno.
3563 : : */
3564 : : TargetEntry *
8441 3565 : 220868 : get_tle_by_resno(List *tlist, AttrNumber resno)
3566 : : {
3567 : : ListCell *l;
3568 : :
8152 neilc@samurai.com 3569 [ + + + + : 733925 : foreach(l, tlist)
+ + ]
3570 : : {
3571 : 733435 : TargetEntry *tle = (TargetEntry *) lfirst(l);
3572 : :
7837 tgl@sss.pgh.pa.us 3573 [ + + ]: 733435 : if (tle->resno == resno)
8441 3574 : 220378 : return tle;
3575 : : }
3576 : 490 : return NULL;
3577 : : }
3578 : :
3579 : : /*
3580 : : * Given a Query and rangetable index, return relation's RowMarkClause if any
3581 : : *
3582 : : * Returns NULL if relation is not selected FOR UPDATE/SHARE
3583 : : */
3584 : : RowMarkClause *
6173 3585 : 20296 : get_parse_rowmark(Query *qry, Index rtindex)
3586 : : {
3587 : : ListCell *l;
3588 : :
7448 3589 [ + + + + : 20435 : foreach(l, qry->rowMarks)
+ + ]
3590 : : {
3591 : 203 : RowMarkClause *rc = (RowMarkClause *) lfirst(l);
3592 : :
3593 [ + + ]: 203 : if (rc->rti == rtindex)
3594 : 64 : return rc;
3595 : : }
3596 : 20232 : return NULL;
3597 : : }
3598 : :
3599 : : /*
3600 : : * given relation and att name, return attnum of variable
3601 : : *
3602 : : * Returns InvalidAttrNumber if the attr doesn't exist (or is dropped).
3603 : : *
3604 : : * This should only be used if the relation is already
3605 : : * table_open()'ed. Use the cache version get_attnum()
3606 : : * for access to non-opened relations.
3607 : : */
3608 : : int
8815 3609 : 30884 : attnameAttNum(Relation rd, const char *attname, bool sysColOK)
3610 : : {
3611 : : int i;
3612 : :
3088 teodor@sigaev.ru 3613 [ + + ]: 147288 : for (i = 0; i < RelationGetNumberOfAttributes(rd); i++)
3614 : : {
3318 andres@anarazel.de 3615 : 147214 : Form_pg_attribute att = TupleDescAttr(rd->rd_att, i);
3616 : :
8815 tgl@sss.pgh.pa.us 3617 [ + + + + ]: 147214 : if (namestrcmp(&(att->attname), attname) == 0 && !att->attisdropped)
10246 bruce@momjian.us 3618 : 30810 : return i + 1;
3619 : : }
3620 : :
8815 tgl@sss.pgh.pa.us 3621 [ + + ]: 74 : if (sysColOK)
3622 : : {
3623 [ - + ]: 16 : if ((i = specialAttNum(attname)) != InvalidAttrNumber)
2861 andres@anarazel.de 3624 :UBC 0 : return i;
3625 : : }
3626 : :
3627 : : /* on failure */
7486 tgl@sss.pgh.pa.us 3628 :CBC 74 : return InvalidAttrNumber;
3629 : : }
3630 : :
3631 : : /*
3632 : : * specialAttNum()
3633 : : *
3634 : : * Check attribute name to see if it is "special", e.g. "xmin".
3635 : : * - thomas 2000-02-07
3636 : : *
3637 : : * Note: this only discovers whether the name could be a system attribute.
3638 : : * Caller needs to ensure that it really is an attribute of the rel.
3639 : : */
3640 : : static int
8815 3641 : 74719 : specialAttNum(const char *attname)
3642 : : {
3643 : : const FormData_pg_attribute *sysatt;
3644 : :
2861 andres@anarazel.de 3645 : 74719 : sysatt = SystemAttributeByName(attname);
9099 tgl@sss.pgh.pa.us 3646 [ + + ]: 74719 : if (sysatt != NULL)
3647 : 20723 : return sysatt->attnum;
9714 lockhart@fourpalms.o 3648 : 53996 : return InvalidAttrNumber;
3649 : : }
3650 : :
3651 : :
3652 : : /*
3653 : : * given attribute id, return name of that attribute
3654 : : *
3655 : : * This should only be used if the relation is already
3656 : : * table_open()'ed. Use the cache version get_atttype()
3657 : : * for access to non-opened relations.
3658 : : */
3659 : : const NameData *
9098 tgl@sss.pgh.pa.us 3660 : 8387 : attnumAttName(Relation rd, int attid)
3661 : : {
3662 [ - + ]: 8387 : if (attid <= 0)
3663 : : {
3664 : : const FormData_pg_attribute *sysatt;
3665 : :
2861 andres@anarazel.de 3666 :UBC 0 : sysatt = SystemAttributeDefinition(attid);
9098 tgl@sss.pgh.pa.us 3667 : 0 : return &sysatt->attname;
3668 : : }
9098 tgl@sss.pgh.pa.us 3669 [ - + ]:CBC 8387 : if (attid > rd->rd_att->natts)
8464 tgl@sss.pgh.pa.us 3670 [ # # ]:UBC 0 : elog(ERROR, "invalid attribute number %d", attid);
3318 andres@anarazel.de 3671 :CBC 8387 : return &TupleDescAttr(rd->rd_att, attid - 1)->attname;
3672 : : }
3673 : :
3674 : : /*
3675 : : * given attribute id, return type of that attribute
3676 : : *
3677 : : * This should only be used if the relation is already
3678 : : * table_open()'ed. Use the cache version get_atttype()
3679 : : * for access to non-opened relations.
3680 : : */
3681 : : Oid
10526 bruce@momjian.us 3682 : 127664 : attnumTypeId(Relation rd, int attid)
3683 : : {
9099 tgl@sss.pgh.pa.us 3684 [ - + ]: 127664 : if (attid <= 0)
3685 : : {
3686 : : const FormData_pg_attribute *sysatt;
3687 : :
2861 andres@anarazel.de 3688 :UBC 0 : sysatt = SystemAttributeDefinition(attid);
9099 tgl@sss.pgh.pa.us 3689 : 0 : return sysatt->atttypid;
3690 : : }
9098 tgl@sss.pgh.pa.us 3691 [ - + ]:CBC 127664 : if (attid > rd->rd_att->natts)
8464 tgl@sss.pgh.pa.us 3692 [ # # ]:UBC 0 : elog(ERROR, "invalid attribute number %d", attid);
3318 andres@anarazel.de 3693 :CBC 127664 : return TupleDescAttr(rd->rd_att, attid - 1)->atttypid;
3694 : : }
3695 : :
3696 : : /*
3697 : : * given attribute id, return collation of that attribute
3698 : : *
3699 : : * This should only be used if the relation is already table_open()'ed.
3700 : : */
3701 : : Oid
5641 tgl@sss.pgh.pa.us 3702 : 5087 : attnumCollationId(Relation rd, int attid)
3703 : : {
3704 [ - + ]: 5087 : if (attid <= 0)
3705 : : {
3706 : : /* All system attributes are of noncollatable types. */
5641 tgl@sss.pgh.pa.us 3707 :UBC 0 : return InvalidOid;
3708 : : }
5641 tgl@sss.pgh.pa.us 3709 [ - + ]:CBC 5087 : if (attid > rd->rd_att->natts)
5641 tgl@sss.pgh.pa.us 3710 [ # # ]:UBC 0 : elog(ERROR, "invalid attribute number %d", attid);
3318 andres@anarazel.de 3711 :CBC 5087 : return TupleDescAttr(rd->rd_att, attid - 1)->attcollation;
3712 : : }
3713 : :
3714 : : /*
3715 : : * Generate a suitable error about a missing RTE.
3716 : : *
3717 : : * Since this is a very common type of error, we work rather hard to
3718 : : * produce a helpful message.
3719 : : */
3720 : : void
6178 tgl@sss.pgh.pa.us 3721 : 76 : errorMissingRTE(ParseState *pstate, RangeVar *relation)
3722 : : {
3723 : : RangeTblEntry *rte;
7558 3724 : 76 : const char *badAlias = NULL;
3725 : :
3726 : : /*
3727 : : * Check to see if there are any potential matches in the query's
3728 : : * rangetable. (Note: cases involving a bad schema name in the RangeVar
3729 : : * will throw error immediately here. That seems OK.)
3730 : : */
5157 3731 : 76 : rte = searchRangeTableForRel(pstate, relation);
3732 : :
3733 : : /*
3734 : : * If we found a match that has an alias and the alias is visible in the
3735 : : * namespace, then the problem is probably use of the relation's real name
3736 : : * instead of its alias, ie "SELECT foo.* FROM foo f". This mistake is
3737 : : * common enough to justify a specific hint.
3738 : : *
3739 : : * If we found a match that doesn't meet those criteria, assume the
3740 : : * problem is illegal use of a relation outside its scope, as in the
3741 : : * MySQL-ism "SELECT ... FROM a, b LEFT JOIN c ON (a.x = c.y)".
3742 : : */
7558 3743 [ + + + + ]: 76 : if (rte && rte->alias &&
2460 3744 [ + + ]: 52 : strcmp(rte->eref->aliasname, relation->relname) != 0)
3745 : : {
3746 : : ParseNamespaceItem *nsitem;
3747 : : int sublevels_up;
3748 : :
3749 : 16 : nsitem = refnameNamespaceItem(pstate, NULL, rte->eref->aliasname,
3750 : : relation->location,
3751 : : &sublevels_up);
3752 [ + - + - ]: 16 : if (nsitem && nsitem->p_rte == rte)
3753 : 16 : badAlias = rte->eref->aliasname;
3754 : : }
3755 : :
3756 : : /* If it looks like the user forgot to use an alias, hint about that */
1398 3757 [ + + ]: 76 : if (badAlias)
6178 3758 [ + - ]: 16 : ereport(ERROR,
3759 : : (errcode(ERRCODE_UNDEFINED_TABLE),
3760 : : errmsg("invalid reference to FROM-clause entry for table \"%s\"",
3761 : : relation->relname),
3762 : : errhint("Perhaps you meant to reference the table alias \"%s\".",
3763 : : badAlias),
3764 : : parser_errposition(pstate, relation->location)));
3765 : : /* Hint about case where we found an (inaccessible) exact match */
1398 3766 [ + + ]: 60 : else if (rte)
3767 [ + - + + ]: 48 : ereport(ERROR,
3768 : : (errcode(ERRCODE_UNDEFINED_TABLE),
3769 : : errmsg("invalid reference to FROM-clause entry for table \"%s\"",
3770 : : relation->relname),
3771 : : errdetail("There is an entry for table \"%s\", but it cannot be referenced from this part of the query.",
3772 : : rte->eref->aliasname),
3773 : : rte_visible_if_lateral(pstate, rte) ?
3774 : : errhint("To reference that table, you must mark this subquery with LATERAL.") : 0,
3775 : : parser_errposition(pstate, relation->location)));
3776 : : /* Else, we have nothing to offer but the bald statement of error */
3777 : : else
6178 3778 [ + - ]: 12 : ereport(ERROR,
3779 : : (errcode(ERRCODE_UNDEFINED_TABLE),
3780 : : errmsg("missing FROM-clause entry for table \"%s\"",
3781 : : relation->relname),
3782 : : parser_errposition(pstate, relation->location)));
3783 : : }
3784 : :
3785 : : /*
3786 : : * Generate a suitable error about a missing column.
3787 : : *
3788 : : * Since this is a very common type of error, we work rather hard to
3789 : : * produce a helpful message.
3790 : : */
3791 : : void
5157 3792 : 245 : errorMissingColumn(ParseState *pstate,
3793 : : const char *relname, const char *colname, int location)
3794 : : {
3795 : : FuzzyAttrMatchState *state;
3796 : :
3797 : : /*
3798 : : * Search the entire rtable looking for possible matches. If we find one,
3799 : : * emit a hint about it.
3800 : : */
4211 rhaas@postgresql.org 3801 : 245 : state = searchRangeTableForCol(pstate, relname, colname, location);
3802 : :
3803 : : /*
3804 : : * If there are exact match(es), they must be inaccessible for some
3805 : : * reason.
3806 : : */
1398 tgl@sss.pgh.pa.us 3807 [ + + ]: 245 : if (state->rexact1)
3808 : : {
3809 : : /*
3810 : : * We don't try too hard when there's multiple inaccessible exact
3811 : : * matches, but at least be sure that we don't misleadingly suggest
3812 : : * that there's only one.
3813 : : */
3814 [ + + ]: 28 : if (state->rexact2)
3815 [ + - - + : 8 : ereport(ERROR,
+ - ]
3816 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
3817 : : relname ?
3818 : : errmsg("column %s.%s does not exist", relname, colname) :
3819 : : errmsg("column \"%s\" does not exist", colname),
3820 : : errdetail("There are columns named \"%s\", but they are in tables that cannot be referenced from this part of the query.",
3821 : : colname),
3822 : : !relname ? errhint("Try using a table-qualified name.") : 0,
3823 : : parser_errposition(pstate, location)));
3824 : : /* Single exact match, so try to determine why it's inaccessible. */
3825 [ + - - + : 20 : ereport(ERROR,
+ + + - -
+ ]
3826 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
3827 : : relname ?
3828 : : errmsg("column %s.%s does not exist", relname, colname) :
3829 : : errmsg("column \"%s\" does not exist", colname),
3830 : : errdetail("There is a column named \"%s\" in table \"%s\", but it cannot be referenced from this part of the query.",
3831 : : colname, state->rexact1->eref->aliasname),
3832 : : rte_visible_if_lateral(pstate, state->rexact1) ?
3833 : : errhint("To reference that column, you must mark this subquery with LATERAL.") :
3834 : : (!relname && rte_visible_if_qualified(pstate, state->rexact1)) ?
3835 : : errhint("To reference that column, you must use a table-qualified name.") : 0,
3836 : : parser_errposition(pstate, location)));
3837 : : }
3838 : :
3839 [ + + ]: 217 : if (!state->rsecond)
3840 : : {
3841 : : /* If we found no match at all, we have little to report */
3842 [ + + ]: 209 : if (!state->rfirst)
3843 [ + - + + ]: 177 : ereport(ERROR,
3844 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
3845 : : relname ?
3846 : : errmsg("column %s.%s does not exist", relname, colname) :
3847 : : errmsg("column \"%s\" does not exist", colname),
3848 : : parser_errposition(pstate, location)));
3849 : : /* Handle case where we have a single alternative spelling to offer */
4211 rhaas@postgresql.org 3850 [ + - + + ]: 32 : ereport(ERROR,
3851 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
3852 : : relname ?
3853 : : errmsg("column %s.%s does not exist", relname, colname) :
3854 : : errmsg("column \"%s\" does not exist", colname),
3855 : : errhint("Perhaps you meant to reference the column \"%s.%s\".",
3856 : : state->rfirst->eref->aliasname,
3857 : : strVal(list_nth(state->rfirst->eref->colnames,
3858 : : state->first - 1))),
3859 : : parser_errposition(pstate, location)));
3860 : : }
3861 : : else
3862 : : {
3863 : : /* Handle case where there are two equally useful column hints */
3864 [ + - - + ]: 8 : ereport(ERROR,
3865 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
3866 : : relname ?
3867 : : errmsg("column %s.%s does not exist", relname, colname) :
3868 : : errmsg("column \"%s\" does not exist", colname),
3869 : : errhint("Perhaps you meant to reference the column \"%s.%s\" or the column \"%s.%s\".",
3870 : : state->rfirst->eref->aliasname,
3871 : : strVal(list_nth(state->rfirst->eref->colnames,
3872 : : state->first - 1)),
3873 : : state->rsecond->eref->aliasname,
3874 : : strVal(list_nth(state->rsecond->eref->colnames,
3875 : : state->second - 1))),
3876 : : parser_errposition(pstate, location)));
3877 : : }
3878 : : }
3879 : :
3880 : : /*
3881 : : * Find ParseNamespaceItem for RTE, if it's visible at all.
3882 : : * We assume an RTE couldn't appear more than once in the namespace lists.
3883 : : */
3884 : : static ParseNamespaceItem *
1398 tgl@sss.pgh.pa.us 3885 : 80 : findNSItemForRTE(ParseState *pstate, RangeTblEntry *rte)
3886 : : {
3887 [ + + ]: 148 : while (pstate != NULL)
3888 : : {
3889 : : ListCell *l;
3890 : :
3891 [ + + + + : 196 : foreach(l, pstate->p_namespace)
+ + ]
3892 : : {
3893 : 128 : ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(l);
3894 : :
3895 [ + + ]: 128 : if (nsitem->p_rte == rte)
3896 : 56 : return nsitem;
3897 : : }
3898 : 68 : pstate = pstate->parentParseState;
3899 : : }
3900 : 24 : return NULL;
3901 : : }
3902 : :
3903 : : /*
3904 : : * Would this RTE be visible, if only the user had written LATERAL?
3905 : : *
3906 : : * This is a helper for deciding whether to issue a HINT about LATERAL.
3907 : : * As such, it doesn't need to be 100% accurate; the HINT could be useful
3908 : : * even if it's not quite right. Hence, we don't delve into fine points
3909 : : * about whether a found nsitem has the appropriate one of p_rel_visible or
3910 : : * p_cols_visible set.
3911 : : */
3912 : : static bool
3913 : 68 : rte_visible_if_lateral(ParseState *pstate, RangeTblEntry *rte)
3914 : : {
3915 : : ParseNamespaceItem *nsitem;
3916 : :
3917 : : /* If LATERAL *is* active, we're clearly barking up the wrong tree */
3918 [ - + ]: 68 : if (pstate->p_lateral_active)
1398 tgl@sss.pgh.pa.us 3919 :UBC 0 : return false;
1398 tgl@sss.pgh.pa.us 3920 :CBC 68 : nsitem = findNSItemForRTE(pstate, rte);
3921 [ + + ]: 68 : if (nsitem)
3922 : : {
3923 : : /* Found it, report whether it's LATERAL-only */
3924 [ + + + + ]: 48 : return nsitem->p_lateral_only && nsitem->p_lateral_ok;
3925 : : }
3926 : 20 : return false;
3927 : : }
3928 : :
3929 : : /*
3930 : : * Would columns in this RTE be visible if qualified?
3931 : : */
3932 : : static bool
3933 : 12 : rte_visible_if_qualified(ParseState *pstate, RangeTblEntry *rte)
3934 : : {
3935 : 12 : ParseNamespaceItem *nsitem = findNSItemForRTE(pstate, rte);
3936 : :
3937 [ + + ]: 12 : if (nsitem)
3938 : : {
3939 : : /* Found it, report whether it's relation-only */
3940 [ + - - + ]: 8 : return nsitem->p_rel_visible && !nsitem->p_cols_visible;
3941 : : }
3942 : 4 : return false;
3943 : : }
3944 : :
3945 : :
3946 : : /*
3947 : : * addRTEPermissionInfo
3948 : : * Creates RTEPermissionInfo for a given RTE and adds it into the
3949 : : * provided list.
3950 : : *
3951 : : * Returns the RTEPermissionInfo and sets rte->perminfoindex.
3952 : : */
3953 : : RTEPermissionInfo *
1384 alvherre@alvh.no-ip. 3954 : 934164 : addRTEPermissionInfo(List **rteperminfos, RangeTblEntry *rte)
3955 : : {
3956 : : RTEPermissionInfo *perminfo;
3957 : :
1341 tgl@sss.pgh.pa.us 3958 [ - + ]: 934164 : Assert(OidIsValid(rte->relid));
1384 alvherre@alvh.no-ip. 3959 [ - + ]: 934164 : Assert(rte->perminfoindex == 0);
3960 : :
3961 : : /* Nope, so make one and add to the list. */
3962 : 934164 : perminfo = makeNode(RTEPermissionInfo);
3963 : 934164 : perminfo->relid = rte->relid;
3964 : 934164 : perminfo->inh = rte->inh;
3965 : : /* Other information is set by fetching the node as and where needed. */
3966 : :
3967 : 934164 : *rteperminfos = lappend(*rteperminfos, perminfo);
3968 : :
3969 : : /* Note its index (1-based!) */
3970 : 934164 : rte->perminfoindex = list_length(*rteperminfos);
3971 : :
3972 : 934164 : return perminfo;
3973 : : }
3974 : :
3975 : : /*
3976 : : * getRTEPermissionInfo
3977 : : * Find RTEPermissionInfo for a given relation in the provided list.
3978 : : *
3979 : : * This is a simple list_nth() operation, though it's good to have the
3980 : : * function for the various sanity checks.
3981 : : */
3982 : : RTEPermissionInfo *
3983 : 2558419 : getRTEPermissionInfo(List *rteperminfos, RangeTblEntry *rte)
3984 : : {
3985 : : RTEPermissionInfo *perminfo;
3986 : :
3987 [ + - ]: 2558419 : if (rte->perminfoindex == 0 ||
3988 [ - + ]: 2558419 : rte->perminfoindex > list_length(rteperminfos))
1318 peter@eisentraut.org 3989 [ # # ]:UBC 0 : elog(ERROR, "invalid perminfoindex %u in RTE with relid %u",
3990 : : rte->perminfoindex, rte->relid);
1384 alvherre@alvh.no-ip. 3991 :CBC 2558419 : perminfo = list_nth_node(RTEPermissionInfo, rteperminfos,
3992 : : rte->perminfoindex - 1);
3993 [ - + ]: 2558419 : if (perminfo->relid != rte->relid)
1384 alvherre@alvh.no-ip. 3994 [ # # ]:UBC 0 : elog(ERROR, "permission info at index %u (with relid=%u) does not match provided RTE (with relid=%u)",
3995 : : rte->perminfoindex, perminfo->relid, rte->relid);
3996 : :
1384 alvherre@alvh.no-ip. 3997 :CBC 2558419 : return perminfo;
3998 : : }
|