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.327 2005/11/22 18:17:15 momjian Exp $
11 *-------------------------------------------------------------------------
16 #include "access/heapam.h"
17 #include "catalog/heap.h"
18 #include "catalog/index.h"
19 #include "catalog/namespace.h"
20 #include "catalog/pg_index.h"
21 #include "catalog/pg_type.h"
22 #include "commands/defrem.h"
23 #include "commands/prepare.h"
24 #include "miscadmin.h"
25 #include "nodes/makefuncs.h"
26 #include "optimizer/clauses.h"
27 #include "optimizer/var.h"
28 #include "parser/analyze.h"
29 #include "parser/gramparse.h"
30 #include "parser/parsetree.h"
31 #include "parser/parse_agg.h"
32 #include "parser/parse_clause.h"
33 #include "parser/parse_coerce.h"
34 #include "parser/parse_expr.h"
35 #include "parser/parse_oper.h"
36 #include "parser/parse_relation.h"
37 #include "parser/parse_target.h"
38 #include "parser/parse_type.h"
39 #include "parser/parse_expr.h"
40 #include "rewrite/rewriteManip.h"
41 #include "utils/acl.h"
42 #include "utils/builtins.h"
43 #include "utils/fmgroids.h"
44 #include "utils/guc.h"
45 #include "utils/lsyscache.h"
46 #include "utils/relcache.h"
47 #include "utils/syscache.h"
50 /* State shared by transformCreateSchemaStmt and its subroutines */
53 const char *stmtType; /* "CREATE SCHEMA" or "ALTER SCHEMA" */
54 char *schemaname; /* name of schema */
55 char *authid; /* owner of schema */
56 List *sequences; /* CREATE SEQUENCE items */
57 List *tables; /* CREATE TABLE items */
58 List *views; /* CREATE VIEW items */
59 List *indexes; /* CREATE INDEX items */
60 List *triggers; /* CREATE TRIGGER items */
61 List *grants; /* GRANT items */
62 List *fwconstraints; /* Forward referencing FOREIGN KEY constraints */
63 List *alters; /* Generated ALTER items (from the above) */
64 List *ixconstraints; /* index-creating constraints */
65 List *blist; /* "before list" of things to do before
66 * creating the schema */
67 List *alist; /* "after list" of things to do after creating
69 } CreateSchemaStmtContext;
71 /* State shared by transformCreateStmt and its subroutines */
74 const char *stmtType; /* "CREATE TABLE" or "ALTER TABLE" */
75 RangeVar *relation; /* relation to create */
76 List *inhRelations; /* relations to inherit from */
77 bool hasoids; /* does relation have an OID column? */
78 bool isalter; /* true if altering existing table */
79 List *columns; /* ColumnDef items */
80 List *ckconstraints; /* CHECK constraints */
81 List *fkconstraints; /* FOREIGN KEY constraints */
82 List *ixconstraints; /* index-creating constraints */
83 List *blist; /* "before list" of things to do before
84 * creating the table */
85 List *alist; /* "after list" of things to do after creating
87 IndexStmt *pkey; /* PRIMARY KEY index, if any */
94 } check_parameter_resolution_context;
97 static List *do_parse_analyze(Node *parseTree, ParseState *pstate);
98 static Query *transformStmt(ParseState *pstate, Node *stmt,
99 List **extras_before, List **extras_after);
100 static Query *transformViewStmt(ParseState *pstate, ViewStmt *stmt,
101 List **extras_before, List **extras_after);
102 static Query *transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt);
103 static Query *transformInsertStmt(ParseState *pstate, InsertStmt *stmt,
104 List **extras_before, List **extras_after);
105 static Query *transformIndexStmt(ParseState *pstate, IndexStmt *stmt);
106 static Query *transformRuleStmt(ParseState *query, RuleStmt *stmt,
107 List **extras_before, List **extras_after);
108 static Query *transformSelectStmt(ParseState *pstate, SelectStmt *stmt);
109 static Query *transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt);
110 static Node *transformSetOperationTree(ParseState *pstate, SelectStmt *stmt);
111 static Query *transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt);
112 static Query *transformDeclareCursorStmt(ParseState *pstate,
113 DeclareCursorStmt *stmt);
114 static Query *transformPrepareStmt(ParseState *pstate, PrepareStmt *stmt);
115 static Query *transformExecuteStmt(ParseState *pstate, ExecuteStmt *stmt);
116 static Query *transformCreateStmt(ParseState *pstate, CreateStmt *stmt,
117 List **extras_before, List **extras_after);
118 static Query *transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt,
119 List **extras_before, List **extras_after);
120 static void transformColumnDefinition(ParseState *pstate,
121 CreateStmtContext *cxt,
123 static void transformTableConstraint(ParseState *pstate,
124 CreateStmtContext *cxt,
125 Constraint *constraint);
126 static void transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
127 InhRelation *inhrelation);
128 static void transformIndexConstraints(ParseState *pstate,
129 CreateStmtContext *cxt);
130 static void transformFKConstraints(ParseState *pstate,
131 CreateStmtContext *cxt,
133 bool isAddConstraint);
134 static void applyColumnNames(List *dst, List *src);
135 static List *getSetColTypes(ParseState *pstate, Node *node);
136 static void transformLockingClause(Query *qry, LockingClause *lc);
137 static void transformConstraintAttrs(List *constraintList);
138 static void transformColumnType(ParseState *pstate, ColumnDef *column);
139 static void release_pstate_resources(ParseState *pstate);
140 static FromExpr *makeFromExpr(List *fromlist, Node *quals);
141 static bool check_parameter_resolution_walker(Node *node,
142 check_parameter_resolution_context *context);
147 * Analyze a raw parse tree and transform it to Query form.
149 * Optionally, information about $n parameter types can be supplied.
150 * References to $n indexes not defined by paramTypes[] are disallowed.
152 * The result is a List of Query nodes (we need a list since some commands
153 * produce multiple Queries). Optimizable statements require considerable
154 * transformation, while many utility-type statements are simply hung off
155 * a dummy CMD_UTILITY Query node.
158 parse_analyze(Node *parseTree, Oid *paramTypes, int numParams)
160 ParseState *pstate = make_parsestate(NULL);
163 pstate->p_paramtypes = paramTypes;
164 pstate->p_numparams = numParams;
165 pstate->p_variableparams = false;
167 result = do_parse_analyze(parseTree, pstate);
175 * parse_analyze_varparams
177 * This variant is used when it's okay to deduce information about $n
178 * symbol datatypes from context. The passed-in paramTypes[] array can
179 * be modified or enlarged (via repalloc).
182 parse_analyze_varparams(Node *parseTree, Oid **paramTypes, int *numParams)
184 ParseState *pstate = make_parsestate(NULL);
187 pstate->p_paramtypes = *paramTypes;
188 pstate->p_numparams = *numParams;
189 pstate->p_variableparams = true;
191 result = do_parse_analyze(parseTree, pstate);
193 *paramTypes = pstate->p_paramtypes;
194 *numParams = pstate->p_numparams;
198 /* make sure all is well with parameter types */
201 check_parameter_resolution_context context;
203 context.paramTypes = *paramTypes;
204 context.numParams = *numParams;
205 check_parameter_resolution_walker((Node *) result, &context);
213 * Entry point for recursively analyzing a sub-statement.
216 parse_sub_analyze(Node *parseTree, ParseState *parentParseState)
218 ParseState *pstate = make_parsestate(parentParseState);
221 result = do_parse_analyze(parseTree, pstate);
230 * Workhorse code shared by the above variants of parse_analyze.
233 do_parse_analyze(Node *parseTree, ParseState *pstate)
237 /* Lists to return extra commands from transformation */
238 List *extras_before = NIL;
239 List *extras_after = NIL;
243 query = transformStmt(pstate, parseTree, &extras_before, &extras_after);
245 /* don't need to access result relation any more */
246 release_pstate_resources(pstate);
248 foreach(l, extras_before)
249 result = list_concat(result, parse_sub_analyze(lfirst(l), pstate));
251 result = lappend(result, query);
253 foreach(l, extras_after)
254 result = list_concat(result, parse_sub_analyze(lfirst(l), pstate));
257 * Make sure that only the original query is marked original. We have to
258 * do this explicitly since recursive calls of do_parse_analyze will have
259 * marked some of the added-on queries as "original". Also mark only the
260 * original query as allowed to set the command-result tag.
264 Query *q = lfirst(l);
268 q->querySource = QSRC_ORIGINAL;
273 q->querySource = QSRC_PARSER;
274 q->canSetTag = false;
282 release_pstate_resources(ParseState *pstate)
284 if (pstate->p_target_relation != NULL)
285 heap_close(pstate->p_target_relation, NoLock);
286 pstate->p_target_relation = NULL;
287 pstate->p_target_rangetblentry = NULL;
292 * transform a Parse tree into a Query tree.
295 transformStmt(ParseState *pstate, Node *parseTree,
296 List **extras_before, List **extras_after)
298 Query *result = NULL;
300 switch (nodeTag(parseTree))
303 * Non-optimizable statements
306 result = transformCreateStmt(pstate, (CreateStmt *) parseTree,
307 extras_before, extras_after);
311 result = transformIndexStmt(pstate, (IndexStmt *) parseTree);
315 result = transformRuleStmt(pstate, (RuleStmt *) parseTree,
316 extras_before, extras_after);
320 result = transformViewStmt(pstate, (ViewStmt *) parseTree,
321 extras_before, extras_after);
326 ExplainStmt *n = (ExplainStmt *) parseTree;
328 result = makeNode(Query);
329 result->commandType = CMD_UTILITY;
330 n->query = transformStmt(pstate, (Node *) n->query,
331 extras_before, extras_after);
332 result->utilityStmt = (Node *) parseTree;
336 case T_AlterTableStmt:
337 result = transformAlterTableStmt(pstate,
338 (AlterTableStmt *) parseTree,
339 extras_before, extras_after);
343 result = transformPrepareStmt(pstate, (PrepareStmt *) parseTree);
347 result = transformExecuteStmt(pstate, (ExecuteStmt *) parseTree);
351 * Optimizable statements
354 result = transformInsertStmt(pstate, (InsertStmt *) parseTree,
355 extras_before, extras_after);
359 result = transformDeleteStmt(pstate, (DeleteStmt *) parseTree);
363 result = transformUpdateStmt(pstate, (UpdateStmt *) parseTree);
367 if (((SelectStmt *) parseTree)->op == SETOP_NONE)
368 result = transformSelectStmt(pstate,
369 (SelectStmt *) parseTree);
371 result = transformSetOperationStmt(pstate,
372 (SelectStmt *) parseTree);
375 case T_DeclareCursorStmt:
376 result = transformDeclareCursorStmt(pstate,
377 (DeclareCursorStmt *) parseTree);
383 * other statements don't require any transformation-- just return
384 * the original parsetree, yea!
386 result = makeNode(Query);
387 result->commandType = CMD_UTILITY;
388 result->utilityStmt = (Node *) parseTree;
392 /* Mark as original query until we learn differently */
393 result->querySource = QSRC_ORIGINAL;
394 result->canSetTag = true;
397 * Check that we did not produce too many resnos; at the very least we
398 * cannot allow more than 2^16, since that would exceed the range of a
399 * AttrNumber. It seems safest to use MaxTupleAttributeNumber.
401 if (pstate->p_next_resno - 1 > MaxTupleAttributeNumber)
403 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
404 errmsg("target lists can have at most %d entries",
405 MaxTupleAttributeNumber)));
411 transformViewStmt(ParseState *pstate, ViewStmt *stmt,
412 List **extras_before, List **extras_after)
414 Query *result = makeNode(Query);
416 result->commandType = CMD_UTILITY;
417 result->utilityStmt = (Node *) stmt;
419 stmt->query = transformStmt(pstate, (Node *) stmt->query,
420 extras_before, extras_after);
423 * If a list of column names was given, run through and insert these into
424 * the actual query tree. - thomas 2000-03-08
426 * Outer loop is over targetlist to make it easier to skip junk targetlist
429 if (stmt->aliases != NIL)
431 ListCell *alist_item = list_head(stmt->aliases);
432 ListCell *targetList;
434 foreach(targetList, stmt->query->targetList)
436 TargetEntry *te = (TargetEntry *) lfirst(targetList);
438 Assert(IsA(te, TargetEntry));
439 /* junk columns don't get aliases */
442 te->resname = pstrdup(strVal(lfirst(alist_item)));
443 alist_item = lnext(alist_item);
444 if (alist_item == NULL)
445 break; /* done assigning aliases */
448 if (alist_item != NULL)
450 (errcode(ERRCODE_SYNTAX_ERROR),
451 errmsg("CREATE VIEW specifies more column "
452 "names than columns")));
459 * transformDeleteStmt -
460 * transforms a Delete Statement
463 transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
465 Query *qry = makeNode(Query);
468 qry->commandType = CMD_DELETE;
470 /* set up range table with just the result rel */
471 qry->resultRelation = setTargetTable(pstate, stmt->relation,
472 interpretInhOption(stmt->relation->inhOpt),
476 qry->distinctClause = NIL;
479 * The USING clause is non-standard SQL syntax, and is equivalent in
480 * functionality to the FROM list that can be specified for UPDATE. The
481 * USING keyword is used rather than FROM because FROM is already a
482 * keyword in the DELETE syntax.
484 transformFromClause(pstate, stmt->usingClause);
486 /* fix where clause */
487 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
489 /* done building the range table and jointree */
490 qry->rtable = pstate->p_rtable;
491 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
493 qry->hasSubLinks = pstate->p_hasSubLinks;
494 qry->hasAggs = pstate->p_hasAggs;
495 if (pstate->p_hasAggs)
496 parseCheckAggregates(pstate, qry);
502 * transformInsertStmt -
503 * transform an Insert Statement
506 transformInsertStmt(ParseState *pstate, InsertStmt *stmt,
507 List **extras_before, List **extras_after)
509 Query *qry = makeNode(Query);
510 Query *selectQuery = NULL;
512 List *sub_relnamespace;
513 List *sub_varnamespace;
520 qry->commandType = CMD_INSERT;
521 pstate->p_is_insert = true;
524 * If a non-nil rangetable/namespace was passed in, and we are doing
525 * INSERT/SELECT, arrange to pass the rangetable/namespace down to the
526 * SELECT. This can only happen if we are inside a CREATE RULE, and in
527 * that case we want the rule's OLD and NEW rtable entries to appear as
528 * part of the SELECT's rtable, not as outer references for it. (Kluge!)
529 * The SELECT's joinlist is not affected however. We must do this before
530 * adding the target table to the INSERT's rtable.
532 if (stmt->selectStmt)
534 sub_rtable = pstate->p_rtable;
535 pstate->p_rtable = NIL;
536 sub_relnamespace = pstate->p_relnamespace;
537 pstate->p_relnamespace = NIL;
538 sub_varnamespace = pstate->p_varnamespace;
539 pstate->p_varnamespace = NIL;
543 sub_rtable = NIL; /* not used, but keep compiler quiet */
544 sub_relnamespace = NIL;
545 sub_varnamespace = NIL;
549 * Must get write lock on INSERT target table before scanning SELECT, else
550 * we will grab the wrong kind of initial lock if the target table is also
551 * mentioned in the SELECT part. Note that the target table is not added
552 * to the joinlist or namespace.
554 qry->resultRelation = setTargetTable(pstate, stmt->relation,
555 false, false, ACL_INSERT);
558 * Is it INSERT ... SELECT or INSERT ... VALUES?
560 if (stmt->selectStmt)
563 * We make the sub-pstate a child of the outer pstate so that it can
564 * see any Param definitions supplied from above. Since the outer
565 * pstate's rtable and namespace are presently empty, there are no
566 * side-effects of exposing names the sub-SELECT shouldn't be able to
569 ParseState *sub_pstate = make_parsestate(pstate);
574 * Process the source SELECT.
576 * It is important that this be handled just like a standalone SELECT;
577 * otherwise the behavior of SELECT within INSERT might be different
578 * from a stand-alone SELECT. (Indeed, Postgres up through 6.5 had
579 * bugs of just that nature...)
581 sub_pstate->p_rtable = sub_rtable;
582 sub_pstate->p_relnamespace = sub_relnamespace;
583 sub_pstate->p_varnamespace = sub_varnamespace;
586 * Note: we are not expecting that extras_before and extras_after are
587 * going to be used by the transformation of the SELECT statement.
589 selectQuery = transformStmt(sub_pstate, stmt->selectStmt,
590 extras_before, extras_after);
592 release_pstate_resources(sub_pstate);
595 Assert(IsA(selectQuery, Query));
596 Assert(selectQuery->commandType == CMD_SELECT);
597 if (selectQuery->into)
599 (errcode(ERRCODE_SYNTAX_ERROR),
600 errmsg("INSERT ... SELECT may not specify INTO")));
603 * Make the source be a subquery in the INSERT's rangetable, and add
604 * it to the INSERT's joinlist.
606 rte = addRangeTableEntryForSubquery(pstate,
608 makeAlias("*SELECT*", NIL),
610 rtr = makeNode(RangeTblRef);
611 /* assume new rte is at end */
612 rtr->rtindex = list_length(pstate->p_rtable);
613 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
614 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
617 * Generate a targetlist for the INSERT that selects all the
618 * non-resjunk columns from the subquery. (We need this to be
619 * separate from the subquery's tlist because we may add columns,
620 * insert datatype coercions, etc.)
622 * HACK: unknown-type constants and params in the SELECT's targetlist
623 * are copied up as-is rather than being referenced as subquery
624 * outputs. This is to ensure that when we try to coerce them to
625 * the target column's datatype, the right things happen (see
626 * special cases in coerce_type). Otherwise, this fails:
627 * INSERT INTO foo SELECT 'bar', ... FROM baz
630 qry->targetList = NIL;
631 foreach(tl, selectQuery->targetList)
633 TargetEntry *tle = (TargetEntry *) lfirst(tl);
639 (IsA(tle->expr, Const) ||IsA(tle->expr, Param)) &&
640 exprType((Node *) tle->expr) == UNKNOWNOID)
643 expr = (Expr *) makeVar(rtr->rtindex,
645 exprType((Node *) tle->expr),
646 exprTypmod((Node *) tle->expr),
648 tle = makeTargetEntry(expr,
649 (AttrNumber) pstate->p_next_resno++,
652 qry->targetList = lappend(qry->targetList, tle);
658 * For INSERT ... VALUES, transform the given list of values to form a
659 * targetlist for the INSERT.
661 qry->targetList = transformTargetList(pstate, stmt->targetList);
665 * Now we are done with SELECT-like processing, and can get on with
666 * transforming the target list to match the INSERT target columns.
669 /* Prepare to assign non-conflicting resnos to resjunk attributes */
670 if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
671 pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
673 /* Validate stmt->cols list, or build default list if no list given */
674 icolumns = checkInsertTargets(pstate, stmt->cols, &attrnos);
677 * Prepare columns for assignment to target table.
679 icols = list_head(icolumns);
680 attnos = list_head(attrnos);
681 foreach(tl, qry->targetList)
683 TargetEntry *tle = (TargetEntry *) lfirst(tl);
686 if (icols == NULL || attnos == NULL)
688 (errcode(ERRCODE_SYNTAX_ERROR),
689 errmsg("INSERT has more expressions than target columns")));
691 col = (ResTarget *) lfirst(icols);
692 Assert(IsA(col, ResTarget));
694 Assert(!tle->resjunk);
695 updateTargetListEntry(pstate, tle, col->name, lfirst_int(attnos),
698 icols = lnext(icols);
699 attnos = lnext(attnos);
703 * Ensure that the targetlist has the same number of entries that were
704 * present in the columns list. Don't do the check unless an explicit
705 * columns list was given, though.
707 if (stmt->cols != NIL && (icols != NULL || attnos != NULL))
709 (errcode(ERRCODE_SYNTAX_ERROR),
710 errmsg("INSERT has more target columns than expressions")));
712 /* done building the range table and jointree */
713 qry->rtable = pstate->p_rtable;
714 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
716 qry->hasSubLinks = pstate->p_hasSubLinks;
717 qry->hasAggs = pstate->p_hasAggs;
718 if (pstate->p_hasAggs)
719 parseCheckAggregates(pstate, qry);
725 * transformCreateStmt -
726 * transforms the "create table" statement
727 * SQL92 allows constraints to be scattered all over, so thumb through
728 * the columns and collect all constraints into one place.
729 * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
730 * then expand those into multiple IndexStmt blocks.
731 * - thomas 1997-12-02
734 transformCreateStmt(ParseState *pstate, CreateStmt *stmt,
735 List **extras_before, List **extras_after)
737 CreateStmtContext cxt;
741 cxt.stmtType = "CREATE TABLE";
742 cxt.relation = stmt->relation;
743 cxt.inhRelations = stmt->inhRelations;
746 cxt.ckconstraints = NIL;
747 cxt.fkconstraints = NIL;
748 cxt.ixconstraints = NIL;
752 cxt.hasoids = interpretOidsOption(stmt->hasoids);
755 * Run through each primary element in the table creation clause. Separate
756 * column defs from constraints, and do preliminary analysis.
758 foreach(elements, stmt->tableElts)
760 Node *element = lfirst(elements);
762 switch (nodeTag(element))
765 transformColumnDefinition(pstate, &cxt,
766 (ColumnDef *) element);
770 transformTableConstraint(pstate, &cxt,
771 (Constraint *) element);
775 /* No pre-transformation needed */
776 cxt.fkconstraints = lappend(cxt.fkconstraints, element);
780 transformInhRelation(pstate, &cxt,
781 (InhRelation *) element);
785 elog(ERROR, "unrecognized node type: %d",
786 (int) nodeTag(element));
791 Assert(stmt->constraints == NIL);
794 * Postprocess constraints that give rise to index definitions.
796 transformIndexConstraints(pstate, &cxt);
799 * Postprocess foreign-key constraints.
801 transformFKConstraints(pstate, &cxt, true, false);
807 q->commandType = CMD_UTILITY;
808 q->utilityStmt = (Node *) stmt;
809 stmt->tableElts = cxt.columns;
810 stmt->constraints = cxt.ckconstraints;
811 *extras_before = list_concat(*extras_before, cxt.blist);
812 *extras_after = list_concat(cxt.alist, *extras_after);
818 transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
823 Constraint *constraint;
826 cxt->columns = lappend(cxt->columns, column);
828 /* Check for SERIAL pseudo-types */
830 if (list_length(column->typename->names) == 1)
832 char *typname = strVal(linitial(column->typename->names));
834 if (strcmp(typname, "serial") == 0 ||
835 strcmp(typname, "serial4") == 0)
838 column->typename->names = NIL;
839 column->typename->typeid = INT4OID;
841 else if (strcmp(typname, "bigserial") == 0 ||
842 strcmp(typname, "serial8") == 0)
845 column->typename->names = NIL;
846 column->typename->typeid = INT8OID;
850 /* Do necessary work on the column type declaration */
851 transformColumnType(pstate, column);
853 /* Special actions for SERIAL pseudo-types */
861 FuncCall *funccallnode;
862 CreateSeqStmt *seqstmt;
865 * Determine namespace and name to use for the sequence.
867 * Although we use ChooseRelationName, it's not guaranteed that the
868 * selected sequence name won't conflict; given sufficiently long
869 * field names, two different serial columns in the same table could
870 * be assigned the same sequence name, and we'd not notice since we
871 * aren't creating the sequence quite yet. In practice this seems
872 * quite unlikely to be a problem, especially since few people would
873 * need two serial columns in one table.
875 snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
876 snamespace = get_namespace_name(snamespaceid);
877 sname = ChooseRelationName(cxt->relation->relname,
883 (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
884 cxt->stmtType, sname,
885 cxt->relation->relname, column->colname)));
888 * Build a CREATE SEQUENCE command to create the sequence object, and
889 * add it to the list of things to be done before this CREATE/ALTER
892 seqstmt = makeNode(CreateSeqStmt);
893 seqstmt->sequence = makeRangeVar(snamespace, sname);
894 seqstmt->options = NIL;
896 cxt->blist = lappend(cxt->blist, seqstmt);
899 * Mark the ColumnDef so that during execution, an appropriate
900 * dependency will be added from the sequence to the column.
902 column->support = makeRangeVar(snamespace, sname);
905 * Create appropriate constraints for SERIAL. We do this in full,
906 * rather than shortcutting, so that we will detect any conflicting
907 * constraints the user wrote (like a different DEFAULT).
909 * Create an expression tree representing the function call
910 * nextval('sequencename'). We cannot reduce the raw tree to cooked
911 * form until after the sequence is created, but there's no need to do
914 qstring = quote_qualified_identifier(snamespace, sname);
915 snamenode = makeNode(A_Const);
916 snamenode->val.type = T_String;
917 snamenode->val.val.str = qstring;
918 snamenode->typename = SystemTypeName("regclass");
919 funccallnode = makeNode(FuncCall);
920 funccallnode->funcname = SystemFuncName("nextval");
921 funccallnode->args = list_make1(snamenode);
922 funccallnode->agg_star = false;
923 funccallnode->agg_distinct = false;
925 constraint = makeNode(Constraint);
926 constraint->contype = CONSTR_DEFAULT;
927 constraint->raw_expr = (Node *) funccallnode;
928 constraint->cooked_expr = NULL;
929 constraint->keys = NIL;
930 column->constraints = lappend(column->constraints, constraint);
932 constraint = makeNode(Constraint);
933 constraint->contype = CONSTR_NOTNULL;
934 column->constraints = lappend(column->constraints, constraint);
937 /* Process column constraints, if any... */
938 transformConstraintAttrs(column->constraints);
940 saw_nullable = false;
942 foreach(clist, column->constraints)
944 constraint = lfirst(clist);
947 * If this column constraint is a FOREIGN KEY constraint, then we fill
948 * in the current attribute's name and throw it into the list of FK
949 * constraints to be processed later.
951 if (IsA(constraint, FkConstraint))
953 FkConstraint *fkconstraint = (FkConstraint *) constraint;
955 fkconstraint->fk_attrs = list_make1(makeString(column->colname));
956 cxt->fkconstraints = lappend(cxt->fkconstraints, fkconstraint);
960 Assert(IsA(constraint, Constraint));
962 switch (constraint->contype)
965 if (saw_nullable && column->is_not_null)
967 (errcode(ERRCODE_SYNTAX_ERROR),
968 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
969 column->colname, cxt->relation->relname)));
970 column->is_not_null = FALSE;
975 if (saw_nullable && !column->is_not_null)
977 (errcode(ERRCODE_SYNTAX_ERROR),
978 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
979 column->colname, cxt->relation->relname)));
980 column->is_not_null = TRUE;
985 if (column->raw_default != NULL)
987 (errcode(ERRCODE_SYNTAX_ERROR),
988 errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
989 column->colname, cxt->relation->relname)));
990 column->raw_default = constraint->raw_expr;
991 Assert(constraint->cooked_expr == NULL);
996 if (constraint->keys == NIL)
997 constraint->keys = list_make1(makeString(column->colname));
998 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
1002 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
1005 case CONSTR_ATTR_DEFERRABLE:
1006 case CONSTR_ATTR_NOT_DEFERRABLE:
1007 case CONSTR_ATTR_DEFERRED:
1008 case CONSTR_ATTR_IMMEDIATE:
1009 /* transformConstraintAttrs took care of these */
1013 elog(ERROR, "unrecognized constraint type: %d",
1014 constraint->contype);
1021 transformTableConstraint(ParseState *pstate, CreateStmtContext *cxt,
1022 Constraint *constraint)
1024 switch (constraint->contype)
1026 case CONSTR_PRIMARY:
1028 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
1032 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
1036 case CONSTR_NOTNULL:
1037 case CONSTR_DEFAULT:
1038 case CONSTR_ATTR_DEFERRABLE:
1039 case CONSTR_ATTR_NOT_DEFERRABLE:
1040 case CONSTR_ATTR_DEFERRED:
1041 case CONSTR_ATTR_IMMEDIATE:
1042 elog(ERROR, "invalid context for constraint type %d",
1043 constraint->contype);
1047 elog(ERROR, "unrecognized constraint type: %d",
1048 constraint->contype);
1054 * transformInhRelation
1056 * Change the LIKE <subtable> portion of a CREATE TABLE statement into the
1057 * column definitions which recreate the user defined column portions of <subtable>.
1060 transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
1061 InhRelation *inhRelation)
1063 AttrNumber parent_attno;
1066 TupleDesc tupleDesc;
1067 TupleConstr *constr;
1068 AclResult aclresult;
1070 relation = heap_openrv(inhRelation->relation, AccessShareLock);
1072 if (relation->rd_rel->relkind != RELKIND_RELATION)
1074 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1075 errmsg("inherited relation \"%s\" is not a table",
1076 inhRelation->relation->relname)));
1079 * Check for SELECT privilages
1081 aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
1083 if (aclresult != ACLCHECK_OK)
1084 aclcheck_error(aclresult, ACL_KIND_CLASS,
1085 RelationGetRelationName(relation));
1087 tupleDesc = RelationGetDescr(relation);
1088 constr = tupleDesc->constr;
1091 * Insert the inherited attributes into the cxt for the new table
1094 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1097 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
1098 char *attributeName = NameStr(attribute->attname);
1103 * Ignore dropped columns in the parent.
1105 if (attribute->attisdropped)
1109 * Create a new inherited column.
1111 * For constraints, ONLY the NOT NULL constraint is inherited by the
1112 * new column definition per SQL99.
1114 def = makeNode(ColumnDef);
1115 def->colname = pstrdup(attributeName);
1116 typename = makeNode(TypeName);
1117 typename->typeid = attribute->atttypid;
1118 typename->typmod = attribute->atttypmod;
1119 def->typename = typename;
1121 def->is_local = false;
1122 def->is_not_null = attribute->attnotnull;
1123 def->raw_default = NULL;
1124 def->cooked_default = NULL;
1125 def->constraints = NIL;
1126 def->support = NULL;
1129 * Add to column list
1131 cxt->columns = lappend(cxt->columns, def);
1134 * Copy default if any, and the default has been requested
1136 if (attribute->atthasdef && inhRelation->including_defaults)
1138 char *this_default = NULL;
1139 AttrDefault *attrdef;
1142 /* Find default in constraint structure */
1143 Assert(constr != NULL);
1144 attrdef = constr->defval;
1145 for (i = 0; i < constr->num_defval; i++)
1147 if (attrdef[i].adnum == parent_attno)
1149 this_default = attrdef[i].adbin;
1153 Assert(this_default != NULL);
1156 * If default expr could contain any vars, we'd need to fix 'em,
1157 * but it can't; so default is ready to apply to child.
1160 def->cooked_default = pstrdup(this_default);
1165 * Close the parent rel, but keep our AccessShareLock on it until xact
1166 * commit. That will prevent someone else from deleting or ALTERing the
1167 * parent before the child is committed.
1169 heap_close(relation, NoLock);
1173 transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
1176 List *indexlist = NIL;
1181 * Run through the constraints that need to generate an index. For PRIMARY
1182 * KEY, mark each column as NOT NULL and create an index. For UNIQUE,
1183 * create an index as for PRIMARY KEY, but do not insist on NOT NULL.
1185 foreach(listptr, cxt->ixconstraints)
1187 Constraint *constraint = lfirst(listptr);
1191 Assert(IsA(constraint, Constraint));
1192 Assert((constraint->contype == CONSTR_PRIMARY)
1193 || (constraint->contype == CONSTR_UNIQUE));
1195 index = makeNode(IndexStmt);
1197 index->unique = true;
1198 index->primary = (constraint->contype == CONSTR_PRIMARY);
1201 if (cxt->pkey != NULL)
1203 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1204 errmsg("multiple primary keys for table \"%s\" are not allowed",
1205 cxt->relation->relname)));
1209 * In ALTER TABLE case, a primary index might already exist, but
1210 * DefineIndex will check for it.
1213 index->isconstraint = true;
1215 if (constraint->name != NULL)
1216 index->idxname = pstrdup(constraint->name);
1218 index->idxname = NULL; /* DefineIndex will choose name */
1220 index->relation = cxt->relation;
1221 index->accessMethod = DEFAULT_INDEX_TYPE;
1222 index->tableSpace = constraint->indexspace;
1223 index->indexParams = NIL;
1224 index->whereClause = NULL;
1227 * Make sure referenced keys exist. If we are making a PRIMARY KEY
1228 * index, also make sure they are NOT NULL, if possible. (Although we
1229 * could leave it to DefineIndex to mark the columns NOT NULL, it's
1230 * more efficient to get it right the first time.)
1232 foreach(keys, constraint->keys)
1234 char *key = strVal(lfirst(keys));
1236 ColumnDef *column = NULL;
1239 foreach(columns, cxt->columns)
1241 column = (ColumnDef *) lfirst(columns);
1242 Assert(IsA(column, ColumnDef));
1243 if (strcmp(column->colname, key) == 0)
1251 /* found column in the new table; force it to be NOT NULL */
1252 if (constraint->contype == CONSTR_PRIMARY)
1253 column->is_not_null = TRUE;
1255 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1258 * column will be a system column in the new table, so accept
1259 * it. System columns can't ever be null, so no need to worry
1260 * about PRIMARY/NOT NULL constraint.
1264 else if (cxt->inhRelations)
1266 /* try inherited tables */
1269 foreach(inher, cxt->inhRelations)
1271 RangeVar *inh = (RangeVar *) lfirst(inher);
1275 Assert(IsA(inh, RangeVar));
1276 rel = heap_openrv(inh, AccessShareLock);
1277 if (rel->rd_rel->relkind != RELKIND_RELATION)
1279 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1280 errmsg("inherited relation \"%s\" is not a table",
1282 for (count = 0; count < rel->rd_att->natts; count++)
1284 Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1285 char *inhname = NameStr(inhattr->attname);
1287 if (inhattr->attisdropped)
1289 if (strcmp(key, inhname) == 0)
1294 * We currently have no easy way to force an
1295 * inherited column to be NOT NULL at creation, if
1296 * its parent wasn't so already. We leave it to
1297 * DefineIndex to fix things up in this case.
1302 heap_close(rel, NoLock);
1309 * In the ALTER TABLE case, don't complain about index keys not
1310 * created in the command; they may well exist already.
1311 * DefineIndex will complain about them if not, and will also take
1312 * care of marking them NOT NULL.
1314 if (!found && !cxt->isalter)
1316 (errcode(ERRCODE_UNDEFINED_COLUMN),
1317 errmsg("column \"%s\" named in key does not exist",
1320 /* Check for PRIMARY KEY(foo, foo) */
1321 foreach(columns, index->indexParams)
1323 iparam = (IndexElem *) lfirst(columns);
1324 if (iparam->name && strcmp(key, iparam->name) == 0)
1328 (errcode(ERRCODE_DUPLICATE_COLUMN),
1329 errmsg("column \"%s\" appears twice in primary key constraint",
1333 (errcode(ERRCODE_DUPLICATE_COLUMN),
1334 errmsg("column \"%s\" appears twice in unique constraint",
1339 /* OK, add it to the index definition */
1340 iparam = makeNode(IndexElem);
1341 iparam->name = pstrdup(key);
1342 iparam->expr = NULL;
1343 iparam->opclass = NIL;
1344 index->indexParams = lappend(index->indexParams, iparam);
1347 indexlist = lappend(indexlist, index);
1351 * Scan the index list and remove any redundant index specifications. This
1352 * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
1353 * strict reading of SQL92 would suggest raising an error instead, but
1354 * that strikes me as too anal-retentive. - tgl 2001-02-14
1356 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1357 * pre-existing indexes, too.
1360 if (cxt->pkey != NULL)
1362 /* Make sure we keep the PKEY index in preference to others... */
1363 cxt->alist = list_make1(cxt->pkey);
1366 foreach(l, indexlist)
1373 /* if it's pkey, it's already in cxt->alist */
1374 if (index == cxt->pkey)
1377 foreach(k, cxt->alist)
1379 IndexStmt *priorindex = lfirst(k);
1381 if (equal(index->indexParams, priorindex->indexParams))
1384 * If the prior index is as yet unnamed, and this one is
1385 * named, then transfer the name to the prior index. This
1386 * ensures that if we have named and unnamed constraints,
1387 * we'll use (at least one of) the names for the index.
1389 if (priorindex->idxname == NULL)
1390 priorindex->idxname = index->idxname;
1397 cxt->alist = lappend(cxt->alist, index);
1402 transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
1403 bool skipValidation, bool isAddConstraint)
1407 if (cxt->fkconstraints == NIL)
1411 * If CREATE TABLE or adding a column with NULL default, we can safely
1412 * skip validation of the constraint.
1416 foreach(fkclist, cxt->fkconstraints)
1418 FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1420 fkconstraint->skip_validation = true;
1425 * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
1426 * CONSTRAINT command to execute after the basic command is complete. (If
1427 * called from ADD CONSTRAINT, that routine will add the FK constraints to
1428 * its own subcommand list.)
1430 * Note: the ADD CONSTRAINT command must also execute after any index
1431 * creation commands. Thus, this should run after
1432 * transformIndexConstraints, so that the CREATE INDEX commands are
1433 * already in cxt->alist.
1435 if (!isAddConstraint)
1437 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1439 alterstmt->relation = cxt->relation;
1440 alterstmt->cmds = NIL;
1441 alterstmt->relkind = OBJECT_TABLE;
1443 foreach(fkclist, cxt->fkconstraints)
1445 FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1446 AlterTableCmd *altercmd = makeNode(AlterTableCmd);
1448 altercmd->subtype = AT_ProcessedConstraint;
1449 altercmd->name = NULL;
1450 altercmd->def = (Node *) fkconstraint;
1451 alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
1454 cxt->alist = lappend(cxt->alist, alterstmt);
1459 * transformIndexStmt -
1460 * transforms the qualification of the index statement
1463 transformIndexStmt(ParseState *pstate, IndexStmt *stmt)
1466 RangeTblEntry *rte = NULL;
1469 qry = makeNode(Query);
1470 qry->commandType = CMD_UTILITY;
1472 /* take care of the where clause */
1473 if (stmt->whereClause)
1476 * Put the parent table into the rtable so that the WHERE clause can
1477 * refer to its fields without qualification. Note that this only
1478 * works if the parent table already exists --- so we can't easily
1479 * support predicates on indexes created implicitly by CREATE TABLE.
1480 * Fortunately, that's not necessary.
1482 rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1484 /* no to join list, yes to namespaces */
1485 addRTEtoQuery(pstate, rte, false, true, true);
1487 stmt->whereClause = transformWhereClause(pstate, stmt->whereClause,
1491 /* take care of any index expressions */
1492 foreach(l, stmt->indexParams)
1494 IndexElem *ielem = (IndexElem *) lfirst(l);
1498 /* Set up rtable as for predicate, see notes above */
1501 rte = addRangeTableEntry(pstate, stmt->relation, NULL,
1503 /* no to join list, yes to namespaces */
1504 addRTEtoQuery(pstate, rte, false, true, true);
1506 ielem->expr = transformExpr(pstate, ielem->expr);
1509 * We check only that the result type is legitimate; this is for
1510 * consistency with what transformWhereClause() checks for the
1511 * predicate. DefineIndex() will make more checks.
1513 if (expression_returns_set(ielem->expr))
1515 (errcode(ERRCODE_DATATYPE_MISMATCH),
1516 errmsg("index expression may not return a set")));
1520 qry->hasSubLinks = pstate->p_hasSubLinks;
1521 stmt->rangetable = pstate->p_rtable;
1523 qry->utilityStmt = (Node *) stmt;
1529 * transformRuleStmt -
1530 * transform a Create Rule Statement. The actions is a list of parse
1531 * trees which is transformed into a list of query trees.
1534 transformRuleStmt(ParseState *pstate, RuleStmt *stmt,
1535 List **extras_before, List **extras_after)
1539 RangeTblEntry *oldrte;
1540 RangeTblEntry *newrte;
1542 qry = makeNode(Query);
1543 qry->commandType = CMD_UTILITY;
1544 qry->utilityStmt = (Node *) stmt;
1547 * To avoid deadlock, make sure the first thing we do is grab
1548 * AccessExclusiveLock on the target relation. This will be needed by
1549 * DefineQueryRewrite(), and we don't want to grab a lesser lock
1552 rel = heap_openrv(stmt->relation, AccessExclusiveLock);
1555 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
1556 * Set up their RTEs in the main pstate for use in parsing the rule
1559 Assert(pstate->p_rtable == NIL);
1560 oldrte = addRangeTableEntryForRelation(pstate, rel,
1561 makeAlias("*OLD*", NIL),
1563 newrte = addRangeTableEntryForRelation(pstate, rel,
1564 makeAlias("*NEW*", NIL),
1566 /* Must override addRangeTableEntry's default access-check flags */
1567 oldrte->requiredPerms = 0;
1568 newrte->requiredPerms = 0;
1571 * They must be in the namespace too for lookup purposes, but only add the
1572 * one(s) that are relevant for the current kind of rule. In an UPDATE
1573 * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
1574 * there's no need to be so picky for INSERT & DELETE. We do not add them
1577 switch (stmt->event)
1580 addRTEtoQuery(pstate, oldrte, false, true, true);
1583 addRTEtoQuery(pstate, oldrte, false, true, true);
1584 addRTEtoQuery(pstate, newrte, false, true, true);
1587 addRTEtoQuery(pstate, newrte, false, true, true);
1590 addRTEtoQuery(pstate, oldrte, false, true, true);
1593 elog(ERROR, "unrecognized event type: %d",
1598 /* take care of the where clause */
1599 stmt->whereClause = transformWhereClause(pstate, stmt->whereClause,
1602 if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
1604 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1605 errmsg("rule WHERE condition may not contain references to other relations")));
1607 /* aggregates not allowed (but subselects are okay) */
1608 if (pstate->p_hasAggs)
1610 (errcode(ERRCODE_GROUPING_ERROR),
1611 errmsg("rule WHERE condition may not contain aggregate functions")));
1613 /* save info about sublinks in where clause */
1614 qry->hasSubLinks = pstate->p_hasSubLinks;
1617 * 'instead nothing' rules with a qualification need a query rangetable so
1618 * the rewrite handler can add the negated rule qualification to the
1619 * original query. We create a query with the new command type CMD_NOTHING
1620 * here that is treated specially by the rewrite system.
1622 if (stmt->actions == NIL)
1624 Query *nothing_qry = makeNode(Query);
1626 nothing_qry->commandType = CMD_NOTHING;
1627 nothing_qry->rtable = pstate->p_rtable;
1628 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
1630 stmt->actions = list_make1(nothing_qry);
1635 List *newactions = NIL;
1638 * transform each statement, like parse_sub_analyze()
1640 foreach(l, stmt->actions)
1642 Node *action = (Node *) lfirst(l);
1643 ParseState *sub_pstate = make_parsestate(pstate->parentParseState);
1650 * Set up OLD/NEW in the rtable for this statement. The entries
1651 * are added only to relnamespace, not varnamespace, because we
1652 * don't want them to be referred to by unqualified field names
1653 * nor "*" in the rule actions. We decide later whether to put
1654 * them in the joinlist.
1656 oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
1657 makeAlias("*OLD*", NIL),
1659 newrte = addRangeTableEntryForRelation(sub_pstate, rel,
1660 makeAlias("*NEW*", NIL),
1662 oldrte->requiredPerms = 0;
1663 newrte->requiredPerms = 0;
1664 addRTEtoQuery(sub_pstate, oldrte, false, true, false);
1665 addRTEtoQuery(sub_pstate, newrte, false, true, false);
1667 /* Transform the rule action statement */
1668 top_subqry = transformStmt(sub_pstate, action,
1669 extras_before, extras_after);
1672 * We cannot support utility-statement actions (eg NOTIFY) with
1673 * nonempty rule WHERE conditions, because there's no way to make
1674 * the utility action execute conditionally.
1676 if (top_subqry->commandType == CMD_UTILITY &&
1677 stmt->whereClause != NULL)
1679 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1680 errmsg("rules with WHERE conditions may only have SELECT, INSERT, UPDATE, or DELETE actions")));
1683 * If the action is INSERT...SELECT, OLD/NEW have been pushed down
1684 * into the SELECT, and that's what we need to look at. (Ugly
1685 * kluge ... try to fix this when we redesign querytrees.)
1687 sub_qry = getInsertSelectQuery(top_subqry, NULL);
1690 * If the sub_qry is a setop, we cannot attach any qualifications
1691 * to it, because the planner won't notice them. This could
1692 * perhaps be relaxed someday, but for now, we may as well reject
1693 * such a rule immediately.
1695 if (sub_qry->setOperations != NULL && stmt->whereClause != NULL)
1697 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1698 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1701 * Validate action's use of OLD/NEW, qual too
1704 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
1705 rangeTableEntry_used(stmt->whereClause, PRS2_OLD_VARNO, 0);
1707 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
1708 rangeTableEntry_used(stmt->whereClause, PRS2_NEW_VARNO, 0);
1710 switch (stmt->event)
1715 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1716 errmsg("ON SELECT rule may not use OLD")));
1719 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1720 errmsg("ON SELECT rule may not use NEW")));
1728 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1729 errmsg("ON INSERT rule may not use OLD")));
1734 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1735 errmsg("ON DELETE rule may not use NEW")));
1738 elog(ERROR, "unrecognized event type: %d",
1744 * For efficiency's sake, add OLD to the rule action's jointree
1745 * only if it was actually referenced in the statement or qual.
1747 * For INSERT, NEW is not really a relation (only a reference to
1748 * the to-be-inserted tuple) and should never be added to the
1751 * For UPDATE, we treat NEW as being another kind of reference to
1752 * OLD, because it represents references to *transformed* tuples
1753 * of the existing relation. It would be wrong to enter NEW
1754 * separately in the jointree, since that would cause a double
1755 * join of the updated relation. It's also wrong to fail to make
1756 * a jointree entry if only NEW and not OLD is mentioned.
1758 if (has_old || (has_new && stmt->event == CMD_UPDATE))
1761 * If sub_qry is a setop, manipulating its jointree will do no
1762 * good at all, because the jointree is dummy. (This should be
1763 * a can't-happen case because of prior tests.)
1765 if (sub_qry->setOperations != NULL)
1767 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1768 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1769 /* hack so we can use addRTEtoQuery() */
1770 sub_pstate->p_rtable = sub_qry->rtable;
1771 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
1772 addRTEtoQuery(sub_pstate, oldrte, true, false, false);
1773 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
1776 newactions = lappend(newactions, top_subqry);
1778 release_pstate_resources(sub_pstate);
1782 stmt->actions = newactions;
1785 /* Close relation, but keep the exclusive lock */
1786 heap_close(rel, NoLock);
1793 * transformSelectStmt -
1794 * transforms a Select Statement
1796 * Note: this is also used for DECLARE CURSOR statements.
1799 transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
1801 Query *qry = makeNode(Query);
1804 qry->commandType = CMD_SELECT;
1806 /* make FOR UPDATE/FOR SHARE info available to addRangeTableEntry */
1807 pstate->p_locking_clause = stmt->lockingClause;
1809 /* process the FROM clause */
1810 transformFromClause(pstate, stmt->fromClause);
1812 /* transform targetlist */
1813 qry->targetList = transformTargetList(pstate, stmt->targetList);
1815 /* handle any SELECT INTO/CREATE TABLE AS spec */
1816 qry->into = stmt->into;
1817 if (stmt->intoColNames)
1818 applyColumnNames(qry->targetList, stmt->intoColNames);
1820 qry->intoHasOids = interpretOidsOption(stmt->intoHasOids);
1822 /* mark column origins */
1823 markTargetListOrigins(pstate, qry->targetList);
1825 /* transform WHERE */
1826 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
1829 * Initial processing of HAVING clause is just like WHERE clause.
1831 qry->havingQual = transformWhereClause(pstate, stmt->havingClause,
1835 * Transform sorting/grouping stuff. Do ORDER BY first because both
1836 * transformGroupClause and transformDistinctClause need the results.
1838 qry->sortClause = transformSortClause(pstate,
1841 true /* fix unknowns */ );
1843 qry->groupClause = transformGroupClause(pstate,
1848 qry->distinctClause = transformDistinctClause(pstate,
1849 stmt->distinctClause,
1853 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
1855 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
1858 qry->rtable = pstate->p_rtable;
1859 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
1861 qry->hasSubLinks = pstate->p_hasSubLinks;
1862 qry->hasAggs = pstate->p_hasAggs;
1863 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
1864 parseCheckAggregates(pstate, qry);
1866 if (stmt->lockingClause)
1867 transformLockingClause(qry, stmt->lockingClause);
1873 * transformSetOperationsStmt -
1874 * transforms a set-operations tree
1876 * A set-operation tree is just a SELECT, but with UNION/INTERSECT/EXCEPT
1877 * structure to it. We must transform each leaf SELECT and build up a top-
1878 * level Query that contains the leaf SELECTs as subqueries in its rangetable.
1879 * The tree of set operations is converted into the setOperations field of
1880 * the top-level Query.
1883 transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
1885 Query *qry = makeNode(Query);
1886 SelectStmt *leftmostSelect;
1888 Query *leftmostQuery;
1889 SetOperationStmt *sostmt;
1895 LockingClause *lockingClause;
1897 ListCell *left_tlist,
1904 RangeTblEntry *jrte;
1907 qry->commandType = CMD_SELECT;
1910 * Find leftmost leaf SelectStmt; extract the one-time-only items from it
1911 * and from the top-level node.
1913 leftmostSelect = stmt->larg;
1914 while (leftmostSelect && leftmostSelect->op != SETOP_NONE)
1915 leftmostSelect = leftmostSelect->larg;
1916 Assert(leftmostSelect && IsA(leftmostSelect, SelectStmt) &&
1917 leftmostSelect->larg == NULL);
1918 into = leftmostSelect->into;
1919 intoColNames = leftmostSelect->intoColNames;
1921 /* clear them to prevent complaints in transformSetOperationTree() */
1922 leftmostSelect->into = NULL;
1923 leftmostSelect->intoColNames = NIL;
1926 * These are not one-time, exactly, but we want to process them here and
1927 * not let transformSetOperationTree() see them --- else it'll just
1928 * recurse right back here!
1930 sortClause = stmt->sortClause;
1931 limitOffset = stmt->limitOffset;
1932 limitCount = stmt->limitCount;
1933 lockingClause = stmt->lockingClause;
1935 stmt->sortClause = NIL;
1936 stmt->limitOffset = NULL;
1937 stmt->limitCount = NULL;
1938 stmt->lockingClause = NULL;
1940 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
1943 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1944 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
1947 * Recursively transform the components of the tree.
1949 sostmt = (SetOperationStmt *) transformSetOperationTree(pstate, stmt);
1950 Assert(sostmt && IsA(sostmt, SetOperationStmt));
1951 qry->setOperations = (Node *) sostmt;
1954 * Re-find leftmost SELECT (now it's a sub-query in rangetable)
1956 node = sostmt->larg;
1957 while (node && IsA(node, SetOperationStmt))
1958 node = ((SetOperationStmt *) node)->larg;
1959 Assert(node && IsA(node, RangeTblRef));
1960 leftmostRTI = ((RangeTblRef *) node)->rtindex;
1961 leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
1962 Assert(leftmostQuery != NULL);
1965 * Generate dummy targetlist for outer query using column names of
1966 * leftmost select and common datatypes of topmost set operation. Also
1967 * make lists of the dummy vars and their names for use in parsing ORDER
1970 * Note: we use leftmostRTI as the varno of the dummy variables. It
1971 * shouldn't matter too much which RT index they have, as long as they
1972 * have one that corresponds to a real RT entry; else funny things may
1973 * happen when the tree is mashed by rule rewriting.
1975 qry->targetList = NIL;
1978 left_tlist = list_head(leftmostQuery->targetList);
1980 foreach(dtlist, sostmt->colTypes)
1982 Oid colType = lfirst_oid(dtlist);
1983 TargetEntry *lefttle = (TargetEntry *) lfirst(left_tlist);
1988 Assert(!lefttle->resjunk);
1989 colName = pstrdup(lefttle->resname);
1990 expr = (Expr *) makeVar(leftmostRTI,
1995 tle = makeTargetEntry(expr,
1996 (AttrNumber) pstate->p_next_resno++,
1999 qry->targetList = lappend(qry->targetList, tle);
2000 targetvars = lappend(targetvars, expr);
2001 targetnames = lappend(targetnames, makeString(colName));
2002 left_tlist = lnext(left_tlist);
2006 * Handle SELECT INTO/CREATE TABLE AS.
2008 * Any column names from CREATE TABLE AS need to be attached to both the
2009 * top level and the leftmost subquery. We do not do this earlier because
2010 * we do *not* want the targetnames list to be affected.
2015 applyColumnNames(qry->targetList, intoColNames);
2016 applyColumnNames(leftmostQuery->targetList, intoColNames);
2020 * As a first step towards supporting sort clauses that are expressions
2021 * using the output columns, generate a varnamespace entry that makes the
2022 * output columns visible. A Join RTE node is handy for this, since we
2023 * can easily control the Vars generated upon matches.
2025 * Note: we don't yet do anything useful with such cases, but at least
2026 * "ORDER BY upper(foo)" will draw the right error message rather than
2029 jrte = addRangeTableEntryForJoin(NULL,
2036 sv_rtable = pstate->p_rtable;
2037 pstate->p_rtable = list_make1(jrte);
2039 sv_relnamespace = pstate->p_relnamespace;
2040 pstate->p_relnamespace = NIL; /* no qualified names allowed */
2042 sv_varnamespace = pstate->p_varnamespace;
2043 pstate->p_varnamespace = list_make1(jrte);
2046 * For now, we don't support resjunk sort clauses on the output of a
2047 * setOperation tree --- you can only use the SQL92-spec options of
2048 * selecting an output column by name or number. Enforce by checking that
2049 * transformSortClause doesn't add any items to tlist.
2051 tllen = list_length(qry->targetList);
2053 qry->sortClause = transformSortClause(pstate,
2056 false /* no unknowns expected */ );
2058 pstate->p_rtable = sv_rtable;
2059 pstate->p_relnamespace = sv_relnamespace;
2060 pstate->p_varnamespace = sv_varnamespace;
2062 if (tllen != list_length(qry->targetList))
2064 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2065 errmsg("ORDER BY on a UNION/INTERSECT/EXCEPT result must be on one of the result columns")));
2067 qry->limitOffset = transformLimitClause(pstate, limitOffset,
2069 qry->limitCount = transformLimitClause(pstate, limitCount,
2072 qry->rtable = pstate->p_rtable;
2073 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
2075 qry->hasSubLinks = pstate->p_hasSubLinks;
2076 qry->hasAggs = pstate->p_hasAggs;
2077 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
2078 parseCheckAggregates(pstate, qry);
2081 transformLockingClause(qry, lockingClause);
2087 * transformSetOperationTree
2088 * Recursively transform leaves and internal nodes of a set-op tree
2091 transformSetOperationTree(ParseState *pstate, SelectStmt *stmt)
2095 Assert(stmt && IsA(stmt, SelectStmt));
2098 * Validity-check both leaf and internal SELECTs for disallowed ops.
2102 (errcode(ERRCODE_SYNTAX_ERROR),
2103 errmsg("INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT")));
2104 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
2105 if (stmt->lockingClause)
2107 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2108 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
2111 * If an internal node of a set-op tree has ORDER BY, UPDATE, or LIMIT
2112 * clauses attached, we need to treat it like a leaf node to generate an
2113 * independent sub-Query tree. Otherwise, it can be represented by a
2114 * SetOperationStmt node underneath the parent Query.
2116 if (stmt->op == SETOP_NONE)
2118 Assert(stmt->larg == NULL && stmt->rarg == NULL);
2123 Assert(stmt->larg != NULL && stmt->rarg != NULL);
2124 if (stmt->sortClause || stmt->limitOffset || stmt->limitCount ||
2125 stmt->lockingClause)
2133 /* Process leaf SELECT */
2136 char selectName[32];
2141 * Transform SelectStmt into a Query.
2143 * Note: previously transformed sub-queries don't affect the parsing
2144 * of this sub-query, because they are not in the toplevel pstate's
2147 selectList = parse_sub_analyze((Node *) stmt, pstate);
2149 Assert(list_length(selectList) == 1);
2150 selectQuery = (Query *) linitial(selectList);
2151 Assert(IsA(selectQuery, Query));
2154 * Check for bogus references to Vars on the current query level (but
2155 * upper-level references are okay). Normally this can't happen
2156 * because the namespace will be empty, but it could happen if we are
2159 if (pstate->p_relnamespace || pstate->p_varnamespace)
2161 if (contain_vars_of_level((Node *) selectQuery, 1))
2163 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2164 errmsg("UNION/INTERSECT/EXCEPT member statement may not refer to other relations of same query level")));
2168 * Make the leaf query be a subquery in the top-level rangetable.
2170 snprintf(selectName, sizeof(selectName), "*SELECT* %d",
2171 list_length(pstate->p_rtable) + 1);
2172 rte = addRangeTableEntryForSubquery(pstate,
2174 makeAlias(selectName, NIL),
2178 * Return a RangeTblRef to replace the SelectStmt in the set-op tree.
2180 rtr = makeNode(RangeTblRef);
2181 /* assume new rte is at end */
2182 rtr->rtindex = list_length(pstate->p_rtable);
2183 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
2184 return (Node *) rtr;
2188 /* Process an internal node (set operation node) */
2189 SetOperationStmt *op = makeNode(SetOperationStmt);
2194 const char *context;
2196 context = (stmt->op == SETOP_UNION ? "UNION" :
2197 (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
2201 op->all = stmt->all;
2204 * Recursively transform the child nodes.
2206 op->larg = transformSetOperationTree(pstate, stmt->larg);
2207 op->rarg = transformSetOperationTree(pstate, stmt->rarg);
2210 * Verify that the two children have the same number of non-junk
2211 * columns, and determine the types of the merged output columns.
2213 lcoltypes = getSetColTypes(pstate, op->larg);
2214 rcoltypes = getSetColTypes(pstate, op->rarg);
2215 if (list_length(lcoltypes) != list_length(rcoltypes))
2217 (errcode(ERRCODE_SYNTAX_ERROR),
2218 errmsg("each %s query must have the same number of columns",
2222 forboth(l, lcoltypes, r, rcoltypes)
2224 Oid lcoltype = lfirst_oid(l);
2225 Oid rcoltype = lfirst_oid(r);
2228 rescoltype = select_common_type(list_make2_oid(lcoltype, rcoltype),
2230 op->colTypes = lappend_oid(op->colTypes, rescoltype);
2239 * Get output column types of an (already transformed) set-op node
2242 getSetColTypes(ParseState *pstate, Node *node)
2244 if (IsA(node, RangeTblRef))
2246 RangeTblRef *rtr = (RangeTblRef *) node;
2247 RangeTblEntry *rte = rt_fetch(rtr->rtindex, pstate->p_rtable);
2248 Query *selectQuery = rte->subquery;
2252 Assert(selectQuery != NULL);
2253 /* Get types of non-junk columns */
2254 foreach(tl, selectQuery->targetList)
2256 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2260 result = lappend_oid(result, exprType((Node *) tle->expr));
2264 else if (IsA(node, SetOperationStmt))
2266 SetOperationStmt *op = (SetOperationStmt *) node;
2268 /* Result already computed during transformation of node */
2269 Assert(op->colTypes != NIL);
2270 return op->colTypes;
2274 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node));
2275 return NIL; /* keep compiler quiet */
2279 /* Attach column names from a ColumnDef list to a TargetEntry list */
2281 applyColumnNames(List *dst, List *src)
2286 if (list_length(src) > list_length(dst))
2288 (errcode(ERRCODE_SYNTAX_ERROR),
2289 errmsg("CREATE TABLE AS specifies too many column names")));
2291 forboth(dst_item, dst, src_item, src)
2293 TargetEntry *d = (TargetEntry *) lfirst(dst_item);
2294 ColumnDef *s = (ColumnDef *) lfirst(src_item);
2296 Assert(!d->resjunk);
2297 d->resname = pstrdup(s->colname);
2303 * transformUpdateStmt -
2304 * transforms an update statement
2307 transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
2309 Query *qry = makeNode(Query);
2311 ListCell *origTargetList;
2314 qry->commandType = CMD_UPDATE;
2315 pstate->p_is_update = true;
2317 qry->resultRelation = setTargetTable(pstate, stmt->relation,
2318 interpretInhOption(stmt->relation->inhOpt),
2323 * the FROM clause is non-standard SQL syntax. We used to be able to do
2324 * this with REPLACE in POSTQUEL so we keep the feature.
2326 transformFromClause(pstate, stmt->fromClause);
2328 qry->targetList = transformTargetList(pstate, stmt->targetList);
2330 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
2332 qry->rtable = pstate->p_rtable;
2333 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
2335 qry->hasSubLinks = pstate->p_hasSubLinks;
2336 qry->hasAggs = pstate->p_hasAggs;
2337 if (pstate->p_hasAggs)
2338 parseCheckAggregates(pstate, qry);
2341 * Now we are done with SELECT-like processing, and can get on with
2342 * transforming the target list to match the UPDATE target columns.
2345 /* Prepare to assign non-conflicting resnos to resjunk attributes */
2346 if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
2347 pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
2349 /* Prepare non-junk columns for assignment to target table */
2350 origTargetList = list_head(stmt->targetList);
2352 foreach(tl, qry->targetList)
2354 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2355 ResTarget *origTarget;
2360 * Resjunk nodes need no additional processing, but be sure they
2361 * have resnos that do not match any target columns; else rewriter
2362 * or planner might get confused. They don't need a resname
2365 tle->resno = (AttrNumber) pstate->p_next_resno++;
2366 tle->resname = NULL;
2369 if (origTargetList == NULL)
2370 elog(ERROR, "UPDATE target count mismatch --- internal error");
2371 origTarget = (ResTarget *) lfirst(origTargetList);
2372 Assert(IsA(origTarget, ResTarget));
2374 updateTargetListEntry(pstate, tle, origTarget->name,
2375 attnameAttNum(pstate->p_target_relation,
2376 origTarget->name, true),
2377 origTarget->indirection);
2379 origTargetList = lnext(origTargetList);
2381 if (origTargetList != NULL)
2382 elog(ERROR, "UPDATE target count mismatch --- internal error");
2388 * tranformAlterTableStmt -
2389 * transform an Alter Table Statement
2392 transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt,
2393 List **extras_before, List **extras_after)
2395 CreateStmtContext cxt;
2399 List *newcmds = NIL;
2400 bool skipValidation = true;
2401 AlterTableCmd *newcmd;
2403 cxt.stmtType = "ALTER TABLE";
2404 cxt.relation = stmt->relation;
2405 cxt.inhRelations = NIL;
2407 cxt.hasoids = false; /* need not be right */
2409 cxt.ckconstraints = NIL;
2410 cxt.fkconstraints = NIL;
2411 cxt.ixconstraints = NIL;
2417 * The only subtypes that currently require parse transformation handling
2418 * are ADD COLUMN and ADD CONSTRAINT. These largely re-use code from
2421 foreach(lcmd, stmt->cmds)
2423 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2425 switch (cmd->subtype)
2429 ColumnDef *def = (ColumnDef *) cmd->def;
2431 Assert(IsA(cmd->def, ColumnDef));
2432 transformColumnDefinition(pstate, &cxt,
2433 (ColumnDef *) cmd->def);
2436 * If the column has a non-null default, we can't skip
2437 * validation of foreign keys.
2439 if (((ColumnDef *) cmd->def)->raw_default != NULL)
2440 skipValidation = false;
2442 newcmds = lappend(newcmds, cmd);
2445 * Convert an ADD COLUMN ... NOT NULL constraint to a
2448 if (def->is_not_null)
2450 /* Remove NOT NULL from AddColumn */
2451 def->is_not_null = false;
2453 /* Add as a separate AlterTableCmd */
2454 newcmd = makeNode(AlterTableCmd);
2455 newcmd->subtype = AT_SetNotNull;
2456 newcmd->name = pstrdup(def->colname);
2457 newcmds = lappend(newcmds, newcmd);
2461 * All constraints are processed in other ways. Remove the
2464 def->constraints = NIL;
2468 case AT_AddConstraint:
2471 * The original AddConstraint cmd node doesn't go to newcmds
2474 if (IsA(cmd->def, Constraint))
2475 transformTableConstraint(pstate, &cxt,
2476 (Constraint *) cmd->def);
2477 else if (IsA(cmd->def, FkConstraint))
2479 cxt.fkconstraints = lappend(cxt.fkconstraints, cmd->def);
2480 skipValidation = false;
2483 elog(ERROR, "unrecognized node type: %d",
2484 (int) nodeTag(cmd->def));
2487 case AT_ProcessedConstraint:
2490 * Already-transformed ADD CONSTRAINT, so just make it look
2491 * like the standard case.
2493 cmd->subtype = AT_AddConstraint;
2494 newcmds = lappend(newcmds, cmd);
2498 newcmds = lappend(newcmds, cmd);
2503 /* Postprocess index and FK constraints */
2504 transformIndexConstraints(pstate, &cxt);
2506 transformFKConstraints(pstate, &cxt, skipValidation, true);
2509 * Push any index-creation commands into the ALTER, so that they can be
2510 * scheduled nicely by tablecmds.c.
2512 foreach(l, cxt.alist)
2514 Node *idxstmt = (Node *) lfirst(l);
2516 Assert(IsA(idxstmt, IndexStmt));
2517 newcmd = makeNode(AlterTableCmd);
2518 newcmd->subtype = AT_AddIndex;
2519 newcmd->def = idxstmt;
2520 newcmds = lappend(newcmds, newcmd);
2524 /* Append any CHECK or FK constraints to the commands list */
2525 foreach(l, cxt.ckconstraints)
2527 newcmd = makeNode(AlterTableCmd);
2528 newcmd->subtype = AT_AddConstraint;
2529 newcmd->def = (Node *) lfirst(l);
2530 newcmds = lappend(newcmds, newcmd);
2532 foreach(l, cxt.fkconstraints)
2534 newcmd = makeNode(AlterTableCmd);
2535 newcmd->subtype = AT_AddConstraint;
2536 newcmd->def = (Node *) lfirst(l);
2537 newcmds = lappend(newcmds, newcmd);
2540 /* Update statement's commands list */
2541 stmt->cmds = newcmds;
2543 qry = makeNode(Query);
2544 qry->commandType = CMD_UTILITY;
2545 qry->utilityStmt = (Node *) stmt;
2547 *extras_before = list_concat(*extras_before, cxt.blist);
2548 *extras_after = list_concat(cxt.alist, *extras_after);
2554 transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
2556 Query *result = makeNode(Query);
2557 List *extras_before = NIL,
2558 *extras_after = NIL;
2560 result->commandType = CMD_UTILITY;
2561 result->utilityStmt = (Node *) stmt;
2564 * Don't allow both SCROLL and NO SCROLL to be specified
2566 if ((stmt->options & CURSOR_OPT_SCROLL) &&
2567 (stmt->options & CURSOR_OPT_NO_SCROLL))
2569 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
2570 errmsg("cannot specify both SCROLL and NO SCROLL")));
2572 stmt->query = (Node *) transformStmt(pstate, stmt->query,
2573 &extras_before, &extras_after);
2575 /* Shouldn't get any extras, since grammar only allows SelectStmt */
2576 if (extras_before || extras_after)
2577 elog(ERROR, "unexpected extra stuff in cursor statement");
2584 transformPrepareStmt(ParseState *pstate, PrepareStmt *stmt)
2586 Query *result = makeNode(Query);
2587 List *argtype_oids = NIL; /* argtype OIDs in a list */
2588 Oid *argtoids = NULL; /* and as an array */
2592 result->commandType = CMD_UTILITY;
2593 result->utilityStmt = (Node *) stmt;
2595 /* Transform list of TypeNames to list (and array) of type OIDs */
2596 nargs = list_length(stmt->argtypes);
2603 argtoids = (Oid *) palloc(nargs * sizeof(Oid));
2605 foreach(l, stmt->argtypes)
2607 TypeName *tn = lfirst(l);
2608 Oid toid = typenameTypeId(tn);
2610 argtype_oids = lappend_oid(argtype_oids, toid);
2611 argtoids[i++] = toid;
2615 stmt->argtype_oids = argtype_oids;
2618 * Analyze the statement using these parameter types (any parameters
2619 * passed in from above us will not be visible to it).
2621 queries = parse_analyze((Node *) stmt->query, argtoids, nargs);
2624 * Shouldn't get any extra statements, since grammar only allows
2627 if (list_length(queries) != 1)
2628 elog(ERROR, "unexpected extra stuff in prepared statement");
2630 stmt->query = linitial(queries);
2636 transformExecuteStmt(ParseState *pstate, ExecuteStmt *stmt)
2638 Query *result = makeNode(Query);
2641 result->commandType = CMD_UTILITY;
2642 result->utilityStmt = (Node *) stmt;
2644 paramtypes = FetchPreparedStatementParams(stmt->name);
2646 if (stmt->params || paramtypes)
2648 int nparams = list_length(stmt->params);
2649 int nexpected = list_length(paramtypes);
2654 if (nparams != nexpected)
2656 (errcode(ERRCODE_SYNTAX_ERROR),
2657 errmsg("wrong number of parameters for prepared statement \"%s\"",
2659 errdetail("Expected %d parameters but got %d.",
2660 nexpected, nparams)));
2662 forboth(l, stmt->params, l2, paramtypes)
2664 Node *expr = lfirst(l);
2665 Oid expected_type_id = lfirst_oid(l2);
2668 expr = transformExpr(pstate, expr);
2670 /* Cannot contain subselects or aggregates */
2671 if (pstate->p_hasSubLinks)
2673 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2674 errmsg("cannot use subquery in EXECUTE parameter")));
2675 if (pstate->p_hasAggs)
2677 (errcode(ERRCODE_GROUPING_ERROR),
2678 errmsg("cannot use aggregate function in EXECUTE parameter")));
2680 given_type_id = exprType(expr);
2682 expr = coerce_to_target_type(pstate, expr, given_type_id,
2683 expected_type_id, -1,
2684 COERCION_ASSIGNMENT,
2685 COERCE_IMPLICIT_CAST);
2689 (errcode(ERRCODE_DATATYPE_MISMATCH),
2690 errmsg("parameter $%d of type %s cannot be coerced to the expected type %s",
2692 format_type_be(given_type_id),
2693 format_type_be(expected_type_id)),
2694 errhint("You will need to rewrite or cast the expression.")));
2704 /* exported so planner can check again after rewriting, query pullup, etc */
2706 CheckSelectLocking(Query *qry, bool forUpdate)
2708 const char *operation;
2711 operation = "SELECT FOR UPDATE";
2713 operation = "SELECT FOR SHARE";
2715 if (qry->setOperations)
2717 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2718 /* translator: %s is a SQL command, like SELECT FOR UPDATE */
2719 errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT", operation)));
2720 if (qry->distinctClause != NIL)
2722 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2723 /* translator: %s is a SQL command, like SELECT FOR UPDATE */
2724 errmsg("%s is not allowed with DISTINCT clause", operation)));
2725 if (qry->groupClause != NIL)
2727 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2728 /* translator: %s is a SQL command, like SELECT FOR UPDATE */
2729 errmsg("%s is not allowed with GROUP BY clause", operation)));
2730 if (qry->havingQual != NULL)
2732 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2733 /* translator: %s is a SQL command, like SELECT FOR UPDATE */
2734 errmsg("%s is not allowed with HAVING clause", operation)));
2737 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2738 /* translator: %s is a SQL command, like SELECT FOR UPDATE */
2739 errmsg("%s is not allowed with aggregate functions", operation)));
2743 * Convert FOR UPDATE/SHARE name list into rowMarks list of integer relids
2745 * NB: if you need to change this, see also markQueryForLocking()
2746 * in rewriteHandler.c.
2749 transformLockingClause(Query *qry, LockingClause *lc)
2751 List *lockedRels = lc->lockedRels;
2756 LockingClause *allrels;
2760 if (lc->forUpdate != qry->forUpdate)
2762 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2763 errmsg("cannot use both FOR UPDATE and FOR SHARE in one query")));
2764 if (lc->nowait != qry->rowNoWait)
2766 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2767 errmsg("cannot use both wait and NOWAIT in one query")));
2769 qry->forUpdate = lc->forUpdate;
2770 qry->rowNoWait = lc->nowait;
2772 CheckSelectLocking(qry, lc->forUpdate);
2774 /* make a clause we can pass down to subqueries to select all rels */
2775 allrels = makeNode(LockingClause);
2776 allrels->lockedRels = NIL; /* indicates all rels */
2777 allrels->forUpdate = lc->forUpdate;
2778 allrels->nowait = lc->nowait;
2780 rowMarks = qry->rowMarks;
2782 if (lockedRels == NIL)
2784 /* all regular tables used in query */
2786 foreach(rt, qry->rtable)
2788 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2791 switch (rte->rtekind)
2794 /* use list_append_unique to avoid duplicates */
2795 rowMarks = list_append_unique_int(rowMarks, i);
2796 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
2801 * FOR UPDATE/SHARE of subquery is propagated to all of
2804 transformLockingClause(rte->subquery, allrels);
2807 /* ignore JOIN, SPECIAL, FUNCTION RTEs */
2814 /* just the named tables */
2815 foreach(l, lockedRels)
2817 char *relname = strVal(lfirst(l));
2820 foreach(rt, qry->rtable)
2822 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2825 if (strcmp(rte->eref->aliasname, relname) == 0)
2827 switch (rte->rtekind)
2830 /* use list_append_unique to avoid duplicates */
2831 rowMarks = list_append_unique_int(rowMarks, i);
2832 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
2837 * FOR UPDATE/SHARE of subquery is propagated to
2838 * all of subquery's rels
2840 transformLockingClause(rte->subquery, allrels);
2844 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2845 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a join")));
2849 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2850 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to NEW or OLD")));
2854 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2855 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a function")));
2858 elog(ERROR, "unrecognized RTE type: %d",
2859 (int) rte->rtekind);
2862 break; /* out of foreach loop */
2867 (errcode(ERRCODE_UNDEFINED_TABLE),
2868 errmsg("relation \"%s\" in FOR UPDATE/SHARE clause not found in FROM clause",
2873 qry->rowMarks = rowMarks;
2878 * Preprocess a list of column constraint clauses
2879 * to attach constraint attributes to their primary constraint nodes
2880 * and detect inconsistent/misplaced constraint attributes.
2882 * NOTE: currently, attributes are only supported for FOREIGN KEY primary
2883 * constraints, but someday they ought to be supported for other constraints.
2886 transformConstraintAttrs(List *constraintList)
2888 Node *lastprimarynode = NULL;
2889 bool saw_deferrability = false;
2890 bool saw_initially = false;
2893 foreach(clist, constraintList)
2895 Node *node = lfirst(clist);
2897 if (!IsA(node, Constraint))
2899 lastprimarynode = node;
2900 /* reset flags for new primary node */
2901 saw_deferrability = false;
2902 saw_initially = false;
2906 Constraint *con = (Constraint *) node;
2908 switch (con->contype)
2910 case CONSTR_ATTR_DEFERRABLE:
2911 if (lastprimarynode == NULL ||
2912 !IsA(lastprimarynode, FkConstraint))
2914 (errcode(ERRCODE_SYNTAX_ERROR),
2915 errmsg("misplaced DEFERRABLE clause")));
2916 if (saw_deferrability)
2918 (errcode(ERRCODE_SYNTAX_ERROR),
2919 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
2920 saw_deferrability = true;
2921 ((FkConstraint *) lastprimarynode)->deferrable = true;
2923 case CONSTR_ATTR_NOT_DEFERRABLE:
2924 if (lastprimarynode == NULL ||
2925 !IsA(lastprimarynode, FkConstraint))
2927 (errcode(ERRCODE_SYNTAX_ERROR),
2928 errmsg("misplaced NOT DEFERRABLE clause")));
2929 if (saw_deferrability)
2931 (errcode(ERRCODE_SYNTAX_ERROR),
2932 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
2933 saw_deferrability = true;
2934 ((FkConstraint *) lastprimarynode)->deferrable = false;
2935 if (saw_initially &&
2936 ((FkConstraint *) lastprimarynode)->initdeferred)
2938 (errcode(ERRCODE_SYNTAX_ERROR),
2939 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
2941 case CONSTR_ATTR_DEFERRED:
2942 if (lastprimarynode == NULL ||
2943 !IsA(lastprimarynode, FkConstraint))
2945 (errcode(ERRCODE_SYNTAX_ERROR),
2946 errmsg("misplaced INITIALLY DEFERRED clause")));
2949 (errcode(ERRCODE_SYNTAX_ERROR),
2950 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
2951 saw_initially = true;
2952 ((FkConstraint *) lastprimarynode)->initdeferred = true;
2955 * If only INITIALLY DEFERRED appears, assume DEFERRABLE
2957 if (!saw_deferrability)
2958 ((FkConstraint *) lastprimarynode)->deferrable = true;
2959 else if (!((FkConstraint *) lastprimarynode)->deferrable)
2961 (errcode(ERRCODE_SYNTAX_ERROR),
2962 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
2964 case CONSTR_ATTR_IMMEDIATE:
2965 if (lastprimarynode == NULL ||
2966 !IsA(lastprimarynode, FkConstraint))
2968 (errcode(ERRCODE_SYNTAX_ERROR),
2969 errmsg("misplaced INITIALLY IMMEDIATE clause")));
2972 (errcode(ERRCODE_SYNTAX_ERROR),
2973 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
2974 saw_initially = true;
2975 ((FkConstraint *) lastprimarynode)->initdeferred = false;
2978 /* Otherwise it's not an attribute */
2979 lastprimarynode = node;
2980 /* reset flags for new primary node */
2981 saw_deferrability = false;
2982 saw_initially = false;
2989 /* Build a FromExpr node */
2991 makeFromExpr(List *fromlist, Node *quals)
2993 FromExpr *f = makeNode(FromExpr);
2995 f->fromlist = fromlist;
3001 * Special handling of type definition for a column
3004 transformColumnType(ParseState *pstate, ColumnDef *column)
3007 * All we really need to do here is verify that the type is valid.
3009 Type ctype = typenameType(column->typename);
3011 ReleaseSysCache(ctype);
3015 setSchemaName(char *context_schema, char **stmt_schema_name)
3017 if (*stmt_schema_name == NULL)
3018 *stmt_schema_name = context_schema;
3019 else if (strcmp(context_schema, *stmt_schema_name) != 0)
3021 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
3022 errmsg("CREATE specifies a schema (%s) "
3023 "different from the one being created (%s)",
3024 *stmt_schema_name, context_schema)));
3028 * analyzeCreateSchemaStmt -
3029 * analyzes the "create schema" statement
3031 * Split the schema element list into individual commands and place
3032 * them in the result list in an order such that there are no forward
3033 * references (e.g. GRANT to a table created later in the list). Note
3034 * that the logic we use for determining forward references is
3035 * presently quite incomplete.
3037 * SQL92 also allows constraints to make forward references, so thumb through
3038 * the table columns and move forward references to a posterior alter-table
3041 * The result is a list of parse nodes that still need to be analyzed ---
3042 * but we can't analyze the later commands until we've executed the earlier
3043 * ones, because of possible inter-object references.
3045 * Note: Called from commands/schemacmds.c
3048 analyzeCreateSchemaStmt(CreateSchemaStmt *stmt)
3050 CreateSchemaStmtContext cxt;
3054 cxt.stmtType = "CREATE SCHEMA";
3055 cxt.schemaname = stmt->schemaname;
3056 cxt.authid = stmt->authid;
3057 cxt.sequences = NIL;
3063 cxt.fwconstraints = NIL;
3069 * Run through each schema element in the schema element list. Separate
3070 * statements by type, and do preliminary analysis.
3072 foreach(elements, stmt->schemaElts)
3074 Node *element = lfirst(elements);
3076 switch (nodeTag(element))
3078 case T_CreateSeqStmt:
3080 CreateSeqStmt *elp = (CreateSeqStmt *) element;
3082 setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
3083 cxt.sequences = lappend(cxt.sequences, element);
3089 CreateStmt *elp = (CreateStmt *) element;
3091 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3094 * XXX todo: deal with constraints
3096 cxt.tables = lappend(cxt.tables, element);
3102 ViewStmt *elp = (ViewStmt *) element;
3104 setSchemaName(cxt.schemaname, &elp->view->schemaname);
3107 * XXX todo: deal with references between views
3109 cxt.views = lappend(cxt.views, element);
3115 IndexStmt *elp = (IndexStmt *) element;
3117 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3118 cxt.indexes = lappend(cxt.indexes, element);
3122 case T_CreateTrigStmt:
3124 CreateTrigStmt *elp = (CreateTrigStmt *) element;
3126 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3127 cxt.triggers = lappend(cxt.triggers, element);
3132 cxt.grants = lappend(cxt.grants, element);
3136 elog(ERROR, "unrecognized node type: %d",
3137 (int) nodeTag(element));
3142 result = list_concat(result, cxt.sequences);
3143 result = list_concat(result, cxt.tables);
3144 result = list_concat(result, cxt.views);
3145 result = list_concat(result, cxt.indexes);
3146 result = list_concat(result, cxt.triggers);
3147 result = list_concat(result, cxt.grants);
3153 * Traverse a fully-analyzed tree to verify that parameter symbols
3154 * match their types. We need this because some Params might still
3155 * be UNKNOWN, if there wasn't anything to force their coercion,
3156 * and yet other instances seen later might have gotten coerced.
3159 check_parameter_resolution_walker(Node *node,
3160 check_parameter_resolution_context *context)
3164 if (IsA(node, Param))
3166 Param *param = (Param *) node;
3168 if (param->paramkind == PARAM_NUM)
3170 int paramno = param->paramid;
3172 if (paramno <= 0 || /* shouldn't happen, but... */
3173 paramno > context->numParams)
3175 (errcode(ERRCODE_UNDEFINED_PARAMETER),
3176 errmsg("there is no parameter $%d", paramno)));
3178 if (param->paramtype != context->paramTypes[paramno - 1])
3180 (errcode(ERRCODE_AMBIGUOUS_PARAMETER),
3181 errmsg("could not determine data type of parameter $%d",
3186 if (IsA(node, Query))
3188 /* Recurse into RTE subquery or not-yet-planned sublink subquery */
3189 return query_tree_walker((Query *) node,
3190 check_parameter_resolution_walker,
3191 (void *) context, 0);
3193 return expression_tree_walker(node, check_parameter_resolution_walker,