1 /*-------------------------------------------------------------------------
4 * transform the parse tree into a query tree
6 * Copyright (c) 1994, Regents of the University of California
10 * $Header: /cvsroot/pgsql/src/backend/parser/analyze.c,v 1.29 1997/07/30 04:42:26 vadim Exp $
12 *-------------------------------------------------------------------------
18 #include "nodes/nodes.h"
19 #include "nodes/params.h"
20 #include "nodes/primnodes.h"
21 #include "nodes/parsenodes.h"
22 #include "nodes/relation.h"
23 #include "parse.h" /* for AND, OR, etc. */
24 #include "catalog/pg_type.h" /* for INT4OID, etc. */
25 #include "catalog/pg_proc.h"
26 #include "utils/elog.h"
27 #include "utils/builtins.h" /* namecmp(), textout() */
28 #include "utils/lsyscache.h"
29 #include "utils/palloc.h"
30 #include "utils/mcxt.h"
31 #include "utils/syscache.h"
32 #include "utils/acl.h"
33 #include "parser/parse_query.h"
34 #include "parser/parse_state.h"
35 #include "nodes/makefuncs.h" /* for makeResdom(), etc. */
36 #include "nodes/nodeFuncs.h"
37 #include "commands/sequence.h"
39 #include "optimizer/clauses.h"
40 #include "access/heapam.h"
42 #include "miscadmin.h"
44 #include "port-protos.h" /* strdup() */
46 /* convert the parse tree into a query tree */
47 static Query *transformStmt(ParseState *pstate, Node *stmt);
49 static Query *transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt);
50 static Query *transformInsertStmt(ParseState *pstate, AppendStmt *stmt);
51 static Query *transformIndexStmt(ParseState *pstate, IndexStmt *stmt);
52 static Query *transformExtendStmt(ParseState *pstate, ExtendStmt *stmt);
53 static Query *transformRuleStmt(ParseState *query, RuleStmt *stmt);
54 static Query *transformSelectStmt(ParseState *pstate, RetrieveStmt *stmt);
55 static Query *transformUpdateStmt(ParseState *pstate, ReplaceStmt *stmt);
56 static Query *transformCursorStmt(ParseState *pstate, CursorStmt *stmt);
57 static Node *handleNestedDots(ParseState *pstate, Attr *attr, int *curr_resno);
59 #define EXPR_COLUMN_FIRST 1
60 #define EXPR_RELATION_FIRST 2
61 static Node *transformExpr(ParseState *pstate, Node *expr, int precedence);
62 static Node *transformIdent(ParseState *pstate, Node *expr, int precedence);
64 static void makeRangeTable(ParseState *pstate, char *relname, List *frmList);
65 static List *expandAllTables(ParseState *pstate);
66 static char *figureColname(Node *expr, Node *resval);
67 static List *makeTargetNames(ParseState *pstate, List *cols);
68 static List *transformTargetList(ParseState *pstate, List *targetlist);
69 static TargetEntry *make_targetlist_expr(ParseState *pstate,
70 char *colname, Node *expr,
72 static bool inWhereClause = false;
73 static Node *transformWhereClause(ParseState *pstate, Node *a_expr);
74 static List *transformGroupClause(ParseState *pstate, List *grouplist,
76 static List *transformSortClause(ParseState *pstate,
77 List *orderlist, List *targetlist,
80 static void parseFromClause(ParseState *pstate, List *frmList);
81 static Node *ParseFunc(ParseState *pstate, char *funcname,
82 List *fargs, int *curr_resno);
83 static List *setup_tlist(char *attname, Oid relid);
84 static List *setup_base_tlist(Oid typeid);
85 static void make_arguments(int nargs, List *fargs, Oid *input_typeids,
86 Oid *function_typeids);
87 static void AddAggToParseState(ParseState *pstate, Aggreg *aggreg);
88 static void finalizeAggregates(ParseState *pstate, Query *qry);
89 static void parseCheckAggregates(ParseState *pstate, Query *qry);
91 /*****************************************************************************
93 *****************************************************************************/
97 * allocate and initialize a new ParseState.
98 * the CALLERS is responsible for freeing the ParseState* returned
107 pstate = malloc(sizeof(ParseState));
108 pstate->p_last_resno = 1;
109 pstate->p_rtable = NIL;
110 pstate->p_numAgg = 0;
111 pstate->p_aggs = NIL;
112 pstate->p_is_insert = false;
113 pstate->p_insert_columns = NIL;
114 pstate->p_is_update = false;
115 pstate->p_is_rule = false;
116 pstate->p_target_relation = NULL;
117 pstate->p_target_rangetblentry = NULL;
124 * analyze a list of parse trees and transform them if necessary.
126 * Returns a list of transformed parse trees. Optimizable statements are
127 * all transformed to Query while the rest stays the same.
129 * CALLER is responsible for freeing the QueryTreeList* returned
132 parse_analyze(List *pl)
134 QueryTreeList *result;
138 result = malloc(sizeof(QueryTreeList));
139 result->len = length(pl);
140 result->qtrees = (Query**)malloc(result->len * sizeof(Query*));
142 inWhereClause = false; /* to avoid nextval(sequence) in WHERE */
145 pstate = makeParseState();
146 result->qtrees[i++] = transformStmt(pstate, lfirst(pl));
148 if (pstate->p_target_relation != NULL)
149 heap_close(pstate->p_target_relation);
158 * transform a Parse tree. If it is an optimizable statement, turn it
162 transformStmt(ParseState* pstate, Node *parseTree)
164 Query* result = NULL;
166 switch(nodeTag(parseTree)) {
167 /*------------------------
168 * Non-optimizable statements
169 *------------------------
172 result = transformIndexStmt(pstate, (IndexStmt *)parseTree);
176 result = transformExtendStmt(pstate, (ExtendStmt *)parseTree);
180 result = transformRuleStmt(pstate, (RuleStmt *)parseTree);
185 ViewStmt *n = (ViewStmt *)parseTree;
186 n->query = (Query *)transformStmt(pstate, (Node*)n->query);
187 result = makeNode(Query);
188 result->commandType = CMD_UTILITY;
189 result->utilityStmt = (Node*)n;
195 MemoryContext oldcontext;
196 /* make sure that this Query is allocated in TopMemory context
197 because vacuum spans transactions and we don't want to lose
198 the vacuum Query due to end-of-transaction free'ing*/
199 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
200 result = makeNode(Query);
201 result->commandType = CMD_UTILITY;
202 result->utilityStmt = (Node*)parseTree;
203 MemoryContextSwitchTo(oldcontext);
209 ExplainStmt *n = (ExplainStmt *)parseTree;
210 result = makeNode(Query);
211 result->commandType = CMD_UTILITY;
212 n->query = transformStmt(pstate, (Node*)n->query);
213 result->utilityStmt = (Node*)parseTree;
217 /*------------------------
218 * Optimizable statements
219 *------------------------
222 result = transformInsertStmt(pstate, (AppendStmt *)parseTree);
226 result = transformDeleteStmt(pstate, (DeleteStmt *)parseTree);
230 result = transformUpdateStmt(pstate, (ReplaceStmt *)parseTree);
234 result = transformCursorStmt(pstate, (CursorStmt *)parseTree);
238 result = transformSelectStmt(pstate, (RetrieveStmt *)parseTree);
243 * other statments don't require any transformation-- just
244 * return the original parsetree
246 result = makeNode(Query);
247 result->commandType = CMD_UTILITY;
248 result->utilityStmt = (Node*)parseTree;
255 * transformDeleteStmt -
256 * transforms a Delete Statement
259 transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
261 Query *qry = makeNode(Query);
263 qry->commandType = CMD_DELETE;
265 /* set up a range table */
266 makeRangeTable(pstate, stmt->relname, NULL);
268 qry->uniqueFlag = NULL;
270 /* fix where clause */
271 qry->qual = transformWhereClause(pstate, stmt->whereClause);
273 qry->rtable = pstate->p_rtable;
274 qry->resultRelation = refnameRangeTablePosn(pstate->p_rtable, stmt->relname);
276 /* make sure we don't have aggregates in the where clause */
277 if (pstate->p_numAgg > 0)
278 parseCheckAggregates(pstate, qry);
284 * transformInsertStmt -
285 * transform an Insert Statement
288 transformInsertStmt(ParseState *pstate, AppendStmt *stmt)
290 Query *qry = makeNode(Query); /* make a new query tree */
292 qry->commandType = CMD_INSERT;
293 pstate->p_is_insert = true;
295 /* set up a range table */
296 makeRangeTable(pstate, stmt->relname, stmt->fromClause);
298 qry->uniqueFlag = NULL;
300 /* fix the target list */
301 pstate->p_insert_columns = makeTargetNames(pstate, stmt->cols);
303 qry->targetList = transformTargetList(pstate, stmt->targetList);
305 /* fix where clause */
306 qry->qual = transformWhereClause(pstate, stmt->whereClause);
308 /* now the range table will not change */
309 qry->rtable = pstate->p_rtable;
310 qry->resultRelation = refnameRangeTablePosn(pstate->p_rtable, stmt->relname);
312 if (pstate->p_numAgg > 0)
313 finalizeAggregates(pstate, qry);
319 * transformIndexStmt -
320 * transforms the qualification of the index statement
323 transformIndexStmt(ParseState *pstate, IndexStmt *stmt)
328 q->commandType = CMD_UTILITY;
330 /* take care of the where clause */
331 stmt->whereClause = transformWhereClause(pstate,stmt->whereClause);
332 stmt->rangetable = pstate->p_rtable;
334 q->utilityStmt = (Node*)stmt;
340 * transformExtendStmt -
341 * transform the qualifications of the Extend Index Statement
345 transformExtendStmt(ParseState *pstate, ExtendStmt *stmt)
350 q->commandType = CMD_UTILITY;
352 /* take care of the where clause */
353 stmt->whereClause = transformWhereClause(pstate,stmt->whereClause);
354 stmt->rangetable = pstate->p_rtable;
356 q->utilityStmt = (Node*)stmt;
361 * transformRuleStmt -
362 * transform a Create Rule Statement. The actions is a list of parse
363 * trees which is transformed into a list of query trees.
366 transformRuleStmt(ParseState *pstate, RuleStmt *stmt)
372 q->commandType = CMD_UTILITY;
374 actions = stmt->actions;
376 * transform each statment, like parse_analyze()
378 while (actions != NIL) {
380 * NOTE: 'CURRENT' must always have a varno equal to 1 and 'NEW'
383 addRangeTableEntry(pstate, stmt->object->relname, "*CURRENT*",
385 addRangeTableEntry(pstate, stmt->object->relname, "*NEW*",
388 pstate->p_last_resno = 1;
389 pstate->p_is_rule = true; /* for expand all */
390 pstate->p_numAgg = 0;
391 pstate->p_aggs = NULL;
393 lfirst(actions) = transformStmt(pstate, lfirst(actions));
394 actions = lnext(actions);
397 /* take care of the where clause */
398 stmt->whereClause = transformWhereClause(pstate,stmt->whereClause);
400 q->utilityStmt = (Node*)stmt;
406 * transformSelectStmt -
407 * transforms a Select Statement
411 transformSelectStmt(ParseState *pstate, RetrieveStmt *stmt)
413 Query *qry = makeNode(Query);
415 qry->commandType = CMD_SELECT;
417 /* set up a range table */
418 makeRangeTable(pstate, NULL, stmt->fromClause);
420 qry->uniqueFlag = stmt->unique;
422 qry->into = stmt->into;
423 qry->isPortal = FALSE;
425 /* fix the target list */
426 qry->targetList = transformTargetList(pstate, stmt->targetList);
428 /* fix where clause */
429 qry->qual = transformWhereClause(pstate,stmt->whereClause);
431 /* fix order clause */
432 qry->sortClause = transformSortClause(pstate,
437 /* fix group by clause */
438 qry->groupClause = transformGroupClause(pstate,
441 qry->rtable = pstate->p_rtable;
443 if (pstate->p_numAgg > 0)
444 finalizeAggregates(pstate, qry);
450 * transformUpdateStmt -
451 * transforms an update statement
455 transformUpdateStmt(ParseState *pstate, ReplaceStmt *stmt)
457 Query *qry = makeNode(Query);
459 qry->commandType = CMD_UPDATE;
460 pstate->p_is_update = true;
462 * the FROM clause is non-standard SQL syntax. We used to be able to
463 * do this with REPLACE in POSTQUEL so we keep the feature.
465 makeRangeTable(pstate, stmt->relname, stmt->fromClause);
467 /* fix the target list */
468 qry->targetList = transformTargetList(pstate, stmt->targetList);
470 /* fix where clause */
471 qry->qual = transformWhereClause(pstate,stmt->whereClause);
473 qry->rtable = pstate->p_rtable;
474 qry->resultRelation = refnameRangeTablePosn(pstate->p_rtable, stmt->relname);
476 /* make sure we don't have aggregates in the where clause */
477 if (pstate->p_numAgg > 0)
478 parseCheckAggregates(pstate, qry);
484 * transformCursorStmt -
485 * transform a Create Cursor Statement
489 transformCursorStmt(ParseState *pstate, CursorStmt *stmt)
491 Query *qry = makeNode(Query);
494 * in the old days, a cursor statement is a 'retrieve into portal';
495 * If you change the following, make sure you also go through the code
496 * in various places that tests the kind of operation.
498 qry->commandType = CMD_SELECT;
500 /* set up a range table */
501 makeRangeTable(pstate, NULL, stmt->fromClause);
503 qry->uniqueFlag = stmt->unique;
505 qry->into = stmt->portalname;
506 qry->isPortal = TRUE;
507 qry->isBinary = stmt->binary; /* internal portal */
509 /* fix the target list */
510 qry->targetList = transformTargetList(pstate, stmt->targetList);
512 /* fix where clause */
513 qry->qual = transformWhereClause(pstate,stmt->whereClause);
515 /* fix order clause */
516 qry->sortClause = transformSortClause(pstate,
520 /* fix group by clause */
521 qry->groupClause = transformGroupClause(pstate,
525 qry->rtable = pstate->p_rtable;
527 if (pstate->p_numAgg > 0)
528 finalizeAggregates(pstate, qry);
533 /*****************************************************************************
535 * Transform Exprs, Aggs, etc.
537 *****************************************************************************/
541 * analyze and transform expressions. Type checking and type casting is
542 * done here. The optimizer and the executor cannot handle the original
543 * (raw) expressions collected by the parse tree. Hence the transformation
547 transformExpr(ParseState *pstate, Node *expr, int precedence)
554 switch(nodeTag(expr)) {
556 Attr *att = (Attr *)expr;
559 /* what if att.attrs == "*"?? */
560 temp = handleNestedDots(pstate, att, &pstate->p_last_resno);
561 if (att->indirection != NIL) {
562 List *idx = att->indirection;
564 A_Indices *ai = (A_Indices *)lfirst(idx);
565 Node *lexpr=NULL, *uexpr;
566 uexpr = transformExpr(pstate, ai->uidx, precedence); /* must exists */
567 if (exprType(uexpr) != INT4OID)
568 elog(WARN, "array index expressions must be int4's");
569 if (ai->lidx != NULL) {
570 lexpr = transformExpr(pstate, ai->lidx, precedence);
571 if (exprType(lexpr) != INT4OID)
572 elog(WARN, "array index expressions must be int4's");
576 if (ai->lidx!=NULL) pfree(ai->lidx);
580 /* note we reuse the list of indices, make sure we don't free
581 them! Otherwise, make a new list here */
584 result = (Node*)make_array_ref(temp, att->indirection);
591 A_Const *con= (A_Const *)expr;
592 Value *val = &con->val;
593 if (con->typename != NULL) {
594 result = parser_typecast(val, con->typename, -1);
596 result = (Node *)make_const(val);
601 ParamNo *pno = (ParamNo *)expr;
606 paramno = pno->number;
607 toid = param_type(paramno);
608 if (!OidIsValid(toid)) {
609 elog(WARN, "Parameter '$%d' is out of range",
612 param = makeNode(Param);
613 param->paramkind = PARAM_NUM;
614 param->paramid = (AttrNumber) paramno;
615 param->paramname = "<unnamed>";
616 param->paramtype = (Oid)toid;
617 param->param_tlist = (List*) NULL;
619 result = (Node *)param;
623 A_Expr *a = (A_Expr *)expr;
628 Node *lexpr = transformExpr(pstate, a->lexpr, precedence);
629 Node *rexpr = transformExpr(pstate, a->rexpr, precedence);
630 result = (Node *)make_op(a->opname, lexpr, rexpr);
635 Node *lexpr = transformExpr(pstate, a->lexpr, precedence);
636 result = ParseFunc(pstate,
637 "nullvalue", lcons(lexpr, NIL),
638 &pstate->p_last_resno);
643 Node *lexpr = transformExpr(pstate, a->lexpr, precedence);
644 result = ParseFunc(pstate,
645 "nonnullvalue", lcons(lexpr, NIL),
646 &pstate->p_last_resno);
651 Expr *expr = makeNode(Expr);
652 Node *lexpr = transformExpr(pstate, a->lexpr, precedence);
653 Node *rexpr = transformExpr(pstate, a->rexpr, precedence);
654 if (exprType(lexpr) != BOOLOID)
656 "left-hand side of AND is type '%s', not bool",
657 tname(get_id_type(exprType(lexpr))));
658 if (exprType(rexpr) != BOOLOID)
660 "right-hand side of AND is type '%s', not bool",
661 tname(get_id_type(exprType(rexpr))));
662 expr->typeOid = BOOLOID;
663 expr->opType = AND_EXPR;
664 expr->args = makeList(lexpr, rexpr, -1);
665 result = (Node *)expr;
670 Expr *expr = makeNode(Expr);
671 Node *lexpr = transformExpr(pstate, a->lexpr, precedence);
672 Node *rexpr = transformExpr(pstate, a->rexpr, precedence);
673 if (exprType(lexpr) != BOOLOID)
675 "left-hand side of OR is type '%s', not bool",
676 tname(get_id_type(exprType(lexpr))));
677 if (exprType(rexpr) != BOOLOID)
679 "right-hand side of OR is type '%s', not bool",
680 tname(get_id_type(exprType(rexpr))));
681 expr->typeOid = BOOLOID;
682 expr->opType = OR_EXPR;
683 expr->args = makeList(lexpr, rexpr, -1);
684 result = (Node *)expr;
689 Expr *expr = makeNode(Expr);
690 Node *rexpr = transformExpr(pstate, a->rexpr, precedence);
691 if (exprType(rexpr) != BOOLOID)
693 "argument to NOT is type '%s', not bool",
694 tname(get_id_type(exprType(rexpr))));
695 expr->typeOid = BOOLOID;
696 expr->opType = NOT_EXPR;
697 expr->args = makeList(rexpr, -1);
698 result = (Node *)expr;
705 /* look for a column name or a relation name (the default behavior) */
706 result = transformIdent(pstate, expr, precedence);
710 FuncCall *fn = (FuncCall *)expr;
713 /* transform the list of arguments */
714 foreach(args, fn->args)
715 lfirst(args) = transformExpr(pstate, (Node*)lfirst(args), precedence);
716 result = ParseFunc(pstate,
717 fn->funcname, fn->args, &pstate->p_last_resno);
721 /* should not reach here */
722 elog(WARN, "transformExpr: does not know how to transform %d\n",
731 transformIdent(ParseState *pstate, Node *expr, int precedence)
733 Ident *ident = (Ident*)expr;
735 Node *column_result, *relation_result, *result;
737 column_result = relation_result = result = 0;
738 /* try to find the ident as a column */
739 if ((rte = colnameRangeTableEntry(pstate, ident->name)) != NULL) {
740 Attr *att = makeNode(Attr);
742 att->relname = rte->refname;
743 att->attrs = lcons(makeString(ident->name), NIL);
745 (Node*)handleNestedDots(pstate, att, &pstate->p_last_resno);
748 /* try to find the ident as a relation */
749 if (refnameRangeTableEntry(pstate->p_rtable, ident->name) != NULL) {
751 relation_result = (Node*)ident;
754 /* choose the right result based on the precedence */
755 if(precedence == EXPR_COLUMN_FIRST) {
757 result = column_result;
759 result = relation_result;
762 result = relation_result;
764 result = column_result;
768 elog(WARN, "attribute \"%s\" not found", ident->name);
773 /*****************************************************************************
777 *****************************************************************************/
781 * turns the table references specified in the from-clause into a
782 * range table. The range table may grow as we transform the expressions
783 * in the target list. (Note that this happens because in POSTQUEL, we
784 * allow references to relations not specified in the from-clause. We
785 * also allow that in our POST-SQL)
789 parseFromClause(ParseState *pstate, List *frmList)
795 RangeVar *r = lfirst(fl);
796 RelExpr *baserel = r->relExpr;
797 char *relname = baserel->relname;
798 char *refname = r->name;
805 * marks this entry to indicate it comes from the FROM clause. In
806 * SQL, the target list can only refer to range variables specified
807 * in the from clause but we follow the more powerful POSTQUEL
808 * semantics and automatically generate the range variable if not
809 * specified. However there are times we need to know whether the
810 * entries are legitimate.
812 * eg. select * from foo f where f.x = 1; will generate wrong answer
813 * if we expand * to foo.x.
815 rte = addRangeTableEntry(pstate, relname, refname, baserel->inh, TRUE,
822 * make a range table with the specified relation (optional) and the
826 makeRangeTable(ParseState *pstate, char *relname, List *frmList)
830 parseFromClause(pstate, frmList);
835 if (refnameRangeTablePosn(pstate->p_rtable, relname) < 1)
836 rte = addRangeTableEntry(pstate, relname, relname, FALSE, FALSE, NULL);
838 rte = refnameRangeTableEntry(pstate->p_rtable, relname);
840 pstate->p_target_rangetblentry = rte;
841 Assert(pstate->p_target_relation == NULL);
842 pstate->p_target_relation = heap_open(rte->relid);
843 Assert(pstate->p_target_relation != NULL);
844 /* will close relation later */
849 * returns the Oid of the type of the expression. (Used for typechecking.)
856 switch(nodeTag(expr)) {
858 type = ((Func*)expr)->functype;
861 type = ((Iter*)expr)->itertype;
864 type = ((Var*)expr)->vartype;
867 type = ((Expr*)expr)->typeOid;
870 type = ((Const*)expr)->consttype;
873 type = ((ArrayRef*)expr)->refelemtype;
876 type = ((Aggreg*)expr)->aggtype;
879 type = ((Param*)expr)->paramtype;
886 elog(WARN, "exprType: don't know how to get type for %d node",
895 * turns '*' (in the target list) into a list of attributes (of all
896 * relations in the range table)
899 expandAllTables(ParseState *pstate)
902 List *legit_rtable=NIL;
905 rtable = pstate->p_rtable;
906 if (pstate->p_is_rule) {
908 * skip first two entries, "*new*" and "*current*"
910 rtable = lnext(lnext(pstate->p_rtable));
913 /* this should not happen */
915 elog(WARN, "cannot expand: null p_rtable");
918 * go through the range table and make a list of range table entries
919 * which we will expand.
921 foreach(rt, rtable) {
922 RangeTblEntry *rte = lfirst(rt);
925 * we only expand those specify in the from clause. (This will
926 * also prevent us from using the wrong table in inserts: eg. tenk2
927 * in "insert into tenk2 select * from tenk1;")
931 legit_rtable = lappend(legit_rtable, rte);
934 foreach(rt, legit_rtable) {
935 RangeTblEntry *rte = lfirst(rt);
939 target = expandAll(pstate, rte->relname, rte->refname,
940 &pstate->p_last_resno);
942 while (temp != NIL && lnext(temp) != NIL)
944 lnext(temp) = expandAll(pstate, rte->relname, rte->refname,
945 &pstate->p_last_resno);
954 * if the name of the resulting column is not specified in the target
955 * list, we have to guess.
959 figureColname(Node *expr, Node *resval)
961 switch (nodeTag(expr)) {
963 return (char*) /* XXX */
964 ((Aggreg *)expr)->aggname;
966 if (((Expr*)expr)->opType == FUNC_EXPR) {
967 if (nodeTag(resval)==T_FuncCall)
968 return ((FuncCall*)resval)->funcname;
978 /*****************************************************************************
982 *****************************************************************************/
986 * generate a list of column names if not supplied or
987 * test supplied column names to make sure they are in target table
988 * (used exclusively for inserts)
991 makeTargetNames(ParseState *pstate, List *cols)
995 /* Generate ResTarget if not supplied */
1000 AttributeTupleForm *attr = pstate->p_target_relation->rd_att->attrs;
1002 numcol = pstate->p_target_relation->rd_rel->relnatts;
1003 for(i=0; i < numcol; i++) {
1004 Ident *id = makeNode(Ident);
1006 id->name = palloc(NAMEDATALEN+1);
1007 strncpy(id->name, attr[i]->attname.data, NAMEDATALEN);
1008 id->name[NAMEDATALEN]='\0';
1009 id->indirection = NIL;
1012 cols = tl = lcons(id, NIL);
1014 lnext(tl) = lcons(id,NIL);
1021 /* elog on failure */
1022 (void)varattno(pstate->p_target_relation,((Ident *)lfirst(tl))->name);
1028 * transformTargetList -
1029 * turns a list of ResTarget's into a list of TargetEntry's
1032 transformTargetList(ParseState *pstate, List *targetlist)
1034 List *p_target= NIL;
1035 List *tail_p_target = NIL;
1037 while(targetlist != NIL) {
1038 ResTarget *res= (ResTarget *)lfirst(targetlist);
1039 TargetEntry *tent = makeNode(TargetEntry);
1041 switch(nodeTag(res->val)) {
1049 identname = ((Ident*)res->val)->name;
1050 handleTargetColname(pstate, &res->name, NULL, identname );
1052 /* here we want to look for column names only, not relation */
1053 /* names (even though they can be stored in Ident nodes, */
1055 expr = transformIdent(pstate, (Node*)res->val, EXPR_COLUMN_FIRST);
1056 type_id = exprType(expr);
1057 type_len = tlen(get_id_type(type_id));
1058 resname = (res->name) ? res->name : identname;
1059 tent->resdom = makeResdom((AttrNumber)pstate->p_last_resno++,
1074 Node *expr = transformExpr(pstate, (Node *)res->val, EXPR_COLUMN_FIRST);
1076 handleTargetColname(pstate, &res->name, NULL, NULL);
1077 /* note indirection has not been transformed */
1078 if (pstate->p_is_insert && res->indirection!=NIL) {
1079 /* this is an array assignment */
1081 char *str, *save_str;
1084 int lindx[MAXDIM], uindx[MAXDIM];
1089 if (exprType(expr) != UNKNOWNOID ||
1091 elog(WARN, "yyparse: string constant expected");
1093 val = (char *) textout((struct varlena *)
1094 ((Const *)expr)->constvalue);
1095 str = save_str = (char*)palloc(strlen(val) + MAXDIM * 25 + 2);
1096 foreach(elt, res->indirection) {
1097 A_Indices *aind = (A_Indices *)lfirst(elt);
1098 aind->uidx = transformExpr(pstate, aind->uidx, EXPR_COLUMN_FIRST);
1099 if (!IsA(aind->uidx,Const))
1101 "Array Index for Append should be a constant");
1102 uindx[i] = ((Const *)aind->uidx)->constvalue;
1103 if (aind->lidx!=NULL) {
1104 aind->lidx = transformExpr(pstate, aind->lidx, EXPR_COLUMN_FIRST);
1105 if (!IsA(aind->lidx,Const))
1107 "Array Index for Append should be a constant");
1108 lindx[i] = ((Const*)aind->lidx)->constvalue;
1112 if (lindx[i] > uindx[i])
1113 elog(WARN, "yyparse: lower index cannot be greater than upper index");
1114 sprintf(str, "[%d:%d]", lindx[i], uindx[i]);
1118 sprintf(str, "=%s", val);
1119 rd = pstate->p_target_relation;
1121 resdomno = varattno(rd, res->name);
1122 ndims = att_attnelems(rd, resdomno);
1124 elog(WARN, "yyparse: array dimensions do not match");
1125 constval = makeNode(Value);
1126 constval->type = T_String;
1127 constval->val.str = save_str;
1128 tent = make_targetlist_expr(pstate, res->name,
1129 (Node*)make_const(constval),
1133 char *colname= res->name;
1134 /* this is not an array assignment */
1135 if (colname==NULL) {
1136 /* if you're wondering why this is here, look at
1137 * the yacc grammar for why a name can be missing. -ay
1139 colname = figureColname(expr, res->val);
1141 if (res->indirection) {
1142 List *ilist = res->indirection;
1143 while (ilist!=NIL) {
1144 A_Indices *ind = lfirst(ilist);
1145 ind->lidx = transformExpr(pstate, ind->lidx, EXPR_COLUMN_FIRST);
1146 ind->uidx = transformExpr(pstate, ind->uidx, EXPR_COLUMN_FIRST);
1147 ilist = lnext(ilist);
1150 res->name = colname;
1151 tent = make_targetlist_expr(pstate, res->name, expr,
1159 Attr *att = (Attr *)res->val;
1164 List *attrs = att->attrs;
1167 * Target item is a single '*', expand all tables
1168 * (eg. SELECT * FROM emp)
1170 if (att->relname!=NULL && !strcmp(att->relname, "*")) {
1171 if (tail_p_target == NIL)
1172 p_target = tail_p_target = expandAllTables(pstate);
1174 lnext(tail_p_target) = expandAllTables(pstate);
1176 while(lnext(tail_p_target)!=NIL)
1177 /* make sure we point to the last target entry */
1178 tail_p_target = lnext(tail_p_target);
1180 * skip rest of while loop
1182 targetlist = lnext(targetlist);
1187 * Target item is relation.*, expand the table
1188 * (eg. SELECT emp.*, dname FROM emp, dept)
1190 attrname = strVal(lfirst(att->attrs));
1191 if (att->attrs!=NIL && !strcmp(attrname,"*")) {
1192 /* tail_p_target is the target list we're building in the while
1193 * loop. Make sure we fix it after appending more nodes.
1195 if (tail_p_target == NIL)
1196 p_target = tail_p_target = expandAll(pstate, att->relname,
1197 att->relname, &pstate->p_last_resno);
1199 lnext(tail_p_target) =
1200 expandAll(pstate, att->relname, att->relname,
1201 &pstate->p_last_resno);
1202 while(lnext(tail_p_target)!=NIL)
1203 /* make sure we point to the last target entry */
1204 tail_p_target = lnext(tail_p_target);
1206 * skip the rest of the while loop
1208 targetlist = lnext(targetlist);
1214 * Target item is fully specified: ie. relation.attribute
1216 result = handleNestedDots(pstate, att, &pstate->p_last_resno);
1217 handleTargetColname(pstate, &res->name, att->relname, attrname);
1218 if (att->indirection != NIL) {
1219 List *ilist = att->indirection;
1220 while (ilist!=NIL) {
1221 A_Indices *ind = lfirst(ilist);
1222 ind->lidx = transformExpr(pstate, ind->lidx, EXPR_COLUMN_FIRST);
1223 ind->uidx = transformExpr(pstate, ind->uidx, EXPR_COLUMN_FIRST);
1224 ilist = lnext(ilist);
1226 result = (Node*)make_array_ref(result, att->indirection);
1228 type_id = exprType(result);
1229 type_len = tlen(get_id_type(type_id));
1230 /* move to last entry */
1231 while(lnext(attrs)!=NIL)
1233 resname = (res->name) ? res->name : strVal(lfirst(attrs));
1234 resnode = makeResdom((AttrNumber)pstate->p_last_resno++,
1241 tent->resdom = resnode;
1242 tent->expr = result;
1246 /* internal error */
1248 "internal error: do not know how to transform targetlist");
1252 if (p_target == NIL) {
1253 p_target = tail_p_target = lcons(tent, NIL);
1255 lnext(tail_p_target) = lcons(tent, NIL);
1256 tail_p_target = lnext(tail_p_target);
1258 targetlist = lnext(targetlist);
1266 * make_targetlist_expr -
1267 * make a TargetEntry from an expression
1269 * arrayRef is a list of transformed A_Indices
1271 static TargetEntry *
1272 make_targetlist_expr(ParseState *pstate,
1277 Oid type_id, attrtype;
1278 int type_len, attrlen;
1286 elog(WARN, "make_targetlist_expr: invalid use of NULL expression");
1288 type_id = exprType(expr);
1289 if (type_id == InvalidOid) {
1292 type_len = tlen(get_id_type(type_id));
1294 /* I have no idea what the following does! */
1295 /* It appears to process target columns that will be receiving results */
1296 if (pstate->p_is_insert||pstate->p_is_update) {
1298 * append or replace query --
1299 * append, replace work only on one relation,
1300 * so multiple occurence of same resdomno is bogus
1302 rd = pstate->p_target_relation;
1304 resdomno = varattno(rd,colname);
1305 attrisset = varisset(rd,colname);
1306 attrtype = att_typeid(rd,resdomno);
1307 if ((arrayRef != NIL) && (lfirst(arrayRef) == NIL))
1308 attrtype = GetArrayElementType(attrtype);
1309 if (attrtype==BPCHAROID || attrtype==VARCHAROID) {
1310 attrlen = rd->rd_att->attrs[resdomno-1]->attlen;
1312 attrlen = tlen(get_id_type(attrtype));
1315 if(Input_is_string && Typecast_ok){
1317 if (type_id == typeid(type("unknown"))){
1318 val = (Datum)textout((struct varlena *)
1319 ((Const)lnext(expr))->constvalue);
1321 val = ((Const)lnext(expr))->constvalue;
1324 lnext(expr) = makeConst(attrtype,
1335 (Datum)fmgr(typeid_get_retinfunc(attrtype),
1336 val,get_typelem(attrtype),-1),
1338 true /* Maybe correct-- 80% chance */,
1339 false, /* is not a set */
1342 } else if((Typecast_ok) && (attrtype != type_id)){
1344 parser_typecast2(expr, get_id_type(attrtype));
1346 if (attrtype != type_id) {
1347 if ((attrtype == INT2OID) && (type_id == INT4OID))
1348 lfirst(expr) = lispInteger (INT2OID);
1349 else if ((attrtype == FLOAT4OID) && (type_id == FLOAT8OID))
1350 lfirst(expr) = lispInteger (FLOAT4OID);
1352 elog(WARN, "unequal type in tlist : %s \n",
1356 Input_is_string = false;
1357 Input_is_integer = false;
1361 if (attrtype != type_id) {
1362 if (IsA(expr,Const)) {
1363 /* try to cast the constant */
1364 if (arrayRef && !(((A_Indices *)lfirst(arrayRef))->lidx)) {
1365 /* updating a single item */
1366 Oid typelem = get_typelem(attrtype);
1367 expr = (Node*)parser_typecast2(expr,
1369 get_id_type(typelem),
1372 expr = (Node*)parser_typecast2(expr,
1374 get_id_type(attrtype),
1377 /* currently, we can't handle casting of expressions */
1378 elog(WARN, "parser: attribute '%s' is of type '%.*s' but expression is of type '%.*s'",
1380 NAMEDATALEN, get_id_typname(attrtype),
1381 NAMEDATALEN, get_id_typname(type_id));
1385 if (arrayRef != NIL) {
1387 Attr *att = makeNode(Attr);
1388 List *ar = arrayRef;
1389 List *upperIndexpr = NIL;
1390 List *lowerIndexpr = NIL;
1392 att->relname = pstrdup(RelationGetRelationName(rd)->data);
1393 att->attrs = lcons(makeString(colname), NIL);
1394 target_expr = (Expr*)handleNestedDots(pstate, att,
1395 &pstate->p_last_resno);
1397 A_Indices *ind = lfirst(ar);
1398 if (lowerIndexpr || (!upperIndexpr && ind->lidx)) {
1399 /* XXX assume all lowerIndexpr is non-null in
1402 lowerIndexpr = lappend(lowerIndexpr, ind->lidx);
1404 upperIndexpr = lappend(upperIndexpr, ind->uidx);
1408 expr = (Node*)make_array_set(target_expr,
1412 attrtype = att_typeid(rd,resdomno);
1413 attrlen = tlen(get_id_type(attrtype));
1416 resdomno = pstate->p_last_resno++;
1420 tent = makeNode(TargetEntry);
1422 resnode = makeResdom((AttrNumber)resdomno,
1430 tent->resdom = resnode;
1437 /*****************************************************************************
1441 *****************************************************************************/
1444 * transformWhereClause -
1445 * transforms the qualification and make sure it is of type Boolean
1449 transformWhereClause(ParseState *pstate, Node *a_expr)
1454 return (Node *)NULL; /* no qualifiers */
1456 inWhereClause = true;
1457 qual = transformExpr(pstate, a_expr, EXPR_COLUMN_FIRST);
1458 inWhereClause = false;
1459 if (exprType(qual) != BOOLOID) {
1461 "where clause must return type bool, not %s",
1462 tname(get_id_type(exprType(qual))));
1467 /*****************************************************************************
1471 *****************************************************************************/
1474 * find_targetlist_entry -
1475 * returns the Resdom in the target list matching the specified varname
1479 static TargetEntry *
1480 find_targetlist_entry(ParseState *pstate, SortGroupBy *sortgroupby, List *tlist)
1483 int real_rtable_pos = 0, target_pos = 0;
1484 TargetEntry *target_result = NULL;
1486 if(sortgroupby->range)
1487 real_rtable_pos = refnameRangeTablePosn(pstate->p_rtable,
1488 sortgroupby->range);
1491 TargetEntry *target = (TargetEntry *)lfirst(i);
1492 Resdom *resnode = target->resdom;
1493 Var *var = (Var *)target->expr;
1494 char *resname = resnode->resname;
1495 int test_rtable_pos = var->varno;
1497 if (!sortgroupby->name) {
1498 if (sortgroupby->resno == ++target_pos) {
1499 target_result = target;
1504 if (!strcmp(resname, sortgroupby->name)) {
1505 if(sortgroupby->range) {
1506 if(real_rtable_pos == test_rtable_pos) {
1507 if (target_result != NULL)
1508 elog(WARN, "Order/Group By %s is ambiguous", sortgroupby->name);
1509 else target_result = target;
1513 if (target_result != NULL)
1514 elog(WARN, "Order/Group By %s is ambiguous", sortgroupby->name);
1515 else target_result = target;
1520 return target_result;
1524 any_ordering_op(int restype)
1529 order_op = oper("<",restype,restype,false);
1530 order_opid = oprid(order_op);
1536 * transformGroupClause -
1537 * transform an Group By clause
1541 transformGroupClause(ParseState *pstate, List *grouplist, List *targetlist)
1543 List *glist = NIL, *gl = NIL;
1545 while (grouplist != NIL) {
1546 GroupClause *grpcl = makeNode(GroupClause);
1547 TargetEntry *restarget;
1550 restarget = find_targetlist_entry(pstate, lfirst(grouplist), targetlist);
1552 if (restarget == NULL)
1553 elog(WARN,"The field being grouped by must appear in the target list");
1555 grpcl->entry = restarget;
1556 resdom = restarget->resdom;
1557 grpcl->grpOpoid = oprid(oper("<",
1559 resdom->restype,false));
1561 gl = glist = lcons(grpcl, NIL);
1563 lnext(gl) = lcons(grpcl, NIL);
1566 grouplist = lnext(grouplist);
1573 * transformSortClause -
1574 * transform an Order By clause
1578 transformSortClause(ParseState *pstate,
1579 List *orderlist, List *targetlist,
1582 List *sortlist = NIL;
1585 while(orderlist != NIL) {
1586 SortGroupBy *sortby = lfirst(orderlist);
1587 SortClause *sortcl = makeNode(SortClause);
1588 TargetEntry *restarget;
1591 restarget = find_targetlist_entry(pstate, sortby, targetlist);
1592 if (restarget == NULL)
1593 elog(WARN,"The field being ordered by must appear in the target list");
1595 sortcl->resdom = resdom = restarget->resdom;
1596 sortcl->opoid = oprid(oper(sortby->useOp,
1598 resdom->restype,false));
1599 if (sortlist == NIL) {
1600 s = sortlist = lcons(sortcl, NIL);
1602 lnext(s) = lcons(sortcl, NIL);
1605 orderlist = lnext(orderlist);
1609 if (uniqueFlag[0] == '*') {
1610 /* concatenate all elements from target list
1611 that are not already in the sortby list */
1612 foreach (i,targetlist) {
1613 TargetEntry *tlelt = (TargetEntry *)lfirst(i);
1617 SortClause *sortcl = lfirst(s);
1618 if (sortcl->resdom==tlelt->resdom)
1623 /* not a member of the sortclauses yet */
1624 SortClause *sortcl = makeNode(SortClause);
1626 sortcl->resdom = tlelt->resdom;
1627 sortcl->opoid = any_ordering_op(tlelt->resdom->restype);
1629 sortlist = lappend(sortlist, sortcl);
1634 TargetEntry *tlelt = NULL;
1635 char* uniqueAttrName = uniqueFlag;
1637 /* only create sort clause with the specified unique attribute */
1638 foreach (i, targetlist) {
1639 tlelt = (TargetEntry*)lfirst(i);
1640 if (strcmp(tlelt->resdom->resname, uniqueAttrName) == 0)
1644 elog(WARN, "The field specified in the UNIQUE ON clause is not in the targetlist");
1647 foreach (s, sortlist) {
1648 SortClause *sortcl = lfirst(s);
1649 if (sortcl->resdom == tlelt->resdom)
1653 /* not a member of the sortclauses yet */
1654 SortClause *sortcl = makeNode(SortClause);
1656 sortcl->resdom = tlelt->resdom;
1657 sortcl->opoid = any_ordering_op(tlelt->resdom->restype);
1659 sortlist = lappend(sortlist, sortcl);
1669 ** HandleNestedDots --
1670 ** Given a nested dot expression (i.e. (relation func ... attr), build up
1671 ** a tree with of Iter and Func nodes.
1674 handleNestedDots(ParseState *pstate, Attr *attr, int *curr_resno)
1677 Node *retval = NULL;
1679 if (attr->paramNo != NULL) {
1680 Param *param = (Param *)transformExpr(pstate, (Node*)attr->paramNo, EXPR_RELATION_FIRST);
1683 ParseFunc(pstate, strVal(lfirst(attr->attrs)),
1687 Ident *ident = makeNode(Ident);
1689 ident->name = attr->relname;
1690 ident->isRel = TRUE;
1692 ParseFunc(pstate, strVal(lfirst(attr->attrs)),
1697 foreach (mutator_iter, lnext(attr->attrs)) {
1698 retval = ParseFunc(pstate,strVal(lfirst(mutator_iter)),
1707 ** make_arguments --
1708 ** Given the number and types of arguments to a function, and the
1709 ** actual arguments and argument types, do the necessary typecasting.
1712 make_arguments(int nargs,
1715 Oid *function_typeids)
1718 * there are two ways an input typeid can differ from a function typeid :
1719 * either the input type inherits the function type, so no typecasting is
1720 * necessary, or the input type can be typecast into the function type.
1721 * right now, we only typecast unknowns, and that is all we check for.
1724 List *current_fargs;
1727 for (i=0, current_fargs = fargs;
1729 i++, current_fargs = lnext(current_fargs)) {
1731 if (input_typeids[i] == UNKNOWNOID && function_typeids[i] != InvalidOid) {
1732 lfirst(current_fargs) =
1733 parser_typecast2(lfirst(current_fargs),
1735 get_id_type(function_typeids[i]),
1743 ** Build a tlist that says which attribute to project to.
1744 ** This routine is called by ParseFunc() to set up a target list
1745 ** on a tuple parameter or return value. Due to a bug in 4.0,
1746 ** it's not possible to refer to system attributes in this case.
1749 setup_tlist(char *attname, Oid relid)
1757 attno = get_attnum(relid, attname);
1759 elog(WARN, "cannot reference attribute %s of tuple params/return values for functions", attname);
1761 typeid = find_atttype(relid, attname);
1762 resnode = makeResdom(1,
1764 tlen(get_id_type(typeid)),
1765 get_attname(relid, attno),
1769 varnode = makeVar(-1, attno, typeid, -1, attno);
1771 tle = makeNode(TargetEntry);
1772 tle->resdom = resnode;
1773 tle->expr = (Node*)varnode;
1774 return (lcons(tle, NIL));
1778 ** setup_base_tlist --
1779 ** Build a tlist that extracts a base type from the tuple
1780 ** returned by the executor.
1783 setup_base_tlist(Oid typeid)
1789 resnode = makeResdom(1,
1791 tlen(get_id_type(typeid)),
1796 varnode = makeVar(-1, 1, typeid, -1, 1);
1797 tle = makeNode(TargetEntry);
1798 tle->resdom = resnode;
1799 tle->expr = (Node*)varnode;
1801 return (lcons(tle, NIL));
1805 * ParseComplexProjection -
1806 * handles function calls with a single argument that is of complex type.
1807 * This routine returns NULL if it can't handle the projection (eg. sets).
1810 ParseComplexProjection(ParseState *pstate,
1822 switch (nodeTag(first_arg)) {
1828 iter = (Iter*)first_arg;
1829 func = (Func *)((Expr*)iter->iterexpr)->oper;
1830 argtype = funcid_get_rettype(func->funcid);
1831 argrelid = typeid_get_relid(argtype);
1833 ((attnum = get_attnum(argrelid, funcname))
1834 != InvalidAttrNumber)) {
1836 /* the argument is a function returning a tuple, so funcname
1837 may be a projection */
1839 /* add a tlist to the func node and return the Iter */
1840 rd = heap_openr(tname(get_id_type(argtype)));
1841 if (RelationIsValid(rd)) {
1842 relid = RelationGetRelationId(rd);
1843 relname = RelationGetRelationName(rd);
1846 if (RelationIsValid(rd)) {
1848 setup_tlist(funcname, argrelid);
1849 iter->itertype = att_typeid(rd,attnum);
1850 return ((Node*)iter);
1853 "Function %s has bad returntype %d",
1865 * The argument is a set, so this is either a projection
1866 * or a function call on this set.
1873 Expr *expr = (Expr*)first_arg;
1876 if (expr->opType != FUNC_EXPR)
1879 funcnode= (Func *) expr->oper;
1880 argtype = funcid_get_rettype(funcnode->funcid);
1881 argrelid = typeid_get_relid(argtype);
1883 * the argument is a function returning a tuple, so funcname
1884 * may be a projection
1887 (attnum = get_attnum(argrelid, funcname))
1888 != InvalidAttrNumber) {
1890 /* add a tlist to the func node */
1891 rd = heap_openr(tname(get_id_type(argtype)));
1892 if (RelationIsValid(rd)) {
1893 relid = RelationGetRelationId(rd);
1894 relname = RelationGetRelationName(rd);
1897 if (RelationIsValid(rd)) {
1900 funcnode->func_tlist =
1901 setup_tlist(funcname, argrelid);
1902 funcnode->functype = att_typeid(rd,attnum);
1904 newexpr = makeNode(Expr);
1905 newexpr->typeOid = funcnode->functype;
1906 newexpr->opType = FUNC_EXPR;
1907 newexpr->oper = (Node *)funcnode;
1908 newexpr->args = lcons(first_arg, NIL);
1910 return ((Node*)newexpr);
1915 elog(WARN, "Function %s has bad returntype %d",
1921 Param *param = (Param*)first_arg;
1923 * If the Param is a complex type, this could be a projection
1925 rd = heap_openr(tname(get_id_type(param->paramtype)));
1926 if (RelationIsValid(rd)) {
1927 relid = RelationGetRelationId(rd);
1928 relname = RelationGetRelationName(rd);
1931 if (RelationIsValid(rd) &&
1932 (attnum = get_attnum(relid, funcname))
1933 != InvalidAttrNumber) {
1935 param->paramtype = att_typeid(rd, attnum);
1936 param->param_tlist = setup_tlist(funcname, relid);
1937 return ((Node*)param);
1949 ParseFunc(ParseState *pstate, char *funcname, List *fargs, int *curr_resno)
1951 Oid rettype = (Oid)0;
1952 Oid argrelid = (Oid)0;
1953 Oid funcid = (Oid)0;
1955 Node *first_arg= NULL;
1956 char *relname = NULL;
1957 char *refname = NULL;
1963 Oid *true_oid_array;
1967 bool attisset = false;
1972 first_arg = lfirst(fargs);
1973 if (first_arg == NULL)
1974 elog (WARN,"function %s does not allow NULL input",funcname);
1978 ** check for projection methods: if function takes one argument, and
1979 ** that argument is a relation, param, or PQ function returning a complex
1980 ** type, then the function could be a projection.
1982 if (length(fargs) == 1) {
1984 if (nodeTag(first_arg)==T_Ident && ((Ident*)first_arg)->isRel) {
1986 Ident *ident = (Ident*)first_arg;
1989 * first arg is a relation. This could be a projection.
1991 refname = ident->name;
1993 rte = refnameRangeTableEntry(pstate->p_rtable, refname);
1995 rte = addRangeTableEntry(pstate, refname, refname, FALSE, FALSE,NULL);
1997 relname = rte->relname;
2000 /* If the attr isn't a set, just make a var for it. If
2001 * it is a set, treat it like a function and drop through.
2003 if (get_attnum(relid, funcname) != InvalidAttrNumber) {
2007 ((Node*)make_var(pstate,
2012 /* drop through - attr is a set */
2015 } else if (ISCOMPLEX(exprType(first_arg))) {
2017 * Attempt to handle projection of a complex argument. If
2018 * ParseComplexProjection can't handle the projection, we
2019 * have to keep going.
2021 retval = ParseComplexProjection(pstate,
2026 toid = exprType(first_arg);
2027 rd = heap_openr(tname(get_id_type(toid)));
2028 if (RelationIsValid(rd)) {
2029 relname = RelationGetRelationName(rd)->data;
2033 "Type %s is not a relation type",
2034 tname(get_id_type(toid)));
2035 argrelid = typeid_get_relid(toid);
2036 /* A projection contains either an attribute name or the
2039 if ((get_attnum(argrelid, funcname) == InvalidAttrNumber)
2040 && strcmp(funcname, "*")) {
2041 elog(WARN, "Functions on sets are not yet supported");
2049 * Parsing aggregates.
2052 /* the aggregate count is a special case,
2053 ignore its base type. Treat it as zero */
2054 if (strcmp(funcname, "count") == 0)
2057 basetype = exprType(lfirst(fargs));
2058 if (SearchSysCacheTuple(AGGNAME,
2059 PointerGetDatum(funcname),
2060 ObjectIdGetDatum(basetype),
2062 Aggreg *aggreg = ParseAgg(funcname, basetype, lfirst(fargs));
2064 AddAggToParseState(pstate, aggreg);
2065 return (Node*)aggreg;
2072 ** If we dropped through to here it's really a function (or a set, which
2073 ** is implemented as a function.)
2074 ** extract arg type info and transform relation name arguments into
2075 ** varnodes of the appropriate form.
2077 memset(&oid_array[0], 0, 8 * sizeof(Oid));
2080 foreach ( i , fargs ) {
2083 Node *pair = lfirst(i);
2085 if (nodeTag(pair)==T_Ident && ((Ident*)pair)->isRel) {
2089 refname = ((Ident*)pair)->name;
2091 rte = refnameRangeTableEntry(pstate->p_rtable, refname);
2093 rte = addRangeTableEntry(pstate, refname, refname,
2094 FALSE, FALSE, NULL);
2095 relname = rte->relname;
2097 vnum = refnameRangeTablePosn (pstate->p_rtable, rte->refname);
2100 * for func(relname), the param to the function
2101 * is the tuple under consideration. we build a special
2102 * VarNode to reflect this -- it has varno set to the
2103 * correct range table entry, but has varattno == 0 to
2104 * signal that the whole tuple is the argument.
2106 toid = typeid(type(relname));
2107 /* replace it in the arg list */
2109 makeVar(vnum, 0, toid, vnum, 0);
2110 }else if (!attisset) { /* set functions don't have parameters */
2112 /* any functiona args which are typed "unknown", but aren't
2113 constants, we don't know what to do with, because we
2114 can't cast them - jolly*/
2115 if (exprType(pair) == UNKNOWNOID &&
2118 elog(WARN, "ParseFunc: no function named %s that takes in an unknown type as argument #%d", funcname, nargs);
2121 toid = exprType(pair);
2124 oid_array[nargs++] = toid;
2128 * func_get_detail looks up the function in the catalogs, does
2129 * disambiguation for polymorphic functions, handles inheritance,
2130 * and returns the funcid and type and set or singleton status of
2131 * the function's return value. it also returns the true argument
2132 * types to the function. if func_get_detail returns true,
2133 * the function exists. otherwise, there was an error.
2135 if (attisset) { /* we know all of these fields already */
2136 /* We create a funcnode with a placeholder function SetEval.
2137 * SetEval() never actually gets executed. When the function
2138 * evaluation routines see it, they use the funcid projected
2139 * out from the relation as the actual function to call.
2140 * Example: retrieve (emp.mgr.name)
2141 * The plan for this will scan the emp relation, projecting
2142 * out the mgr attribute, which is a funcid. This function
2143 * is then called (instead of SetEval) and "name" is projected
2146 funcid = SetEvalRegProcedure;
2149 true_oid_array = oid_array;
2152 exists = func_get_detail(funcname, nargs, oid_array, &funcid,
2153 &rettype, &retset, &true_oid_array);
2157 elog(WARN, "no such attribute or function %s", funcname);
2160 funcnode = makeNode(Func);
2161 funcnode->funcid = funcid;
2162 funcnode->functype = rettype;
2163 funcnode->funcisindex = false;
2164 funcnode->funcsize = 0;
2165 funcnode->func_fcache = NULL;
2166 funcnode->func_tlist = NIL;
2167 funcnode->func_planlist = NIL;
2169 /* perform the necessary typecasting */
2170 make_arguments(nargs, fargs, oid_array, true_oid_array);
2173 * for functions returning base types, we want to project out the
2174 * return value. set up a target list to do that. the executor
2175 * will ignore these for c functions, and do the right thing for
2176 * postquel functions.
2179 if (typeid_get_relid(rettype) == InvalidOid)
2180 funcnode->func_tlist = setup_base_tlist(rettype);
2182 /* For sets, we want to make a targetlist to project out this
2183 * attribute of the set tuples.
2186 if (!strcmp(funcname, "*")) {
2187 funcnode->func_tlist =
2188 expandAll(pstate, relname, refname, curr_resno);
2190 funcnode->func_tlist = setup_tlist(funcname,argrelid);
2191 rettype = find_atttype(argrelid, funcname);
2196 * Sequence handling.
2198 if ( funcid == SeqNextValueRegProcedure ||
2199 funcid == SeqCurrValueRegProcedure )
2203 int32 aclcheck_result = -1;
2205 Assert ( length(fargs) == 1 );
2206 seq = (Const*)lfirst(fargs);
2207 if ( ! IsA ((Node*)seq, Const) )
2208 elog (WARN, "%s: only constant sequence names are acceptable", funcname);
2209 seqrel = textout ((struct varlena *) (seq->constvalue));
2211 if ( ( aclcheck_result = pg_aclcheck (seqrel, GetPgUserName(),
2212 ((funcid == SeqNextValueRegProcedure) ? ACL_WR : ACL_RD)) )
2214 elog (WARN, "%s.%s: %s",
2215 seqrel, funcname, aclcheck_error_strings[aclcheck_result]);
2219 if ( funcid == SeqNextValueRegProcedure && inWhereClause )
2220 elog (WARN, "nextval of a sequence in WHERE disallowed");
2223 expr = makeNode(Expr);
2224 expr->typeOid = rettype;
2225 expr->opType = FUNC_EXPR;
2226 expr->oper = (Node *)funcnode;
2228 retval = (Node*)expr;
2231 * if the function returns a set of values, then we need to iterate
2232 * over all the returned values in the executor, so we stick an
2233 * iter node here. if it returns a singleton, then we don't need
2238 Iter *iter = makeNode(Iter);
2239 iter->itertype = rettype;
2240 iter->iterexpr = retval;
2241 retval = (Node*)iter;
2247 /*****************************************************************************
2249 *****************************************************************************/
2252 * AddAggToParseState -
2253 * add the aggregate to the list of unique aggregates in pstate.
2255 * SIDE EFFECT: aggno in target list entry will be modified
2258 AddAggToParseState(ParseState *pstate, Aggreg *aggreg)
2264 * see if we have the aggregate already (we only need to record
2265 * the aggregate once)
2268 foreach(ag, pstate->p_aggs) {
2269 Aggreg *a = lfirst(ag);
2271 if (!strcmp(a->aggname, aggreg->aggname) &&
2272 equal(a->target, aggreg->target)) {
2274 /* fill in the aggno and we're done */
2281 /* not found, new aggregate */
2284 pstate->p_aggs = lappend(pstate->p_aggs, aggreg);
2289 * finalizeAggregates -
2290 * fill in qry_aggs from pstate. Also checks to make sure that aggregates
2291 * are used in the proper place.
2294 finalizeAggregates(ParseState *pstate, Query *qry)
2299 parseCheckAggregates(pstate, qry);
2301 qry->qry_numAgg = pstate->p_numAgg;
2303 (Aggreg **)palloc(sizeof(Aggreg *) * qry->qry_numAgg);
2305 foreach(l, pstate->p_aggs)
2306 qry->qry_aggs[i++] = (Aggreg*)lfirst(l);
2310 * contain_agg_clause--
2311 * Recursively find aggreg nodes from a clause.
2313 * Returns true if any aggregate found.
2316 contain_agg_clause(Node *clause)
2320 else if (IsA(clause,Aggreg))
2322 else if (IsA(clause,Iter))
2323 return contain_agg_clause(((Iter*)clause)->iterexpr);
2324 else if (single_node(clause))
2326 else if (or_clause(clause)) {
2329 foreach (temp, ((Expr*)clause)->args)
2330 if (contain_agg_clause(lfirst(temp)))
2333 } else if (is_funcclause (clause)) {
2336 foreach(temp, ((Expr *)clause)->args)
2337 if (contain_agg_clause(lfirst(temp)))
2340 } else if (IsA(clause,ArrayRef)) {
2343 foreach(temp, ((ArrayRef*)clause)->refupperindexpr)
2344 if (contain_agg_clause(lfirst(temp)))
2346 foreach(temp, ((ArrayRef*)clause)->reflowerindexpr)
2347 if (contain_agg_clause(lfirst(temp)))
2349 if (contain_agg_clause(((ArrayRef*)clause)->refexpr))
2351 if (contain_agg_clause(((ArrayRef*)clause)->refassgnexpr))
2354 } else if (not_clause(clause))
2355 return contain_agg_clause((Node*)get_notclausearg((Expr*)clause));
2356 else if (is_opclause(clause))
2357 return (contain_agg_clause((Node*)get_leftop((Expr*)clause)) ||
2358 contain_agg_clause((Node*)get_rightop((Expr*)clause)));
2364 * exprIsAggOrGroupCol -
2365 * returns true if the expression does not contain non-group columns.
2368 exprIsAggOrGroupCol(Node *expr, List *groupClause)
2372 if ( expr == NULL || IsA (expr, Const) ||
2373 IsA (expr, Param) || IsA (expr, Aggreg) )
2376 foreach (gl, groupClause)
2378 GroupClause *grpcl = lfirst(gl);
2380 if ( equal (expr, grpcl->entry->expr) )
2384 if ( IsA (expr, Expr) )
2388 foreach (temp, ((Expr*)expr)->args)
2389 if (!exprIsAggOrGroupCol(lfirst(temp),groupClause))
2398 * tleIsAggOrGroupCol -
2399 * returns true if the TargetEntry is Agg or GroupCol.
2402 tleIsAggOrGroupCol(TargetEntry *tle, List *groupClause)
2404 Node *expr = tle->expr;
2407 if ( expr == NULL || IsA (expr, Const) || IsA (expr, Param) )
2410 foreach (gl, groupClause)
2412 GroupClause *grpcl = lfirst(gl);
2414 if ( tle->resdom->resno == grpcl->entry->resdom->resno )
2416 if ( contain_agg_clause ((Node*) expr) )
2417 elog (WARN, "parser: aggregates not allowed in GROUP BY clause");
2422 if ( IsA (expr, Aggreg) )
2425 if ( IsA (expr, Expr) )
2429 foreach (temp, ((Expr*)expr)->args)
2430 if (!exprIsAggOrGroupCol(lfirst(temp),groupClause))
2439 * parseCheckAggregates -
2440 * this should really be done earlier but the current grammar
2441 * cannot differentiate functions from aggregates. So we have do check
2442 * here when the target list and the qualifications are finalized.
2445 parseCheckAggregates(ParseState *pstate, Query *qry)
2448 Assert(pstate->p_numAgg > 0);
2451 * aggregates never appear in WHERE clauses. (we have to check where
2452 * clause first because if there is an aggregate, the check for
2453 * non-group column in target list may fail.)
2455 if (contain_agg_clause(qry->qual))
2456 elog(WARN, "parser: aggregates not allowed in WHERE clause");
2459 * the target list can only contain aggregates, group columns and
2460 * functions thereof.
2462 foreach (tl, qry->targetList) {
2463 TargetEntry *tle = lfirst(tl);
2464 if (!tleIsAggOrGroupCol(tle, qry->groupClause))
2466 "parser: illegal use of aggregates or non-group column in target list");
2470 * the expression specified in the HAVING clause has the same restriction
2471 * as those in the target list.
2474 * Need to change here when we get HAVING works. Currently
2475 * qry->havingQual is NULL. - vadim 04/05/97
2476 if (!exprIsAggOrGroupCol(qry->havingQual, qry->groupClause))
2478 "parser: illegal use of aggregates or non-group column in HAVING clause");