1
/*-------------------------------------------------------------------------
6
* Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
7
* Portions Copyright (c) 1994, Regents of the University of California
13
*-------------------------------------------------------------------------
17
#include "catalog/pg_type.h"
18
#include "commands/dbcommands.h"
20
#include "miscadmin.h"
21
#include "nodes/makefuncs.h"
22
#include "nodes/nodeFuncs.h"
23
#include "parser/parsetree.h"
24
#include "parser/parse_coerce.h"
25
#include "parser/parse_expr.h"
26
#include "parser/parse_func.h"
27
#include "parser/parse_relation.h"
28
#include "parser/parse_target.h"
29
#include "parser/parse_type.h"
30
#include "utils/builtins.h"
31
#include "utils/lsyscache.h"
32
#include "utils/typcache.h"
35
static void markTargetListOrigin(ParseState *pstate, TargetEntry *tle,
36
Var *var, int levelsup);
37
static Node *transformAssignmentIndirection(ParseState *pstate,
39
const char *targetName,
43
ListCell *indirection,
46
static List *ExpandColumnRefStar(ParseState *pstate, ColumnRef *cref,
48
static List *ExpandAllTables(ParseState *pstate, int location);
49
static List *ExpandIndirectionStar(ParseState *pstate, A_Indirection *ind,
51
static int FigureColnameInternal(Node *node, char **name);
55
* transformTargetEntry()
56
* Transform any ordinary "expression-type" node into a targetlist entry.
57
* This is exported so that parse_clause.c can generate targetlist entries
58
* for ORDER/GROUP BY items that are not already in the targetlist.
60
* node the (untransformed) parse tree for the value expression.
61
* expr the transformed expression, or NULL if caller didn't do it yet.
62
* colname the column name to be assigned, or NULL if none yet set.
63
* resjunk true if the target should be marked resjunk, ie, it is not
64
* wanted in the final projected tuple.
67
transformTargetEntry(ParseState *pstate,
73
/* Transform the node if caller didn't do it already */
75
expr = transformExpr(pstate, node);
77
if (colname == NULL && !resjunk)
80
* Generate a suitable column name for a column without any explicit
81
* 'AS ColumnName' clause.
83
colname = FigureColname(node);
86
return makeTargetEntry((Expr *) expr,
87
(AttrNumber) pstate->p_next_resno++,
94
* transformTargetList()
95
* Turns a list of ResTarget's into a list of TargetEntry's.
97
* At this point, we don't care whether we are doing SELECT, INSERT,
98
* or UPDATE; we just transform the given expressions (the "val" fields).
101
transformTargetList(ParseState *pstate, List *targetlist)
103
List *p_target = NIL;
106
foreach(o_target, targetlist)
108
ResTarget *res = (ResTarget *) lfirst(o_target);
111
* Check for "something.*". Depending on the complexity of the
112
* "something", the star could appear as the last field in ColumnRef,
113
* or as the last indirection item in A_Indirection.
115
if (IsA(res->val, ColumnRef))
117
ColumnRef *cref = (ColumnRef *) res->val;
119
if (IsA(llast(cref->fields), A_Star))
121
/* It is something.*, expand into multiple items */
122
p_target = list_concat(p_target,
123
ExpandColumnRefStar(pstate, cref,
128
else if (IsA(res->val, A_Indirection))
130
A_Indirection *ind = (A_Indirection *) res->val;
132
if (IsA(llast(ind->indirection), A_Star))
134
/* It is something.*, expand into multiple items */
135
p_target = list_concat(p_target,
136
ExpandIndirectionStar(pstate, ind,
143
* Not "something.*", so transform as a single expression
145
p_target = lappend(p_target,
146
transformTargetEntry(pstate,
158
* transformExpressionList()
160
* This is the identical transformation to transformTargetList, except that
161
* the input list elements are bare expressions without ResTarget decoration,
162
* and the output elements are likewise just expressions without TargetEntry
163
* decoration. We use this for ROW() and VALUES() constructs.
166
transformExpressionList(ParseState *pstate, List *exprlist)
171
foreach(lc, exprlist)
173
Node *e = (Node *) lfirst(lc);
176
* Check for "something.*". Depending on the complexity of the
177
* "something", the star could appear as the last field in ColumnRef,
178
* or as the last indirection item in A_Indirection.
180
if (IsA(e, ColumnRef))
182
ColumnRef *cref = (ColumnRef *) e;
184
if (IsA(llast(cref->fields), A_Star))
186
/* It is something.*, expand into multiple items */
187
result = list_concat(result,
188
ExpandColumnRefStar(pstate, cref,
193
else if (IsA(e, A_Indirection))
195
A_Indirection *ind = (A_Indirection *) e;
197
if (IsA(llast(ind->indirection), A_Star))
199
/* It is something.*, expand into multiple items */
200
result = list_concat(result,
201
ExpandIndirectionStar(pstate, ind,
208
* Not "something.*", so transform as a single expression
210
result = lappend(result,
211
transformExpr(pstate, e));
219
* markTargetListOrigins()
220
* Mark targetlist columns that are simple Vars with the source
221
* table's OID and column number.
223
* Currently, this is done only for SELECT targetlists, since we only
224
* need the info if we are going to send it to the frontend.
227
markTargetListOrigins(ParseState *pstate, List *targetlist)
231
foreach(l, targetlist)
233
TargetEntry *tle = (TargetEntry *) lfirst(l);
235
markTargetListOrigin(pstate, tle, (Var *) tle->expr, 0);
240
* markTargetListOrigin()
241
* If 'var' is a Var of a plain relation, mark 'tle' with its origin
243
* levelsup is an extra offset to interpret the Var's varlevelsup correctly.
245
* This is split out so it can recurse for join references. Note that we
246
* do not drill down into views, but report the view as the column owner.
249
markTargetListOrigin(ParseState *pstate, TargetEntry *tle,
250
Var *var, int levelsup)
256
if (var == NULL || !IsA(var, Var))
258
netlevelsup = var->varlevelsup + levelsup;
259
rte = GetRTEByRangeTablePosn(pstate, var->varno, netlevelsup);
260
attnum = var->varattno;
262
switch (rte->rtekind)
265
/* It's a table or view, report it */
266
tle->resorigtbl = rte->relid;
267
tle->resorigcol = attnum;
270
/* Subselect-in-FROM: copy up from the subselect */
271
if (attnum != InvalidAttrNumber)
273
TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
276
if (ste == NULL || ste->resjunk)
277
elog(ERROR, "subquery %s does not have attribute %d",
278
rte->eref->aliasname, attnum);
279
tle->resorigtbl = ste->resorigtbl;
280
tle->resorigcol = ste->resorigcol;
284
/* Join RTE --- recursively inspect the alias variable */
285
if (attnum != InvalidAttrNumber)
289
Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
290
aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
291
markTargetListOrigin(pstate, tle, aliasvar, netlevelsup);
297
/* not a simple relation, leave it unmarked */
301
* CTE reference: copy up from the subquery, if possible.
302
* If the RTE is a recursive self-reference then we can't do
303
* anything because we haven't finished analyzing it yet.
304
* However, it's no big loss because we must be down inside
305
* the recursive term of a recursive CTE, and so any markings
306
* on the current targetlist are not going to affect the results
309
if (attnum != InvalidAttrNumber && !rte->self_reference)
311
CommonTableExpr *cte = GetCTEForRTE(pstate, rte, netlevelsup);
314
/* should be analyzed by now */
315
Assert(IsA(cte->ctequery, Query));
316
ste = get_tle_by_resno(((Query *) cte->ctequery)->targetList,
318
if (ste == NULL || ste->resjunk)
319
elog(ERROR, "subquery %s does not have attribute %d",
320
rte->eref->aliasname, attnum);
321
tle->resorigtbl = ste->resorigtbl;
322
tle->resorigcol = ste->resorigcol;
330
* transformAssignedExpr()
331
* This is used in INSERT and UPDATE statements only. It prepares an
332
* expression for assignment to a column of the target table.
333
* This includes coercing the given value to the target column's type
334
* (if necessary), and dealing with any subfield names or subscripts
335
* attached to the target column itself. The input expression has
336
* already been through transformExpr().
339
* expr expression to be modified
340
* colname target column name (ie, name of attribute to be assigned to)
341
* attrno target attribute number
342
* indirection subscripts/field names for target column, if any
343
* location error cursor position for the target column, or -1
345
* Returns the modified expression.
347
* Note: location points at the target column name (SET target or INSERT
348
* column name list entry), and must therefore be -1 in an INSERT that
349
* omits the column name list. So we should usually prefer to use
350
* exprLocation(expr) for errors that can happen in a default INSERT.
353
transformAssignedExpr(ParseState *pstate,
360
Oid type_id; /* type of value provided */
361
Oid attrtype; /* type of target column */
363
Relation rd = pstate->p_target_relation;
368
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
369
errmsg("cannot assign to system column \"%s\"",
371
parser_errposition(pstate, location)));
372
attrtype = attnumTypeId(rd, attrno);
373
attrtypmod = rd->rd_att->attrs[attrno - 1]->atttypmod;
376
* If the expression is a DEFAULT placeholder, insert the attribute's
377
* type/typmod into it so that exprType will report the right things. (We
378
* expect that the eventually substituted default expression will in fact
379
* have this type and typmod.) Also, reject trying to update a subfield
380
* or array element with DEFAULT, since there can't be any default for
381
* portions of a column.
383
if (expr && IsA(expr, SetToDefault))
385
SetToDefault *def = (SetToDefault *) expr;
387
def->typeId = attrtype;
388
def->typeMod = attrtypmod;
391
if (IsA(linitial(indirection), A_Indices))
393
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
394
errmsg("cannot set an array element to DEFAULT"),
395
parser_errposition(pstate, location)));
398
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
399
errmsg("cannot set a subfield to DEFAULT"),
400
parser_errposition(pstate, location)));
404
/* Now we can use exprType() safely. */
405
type_id = exprType((Node *) expr);
408
* If there is indirection on the target column, prepare an array or
409
* subfield assignment expression. This will generate a new column value
410
* that the source value has been inserted into, which can then be placed
411
* in the new tuple constructed by INSERT or UPDATE.
417
if (pstate->p_is_insert)
420
* The command is INSERT INTO table (col.something) ... so there
421
* is not really a source value to work with. Insert a NULL
422
* constant as the source value.
424
colVar = (Node *) makeNullConst(attrtype, attrtypmod);
429
* Build a Var for the column to be updated.
431
colVar = (Node *) make_var(pstate,
432
pstate->p_target_rangetblentry,
438
transformAssignmentIndirection(pstate,
444
list_head(indirection),
451
* For normal non-qualified target column, do type checking and
454
Node *orig_expr = (Node *) expr;
457
coerce_to_target_type(pstate,
459
attrtype, attrtypmod,
461
COERCE_IMPLICIT_CAST,
465
(errcode(ERRCODE_DATATYPE_MISMATCH),
466
errmsg("column \"%s\" is of type %s"
467
" but expression is of type %s",
469
format_type_be(attrtype),
470
format_type_be(type_id)),
471
errhint("You will need to rewrite or cast the expression."),
472
parser_errposition(pstate, exprLocation(orig_expr))));
480
* updateTargetListEntry()
481
* This is used in UPDATE statements only. It prepares an UPDATE
482
* TargetEntry for assignment to a column of the target table.
483
* This includes coercing the given value to the target column's type
484
* (if necessary), and dealing with any subfield names or subscripts
485
* attached to the target column itself.
488
* tle target list entry to be modified
489
* colname target column name (ie, name of attribute to be assigned to)
490
* attrno target attribute number
491
* indirection subscripts/field names for target column, if any
492
* location error cursor position (should point at column name), or -1
495
updateTargetListEntry(ParseState *pstate,
502
/* Fix up expression as needed */
503
tle->expr = transformAssignedExpr(pstate,
511
* Set the resno to identify the target column --- the rewriter and
512
* planner depend on this. We also set the resname to identify the target
513
* column, but this is only for debugging purposes; it should not be
514
* relied on. (In particular, it might be out of date in a stored rule.)
516
tle->resno = (AttrNumber) attrno;
517
tle->resname = colname;
522
* Process indirection (field selection or subscripting) of the target
523
* column in INSERT/UPDATE. This routine recurses for multiple levels
524
* of indirection --- but note that several adjacent A_Indices nodes in
525
* the indirection list are treated as a single multidimensional subscript
528
* In the initial call, basenode is a Var for the target column in UPDATE,
529
* or a null Const of the target's type in INSERT. In recursive calls,
530
* basenode is NULL, indicating that a substitute node should be consed up if
533
* targetName is the name of the field or subfield we're assigning to, and
534
* targetIsArray is true if we're subscripting it. These are just for
537
* targetTypeId and targetTypMod indicate the datatype of the object to
538
* be assigned to (initially the target column, later some subobject).
540
* indirection is the sublist remaining to process. When it's NULL, we're
541
* done recursing and can just coerce and return the RHS.
543
* rhs is the already-transformed value to be assigned; note it has not been
544
* coerced to any particular type.
546
* location is the cursor error position for any errors. (Note: this points
547
* to the head of the target clause, eg "foo" in "foo.bar[baz]". Later we
548
* might want to decorate indirection cells with their own location info,
549
* in which case the location argument could probably be dropped.)
552
transformAssignmentIndirection(ParseState *pstate,
554
const char *targetName,
558
ListCell *indirection,
563
List *subscripts = NIL;
564
bool isSlice = false;
567
if (indirection && !basenode)
569
/* Set up a substitution. We reuse CaseTestExpr for this. */
570
CaseTestExpr *ctest = makeNode(CaseTestExpr);
572
ctest->typeId = targetTypeId;
573
ctest->typeMod = targetTypMod;
574
basenode = (Node *) ctest;
578
* We have to split any field-selection operations apart from
579
* subscripting. Adjacent A_Indices nodes have to be treated as a single
580
* multidimensional subscript operation.
582
for_each_cell(i, indirection)
586
if (IsA(n, A_Indices))
588
subscripts = lappend(subscripts, n);
589
if (((A_Indices *) n)->lidx != NULL)
592
else if (IsA(n, A_Star))
595
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
596
errmsg("row expansion via \"*\" is not supported here"),
597
parser_errposition(pstate, location)));
607
Assert(IsA(n, String));
609
/* process subscripts before this field selection */
612
Oid elementTypeId = transformArrayType(targetTypeId);
613
Oid typeNeeded = isSlice ? targetTypeId : elementTypeId;
615
/* recurse to create appropriate RHS for array assign */
616
rhs = transformAssignmentIndirection(pstate,
625
/* process subscripts */
626
return (Node *) transformArraySubscripts(pstate,
635
/* No subscripts, so can process field selection here */
637
typrelid = typeidTypeRelid(targetTypeId);
640
(errcode(ERRCODE_DATATYPE_MISMATCH),
641
errmsg("cannot assign to field \"%s\" of column \"%s\" because its type %s is not a composite type",
642
strVal(n), targetName,
643
format_type_be(targetTypeId)),
644
parser_errposition(pstate, location)));
646
attnum = get_attnum(typrelid, strVal(n));
647
if (attnum == InvalidAttrNumber)
649
(errcode(ERRCODE_UNDEFINED_COLUMN),
650
errmsg("cannot assign to field \"%s\" of column \"%s\" because there is no such column in data type %s",
651
strVal(n), targetName,
652
format_type_be(targetTypeId)),
653
parser_errposition(pstate, location)));
656
(errcode(ERRCODE_UNDEFINED_COLUMN),
657
errmsg("cannot assign to system column \"%s\"",
659
parser_errposition(pstate, location)));
661
get_atttypetypmod(typrelid, attnum,
662
&fieldTypeId, &fieldTypMod);
664
/* recurse to create appropriate RHS for field assign */
665
rhs = transformAssignmentIndirection(pstate,
675
/* and build a FieldStore node */
676
fstore = makeNode(FieldStore);
677
fstore->arg = (Expr *) basenode;
678
fstore->newvals = list_make1(rhs);
679
fstore->fieldnums = list_make1_int(attnum);
680
fstore->resulttype = targetTypeId;
682
return (Node *) fstore;
686
/* process trailing subscripts, if any */
689
Oid elementTypeId = transformArrayType(targetTypeId);
690
Oid typeNeeded = isSlice ? targetTypeId : elementTypeId;
692
/* recurse to create appropriate RHS for array assign */
693
rhs = transformAssignmentIndirection(pstate,
702
/* process subscripts */
703
return (Node *) transformArraySubscripts(pstate,
712
/* base case: just coerce RHS to match target type ID */
714
result = coerce_to_target_type(pstate,
716
targetTypeId, targetTypMod,
718
COERCE_IMPLICIT_CAST,
724
(errcode(ERRCODE_DATATYPE_MISMATCH),
725
errmsg("array assignment to \"%s\" requires type %s"
726
" but expression is of type %s",
728
format_type_be(targetTypeId),
729
format_type_be(exprType(rhs))),
730
errhint("You will need to rewrite or cast the expression."),
731
parser_errposition(pstate, location)));
734
(errcode(ERRCODE_DATATYPE_MISMATCH),
735
errmsg("subfield \"%s\" is of type %s"
736
" but expression is of type %s",
738
format_type_be(targetTypeId),
739
format_type_be(exprType(rhs))),
740
errhint("You will need to rewrite or cast the expression."),
741
parser_errposition(pstate, location)));
749
* checkInsertTargets -
750
* generate a list of INSERT column targets if not supplied, or
751
* test supplied column names to make sure they are in target table.
752
* Also return an integer list of the columns' attribute numbers.
755
checkInsertTargets(ParseState *pstate, List *cols, List **attrnos)
762
* Generate default column list for INSERT.
764
Form_pg_attribute *attr = pstate->p_target_relation->rd_att->attrs;
765
int numcol = pstate->p_target_relation->rd_rel->relnatts;
768
for (i = 0; i < numcol; i++)
772
if (attr[i]->attisdropped)
775
col = makeNode(ResTarget);
776
col->name = pstrdup(NameStr(attr[i]->attname));
777
col->indirection = NIL;
780
cols = lappend(cols, col);
781
*attrnos = lappend_int(*attrnos, i + 1);
787
* Do initial validation of user-supplied INSERT column list.
789
Bitmapset *wholecols = NULL;
790
Bitmapset *partialcols = NULL;
795
ResTarget *col = (ResTarget *) lfirst(tl);
796
char *name = col->name;
799
/* Lookup column name, ereport on failure */
800
attrno = attnameAttNum(pstate->p_target_relation, name, false);
801
if (attrno == InvalidAttrNumber)
803
(errcode(ERRCODE_UNDEFINED_COLUMN),
804
errmsg("column \"%s\" of relation \"%s\" does not exist",
806
RelationGetRelationName(pstate->p_target_relation)),
807
parser_errposition(pstate, col->location)));
810
* Check for duplicates, but only of whole columns --- we allow
811
* INSERT INTO foo (col.subcol1, col.subcol2)
813
if (col->indirection == NIL)
815
/* whole column; must not have any other assignment */
816
if (bms_is_member(attrno, wholecols) ||
817
bms_is_member(attrno, partialcols))
819
(errcode(ERRCODE_DUPLICATE_COLUMN),
820
errmsg("column \"%s\" specified more than once",
822
parser_errposition(pstate, col->location)));
823
wholecols = bms_add_member(wholecols, attrno);
827
/* partial column; must not have any whole assignment */
828
if (bms_is_member(attrno, wholecols))
830
(errcode(ERRCODE_DUPLICATE_COLUMN),
831
errmsg("column \"%s\" specified more than once",
833
parser_errposition(pstate, col->location)));
834
partialcols = bms_add_member(partialcols, attrno);
837
*attrnos = lappend_int(*attrnos, attrno);
845
* ExpandColumnRefStar()
846
* Transforms foo.* into a list of expressions or targetlist entries.
848
* This handles the case where '*' appears as the last or only item in a
849
* ColumnRef. The code is shared between the case of foo.* at the top level
850
* in a SELECT target list (where we want TargetEntry nodes in the result)
851
* and foo.* in a ROW() or VALUES() construct (where we want just bare
854
* The referenced columns are marked as requiring SELECT access.
857
ExpandColumnRefStar(ParseState *pstate, ColumnRef *cref,
860
List *fields = cref->fields;
861
int numnames = list_length(fields);
866
* Target item is a bare '*', expand all tables
868
* (e.g., SELECT * FROM emp, dept)
870
* Since the grammar only accepts bare '*' at top level of SELECT, we
871
* need not handle the targetlist==false case here.
874
return ExpandAllTables(pstate, cref->location);
879
* Target item is relation.*, expand that table
881
* (e.g., SELECT emp.*, dname FROM emp, dept)
893
relname = strVal(linitial(fields));
896
schemaname = strVal(linitial(fields));
897
relname = strVal(lsecond(fields));
901
char *name1 = strVal(linitial(fields));
904
* We check the catalog name and then ignore it.
906
if (strcmp(name1, get_database_name(MyDatabaseId)) != 0)
908
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
909
errmsg("cross-database references are not implemented: %s",
910
NameListToString(fields)),
911
parser_errposition(pstate, cref->location)));
912
schemaname = strVal(lsecond(fields));
913
relname = strVal(lthird(fields));
918
(errcode(ERRCODE_SYNTAX_ERROR),
919
errmsg("improper qualified name (too many dotted names): %s",
920
NameListToString(fields)),
921
parser_errposition(pstate, cref->location)));
922
schemaname = NULL; /* keep compiler quiet */
927
rte = refnameRangeTblEntry(pstate, schemaname, relname, cref->location,
930
rte = addImplicitRTE(pstate,
931
makeRangeVar(schemaname, relname,
934
rtindex = RTERangeTablePosn(pstate, rte, &sublevels_up);
938
/* expandRelAttrs handles permissions marking */
939
return expandRelAttrs(pstate, rte, rtindex, sublevels_up,
947
expandRTE(rte, rtindex, sublevels_up, cref->location, false,
951
* Require read access to the table. This is normally redundant
952
* with the markVarForSelectPriv calls below, but not if the table
955
rte->requiredPerms |= ACL_SELECT;
957
/* Require read access to each column */
960
Var *var = (Var *) lfirst(l);
962
markVarForSelectPriv(pstate, var, rte);
972
* Transforms '*' (in the target list) into a list of targetlist entries.
974
* tlist entries are generated for each relation appearing in the query's
975
* varnamespace. We do not consider relnamespace because that would include
976
* input tables of aliasless JOINs, NEW/OLD pseudo-entries, implicit RTEs,
979
* The referenced relations/columns are marked as requiring SELECT access.
982
ExpandAllTables(ParseState *pstate, int location)
987
/* Check for SELECT *; */
988
if (!pstate->p_varnamespace)
990
(errcode(ERRCODE_SYNTAX_ERROR),
991
errmsg("SELECT * with no tables specified is not valid"),
992
parser_errposition(pstate, location)));
994
foreach(l, pstate->p_varnamespace)
996
RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
997
int rtindex = RTERangeTablePosn(pstate, rte, NULL);
999
target = list_concat(target,
1000
expandRelAttrs(pstate, rte, rtindex, 0,
1008
* ExpandIndirectionStar()
1009
* Transforms foo.* into a list of expressions or targetlist entries.
1011
* This handles the case where '*' appears as the last item in A_Indirection.
1012
* The code is shared between the case of foo.* at the top level in a SELECT
1013
* target list (where we want TargetEntry nodes in the result) and foo.* in
1014
* a ROW() or VALUES() construct (where we want just bare expressions).
1017
ExpandIndirectionStar(ParseState *pstate, A_Indirection *ind,
1022
TupleDesc tupleDesc;
1026
/* Strip off the '*' to create a reference to the rowtype object */
1027
ind = copyObject(ind);
1028
ind->indirection = list_truncate(ind->indirection,
1029
list_length(ind->indirection) - 1);
1031
/* And transform that */
1032
expr = transformExpr(pstate, (Node *) ind);
1035
* Verify it's a composite type, and get the tupdesc. We use
1036
* get_expr_result_type() because that can handle references to functions
1037
* returning anonymous record types. If that fails, use
1038
* lookup_rowtype_tupdesc(), which will almost certainly fail as well, but
1039
* it will give an appropriate error message.
1041
* If it's a Var of type RECORD, we have to work even harder: we have to
1042
* find what the Var refers to, and pass that to get_expr_result_type.
1043
* That task is handled by expandRecordVariable().
1045
if (IsA(expr, Var) &&
1046
((Var *) expr)->vartype == RECORDOID)
1047
tupleDesc = expandRecordVariable(pstate, (Var *) expr, 0);
1048
else if (get_expr_result_type(expr, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
1049
tupleDesc = lookup_rowtype_tupdesc_copy(exprType(expr),
1053
/* Generate a list of references to the individual fields */
1054
numAttrs = tupleDesc->natts;
1055
for (i = 0; i < numAttrs; i++)
1057
Form_pg_attribute att = tupleDesc->attrs[i];
1060
if (att->attisdropped)
1064
* If we got a whole-row Var from the rowtype reference, we can expand
1065
* the fields as simple Vars. Otherwise we must generate multiple
1066
* copies of the rowtype reference and do FieldSelects.
1068
if (IsA(expr, Var) &&
1069
((Var *) expr)->varattno == InvalidAttrNumber)
1071
Var *var = (Var *) expr;
1074
newvar = makeVar(var->varno,
1079
newvar->location = var->location;
1081
fieldnode = (Node *) newvar;
1085
FieldSelect *fselect = makeNode(FieldSelect);
1087
fselect->arg = (Expr *) copyObject(expr);
1088
fselect->fieldnum = i + 1;
1089
fselect->resulttype = att->atttypid;
1090
fselect->resulttypmod = att->atttypmod;
1092
fieldnode = (Node *) fselect;
1097
/* add TargetEntry decoration */
1100
te = makeTargetEntry((Expr *) fieldnode,
1101
(AttrNumber) pstate->p_next_resno++,
1102
pstrdup(NameStr(att->attname)),
1104
result = lappend(result, te);
1107
result = lappend(result, fieldnode);
1114
* expandRecordVariable
1115
* Get the tuple descriptor for a Var of type RECORD, if possible.
1117
* Since no actual table or view column is allowed to have type RECORD, such
1118
* a Var must refer to a JOIN or FUNCTION RTE or to a subquery output. We
1119
* drill down to find the ultimate defining expression and attempt to infer
1120
* the tupdesc from it. We ereport if we can't determine the tupdesc.
1122
* levelsup is an extra offset to interpret the Var's varlevelsup correctly.
1125
expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
1127
TupleDesc tupleDesc;
1133
/* Check my caller didn't mess up */
1134
Assert(IsA(var, Var));
1135
Assert(var->vartype == RECORDOID);
1137
netlevelsup = var->varlevelsup + levelsup;
1138
rte = GetRTEByRangeTablePosn(pstate, var->varno, netlevelsup);
1139
attnum = var->varattno;
1141
if (attnum == InvalidAttrNumber)
1143
/* Whole-row reference to an RTE, so expand the known fields */
1150
expandRTE(rte, var->varno, 0, var->location, false,
1153
tupleDesc = CreateTemplateTupleDesc(list_length(vars), false);
1155
forboth(lname, names, lvar, vars)
1157
char *label = strVal(lfirst(lname));
1158
Node *varnode = (Node *) lfirst(lvar);
1160
TupleDescInitEntry(tupleDesc, i,
1163
exprTypmod(varnode),
1167
Assert(lname == NULL && lvar == NULL); /* lists same length? */
1172
expr = (Node *) var; /* default if we can't drill down */
1174
switch (rte->rtekind)
1181
* This case should not occur: a column of a table or values list
1182
* shouldn't have type RECORD. Fall through and fail (most
1183
* likely) at the bottom.
1188
/* Subselect-in-FROM: examine sub-select's output expr */
1189
TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
1192
if (ste == NULL || ste->resjunk)
1193
elog(ERROR, "subquery %s does not have attribute %d",
1194
rte->eref->aliasname, attnum);
1195
expr = (Node *) ste->expr;
1199
* Recurse into the sub-select to see what its Var refers
1200
* to. We have to build an additional level of ParseState
1201
* to keep in step with varlevelsup in the subselect.
1203
ParseState mypstate;
1205
MemSet(&mypstate, 0, sizeof(mypstate));
1206
mypstate.parentParseState = pstate;
1207
mypstate.p_rtable = rte->subquery->rtable;
1208
/* don't bother filling the rest of the fake pstate */
1210
return expandRecordVariable(&mypstate, (Var *) expr, 0);
1212
/* else fall through to inspect the expression */
1216
/* Join RTE --- recursively inspect the alias variable */
1217
Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
1218
expr = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
1220
return expandRecordVariable(pstate, (Var *) expr, netlevelsup);
1221
/* else fall through to inspect the expression */
1226
* We couldn't get here unless a function is declared with one of
1227
* its result columns as RECORD, which is not allowed.
1231
/* CTE reference: examine subquery's output expr */
1232
if (!rte->self_reference)
1234
CommonTableExpr *cte = GetCTEForRTE(pstate, rte, netlevelsup);
1237
/* should be analyzed by now */
1238
Assert(IsA(cte->ctequery, Query));
1239
ste = get_tle_by_resno(((Query *) cte->ctequery)->targetList,
1241
if (ste == NULL || ste->resjunk)
1242
elog(ERROR, "subquery %s does not have attribute %d",
1243
rte->eref->aliasname, attnum);
1244
expr = (Node *) ste->expr;
1248
* Recurse into the CTE to see what its Var refers to. We
1249
* have to build an additional level of ParseState to keep
1250
* in step with varlevelsup in the CTE; furthermore it
1251
* could be an outer CTE.
1253
ParseState mypstate;
1256
MemSet(&mypstate, 0, sizeof(mypstate));
1257
/* this loop must work, since GetCTEForRTE did */
1259
levelsup < rte->ctelevelsup + netlevelsup;
1261
pstate = pstate->parentParseState;
1262
mypstate.parentParseState = pstate;
1263
mypstate.p_rtable = ((Query *) cte->ctequery)->rtable;
1264
/* don't bother filling the rest of the fake pstate */
1266
return expandRecordVariable(&mypstate, (Var *) expr, 0);
1268
/* else fall through to inspect the expression */
1274
* We now have an expression we can't expand any more, so see if
1275
* get_expr_result_type() can do anything with it. If not, pass to
1276
* lookup_rowtype_tupdesc() which will probably fail, but will give an
1277
* appropriate error message while failing.
1279
if (get_expr_result_type(expr, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
1280
tupleDesc = lookup_rowtype_tupdesc_copy(exprType(expr),
1289
* if the name of the resulting column is not specified in the target
1290
* list, we have to guess a suitable name. The SQL spec provides some
1291
* guidance, but not much...
1293
* Note that the argument is the *untransformed* parse tree for the target
1294
* item. This is a shade easier to work with than the transformed tree.
1297
FigureColname(Node *node)
1301
FigureColnameInternal(node, &name);
1304
/* default result if we can't guess anything */
1309
FigureColnameInternal(Node *node, char **name)
1316
switch (nodeTag(node))
1323
/* find last field name, if any, ignoring "*" */
1324
foreach(l, ((ColumnRef *) node)->fields)
1326
Node *i = lfirst(l);
1338
case T_A_Indirection:
1340
A_Indirection *ind = (A_Indirection *) node;
1344
/* find last field name, if any, ignoring "*" and subscripts */
1345
foreach(l, ind->indirection)
1347
Node *i = lfirst(l);
1357
return FigureColnameInternal(ind->arg, name);
1361
*name = strVal(llast(((FuncCall *) node)->funcname));
1364
/* make nullif() act like a regular function */
1365
if (((A_Expr *) node)->kind == AEXPR_NULLIF)
1372
strength = FigureColnameInternal(((TypeCast *) node)->arg,
1376
if (((TypeCast *) node)->typename != NULL)
1378
*name = strVal(llast(((TypeCast *) node)->typename->names));
1384
strength = FigureColnameInternal((Node *) ((CaseExpr *) node)->defresult,
1393
/* make ARRAY[] act like a function */
1397
/* make ROW() act like a function */
1400
case T_CoalesceExpr:
1401
/* make coalesce() act like a regular function */
1405
/* make greatest/least act like a regular function */
1406
switch (((MinMaxExpr *) node)->op)
1417
/* make SQL/XML functions act like a regular function */
1418
switch (((XmlExpr *) node)->op)
1421
*name = "xmlconcat";
1424
*name = "xmlelement";
1427
*name = "xmlforest";
1438
case IS_XMLSERIALIZE:
1439
*name = "xmlserialize";
1446
case T_XmlSerialize:
1447
*name = "xmlserialize";