1 /*-------------------------------------------------------------------------
4 * transform the parse tree into a query tree
6 * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
9 * $PostgreSQL: pgsql/src/backend/parser/analyze.c,v 1.309 2004/08/22 00:08:28 tgl Exp $
11 *-------------------------------------------------------------------------
16 #include "access/heapam.h"
17 #include "catalog/catname.h"
18 #include "catalog/heap.h"
19 #include "catalog/index.h"
20 #include "catalog/namespace.h"
21 #include "catalog/pg_index.h"
22 #include "catalog/pg_type.h"
23 #include "commands/defrem.h"
24 #include "commands/prepare.h"
25 #include "miscadmin.h"
26 #include "nodes/makefuncs.h"
27 #include "optimizer/clauses.h"
28 #include "optimizer/var.h"
29 #include "parser/analyze.h"
30 #include "parser/gramparse.h"
31 #include "parser/parsetree.h"
32 #include "parser/parse_agg.h"
33 #include "parser/parse_clause.h"
34 #include "parser/parse_coerce.h"
35 #include "parser/parse_expr.h"
36 #include "parser/parse_oper.h"
37 #include "parser/parse_relation.h"
38 #include "parser/parse_target.h"
39 #include "parser/parse_type.h"
40 #include "parser/parse_expr.h"
41 #include "rewrite/rewriteManip.h"
42 #include "utils/acl.h"
43 #include "utils/builtins.h"
44 #include "utils/fmgroids.h"
45 #include "utils/guc.h"
46 #include "utils/lsyscache.h"
47 #include "utils/relcache.h"
48 #include "utils/syscache.h"
51 /* State shared by transformCreateSchemaStmt and its subroutines */
54 const char *stmtType; /* "CREATE SCHEMA" or "ALTER SCHEMA" */
55 char *schemaname; /* name of schema */
56 char *authid; /* owner of schema */
57 List *sequences; /* CREATE SEQUENCE items */
58 List *tables; /* CREATE TABLE items */
59 List *views; /* CREATE VIEW items */
60 List *indexes; /* CREATE INDEX items */
61 List *triggers; /* CREATE TRIGGER items */
62 List *grants; /* GRANT items */
63 List *fwconstraints; /* Forward referencing FOREIGN KEY
65 List *alters; /* Generated ALTER items (from the above) */
66 List *ixconstraints; /* index-creating constraints */
67 List *blist; /* "before list" of things to do before
68 * creating the schema */
69 List *alist; /* "after list" of things to do after
70 * creating the schema */
71 } CreateSchemaStmtContext;
73 /* State shared by transformCreateStmt and its subroutines */
76 const char *stmtType; /* "CREATE TABLE" or "ALTER TABLE" */
77 RangeVar *relation; /* relation to create */
78 List *inhRelations; /* relations to inherit from */
79 bool hasoids; /* does relation have an OID column? */
80 bool isalter; /* true if altering existing table */
81 List *columns; /* ColumnDef items */
82 List *ckconstraints; /* CHECK constraints */
83 List *fkconstraints; /* FOREIGN KEY constraints */
84 List *ixconstraints; /* index-creating constraints */
85 List *blist; /* "before list" of things to do before
86 * creating the table */
87 List *alist; /* "after list" of things to do after
88 * creating the table */
89 IndexStmt *pkey; /* PRIMARY KEY index, if any */
96 } check_parameter_resolution_context;
99 static List *do_parse_analyze(Node *parseTree, ParseState *pstate);
100 static Query *transformStmt(ParseState *pstate, Node *stmt,
101 List **extras_before, List **extras_after);
102 static Query *transformViewStmt(ParseState *pstate, ViewStmt *stmt,
103 List **extras_before, List **extras_after);
104 static Query *transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt);
105 static Query *transformInsertStmt(ParseState *pstate, InsertStmt *stmt,
106 List **extras_before, List **extras_after);
107 static Query *transformIndexStmt(ParseState *pstate, IndexStmt *stmt);
108 static Query *transformRuleStmt(ParseState *query, RuleStmt *stmt,
109 List **extras_before, List **extras_after);
110 static Query *transformSelectStmt(ParseState *pstate, SelectStmt *stmt);
111 static Query *transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt);
112 static Node *transformSetOperationTree(ParseState *pstate, SelectStmt *stmt);
113 static Query *transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt);
114 static Query *transformDeclareCursorStmt(ParseState *pstate,
115 DeclareCursorStmt *stmt);
116 static Query *transformPrepareStmt(ParseState *pstate, PrepareStmt *stmt);
117 static Query *transformExecuteStmt(ParseState *pstate, ExecuteStmt *stmt);
118 static Query *transformCreateStmt(ParseState *pstate, CreateStmt *stmt,
119 List **extras_before, List **extras_after);
120 static Query *transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt,
121 List **extras_before, List **extras_after);
122 static void transformColumnDefinition(ParseState *pstate,
123 CreateStmtContext *cxt,
125 static void transformTableConstraint(ParseState *pstate,
126 CreateStmtContext *cxt,
127 Constraint *constraint);
128 static void transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
129 InhRelation *inhrelation);
130 static void transformIndexConstraints(ParseState *pstate,
131 CreateStmtContext *cxt);
132 static void transformFKConstraints(ParseState *pstate,
133 CreateStmtContext *cxt,
135 bool isAddConstraint);
136 static void applyColumnNames(List *dst, List *src);
137 static List *getSetColTypes(ParseState *pstate, Node *node);
138 static void transformForUpdate(Query *qry, List *forUpdate);
139 static void transformConstraintAttrs(List *constraintList);
140 static void transformColumnType(ParseState *pstate, ColumnDef *column);
141 static void release_pstate_resources(ParseState *pstate);
142 static FromExpr *makeFromExpr(List *fromlist, Node *quals);
143 static bool check_parameter_resolution_walker(Node *node,
144 check_parameter_resolution_context *context);
149 * Analyze a raw parse tree and transform it to Query form.
151 * Optionally, information about $n parameter types can be supplied.
152 * References to $n indexes not defined by paramTypes[] are disallowed.
154 * The result is a List of Query nodes (we need a list since some commands
155 * produce multiple Queries). Optimizable statements require considerable
156 * transformation, while many utility-type statements are simply hung off
157 * a dummy CMD_UTILITY Query node.
160 parse_analyze(Node *parseTree, Oid *paramTypes, int numParams)
162 ParseState *pstate = make_parsestate(NULL);
165 pstate->p_paramtypes = paramTypes;
166 pstate->p_numparams = numParams;
167 pstate->p_variableparams = false;
169 result = do_parse_analyze(parseTree, pstate);
177 * parse_analyze_varparams
179 * This variant is used when it's okay to deduce information about $n
180 * symbol datatypes from context. The passed-in paramTypes[] array can
181 * be modified or enlarged (via repalloc).
184 parse_analyze_varparams(Node *parseTree, Oid **paramTypes, int *numParams)
186 ParseState *pstate = make_parsestate(NULL);
189 pstate->p_paramtypes = *paramTypes;
190 pstate->p_numparams = *numParams;
191 pstate->p_variableparams = true;
193 result = do_parse_analyze(parseTree, pstate);
195 *paramTypes = pstate->p_paramtypes;
196 *numParams = pstate->p_numparams;
200 /* make sure all is well with parameter types */
203 check_parameter_resolution_context context;
205 context.paramTypes = *paramTypes;
206 context.numParams = *numParams;
207 check_parameter_resolution_walker((Node *) result, &context);
215 * Entry point for recursively analyzing a sub-statement.
218 parse_sub_analyze(Node *parseTree, ParseState *parentParseState)
220 ParseState *pstate = make_parsestate(parentParseState);
223 result = do_parse_analyze(parseTree, pstate);
232 * Workhorse code shared by the above variants of parse_analyze.
235 do_parse_analyze(Node *parseTree, ParseState *pstate)
239 /* Lists to return extra commands from transformation */
240 List *extras_before = NIL;
241 List *extras_after = NIL;
245 query = transformStmt(pstate, parseTree, &extras_before, &extras_after);
247 /* don't need to access result relation any more */
248 release_pstate_resources(pstate);
250 foreach(l, extras_before)
251 result = list_concat(result, parse_sub_analyze(lfirst(l), pstate));
253 result = lappend(result, query);
255 foreach(l, extras_after)
256 result = list_concat(result, parse_sub_analyze(lfirst(l), pstate));
259 * Make sure that only the original query is marked original. We have
260 * to do this explicitly since recursive calls of do_parse_analyze
261 * will have marked some of the added-on queries as "original". Also
262 * mark only the original query as allowed to set the command-result
267 Query *q = lfirst(l);
271 q->querySource = QSRC_ORIGINAL;
276 q->querySource = QSRC_PARSER;
277 q->canSetTag = false;
285 release_pstate_resources(ParseState *pstate)
287 if (pstate->p_target_relation != NULL)
288 heap_close(pstate->p_target_relation, NoLock);
289 pstate->p_target_relation = NULL;
290 pstate->p_target_rangetblentry = NULL;
295 * transform a Parse tree into a Query tree.
298 transformStmt(ParseState *pstate, Node *parseTree,
299 List **extras_before, List **extras_after)
301 Query *result = NULL;
303 switch (nodeTag(parseTree))
306 * Non-optimizable statements
309 result = transformCreateStmt(pstate, (CreateStmt *) parseTree,
310 extras_before, extras_after);
314 result = transformIndexStmt(pstate, (IndexStmt *) parseTree);
318 result = transformRuleStmt(pstate, (RuleStmt *) parseTree,
319 extras_before, extras_after);
323 result = transformViewStmt(pstate, (ViewStmt *) parseTree,
324 extras_before, extras_after);
329 ExplainStmt *n = (ExplainStmt *) parseTree;
331 result = makeNode(Query);
332 result->commandType = CMD_UTILITY;
333 n->query = transformStmt(pstate, (Node *) n->query,
334 extras_before, extras_after);
335 result->utilityStmt = (Node *) parseTree;
339 case T_AlterTableStmt:
340 result = transformAlterTableStmt(pstate,
341 (AlterTableStmt *) parseTree,
342 extras_before, extras_after);
346 result = transformPrepareStmt(pstate, (PrepareStmt *) parseTree);
350 result = transformExecuteStmt(pstate, (ExecuteStmt *) parseTree);
354 * Optimizable statements
357 result = transformInsertStmt(pstate, (InsertStmt *) parseTree,
358 extras_before, extras_after);
362 result = transformDeleteStmt(pstate, (DeleteStmt *) parseTree);
366 result = transformUpdateStmt(pstate, (UpdateStmt *) parseTree);
370 if (((SelectStmt *) parseTree)->op == SETOP_NONE)
371 result = transformSelectStmt(pstate,
372 (SelectStmt *) parseTree);
374 result = transformSetOperationStmt(pstate,
375 (SelectStmt *) parseTree);
378 case T_DeclareCursorStmt:
379 result = transformDeclareCursorStmt(pstate,
380 (DeclareCursorStmt *) parseTree);
386 * other statements don't require any transformation-- just
387 * return the original parsetree, yea!
389 result = makeNode(Query);
390 result->commandType = CMD_UTILITY;
391 result->utilityStmt = (Node *) parseTree;
395 /* Mark as original query until we learn differently */
396 result->querySource = QSRC_ORIGINAL;
397 result->canSetTag = true;
403 transformViewStmt(ParseState *pstate, ViewStmt *stmt,
404 List **extras_before, List **extras_after)
406 Query *result = makeNode(Query);
408 result->commandType = CMD_UTILITY;
409 result->utilityStmt = (Node *) stmt;
411 stmt->query = transformStmt(pstate, (Node *) stmt->query,
412 extras_before, extras_after);
415 * If a list of column names was given, run through and insert
416 * these into the actual query tree. - thomas 2000-03-08
418 * Outer loop is over targetlist to make it easier to skip junk
419 * targetlist entries.
421 if (stmt->aliases != NIL)
423 ListCell *alist_item = list_head(stmt->aliases);
424 ListCell *targetList;
426 foreach(targetList, stmt->query->targetList)
428 TargetEntry *te = (TargetEntry *) lfirst(targetList);
431 Assert(IsA(te, TargetEntry));
433 Assert(IsA(rd, Resdom));
434 /* junk columns don't get aliases */
437 rd->resname = pstrdup(strVal(lfirst(alist_item)));
438 alist_item = lnext(alist_item);
439 if (alist_item == NULL)
440 break; /* done assigning aliases */
443 if (alist_item != NULL)
445 (errcode(ERRCODE_SYNTAX_ERROR),
446 errmsg("CREATE VIEW specifies more column "
447 "names than columns")));
454 * transformDeleteStmt -
455 * transforms a Delete Statement
458 transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
460 Query *qry = makeNode(Query);
463 qry->commandType = CMD_DELETE;
465 /* set up range table with just the result rel */
466 qry->resultRelation = setTargetTable(pstate, stmt->relation,
467 interpretInhOption(stmt->relation->inhOpt),
471 qry->distinctClause = NIL;
473 /* fix where clause */
474 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
476 /* done building the range table and jointree */
477 qry->rtable = pstate->p_rtable;
478 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
480 qry->hasSubLinks = pstate->p_hasSubLinks;
481 qry->hasAggs = pstate->p_hasAggs;
482 if (pstate->p_hasAggs)
483 parseCheckAggregates(pstate, qry);
489 * transformInsertStmt -
490 * transform an Insert Statement
493 transformInsertStmt(ParseState *pstate, InsertStmt *stmt,
494 List **extras_before, List **extras_after)
496 Query *qry = makeNode(Query);
505 qry->commandType = CMD_INSERT;
506 pstate->p_is_insert = true;
509 * If a non-nil rangetable/namespace was passed in, and we are doing
510 * INSERT/SELECT, arrange to pass the rangetable/namespace down to the
511 * SELECT. This can only happen if we are inside a CREATE RULE, and
512 * in that case we want the rule's OLD and NEW rtable entries to
513 * appear as part of the SELECT's rtable, not as outer references for
514 * it. (Kluge!) The SELECT's joinlist is not affected however. We
515 * must do this before adding the target table to the INSERT's rtable.
517 if (stmt->selectStmt)
519 sub_rtable = pstate->p_rtable;
520 pstate->p_rtable = NIL;
521 sub_namespace = pstate->p_namespace;
522 pstate->p_namespace = NIL;
526 sub_rtable = NIL; /* not used, but keep compiler quiet */
531 * Must get write lock on INSERT target table before scanning SELECT,
532 * else we will grab the wrong kind of initial lock if the target
533 * table is also mentioned in the SELECT part. Note that the target
534 * table is not added to the joinlist or namespace.
536 qry->resultRelation = setTargetTable(pstate, stmt->relation,
537 false, false, ACL_INSERT);
540 * Is it INSERT ... SELECT or INSERT ... VALUES?
542 if (stmt->selectStmt)
545 * We make the sub-pstate a child of the outer pstate so that it
546 * can see any Param definitions supplied from above. Since the
547 * outer pstate's rtable and namespace are presently empty, there
548 * are no side-effects of exposing names the sub-SELECT shouldn't
551 ParseState *sub_pstate = make_parsestate(pstate);
557 * Process the source SELECT.
559 * It is important that this be handled just like a standalone
560 * SELECT; otherwise the behavior of SELECT within INSERT might be
561 * different from a stand-alone SELECT. (Indeed, Postgres up
562 * through 6.5 had bugs of just that nature...)
564 sub_pstate->p_rtable = sub_rtable;
565 sub_pstate->p_namespace = sub_namespace;
568 * Note: we are not expecting that extras_before and extras_after
569 * are going to be used by the transformation of the SELECT
572 selectQuery = transformStmt(sub_pstate, stmt->selectStmt,
573 extras_before, extras_after);
575 release_pstate_resources(sub_pstate);
578 Assert(IsA(selectQuery, Query));
579 Assert(selectQuery->commandType == CMD_SELECT);
580 if (selectQuery->into)
582 (errcode(ERRCODE_SYNTAX_ERROR),
583 errmsg("INSERT ... SELECT may not specify INTO")));
586 * Make the source be a subquery in the INSERT's rangetable, and
587 * add it to the INSERT's joinlist.
589 rte = addRangeTableEntryForSubquery(pstate,
591 makeAlias("*SELECT*", NIL),
593 rtr = makeNode(RangeTblRef);
594 /* assume new rte is at end */
595 rtr->rtindex = list_length(pstate->p_rtable);
596 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
597 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
600 * Generate a targetlist for the INSERT that selects all the
601 * non-resjunk columns from the subquery. (We need this to be
602 * separate from the subquery's tlist because we may add columns,
603 * insert datatype coercions, etc.)
605 * HACK: unknown-type constants and params in the INSERT's targetlist
606 * are copied up as-is rather than being referenced as subquery
607 * outputs. This is to ensure that when we try to coerce them to
608 * the target column's datatype, the right things happen (see
609 * special cases in coerce_type). Otherwise, this fails: INSERT
610 * INTO foo SELECT 'bar', ... FROM baz
612 qry->targetList = NIL;
613 foreach(tl, selectQuery->targetList)
615 TargetEntry *tle = (TargetEntry *) lfirst(tl);
616 Resdom *resnode = tle->resdom;
619 if (resnode->resjunk)
622 (IsA(tle->expr, Const) ||IsA(tle->expr, Param)) &&
623 exprType((Node *) tle->expr) == UNKNOWNOID)
626 expr = (Expr *) makeVar(rtr->rtindex,
631 resnode = copyObject(resnode);
632 resnode->resno = (AttrNumber) pstate->p_next_resno++;
633 qry->targetList = lappend(qry->targetList,
634 makeTargetEntry(resnode, expr));
640 * For INSERT ... VALUES, transform the given list of values to
641 * form a targetlist for the INSERT.
643 qry->targetList = transformTargetList(pstate, stmt->targetList);
647 * Now we are done with SELECT-like processing, and can get on with
648 * transforming the target list to match the INSERT target columns.
651 /* Prepare to assign non-conflicting resnos to resjunk attributes */
652 if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
653 pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
655 /* Validate stmt->cols list, or build default list if no list given */
656 icolumns = checkInsertTargets(pstate, stmt->cols, &attrnos);
659 * Prepare columns for assignment to target table.
661 icols = list_head(icolumns);
662 attnos = list_head(attrnos);
663 foreach(tl, qry->targetList)
665 TargetEntry *tle = (TargetEntry *) lfirst(tl);
668 if (icols == NULL || attnos == NULL)
670 (errcode(ERRCODE_SYNTAX_ERROR),
671 errmsg("INSERT has more expressions than target columns")));
673 col = (ResTarget *) lfirst(icols);
674 Assert(IsA(col, ResTarget));
676 Assert(!tle->resdom->resjunk);
677 updateTargetListEntry(pstate, tle, col->name, lfirst_int(attnos),
680 icols = lnext(icols);
681 attnos = lnext(attnos);
685 * Ensure that the targetlist has the same number of entries that were
686 * present in the columns list. Don't do the check unless an explicit
687 * columns list was given, though.
689 if (stmt->cols != NIL && (icols != NULL || attnos != NULL))
691 (errcode(ERRCODE_SYNTAX_ERROR),
692 errmsg("INSERT has more target columns than expressions")));
694 /* done building the range table and jointree */
695 qry->rtable = pstate->p_rtable;
696 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
698 qry->hasSubLinks = pstate->p_hasSubLinks;
699 qry->hasAggs = pstate->p_hasAggs;
700 if (pstate->p_hasAggs)
701 parseCheckAggregates(pstate, qry);
707 * transformCreateStmt -
708 * transforms the "create table" statement
709 * SQL92 allows constraints to be scattered all over, so thumb through
710 * the columns and collect all constraints into one place.
711 * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
712 * then expand those into multiple IndexStmt blocks.
713 * - thomas 1997-12-02
716 transformCreateStmt(ParseState *pstate, CreateStmt *stmt,
717 List **extras_before, List **extras_after)
719 CreateStmtContext cxt;
723 cxt.stmtType = "CREATE TABLE";
724 cxt.relation = stmt->relation;
725 cxt.inhRelations = stmt->inhRelations;
728 cxt.ckconstraints = NIL;
729 cxt.fkconstraints = NIL;
730 cxt.ixconstraints = NIL;
734 cxt.hasoids = interpretOidsOption(stmt->hasoids);
737 * Run through each primary element in the table creation clause.
738 * Separate column defs from constraints, and do preliminary analysis.
740 foreach(elements, stmt->tableElts)
742 Node *element = lfirst(elements);
744 switch (nodeTag(element))
747 transformColumnDefinition(pstate, &cxt,
748 (ColumnDef *) element);
752 transformTableConstraint(pstate, &cxt,
753 (Constraint *) element);
757 /* No pre-transformation needed */
758 cxt.fkconstraints = lappend(cxt.fkconstraints, element);
762 transformInhRelation(pstate, &cxt,
763 (InhRelation *) element);
767 elog(ERROR, "unrecognized node type: %d",
768 (int) nodeTag(element));
773 Assert(stmt->constraints == NIL);
776 * Postprocess constraints that give rise to index definitions.
778 transformIndexConstraints(pstate, &cxt);
781 * Postprocess foreign-key constraints.
783 transformFKConstraints(pstate, &cxt, true, false);
789 q->commandType = CMD_UTILITY;
790 q->utilityStmt = (Node *) stmt;
791 stmt->tableElts = cxt.columns;
792 stmt->constraints = cxt.ckconstraints;
793 *extras_before = list_concat(*extras_before, cxt.blist);
794 *extras_after = list_concat(cxt.alist, *extras_after);
800 transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
805 Constraint *constraint;
808 cxt->columns = lappend(cxt->columns, column);
810 /* Check for SERIAL pseudo-types */
812 if (list_length(column->typename->names) == 1)
814 char *typname = strVal(linitial(column->typename->names));
816 if (strcmp(typname, "serial") == 0 ||
817 strcmp(typname, "serial4") == 0)
820 column->typename->names = NIL;
821 column->typename->typeid = INT4OID;
823 else if (strcmp(typname, "bigserial") == 0 ||
824 strcmp(typname, "serial8") == 0)
827 column->typename->names = NIL;
828 column->typename->typeid = INT8OID;
832 /* Do necessary work on the column type declaration */
833 transformColumnType(pstate, column);
835 /* Special actions for SERIAL pseudo-types */
843 FuncCall *funccallnode;
844 CreateSeqStmt *seqstmt;
847 * Determine namespace and name to use for the sequence.
849 * Although we use ChooseRelationName, it's not guaranteed that
850 * the selected sequence name won't conflict; given sufficiently
851 * long field names, two different serial columns in the same table
852 * could be assigned the same sequence name, and we'd not notice
853 * since we aren't creating the sequence quite yet. In practice
854 * this seems quite unlikely to be a problem, especially since
855 * few people would need two serial columns in one table.
857 snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
858 snamespace = get_namespace_name(snamespaceid);
859 sname = ChooseRelationName(cxt->relation->relname,
865 (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
866 cxt->stmtType, sname,
867 cxt->relation->relname, column->colname)));
870 * Build a CREATE SEQUENCE command to create the sequence object,
871 * and add it to the list of things to be done before this
872 * CREATE/ALTER TABLE.
874 seqstmt = makeNode(CreateSeqStmt);
875 seqstmt->sequence = makeRangeVar(snamespace, sname);
876 seqstmt->options = NIL;
878 cxt->blist = lappend(cxt->blist, seqstmt);
881 * Mark the ColumnDef so that during execution, an appropriate
882 * dependency will be added from the sequence to the column.
884 column->support = makeRangeVar(snamespace, sname);
887 * Create appropriate constraints for SERIAL. We do this in full,
888 * rather than shortcutting, so that we will detect any
889 * conflicting constraints the user wrote (like a different
892 * Create an expression tree representing the function call
893 * nextval('"sequencename"')
895 qstring = quote_qualified_identifier(snamespace, sname);
896 snamenode = makeNode(A_Const);
897 snamenode->val.type = T_String;
898 snamenode->val.val.str = qstring;
899 funccallnode = makeNode(FuncCall);
900 funccallnode->funcname = SystemFuncName("nextval");
901 funccallnode->args = list_make1(snamenode);
902 funccallnode->agg_star = false;
903 funccallnode->agg_distinct = false;
905 constraint = makeNode(Constraint);
906 constraint->contype = CONSTR_DEFAULT;
907 constraint->raw_expr = (Node *) funccallnode;
908 constraint->cooked_expr = NULL;
909 constraint->keys = NIL;
910 column->constraints = lappend(column->constraints, constraint);
912 constraint = makeNode(Constraint);
913 constraint->contype = CONSTR_NOTNULL;
914 column->constraints = lappend(column->constraints, constraint);
917 /* Process column constraints, if any... */
918 transformConstraintAttrs(column->constraints);
920 saw_nullable = false;
922 foreach(clist, column->constraints)
924 constraint = lfirst(clist);
927 * If this column constraint is a FOREIGN KEY constraint, then we
928 * fill in the current attribute's name and throw it into the list
929 * of FK constraints to be processed later.
931 if (IsA(constraint, FkConstraint))
933 FkConstraint *fkconstraint = (FkConstraint *) constraint;
935 fkconstraint->fk_attrs = list_make1(makeString(column->colname));
936 cxt->fkconstraints = lappend(cxt->fkconstraints, fkconstraint);
940 Assert(IsA(constraint, Constraint));
942 switch (constraint->contype)
945 if (saw_nullable && column->is_not_null)
947 (errcode(ERRCODE_SYNTAX_ERROR),
948 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
949 column->colname, cxt->relation->relname)));
950 column->is_not_null = FALSE;
955 if (saw_nullable && !column->is_not_null)
957 (errcode(ERRCODE_SYNTAX_ERROR),
958 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
959 column->colname, cxt->relation->relname)));
960 column->is_not_null = TRUE;
965 if (column->raw_default != NULL)
967 (errcode(ERRCODE_SYNTAX_ERROR),
968 errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
969 column->colname, cxt->relation->relname)));
970 column->raw_default = constraint->raw_expr;
971 Assert(constraint->cooked_expr == NULL);
976 if (constraint->keys == NIL)
977 constraint->keys = list_make1(makeString(column->colname));
978 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
982 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
985 case CONSTR_ATTR_DEFERRABLE:
986 case CONSTR_ATTR_NOT_DEFERRABLE:
987 case CONSTR_ATTR_DEFERRED:
988 case CONSTR_ATTR_IMMEDIATE:
989 /* transformConstraintAttrs took care of these */
993 elog(ERROR, "unrecognized constraint type: %d",
994 constraint->contype);
1001 transformTableConstraint(ParseState *pstate, CreateStmtContext *cxt,
1002 Constraint *constraint)
1004 switch (constraint->contype)
1006 case CONSTR_PRIMARY:
1008 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
1012 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
1016 case CONSTR_NOTNULL:
1017 case CONSTR_DEFAULT:
1018 case CONSTR_ATTR_DEFERRABLE:
1019 case CONSTR_ATTR_NOT_DEFERRABLE:
1020 case CONSTR_ATTR_DEFERRED:
1021 case CONSTR_ATTR_IMMEDIATE:
1022 elog(ERROR, "invalid context for constraint type %d",
1023 constraint->contype);
1027 elog(ERROR, "unrecognized constraint type: %d",
1028 constraint->contype);
1034 * transformInhRelation
1036 * Change the LIKE <subtable> portion of a CREATE TABLE statement into the
1037 * column definitions which recreate the user defined column portions of <subtable>.
1040 transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
1041 InhRelation *inhRelation)
1043 AttrNumber parent_attno;
1046 TupleDesc tupleDesc;
1047 TupleConstr *constr;
1048 AclResult aclresult;
1050 relation = heap_openrv(inhRelation->relation, AccessShareLock);
1052 if (relation->rd_rel->relkind != RELKIND_RELATION)
1054 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1055 errmsg("inherited relation \"%s\" is not a table",
1056 inhRelation->relation->relname)));
1059 * Check for SELECT privilages
1061 aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
1063 if (aclresult != ACLCHECK_OK)
1064 aclcheck_error(aclresult, ACL_KIND_CLASS,
1065 RelationGetRelationName(relation));
1067 tupleDesc = RelationGetDescr(relation);
1068 constr = tupleDesc->constr;
1071 * Insert the inherited attributes into the cxt for the new table
1074 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1077 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
1078 char *attributeName = NameStr(attribute->attname);
1083 * Ignore dropped columns in the parent.
1085 if (attribute->attisdropped)
1089 * Create a new inherited column.
1091 * For constraints, ONLY the NOT NULL constraint is inherited by the
1092 * new column definition per SQL99.
1094 def = makeNode(ColumnDef);
1095 def->colname = pstrdup(attributeName);
1096 typename = makeNode(TypeName);
1097 typename->typeid = attribute->atttypid;
1098 typename->typmod = attribute->atttypmod;
1099 def->typename = typename;
1101 def->is_local = false;
1102 def->is_not_null = attribute->attnotnull;
1103 def->raw_default = NULL;
1104 def->cooked_default = NULL;
1105 def->constraints = NIL;
1106 def->support = NULL;
1109 * Add to column list
1111 cxt->columns = lappend(cxt->columns, def);
1114 * Copy default if any, and the default has been requested
1116 if (attribute->atthasdef && inhRelation->including_defaults)
1118 char *this_default = NULL;
1119 AttrDefault *attrdef;
1122 /* Find default in constraint structure */
1123 Assert(constr != NULL);
1124 attrdef = constr->defval;
1125 for (i = 0; i < constr->num_defval; i++)
1127 if (attrdef[i].adnum == parent_attno)
1129 this_default = attrdef[i].adbin;
1133 Assert(this_default != NULL);
1136 * If default expr could contain any vars, we'd need to fix
1137 * 'em, but it can't; so default is ready to apply to child.
1140 def->cooked_default = pstrdup(this_default);
1145 * Close the parent rel, but keep our AccessShareLock on it until xact
1146 * commit. That will prevent someone else from deleting or ALTERing
1147 * the parent before the child is committed.
1149 heap_close(relation, NoLock);
1153 transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
1156 List *indexlist = NIL;
1161 * Run through the constraints that need to generate an index. For
1162 * PRIMARY KEY, mark each column as NOT NULL and create an index. For
1163 * UNIQUE, create an index as for PRIMARY KEY, but do not insist on
1166 foreach(listptr, cxt->ixconstraints)
1168 Constraint *constraint = lfirst(listptr);
1172 Assert(IsA(constraint, Constraint));
1173 Assert((constraint->contype == CONSTR_PRIMARY)
1174 || (constraint->contype == CONSTR_UNIQUE));
1176 index = makeNode(IndexStmt);
1178 index->unique = true;
1179 index->primary = (constraint->contype == CONSTR_PRIMARY);
1182 if (cxt->pkey != NULL)
1184 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1185 errmsg("multiple primary keys for table \"%s\" are not allowed",
1186 cxt->relation->relname)));
1189 * In ALTER TABLE case, a primary index might already exist,
1190 * but DefineIndex will check for it.
1193 index->isconstraint = true;
1195 if (constraint->name != NULL)
1196 index->idxname = pstrdup(constraint->name);
1198 index->idxname = NULL; /* DefineIndex will choose name */
1200 index->relation = cxt->relation;
1201 index->accessMethod = DEFAULT_INDEX_TYPE;
1202 index->tableSpace = constraint->indexspace;
1203 index->indexParams = NIL;
1204 index->whereClause = NULL;
1207 * Make sure referenced keys exist. If we are making a PRIMARY
1208 * KEY index, also make sure they are NOT NULL, if possible.
1209 * (Although we could leave it to DefineIndex to mark the columns
1210 * NOT NULL, it's more efficient to get it right the first time.)
1212 foreach(keys, constraint->keys)
1214 char *key = strVal(lfirst(keys));
1216 ColumnDef *column = NULL;
1219 foreach(columns, cxt->columns)
1221 column = (ColumnDef *) lfirst(columns);
1222 Assert(IsA(column, ColumnDef));
1223 if (strcmp(column->colname, key) == 0)
1231 /* found column in the new table; force it to be NOT NULL */
1232 if (constraint->contype == CONSTR_PRIMARY)
1233 column->is_not_null = TRUE;
1235 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1238 * column will be a system column in the new table, so
1239 * accept it. System columns can't ever be null, so no
1240 * need to worry about PRIMARY/NOT NULL constraint.
1244 else if (cxt->inhRelations)
1246 /* try inherited tables */
1249 foreach(inher, cxt->inhRelations)
1251 RangeVar *inh = (RangeVar *) lfirst(inher);
1255 Assert(IsA(inh, RangeVar));
1256 rel = heap_openrv(inh, AccessShareLock);
1257 if (rel->rd_rel->relkind != RELKIND_RELATION)
1259 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1260 errmsg("inherited relation \"%s\" is not a table",
1262 for (count = 0; count < rel->rd_att->natts; count++)
1264 Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1265 char *inhname = NameStr(inhattr->attname);
1267 if (inhattr->attisdropped)
1269 if (strcmp(key, inhname) == 0)
1274 * We currently have no easy way to force an
1275 * inherited column to be NOT NULL at
1276 * creation, if its parent wasn't so already.
1277 * We leave it to DefineIndex to fix things up
1283 heap_close(rel, NoLock);
1290 * In the ALTER TABLE case, don't complain about index keys
1291 * not created in the command; they may well exist already.
1292 * DefineIndex will complain about them if not, and will also
1293 * take care of marking them NOT NULL.
1295 if (!found && !cxt->isalter)
1297 (errcode(ERRCODE_UNDEFINED_COLUMN),
1298 errmsg("column \"%s\" named in key does not exist",
1301 /* Check for PRIMARY KEY(foo, foo) */
1302 foreach(columns, index->indexParams)
1304 iparam = (IndexElem *) lfirst(columns);
1305 if (iparam->name && strcmp(key, iparam->name) == 0)
1309 (errcode(ERRCODE_DUPLICATE_COLUMN),
1310 errmsg("column \"%s\" appears twice in primary key constraint",
1314 (errcode(ERRCODE_DUPLICATE_COLUMN),
1315 errmsg("column \"%s\" appears twice in unique constraint",
1320 /* OK, add it to the index definition */
1321 iparam = makeNode(IndexElem);
1322 iparam->name = pstrdup(key);
1323 iparam->expr = NULL;
1324 iparam->opclass = NIL;
1325 index->indexParams = lappend(index->indexParams, iparam);
1328 indexlist = lappend(indexlist, index);
1332 * Scan the index list and remove any redundant index specifications.
1333 * This can happen if, for instance, the user writes UNIQUE PRIMARY
1334 * KEY. A strict reading of SQL92 would suggest raising an error
1335 * instead, but that strikes me as too anal-retentive. - tgl
1338 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1339 * pre-existing indexes, too.
1342 if (cxt->pkey != NULL)
1344 /* Make sure we keep the PKEY index in preference to others... */
1345 cxt->alist = list_make1(cxt->pkey);
1348 foreach(l, indexlist)
1355 /* if it's pkey, it's already in cxt->alist */
1356 if (index == cxt->pkey)
1359 foreach(k, cxt->alist)
1361 IndexStmt *priorindex = lfirst(k);
1363 if (equal(index->indexParams, priorindex->indexParams))
1366 * If the prior index is as yet unnamed, and this one
1367 * is named, then transfer the name to the prior
1368 * index. This ensures that if we have named and
1369 * unnamed constraints, we'll use (at least one of)
1370 * the names for the index.
1372 if (priorindex->idxname == NULL)
1373 priorindex->idxname = index->idxname;
1380 cxt->alist = lappend(cxt->alist, index);
1385 transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
1386 bool skipValidation, bool isAddConstraint)
1390 if (cxt->fkconstraints == NIL)
1394 * If CREATE TABLE or adding a column with NULL default, we can safely
1395 * skip validation of the constraint.
1399 foreach(fkclist, cxt->fkconstraints)
1401 FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1403 fkconstraint->skip_validation = true;
1408 * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE
1409 * ADD CONSTRAINT command to execute after the basic command is complete.
1410 * (If called from ADD CONSTRAINT, that routine will add the FK constraints
1411 * to its own subcommand list.)
1413 * Note: the ADD CONSTRAINT command must also execute after any index
1414 * creation commands. Thus, this should run after
1415 * transformIndexConstraints, so that the CREATE INDEX commands are
1416 * already in cxt->alist.
1418 if (!isAddConstraint)
1420 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1422 alterstmt->relation = cxt->relation;
1423 alterstmt->cmds = NIL;
1424 alterstmt->relkind = OBJECT_TABLE;
1426 foreach(fkclist, cxt->fkconstraints)
1428 FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1429 AlterTableCmd *altercmd = makeNode(AlterTableCmd);
1431 altercmd->subtype = AT_ProcessedConstraint;
1432 altercmd->name = NULL;
1433 altercmd->def = (Node *) fkconstraint;
1434 alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
1437 cxt->alist = lappend(cxt->alist, alterstmt);
1442 * transformIndexStmt -
1443 * transforms the qualification of the index statement
1446 transformIndexStmt(ParseState *pstate, IndexStmt *stmt)
1449 RangeTblEntry *rte = NULL;
1452 qry = makeNode(Query);
1453 qry->commandType = CMD_UTILITY;
1455 /* take care of the where clause */
1456 if (stmt->whereClause)
1459 * Put the parent table into the rtable so that the WHERE clause
1460 * can refer to its fields without qualification. Note that this
1461 * only works if the parent table already exists --- so we can't
1462 * easily support predicates on indexes created implicitly by
1463 * CREATE TABLE. Fortunately, that's not necessary.
1465 rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1467 /* no to join list, yes to namespace */
1468 addRTEtoQuery(pstate, rte, false, true);
1470 stmt->whereClause = transformWhereClause(pstate, stmt->whereClause,
1474 /* take care of any index expressions */
1475 foreach(l, stmt->indexParams)
1477 IndexElem *ielem = (IndexElem *) lfirst(l);
1481 /* Set up rtable as for predicate, see notes above */
1484 rte = addRangeTableEntry(pstate, stmt->relation, NULL,
1486 /* no to join list, yes to namespace */
1487 addRTEtoQuery(pstate, rte, false, true);
1489 ielem->expr = transformExpr(pstate, ielem->expr);
1492 * We check only that the result type is legitimate; this is
1493 * for consistency with what transformWhereClause() checks for
1494 * the predicate. DefineIndex() will make more checks.
1496 if (expression_returns_set(ielem->expr))
1498 (errcode(ERRCODE_DATATYPE_MISMATCH),
1499 errmsg("index expression may not return a set")));
1503 qry->hasSubLinks = pstate->p_hasSubLinks;
1504 stmt->rangetable = pstate->p_rtable;
1506 qry->utilityStmt = (Node *) stmt;
1512 * transformRuleStmt -
1513 * transform a Create Rule Statement. The actions is a list of parse
1514 * trees which is transformed into a list of query trees.
1517 transformRuleStmt(ParseState *pstate, RuleStmt *stmt,
1518 List **extras_before, List **extras_after)
1521 RangeTblEntry *oldrte;
1522 RangeTblEntry *newrte;
1524 qry = makeNode(Query);
1525 qry->commandType = CMD_UTILITY;
1526 qry->utilityStmt = (Node *) stmt;
1529 * To avoid deadlock, make sure the first thing we do is grab
1530 * AccessExclusiveLock on the target relation. This will be needed by
1531 * DefineQueryRewrite(), and we don't want to grab a lesser lock
1532 * beforehand. We don't need to hold a refcount on the relcache
1535 heap_close(heap_openrv(stmt->relation, AccessExclusiveLock),
1539 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to
1540 * 2. Set up their RTEs in the main pstate for use in parsing the
1541 * rule qualification.
1543 Assert(pstate->p_rtable == NIL);
1544 oldrte = addRangeTableEntry(pstate, stmt->relation,
1545 makeAlias("*OLD*", NIL),
1547 newrte = addRangeTableEntry(pstate, stmt->relation,
1548 makeAlias("*NEW*", NIL),
1550 /* Must override addRangeTableEntry's default access-check flags */
1551 oldrte->requiredPerms = 0;
1552 newrte->requiredPerms = 0;
1555 * They must be in the namespace too for lookup purposes, but only add
1556 * the one(s) that are relevant for the current kind of rule. In an
1557 * UPDATE rule, quals must refer to OLD.field or NEW.field to be
1558 * unambiguous, but there's no need to be so picky for INSERT &
1559 * DELETE. (Note we marked the RTEs "inFromCl = true" above to allow
1560 * unqualified references to their fields.) We do not add them to the
1563 switch (stmt->event)
1566 addRTEtoQuery(pstate, oldrte, false, true);
1569 addRTEtoQuery(pstate, oldrte, false, true);
1570 addRTEtoQuery(pstate, newrte, false, true);
1573 addRTEtoQuery(pstate, newrte, false, true);
1576 addRTEtoQuery(pstate, oldrte, false, true);
1579 elog(ERROR, "unrecognized event type: %d",
1584 /* take care of the where clause */
1585 stmt->whereClause = transformWhereClause(pstate, stmt->whereClause,
1588 if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
1590 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1591 errmsg("rule WHERE condition may not contain references to other relations")));
1593 /* aggregates not allowed (but subselects are okay) */
1594 if (pstate->p_hasAggs)
1596 (errcode(ERRCODE_GROUPING_ERROR),
1597 errmsg("rule WHERE condition may not contain aggregate functions")));
1599 /* save info about sublinks in where clause */
1600 qry->hasSubLinks = pstate->p_hasSubLinks;
1603 * 'instead nothing' rules with a qualification need a query
1604 * rangetable so the rewrite handler can add the negated rule
1605 * qualification to the original query. We create a query with the new
1606 * command type CMD_NOTHING here that is treated specially by the
1609 if (stmt->actions == NIL)
1611 Query *nothing_qry = makeNode(Query);
1613 nothing_qry->commandType = CMD_NOTHING;
1614 nothing_qry->rtable = pstate->p_rtable;
1615 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
1617 stmt->actions = list_make1(nothing_qry);
1622 List *newactions = NIL;
1625 * transform each statement, like parse_sub_analyze()
1627 foreach(l, stmt->actions)
1629 Node *action = (Node *) lfirst(l);
1630 ParseState *sub_pstate = make_parsestate(pstate->parentParseState);
1637 * Set up OLD/NEW in the rtable for this statement. The
1638 * entries are marked not inFromCl because we don't want them
1639 * to be referred to by unqualified field names nor "*" in the
1640 * rule actions. We must add them to the namespace, however,
1641 * or they won't be accessible at all. We decide later
1642 * whether to put them in the joinlist.
1644 oldrte = addRangeTableEntry(sub_pstate, stmt->relation,
1645 makeAlias("*OLD*", NIL),
1647 newrte = addRangeTableEntry(sub_pstate, stmt->relation,
1648 makeAlias("*NEW*", NIL),
1650 oldrte->requiredPerms = 0;
1651 newrte->requiredPerms = 0;
1652 addRTEtoQuery(sub_pstate, oldrte, false, true);
1653 addRTEtoQuery(sub_pstate, newrte, false, true);
1655 /* Transform the rule action statement */
1656 top_subqry = transformStmt(sub_pstate, action,
1657 extras_before, extras_after);
1660 * We cannot support utility-statement actions (eg NOTIFY)
1661 * with nonempty rule WHERE conditions, because there's no way
1662 * to make the utility action execute conditionally.
1664 if (top_subqry->commandType == CMD_UTILITY &&
1665 stmt->whereClause != NULL)
1667 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1668 errmsg("rules with WHERE conditions may only have SELECT, INSERT, UPDATE, or DELETE actions")));
1671 * If the action is INSERT...SELECT, OLD/NEW have been pushed
1672 * down into the SELECT, and that's what we need to look at.
1673 * (Ugly kluge ... try to fix this when we redesign
1676 sub_qry = getInsertSelectQuery(top_subqry, NULL);
1679 * If the sub_qry is a setop, we cannot attach any
1680 * qualifications to it, because the planner won't notice
1681 * them. This could perhaps be relaxed someday, but for now,
1682 * we may as well reject such a rule immediately.
1684 if (sub_qry->setOperations != NULL && stmt->whereClause != NULL)
1686 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1687 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1690 * Validate action's use of OLD/NEW, qual too
1693 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
1694 rangeTableEntry_used(stmt->whereClause, PRS2_OLD_VARNO, 0);
1696 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
1697 rangeTableEntry_used(stmt->whereClause, PRS2_NEW_VARNO, 0);
1699 switch (stmt->event)
1704 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1705 errmsg("ON SELECT rule may not use OLD")));
1708 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1709 errmsg("ON SELECT rule may not use NEW")));
1717 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1718 errmsg("ON INSERT rule may not use OLD")));
1723 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1724 errmsg("ON DELETE rule may not use NEW")));
1727 elog(ERROR, "unrecognized event type: %d",
1733 * For efficiency's sake, add OLD to the rule action's
1734 * jointree only if it was actually referenced in the
1735 * statement or qual.
1737 * For INSERT, NEW is not really a relation (only a reference to
1738 * the to-be-inserted tuple) and should never be added to the
1741 * For UPDATE, we treat NEW as being another kind of reference to
1742 * OLD, because it represents references to *transformed*
1743 * tuples of the existing relation. It would be wrong to
1744 * enter NEW separately in the jointree, since that would
1745 * cause a double join of the updated relation. It's also
1746 * wrong to fail to make a jointree entry if only NEW and not
1749 if (has_old || (has_new && stmt->event == CMD_UPDATE))
1752 * If sub_qry is a setop, manipulating its jointree will
1753 * do no good at all, because the jointree is dummy. (This
1754 * should be a can't-happen case because of prior tests.)
1756 if (sub_qry->setOperations != NULL)
1758 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1759 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1760 /* hack so we can use addRTEtoQuery() */
1761 sub_pstate->p_rtable = sub_qry->rtable;
1762 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
1763 addRTEtoQuery(sub_pstate, oldrte, true, false);
1764 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
1767 newactions = lappend(newactions, top_subqry);
1769 release_pstate_resources(sub_pstate);
1773 stmt->actions = newactions;
1781 * transformSelectStmt -
1782 * transforms a Select Statement
1784 * Note: this is also used for DECLARE CURSOR statements.
1787 transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
1789 Query *qry = makeNode(Query);
1792 qry->commandType = CMD_SELECT;
1794 /* make FOR UPDATE clause available to addRangeTableEntry */
1795 pstate->p_forUpdate = stmt->forUpdate;
1797 /* process the FROM clause */
1798 transformFromClause(pstate, stmt->fromClause);
1800 /* transform targetlist */
1801 qry->targetList = transformTargetList(pstate, stmt->targetList);
1803 /* handle any SELECT INTO/CREATE TABLE AS spec */
1804 qry->into = stmt->into;
1805 if (stmt->intoColNames)
1806 applyColumnNames(qry->targetList, stmt->intoColNames);
1808 qry->intoHasOids = interpretOidsOption(stmt->intoHasOids);
1810 /* mark column origins */
1811 markTargetListOrigins(pstate, qry->targetList);
1813 /* transform WHERE */
1814 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
1817 * Initial processing of HAVING clause is just like WHERE clause.
1818 * Additional work will be done in optimizer/plan/planner.c.
1820 qry->havingQual = transformWhereClause(pstate, stmt->havingClause,
1824 * Transform sorting/grouping stuff. Do ORDER BY first because both
1825 * transformGroupClause and transformDistinctClause need the results.
1827 qry->sortClause = transformSortClause(pstate,
1830 true /* fix unknowns */ );
1832 qry->groupClause = transformGroupClause(pstate,
1837 qry->distinctClause = transformDistinctClause(pstate,
1838 stmt->distinctClause,
1842 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
1844 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
1847 qry->rtable = pstate->p_rtable;
1848 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
1850 qry->hasSubLinks = pstate->p_hasSubLinks;
1851 qry->hasAggs = pstate->p_hasAggs;
1852 if (pstate->p_hasAggs || qry->groupClause)
1853 parseCheckAggregates(pstate, qry);
1855 if (stmt->forUpdate != NIL)
1856 transformForUpdate(qry, stmt->forUpdate);
1862 * transformSetOperationsStmt -
1863 * transforms a set-operations tree
1865 * A set-operation tree is just a SELECT, but with UNION/INTERSECT/EXCEPT
1866 * structure to it. We must transform each leaf SELECT and build up a top-
1867 * level Query that contains the leaf SELECTs as subqueries in its rangetable.
1868 * The tree of set operations is converted into the setOperations field of
1869 * the top-level Query.
1872 transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
1874 Query *qry = makeNode(Query);
1875 SelectStmt *leftmostSelect;
1877 Query *leftmostQuery;
1878 SetOperationStmt *sostmt;
1886 ListCell *left_tlist,
1892 RangeTblEntry *jrte;
1896 qry->commandType = CMD_SELECT;
1899 * Find leftmost leaf SelectStmt; extract the one-time-only items from
1900 * it and from the top-level node.
1902 leftmostSelect = stmt->larg;
1903 while (leftmostSelect && leftmostSelect->op != SETOP_NONE)
1904 leftmostSelect = leftmostSelect->larg;
1905 Assert(leftmostSelect && IsA(leftmostSelect, SelectStmt) &&
1906 leftmostSelect->larg == NULL);
1907 into = leftmostSelect->into;
1908 intoColNames = leftmostSelect->intoColNames;
1910 /* clear them to prevent complaints in transformSetOperationTree() */
1911 leftmostSelect->into = NULL;
1912 leftmostSelect->intoColNames = NIL;
1915 * These are not one-time, exactly, but we want to process them here
1916 * and not let transformSetOperationTree() see them --- else it'll
1917 * just recurse right back here!
1919 sortClause = stmt->sortClause;
1920 limitOffset = stmt->limitOffset;
1921 limitCount = stmt->limitCount;
1922 forUpdate = stmt->forUpdate;
1924 stmt->sortClause = NIL;
1925 stmt->limitOffset = NULL;
1926 stmt->limitCount = NULL;
1927 stmt->forUpdate = NIL;
1929 /* We don't support forUpdate with set ops at the moment. */
1932 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1933 errmsg("SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT")));
1936 * Recursively transform the components of the tree.
1938 sostmt = (SetOperationStmt *) transformSetOperationTree(pstate, stmt);
1939 Assert(sostmt && IsA(sostmt, SetOperationStmt));
1940 qry->setOperations = (Node *) sostmt;
1943 * Re-find leftmost SELECT (now it's a sub-query in rangetable)
1945 node = sostmt->larg;
1946 while (node && IsA(node, SetOperationStmt))
1947 node = ((SetOperationStmt *) node)->larg;
1948 Assert(node && IsA(node, RangeTblRef));
1949 leftmostRTI = ((RangeTblRef *) node)->rtindex;
1950 leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
1951 Assert(leftmostQuery != NULL);
1954 * Generate dummy targetlist for outer query using column names of
1955 * leftmost select and common datatypes of topmost set operation. Also
1956 * make lists of the dummy vars and their names for use in parsing
1959 * Note: we use leftmostRTI as the varno of the dummy variables. It
1960 * shouldn't matter too much which RT index they have, as long as they
1961 * have one that corresponds to a real RT entry; else funny things may
1962 * happen when the tree is mashed by rule rewriting.
1964 qry->targetList = NIL;
1967 left_tlist = list_head(leftmostQuery->targetList);
1969 foreach(dtlist, sostmt->colTypes)
1971 Oid colType = lfirst_oid(dtlist);
1977 leftResdom = ((TargetEntry *) lfirst(left_tlist))->resdom;
1978 Assert(!leftResdom->resjunk);
1979 colName = pstrdup(leftResdom->resname);
1980 resdom = makeResdom((AttrNumber) pstate->p_next_resno++,
1985 expr = (Expr *) makeVar(leftmostRTI,
1990 qry->targetList = lappend(qry->targetList,
1991 makeTargetEntry(resdom, expr));
1992 targetvars = lappend(targetvars, expr);
1993 targetnames = lappend(targetnames, makeString(colName));
1994 left_tlist = lnext(left_tlist);
1998 * Handle SELECT INTO/CREATE TABLE AS.
2000 * Any column names from CREATE TABLE AS need to be attached to both the
2001 * top level and the leftmost subquery. We do not do this earlier
2002 * because we do *not* want the targetnames list to be affected.
2007 applyColumnNames(qry->targetList, intoColNames);
2008 applyColumnNames(leftmostQuery->targetList, intoColNames);
2012 * As a first step towards supporting sort clauses that are
2013 * expressions using the output columns, generate a namespace entry
2014 * that makes the output columns visible. A Join RTE node is handy
2015 * for this, since we can easily control the Vars generated upon
2018 * Note: we don't yet do anything useful with such cases, but at least
2019 * "ORDER BY upper(foo)" will draw the right error message rather than
2022 jrte = addRangeTableEntryForJoin(NULL,
2028 jrtr = makeNode(RangeTblRef);
2029 jrtr->rtindex = 1; /* only entry in dummy rtable */
2031 sv_rtable = pstate->p_rtable;
2032 pstate->p_rtable = list_make1(jrte);
2034 sv_namespace = pstate->p_namespace;
2035 pstate->p_namespace = list_make1(jrtr);
2038 * For now, we don't support resjunk sort clauses on the output of a
2039 * setOperation tree --- you can only use the SQL92-spec options of
2040 * selecting an output column by name or number. Enforce by checking
2041 * that transformSortClause doesn't add any items to tlist.
2043 tllen = list_length(qry->targetList);
2045 qry->sortClause = transformSortClause(pstate,
2048 false /* no unknowns expected */ );
2050 pstate->p_namespace = sv_namespace;
2051 pstate->p_rtable = sv_rtable;
2053 if (tllen != list_length(qry->targetList))
2055 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2056 errmsg("ORDER BY on a UNION/INTERSECT/EXCEPT result must be on one of the result columns")));
2058 qry->limitOffset = transformLimitClause(pstate, limitOffset,
2060 qry->limitCount = transformLimitClause(pstate, limitCount,
2063 qry->rtable = pstate->p_rtable;
2064 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
2066 qry->hasSubLinks = pstate->p_hasSubLinks;
2067 qry->hasAggs = pstate->p_hasAggs;
2068 if (pstate->p_hasAggs || qry->groupClause)
2069 parseCheckAggregates(pstate, qry);
2071 if (forUpdate != NIL)
2072 transformForUpdate(qry, forUpdate);
2078 * transformSetOperationTree
2079 * Recursively transform leaves and internal nodes of a set-op tree
2082 transformSetOperationTree(ParseState *pstate, SelectStmt *stmt)
2086 Assert(stmt && IsA(stmt, SelectStmt));
2089 * Validity-check both leaf and internal SELECTs for disallowed ops.
2093 (errcode(ERRCODE_SYNTAX_ERROR),
2094 errmsg("INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT")));
2095 /* We don't support forUpdate with set ops at the moment. */
2096 if (stmt->forUpdate)
2098 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2099 errmsg("SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT")));
2102 * If an internal node of a set-op tree has ORDER BY, UPDATE, or LIMIT
2103 * clauses attached, we need to treat it like a leaf node to generate
2104 * an independent sub-Query tree. Otherwise, it can be represented by
2105 * a SetOperationStmt node underneath the parent Query.
2107 if (stmt->op == SETOP_NONE)
2109 Assert(stmt->larg == NULL && stmt->rarg == NULL);
2114 Assert(stmt->larg != NULL && stmt->rarg != NULL);
2115 if (stmt->sortClause || stmt->limitOffset || stmt->limitCount ||
2124 /* Process leaf SELECT */
2127 char selectName[32];
2132 * Transform SelectStmt into a Query.
2134 * Note: previously transformed sub-queries don't affect the parsing
2135 * of this sub-query, because they are not in the toplevel
2136 * pstate's namespace list.
2138 selectList = parse_sub_analyze((Node *) stmt, pstate);
2140 Assert(list_length(selectList) == 1);
2141 selectQuery = (Query *) linitial(selectList);
2142 Assert(IsA(selectQuery, Query));
2145 * Check for bogus references to Vars on the current query level
2146 * (but upper-level references are okay). Normally this can't
2147 * happen because the namespace will be empty, but it could happen
2148 * if we are inside a rule.
2150 if (pstate->p_namespace)
2152 if (contain_vars_of_level((Node *) selectQuery, 1))
2154 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2155 errmsg("UNION/INTERSECT/EXCEPT member statement may not refer to other relations of same query level")));
2159 * Make the leaf query be a subquery in the top-level rangetable.
2161 snprintf(selectName, sizeof(selectName), "*SELECT* %d",
2162 list_length(pstate->p_rtable) + 1);
2163 rte = addRangeTableEntryForSubquery(pstate,
2165 makeAlias(selectName, NIL),
2169 * Return a RangeTblRef to replace the SelectStmt in the set-op
2172 rtr = makeNode(RangeTblRef);
2173 /* assume new rte is at end */
2174 rtr->rtindex = list_length(pstate->p_rtable);
2175 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
2176 return (Node *) rtr;
2180 /* Process an internal node (set operation node) */
2181 SetOperationStmt *op = makeNode(SetOperationStmt);
2186 const char *context;
2188 context = (stmt->op == SETOP_UNION ? "UNION" :
2189 (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
2193 op->all = stmt->all;
2196 * Recursively transform the child nodes.
2198 op->larg = transformSetOperationTree(pstate, stmt->larg);
2199 op->rarg = transformSetOperationTree(pstate, stmt->rarg);
2202 * Verify that the two children have the same number of non-junk
2203 * columns, and determine the types of the merged output columns.
2205 lcoltypes = getSetColTypes(pstate, op->larg);
2206 rcoltypes = getSetColTypes(pstate, op->rarg);
2207 if (list_length(lcoltypes) != list_length(rcoltypes))
2209 (errcode(ERRCODE_SYNTAX_ERROR),
2210 errmsg("each %s query must have the same number of columns",
2214 forboth(l, lcoltypes, r, rcoltypes)
2216 Oid lcoltype = lfirst_oid(l);
2217 Oid rcoltype = lfirst_oid(r);
2220 rescoltype = select_common_type(list_make2_oid(lcoltype, rcoltype),
2222 op->colTypes = lappend_oid(op->colTypes, rescoltype);
2231 * Get output column types of an (already transformed) set-op node
2234 getSetColTypes(ParseState *pstate, Node *node)
2236 if (IsA(node, RangeTblRef))
2238 RangeTblRef *rtr = (RangeTblRef *) node;
2239 RangeTblEntry *rte = rt_fetch(rtr->rtindex, pstate->p_rtable);
2240 Query *selectQuery = rte->subquery;
2244 Assert(selectQuery != NULL);
2245 /* Get types of non-junk columns */
2246 foreach(tl, selectQuery->targetList)
2248 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2249 Resdom *resnode = tle->resdom;
2251 if (resnode->resjunk)
2253 result = lappend_oid(result, resnode->restype);
2257 else if (IsA(node, SetOperationStmt))
2259 SetOperationStmt *op = (SetOperationStmt *) node;
2261 /* Result already computed during transformation of node */
2262 Assert(op->colTypes != NIL);
2263 return op->colTypes;
2267 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node));
2268 return NIL; /* keep compiler quiet */
2272 /* Attach column names from a ColumnDef list to a TargetEntry list */
2274 applyColumnNames(List *dst, List *src)
2276 ListCell *dst_item = list_head(dst);
2277 ListCell *src_item = list_head(src);
2279 if (list_length(src) > list_length(dst))
2281 (errcode(ERRCODE_SYNTAX_ERROR),
2282 errmsg("CREATE TABLE AS specifies too many column names")));
2284 while (src_item != NULL && dst_item != NULL)
2286 TargetEntry *d = (TargetEntry *) lfirst(dst_item);
2287 ColumnDef *s = (ColumnDef *) lfirst(src_item);
2289 Assert(d->resdom && !d->resdom->resjunk);
2291 d->resdom->resname = pstrdup(s->colname);
2293 dst_item = lnext(dst_item);
2294 src_item = lnext(src_item);
2300 * transformUpdateStmt -
2301 * transforms an update statement
2304 transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
2306 Query *qry = makeNode(Query);
2308 ListCell *origTargetList;
2311 qry->commandType = CMD_UPDATE;
2312 pstate->p_is_update = true;
2314 qry->resultRelation = setTargetTable(pstate, stmt->relation,
2315 interpretInhOption(stmt->relation->inhOpt),
2320 * the FROM clause is non-standard SQL syntax. We used to be able to
2321 * do this with REPLACE in POSTQUEL so we keep the feature.
2323 transformFromClause(pstate, stmt->fromClause);
2325 qry->targetList = transformTargetList(pstate, stmt->targetList);
2327 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
2329 qry->rtable = pstate->p_rtable;
2330 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
2332 qry->hasSubLinks = pstate->p_hasSubLinks;
2333 qry->hasAggs = pstate->p_hasAggs;
2334 if (pstate->p_hasAggs)
2335 parseCheckAggregates(pstate, qry);
2338 * Now we are done with SELECT-like processing, and can get on with
2339 * transforming the target list to match the UPDATE target columns.
2342 /* Prepare to assign non-conflicting resnos to resjunk attributes */
2343 if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
2344 pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
2346 /* Prepare non-junk columns for assignment to target table */
2347 origTargetList = list_head(stmt->targetList);
2349 foreach(tl, qry->targetList)
2351 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2352 Resdom *resnode = tle->resdom;
2353 ResTarget *origTarget;
2355 if (resnode->resjunk)
2358 * Resjunk nodes need no additional processing, but be sure
2359 * they have resnos that do not match any target columns;
2360 * else rewriter or planner might get confused. They don't
2361 * need a resname either.
2363 resnode->resno = (AttrNumber) pstate->p_next_resno++;
2364 resnode->resname = NULL;
2367 if (origTargetList == NULL)
2368 elog(ERROR, "UPDATE target count mismatch --- internal error");
2369 origTarget = (ResTarget *) lfirst(origTargetList);
2370 Assert(IsA(origTarget, ResTarget));
2372 updateTargetListEntry(pstate, tle, origTarget->name,
2373 attnameAttNum(pstate->p_target_relation,
2374 origTarget->name, true),
2375 origTarget->indirection);
2377 origTargetList = lnext(origTargetList);
2379 if (origTargetList != NULL)
2380 elog(ERROR, "UPDATE target count mismatch --- internal error");
2386 * tranformAlterTableStmt -
2387 * transform an Alter Table Statement
2390 transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt,
2391 List **extras_before, List **extras_after)
2393 CreateStmtContext cxt;
2397 List *newcmds = NIL;
2398 bool skipValidation = true;
2399 AlterTableCmd *newcmd;
2401 cxt.stmtType = "ALTER TABLE";
2402 cxt.relation = stmt->relation;
2403 cxt.inhRelations = NIL;
2405 cxt.hasoids = false; /* need not be right */
2407 cxt.ckconstraints = NIL;
2408 cxt.fkconstraints = NIL;
2409 cxt.ixconstraints = NIL;
2415 * The only subtypes that currently require parse transformation
2416 * handling are ADD COLUMN and ADD CONSTRAINT. These largely
2417 * re-use code from CREATE TABLE.
2419 foreach(lcmd, stmt->cmds)
2421 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2423 switch (cmd->subtype)
2427 ColumnDef *def = (ColumnDef *) cmd->def;
2429 Assert(IsA(cmd->def, ColumnDef));
2430 transformColumnDefinition(pstate, &cxt,
2431 (ColumnDef *) cmd->def);
2434 * If the column has a non-null default, we can't skip
2435 * validation of foreign keys.
2437 if (((ColumnDef *) cmd->def)->raw_default != NULL)
2438 skipValidation = false;
2440 newcmds = lappend(newcmds, cmd);
2443 * Convert an ADD COLUMN ... NOT NULL constraint to a separate
2446 if (def->is_not_null)
2448 /* Remove NOT NULL from AddColumn */
2449 def->is_not_null = false;
2451 /* Add as a separate AlterTableCmd */
2452 newcmd = makeNode(AlterTableCmd);
2453 newcmd->subtype = AT_SetNotNull;
2454 newcmd->name = pstrdup(def->colname);
2455 newcmds = lappend(newcmds, newcmd);
2459 * All constraints are processed in other ways.
2460 * Remove the original list
2462 def->constraints = NIL;
2466 case AT_AddConstraint:
2467 /* The original AddConstraint cmd node doesn't go to newcmds */
2469 if (IsA(cmd->def, Constraint))
2470 transformTableConstraint(pstate, &cxt,
2471 (Constraint *) cmd->def);
2472 else if (IsA(cmd->def, FkConstraint))
2474 cxt.fkconstraints = lappend(cxt.fkconstraints, cmd->def);
2475 skipValidation = false;
2478 elog(ERROR, "unrecognized node type: %d",
2479 (int) nodeTag(cmd->def));
2482 case AT_ProcessedConstraint:
2485 * Already-transformed ADD CONSTRAINT, so just make it look
2486 * like the standard case.
2488 cmd->subtype = AT_AddConstraint;
2489 newcmds = lappend(newcmds, cmd);
2493 newcmds = lappend(newcmds, cmd);
2498 /* Postprocess index and FK constraints */
2499 transformIndexConstraints(pstate, &cxt);
2501 transformFKConstraints(pstate, &cxt, skipValidation, true);
2504 * Push any index-creation commands into the ALTER, so that
2505 * they can be scheduled nicely by tablecmds.c.
2507 foreach(l, cxt.alist)
2509 Node *idxstmt = (Node *) lfirst(l);
2511 Assert(IsA(idxstmt, IndexStmt));
2512 newcmd = makeNode(AlterTableCmd);
2513 newcmd->subtype = AT_AddIndex;
2514 newcmd->def = idxstmt;
2515 newcmds = lappend(newcmds, newcmd);
2519 /* Append any CHECK or FK constraints to the commands list */
2520 foreach(l, cxt.ckconstraints)
2522 newcmd = makeNode(AlterTableCmd);
2523 newcmd->subtype = AT_AddConstraint;
2524 newcmd->def = (Node *) lfirst(l);
2525 newcmds = lappend(newcmds, newcmd);
2527 foreach(l, cxt.fkconstraints)
2529 newcmd = makeNode(AlterTableCmd);
2530 newcmd->subtype = AT_AddConstraint;
2531 newcmd->def = (Node *) lfirst(l);
2532 newcmds = lappend(newcmds, newcmd);
2535 /* Update statement's commands list */
2536 stmt->cmds = newcmds;
2538 qry = makeNode(Query);
2539 qry->commandType = CMD_UTILITY;
2540 qry->utilityStmt = (Node *) stmt;
2542 *extras_before = list_concat(*extras_before, cxt.blist);
2543 *extras_after = list_concat(cxt.alist, *extras_after);
2549 transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
2551 Query *result = makeNode(Query);
2552 List *extras_before = NIL,
2553 *extras_after = NIL;
2555 result->commandType = CMD_UTILITY;
2556 result->utilityStmt = (Node *) stmt;
2559 * Don't allow both SCROLL and NO SCROLL to be specified
2561 if ((stmt->options & CURSOR_OPT_SCROLL) &&
2562 (stmt->options & CURSOR_OPT_NO_SCROLL))
2564 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
2565 errmsg("cannot specify both SCROLL and NO SCROLL")));
2567 stmt->query = (Node *) transformStmt(pstate, stmt->query,
2568 &extras_before, &extras_after);
2570 /* Shouldn't get any extras, since grammar only allows SelectStmt */
2571 if (extras_before || extras_after)
2572 elog(ERROR, "unexpected extra stuff in cursor statement");
2579 transformPrepareStmt(ParseState *pstate, PrepareStmt *stmt)
2581 Query *result = makeNode(Query);
2582 List *argtype_oids = NIL; /* argtype OIDs in a list */
2583 Oid *argtoids = NULL; /* and as an array */
2587 result->commandType = CMD_UTILITY;
2588 result->utilityStmt = (Node *) stmt;
2590 /* Transform list of TypeNames to list (and array) of type OIDs */
2591 nargs = list_length(stmt->argtypes);
2598 argtoids = (Oid *) palloc(nargs * sizeof(Oid));
2600 foreach(l, stmt->argtypes)
2602 TypeName *tn = lfirst(l);
2603 Oid toid = typenameTypeId(tn);
2605 argtype_oids = lappend_oid(argtype_oids, toid);
2606 argtoids[i++] = toid;
2610 stmt->argtype_oids = argtype_oids;
2613 * Analyze the statement using these parameter types (any parameters
2614 * passed in from above us will not be visible to it).
2616 queries = parse_analyze((Node *) stmt->query, argtoids, nargs);
2619 * Shouldn't get any extra statements, since grammar only allows
2622 if (list_length(queries) != 1)
2623 elog(ERROR, "unexpected extra stuff in prepared statement");
2625 stmt->query = linitial(queries);
2631 transformExecuteStmt(ParseState *pstate, ExecuteStmt *stmt)
2633 Query *result = makeNode(Query);
2636 result->commandType = CMD_UTILITY;
2637 result->utilityStmt = (Node *) stmt;
2639 paramtypes = FetchPreparedStatementParams(stmt->name);
2641 if (stmt->params || paramtypes)
2643 int nparams = list_length(stmt->params);
2644 int nexpected = list_length(paramtypes);
2648 if (nparams != nexpected)
2650 (errcode(ERRCODE_SYNTAX_ERROR),
2651 errmsg("wrong number of parameters for prepared statement \"%s\"",
2653 errdetail("Expected %d parameters but got %d.",
2654 nexpected, nparams)));
2656 forboth(l, stmt->params, l2, paramtypes)
2658 Node *expr = lfirst(l);
2659 Oid expected_type_id = lfirst_oid(l2);
2662 expr = transformExpr(pstate, expr);
2664 /* Cannot contain subselects or aggregates */
2665 if (pstate->p_hasSubLinks)
2667 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2668 errmsg("cannot use subquery in EXECUTE parameter")));
2669 if (pstate->p_hasAggs)
2671 (errcode(ERRCODE_GROUPING_ERROR),
2672 errmsg("cannot use aggregate function in EXECUTE parameter")));
2674 given_type_id = exprType(expr);
2676 expr = coerce_to_target_type(pstate, expr, given_type_id,
2677 expected_type_id, -1,
2678 COERCION_ASSIGNMENT,
2679 COERCE_IMPLICIT_CAST);
2683 (errcode(ERRCODE_DATATYPE_MISMATCH),
2684 errmsg("parameter $%d of type %s cannot be coerced to the expected type %s",
2686 format_type_be(given_type_id),
2687 format_type_be(expected_type_id)),
2688 errhint("You will need to rewrite or cast the expression.")));
2698 /* exported so planner can check again after rewriting, query pullup, etc */
2700 CheckSelectForUpdate(Query *qry)
2702 if (qry->setOperations)
2704 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2705 errmsg("SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT")));
2706 if (qry->distinctClause != NIL)
2708 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2709 errmsg("SELECT FOR UPDATE is not allowed with DISTINCT clause")));
2710 if (qry->groupClause != NIL)
2712 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2713 errmsg("SELECT FOR UPDATE is not allowed with GROUP BY clause")));
2716 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2717 errmsg("SELECT FOR UPDATE is not allowed with aggregate functions")));
2721 * Convert FOR UPDATE name list into rowMarks list of integer relids
2723 * NB: if you need to change this, see also markQueryForUpdate()
2724 * in rewriteHandler.c.
2727 transformForUpdate(Query *qry, List *forUpdate)
2729 List *rowMarks = qry->rowMarks;
2734 CheckSelectForUpdate(qry);
2736 if (linitial(forUpdate) == NULL)
2738 /* all regular tables used in query */
2740 foreach(rt, qry->rtable)
2742 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2745 switch (rte->rtekind)
2748 if (!list_member_int(rowMarks, i)) /* avoid duplicates */
2749 rowMarks = lappend_int(rowMarks, i);
2750 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
2754 * FOR UPDATE of subquery is propagated to subquery's
2757 transformForUpdate(rte->subquery, list_make1(NULL));
2760 /* ignore JOIN, SPECIAL, FUNCTION RTEs */
2767 /* just the named tables */
2768 foreach(l, forUpdate)
2770 char *relname = strVal(lfirst(l));
2773 foreach(rt, qry->rtable)
2775 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2778 if (strcmp(rte->eref->aliasname, relname) == 0)
2780 switch (rte->rtekind)
2783 if (!list_member_int(rowMarks, i)) /* avoid duplicates */
2784 rowMarks = lappend_int(rowMarks, i);
2785 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
2789 * FOR UPDATE of subquery is propagated to
2792 transformForUpdate(rte->subquery, list_make1(NULL));
2796 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2797 errmsg("SELECT FOR UPDATE cannot be applied to a join")));
2801 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2802 errmsg("SELECT FOR UPDATE cannot be applied to NEW or OLD")));
2806 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2807 errmsg("SELECT FOR UPDATE cannot be applied to a function")));
2810 elog(ERROR, "unrecognized RTE type: %d",
2811 (int) rte->rtekind);
2814 break; /* out of foreach loop */
2819 (errcode(ERRCODE_UNDEFINED_TABLE),
2820 errmsg("relation \"%s\" in FOR UPDATE clause not found in FROM clause",
2825 qry->rowMarks = rowMarks;
2830 * Preprocess a list of column constraint clauses
2831 * to attach constraint attributes to their primary constraint nodes
2832 * and detect inconsistent/misplaced constraint attributes.
2834 * NOTE: currently, attributes are only supported for FOREIGN KEY primary
2835 * constraints, but someday they ought to be supported for other constraints.
2838 transformConstraintAttrs(List *constraintList)
2840 Node *lastprimarynode = NULL;
2841 bool saw_deferrability = false;
2842 bool saw_initially = false;
2845 foreach(clist, constraintList)
2847 Node *node = lfirst(clist);
2849 if (!IsA(node, Constraint))
2851 lastprimarynode = node;
2852 /* reset flags for new primary node */
2853 saw_deferrability = false;
2854 saw_initially = false;
2858 Constraint *con = (Constraint *) node;
2860 switch (con->contype)
2862 case CONSTR_ATTR_DEFERRABLE:
2863 if (lastprimarynode == NULL ||
2864 !IsA(lastprimarynode, FkConstraint))
2866 (errcode(ERRCODE_SYNTAX_ERROR),
2867 errmsg("misplaced DEFERRABLE clause")));
2868 if (saw_deferrability)
2870 (errcode(ERRCODE_SYNTAX_ERROR),
2871 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
2872 saw_deferrability = true;
2873 ((FkConstraint *) lastprimarynode)->deferrable = true;
2875 case CONSTR_ATTR_NOT_DEFERRABLE:
2876 if (lastprimarynode == NULL ||
2877 !IsA(lastprimarynode, FkConstraint))
2879 (errcode(ERRCODE_SYNTAX_ERROR),
2880 errmsg("misplaced NOT DEFERRABLE clause")));
2881 if (saw_deferrability)
2883 (errcode(ERRCODE_SYNTAX_ERROR),
2884 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
2885 saw_deferrability = true;
2886 ((FkConstraint *) lastprimarynode)->deferrable = false;
2887 if (saw_initially &&
2888 ((FkConstraint *) lastprimarynode)->initdeferred)
2890 (errcode(ERRCODE_SYNTAX_ERROR),
2891 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
2893 case CONSTR_ATTR_DEFERRED:
2894 if (lastprimarynode == NULL ||
2895 !IsA(lastprimarynode, FkConstraint))
2897 (errcode(ERRCODE_SYNTAX_ERROR),
2898 errmsg("misplaced INITIALLY DEFERRED clause")));
2901 (errcode(ERRCODE_SYNTAX_ERROR),
2902 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
2903 saw_initially = true;
2904 ((FkConstraint *) lastprimarynode)->initdeferred = true;
2907 * If only INITIALLY DEFERRED appears, assume
2910 if (!saw_deferrability)
2911 ((FkConstraint *) lastprimarynode)->deferrable = true;
2912 else if (!((FkConstraint *) lastprimarynode)->deferrable)
2914 (errcode(ERRCODE_SYNTAX_ERROR),
2915 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
2917 case CONSTR_ATTR_IMMEDIATE:
2918 if (lastprimarynode == NULL ||
2919 !IsA(lastprimarynode, FkConstraint))
2921 (errcode(ERRCODE_SYNTAX_ERROR),
2922 errmsg("misplaced INITIALLY IMMEDIATE clause")));
2925 (errcode(ERRCODE_SYNTAX_ERROR),
2926 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
2927 saw_initially = true;
2928 ((FkConstraint *) lastprimarynode)->initdeferred = false;
2931 /* Otherwise it's not an attribute */
2932 lastprimarynode = node;
2933 /* reset flags for new primary node */
2934 saw_deferrability = false;
2935 saw_initially = false;
2942 /* Build a FromExpr node */
2944 makeFromExpr(List *fromlist, Node *quals)
2946 FromExpr *f = makeNode(FromExpr);
2948 f->fromlist = fromlist;
2954 * Special handling of type definition for a column
2957 transformColumnType(ParseState *pstate, ColumnDef *column)
2960 * All we really need to do here is verify that the type is valid.
2962 Type ctype = typenameType(column->typename);
2964 ReleaseSysCache(ctype);
2968 setSchemaName(char *context_schema, char **stmt_schema_name)
2970 if (*stmt_schema_name == NULL)
2971 *stmt_schema_name = context_schema;
2972 else if (strcmp(context_schema, *stmt_schema_name) != 0)
2974 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
2975 errmsg("CREATE specifies a schema (%s) "
2976 "different from the one being created (%s)",
2977 *stmt_schema_name, context_schema)));
2981 * analyzeCreateSchemaStmt -
2982 * analyzes the "create schema" statement
2984 * Split the schema element list into individual commands and place
2985 * them in the result list in an order such that there are no forward
2986 * references (e.g. GRANT to a table created later in the list). Note
2987 * that the logic we use for determining forward references is
2988 * presently quite incomplete.
2990 * SQL92 also allows constraints to make forward references, so thumb through
2991 * the table columns and move forward references to a posterior alter-table
2994 * The result is a list of parse nodes that still need to be analyzed ---
2995 * but we can't analyze the later commands until we've executed the earlier
2996 * ones, because of possible inter-object references.
2998 * Note: Called from commands/schemacmds.c
3001 analyzeCreateSchemaStmt(CreateSchemaStmt *stmt)
3003 CreateSchemaStmtContext cxt;
3007 cxt.stmtType = "CREATE SCHEMA";
3008 cxt.schemaname = stmt->schemaname;
3009 cxt.authid = stmt->authid;
3010 cxt.sequences = NIL;
3016 cxt.fwconstraints = NIL;
3022 * Run through each schema element in the schema element list.
3023 * Separate statements by type, and do preliminary analysis.
3025 foreach(elements, stmt->schemaElts)
3027 Node *element = lfirst(elements);
3029 switch (nodeTag(element))
3031 case T_CreateSeqStmt:
3033 CreateSeqStmt *elp = (CreateSeqStmt *) element;
3035 setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
3036 cxt.sequences = lappend(cxt.sequences, element);
3042 CreateStmt *elp = (CreateStmt *) element;
3044 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3047 * XXX todo: deal with constraints
3049 cxt.tables = lappend(cxt.tables, element);
3055 ViewStmt *elp = (ViewStmt *) element;
3057 setSchemaName(cxt.schemaname, &elp->view->schemaname);
3060 * XXX todo: deal with references between views
3062 cxt.views = lappend(cxt.views, element);
3068 IndexStmt *elp = (IndexStmt *) element;
3070 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3071 cxt.indexes = lappend(cxt.indexes, element);
3075 case T_CreateTrigStmt:
3077 CreateTrigStmt *elp = (CreateTrigStmt *) element;
3079 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3080 cxt.triggers = lappend(cxt.triggers, element);
3085 cxt.grants = lappend(cxt.grants, element);
3089 elog(ERROR, "unrecognized node type: %d",
3090 (int) nodeTag(element));
3095 result = list_concat(result, cxt.sequences);
3096 result = list_concat(result, cxt.tables);
3097 result = list_concat(result, cxt.views);
3098 result = list_concat(result, cxt.indexes);
3099 result = list_concat(result, cxt.triggers);
3100 result = list_concat(result, cxt.grants);
3106 * Traverse a fully-analyzed tree to verify that parameter symbols
3107 * match their types. We need this because some Params might still
3108 * be UNKNOWN, if there wasn't anything to force their coercion,
3109 * and yet other instances seen later might have gotten coerced.
3112 check_parameter_resolution_walker(Node *node,
3113 check_parameter_resolution_context *context)
3117 if (IsA(node, Param))
3119 Param *param = (Param *) node;
3121 if (param->paramkind == PARAM_NUM)
3123 int paramno = param->paramid;
3125 if (paramno <= 0 || /* shouldn't happen, but... */
3126 paramno > context->numParams)
3128 (errcode(ERRCODE_UNDEFINED_PARAMETER),
3129 errmsg("there is no parameter $%d", paramno)));
3131 if (param->paramtype != context->paramTypes[paramno - 1])
3133 (errcode(ERRCODE_AMBIGUOUS_PARAMETER),
3134 errmsg("could not determine data type of parameter $%d",
3139 if (IsA(node, Query))
3141 /* Recurse into RTE subquery or not-yet-planned sublink subquery */
3142 return query_tree_walker((Query *) node,
3143 check_parameter_resolution_walker,
3144 (void *) context, 0);
3146 return expression_tree_walker(node, check_parameter_resolution_walker,