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.25 1997/04/05 06:29:03 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, res->name);
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->resdom = resdom = restarget->resdom;
1556 grpcl->grpOpoid = oprid(oper("<",
1558 resdom->restype,false));
1560 gl = glist = lcons(grpcl, NIL);
1562 lnext(gl) = lcons(grpcl, NIL);
1565 grouplist = lnext(grouplist);
1572 * transformSortClause -
1573 * transform an Order By clause
1577 transformSortClause(ParseState *pstate,
1578 List *orderlist, List *targetlist,
1581 List *sortlist = NIL;
1584 while(orderlist != NIL) {
1585 SortGroupBy *sortby = lfirst(orderlist);
1586 SortClause *sortcl = makeNode(SortClause);
1587 TargetEntry *restarget;
1590 restarget = find_targetlist_entry(pstate, sortby, targetlist);
1591 if (restarget == NULL)
1592 elog(WARN,"The field being ordered by must appear in the target list");
1594 sortcl->resdom = resdom = restarget->resdom;
1595 sortcl->opoid = oprid(oper(sortby->useOp,
1597 resdom->restype,false));
1598 if (sortlist == NIL) {
1599 s = sortlist = lcons(sortcl, NIL);
1601 lnext(s) = lcons(sortcl, NIL);
1604 orderlist = lnext(orderlist);
1608 if (uniqueFlag[0] == '*') {
1609 /* concatenate all elements from target list
1610 that are not already in the sortby list */
1611 foreach (i,targetlist) {
1612 TargetEntry *tlelt = (TargetEntry *)lfirst(i);
1616 SortClause *sortcl = lfirst(s);
1617 if (sortcl->resdom==tlelt->resdom)
1622 /* not a member of the sortclauses yet */
1623 SortClause *sortcl = makeNode(SortClause);
1625 sortcl->resdom = tlelt->resdom;
1626 sortcl->opoid = any_ordering_op(tlelt->resdom->restype);
1628 sortlist = lappend(sortlist, sortcl);
1633 TargetEntry *tlelt = NULL;
1634 char* uniqueAttrName = uniqueFlag;
1636 /* only create sort clause with the specified unique attribute */
1637 foreach (i, targetlist) {
1638 tlelt = (TargetEntry*)lfirst(i);
1639 if (strcmp(tlelt->resdom->resname, uniqueAttrName) == 0)
1643 elog(WARN, "The field specified in the UNIQUE ON clause is not in the targetlist");
1646 foreach (s, sortlist) {
1647 SortClause *sortcl = lfirst(s);
1648 if (sortcl->resdom == tlelt->resdom)
1652 /* not a member of the sortclauses yet */
1653 SortClause *sortcl = makeNode(SortClause);
1655 sortcl->resdom = tlelt->resdom;
1656 sortcl->opoid = any_ordering_op(tlelt->resdom->restype);
1658 sortlist = lappend(sortlist, sortcl);
1668 ** HandleNestedDots --
1669 ** Given a nested dot expression (i.e. (relation func ... attr), build up
1670 ** a tree with of Iter and Func nodes.
1673 handleNestedDots(ParseState *pstate, Attr *attr, int *curr_resno)
1676 Node *retval = NULL;
1678 if (attr->paramNo != NULL) {
1679 Param *param = (Param *)transformExpr(pstate, (Node*)attr->paramNo, EXPR_RELATION_FIRST);
1682 ParseFunc(pstate, strVal(lfirst(attr->attrs)),
1686 Ident *ident = makeNode(Ident);
1688 ident->name = attr->relname;
1689 ident->isRel = TRUE;
1691 ParseFunc(pstate, strVal(lfirst(attr->attrs)),
1696 foreach (mutator_iter, lnext(attr->attrs)) {
1697 retval = ParseFunc(pstate,strVal(lfirst(mutator_iter)),
1706 ** make_arguments --
1707 ** Given the number and types of arguments to a function, and the
1708 ** actual arguments and argument types, do the necessary typecasting.
1711 make_arguments(int nargs,
1714 Oid *function_typeids)
1717 * there are two ways an input typeid can differ from a function typeid :
1718 * either the input type inherits the function type, so no typecasting is
1719 * necessary, or the input type can be typecast into the function type.
1720 * right now, we only typecast unknowns, and that is all we check for.
1723 List *current_fargs;
1726 for (i=0, current_fargs = fargs;
1728 i++, current_fargs = lnext(current_fargs)) {
1730 if (input_typeids[i] == UNKNOWNOID && function_typeids[i] != InvalidOid) {
1731 lfirst(current_fargs) =
1732 parser_typecast2(lfirst(current_fargs),
1734 get_id_type(function_typeids[i]),
1742 ** Build a tlist that says which attribute to project to.
1743 ** This routine is called by ParseFunc() to set up a target list
1744 ** on a tuple parameter or return value. Due to a bug in 4.0,
1745 ** it's not possible to refer to system attributes in this case.
1748 setup_tlist(char *attname, Oid relid)
1756 attno = get_attnum(relid, attname);
1758 elog(WARN, "cannot reference attribute %s of tuple params/return values for functions", attname);
1760 typeid = find_atttype(relid, attname);
1761 resnode = makeResdom(1,
1763 tlen(get_id_type(typeid)),
1764 get_attname(relid, attno),
1768 varnode = makeVar(-1, attno, typeid, -1, attno);
1770 tle = makeNode(TargetEntry);
1771 tle->resdom = resnode;
1772 tle->expr = (Node*)varnode;
1773 return (lcons(tle, NIL));
1777 ** setup_base_tlist --
1778 ** Build a tlist that extracts a base type from the tuple
1779 ** returned by the executor.
1782 setup_base_tlist(Oid typeid)
1788 resnode = makeResdom(1,
1790 tlen(get_id_type(typeid)),
1795 varnode = makeVar(-1, 1, typeid, -1, 1);
1796 tle = makeNode(TargetEntry);
1797 tle->resdom = resnode;
1798 tle->expr = (Node*)varnode;
1800 return (lcons(tle, NIL));
1804 * ParseComplexProjection -
1805 * handles function calls with a single argument that is of complex type.
1806 * This routine returns NULL if it can't handle the projection (eg. sets).
1809 ParseComplexProjection(ParseState *pstate,
1821 switch (nodeTag(first_arg)) {
1827 iter = (Iter*)first_arg;
1828 func = (Func *)((Expr*)iter->iterexpr)->oper;
1829 argtype = funcid_get_rettype(func->funcid);
1830 argrelid = typeid_get_relid(argtype);
1832 ((attnum = get_attnum(argrelid, funcname))
1833 != InvalidAttrNumber)) {
1835 /* the argument is a function returning a tuple, so funcname
1836 may be a projection */
1838 /* add a tlist to the func node and return the Iter */
1839 rd = heap_openr(tname(get_id_type(argtype)));
1840 if (RelationIsValid(rd)) {
1841 relid = RelationGetRelationId(rd);
1842 relname = RelationGetRelationName(rd);
1845 if (RelationIsValid(rd)) {
1847 setup_tlist(funcname, argrelid);
1848 iter->itertype = att_typeid(rd,attnum);
1849 return ((Node*)iter);
1852 "Function %s has bad returntype %d",
1864 * The argument is a set, so this is either a projection
1865 * or a function call on this set.
1872 Expr *expr = (Expr*)first_arg;
1875 if (expr->opType != FUNC_EXPR)
1878 funcnode= (Func *) expr->oper;
1879 argtype = funcid_get_rettype(funcnode->funcid);
1880 argrelid = typeid_get_relid(argtype);
1882 * the argument is a function returning a tuple, so funcname
1883 * may be a projection
1886 (attnum = get_attnum(argrelid, funcname))
1887 != InvalidAttrNumber) {
1889 /* add a tlist to the func node */
1890 rd = heap_openr(tname(get_id_type(argtype)));
1891 if (RelationIsValid(rd)) {
1892 relid = RelationGetRelationId(rd);
1893 relname = RelationGetRelationName(rd);
1896 if (RelationIsValid(rd)) {
1899 funcnode->func_tlist =
1900 setup_tlist(funcname, argrelid);
1901 funcnode->functype = att_typeid(rd,attnum);
1903 newexpr = makeNode(Expr);
1904 newexpr->typeOid = funcnode->functype;
1905 newexpr->opType = FUNC_EXPR;
1906 newexpr->oper = (Node *)funcnode;
1907 newexpr->args = lcons(first_arg, NIL);
1909 return ((Node*)newexpr);
1914 elog(WARN, "Function %s has bad returntype %d",
1920 Param *param = (Param*)first_arg;
1922 * If the Param is a complex type, this could be a projection
1924 rd = heap_openr(tname(get_id_type(param->paramtype)));
1925 if (RelationIsValid(rd)) {
1926 relid = RelationGetRelationId(rd);
1927 relname = RelationGetRelationName(rd);
1930 if (RelationIsValid(rd) &&
1931 (attnum = get_attnum(relid, funcname))
1932 != InvalidAttrNumber) {
1934 param->paramtype = att_typeid(rd, attnum);
1935 param->param_tlist = setup_tlist(funcname, relid);
1936 return ((Node*)param);
1948 ParseFunc(ParseState *pstate, char *funcname, List *fargs, int *curr_resno)
1950 Oid rettype = (Oid)0;
1951 Oid argrelid = (Oid)0;
1952 Oid funcid = (Oid)0;
1954 Node *first_arg= NULL;
1955 char *relname = NULL;
1956 char *refname = NULL;
1962 Oid *true_oid_array;
1966 bool attisset = false;
1971 first_arg = lfirst(fargs);
1972 if (first_arg == NULL)
1973 elog (WARN,"function %s does not allow NULL input",funcname);
1977 ** check for projection methods: if function takes one argument, and
1978 ** that argument is a relation, param, or PQ function returning a complex
1979 ** type, then the function could be a projection.
1981 if (length(fargs) == 1) {
1983 if (nodeTag(first_arg)==T_Ident && ((Ident*)first_arg)->isRel) {
1985 Ident *ident = (Ident*)first_arg;
1988 * first arg is a relation. This could be a projection.
1990 refname = ident->name;
1992 rte = refnameRangeTableEntry(pstate->p_rtable, refname);
1994 rte = addRangeTableEntry(pstate, refname, refname, FALSE, FALSE,NULL);
1996 relname = rte->relname;
1999 /* If the attr isn't a set, just make a var for it. If
2000 * it is a set, treat it like a function and drop through.
2002 if (get_attnum(relid, funcname) != InvalidAttrNumber) {
2006 ((Node*)make_var(pstate,
2011 /* drop through - attr is a set */
2014 } else if (ISCOMPLEX(exprType(first_arg))) {
2016 * Attempt to handle projection of a complex argument. If
2017 * ParseComplexProjection can't handle the projection, we
2018 * have to keep going.
2020 retval = ParseComplexProjection(pstate,
2025 toid = exprType(first_arg);
2026 rd = heap_openr(tname(get_id_type(toid)));
2027 if (RelationIsValid(rd)) {
2028 relname = RelationGetRelationName(rd)->data;
2032 "Type %s is not a relation type",
2033 tname(get_id_type(toid)));
2034 argrelid = typeid_get_relid(toid);
2035 /* A projection contains either an attribute name or the
2038 if ((get_attnum(argrelid, funcname) == InvalidAttrNumber)
2039 && strcmp(funcname, "*")) {
2040 elog(WARN, "Functions on sets are not yet supported");
2048 * Parsing aggregates.
2051 /* the aggregate count is a special case,
2052 ignore its base type. Treat it as zero */
2053 if (strcmp(funcname, "count") == 0)
2056 basetype = exprType(lfirst(fargs));
2057 if (SearchSysCacheTuple(AGGNAME,
2058 PointerGetDatum(funcname),
2059 ObjectIdGetDatum(basetype),
2061 Aggreg *aggreg = ParseAgg(funcname, basetype, lfirst(fargs));
2063 AddAggToParseState(pstate, aggreg);
2064 return (Node*)aggreg;
2071 ** If we dropped through to here it's really a function (or a set, which
2072 ** is implemented as a function.)
2073 ** extract arg type info and transform relation name arguments into
2074 ** varnodes of the appropriate form.
2076 memset(&oid_array[0], 0, 8 * sizeof(Oid));
2079 foreach ( i , fargs ) {
2082 Node *pair = lfirst(i);
2084 if (nodeTag(pair)==T_Ident && ((Ident*)pair)->isRel) {
2088 refname = ((Ident*)pair)->name;
2090 rte = refnameRangeTableEntry(pstate->p_rtable, refname);
2092 rte = addRangeTableEntry(pstate, refname, refname,
2093 FALSE, FALSE, NULL);
2094 relname = rte->relname;
2096 vnum = refnameRangeTablePosn (pstate->p_rtable, rte->refname);
2099 * for func(relname), the param to the function
2100 * is the tuple under consideration. we build a special
2101 * VarNode to reflect this -- it has varno set to the
2102 * correct range table entry, but has varattno == 0 to
2103 * signal that the whole tuple is the argument.
2105 toid = typeid(type(relname));
2106 /* replace it in the arg list */
2108 makeVar(vnum, 0, toid, vnum, 0);
2109 }else if (!attisset) { /* set functions don't have parameters */
2111 /* any functiona args which are typed "unknown", but aren't
2112 constants, we don't know what to do with, because we
2113 can't cast them - jolly*/
2114 if (exprType(pair) == UNKNOWNOID &&
2117 elog(WARN, "ParseFunc: no function named %s that takes in an unknown type as argument #%d", funcname, nargs);
2120 toid = exprType(pair);
2123 oid_array[nargs++] = toid;
2127 * func_get_detail looks up the function in the catalogs, does
2128 * disambiguation for polymorphic functions, handles inheritance,
2129 * and returns the funcid and type and set or singleton status of
2130 * the function's return value. it also returns the true argument
2131 * types to the function. if func_get_detail returns true,
2132 * the function exists. otherwise, there was an error.
2134 if (attisset) { /* we know all of these fields already */
2135 /* We create a funcnode with a placeholder function SetEval.
2136 * SetEval() never actually gets executed. When the function
2137 * evaluation routines see it, they use the funcid projected
2138 * out from the relation as the actual function to call.
2139 * Example: retrieve (emp.mgr.name)
2140 * The plan for this will scan the emp relation, projecting
2141 * out the mgr attribute, which is a funcid. This function
2142 * is then called (instead of SetEval) and "name" is projected
2145 funcid = SetEvalRegProcedure;
2148 true_oid_array = oid_array;
2151 exists = func_get_detail(funcname, nargs, oid_array, &funcid,
2152 &rettype, &retset, &true_oid_array);
2156 elog(WARN, "no such attribute or function %s", funcname);
2159 funcnode = makeNode(Func);
2160 funcnode->funcid = funcid;
2161 funcnode->functype = rettype;
2162 funcnode->funcisindex = false;
2163 funcnode->funcsize = 0;
2164 funcnode->func_fcache = NULL;
2165 funcnode->func_tlist = NIL;
2166 funcnode->func_planlist = NIL;
2168 /* perform the necessary typecasting */
2169 make_arguments(nargs, fargs, oid_array, true_oid_array);
2172 * for functions returning base types, we want to project out the
2173 * return value. set up a target list to do that. the executor
2174 * will ignore these for c functions, and do the right thing for
2175 * postquel functions.
2178 if (typeid_get_relid(rettype) == InvalidOid)
2179 funcnode->func_tlist = setup_base_tlist(rettype);
2181 /* For sets, we want to make a targetlist to project out this
2182 * attribute of the set tuples.
2185 if (!strcmp(funcname, "*")) {
2186 funcnode->func_tlist =
2187 expandAll(pstate, relname, refname, curr_resno);
2189 funcnode->func_tlist = setup_tlist(funcname,argrelid);
2190 rettype = find_atttype(argrelid, funcname);
2195 * Sequence handling.
2197 if ( funcid == SeqNextValueRegProcedure ||
2198 funcid == SeqCurrValueRegProcedure )
2202 int32 aclcheck_result = -1;
2204 Assert ( length(fargs) == 1 );
2205 seq = (Const*)lfirst(fargs);
2206 if ( ! IsA ((Node*)seq, Const) )
2207 elog (WARN, "%s: only constant sequence names are acceptable", funcname);
2208 seqrel = textout ((struct varlena *) (seq->constvalue));
2210 if ( ( aclcheck_result = pg_aclcheck (seqrel, GetPgUserName(),
2211 ((funcid == SeqNextValueRegProcedure) ? ACL_WR : ACL_RD)) )
2213 elog (WARN, "%s.%s: %s",
2214 seqrel, funcname, aclcheck_error_strings[aclcheck_result]);
2218 if ( funcid == SeqNextValueRegProcedure && inWhereClause )
2219 elog (WARN, "nextval of a sequence in WHERE disallowed");
2222 expr = makeNode(Expr);
2223 expr->typeOid = rettype;
2224 expr->opType = FUNC_EXPR;
2225 expr->oper = (Node *)funcnode;
2227 retval = (Node*)expr;
2230 * if the function returns a set of values, then we need to iterate
2231 * over all the returned values in the executor, so we stick an
2232 * iter node here. if it returns a singleton, then we don't need
2237 Iter *iter = makeNode(Iter);
2238 iter->itertype = rettype;
2239 iter->iterexpr = retval;
2240 retval = (Node*)iter;
2246 /*****************************************************************************
2248 *****************************************************************************/
2251 * AddAggToParseState -
2252 * add the aggregate to the list of unique aggregates in pstate.
2254 * SIDE EFFECT: aggno in target list entry will be modified
2257 AddAggToParseState(ParseState *pstate, Aggreg *aggreg)
2263 * see if we have the aggregate already (we only need to record
2264 * the aggregate once)
2267 foreach(ag, pstate->p_aggs) {
2268 Aggreg *a = lfirst(ag);
2270 if (!strcmp(a->aggname, aggreg->aggname) &&
2271 equal(a->target, aggreg->target)) {
2273 /* fill in the aggno and we're done */
2280 /* not found, new aggregate */
2283 pstate->p_aggs = lappend(pstate->p_aggs, aggreg);
2288 * finalizeAggregates -
2289 * fill in qry_aggs from pstate. Also checks to make sure that aggregates
2290 * are used in the proper place.
2293 finalizeAggregates(ParseState *pstate, Query *qry)
2298 parseCheckAggregates(pstate, qry);
2300 qry->qry_numAgg = pstate->p_numAgg;
2302 (Aggreg **)palloc(sizeof(Aggreg *) * qry->qry_numAgg);
2304 foreach(l, pstate->p_aggs)
2305 qry->qry_aggs[i++] = (Aggreg*)lfirst(l);
2309 * contain_agg_clause--
2310 * Recursively find aggreg nodes from a clause.
2312 * Returns true if any aggregate found.
2315 contain_agg_clause(Node *clause)
2319 else if (IsA(clause,Aggreg))
2321 else if (IsA(clause,Iter))
2322 return contain_agg_clause(((Iter*)clause)->iterexpr);
2323 else if (single_node(clause))
2325 else if (or_clause(clause)) {
2328 foreach (temp, ((Expr*)clause)->args)
2329 if (contain_agg_clause(lfirst(temp)))
2332 } else if (is_funcclause (clause)) {
2335 foreach(temp, ((Expr *)clause)->args)
2336 if (contain_agg_clause(lfirst(temp)))
2339 } else if (IsA(clause,ArrayRef)) {
2342 foreach(temp, ((ArrayRef*)clause)->refupperindexpr)
2343 if (contain_agg_clause(lfirst(temp)))
2345 foreach(temp, ((ArrayRef*)clause)->reflowerindexpr)
2346 if (contain_agg_clause(lfirst(temp)))
2348 if (contain_agg_clause(((ArrayRef*)clause)->refexpr))
2350 if (contain_agg_clause(((ArrayRef*)clause)->refassgnexpr))
2353 } else if (not_clause(clause))
2354 return contain_agg_clause((Node*)get_notclausearg((Expr*)clause));
2355 else if (is_opclause(clause))
2356 return (contain_agg_clause((Node*)get_leftop((Expr*)clause)) ||
2357 contain_agg_clause((Node*)get_rightop((Expr*)clause)));
2363 * tleIsAggOrGroupCol -
2364 * returns true if the TargetEntry is Agg or GroupCol.
2367 tleIsAggOrGroupCol(TargetEntry *tle, List *groupClause)
2369 Node *expr = tle->expr;
2372 if ( expr == NULL || IsA (expr, Const) )
2375 foreach (gl, groupClause)
2377 GroupClause *grpcl = lfirst(gl);
2379 if ( tle->resdom->resno == grpcl->resdom->resno )
2381 if ( IsA (expr, Aggreg) )
2382 elog (WARN, "parser: aggregates not allowed in GROUP BY clause");
2387 if ( IsA (expr, Aggreg) )
2393 #if 0 /* Now GroupBy contains resdom to enable Group By func_results */
2395 * exprIsAggOrGroupCol -
2396 * returns true if the expression does not contain non-group columns.
2399 exprIsAggOrGroupCol(Node *expr, List *groupClause)
2403 else if (IsA(expr,Const))
2405 else if (IsA(expr,Var)) {
2407 Var *var = (Var*)expr;
2409 * only group columns are legal
2411 foreach (gl, groupClause) {
2412 GroupClause *grpcl = lfirst(gl);
2413 if ((grpcl->grpAttr->varno == var->varno) &&
2414 (grpcl->grpAttr->varattno == var->varattno))
2418 } else if (IsA(expr,Aggreg))
2419 /* aggregates can take group column or non-group column as argument,
2420 no further check necessary. */
2422 else if (IsA(expr,Expr)) {
2425 foreach (temp, ((Expr*)expr)->args)
2426 if (!exprIsAggOrGroupCol(lfirst(temp),groupClause))
2436 * parseCheckAggregates -
2437 * this should really be done earlier but the current grammar
2438 * cannot differentiate functions from aggregates. So we have do check
2439 * here when the target list and the qualifications are finalized.
2442 parseCheckAggregates(ParseState *pstate, Query *qry)
2445 Assert(pstate->p_numAgg > 0);
2448 * aggregates never appear in WHERE clauses. (we have to check where
2449 * clause first because if there is an aggregate, the check for
2450 * non-group column in target list may fail.)
2452 if (contain_agg_clause(qry->qual))
2453 elog(WARN, "parser: aggregates not allowed in WHERE clause");
2456 * the target list can only contain aggregates, group columns and
2457 * functions thereof.
2459 foreach (tl, qry->targetList) {
2460 TargetEntry *tle = lfirst(tl);
2461 if (!tleIsAggOrGroupCol(tle, qry->groupClause))
2463 "parser: illegal use of aggregates or non-group column in target list");
2467 * the expression specified in the HAVING clause has the same restriction
2468 * as those in the target list.
2471 * Need to change here when we get HAVING works. Currently
2472 * qry->havingQual is NULL. - vadim 04/05/97
2473 if (!exprIsAggOrGroupCol(qry->havingQual, qry->groupClause))
2475 "parser: illegal use of aggregates or non-group column in HAVING clause");