1 /*-------------------------------------------------------------------------
4 * transform the parse tree into a query tree
6 * Portions Copyright (c) 1996-2005, 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.316 2005/03/10 23:21:23 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;
400 * Check that we did not produce too many resnos; at the very
401 * least we cannot allow more than 2^16, since that would exceed
402 * the range of a AttrNumber. It seems safest to use
403 * MaxTupleAttributeNumber.
405 if (pstate->p_next_resno - 1 > MaxTupleAttributeNumber)
407 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
408 errmsg("target lists can have at most %d entries",
409 MaxTupleAttributeNumber)));
415 transformViewStmt(ParseState *pstate, ViewStmt *stmt,
416 List **extras_before, List **extras_after)
418 Query *result = makeNode(Query);
420 result->commandType = CMD_UTILITY;
421 result->utilityStmt = (Node *) stmt;
423 stmt->query = transformStmt(pstate, (Node *) stmt->query,
424 extras_before, extras_after);
427 * If a list of column names was given, run through and insert these
428 * into the actual query tree. - thomas 2000-03-08
430 * Outer loop is over targetlist to make it easier to skip junk
431 * targetlist entries.
433 if (stmt->aliases != NIL)
435 ListCell *alist_item = list_head(stmt->aliases);
436 ListCell *targetList;
438 foreach(targetList, stmt->query->targetList)
440 TargetEntry *te = (TargetEntry *) lfirst(targetList);
443 Assert(IsA(te, TargetEntry));
445 Assert(IsA(rd, Resdom));
446 /* junk columns don't get aliases */
449 rd->resname = pstrdup(strVal(lfirst(alist_item)));
450 alist_item = lnext(alist_item);
451 if (alist_item == NULL)
452 break; /* done assigning aliases */
455 if (alist_item != NULL)
457 (errcode(ERRCODE_SYNTAX_ERROR),
458 errmsg("CREATE VIEW specifies more column "
459 "names than columns")));
466 * transformDeleteStmt -
467 * transforms a Delete Statement
470 transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
472 Query *qry = makeNode(Query);
475 qry->commandType = CMD_DELETE;
477 /* set up range table with just the result rel */
478 qry->resultRelation = setTargetTable(pstate, stmt->relation,
479 interpretInhOption(stmt->relation->inhOpt),
483 qry->distinctClause = NIL;
485 /* fix where clause */
486 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
488 /* done building the range table and jointree */
489 qry->rtable = pstate->p_rtable;
490 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
492 qry->hasSubLinks = pstate->p_hasSubLinks;
493 qry->hasAggs = pstate->p_hasAggs;
494 if (pstate->p_hasAggs)
495 parseCheckAggregates(pstate, qry);
501 * transformInsertStmt -
502 * transform an Insert Statement
505 transformInsertStmt(ParseState *pstate, InsertStmt *stmt,
506 List **extras_before, List **extras_after)
508 Query *qry = makeNode(Query);
509 Query *selectQuery = NULL;
510 bool copy_up_hack = false;
519 qry->commandType = CMD_INSERT;
520 pstate->p_is_insert = true;
523 * If a non-nil rangetable/namespace was passed in, and we are doing
524 * INSERT/SELECT, arrange to pass the rangetable/namespace down to the
525 * SELECT. This can only happen if we are inside a CREATE RULE, and
526 * in that case we want the rule's OLD and NEW rtable entries to
527 * appear as part of the SELECT's rtable, not as outer references for
528 * it. (Kluge!) The SELECT's joinlist is not affected however. We
529 * must do this before adding the target table to the INSERT's rtable.
531 if (stmt->selectStmt)
533 sub_rtable = pstate->p_rtable;
534 pstate->p_rtable = NIL;
535 sub_namespace = pstate->p_namespace;
536 pstate->p_namespace = NIL;
540 sub_rtable = NIL; /* not used, but keep compiler quiet */
545 * Must get write lock on INSERT target table before scanning SELECT,
546 * else we will grab the wrong kind of initial lock if the target
547 * table is also mentioned in the SELECT part. Note that the target
548 * table is not added to the joinlist or namespace.
550 qry->resultRelation = setTargetTable(pstate, stmt->relation,
551 false, false, ACL_INSERT);
554 * Is it INSERT ... SELECT or INSERT ... VALUES?
556 if (stmt->selectStmt)
559 * We make the sub-pstate a child of the outer pstate so that it
560 * can see any Param definitions supplied from above. Since the
561 * outer pstate's rtable and namespace are presently empty, there
562 * are no side-effects of exposing names the sub-SELECT shouldn't
565 ParseState *sub_pstate = make_parsestate(pstate);
570 * Process the source SELECT.
572 * It is important that this be handled just like a standalone
573 * SELECT; otherwise the behavior of SELECT within INSERT might be
574 * different from a stand-alone SELECT. (Indeed, Postgres up
575 * through 6.5 had bugs of just that nature...)
577 sub_pstate->p_rtable = sub_rtable;
578 sub_pstate->p_namespace = sub_namespace;
581 * Note: we are not expecting that extras_before and extras_after
582 * are going to be used by the transformation of the SELECT
585 selectQuery = transformStmt(sub_pstate, stmt->selectStmt,
586 extras_before, extras_after);
588 release_pstate_resources(sub_pstate);
591 Assert(IsA(selectQuery, Query));
592 Assert(selectQuery->commandType == CMD_SELECT);
593 if (selectQuery->into)
595 (errcode(ERRCODE_SYNTAX_ERROR),
596 errmsg("INSERT ... SELECT may not specify INTO")));
599 * Make the source be a subquery in the INSERT's rangetable, and
600 * add it to the INSERT's joinlist.
602 rte = addRangeTableEntryForSubquery(pstate,
604 makeAlias("*SELECT*", NIL),
606 rtr = makeNode(RangeTblRef);
607 /* assume new rte is at end */
608 rtr->rtindex = list_length(pstate->p_rtable);
609 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
610 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
613 * Generate a targetlist for the INSERT that selects all the
614 * non-resjunk columns from the subquery. (We need this to be
615 * separate from the subquery's tlist because we may add columns,
616 * insert datatype coercions, etc.)
618 * HACK: unknown-type constants and params in the INSERT's targetlist
619 * are copied up as-is rather than being referenced as subquery
620 * outputs. This is to ensure that when we try to coerce them to
621 * the target column's datatype, the right things happen (see
622 * special cases in coerce_type). Otherwise, this fails:
623 * INSERT INTO foo SELECT 'bar', ... FROM baz
626 qry->targetList = NIL;
627 foreach(tl, selectQuery->targetList)
629 TargetEntry *tle = (TargetEntry *) lfirst(tl);
630 Resdom *resnode = tle->resdom;
633 if (resnode->resjunk)
636 (IsA(tle->expr, Const) || IsA(tle->expr, Param)) &&
637 exprType((Node *) tle->expr) == UNKNOWNOID)
643 expr = (Expr *) makeVar(rtr->rtindex,
648 resnode = copyObject(resnode);
649 resnode->resno = (AttrNumber) pstate->p_next_resno++;
650 qry->targetList = lappend(qry->targetList,
651 makeTargetEntry(resnode, expr));
657 * For INSERT ... VALUES, transform the given list of values to
658 * form a targetlist for the INSERT.
660 qry->targetList = transformTargetList(pstate, stmt->targetList);
664 * Now we are done with SELECT-like processing, and can get on with
665 * transforming the target list to match the INSERT target columns.
668 /* Prepare to assign non-conflicting resnos to resjunk attributes */
669 if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
670 pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
672 /* Validate stmt->cols list, or build default list if no list given */
673 icolumns = checkInsertTargets(pstate, stmt->cols, &attrnos);
676 * Prepare columns for assignment to target table.
678 icols = list_head(icolumns);
679 attnos = list_head(attrnos);
680 foreach(tl, qry->targetList)
682 TargetEntry *tle = (TargetEntry *) lfirst(tl);
685 if (icols == NULL || attnos == NULL)
687 (errcode(ERRCODE_SYNTAX_ERROR),
688 errmsg("INSERT has more expressions than target columns")));
690 col = (ResTarget *) lfirst(icols);
691 Assert(IsA(col, ResTarget));
693 Assert(!tle->resdom->resjunk);
694 updateTargetListEntry(pstate, tle, col->name, lfirst_int(attnos),
697 icols = lnext(icols);
698 attnos = lnext(attnos);
702 * Ensure that the targetlist has the same number of entries that were
703 * present in the columns list. Don't do the check unless an explicit
704 * columns list was given, though.
706 if (stmt->cols != NIL && (icols != NULL || attnos != NULL))
708 (errcode(ERRCODE_SYNTAX_ERROR),
709 errmsg("INSERT has more target columns than expressions")));
712 * If we copied up any unknown Params (see HACK above) then their
713 * resolved types need to be propagated into the Resdom nodes of
714 * the sub-INSERT's tlist. One hack begets another :-(
718 foreach(tl, selectQuery->targetList)
720 TargetEntry *tle = (TargetEntry *) lfirst(tl);
721 Resdom *resnode = tle->resdom;
723 if (resnode->resjunk)
725 if (resnode->restype == UNKNOWNOID)
727 resnode->restype = exprType((Node *) tle->expr);
728 resnode->restypmod = exprTypmod((Node *) tle->expr);
733 /* done building the range table and jointree */
734 qry->rtable = pstate->p_rtable;
735 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
737 qry->hasSubLinks = pstate->p_hasSubLinks;
738 qry->hasAggs = pstate->p_hasAggs;
739 if (pstate->p_hasAggs)
740 parseCheckAggregates(pstate, qry);
746 * transformCreateStmt -
747 * transforms the "create table" statement
748 * SQL92 allows constraints to be scattered all over, so thumb through
749 * the columns and collect all constraints into one place.
750 * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
751 * then expand those into multiple IndexStmt blocks.
752 * - thomas 1997-12-02
755 transformCreateStmt(ParseState *pstate, CreateStmt *stmt,
756 List **extras_before, List **extras_after)
758 CreateStmtContext cxt;
762 cxt.stmtType = "CREATE TABLE";
763 cxt.relation = stmt->relation;
764 cxt.inhRelations = stmt->inhRelations;
767 cxt.ckconstraints = NIL;
768 cxt.fkconstraints = NIL;
769 cxt.ixconstraints = NIL;
773 cxt.hasoids = interpretOidsOption(stmt->hasoids);
776 * Run through each primary element in the table creation clause.
777 * Separate column defs from constraints, and do preliminary analysis.
779 foreach(elements, stmt->tableElts)
781 Node *element = lfirst(elements);
783 switch (nodeTag(element))
786 transformColumnDefinition(pstate, &cxt,
787 (ColumnDef *) element);
791 transformTableConstraint(pstate, &cxt,
792 (Constraint *) element);
796 /* No pre-transformation needed */
797 cxt.fkconstraints = lappend(cxt.fkconstraints, element);
801 transformInhRelation(pstate, &cxt,
802 (InhRelation *) element);
806 elog(ERROR, "unrecognized node type: %d",
807 (int) nodeTag(element));
812 Assert(stmt->constraints == NIL);
815 * Postprocess constraints that give rise to index definitions.
817 transformIndexConstraints(pstate, &cxt);
820 * Postprocess foreign-key constraints.
822 transformFKConstraints(pstate, &cxt, true, false);
828 q->commandType = CMD_UTILITY;
829 q->utilityStmt = (Node *) stmt;
830 stmt->tableElts = cxt.columns;
831 stmt->constraints = cxt.ckconstraints;
832 *extras_before = list_concat(*extras_before, cxt.blist);
833 *extras_after = list_concat(cxt.alist, *extras_after);
839 transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
844 Constraint *constraint;
847 cxt->columns = lappend(cxt->columns, column);
849 /* Check for SERIAL pseudo-types */
851 if (list_length(column->typename->names) == 1)
853 char *typname = strVal(linitial(column->typename->names));
855 if (strcmp(typname, "serial") == 0 ||
856 strcmp(typname, "serial4") == 0)
859 column->typename->names = NIL;
860 column->typename->typeid = INT4OID;
862 else if (strcmp(typname, "bigserial") == 0 ||
863 strcmp(typname, "serial8") == 0)
866 column->typename->names = NIL;
867 column->typename->typeid = INT8OID;
871 /* Do necessary work on the column type declaration */
872 transformColumnType(pstate, column);
874 /* Special actions for SERIAL pseudo-types */
882 FuncCall *funccallnode;
883 CreateSeqStmt *seqstmt;
886 * Determine namespace and name to use for the sequence.
888 * Although we use ChooseRelationName, it's not guaranteed that the
889 * selected sequence name won't conflict; given sufficiently long
890 * field names, two different serial columns in the same table
891 * could be assigned the same sequence name, and we'd not notice
892 * since we aren't creating the sequence quite yet. In practice
893 * this seems quite unlikely to be a problem, especially since few
894 * people would need two serial columns in one table.
896 snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
897 snamespace = get_namespace_name(snamespaceid);
898 sname = ChooseRelationName(cxt->relation->relname,
904 (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
905 cxt->stmtType, sname,
906 cxt->relation->relname, column->colname)));
909 * Build a CREATE SEQUENCE command to create the sequence object,
910 * and add it to the list of things to be done before this
911 * CREATE/ALTER TABLE.
913 seqstmt = makeNode(CreateSeqStmt);
914 seqstmt->sequence = makeRangeVar(snamespace, sname);
915 seqstmt->options = NIL;
917 cxt->blist = lappend(cxt->blist, seqstmt);
920 * Mark the ColumnDef so that during execution, an appropriate
921 * dependency will be added from the sequence to the column.
923 column->support = makeRangeVar(snamespace, sname);
926 * Create appropriate constraints for SERIAL. We do this in full,
927 * rather than shortcutting, so that we will detect any
928 * conflicting constraints the user wrote (like a different
931 * Create an expression tree representing the function call
932 * nextval('"sequencename"')
934 qstring = quote_qualified_identifier(snamespace, sname);
935 snamenode = makeNode(A_Const);
936 snamenode->val.type = T_String;
937 snamenode->val.val.str = qstring;
938 funccallnode = makeNode(FuncCall);
939 funccallnode->funcname = SystemFuncName("nextval");
940 funccallnode->args = list_make1(snamenode);
941 funccallnode->agg_star = false;
942 funccallnode->agg_distinct = false;
944 constraint = makeNode(Constraint);
945 constraint->contype = CONSTR_DEFAULT;
946 constraint->raw_expr = (Node *) funccallnode;
947 constraint->cooked_expr = NULL;
948 constraint->keys = NIL;
949 column->constraints = lappend(column->constraints, constraint);
951 constraint = makeNode(Constraint);
952 constraint->contype = CONSTR_NOTNULL;
953 column->constraints = lappend(column->constraints, constraint);
956 /* Process column constraints, if any... */
957 transformConstraintAttrs(column->constraints);
959 saw_nullable = false;
961 foreach(clist, column->constraints)
963 constraint = lfirst(clist);
966 * If this column constraint is a FOREIGN KEY constraint, then we
967 * fill in the current attribute's name and throw it into the list
968 * of FK constraints to be processed later.
970 if (IsA(constraint, FkConstraint))
972 FkConstraint *fkconstraint = (FkConstraint *) constraint;
974 fkconstraint->fk_attrs = list_make1(makeString(column->colname));
975 cxt->fkconstraints = lappend(cxt->fkconstraints, fkconstraint);
979 Assert(IsA(constraint, Constraint));
981 switch (constraint->contype)
984 if (saw_nullable && column->is_not_null)
986 (errcode(ERRCODE_SYNTAX_ERROR),
987 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
988 column->colname, cxt->relation->relname)));
989 column->is_not_null = FALSE;
994 if (saw_nullable && !column->is_not_null)
996 (errcode(ERRCODE_SYNTAX_ERROR),
997 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
998 column->colname, cxt->relation->relname)));
999 column->is_not_null = TRUE;
1000 saw_nullable = true;
1003 case CONSTR_DEFAULT:
1004 if (column->raw_default != NULL)
1006 (errcode(ERRCODE_SYNTAX_ERROR),
1007 errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
1008 column->colname, cxt->relation->relname)));
1009 column->raw_default = constraint->raw_expr;
1010 Assert(constraint->cooked_expr == NULL);
1013 case CONSTR_PRIMARY:
1015 if (constraint->keys == NIL)
1016 constraint->keys = list_make1(makeString(column->colname));
1017 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
1021 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
1024 case CONSTR_ATTR_DEFERRABLE:
1025 case CONSTR_ATTR_NOT_DEFERRABLE:
1026 case CONSTR_ATTR_DEFERRED:
1027 case CONSTR_ATTR_IMMEDIATE:
1028 /* transformConstraintAttrs took care of these */
1032 elog(ERROR, "unrecognized constraint type: %d",
1033 constraint->contype);
1040 transformTableConstraint(ParseState *pstate, CreateStmtContext *cxt,
1041 Constraint *constraint)
1043 switch (constraint->contype)
1045 case CONSTR_PRIMARY:
1047 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
1051 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
1055 case CONSTR_NOTNULL:
1056 case CONSTR_DEFAULT:
1057 case CONSTR_ATTR_DEFERRABLE:
1058 case CONSTR_ATTR_NOT_DEFERRABLE:
1059 case CONSTR_ATTR_DEFERRED:
1060 case CONSTR_ATTR_IMMEDIATE:
1061 elog(ERROR, "invalid context for constraint type %d",
1062 constraint->contype);
1066 elog(ERROR, "unrecognized constraint type: %d",
1067 constraint->contype);
1073 * transformInhRelation
1075 * Change the LIKE <subtable> portion of a CREATE TABLE statement into the
1076 * column definitions which recreate the user defined column portions of <subtable>.
1079 transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
1080 InhRelation *inhRelation)
1082 AttrNumber parent_attno;
1085 TupleDesc tupleDesc;
1086 TupleConstr *constr;
1087 AclResult aclresult;
1089 relation = heap_openrv(inhRelation->relation, AccessShareLock);
1091 if (relation->rd_rel->relkind != RELKIND_RELATION)
1093 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1094 errmsg("inherited relation \"%s\" is not a table",
1095 inhRelation->relation->relname)));
1098 * Check for SELECT privilages
1100 aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
1102 if (aclresult != ACLCHECK_OK)
1103 aclcheck_error(aclresult, ACL_KIND_CLASS,
1104 RelationGetRelationName(relation));
1106 tupleDesc = RelationGetDescr(relation);
1107 constr = tupleDesc->constr;
1110 * Insert the inherited attributes into the cxt for the new table
1113 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1116 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
1117 char *attributeName = NameStr(attribute->attname);
1122 * Ignore dropped columns in the parent.
1124 if (attribute->attisdropped)
1128 * Create a new inherited column.
1130 * For constraints, ONLY the NOT NULL constraint is inherited by the
1131 * new column definition per SQL99.
1133 def = makeNode(ColumnDef);
1134 def->colname = pstrdup(attributeName);
1135 typename = makeNode(TypeName);
1136 typename->typeid = attribute->atttypid;
1137 typename->typmod = attribute->atttypmod;
1138 def->typename = typename;
1140 def->is_local = false;
1141 def->is_not_null = attribute->attnotnull;
1142 def->raw_default = NULL;
1143 def->cooked_default = NULL;
1144 def->constraints = NIL;
1145 def->support = NULL;
1148 * Add to column list
1150 cxt->columns = lappend(cxt->columns, def);
1153 * Copy default if any, and the default has been requested
1155 if (attribute->atthasdef && inhRelation->including_defaults)
1157 char *this_default = NULL;
1158 AttrDefault *attrdef;
1161 /* Find default in constraint structure */
1162 Assert(constr != NULL);
1163 attrdef = constr->defval;
1164 for (i = 0; i < constr->num_defval; i++)
1166 if (attrdef[i].adnum == parent_attno)
1168 this_default = attrdef[i].adbin;
1172 Assert(this_default != NULL);
1175 * If default expr could contain any vars, we'd need to fix
1176 * 'em, but it can't; so default is ready to apply to child.
1179 def->cooked_default = pstrdup(this_default);
1184 * Close the parent rel, but keep our AccessShareLock on it until xact
1185 * commit. That will prevent someone else from deleting or ALTERing
1186 * the parent before the child is committed.
1188 heap_close(relation, NoLock);
1192 transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
1195 List *indexlist = NIL;
1200 * Run through the constraints that need to generate an index. For
1201 * PRIMARY KEY, mark each column as NOT NULL and create an index. For
1202 * UNIQUE, create an index as for PRIMARY KEY, but do not insist on
1205 foreach(listptr, cxt->ixconstraints)
1207 Constraint *constraint = lfirst(listptr);
1211 Assert(IsA(constraint, Constraint));
1212 Assert((constraint->contype == CONSTR_PRIMARY)
1213 || (constraint->contype == CONSTR_UNIQUE));
1215 index = makeNode(IndexStmt);
1217 index->unique = true;
1218 index->primary = (constraint->contype == CONSTR_PRIMARY);
1221 if (cxt->pkey != NULL)
1223 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1224 errmsg("multiple primary keys for table \"%s\" are not allowed",
1225 cxt->relation->relname)));
1229 * In ALTER TABLE case, a primary index might already exist,
1230 * but DefineIndex will check for it.
1233 index->isconstraint = true;
1235 if (constraint->name != NULL)
1236 index->idxname = pstrdup(constraint->name);
1238 index->idxname = NULL; /* DefineIndex will choose name */
1240 index->relation = cxt->relation;
1241 index->accessMethod = DEFAULT_INDEX_TYPE;
1242 index->tableSpace = constraint->indexspace;
1243 index->indexParams = NIL;
1244 index->whereClause = NULL;
1247 * Make sure referenced keys exist. If we are making a PRIMARY
1248 * KEY index, also make sure they are NOT NULL, if possible.
1249 * (Although we could leave it to DefineIndex to mark the columns
1250 * NOT NULL, it's more efficient to get it right the first time.)
1252 foreach(keys, constraint->keys)
1254 char *key = strVal(lfirst(keys));
1256 ColumnDef *column = NULL;
1259 foreach(columns, cxt->columns)
1261 column = (ColumnDef *) lfirst(columns);
1262 Assert(IsA(column, ColumnDef));
1263 if (strcmp(column->colname, key) == 0)
1271 /* found column in the new table; force it to be NOT NULL */
1272 if (constraint->contype == CONSTR_PRIMARY)
1273 column->is_not_null = TRUE;
1275 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1278 * column will be a system column in the new table, so
1279 * accept it. System columns can't ever be null, so no
1280 * need to worry about PRIMARY/NOT NULL constraint.
1284 else if (cxt->inhRelations)
1286 /* try inherited tables */
1289 foreach(inher, cxt->inhRelations)
1291 RangeVar *inh = (RangeVar *) lfirst(inher);
1295 Assert(IsA(inh, RangeVar));
1296 rel = heap_openrv(inh, AccessShareLock);
1297 if (rel->rd_rel->relkind != RELKIND_RELATION)
1299 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1300 errmsg("inherited relation \"%s\" is not a table",
1302 for (count = 0; count < rel->rd_att->natts; count++)
1304 Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1305 char *inhname = NameStr(inhattr->attname);
1307 if (inhattr->attisdropped)
1309 if (strcmp(key, inhname) == 0)
1314 * We currently have no easy way to force an
1315 * inherited column to be NOT NULL at
1316 * creation, if its parent wasn't so already.
1317 * We leave it to DefineIndex to fix things up
1323 heap_close(rel, NoLock);
1330 * In the ALTER TABLE case, don't complain about index keys
1331 * not created in the command; they may well exist already.
1332 * DefineIndex will complain about them if not, and will also
1333 * take care of marking them NOT NULL.
1335 if (!found && !cxt->isalter)
1337 (errcode(ERRCODE_UNDEFINED_COLUMN),
1338 errmsg("column \"%s\" named in key does not exist",
1341 /* Check for PRIMARY KEY(foo, foo) */
1342 foreach(columns, index->indexParams)
1344 iparam = (IndexElem *) lfirst(columns);
1345 if (iparam->name && strcmp(key, iparam->name) == 0)
1349 (errcode(ERRCODE_DUPLICATE_COLUMN),
1350 errmsg("column \"%s\" appears twice in primary key constraint",
1354 (errcode(ERRCODE_DUPLICATE_COLUMN),
1355 errmsg("column \"%s\" appears twice in unique constraint",
1360 /* OK, add it to the index definition */
1361 iparam = makeNode(IndexElem);
1362 iparam->name = pstrdup(key);
1363 iparam->expr = NULL;
1364 iparam->opclass = NIL;
1365 index->indexParams = lappend(index->indexParams, iparam);
1368 indexlist = lappend(indexlist, index);
1372 * Scan the index list and remove any redundant index specifications.
1373 * This can happen if, for instance, the user writes UNIQUE PRIMARY
1374 * KEY. A strict reading of SQL92 would suggest raising an error
1375 * instead, but that strikes me as too anal-retentive. - tgl
1378 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1379 * pre-existing indexes, too.
1382 if (cxt->pkey != NULL)
1384 /* Make sure we keep the PKEY index in preference to others... */
1385 cxt->alist = list_make1(cxt->pkey);
1388 foreach(l, indexlist)
1395 /* if it's pkey, it's already in cxt->alist */
1396 if (index == cxt->pkey)
1399 foreach(k, cxt->alist)
1401 IndexStmt *priorindex = lfirst(k);
1403 if (equal(index->indexParams, priorindex->indexParams))
1406 * If the prior index is as yet unnamed, and this one is
1407 * named, then transfer the name to the prior index. This
1408 * ensures that if we have named and unnamed constraints,
1409 * we'll use (at least one of) the names for the index.
1411 if (priorindex->idxname == NULL)
1412 priorindex->idxname = index->idxname;
1419 cxt->alist = lappend(cxt->alist, index);
1424 transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
1425 bool skipValidation, bool isAddConstraint)
1429 if (cxt->fkconstraints == NIL)
1433 * If CREATE TABLE or adding a column with NULL default, we can safely
1434 * skip validation of the constraint.
1438 foreach(fkclist, cxt->fkconstraints)
1440 FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1442 fkconstraint->skip_validation = true;
1447 * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE
1448 * ADD CONSTRAINT command to execute after the basic command is
1449 * complete. (If called from ADD CONSTRAINT, that routine will add the
1450 * FK constraints to its own subcommand list.)
1452 * Note: the ADD CONSTRAINT command must also execute after any index
1453 * creation commands. Thus, this should run after
1454 * transformIndexConstraints, so that the CREATE INDEX commands are
1455 * already in cxt->alist.
1457 if (!isAddConstraint)
1459 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1461 alterstmt->relation = cxt->relation;
1462 alterstmt->cmds = NIL;
1463 alterstmt->relkind = OBJECT_TABLE;
1465 foreach(fkclist, cxt->fkconstraints)
1467 FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1468 AlterTableCmd *altercmd = makeNode(AlterTableCmd);
1470 altercmd->subtype = AT_ProcessedConstraint;
1471 altercmd->name = NULL;
1472 altercmd->def = (Node *) fkconstraint;
1473 alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
1476 cxt->alist = lappend(cxt->alist, alterstmt);
1481 * transformIndexStmt -
1482 * transforms the qualification of the index statement
1485 transformIndexStmt(ParseState *pstate, IndexStmt *stmt)
1488 RangeTblEntry *rte = NULL;
1491 qry = makeNode(Query);
1492 qry->commandType = CMD_UTILITY;
1494 /* take care of the where clause */
1495 if (stmt->whereClause)
1498 * Put the parent table into the rtable so that the WHERE clause
1499 * can refer to its fields without qualification. Note that this
1500 * only works if the parent table already exists --- so we can't
1501 * easily support predicates on indexes created implicitly by
1502 * CREATE TABLE. Fortunately, that's not necessary.
1504 rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1506 /* no to join list, yes to namespace */
1507 addRTEtoQuery(pstate, rte, false, true);
1509 stmt->whereClause = transformWhereClause(pstate, stmt->whereClause,
1513 /* take care of any index expressions */
1514 foreach(l, stmt->indexParams)
1516 IndexElem *ielem = (IndexElem *) lfirst(l);
1520 /* Set up rtable as for predicate, see notes above */
1523 rte = addRangeTableEntry(pstate, stmt->relation, NULL,
1525 /* no to join list, yes to namespace */
1526 addRTEtoQuery(pstate, rte, false, true);
1528 ielem->expr = transformExpr(pstate, ielem->expr);
1531 * We check only that the result type is legitimate; this is
1532 * for consistency with what transformWhereClause() checks for
1533 * the predicate. DefineIndex() will make more checks.
1535 if (expression_returns_set(ielem->expr))
1537 (errcode(ERRCODE_DATATYPE_MISMATCH),
1538 errmsg("index expression may not return a set")));
1542 qry->hasSubLinks = pstate->p_hasSubLinks;
1543 stmt->rangetable = pstate->p_rtable;
1545 qry->utilityStmt = (Node *) stmt;
1551 * transformRuleStmt -
1552 * transform a Create Rule Statement. The actions is a list of parse
1553 * trees which is transformed into a list of query trees.
1556 transformRuleStmt(ParseState *pstate, RuleStmt *stmt,
1557 List **extras_before, List **extras_after)
1560 RangeTblEntry *oldrte;
1561 RangeTblEntry *newrte;
1563 qry = makeNode(Query);
1564 qry->commandType = CMD_UTILITY;
1565 qry->utilityStmt = (Node *) stmt;
1568 * To avoid deadlock, make sure the first thing we do is grab
1569 * AccessExclusiveLock on the target relation. This will be needed by
1570 * DefineQueryRewrite(), and we don't want to grab a lesser lock
1571 * beforehand. We don't need to hold a refcount on the relcache
1574 heap_close(heap_openrv(stmt->relation, AccessExclusiveLock),
1578 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to
1579 * 2. Set up their RTEs in the main pstate for use in parsing the
1580 * rule qualification.
1582 Assert(pstate->p_rtable == NIL);
1583 oldrte = addRangeTableEntry(pstate, stmt->relation,
1584 makeAlias("*OLD*", NIL),
1586 newrte = addRangeTableEntry(pstate, stmt->relation,
1587 makeAlias("*NEW*", NIL),
1589 /* Must override addRangeTableEntry's default access-check flags */
1590 oldrte->requiredPerms = 0;
1591 newrte->requiredPerms = 0;
1594 * They must be in the namespace too for lookup purposes, but only add
1595 * the one(s) that are relevant for the current kind of rule. In an
1596 * UPDATE rule, quals must refer to OLD.field or NEW.field to be
1597 * unambiguous, but there's no need to be so picky for INSERT &
1598 * DELETE. (Note we marked the RTEs "inFromCl = true" above to allow
1599 * unqualified references to their fields.) We do not add them to the
1602 switch (stmt->event)
1605 addRTEtoQuery(pstate, oldrte, false, true);
1608 addRTEtoQuery(pstate, oldrte, false, true);
1609 addRTEtoQuery(pstate, newrte, false, true);
1612 addRTEtoQuery(pstate, newrte, false, true);
1615 addRTEtoQuery(pstate, oldrte, false, true);
1618 elog(ERROR, "unrecognized event type: %d",
1623 /* take care of the where clause */
1624 stmt->whereClause = transformWhereClause(pstate, stmt->whereClause,
1627 if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
1629 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1630 errmsg("rule WHERE condition may not contain references to other relations")));
1632 /* aggregates not allowed (but subselects are okay) */
1633 if (pstate->p_hasAggs)
1635 (errcode(ERRCODE_GROUPING_ERROR),
1636 errmsg("rule WHERE condition may not contain aggregate functions")));
1638 /* save info about sublinks in where clause */
1639 qry->hasSubLinks = pstate->p_hasSubLinks;
1642 * 'instead nothing' rules with a qualification need a query
1643 * rangetable so the rewrite handler can add the negated rule
1644 * qualification to the original query. We create a query with the new
1645 * command type CMD_NOTHING here that is treated specially by the
1648 if (stmt->actions == NIL)
1650 Query *nothing_qry = makeNode(Query);
1652 nothing_qry->commandType = CMD_NOTHING;
1653 nothing_qry->rtable = pstate->p_rtable;
1654 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
1656 stmt->actions = list_make1(nothing_qry);
1661 List *newactions = NIL;
1664 * transform each statement, like parse_sub_analyze()
1666 foreach(l, stmt->actions)
1668 Node *action = (Node *) lfirst(l);
1669 ParseState *sub_pstate = make_parsestate(pstate->parentParseState);
1676 * Set up OLD/NEW in the rtable for this statement. The
1677 * entries are marked not inFromCl because we don't want them
1678 * to be referred to by unqualified field names nor "*" in the
1679 * rule actions. We must add them to the namespace, however,
1680 * or they won't be accessible at all. We decide later
1681 * whether to put them in the joinlist.
1683 oldrte = addRangeTableEntry(sub_pstate, stmt->relation,
1684 makeAlias("*OLD*", NIL),
1686 newrte = addRangeTableEntry(sub_pstate, stmt->relation,
1687 makeAlias("*NEW*", NIL),
1689 oldrte->requiredPerms = 0;
1690 newrte->requiredPerms = 0;
1691 addRTEtoQuery(sub_pstate, oldrte, false, true);
1692 addRTEtoQuery(sub_pstate, newrte, false, true);
1694 /* Transform the rule action statement */
1695 top_subqry = transformStmt(sub_pstate, action,
1696 extras_before, extras_after);
1699 * We cannot support utility-statement actions (eg NOTIFY)
1700 * with nonempty rule WHERE conditions, because there's no way
1701 * to make the utility action execute conditionally.
1703 if (top_subqry->commandType == CMD_UTILITY &&
1704 stmt->whereClause != NULL)
1706 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1707 errmsg("rules with WHERE conditions may only have SELECT, INSERT, UPDATE, or DELETE actions")));
1710 * If the action is INSERT...SELECT, OLD/NEW have been pushed
1711 * down into the SELECT, and that's what we need to look at.
1712 * (Ugly kluge ... try to fix this when we redesign
1715 sub_qry = getInsertSelectQuery(top_subqry, NULL);
1718 * If the sub_qry is a setop, we cannot attach any
1719 * qualifications to it, because the planner won't notice
1720 * them. This could perhaps be relaxed someday, but for now,
1721 * we may as well reject such a rule immediately.
1723 if (sub_qry->setOperations != NULL && stmt->whereClause != NULL)
1725 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1726 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1729 * Validate action's use of OLD/NEW, qual too
1732 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
1733 rangeTableEntry_used(stmt->whereClause, PRS2_OLD_VARNO, 0);
1735 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
1736 rangeTableEntry_used(stmt->whereClause, PRS2_NEW_VARNO, 0);
1738 switch (stmt->event)
1743 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1744 errmsg("ON SELECT rule may not use OLD")));
1747 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1748 errmsg("ON SELECT rule may not use NEW")));
1756 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1757 errmsg("ON INSERT rule may not use OLD")));
1762 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1763 errmsg("ON DELETE rule may not use NEW")));
1766 elog(ERROR, "unrecognized event type: %d",
1772 * For efficiency's sake, add OLD to the rule action's
1773 * jointree only if it was actually referenced in the
1774 * statement or qual.
1776 * For INSERT, NEW is not really a relation (only a reference to
1777 * the to-be-inserted tuple) and should never be added to the
1780 * For UPDATE, we treat NEW as being another kind of reference to
1781 * OLD, because it represents references to *transformed*
1782 * tuples of the existing relation. It would be wrong to
1783 * enter NEW separately in the jointree, since that would
1784 * cause a double join of the updated relation. It's also
1785 * wrong to fail to make a jointree entry if only NEW and not
1788 if (has_old || (has_new && stmt->event == CMD_UPDATE))
1791 * If sub_qry is a setop, manipulating its jointree will
1792 * do no good at all, because the jointree is dummy. (This
1793 * should be a can't-happen case because of prior tests.)
1795 if (sub_qry->setOperations != NULL)
1797 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1798 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1799 /* hack so we can use addRTEtoQuery() */
1800 sub_pstate->p_rtable = sub_qry->rtable;
1801 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
1802 addRTEtoQuery(sub_pstate, oldrte, true, false);
1803 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
1806 newactions = lappend(newactions, top_subqry);
1808 release_pstate_resources(sub_pstate);
1812 stmt->actions = newactions;
1820 * transformSelectStmt -
1821 * transforms a Select Statement
1823 * Note: this is also used for DECLARE CURSOR statements.
1826 transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
1828 Query *qry = makeNode(Query);
1831 qry->commandType = CMD_SELECT;
1833 /* make FOR UPDATE clause available to addRangeTableEntry */
1834 pstate->p_forUpdate = stmt->forUpdate;
1836 /* process the FROM clause */
1837 transformFromClause(pstate, stmt->fromClause);
1839 /* transform targetlist */
1840 qry->targetList = transformTargetList(pstate, stmt->targetList);
1842 /* handle any SELECT INTO/CREATE TABLE AS spec */
1843 qry->into = stmt->into;
1844 if (stmt->intoColNames)
1845 applyColumnNames(qry->targetList, stmt->intoColNames);
1847 qry->intoHasOids = interpretOidsOption(stmt->intoHasOids);
1849 /* mark column origins */
1850 markTargetListOrigins(pstate, qry->targetList);
1852 /* transform WHERE */
1853 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
1856 * Initial processing of HAVING clause is just like WHERE clause.
1858 qry->havingQual = transformWhereClause(pstate, stmt->havingClause,
1862 * Transform sorting/grouping stuff. Do ORDER BY first because both
1863 * transformGroupClause and transformDistinctClause need the results.
1865 qry->sortClause = transformSortClause(pstate,
1868 true /* fix unknowns */ );
1870 qry->groupClause = transformGroupClause(pstate,
1875 qry->distinctClause = transformDistinctClause(pstate,
1876 stmt->distinctClause,
1880 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
1882 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
1885 qry->rtable = pstate->p_rtable;
1886 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
1888 qry->hasSubLinks = pstate->p_hasSubLinks;
1889 qry->hasAggs = pstate->p_hasAggs;
1890 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
1891 parseCheckAggregates(pstate, qry);
1893 if (stmt->forUpdate != NIL)
1894 transformForUpdate(qry, stmt->forUpdate);
1900 * transformSetOperationsStmt -
1901 * transforms a set-operations tree
1903 * A set-operation tree is just a SELECT, but with UNION/INTERSECT/EXCEPT
1904 * structure to it. We must transform each leaf SELECT and build up a top-
1905 * level Query that contains the leaf SELECTs as subqueries in its rangetable.
1906 * The tree of set operations is converted into the setOperations field of
1907 * the top-level Query.
1910 transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
1912 Query *qry = makeNode(Query);
1913 SelectStmt *leftmostSelect;
1915 Query *leftmostQuery;
1916 SetOperationStmt *sostmt;
1924 ListCell *left_tlist,
1930 RangeTblEntry *jrte;
1934 qry->commandType = CMD_SELECT;
1937 * Find leftmost leaf SelectStmt; extract the one-time-only items from
1938 * it and from the top-level node.
1940 leftmostSelect = stmt->larg;
1941 while (leftmostSelect && leftmostSelect->op != SETOP_NONE)
1942 leftmostSelect = leftmostSelect->larg;
1943 Assert(leftmostSelect && IsA(leftmostSelect, SelectStmt) &&
1944 leftmostSelect->larg == NULL);
1945 into = leftmostSelect->into;
1946 intoColNames = leftmostSelect->intoColNames;
1948 /* clear them to prevent complaints in transformSetOperationTree() */
1949 leftmostSelect->into = NULL;
1950 leftmostSelect->intoColNames = NIL;
1953 * These are not one-time, exactly, but we want to process them here
1954 * and not let transformSetOperationTree() see them --- else it'll
1955 * just recurse right back here!
1957 sortClause = stmt->sortClause;
1958 limitOffset = stmt->limitOffset;
1959 limitCount = stmt->limitCount;
1960 forUpdate = stmt->forUpdate;
1962 stmt->sortClause = NIL;
1963 stmt->limitOffset = NULL;
1964 stmt->limitCount = NULL;
1965 stmt->forUpdate = NIL;
1967 /* We don't support forUpdate with set ops at the moment. */
1970 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1971 errmsg("SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT")));
1974 * Recursively transform the components of the tree.
1976 sostmt = (SetOperationStmt *) transformSetOperationTree(pstate, stmt);
1977 Assert(sostmt && IsA(sostmt, SetOperationStmt));
1978 qry->setOperations = (Node *) sostmt;
1981 * Re-find leftmost SELECT (now it's a sub-query in rangetable)
1983 node = sostmt->larg;
1984 while (node && IsA(node, SetOperationStmt))
1985 node = ((SetOperationStmt *) node)->larg;
1986 Assert(node && IsA(node, RangeTblRef));
1987 leftmostRTI = ((RangeTblRef *) node)->rtindex;
1988 leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
1989 Assert(leftmostQuery != NULL);
1992 * Generate dummy targetlist for outer query using column names of
1993 * leftmost select and common datatypes of topmost set operation. Also
1994 * make lists of the dummy vars and their names for use in parsing
1997 * Note: we use leftmostRTI as the varno of the dummy variables. It
1998 * shouldn't matter too much which RT index they have, as long as they
1999 * have one that corresponds to a real RT entry; else funny things may
2000 * happen when the tree is mashed by rule rewriting.
2002 qry->targetList = NIL;
2005 left_tlist = list_head(leftmostQuery->targetList);
2007 foreach(dtlist, sostmt->colTypes)
2009 Oid colType = lfirst_oid(dtlist);
2015 leftResdom = ((TargetEntry *) lfirst(left_tlist))->resdom;
2016 Assert(!leftResdom->resjunk);
2017 colName = pstrdup(leftResdom->resname);
2018 resdom = makeResdom((AttrNumber) pstate->p_next_resno++,
2023 expr = (Expr *) makeVar(leftmostRTI,
2028 qry->targetList = lappend(qry->targetList,
2029 makeTargetEntry(resdom, expr));
2030 targetvars = lappend(targetvars, expr);
2031 targetnames = lappend(targetnames, makeString(colName));
2032 left_tlist = lnext(left_tlist);
2036 * Handle SELECT INTO/CREATE TABLE AS.
2038 * Any column names from CREATE TABLE AS need to be attached to both the
2039 * top level and the leftmost subquery. We do not do this earlier
2040 * because we do *not* want the targetnames list to be affected.
2045 applyColumnNames(qry->targetList, intoColNames);
2046 applyColumnNames(leftmostQuery->targetList, intoColNames);
2050 * As a first step towards supporting sort clauses that are
2051 * expressions using the output columns, generate a namespace entry
2052 * that makes the output columns visible. A Join RTE node is handy
2053 * for this, since we can easily control the Vars generated upon
2056 * Note: we don't yet do anything useful with such cases, but at least
2057 * "ORDER BY upper(foo)" will draw the right error message rather than
2060 jrte = addRangeTableEntryForJoin(NULL,
2066 jrtr = makeNode(RangeTblRef);
2067 jrtr->rtindex = 1; /* only entry in dummy rtable */
2069 sv_rtable = pstate->p_rtable;
2070 pstate->p_rtable = list_make1(jrte);
2072 sv_namespace = pstate->p_namespace;
2073 pstate->p_namespace = list_make1(jrtr);
2076 * For now, we don't support resjunk sort clauses on the output of a
2077 * setOperation tree --- you can only use the SQL92-spec options of
2078 * selecting an output column by name or number. Enforce by checking
2079 * that transformSortClause doesn't add any items to tlist.
2081 tllen = list_length(qry->targetList);
2083 qry->sortClause = transformSortClause(pstate,
2086 false /* no unknowns expected */ );
2088 pstate->p_namespace = sv_namespace;
2089 pstate->p_rtable = sv_rtable;
2091 if (tllen != list_length(qry->targetList))
2093 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2094 errmsg("ORDER BY on a UNION/INTERSECT/EXCEPT result must be on one of the result columns")));
2096 qry->limitOffset = transformLimitClause(pstate, limitOffset,
2098 qry->limitCount = transformLimitClause(pstate, limitCount,
2101 qry->rtable = pstate->p_rtable;
2102 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
2104 qry->hasSubLinks = pstate->p_hasSubLinks;
2105 qry->hasAggs = pstate->p_hasAggs;
2106 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
2107 parseCheckAggregates(pstate, qry);
2109 if (forUpdate != NIL)
2110 transformForUpdate(qry, forUpdate);
2116 * transformSetOperationTree
2117 * Recursively transform leaves and internal nodes of a set-op tree
2120 transformSetOperationTree(ParseState *pstate, SelectStmt *stmt)
2124 Assert(stmt && IsA(stmt, SelectStmt));
2127 * Validity-check both leaf and internal SELECTs for disallowed ops.
2131 (errcode(ERRCODE_SYNTAX_ERROR),
2132 errmsg("INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT")));
2133 /* We don't support forUpdate with set ops at the moment. */
2134 if (stmt->forUpdate)
2136 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2137 errmsg("SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT")));
2140 * If an internal node of a set-op tree has ORDER BY, UPDATE, or LIMIT
2141 * clauses attached, we need to treat it like a leaf node to generate
2142 * an independent sub-Query tree. Otherwise, it can be represented by
2143 * a SetOperationStmt node underneath the parent Query.
2145 if (stmt->op == SETOP_NONE)
2147 Assert(stmt->larg == NULL && stmt->rarg == NULL);
2152 Assert(stmt->larg != NULL && stmt->rarg != NULL);
2153 if (stmt->sortClause || stmt->limitOffset || stmt->limitCount ||
2162 /* Process leaf SELECT */
2165 char selectName[32];
2170 * Transform SelectStmt into a Query.
2172 * Note: previously transformed sub-queries don't affect the parsing
2173 * of this sub-query, because they are not in the toplevel
2174 * pstate's namespace list.
2176 selectList = parse_sub_analyze((Node *) stmt, pstate);
2178 Assert(list_length(selectList) == 1);
2179 selectQuery = (Query *) linitial(selectList);
2180 Assert(IsA(selectQuery, Query));
2183 * Check for bogus references to Vars on the current query level
2184 * (but upper-level references are okay). Normally this can't
2185 * happen because the namespace will be empty, but it could happen
2186 * if we are inside a rule.
2188 if (pstate->p_namespace)
2190 if (contain_vars_of_level((Node *) selectQuery, 1))
2192 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2193 errmsg("UNION/INTERSECT/EXCEPT member statement may not refer to other relations of same query level")));
2197 * Make the leaf query be a subquery in the top-level rangetable.
2199 snprintf(selectName, sizeof(selectName), "*SELECT* %d",
2200 list_length(pstate->p_rtable) + 1);
2201 rte = addRangeTableEntryForSubquery(pstate,
2203 makeAlias(selectName, NIL),
2207 * Return a RangeTblRef to replace the SelectStmt in the set-op
2210 rtr = makeNode(RangeTblRef);
2211 /* assume new rte is at end */
2212 rtr->rtindex = list_length(pstate->p_rtable);
2213 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
2214 return (Node *) rtr;
2218 /* Process an internal node (set operation node) */
2219 SetOperationStmt *op = makeNode(SetOperationStmt);
2224 const char *context;
2226 context = (stmt->op == SETOP_UNION ? "UNION" :
2227 (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
2231 op->all = stmt->all;
2234 * Recursively transform the child nodes.
2236 op->larg = transformSetOperationTree(pstate, stmt->larg);
2237 op->rarg = transformSetOperationTree(pstate, stmt->rarg);
2240 * Verify that the two children have the same number of non-junk
2241 * columns, and determine the types of the merged output columns.
2243 lcoltypes = getSetColTypes(pstate, op->larg);
2244 rcoltypes = getSetColTypes(pstate, op->rarg);
2245 if (list_length(lcoltypes) != list_length(rcoltypes))
2247 (errcode(ERRCODE_SYNTAX_ERROR),
2248 errmsg("each %s query must have the same number of columns",
2252 forboth(l, lcoltypes, r, rcoltypes)
2254 Oid lcoltype = lfirst_oid(l);
2255 Oid rcoltype = lfirst_oid(r);
2258 rescoltype = select_common_type(list_make2_oid(lcoltype, rcoltype),
2260 op->colTypes = lappend_oid(op->colTypes, rescoltype);
2269 * Get output column types of an (already transformed) set-op node
2272 getSetColTypes(ParseState *pstate, Node *node)
2274 if (IsA(node, RangeTblRef))
2276 RangeTblRef *rtr = (RangeTblRef *) node;
2277 RangeTblEntry *rte = rt_fetch(rtr->rtindex, pstate->p_rtable);
2278 Query *selectQuery = rte->subquery;
2282 Assert(selectQuery != NULL);
2283 /* Get types of non-junk columns */
2284 foreach(tl, selectQuery->targetList)
2286 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2287 Resdom *resnode = tle->resdom;
2289 if (resnode->resjunk)
2291 result = lappend_oid(result, resnode->restype);
2295 else if (IsA(node, SetOperationStmt))
2297 SetOperationStmt *op = (SetOperationStmt *) node;
2299 /* Result already computed during transformation of node */
2300 Assert(op->colTypes != NIL);
2301 return op->colTypes;
2305 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node));
2306 return NIL; /* keep compiler quiet */
2310 /* Attach column names from a ColumnDef list to a TargetEntry list */
2312 applyColumnNames(List *dst, List *src)
2317 if (list_length(src) > list_length(dst))
2319 (errcode(ERRCODE_SYNTAX_ERROR),
2320 errmsg("CREATE TABLE AS specifies too many column names")));
2322 forboth(dst_item, dst, src_item, src)
2324 TargetEntry *d = (TargetEntry *) lfirst(dst_item);
2325 ColumnDef *s = (ColumnDef *) lfirst(src_item);
2327 Assert(d->resdom && !d->resdom->resjunk);
2328 d->resdom->resname = pstrdup(s->colname);
2334 * transformUpdateStmt -
2335 * transforms an update statement
2338 transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
2340 Query *qry = makeNode(Query);
2342 ListCell *origTargetList;
2345 qry->commandType = CMD_UPDATE;
2346 pstate->p_is_update = true;
2348 qry->resultRelation = setTargetTable(pstate, stmt->relation,
2349 interpretInhOption(stmt->relation->inhOpt),
2354 * the FROM clause is non-standard SQL syntax. We used to be able to
2355 * do this with REPLACE in POSTQUEL so we keep the feature.
2357 transformFromClause(pstate, stmt->fromClause);
2359 qry->targetList = transformTargetList(pstate, stmt->targetList);
2361 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
2363 qry->rtable = pstate->p_rtable;
2364 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
2366 qry->hasSubLinks = pstate->p_hasSubLinks;
2367 qry->hasAggs = pstate->p_hasAggs;
2368 if (pstate->p_hasAggs)
2369 parseCheckAggregates(pstate, qry);
2372 * Now we are done with SELECT-like processing, and can get on with
2373 * transforming the target list to match the UPDATE target columns.
2376 /* Prepare to assign non-conflicting resnos to resjunk attributes */
2377 if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
2378 pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
2380 /* Prepare non-junk columns for assignment to target table */
2381 origTargetList = list_head(stmt->targetList);
2383 foreach(tl, qry->targetList)
2385 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2386 Resdom *resnode = tle->resdom;
2387 ResTarget *origTarget;
2389 if (resnode->resjunk)
2392 * Resjunk nodes need no additional processing, but be sure
2393 * they have resnos that do not match any target columns; else
2394 * rewriter or planner might get confused. They don't need a
2397 resnode->resno = (AttrNumber) pstate->p_next_resno++;
2398 resnode->resname = NULL;
2401 if (origTargetList == NULL)
2402 elog(ERROR, "UPDATE target count mismatch --- internal error");
2403 origTarget = (ResTarget *) lfirst(origTargetList);
2404 Assert(IsA(origTarget, ResTarget));
2406 updateTargetListEntry(pstate, tle, origTarget->name,
2407 attnameAttNum(pstate->p_target_relation,
2408 origTarget->name, true),
2409 origTarget->indirection);
2411 origTargetList = lnext(origTargetList);
2413 if (origTargetList != NULL)
2414 elog(ERROR, "UPDATE target count mismatch --- internal error");
2420 * tranformAlterTableStmt -
2421 * transform an Alter Table Statement
2424 transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt,
2425 List **extras_before, List **extras_after)
2427 CreateStmtContext cxt;
2431 List *newcmds = NIL;
2432 bool skipValidation = true;
2433 AlterTableCmd *newcmd;
2435 cxt.stmtType = "ALTER TABLE";
2436 cxt.relation = stmt->relation;
2437 cxt.inhRelations = NIL;
2439 cxt.hasoids = false; /* need not be right */
2441 cxt.ckconstraints = NIL;
2442 cxt.fkconstraints = NIL;
2443 cxt.ixconstraints = NIL;
2449 * The only subtypes that currently require parse transformation
2450 * handling are ADD COLUMN and ADD CONSTRAINT. These largely re-use
2451 * code from CREATE TABLE.
2453 foreach(lcmd, stmt->cmds)
2455 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2457 switch (cmd->subtype)
2461 ColumnDef *def = (ColumnDef *) cmd->def;
2463 Assert(IsA(cmd->def, ColumnDef));
2464 transformColumnDefinition(pstate, &cxt,
2465 (ColumnDef *) cmd->def);
2468 * If the column has a non-null default, we can't skip
2469 * validation of foreign keys.
2471 if (((ColumnDef *) cmd->def)->raw_default != NULL)
2472 skipValidation = false;
2474 newcmds = lappend(newcmds, cmd);
2477 * Convert an ADD COLUMN ... NOT NULL constraint to a
2480 if (def->is_not_null)
2482 /* Remove NOT NULL from AddColumn */
2483 def->is_not_null = false;
2485 /* Add as a separate AlterTableCmd */
2486 newcmd = makeNode(AlterTableCmd);
2487 newcmd->subtype = AT_SetNotNull;
2488 newcmd->name = pstrdup(def->colname);
2489 newcmds = lappend(newcmds, newcmd);
2493 * All constraints are processed in other ways. Remove
2496 def->constraints = NIL;
2500 case AT_AddConstraint:
2503 * The original AddConstraint cmd node doesn't go to
2507 if (IsA(cmd->def, Constraint))
2508 transformTableConstraint(pstate, &cxt,
2509 (Constraint *) cmd->def);
2510 else if (IsA(cmd->def, FkConstraint))
2512 cxt.fkconstraints = lappend(cxt.fkconstraints, cmd->def);
2513 skipValidation = false;
2516 elog(ERROR, "unrecognized node type: %d",
2517 (int) nodeTag(cmd->def));
2520 case AT_ProcessedConstraint:
2523 * Already-transformed ADD CONSTRAINT, so just make it
2524 * look like the standard case.
2526 cmd->subtype = AT_AddConstraint;
2527 newcmds = lappend(newcmds, cmd);
2531 newcmds = lappend(newcmds, cmd);
2536 /* Postprocess index and FK constraints */
2537 transformIndexConstraints(pstate, &cxt);
2539 transformFKConstraints(pstate, &cxt, skipValidation, true);
2542 * Push any index-creation commands into the ALTER, so that they can
2543 * be scheduled nicely by tablecmds.c.
2545 foreach(l, cxt.alist)
2547 Node *idxstmt = (Node *) lfirst(l);
2549 Assert(IsA(idxstmt, IndexStmt));
2550 newcmd = makeNode(AlterTableCmd);
2551 newcmd->subtype = AT_AddIndex;
2552 newcmd->def = idxstmt;
2553 newcmds = lappend(newcmds, newcmd);
2557 /* Append any CHECK or FK constraints to the commands list */
2558 foreach(l, cxt.ckconstraints)
2560 newcmd = makeNode(AlterTableCmd);
2561 newcmd->subtype = AT_AddConstraint;
2562 newcmd->def = (Node *) lfirst(l);
2563 newcmds = lappend(newcmds, newcmd);
2565 foreach(l, cxt.fkconstraints)
2567 newcmd = makeNode(AlterTableCmd);
2568 newcmd->subtype = AT_AddConstraint;
2569 newcmd->def = (Node *) lfirst(l);
2570 newcmds = lappend(newcmds, newcmd);
2573 /* Update statement's commands list */
2574 stmt->cmds = newcmds;
2576 qry = makeNode(Query);
2577 qry->commandType = CMD_UTILITY;
2578 qry->utilityStmt = (Node *) stmt;
2580 *extras_before = list_concat(*extras_before, cxt.blist);
2581 *extras_after = list_concat(cxt.alist, *extras_after);
2587 transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
2589 Query *result = makeNode(Query);
2590 List *extras_before = NIL,
2591 *extras_after = NIL;
2593 result->commandType = CMD_UTILITY;
2594 result->utilityStmt = (Node *) stmt;
2597 * Don't allow both SCROLL and NO SCROLL to be specified
2599 if ((stmt->options & CURSOR_OPT_SCROLL) &&
2600 (stmt->options & CURSOR_OPT_NO_SCROLL))
2602 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
2603 errmsg("cannot specify both SCROLL and NO SCROLL")));
2605 stmt->query = (Node *) transformStmt(pstate, stmt->query,
2606 &extras_before, &extras_after);
2608 /* Shouldn't get any extras, since grammar only allows SelectStmt */
2609 if (extras_before || extras_after)
2610 elog(ERROR, "unexpected extra stuff in cursor statement");
2617 transformPrepareStmt(ParseState *pstate, PrepareStmt *stmt)
2619 Query *result = makeNode(Query);
2620 List *argtype_oids = NIL; /* argtype OIDs in a list */
2621 Oid *argtoids = NULL; /* and as an array */
2625 result->commandType = CMD_UTILITY;
2626 result->utilityStmt = (Node *) stmt;
2628 /* Transform list of TypeNames to list (and array) of type OIDs */
2629 nargs = list_length(stmt->argtypes);
2636 argtoids = (Oid *) palloc(nargs * sizeof(Oid));
2638 foreach(l, stmt->argtypes)
2640 TypeName *tn = lfirst(l);
2641 Oid toid = typenameTypeId(tn);
2643 argtype_oids = lappend_oid(argtype_oids, toid);
2644 argtoids[i++] = toid;
2648 stmt->argtype_oids = argtype_oids;
2651 * Analyze the statement using these parameter types (any parameters
2652 * passed in from above us will not be visible to it).
2654 queries = parse_analyze((Node *) stmt->query, argtoids, nargs);
2657 * Shouldn't get any extra statements, since grammar only allows
2660 if (list_length(queries) != 1)
2661 elog(ERROR, "unexpected extra stuff in prepared statement");
2663 stmt->query = linitial(queries);
2669 transformExecuteStmt(ParseState *pstate, ExecuteStmt *stmt)
2671 Query *result = makeNode(Query);
2674 result->commandType = CMD_UTILITY;
2675 result->utilityStmt = (Node *) stmt;
2677 paramtypes = FetchPreparedStatementParams(stmt->name);
2679 if (stmt->params || paramtypes)
2681 int nparams = list_length(stmt->params);
2682 int nexpected = list_length(paramtypes);
2687 if (nparams != nexpected)
2689 (errcode(ERRCODE_SYNTAX_ERROR),
2690 errmsg("wrong number of parameters for prepared statement \"%s\"",
2692 errdetail("Expected %d parameters but got %d.",
2693 nexpected, nparams)));
2695 forboth(l, stmt->params, l2, paramtypes)
2697 Node *expr = lfirst(l);
2698 Oid expected_type_id = lfirst_oid(l2);
2701 expr = transformExpr(pstate, expr);
2703 /* Cannot contain subselects or aggregates */
2704 if (pstate->p_hasSubLinks)
2706 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2707 errmsg("cannot use subquery in EXECUTE parameter")));
2708 if (pstate->p_hasAggs)
2710 (errcode(ERRCODE_GROUPING_ERROR),
2711 errmsg("cannot use aggregate function in EXECUTE parameter")));
2713 given_type_id = exprType(expr);
2715 expr = coerce_to_target_type(pstate, expr, given_type_id,
2716 expected_type_id, -1,
2717 COERCION_ASSIGNMENT,
2718 COERCE_IMPLICIT_CAST);
2722 (errcode(ERRCODE_DATATYPE_MISMATCH),
2723 errmsg("parameter $%d of type %s cannot be coerced to the expected type %s",
2725 format_type_be(given_type_id),
2726 format_type_be(expected_type_id)),
2727 errhint("You will need to rewrite or cast the expression.")));
2737 /* exported so planner can check again after rewriting, query pullup, etc */
2739 CheckSelectForUpdate(Query *qry)
2741 if (qry->setOperations)
2743 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2744 errmsg("SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT")));
2745 if (qry->distinctClause != NIL)
2747 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2748 errmsg("SELECT FOR UPDATE is not allowed with DISTINCT clause")));
2749 if (qry->groupClause != NIL)
2751 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2752 errmsg("SELECT FOR UPDATE is not allowed with GROUP BY clause")));
2753 if (qry->havingQual != NULL)
2755 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2756 errmsg("SELECT FOR UPDATE is not allowed with HAVING clause")));
2759 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2760 errmsg("SELECT FOR UPDATE is not allowed with aggregate functions")));
2764 * Convert FOR UPDATE name list into rowMarks list of integer relids
2766 * NB: if you need to change this, see also markQueryForUpdate()
2767 * in rewriteHandler.c.
2770 transformForUpdate(Query *qry, List *forUpdate)
2772 List *rowMarks = qry->rowMarks;
2777 CheckSelectForUpdate(qry);
2779 if (linitial(forUpdate) == NULL)
2781 /* all regular tables used in query */
2783 foreach(rt, qry->rtable)
2785 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2788 switch (rte->rtekind)
2791 if (!list_member_int(rowMarks, i)) /* avoid duplicates */
2792 rowMarks = lappend_int(rowMarks, i);
2793 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
2798 * FOR UPDATE of subquery is propagated to subquery's
2801 transformForUpdate(rte->subquery, list_make1(NULL));
2804 /* ignore JOIN, SPECIAL, FUNCTION RTEs */
2811 /* just the named tables */
2812 foreach(l, forUpdate)
2814 char *relname = strVal(lfirst(l));
2817 foreach(rt, qry->rtable)
2819 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2822 if (strcmp(rte->eref->aliasname, relname) == 0)
2824 switch (rte->rtekind)
2827 if (!list_member_int(rowMarks, i)) /* avoid duplicates */
2828 rowMarks = lappend_int(rowMarks, i);
2829 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
2834 * FOR UPDATE of subquery is propagated to
2837 transformForUpdate(rte->subquery, list_make1(NULL));
2841 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2842 errmsg("SELECT FOR UPDATE cannot be applied to a join")));
2846 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2847 errmsg("SELECT FOR UPDATE cannot be applied to NEW or OLD")));
2851 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2852 errmsg("SELECT FOR UPDATE cannot be applied to a function")));
2855 elog(ERROR, "unrecognized RTE type: %d",
2856 (int) rte->rtekind);
2859 break; /* out of foreach loop */
2864 (errcode(ERRCODE_UNDEFINED_TABLE),
2865 errmsg("relation \"%s\" in FOR UPDATE clause not found in FROM clause",
2870 qry->rowMarks = rowMarks;
2875 * Preprocess a list of column constraint clauses
2876 * to attach constraint attributes to their primary constraint nodes
2877 * and detect inconsistent/misplaced constraint attributes.
2879 * NOTE: currently, attributes are only supported for FOREIGN KEY primary
2880 * constraints, but someday they ought to be supported for other constraints.
2883 transformConstraintAttrs(List *constraintList)
2885 Node *lastprimarynode = NULL;
2886 bool saw_deferrability = false;
2887 bool saw_initially = false;
2890 foreach(clist, constraintList)
2892 Node *node = lfirst(clist);
2894 if (!IsA(node, Constraint))
2896 lastprimarynode = node;
2897 /* reset flags for new primary node */
2898 saw_deferrability = false;
2899 saw_initially = false;
2903 Constraint *con = (Constraint *) node;
2905 switch (con->contype)
2907 case CONSTR_ATTR_DEFERRABLE:
2908 if (lastprimarynode == NULL ||
2909 !IsA(lastprimarynode, FkConstraint))
2911 (errcode(ERRCODE_SYNTAX_ERROR),
2912 errmsg("misplaced DEFERRABLE clause")));
2913 if (saw_deferrability)
2915 (errcode(ERRCODE_SYNTAX_ERROR),
2916 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
2917 saw_deferrability = true;
2918 ((FkConstraint *) lastprimarynode)->deferrable = true;
2920 case CONSTR_ATTR_NOT_DEFERRABLE:
2921 if (lastprimarynode == NULL ||
2922 !IsA(lastprimarynode, FkConstraint))
2924 (errcode(ERRCODE_SYNTAX_ERROR),
2925 errmsg("misplaced NOT DEFERRABLE clause")));
2926 if (saw_deferrability)
2928 (errcode(ERRCODE_SYNTAX_ERROR),
2929 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
2930 saw_deferrability = true;
2931 ((FkConstraint *) lastprimarynode)->deferrable = false;
2932 if (saw_initially &&
2933 ((FkConstraint *) lastprimarynode)->initdeferred)
2935 (errcode(ERRCODE_SYNTAX_ERROR),
2936 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
2938 case CONSTR_ATTR_DEFERRED:
2939 if (lastprimarynode == NULL ||
2940 !IsA(lastprimarynode, FkConstraint))
2942 (errcode(ERRCODE_SYNTAX_ERROR),
2943 errmsg("misplaced INITIALLY DEFERRED clause")));
2946 (errcode(ERRCODE_SYNTAX_ERROR),
2947 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
2948 saw_initially = true;
2949 ((FkConstraint *) lastprimarynode)->initdeferred = true;
2952 * If only INITIALLY DEFERRED appears, assume
2955 if (!saw_deferrability)
2956 ((FkConstraint *) lastprimarynode)->deferrable = true;
2957 else if (!((FkConstraint *) lastprimarynode)->deferrable)
2959 (errcode(ERRCODE_SYNTAX_ERROR),
2960 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
2962 case CONSTR_ATTR_IMMEDIATE:
2963 if (lastprimarynode == NULL ||
2964 !IsA(lastprimarynode, FkConstraint))
2966 (errcode(ERRCODE_SYNTAX_ERROR),
2967 errmsg("misplaced INITIALLY IMMEDIATE clause")));
2970 (errcode(ERRCODE_SYNTAX_ERROR),
2971 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
2972 saw_initially = true;
2973 ((FkConstraint *) lastprimarynode)->initdeferred = false;
2976 /* Otherwise it's not an attribute */
2977 lastprimarynode = node;
2978 /* reset flags for new primary node */
2979 saw_deferrability = false;
2980 saw_initially = false;
2987 /* Build a FromExpr node */
2989 makeFromExpr(List *fromlist, Node *quals)
2991 FromExpr *f = makeNode(FromExpr);
2993 f->fromlist = fromlist;
2999 * Special handling of type definition for a column
3002 transformColumnType(ParseState *pstate, ColumnDef *column)
3005 * All we really need to do here is verify that the type is valid.
3007 Type ctype = typenameType(column->typename);
3009 ReleaseSysCache(ctype);
3013 setSchemaName(char *context_schema, char **stmt_schema_name)
3015 if (*stmt_schema_name == NULL)
3016 *stmt_schema_name = context_schema;
3017 else if (strcmp(context_schema, *stmt_schema_name) != 0)
3019 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
3020 errmsg("CREATE specifies a schema (%s) "
3021 "different from the one being created (%s)",
3022 *stmt_schema_name, context_schema)));
3026 * analyzeCreateSchemaStmt -
3027 * analyzes the "create schema" statement
3029 * Split the schema element list into individual commands and place
3030 * them in the result list in an order such that there are no forward
3031 * references (e.g. GRANT to a table created later in the list). Note
3032 * that the logic we use for determining forward references is
3033 * presently quite incomplete.
3035 * SQL92 also allows constraints to make forward references, so thumb through
3036 * the table columns and move forward references to a posterior alter-table
3039 * The result is a list of parse nodes that still need to be analyzed ---
3040 * but we can't analyze the later commands until we've executed the earlier
3041 * ones, because of possible inter-object references.
3043 * Note: Called from commands/schemacmds.c
3046 analyzeCreateSchemaStmt(CreateSchemaStmt *stmt)
3048 CreateSchemaStmtContext cxt;
3052 cxt.stmtType = "CREATE SCHEMA";
3053 cxt.schemaname = stmt->schemaname;
3054 cxt.authid = stmt->authid;
3055 cxt.sequences = NIL;
3061 cxt.fwconstraints = NIL;
3067 * Run through each schema element in the schema element list.
3068 * Separate statements by type, and do preliminary analysis.
3070 foreach(elements, stmt->schemaElts)
3072 Node *element = lfirst(elements);
3074 switch (nodeTag(element))
3076 case T_CreateSeqStmt:
3078 CreateSeqStmt *elp = (CreateSeqStmt *) element;
3080 setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
3081 cxt.sequences = lappend(cxt.sequences, element);
3087 CreateStmt *elp = (CreateStmt *) element;
3089 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3092 * XXX todo: deal with constraints
3094 cxt.tables = lappend(cxt.tables, element);
3100 ViewStmt *elp = (ViewStmt *) element;
3102 setSchemaName(cxt.schemaname, &elp->view->schemaname);
3105 * XXX todo: deal with references between views
3107 cxt.views = lappend(cxt.views, element);
3113 IndexStmt *elp = (IndexStmt *) element;
3115 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3116 cxt.indexes = lappend(cxt.indexes, element);
3120 case T_CreateTrigStmt:
3122 CreateTrigStmt *elp = (CreateTrigStmt *) element;
3124 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3125 cxt.triggers = lappend(cxt.triggers, element);
3130 cxt.grants = lappend(cxt.grants, element);
3134 elog(ERROR, "unrecognized node type: %d",
3135 (int) nodeTag(element));
3140 result = list_concat(result, cxt.sequences);
3141 result = list_concat(result, cxt.tables);
3142 result = list_concat(result, cxt.views);
3143 result = list_concat(result, cxt.indexes);
3144 result = list_concat(result, cxt.triggers);
3145 result = list_concat(result, cxt.grants);
3151 * Traverse a fully-analyzed tree to verify that parameter symbols
3152 * match their types. We need this because some Params might still
3153 * be UNKNOWN, if there wasn't anything to force their coercion,
3154 * and yet other instances seen later might have gotten coerced.
3157 check_parameter_resolution_walker(Node *node,
3158 check_parameter_resolution_context *context)
3162 if (IsA(node, Param))
3164 Param *param = (Param *) node;
3166 if (param->paramkind == PARAM_NUM)
3168 int paramno = param->paramid;
3170 if (paramno <= 0 || /* shouldn't happen, but... */
3171 paramno > context->numParams)
3173 (errcode(ERRCODE_UNDEFINED_PARAMETER),
3174 errmsg("there is no parameter $%d", paramno)));
3176 if (param->paramtype != context->paramTypes[paramno - 1])
3178 (errcode(ERRCODE_AMBIGUOUS_PARAMETER),
3179 errmsg("could not determine data type of parameter $%d",
3184 if (IsA(node, Query))
3186 /* Recurse into RTE subquery or not-yet-planned sublink subquery */
3187 return query_tree_walker((Query *) node,
3188 check_parameter_resolution_walker,
3189 (void *) context, 0);
3191 return expression_tree_walker(node, check_parameter_resolution_walker,