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.324 2005/08/01 20:31:09 tgl 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
64 List *alters; /* Generated ALTER items (from the above) */
65 List *ixconstraints; /* index-creating constraints */
66 List *blist; /* "before list" of things to do before
67 * creating the schema */
68 List *alist; /* "after list" of things to do after
69 * creating the schema */
70 } CreateSchemaStmtContext;
72 /* State shared by transformCreateStmt and its subroutines */
75 const char *stmtType; /* "CREATE TABLE" or "ALTER TABLE" */
76 RangeVar *relation; /* relation to create */
77 List *inhRelations; /* relations to inherit from */
78 bool hasoids; /* does relation have an OID column? */
79 bool isalter; /* true if altering existing table */
80 List *columns; /* ColumnDef items */
81 List *ckconstraints; /* CHECK constraints */
82 List *fkconstraints; /* FOREIGN KEY constraints */
83 List *ixconstraints; /* index-creating constraints */
84 List *blist; /* "before list" of things to do before
85 * creating the table */
86 List *alist; /* "after list" of things to do after
87 * creating the table */
88 IndexStmt *pkey; /* PRIMARY KEY index, if any */
95 } check_parameter_resolution_context;
98 static List *do_parse_analyze(Node *parseTree, ParseState *pstate);
99 static Query *transformStmt(ParseState *pstate, Node *stmt,
100 List **extras_before, List **extras_after);
101 static Query *transformViewStmt(ParseState *pstate, ViewStmt *stmt,
102 List **extras_before, List **extras_after);
103 static Query *transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt);
104 static Query *transformInsertStmt(ParseState *pstate, InsertStmt *stmt,
105 List **extras_before, List **extras_after);
106 static Query *transformIndexStmt(ParseState *pstate, IndexStmt *stmt);
107 static Query *transformRuleStmt(ParseState *query, RuleStmt *stmt,
108 List **extras_before, List **extras_after);
109 static Query *transformSelectStmt(ParseState *pstate, SelectStmt *stmt);
110 static Query *transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt);
111 static Node *transformSetOperationTree(ParseState *pstate, SelectStmt *stmt);
112 static Query *transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt);
113 static Query *transformDeclareCursorStmt(ParseState *pstate,
114 DeclareCursorStmt *stmt);
115 static Query *transformPrepareStmt(ParseState *pstate, PrepareStmt *stmt);
116 static Query *transformExecuteStmt(ParseState *pstate, ExecuteStmt *stmt);
117 static Query *transformCreateStmt(ParseState *pstate, CreateStmt *stmt,
118 List **extras_before, List **extras_after);
119 static Query *transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt,
120 List **extras_before, List **extras_after);
121 static void transformColumnDefinition(ParseState *pstate,
122 CreateStmtContext *cxt,
124 static void transformTableConstraint(ParseState *pstate,
125 CreateStmtContext *cxt,
126 Constraint *constraint);
127 static void transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
128 InhRelation *inhrelation);
129 static void transformIndexConstraints(ParseState *pstate,
130 CreateStmtContext *cxt);
131 static void transformFKConstraints(ParseState *pstate,
132 CreateStmtContext *cxt,
134 bool isAddConstraint);
135 static void applyColumnNames(List *dst, List *src);
136 static List *getSetColTypes(ParseState *pstate, Node *node);
137 static void transformLockingClause(Query *qry, LockingClause *lc);
138 static void transformConstraintAttrs(List *constraintList);
139 static void transformColumnType(ParseState *pstate, ColumnDef *column);
140 static void release_pstate_resources(ParseState *pstate);
141 static FromExpr *makeFromExpr(List *fromlist, Node *quals);
142 static bool check_parameter_resolution_walker(Node *node,
143 check_parameter_resolution_context *context);
148 * Analyze a raw parse tree and transform it to Query form.
150 * Optionally, information about $n parameter types can be supplied.
151 * References to $n indexes not defined by paramTypes[] are disallowed.
153 * The result is a List of Query nodes (we need a list since some commands
154 * produce multiple Queries). Optimizable statements require considerable
155 * transformation, while many utility-type statements are simply hung off
156 * a dummy CMD_UTILITY Query node.
159 parse_analyze(Node *parseTree, Oid *paramTypes, int numParams)
161 ParseState *pstate = make_parsestate(NULL);
164 pstate->p_paramtypes = paramTypes;
165 pstate->p_numparams = numParams;
166 pstate->p_variableparams = false;
168 result = do_parse_analyze(parseTree, pstate);
176 * parse_analyze_varparams
178 * This variant is used when it's okay to deduce information about $n
179 * symbol datatypes from context. The passed-in paramTypes[] array can
180 * be modified or enlarged (via repalloc).
183 parse_analyze_varparams(Node *parseTree, Oid **paramTypes, int *numParams)
185 ParseState *pstate = make_parsestate(NULL);
188 pstate->p_paramtypes = *paramTypes;
189 pstate->p_numparams = *numParams;
190 pstate->p_variableparams = true;
192 result = do_parse_analyze(parseTree, pstate);
194 *paramTypes = pstate->p_paramtypes;
195 *numParams = pstate->p_numparams;
199 /* make sure all is well with parameter types */
202 check_parameter_resolution_context context;
204 context.paramTypes = *paramTypes;
205 context.numParams = *numParams;
206 check_parameter_resolution_walker((Node *) result, &context);
214 * Entry point for recursively analyzing a sub-statement.
217 parse_sub_analyze(Node *parseTree, ParseState *parentParseState)
219 ParseState *pstate = make_parsestate(parentParseState);
222 result = do_parse_analyze(parseTree, pstate);
231 * Workhorse code shared by the above variants of parse_analyze.
234 do_parse_analyze(Node *parseTree, ParseState *pstate)
238 /* Lists to return extra commands from transformation */
239 List *extras_before = NIL;
240 List *extras_after = NIL;
244 query = transformStmt(pstate, parseTree, &extras_before, &extras_after);
246 /* don't need to access result relation any more */
247 release_pstate_resources(pstate);
249 foreach(l, extras_before)
250 result = list_concat(result, parse_sub_analyze(lfirst(l), pstate));
252 result = lappend(result, query);
254 foreach(l, extras_after)
255 result = list_concat(result, parse_sub_analyze(lfirst(l), pstate));
258 * Make sure that only the original query is marked original. We have
259 * to do this explicitly since recursive calls of do_parse_analyze
260 * will have marked some of the added-on queries as "original". Also
261 * mark only the original query as allowed to set the command-result
266 Query *q = lfirst(l);
270 q->querySource = QSRC_ORIGINAL;
275 q->querySource = QSRC_PARSER;
276 q->canSetTag = false;
284 release_pstate_resources(ParseState *pstate)
286 if (pstate->p_target_relation != NULL)
287 heap_close(pstate->p_target_relation, NoLock);
288 pstate->p_target_relation = NULL;
289 pstate->p_target_rangetblentry = NULL;
294 * transform a Parse tree into a Query tree.
297 transformStmt(ParseState *pstate, Node *parseTree,
298 List **extras_before, List **extras_after)
300 Query *result = NULL;
302 switch (nodeTag(parseTree))
305 * Non-optimizable statements
308 result = transformCreateStmt(pstate, (CreateStmt *) parseTree,
309 extras_before, extras_after);
313 result = transformIndexStmt(pstate, (IndexStmt *) parseTree);
317 result = transformRuleStmt(pstate, (RuleStmt *) parseTree,
318 extras_before, extras_after);
322 result = transformViewStmt(pstate, (ViewStmt *) parseTree,
323 extras_before, extras_after);
328 ExplainStmt *n = (ExplainStmt *) parseTree;
330 result = makeNode(Query);
331 result->commandType = CMD_UTILITY;
332 n->query = transformStmt(pstate, (Node *) n->query,
333 extras_before, extras_after);
334 result->utilityStmt = (Node *) parseTree;
338 case T_AlterTableStmt:
339 result = transformAlterTableStmt(pstate,
340 (AlterTableStmt *) parseTree,
341 extras_before, extras_after);
345 result = transformPrepareStmt(pstate, (PrepareStmt *) parseTree);
349 result = transformExecuteStmt(pstate, (ExecuteStmt *) parseTree);
353 * Optimizable statements
356 result = transformInsertStmt(pstate, (InsertStmt *) parseTree,
357 extras_before, extras_after);
361 result = transformDeleteStmt(pstate, (DeleteStmt *) parseTree);
365 result = transformUpdateStmt(pstate, (UpdateStmt *) parseTree);
369 if (((SelectStmt *) parseTree)->op == SETOP_NONE)
370 result = transformSelectStmt(pstate,
371 (SelectStmt *) parseTree);
373 result = transformSetOperationStmt(pstate,
374 (SelectStmt *) parseTree);
377 case T_DeclareCursorStmt:
378 result = transformDeclareCursorStmt(pstate,
379 (DeclareCursorStmt *) parseTree);
385 * other statements don't require any transformation-- just
386 * return the original parsetree, yea!
388 result = makeNode(Query);
389 result->commandType = CMD_UTILITY;
390 result->utilityStmt = (Node *) parseTree;
394 /* Mark as original query until we learn differently */
395 result->querySource = QSRC_ORIGINAL;
396 result->canSetTag = true;
399 * Check that we did not produce too many resnos; at the very
400 * least we cannot allow more than 2^16, since that would exceed
401 * the range of a AttrNumber. It seems safest to use
402 * MaxTupleAttributeNumber.
404 if (pstate->p_next_resno - 1 > MaxTupleAttributeNumber)
406 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
407 errmsg("target lists can have at most %d entries",
408 MaxTupleAttributeNumber)));
414 transformViewStmt(ParseState *pstate, ViewStmt *stmt,
415 List **extras_before, List **extras_after)
417 Query *result = makeNode(Query);
419 result->commandType = CMD_UTILITY;
420 result->utilityStmt = (Node *) stmt;
422 stmt->query = transformStmt(pstate, (Node *) stmt->query,
423 extras_before, extras_after);
426 * If a list of column names was given, run through and insert these
427 * into the actual query tree. - thomas 2000-03-08
429 * Outer loop is over targetlist to make it easier to skip junk
430 * targetlist entries.
432 if (stmt->aliases != NIL)
434 ListCell *alist_item = list_head(stmt->aliases);
435 ListCell *targetList;
437 foreach(targetList, stmt->query->targetList)
439 TargetEntry *te = (TargetEntry *) lfirst(targetList);
441 Assert(IsA(te, TargetEntry));
442 /* junk columns don't get aliases */
445 te->resname = pstrdup(strVal(lfirst(alist_item)));
446 alist_item = lnext(alist_item);
447 if (alist_item == NULL)
448 break; /* done assigning aliases */
451 if (alist_item != NULL)
453 (errcode(ERRCODE_SYNTAX_ERROR),
454 errmsg("CREATE VIEW specifies more column "
455 "names than columns")));
462 * transformDeleteStmt -
463 * transforms a Delete Statement
466 transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
468 Query *qry = makeNode(Query);
471 qry->commandType = CMD_DELETE;
473 /* set up range table with just the result rel */
474 qry->resultRelation = setTargetTable(pstate, stmt->relation,
475 interpretInhOption(stmt->relation->inhOpt),
479 qry->distinctClause = NIL;
482 * The USING clause is non-standard SQL syntax, and is equivalent
483 * in functionality to the FROM list that can be specified for
484 * UPDATE. The USING keyword is used rather than FROM because FROM
485 * is already a keyword in the DELETE syntax.
487 transformFromClause(pstate, stmt->usingClause);
489 /* fix where clause */
490 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
492 /* done building the range table and jointree */
493 qry->rtable = pstate->p_rtable;
494 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
496 qry->hasSubLinks = pstate->p_hasSubLinks;
497 qry->hasAggs = pstate->p_hasAggs;
498 if (pstate->p_hasAggs)
499 parseCheckAggregates(pstate, qry);
505 * transformInsertStmt -
506 * transform an Insert Statement
509 transformInsertStmt(ParseState *pstate, InsertStmt *stmt,
510 List **extras_before, List **extras_after)
512 Query *qry = makeNode(Query);
513 Query *selectQuery = NULL;
515 List *sub_relnamespace;
516 List *sub_varnamespace;
523 qry->commandType = CMD_INSERT;
524 pstate->p_is_insert = true;
527 * If a non-nil rangetable/namespace was passed in, and we are doing
528 * INSERT/SELECT, arrange to pass the rangetable/namespace down to the
529 * SELECT. This can only happen if we are inside a CREATE RULE, and
530 * in that case we want the rule's OLD and NEW rtable entries to
531 * appear as part of the SELECT's rtable, not as outer references for
532 * it. (Kluge!) The SELECT's joinlist is not affected however. We
533 * must do this before adding the target table to the INSERT's rtable.
535 if (stmt->selectStmt)
537 sub_rtable = pstate->p_rtable;
538 pstate->p_rtable = NIL;
539 sub_relnamespace = pstate->p_relnamespace;
540 pstate->p_relnamespace = NIL;
541 sub_varnamespace = pstate->p_varnamespace;
542 pstate->p_varnamespace = NIL;
546 sub_rtable = NIL; /* not used, but keep compiler quiet */
547 sub_relnamespace = NIL;
548 sub_varnamespace = NIL;
552 * Must get write lock on INSERT target table before scanning SELECT,
553 * else we will grab the wrong kind of initial lock if the target
554 * table is also mentioned in the SELECT part. Note that the target
555 * table is not added to the joinlist or namespace.
557 qry->resultRelation = setTargetTable(pstate, stmt->relation,
558 false, false, ACL_INSERT);
561 * Is it INSERT ... SELECT or INSERT ... VALUES?
563 if (stmt->selectStmt)
566 * We make the sub-pstate a child of the outer pstate so that it
567 * can see any Param definitions supplied from above. Since the
568 * outer pstate's rtable and namespace are presently empty, there
569 * are no side-effects of exposing names the sub-SELECT shouldn't
572 ParseState *sub_pstate = make_parsestate(pstate);
577 * Process the source SELECT.
579 * It is important that this be handled just like a standalone
580 * SELECT; otherwise the behavior of SELECT within INSERT might be
581 * different from a stand-alone SELECT. (Indeed, Postgres up
582 * through 6.5 had bugs of just that nature...)
584 sub_pstate->p_rtable = sub_rtable;
585 sub_pstate->p_relnamespace = sub_relnamespace;
586 sub_pstate->p_varnamespace = sub_varnamespace;
589 * Note: we are not expecting that extras_before and extras_after
590 * are going to be used by the transformation of the SELECT
593 selectQuery = transformStmt(sub_pstate, stmt->selectStmt,
594 extras_before, extras_after);
596 release_pstate_resources(sub_pstate);
599 Assert(IsA(selectQuery, Query));
600 Assert(selectQuery->commandType == CMD_SELECT);
601 if (selectQuery->into)
603 (errcode(ERRCODE_SYNTAX_ERROR),
604 errmsg("INSERT ... SELECT may not specify INTO")));
607 * Make the source be a subquery in the INSERT's rangetable, and
608 * add it to the INSERT's joinlist.
610 rte = addRangeTableEntryForSubquery(pstate,
612 makeAlias("*SELECT*", NIL),
614 rtr = makeNode(RangeTblRef);
615 /* assume new rte is at end */
616 rtr->rtindex = list_length(pstate->p_rtable);
617 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
618 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
621 * Generate a targetlist for the INSERT that selects all the
622 * non-resjunk columns from the subquery. (We need this to be
623 * separate from the subquery's tlist because we may add columns,
624 * insert datatype coercions, etc.)
626 * HACK: unknown-type constants and params in the SELECT's targetlist
627 * are copied up as-is rather than being referenced as subquery
628 * outputs. This is to ensure that when we try to coerce them to
629 * the target column's datatype, the right things happen (see
630 * special cases in coerce_type). Otherwise, this fails:
631 * INSERT INTO foo SELECT 'bar', ... FROM baz
634 qry->targetList = NIL;
635 foreach(tl, selectQuery->targetList)
637 TargetEntry *tle = (TargetEntry *) lfirst(tl);
643 (IsA(tle->expr, Const) || IsA(tle->expr, Param)) &&
644 exprType((Node *) tle->expr) == UNKNOWNOID)
647 expr = (Expr *) makeVar(rtr->rtindex,
649 exprType((Node *) tle->expr),
650 exprTypmod((Node *) tle->expr),
652 tle = makeTargetEntry(expr,
653 (AttrNumber) pstate->p_next_resno++,
656 qry->targetList = lappend(qry->targetList, tle);
662 * For INSERT ... VALUES, transform the given list of values to
663 * form a targetlist for the INSERT.
665 qry->targetList = transformTargetList(pstate, stmt->targetList);
669 * Now we are done with SELECT-like processing, and can get on with
670 * transforming the target list to match the INSERT target columns.
673 /* Prepare to assign non-conflicting resnos to resjunk attributes */
674 if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
675 pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
677 /* Validate stmt->cols list, or build default list if no list given */
678 icolumns = checkInsertTargets(pstate, stmt->cols, &attrnos);
681 * Prepare columns for assignment to target table.
683 icols = list_head(icolumns);
684 attnos = list_head(attrnos);
685 foreach(tl, qry->targetList)
687 TargetEntry *tle = (TargetEntry *) lfirst(tl);
690 if (icols == NULL || attnos == NULL)
692 (errcode(ERRCODE_SYNTAX_ERROR),
693 errmsg("INSERT has more expressions than target columns")));
695 col = (ResTarget *) lfirst(icols);
696 Assert(IsA(col, ResTarget));
698 Assert(!tle->resjunk);
699 updateTargetListEntry(pstate, tle, col->name, lfirst_int(attnos),
702 icols = lnext(icols);
703 attnos = lnext(attnos);
707 * Ensure that the targetlist has the same number of entries that were
708 * present in the columns list. Don't do the check unless an explicit
709 * columns list was given, though.
711 if (stmt->cols != NIL && (icols != NULL || attnos != NULL))
713 (errcode(ERRCODE_SYNTAX_ERROR),
714 errmsg("INSERT has more target columns than expressions")));
716 /* done building the range table and jointree */
717 qry->rtable = pstate->p_rtable;
718 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
720 qry->hasSubLinks = pstate->p_hasSubLinks;
721 qry->hasAggs = pstate->p_hasAggs;
722 if (pstate->p_hasAggs)
723 parseCheckAggregates(pstate, qry);
729 * transformCreateStmt -
730 * transforms the "create table" statement
731 * SQL92 allows constraints to be scattered all over, so thumb through
732 * the columns and collect all constraints into one place.
733 * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
734 * then expand those into multiple IndexStmt blocks.
735 * - thomas 1997-12-02
738 transformCreateStmt(ParseState *pstate, CreateStmt *stmt,
739 List **extras_before, List **extras_after)
741 CreateStmtContext cxt;
745 cxt.stmtType = "CREATE TABLE";
746 cxt.relation = stmt->relation;
747 cxt.inhRelations = stmt->inhRelations;
750 cxt.ckconstraints = NIL;
751 cxt.fkconstraints = NIL;
752 cxt.ixconstraints = NIL;
756 cxt.hasoids = interpretOidsOption(stmt->hasoids);
759 * Run through each primary element in the table creation clause.
760 * Separate column defs from constraints, and do preliminary analysis.
762 foreach(elements, stmt->tableElts)
764 Node *element = lfirst(elements);
766 switch (nodeTag(element))
769 transformColumnDefinition(pstate, &cxt,
770 (ColumnDef *) element);
774 transformTableConstraint(pstate, &cxt,
775 (Constraint *) element);
779 /* No pre-transformation needed */
780 cxt.fkconstraints = lappend(cxt.fkconstraints, element);
784 transformInhRelation(pstate, &cxt,
785 (InhRelation *) element);
789 elog(ERROR, "unrecognized node type: %d",
790 (int) nodeTag(element));
795 Assert(stmt->constraints == NIL);
798 * Postprocess constraints that give rise to index definitions.
800 transformIndexConstraints(pstate, &cxt);
803 * Postprocess foreign-key constraints.
805 transformFKConstraints(pstate, &cxt, true, false);
811 q->commandType = CMD_UTILITY;
812 q->utilityStmt = (Node *) stmt;
813 stmt->tableElts = cxt.columns;
814 stmt->constraints = cxt.ckconstraints;
815 *extras_before = list_concat(*extras_before, cxt.blist);
816 *extras_after = list_concat(cxt.alist, *extras_after);
822 transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
827 Constraint *constraint;
830 cxt->columns = lappend(cxt->columns, column);
832 /* Check for SERIAL pseudo-types */
834 if (list_length(column->typename->names) == 1)
836 char *typname = strVal(linitial(column->typename->names));
838 if (strcmp(typname, "serial") == 0 ||
839 strcmp(typname, "serial4") == 0)
842 column->typename->names = NIL;
843 column->typename->typeid = INT4OID;
845 else if (strcmp(typname, "bigserial") == 0 ||
846 strcmp(typname, "serial8") == 0)
849 column->typename->names = NIL;
850 column->typename->typeid = INT8OID;
854 /* Do necessary work on the column type declaration */
855 transformColumnType(pstate, column);
857 /* Special actions for SERIAL pseudo-types */
865 FuncCall *funccallnode;
866 CreateSeqStmt *seqstmt;
869 * Determine namespace and name to use for the sequence.
871 * Although we use ChooseRelationName, it's not guaranteed that the
872 * selected sequence name won't conflict; given sufficiently long
873 * field names, two different serial columns in the same table
874 * could be assigned the same sequence name, and we'd not notice
875 * since we aren't creating the sequence quite yet. In practice
876 * this seems quite unlikely to be a problem, especially since few
877 * people would need two serial columns in one table.
879 snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
880 snamespace = get_namespace_name(snamespaceid);
881 sname = ChooseRelationName(cxt->relation->relname,
887 (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
888 cxt->stmtType, sname,
889 cxt->relation->relname, column->colname)));
892 * Build a CREATE SEQUENCE command to create the sequence object,
893 * and add it to the list of things to be done before this
894 * CREATE/ALTER TABLE.
896 seqstmt = makeNode(CreateSeqStmt);
897 seqstmt->sequence = makeRangeVar(snamespace, sname);
898 seqstmt->options = NIL;
900 cxt->blist = lappend(cxt->blist, seqstmt);
903 * Mark the ColumnDef so that during execution, an appropriate
904 * dependency will be added from the sequence to the column.
906 column->support = makeRangeVar(snamespace, sname);
909 * Create appropriate constraints for SERIAL. We do this in full,
910 * rather than shortcutting, so that we will detect any
911 * conflicting constraints the user wrote (like a different
914 * Create an expression tree representing the function call
915 * nextval('"sequencename"')
917 qstring = quote_qualified_identifier(snamespace, sname);
918 snamenode = makeNode(A_Const);
919 snamenode->val.type = T_String;
920 snamenode->val.val.str = qstring;
921 funccallnode = makeNode(FuncCall);
922 funccallnode->funcname = SystemFuncName("nextval");
923 funccallnode->args = list_make1(snamenode);
924 funccallnode->agg_star = false;
925 funccallnode->agg_distinct = false;
927 constraint = makeNode(Constraint);
928 constraint->contype = CONSTR_DEFAULT;
929 constraint->raw_expr = (Node *) funccallnode;
930 constraint->cooked_expr = NULL;
931 constraint->keys = NIL;
932 column->constraints = lappend(column->constraints, constraint);
934 constraint = makeNode(Constraint);
935 constraint->contype = CONSTR_NOTNULL;
936 column->constraints = lappend(column->constraints, constraint);
939 /* Process column constraints, if any... */
940 transformConstraintAttrs(column->constraints);
942 saw_nullable = false;
944 foreach(clist, column->constraints)
946 constraint = lfirst(clist);
949 * If this column constraint is a FOREIGN KEY constraint, then we
950 * fill in the current attribute's name and throw it into the list
951 * of FK constraints to be processed later.
953 if (IsA(constraint, FkConstraint))
955 FkConstraint *fkconstraint = (FkConstraint *) constraint;
957 fkconstraint->fk_attrs = list_make1(makeString(column->colname));
958 cxt->fkconstraints = lappend(cxt->fkconstraints, fkconstraint);
962 Assert(IsA(constraint, Constraint));
964 switch (constraint->contype)
967 if (saw_nullable && column->is_not_null)
969 (errcode(ERRCODE_SYNTAX_ERROR),
970 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
971 column->colname, cxt->relation->relname)));
972 column->is_not_null = FALSE;
977 if (saw_nullable && !column->is_not_null)
979 (errcode(ERRCODE_SYNTAX_ERROR),
980 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
981 column->colname, cxt->relation->relname)));
982 column->is_not_null = TRUE;
987 if (column->raw_default != NULL)
989 (errcode(ERRCODE_SYNTAX_ERROR),
990 errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
991 column->colname, cxt->relation->relname)));
992 column->raw_default = constraint->raw_expr;
993 Assert(constraint->cooked_expr == NULL);
998 if (constraint->keys == NIL)
999 constraint->keys = list_make1(makeString(column->colname));
1000 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
1004 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
1007 case CONSTR_ATTR_DEFERRABLE:
1008 case CONSTR_ATTR_NOT_DEFERRABLE:
1009 case CONSTR_ATTR_DEFERRED:
1010 case CONSTR_ATTR_IMMEDIATE:
1011 /* transformConstraintAttrs took care of these */
1015 elog(ERROR, "unrecognized constraint type: %d",
1016 constraint->contype);
1023 transformTableConstraint(ParseState *pstate, CreateStmtContext *cxt,
1024 Constraint *constraint)
1026 switch (constraint->contype)
1028 case CONSTR_PRIMARY:
1030 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
1034 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
1038 case CONSTR_NOTNULL:
1039 case CONSTR_DEFAULT:
1040 case CONSTR_ATTR_DEFERRABLE:
1041 case CONSTR_ATTR_NOT_DEFERRABLE:
1042 case CONSTR_ATTR_DEFERRED:
1043 case CONSTR_ATTR_IMMEDIATE:
1044 elog(ERROR, "invalid context for constraint type %d",
1045 constraint->contype);
1049 elog(ERROR, "unrecognized constraint type: %d",
1050 constraint->contype);
1056 * transformInhRelation
1058 * Change the LIKE <subtable> portion of a CREATE TABLE statement into the
1059 * column definitions which recreate the user defined column portions of <subtable>.
1062 transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
1063 InhRelation *inhRelation)
1065 AttrNumber parent_attno;
1068 TupleDesc tupleDesc;
1069 TupleConstr *constr;
1070 AclResult aclresult;
1072 relation = heap_openrv(inhRelation->relation, AccessShareLock);
1074 if (relation->rd_rel->relkind != RELKIND_RELATION)
1076 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1077 errmsg("inherited relation \"%s\" is not a table",
1078 inhRelation->relation->relname)));
1081 * Check for SELECT privilages
1083 aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
1085 if (aclresult != ACLCHECK_OK)
1086 aclcheck_error(aclresult, ACL_KIND_CLASS,
1087 RelationGetRelationName(relation));
1089 tupleDesc = RelationGetDescr(relation);
1090 constr = tupleDesc->constr;
1093 * Insert the inherited attributes into the cxt for the new table
1096 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1099 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
1100 char *attributeName = NameStr(attribute->attname);
1105 * Ignore dropped columns in the parent.
1107 if (attribute->attisdropped)
1111 * Create a new inherited column.
1113 * For constraints, ONLY the NOT NULL constraint is inherited by the
1114 * new column definition per SQL99.
1116 def = makeNode(ColumnDef);
1117 def->colname = pstrdup(attributeName);
1118 typename = makeNode(TypeName);
1119 typename->typeid = attribute->atttypid;
1120 typename->typmod = attribute->atttypmod;
1121 def->typename = typename;
1123 def->is_local = false;
1124 def->is_not_null = attribute->attnotnull;
1125 def->raw_default = NULL;
1126 def->cooked_default = NULL;
1127 def->constraints = NIL;
1128 def->support = NULL;
1131 * Add to column list
1133 cxt->columns = lappend(cxt->columns, def);
1136 * Copy default if any, and the default has been requested
1138 if (attribute->atthasdef && inhRelation->including_defaults)
1140 char *this_default = NULL;
1141 AttrDefault *attrdef;
1144 /* Find default in constraint structure */
1145 Assert(constr != NULL);
1146 attrdef = constr->defval;
1147 for (i = 0; i < constr->num_defval; i++)
1149 if (attrdef[i].adnum == parent_attno)
1151 this_default = attrdef[i].adbin;
1155 Assert(this_default != NULL);
1158 * If default expr could contain any vars, we'd need to fix
1159 * 'em, but it can't; so default is ready to apply to child.
1162 def->cooked_default = pstrdup(this_default);
1167 * Close the parent rel, but keep our AccessShareLock on it until xact
1168 * commit. That will prevent someone else from deleting or ALTERing
1169 * the parent before the child is committed.
1171 heap_close(relation, NoLock);
1175 transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
1178 List *indexlist = NIL;
1183 * Run through the constraints that need to generate an index. For
1184 * PRIMARY KEY, mark each column as NOT NULL and create an index. For
1185 * UNIQUE, create an index as for PRIMARY KEY, but do not insist on
1188 foreach(listptr, cxt->ixconstraints)
1190 Constraint *constraint = lfirst(listptr);
1194 Assert(IsA(constraint, Constraint));
1195 Assert((constraint->contype == CONSTR_PRIMARY)
1196 || (constraint->contype == CONSTR_UNIQUE));
1198 index = makeNode(IndexStmt);
1200 index->unique = true;
1201 index->primary = (constraint->contype == CONSTR_PRIMARY);
1204 if (cxt->pkey != NULL)
1206 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1207 errmsg("multiple primary keys for table \"%s\" are not allowed",
1208 cxt->relation->relname)));
1212 * In ALTER TABLE case, a primary index might already exist,
1213 * but DefineIndex will check for it.
1216 index->isconstraint = true;
1218 if (constraint->name != NULL)
1219 index->idxname = pstrdup(constraint->name);
1221 index->idxname = NULL; /* DefineIndex will choose name */
1223 index->relation = cxt->relation;
1224 index->accessMethod = DEFAULT_INDEX_TYPE;
1225 index->tableSpace = constraint->indexspace;
1226 index->indexParams = NIL;
1227 index->whereClause = NULL;
1230 * Make sure referenced keys exist. If we are making a PRIMARY
1231 * KEY index, also make sure they are NOT NULL, if possible.
1232 * (Although we could leave it to DefineIndex to mark the columns
1233 * NOT NULL, it's more efficient to get it right the first time.)
1235 foreach(keys, constraint->keys)
1237 char *key = strVal(lfirst(keys));
1239 ColumnDef *column = NULL;
1242 foreach(columns, cxt->columns)
1244 column = (ColumnDef *) lfirst(columns);
1245 Assert(IsA(column, ColumnDef));
1246 if (strcmp(column->colname, key) == 0)
1254 /* found column in the new table; force it to be NOT NULL */
1255 if (constraint->contype == CONSTR_PRIMARY)
1256 column->is_not_null = TRUE;
1258 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1261 * column will be a system column in the new table, so
1262 * accept it. System columns can't ever be null, so no
1263 * need to worry about PRIMARY/NOT NULL constraint.
1267 else if (cxt->inhRelations)
1269 /* try inherited tables */
1272 foreach(inher, cxt->inhRelations)
1274 RangeVar *inh = (RangeVar *) lfirst(inher);
1278 Assert(IsA(inh, RangeVar));
1279 rel = heap_openrv(inh, AccessShareLock);
1280 if (rel->rd_rel->relkind != RELKIND_RELATION)
1282 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1283 errmsg("inherited relation \"%s\" is not a table",
1285 for (count = 0; count < rel->rd_att->natts; count++)
1287 Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1288 char *inhname = NameStr(inhattr->attname);
1290 if (inhattr->attisdropped)
1292 if (strcmp(key, inhname) == 0)
1297 * We currently have no easy way to force an
1298 * inherited column to be NOT NULL at
1299 * creation, if its parent wasn't so already.
1300 * We leave it to DefineIndex to fix things up
1306 heap_close(rel, NoLock);
1313 * In the ALTER TABLE case, don't complain about index keys
1314 * not created in the command; they may well exist already.
1315 * DefineIndex will complain about them if not, and will also
1316 * take care of marking them NOT NULL.
1318 if (!found && !cxt->isalter)
1320 (errcode(ERRCODE_UNDEFINED_COLUMN),
1321 errmsg("column \"%s\" named in key does not exist",
1324 /* Check for PRIMARY KEY(foo, foo) */
1325 foreach(columns, index->indexParams)
1327 iparam = (IndexElem *) lfirst(columns);
1328 if (iparam->name && strcmp(key, iparam->name) == 0)
1332 (errcode(ERRCODE_DUPLICATE_COLUMN),
1333 errmsg("column \"%s\" appears twice in primary key constraint",
1337 (errcode(ERRCODE_DUPLICATE_COLUMN),
1338 errmsg("column \"%s\" appears twice in unique constraint",
1343 /* OK, add it to the index definition */
1344 iparam = makeNode(IndexElem);
1345 iparam->name = pstrdup(key);
1346 iparam->expr = NULL;
1347 iparam->opclass = NIL;
1348 index->indexParams = lappend(index->indexParams, iparam);
1351 indexlist = lappend(indexlist, index);
1355 * Scan the index list and remove any redundant index specifications.
1356 * This can happen if, for instance, the user writes UNIQUE PRIMARY
1357 * KEY. A strict reading of SQL92 would suggest raising an error
1358 * instead, but that strikes me as too anal-retentive. - tgl
1361 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1362 * pre-existing indexes, too.
1365 if (cxt->pkey != NULL)
1367 /* Make sure we keep the PKEY index in preference to others... */
1368 cxt->alist = list_make1(cxt->pkey);
1371 foreach(l, indexlist)
1378 /* if it's pkey, it's already in cxt->alist */
1379 if (index == cxt->pkey)
1382 foreach(k, cxt->alist)
1384 IndexStmt *priorindex = lfirst(k);
1386 if (equal(index->indexParams, priorindex->indexParams))
1389 * If the prior index is as yet unnamed, and this one is
1390 * named, then transfer the name to the prior index. This
1391 * ensures that if we have named and unnamed constraints,
1392 * we'll use (at least one of) the names for the index.
1394 if (priorindex->idxname == NULL)
1395 priorindex->idxname = index->idxname;
1402 cxt->alist = lappend(cxt->alist, index);
1407 transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
1408 bool skipValidation, bool isAddConstraint)
1412 if (cxt->fkconstraints == NIL)
1416 * If CREATE TABLE or adding a column with NULL default, we can safely
1417 * skip validation of the constraint.
1421 foreach(fkclist, cxt->fkconstraints)
1423 FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1425 fkconstraint->skip_validation = true;
1430 * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE
1431 * ADD CONSTRAINT command to execute after the basic command is
1432 * complete. (If called from ADD CONSTRAINT, that routine will add the
1433 * FK constraints to its own subcommand list.)
1435 * Note: the ADD CONSTRAINT command must also execute after any index
1436 * creation commands. Thus, this should run after
1437 * transformIndexConstraints, so that the CREATE INDEX commands are
1438 * already in cxt->alist.
1440 if (!isAddConstraint)
1442 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1444 alterstmt->relation = cxt->relation;
1445 alterstmt->cmds = NIL;
1446 alterstmt->relkind = OBJECT_TABLE;
1448 foreach(fkclist, cxt->fkconstraints)
1450 FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1451 AlterTableCmd *altercmd = makeNode(AlterTableCmd);
1453 altercmd->subtype = AT_ProcessedConstraint;
1454 altercmd->name = NULL;
1455 altercmd->def = (Node *) fkconstraint;
1456 alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
1459 cxt->alist = lappend(cxt->alist, alterstmt);
1464 * transformIndexStmt -
1465 * transforms the qualification of the index statement
1468 transformIndexStmt(ParseState *pstate, IndexStmt *stmt)
1471 RangeTblEntry *rte = NULL;
1474 qry = makeNode(Query);
1475 qry->commandType = CMD_UTILITY;
1477 /* take care of the where clause */
1478 if (stmt->whereClause)
1481 * Put the parent table into the rtable so that the WHERE clause
1482 * can refer to its fields without qualification. Note that this
1483 * only works if the parent table already exists --- so we can't
1484 * easily support predicates on indexes created implicitly by
1485 * CREATE TABLE. Fortunately, that's not necessary.
1487 rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1489 /* no to join list, yes to namespaces */
1490 addRTEtoQuery(pstate, rte, false, true, true);
1492 stmt->whereClause = transformWhereClause(pstate, stmt->whereClause,
1496 /* take care of any index expressions */
1497 foreach(l, stmt->indexParams)
1499 IndexElem *ielem = (IndexElem *) lfirst(l);
1503 /* Set up rtable as for predicate, see notes above */
1506 rte = addRangeTableEntry(pstate, stmt->relation, NULL,
1508 /* no to join list, yes to namespaces */
1509 addRTEtoQuery(pstate, rte, false, true, true);
1511 ielem->expr = transformExpr(pstate, ielem->expr);
1514 * We check only that the result type is legitimate; this is
1515 * for consistency with what transformWhereClause() checks for
1516 * the predicate. DefineIndex() will make more checks.
1518 if (expression_returns_set(ielem->expr))
1520 (errcode(ERRCODE_DATATYPE_MISMATCH),
1521 errmsg("index expression may not return a set")));
1525 qry->hasSubLinks = pstate->p_hasSubLinks;
1526 stmt->rangetable = pstate->p_rtable;
1528 qry->utilityStmt = (Node *) stmt;
1534 * transformRuleStmt -
1535 * transform a Create Rule Statement. The actions is a list of parse
1536 * trees which is transformed into a list of query trees.
1539 transformRuleStmt(ParseState *pstate, RuleStmt *stmt,
1540 List **extras_before, List **extras_after)
1544 RangeTblEntry *oldrte;
1545 RangeTblEntry *newrte;
1547 qry = makeNode(Query);
1548 qry->commandType = CMD_UTILITY;
1549 qry->utilityStmt = (Node *) stmt;
1552 * To avoid deadlock, make sure the first thing we do is grab
1553 * AccessExclusiveLock on the target relation. This will be needed by
1554 * DefineQueryRewrite(), and we don't want to grab a lesser lock
1557 rel = heap_openrv(stmt->relation, AccessExclusiveLock);
1560 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to
1561 * 2. Set up their RTEs in the main pstate for use in parsing the
1562 * rule qualification.
1564 Assert(pstate->p_rtable == NIL);
1565 oldrte = addRangeTableEntryForRelation(pstate, rel,
1566 makeAlias("*OLD*", NIL),
1568 newrte = addRangeTableEntryForRelation(pstate, rel,
1569 makeAlias("*NEW*", NIL),
1571 /* Must override addRangeTableEntry's default access-check flags */
1572 oldrte->requiredPerms = 0;
1573 newrte->requiredPerms = 0;
1576 * They must be in the namespace too for lookup purposes, but only add
1577 * the one(s) that are relevant for the current kind of rule. In an
1578 * UPDATE rule, quals must refer to OLD.field or NEW.field to be
1579 * unambiguous, but there's no need to be so picky for INSERT &
1580 * DELETE. We do not add them to the joinlist.
1582 switch (stmt->event)
1585 addRTEtoQuery(pstate, oldrte, false, true, true);
1588 addRTEtoQuery(pstate, oldrte, false, true, true);
1589 addRTEtoQuery(pstate, newrte, false, true, true);
1592 addRTEtoQuery(pstate, newrte, false, true, true);
1595 addRTEtoQuery(pstate, oldrte, false, true, true);
1598 elog(ERROR, "unrecognized event type: %d",
1603 /* take care of the where clause */
1604 stmt->whereClause = transformWhereClause(pstate, stmt->whereClause,
1607 if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
1609 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1610 errmsg("rule WHERE condition may not contain references to other relations")));
1612 /* aggregates not allowed (but subselects are okay) */
1613 if (pstate->p_hasAggs)
1615 (errcode(ERRCODE_GROUPING_ERROR),
1616 errmsg("rule WHERE condition may not contain aggregate functions")));
1618 /* save info about sublinks in where clause */
1619 qry->hasSubLinks = pstate->p_hasSubLinks;
1622 * 'instead nothing' rules with a qualification need a query
1623 * rangetable so the rewrite handler can add the negated rule
1624 * qualification to the original query. We create a query with the new
1625 * command type CMD_NOTHING here that is treated specially by the
1628 if (stmt->actions == NIL)
1630 Query *nothing_qry = makeNode(Query);
1632 nothing_qry->commandType = CMD_NOTHING;
1633 nothing_qry->rtable = pstate->p_rtable;
1634 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
1636 stmt->actions = list_make1(nothing_qry);
1641 List *newactions = NIL;
1644 * transform each statement, like parse_sub_analyze()
1646 foreach(l, stmt->actions)
1648 Node *action = (Node *) lfirst(l);
1649 ParseState *sub_pstate = make_parsestate(pstate->parentParseState);
1656 * Set up OLD/NEW in the rtable for this statement. The
1657 * entries are added only to relnamespace, not varnamespace,
1658 * because we don't want them to be referred to by unqualified
1659 * field names nor "*" in the rule actions. We decide later
1660 * whether to put them in the joinlist.
1662 oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
1663 makeAlias("*OLD*", NIL),
1665 newrte = addRangeTableEntryForRelation(sub_pstate, rel,
1666 makeAlias("*NEW*", NIL),
1668 oldrte->requiredPerms = 0;
1669 newrte->requiredPerms = 0;
1670 addRTEtoQuery(sub_pstate, oldrte, false, true, false);
1671 addRTEtoQuery(sub_pstate, newrte, false, true, false);
1673 /* Transform the rule action statement */
1674 top_subqry = transformStmt(sub_pstate, action,
1675 extras_before, extras_after);
1678 * We cannot support utility-statement actions (eg NOTIFY)
1679 * with nonempty rule WHERE conditions, because there's no way
1680 * to make the utility action execute conditionally.
1682 if (top_subqry->commandType == CMD_UTILITY &&
1683 stmt->whereClause != NULL)
1685 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1686 errmsg("rules with WHERE conditions may only have SELECT, INSERT, UPDATE, or DELETE actions")));
1689 * If the action is INSERT...SELECT, OLD/NEW have been pushed
1690 * down into the SELECT, and that's what we need to look at.
1691 * (Ugly kluge ... try to fix this when we redesign
1694 sub_qry = getInsertSelectQuery(top_subqry, NULL);
1697 * If the sub_qry is a setop, we cannot attach any
1698 * qualifications to it, because the planner won't notice
1699 * them. This could perhaps be relaxed someday, but for now,
1700 * we may as well reject such a rule immediately.
1702 if (sub_qry->setOperations != NULL && stmt->whereClause != NULL)
1704 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1705 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1708 * Validate action's use of OLD/NEW, qual too
1711 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
1712 rangeTableEntry_used(stmt->whereClause, PRS2_OLD_VARNO, 0);
1714 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
1715 rangeTableEntry_used(stmt->whereClause, PRS2_NEW_VARNO, 0);
1717 switch (stmt->event)
1722 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1723 errmsg("ON SELECT rule may not use OLD")));
1726 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1727 errmsg("ON SELECT rule may not use NEW")));
1735 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1736 errmsg("ON INSERT rule may not use OLD")));
1741 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1742 errmsg("ON DELETE rule may not use NEW")));
1745 elog(ERROR, "unrecognized event type: %d",
1751 * For efficiency's sake, add OLD to the rule action's
1752 * jointree only if it was actually referenced in the
1753 * statement or qual.
1755 * For INSERT, NEW is not really a relation (only a reference to
1756 * the to-be-inserted tuple) and should never be added to the
1759 * For UPDATE, we treat NEW as being another kind of reference to
1760 * OLD, because it represents references to *transformed*
1761 * tuples of the existing relation. It would be wrong to
1762 * enter NEW separately in the jointree, since that would
1763 * cause a double join of the updated relation. It's also
1764 * wrong to fail to make a jointree entry if only NEW and not
1767 if (has_old || (has_new && stmt->event == CMD_UPDATE))
1770 * If sub_qry is a setop, manipulating its jointree will
1771 * do no good at all, because the jointree is dummy. (This
1772 * should be a can't-happen case because of prior tests.)
1774 if (sub_qry->setOperations != NULL)
1776 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1777 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1778 /* hack so we can use addRTEtoQuery() */
1779 sub_pstate->p_rtable = sub_qry->rtable;
1780 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
1781 addRTEtoQuery(sub_pstate, oldrte, true, false, false);
1782 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
1785 newactions = lappend(newactions, top_subqry);
1787 release_pstate_resources(sub_pstate);
1791 stmt->actions = newactions;
1794 /* Close relation, but keep the exclusive lock */
1795 heap_close(rel, NoLock);
1802 * transformSelectStmt -
1803 * transforms a Select Statement
1805 * Note: this is also used for DECLARE CURSOR statements.
1808 transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
1810 Query *qry = makeNode(Query);
1813 qry->commandType = CMD_SELECT;
1815 /* make FOR UPDATE/FOR SHARE info available to addRangeTableEntry */
1816 pstate->p_locking_clause = stmt->lockingClause;
1818 /* process the FROM clause */
1819 transformFromClause(pstate, stmt->fromClause);
1821 /* transform targetlist */
1822 qry->targetList = transformTargetList(pstate, stmt->targetList);
1824 /* handle any SELECT INTO/CREATE TABLE AS spec */
1825 qry->into = stmt->into;
1826 if (stmt->intoColNames)
1827 applyColumnNames(qry->targetList, stmt->intoColNames);
1829 qry->intoHasOids = interpretOidsOption(stmt->intoHasOids);
1831 /* mark column origins */
1832 markTargetListOrigins(pstate, qry->targetList);
1834 /* transform WHERE */
1835 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
1838 * Initial processing of HAVING clause is just like WHERE clause.
1840 qry->havingQual = transformWhereClause(pstate, stmt->havingClause,
1844 * Transform sorting/grouping stuff. Do ORDER BY first because both
1845 * transformGroupClause and transformDistinctClause need the results.
1847 qry->sortClause = transformSortClause(pstate,
1850 true /* fix unknowns */ );
1852 qry->groupClause = transformGroupClause(pstate,
1857 qry->distinctClause = transformDistinctClause(pstate,
1858 stmt->distinctClause,
1862 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
1864 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
1867 qry->rtable = pstate->p_rtable;
1868 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
1870 qry->hasSubLinks = pstate->p_hasSubLinks;
1871 qry->hasAggs = pstate->p_hasAggs;
1872 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
1873 parseCheckAggregates(pstate, qry);
1875 if (stmt->lockingClause)
1876 transformLockingClause(qry, stmt->lockingClause);
1882 * transformSetOperationsStmt -
1883 * transforms a set-operations tree
1885 * A set-operation tree is just a SELECT, but with UNION/INTERSECT/EXCEPT
1886 * structure to it. We must transform each leaf SELECT and build up a top-
1887 * level Query that contains the leaf SELECTs as subqueries in its rangetable.
1888 * The tree of set operations is converted into the setOperations field of
1889 * the top-level Query.
1892 transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
1894 Query *qry = makeNode(Query);
1895 SelectStmt *leftmostSelect;
1897 Query *leftmostQuery;
1898 SetOperationStmt *sostmt;
1904 LockingClause *lockingClause;
1906 ListCell *left_tlist,
1913 RangeTblEntry *jrte;
1916 qry->commandType = CMD_SELECT;
1919 * Find leftmost leaf SelectStmt; extract the one-time-only items from
1920 * it and from the top-level node.
1922 leftmostSelect = stmt->larg;
1923 while (leftmostSelect && leftmostSelect->op != SETOP_NONE)
1924 leftmostSelect = leftmostSelect->larg;
1925 Assert(leftmostSelect && IsA(leftmostSelect, SelectStmt) &&
1926 leftmostSelect->larg == NULL);
1927 into = leftmostSelect->into;
1928 intoColNames = leftmostSelect->intoColNames;
1930 /* clear them to prevent complaints in transformSetOperationTree() */
1931 leftmostSelect->into = NULL;
1932 leftmostSelect->intoColNames = NIL;
1935 * These are not one-time, exactly, but we want to process them here
1936 * and not let transformSetOperationTree() see them --- else it'll
1937 * just recurse right back here!
1939 sortClause = stmt->sortClause;
1940 limitOffset = stmt->limitOffset;
1941 limitCount = stmt->limitCount;
1942 lockingClause = stmt->lockingClause;
1944 stmt->sortClause = NIL;
1945 stmt->limitOffset = NULL;
1946 stmt->limitCount = NULL;
1947 stmt->lockingClause = NULL;
1949 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
1952 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1953 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
1956 * Recursively transform the components of the tree.
1958 sostmt = (SetOperationStmt *) transformSetOperationTree(pstate, stmt);
1959 Assert(sostmt && IsA(sostmt, SetOperationStmt));
1960 qry->setOperations = (Node *) sostmt;
1963 * Re-find leftmost SELECT (now it's a sub-query in rangetable)
1965 node = sostmt->larg;
1966 while (node && IsA(node, SetOperationStmt))
1967 node = ((SetOperationStmt *) node)->larg;
1968 Assert(node && IsA(node, RangeTblRef));
1969 leftmostRTI = ((RangeTblRef *) node)->rtindex;
1970 leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
1971 Assert(leftmostQuery != NULL);
1974 * Generate dummy targetlist for outer query using column names of
1975 * leftmost select and common datatypes of topmost set operation. Also
1976 * make lists of the dummy vars and their names for use in parsing
1979 * Note: we use leftmostRTI as the varno of the dummy variables. It
1980 * shouldn't matter too much which RT index they have, as long as they
1981 * have one that corresponds to a real RT entry; else funny things may
1982 * happen when the tree is mashed by rule rewriting.
1984 qry->targetList = NIL;
1987 left_tlist = list_head(leftmostQuery->targetList);
1989 foreach(dtlist, sostmt->colTypes)
1991 Oid colType = lfirst_oid(dtlist);
1992 TargetEntry *lefttle = (TargetEntry *) lfirst(left_tlist);
1997 Assert(!lefttle->resjunk);
1998 colName = pstrdup(lefttle->resname);
1999 expr = (Expr *) makeVar(leftmostRTI,
2004 tle = makeTargetEntry(expr,
2005 (AttrNumber) pstate->p_next_resno++,
2008 qry->targetList = lappend(qry->targetList, tle);
2009 targetvars = lappend(targetvars, expr);
2010 targetnames = lappend(targetnames, makeString(colName));
2011 left_tlist = lnext(left_tlist);
2015 * Handle SELECT INTO/CREATE TABLE AS.
2017 * Any column names from CREATE TABLE AS need to be attached to both the
2018 * top level and the leftmost subquery. We do not do this earlier
2019 * because we do *not* want the targetnames list to be affected.
2024 applyColumnNames(qry->targetList, intoColNames);
2025 applyColumnNames(leftmostQuery->targetList, intoColNames);
2029 * As a first step towards supporting sort clauses that are
2030 * expressions using the output columns, generate a varnamespace entry
2031 * that makes the output columns visible. A Join RTE node is handy
2032 * for this, since we can easily control the Vars generated upon
2035 * Note: we don't yet do anything useful with such cases, but at least
2036 * "ORDER BY upper(foo)" will draw the right error message rather than
2039 jrte = addRangeTableEntryForJoin(NULL,
2046 sv_rtable = pstate->p_rtable;
2047 pstate->p_rtable = list_make1(jrte);
2049 sv_relnamespace = pstate->p_relnamespace;
2050 pstate->p_relnamespace = NIL; /* no qualified names allowed */
2052 sv_varnamespace = pstate->p_varnamespace;
2053 pstate->p_varnamespace = list_make1(jrte);
2056 * For now, we don't support resjunk sort clauses on the output of a
2057 * setOperation tree --- you can only use the SQL92-spec options of
2058 * selecting an output column by name or number. Enforce by checking
2059 * that transformSortClause doesn't add any items to tlist.
2061 tllen = list_length(qry->targetList);
2063 qry->sortClause = transformSortClause(pstate,
2066 false /* no unknowns expected */ );
2068 pstate->p_rtable = sv_rtable;
2069 pstate->p_relnamespace = sv_relnamespace;
2070 pstate->p_varnamespace = sv_varnamespace;
2072 if (tllen != list_length(qry->targetList))
2074 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2075 errmsg("ORDER BY on a UNION/INTERSECT/EXCEPT result must be on one of the result columns")));
2077 qry->limitOffset = transformLimitClause(pstate, limitOffset,
2079 qry->limitCount = transformLimitClause(pstate, limitCount,
2082 qry->rtable = pstate->p_rtable;
2083 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
2085 qry->hasSubLinks = pstate->p_hasSubLinks;
2086 qry->hasAggs = pstate->p_hasAggs;
2087 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
2088 parseCheckAggregates(pstate, qry);
2091 transformLockingClause(qry, lockingClause);
2097 * transformSetOperationTree
2098 * Recursively transform leaves and internal nodes of a set-op tree
2101 transformSetOperationTree(ParseState *pstate, SelectStmt *stmt)
2105 Assert(stmt && IsA(stmt, SelectStmt));
2108 * Validity-check both leaf and internal SELECTs for disallowed ops.
2112 (errcode(ERRCODE_SYNTAX_ERROR),
2113 errmsg("INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT")));
2114 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
2115 if (stmt->lockingClause)
2117 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2118 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
2121 * If an internal node of a set-op tree has ORDER BY, UPDATE, or LIMIT
2122 * clauses attached, we need to treat it like a leaf node to generate
2123 * an independent sub-Query tree. Otherwise, it can be represented by
2124 * a SetOperationStmt node underneath the parent Query.
2126 if (stmt->op == SETOP_NONE)
2128 Assert(stmt->larg == NULL && stmt->rarg == NULL);
2133 Assert(stmt->larg != NULL && stmt->rarg != NULL);
2134 if (stmt->sortClause || stmt->limitOffset || stmt->limitCount ||
2135 stmt->lockingClause)
2143 /* Process leaf SELECT */
2146 char selectName[32];
2151 * Transform SelectStmt into a Query.
2153 * Note: previously transformed sub-queries don't affect the parsing
2154 * of this sub-query, because they are not in the toplevel
2155 * pstate's namespace list.
2157 selectList = parse_sub_analyze((Node *) stmt, pstate);
2159 Assert(list_length(selectList) == 1);
2160 selectQuery = (Query *) linitial(selectList);
2161 Assert(IsA(selectQuery, Query));
2164 * Check for bogus references to Vars on the current query level
2165 * (but upper-level references are okay). Normally this can't
2166 * happen because the namespace will be empty, but it could happen
2167 * if we are inside a rule.
2169 if (pstate->p_relnamespace || pstate->p_varnamespace)
2171 if (contain_vars_of_level((Node *) selectQuery, 1))
2173 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2174 errmsg("UNION/INTERSECT/EXCEPT member statement may not refer to other relations of same query level")));
2178 * Make the leaf query be a subquery in the top-level rangetable.
2180 snprintf(selectName, sizeof(selectName), "*SELECT* %d",
2181 list_length(pstate->p_rtable) + 1);
2182 rte = addRangeTableEntryForSubquery(pstate,
2184 makeAlias(selectName, NIL),
2188 * Return a RangeTblRef to replace the SelectStmt in the set-op
2191 rtr = makeNode(RangeTblRef);
2192 /* assume new rte is at end */
2193 rtr->rtindex = list_length(pstate->p_rtable);
2194 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
2195 return (Node *) rtr;
2199 /* Process an internal node (set operation node) */
2200 SetOperationStmt *op = makeNode(SetOperationStmt);
2205 const char *context;
2207 context = (stmt->op == SETOP_UNION ? "UNION" :
2208 (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
2212 op->all = stmt->all;
2215 * Recursively transform the child nodes.
2217 op->larg = transformSetOperationTree(pstate, stmt->larg);
2218 op->rarg = transformSetOperationTree(pstate, stmt->rarg);
2221 * Verify that the two children have the same number of non-junk
2222 * columns, and determine the types of the merged output columns.
2224 lcoltypes = getSetColTypes(pstate, op->larg);
2225 rcoltypes = getSetColTypes(pstate, op->rarg);
2226 if (list_length(lcoltypes) != list_length(rcoltypes))
2228 (errcode(ERRCODE_SYNTAX_ERROR),
2229 errmsg("each %s query must have the same number of columns",
2233 forboth(l, lcoltypes, r, rcoltypes)
2235 Oid lcoltype = lfirst_oid(l);
2236 Oid rcoltype = lfirst_oid(r);
2239 rescoltype = select_common_type(list_make2_oid(lcoltype, rcoltype),
2241 op->colTypes = lappend_oid(op->colTypes, rescoltype);
2250 * Get output column types of an (already transformed) set-op node
2253 getSetColTypes(ParseState *pstate, Node *node)
2255 if (IsA(node, RangeTblRef))
2257 RangeTblRef *rtr = (RangeTblRef *) node;
2258 RangeTblEntry *rte = rt_fetch(rtr->rtindex, pstate->p_rtable);
2259 Query *selectQuery = rte->subquery;
2263 Assert(selectQuery != NULL);
2264 /* Get types of non-junk columns */
2265 foreach(tl, selectQuery->targetList)
2267 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2271 result = lappend_oid(result, exprType((Node *) tle->expr));
2275 else if (IsA(node, SetOperationStmt))
2277 SetOperationStmt *op = (SetOperationStmt *) node;
2279 /* Result already computed during transformation of node */
2280 Assert(op->colTypes != NIL);
2281 return op->colTypes;
2285 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node));
2286 return NIL; /* keep compiler quiet */
2290 /* Attach column names from a ColumnDef list to a TargetEntry list */
2292 applyColumnNames(List *dst, List *src)
2297 if (list_length(src) > list_length(dst))
2299 (errcode(ERRCODE_SYNTAX_ERROR),
2300 errmsg("CREATE TABLE AS specifies too many column names")));
2302 forboth(dst_item, dst, src_item, src)
2304 TargetEntry *d = (TargetEntry *) lfirst(dst_item);
2305 ColumnDef *s = (ColumnDef *) lfirst(src_item);
2307 Assert(!d->resjunk);
2308 d->resname = pstrdup(s->colname);
2314 * transformUpdateStmt -
2315 * transforms an update statement
2318 transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
2320 Query *qry = makeNode(Query);
2322 ListCell *origTargetList;
2325 qry->commandType = CMD_UPDATE;
2326 pstate->p_is_update = true;
2328 qry->resultRelation = setTargetTable(pstate, stmt->relation,
2329 interpretInhOption(stmt->relation->inhOpt),
2334 * the FROM clause is non-standard SQL syntax. We used to be able to
2335 * do this with REPLACE in POSTQUEL so we keep the feature.
2337 transformFromClause(pstate, stmt->fromClause);
2339 qry->targetList = transformTargetList(pstate, stmt->targetList);
2341 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
2343 qry->rtable = pstate->p_rtable;
2344 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
2346 qry->hasSubLinks = pstate->p_hasSubLinks;
2347 qry->hasAggs = pstate->p_hasAggs;
2348 if (pstate->p_hasAggs)
2349 parseCheckAggregates(pstate, qry);
2352 * Now we are done with SELECT-like processing, and can get on with
2353 * transforming the target list to match the UPDATE target columns.
2356 /* Prepare to assign non-conflicting resnos to resjunk attributes */
2357 if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
2358 pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
2360 /* Prepare non-junk columns for assignment to target table */
2361 origTargetList = list_head(stmt->targetList);
2363 foreach(tl, qry->targetList)
2365 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2366 ResTarget *origTarget;
2371 * Resjunk nodes need no additional processing, but be sure
2372 * they have resnos that do not match any target columns; else
2373 * rewriter or planner might get confused. They don't need a
2376 tle->resno = (AttrNumber) pstate->p_next_resno++;
2377 tle->resname = NULL;
2380 if (origTargetList == NULL)
2381 elog(ERROR, "UPDATE target count mismatch --- internal error");
2382 origTarget = (ResTarget *) lfirst(origTargetList);
2383 Assert(IsA(origTarget, ResTarget));
2385 updateTargetListEntry(pstate, tle, origTarget->name,
2386 attnameAttNum(pstate->p_target_relation,
2387 origTarget->name, true),
2388 origTarget->indirection);
2390 origTargetList = lnext(origTargetList);
2392 if (origTargetList != NULL)
2393 elog(ERROR, "UPDATE target count mismatch --- internal error");
2399 * tranformAlterTableStmt -
2400 * transform an Alter Table Statement
2403 transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt,
2404 List **extras_before, List **extras_after)
2406 CreateStmtContext cxt;
2410 List *newcmds = NIL;
2411 bool skipValidation = true;
2412 AlterTableCmd *newcmd;
2414 cxt.stmtType = "ALTER TABLE";
2415 cxt.relation = stmt->relation;
2416 cxt.inhRelations = NIL;
2418 cxt.hasoids = false; /* need not be right */
2420 cxt.ckconstraints = NIL;
2421 cxt.fkconstraints = NIL;
2422 cxt.ixconstraints = NIL;
2428 * The only subtypes that currently require parse transformation
2429 * handling are ADD COLUMN and ADD CONSTRAINT. These largely re-use
2430 * code from CREATE TABLE.
2432 foreach(lcmd, stmt->cmds)
2434 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2436 switch (cmd->subtype)
2440 ColumnDef *def = (ColumnDef *) cmd->def;
2442 Assert(IsA(cmd->def, ColumnDef));
2443 transformColumnDefinition(pstate, &cxt,
2444 (ColumnDef *) cmd->def);
2447 * If the column has a non-null default, we can't skip
2448 * validation of foreign keys.
2450 if (((ColumnDef *) cmd->def)->raw_default != NULL)
2451 skipValidation = false;
2453 newcmds = lappend(newcmds, cmd);
2456 * Convert an ADD COLUMN ... NOT NULL constraint to a
2459 if (def->is_not_null)
2461 /* Remove NOT NULL from AddColumn */
2462 def->is_not_null = false;
2464 /* Add as a separate AlterTableCmd */
2465 newcmd = makeNode(AlterTableCmd);
2466 newcmd->subtype = AT_SetNotNull;
2467 newcmd->name = pstrdup(def->colname);
2468 newcmds = lappend(newcmds, newcmd);
2472 * All constraints are processed in other ways. Remove
2475 def->constraints = NIL;
2479 case AT_AddConstraint:
2482 * The original AddConstraint cmd node doesn't go to
2486 if (IsA(cmd->def, Constraint))
2487 transformTableConstraint(pstate, &cxt,
2488 (Constraint *) cmd->def);
2489 else if (IsA(cmd->def, FkConstraint))
2491 cxt.fkconstraints = lappend(cxt.fkconstraints, cmd->def);
2492 skipValidation = false;
2495 elog(ERROR, "unrecognized node type: %d",
2496 (int) nodeTag(cmd->def));
2499 case AT_ProcessedConstraint:
2502 * Already-transformed ADD CONSTRAINT, so just make it
2503 * look like the standard case.
2505 cmd->subtype = AT_AddConstraint;
2506 newcmds = lappend(newcmds, cmd);
2510 newcmds = lappend(newcmds, cmd);
2515 /* Postprocess index and FK constraints */
2516 transformIndexConstraints(pstate, &cxt);
2518 transformFKConstraints(pstate, &cxt, skipValidation, true);
2521 * Push any index-creation commands into the ALTER, so that they can
2522 * be scheduled nicely by tablecmds.c.
2524 foreach(l, cxt.alist)
2526 Node *idxstmt = (Node *) lfirst(l);
2528 Assert(IsA(idxstmt, IndexStmt));
2529 newcmd = makeNode(AlterTableCmd);
2530 newcmd->subtype = AT_AddIndex;
2531 newcmd->def = idxstmt;
2532 newcmds = lappend(newcmds, newcmd);
2536 /* Append any CHECK or FK constraints to the commands list */
2537 foreach(l, cxt.ckconstraints)
2539 newcmd = makeNode(AlterTableCmd);
2540 newcmd->subtype = AT_AddConstraint;
2541 newcmd->def = (Node *) lfirst(l);
2542 newcmds = lappend(newcmds, newcmd);
2544 foreach(l, cxt.fkconstraints)
2546 newcmd = makeNode(AlterTableCmd);
2547 newcmd->subtype = AT_AddConstraint;
2548 newcmd->def = (Node *) lfirst(l);
2549 newcmds = lappend(newcmds, newcmd);
2552 /* Update statement's commands list */
2553 stmt->cmds = newcmds;
2555 qry = makeNode(Query);
2556 qry->commandType = CMD_UTILITY;
2557 qry->utilityStmt = (Node *) stmt;
2559 *extras_before = list_concat(*extras_before, cxt.blist);
2560 *extras_after = list_concat(cxt.alist, *extras_after);
2566 transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
2568 Query *result = makeNode(Query);
2569 List *extras_before = NIL,
2570 *extras_after = NIL;
2572 result->commandType = CMD_UTILITY;
2573 result->utilityStmt = (Node *) stmt;
2576 * Don't allow both SCROLL and NO SCROLL to be specified
2578 if ((stmt->options & CURSOR_OPT_SCROLL) &&
2579 (stmt->options & CURSOR_OPT_NO_SCROLL))
2581 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
2582 errmsg("cannot specify both SCROLL and NO SCROLL")));
2584 stmt->query = (Node *) transformStmt(pstate, stmt->query,
2585 &extras_before, &extras_after);
2587 /* Shouldn't get any extras, since grammar only allows SelectStmt */
2588 if (extras_before || extras_after)
2589 elog(ERROR, "unexpected extra stuff in cursor statement");
2596 transformPrepareStmt(ParseState *pstate, PrepareStmt *stmt)
2598 Query *result = makeNode(Query);
2599 List *argtype_oids = NIL; /* argtype OIDs in a list */
2600 Oid *argtoids = NULL; /* and as an array */
2604 result->commandType = CMD_UTILITY;
2605 result->utilityStmt = (Node *) stmt;
2607 /* Transform list of TypeNames to list (and array) of type OIDs */
2608 nargs = list_length(stmt->argtypes);
2615 argtoids = (Oid *) palloc(nargs * sizeof(Oid));
2617 foreach(l, stmt->argtypes)
2619 TypeName *tn = lfirst(l);
2620 Oid toid = typenameTypeId(tn);
2622 argtype_oids = lappend_oid(argtype_oids, toid);
2623 argtoids[i++] = toid;
2627 stmt->argtype_oids = argtype_oids;
2630 * Analyze the statement using these parameter types (any parameters
2631 * passed in from above us will not be visible to it).
2633 queries = parse_analyze((Node *) stmt->query, argtoids, nargs);
2636 * Shouldn't get any extra statements, since grammar only allows
2639 if (list_length(queries) != 1)
2640 elog(ERROR, "unexpected extra stuff in prepared statement");
2642 stmt->query = linitial(queries);
2648 transformExecuteStmt(ParseState *pstate, ExecuteStmt *stmt)
2650 Query *result = makeNode(Query);
2653 result->commandType = CMD_UTILITY;
2654 result->utilityStmt = (Node *) stmt;
2656 paramtypes = FetchPreparedStatementParams(stmt->name);
2658 if (stmt->params || paramtypes)
2660 int nparams = list_length(stmt->params);
2661 int nexpected = list_length(paramtypes);
2666 if (nparams != nexpected)
2668 (errcode(ERRCODE_SYNTAX_ERROR),
2669 errmsg("wrong number of parameters for prepared statement \"%s\"",
2671 errdetail("Expected %d parameters but got %d.",
2672 nexpected, nparams)));
2674 forboth(l, stmt->params, l2, paramtypes)
2676 Node *expr = lfirst(l);
2677 Oid expected_type_id = lfirst_oid(l2);
2680 expr = transformExpr(pstate, expr);
2682 /* Cannot contain subselects or aggregates */
2683 if (pstate->p_hasSubLinks)
2685 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2686 errmsg("cannot use subquery in EXECUTE parameter")));
2687 if (pstate->p_hasAggs)
2689 (errcode(ERRCODE_GROUPING_ERROR),
2690 errmsg("cannot use aggregate function in EXECUTE parameter")));
2692 given_type_id = exprType(expr);
2694 expr = coerce_to_target_type(pstate, expr, given_type_id,
2695 expected_type_id, -1,
2696 COERCION_ASSIGNMENT,
2697 COERCE_IMPLICIT_CAST);
2701 (errcode(ERRCODE_DATATYPE_MISMATCH),
2702 errmsg("parameter $%d of type %s cannot be coerced to the expected type %s",
2704 format_type_be(given_type_id),
2705 format_type_be(expected_type_id)),
2706 errhint("You will need to rewrite or cast the expression.")));
2716 /* exported so planner can check again after rewriting, query pullup, etc */
2718 CheckSelectLocking(Query *qry, bool forUpdate)
2720 const char *operation;
2723 operation = "SELECT FOR UPDATE";
2725 operation = "SELECT FOR SHARE";
2727 if (qry->setOperations)
2729 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2730 /* translator: %s is a SQL command, like SELECT FOR UPDATE */
2731 errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT", operation)));
2732 if (qry->distinctClause != NIL)
2734 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2735 /* translator: %s is a SQL command, like SELECT FOR UPDATE */
2736 errmsg("%s is not allowed with DISTINCT clause", operation)));
2737 if (qry->groupClause != NIL)
2739 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2740 /* translator: %s is a SQL command, like SELECT FOR UPDATE */
2741 errmsg("%s is not allowed with GROUP BY clause", operation)));
2742 if (qry->havingQual != NULL)
2744 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2745 /* translator: %s is a SQL command, like SELECT FOR UPDATE */
2746 errmsg("%s is not allowed with HAVING clause", operation)));
2749 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2750 /* translator: %s is a SQL command, like SELECT FOR UPDATE */
2751 errmsg("%s is not allowed with aggregate functions", operation)));
2755 * Convert FOR UPDATE/SHARE name list into rowMarks list of integer relids
2757 * NB: if you need to change this, see also markQueryForLocking()
2758 * in rewriteHandler.c.
2761 transformLockingClause(Query *qry, LockingClause *lc)
2763 List *lockedRels = lc->lockedRels;
2768 LockingClause *allrels;
2772 if (lc->forUpdate != qry->forUpdate)
2774 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2775 errmsg("cannot use both FOR UPDATE and FOR SHARE in one query")));
2776 if (lc->nowait != qry->rowNoWait)
2778 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2779 errmsg("cannot use both wait and NOWAIT in one query")));
2781 qry->forUpdate = lc->forUpdate;
2782 qry->rowNoWait = lc->nowait;
2784 CheckSelectLocking(qry, lc->forUpdate);
2786 /* make a clause we can pass down to subqueries to select all rels */
2787 allrels = makeNode(LockingClause);
2788 allrels->lockedRels = NIL; /* indicates all rels */
2789 allrels->forUpdate = lc->forUpdate;
2790 allrels->nowait = lc->nowait;
2792 rowMarks = qry->rowMarks;
2794 if (lockedRels == NIL)
2796 /* all regular tables used in query */
2798 foreach(rt, qry->rtable)
2800 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2803 switch (rte->rtekind)
2806 /* use list_append_unique to avoid duplicates */
2807 rowMarks = list_append_unique_int(rowMarks, i);
2808 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
2813 * FOR UPDATE/SHARE of subquery is propagated to all
2814 * of subquery's rels
2816 transformLockingClause(rte->subquery, allrels);
2819 /* ignore JOIN, SPECIAL, FUNCTION RTEs */
2826 /* just the named tables */
2827 foreach(l, lockedRels)
2829 char *relname = strVal(lfirst(l));
2832 foreach(rt, qry->rtable)
2834 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2837 if (strcmp(rte->eref->aliasname, relname) == 0)
2839 switch (rte->rtekind)
2842 /* use list_append_unique to avoid duplicates */
2843 rowMarks = list_append_unique_int(rowMarks, i);
2844 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
2849 * FOR UPDATE/SHARE of subquery is propagated to
2850 * all of subquery's rels
2852 transformLockingClause(rte->subquery, allrels);
2856 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2857 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a join")));
2861 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2862 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to NEW or OLD")));
2866 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2867 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a function")));
2870 elog(ERROR, "unrecognized RTE type: %d",
2871 (int) rte->rtekind);
2874 break; /* out of foreach loop */
2879 (errcode(ERRCODE_UNDEFINED_TABLE),
2880 errmsg("relation \"%s\" in FOR UPDATE/SHARE clause not found in FROM clause",
2885 qry->rowMarks = rowMarks;
2890 * Preprocess a list of column constraint clauses
2891 * to attach constraint attributes to their primary constraint nodes
2892 * and detect inconsistent/misplaced constraint attributes.
2894 * NOTE: currently, attributes are only supported for FOREIGN KEY primary
2895 * constraints, but someday they ought to be supported for other constraints.
2898 transformConstraintAttrs(List *constraintList)
2900 Node *lastprimarynode = NULL;
2901 bool saw_deferrability = false;
2902 bool saw_initially = false;
2905 foreach(clist, constraintList)
2907 Node *node = lfirst(clist);
2909 if (!IsA(node, Constraint))
2911 lastprimarynode = node;
2912 /* reset flags for new primary node */
2913 saw_deferrability = false;
2914 saw_initially = false;
2918 Constraint *con = (Constraint *) node;
2920 switch (con->contype)
2922 case CONSTR_ATTR_DEFERRABLE:
2923 if (lastprimarynode == NULL ||
2924 !IsA(lastprimarynode, FkConstraint))
2926 (errcode(ERRCODE_SYNTAX_ERROR),
2927 errmsg("misplaced DEFERRABLE clause")));
2928 if (saw_deferrability)
2930 (errcode(ERRCODE_SYNTAX_ERROR),
2931 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
2932 saw_deferrability = true;
2933 ((FkConstraint *) lastprimarynode)->deferrable = true;
2935 case CONSTR_ATTR_NOT_DEFERRABLE:
2936 if (lastprimarynode == NULL ||
2937 !IsA(lastprimarynode, FkConstraint))
2939 (errcode(ERRCODE_SYNTAX_ERROR),
2940 errmsg("misplaced NOT DEFERRABLE clause")));
2941 if (saw_deferrability)
2943 (errcode(ERRCODE_SYNTAX_ERROR),
2944 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
2945 saw_deferrability = true;
2946 ((FkConstraint *) lastprimarynode)->deferrable = false;
2947 if (saw_initially &&
2948 ((FkConstraint *) lastprimarynode)->initdeferred)
2950 (errcode(ERRCODE_SYNTAX_ERROR),
2951 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
2953 case CONSTR_ATTR_DEFERRED:
2954 if (lastprimarynode == NULL ||
2955 !IsA(lastprimarynode, FkConstraint))
2957 (errcode(ERRCODE_SYNTAX_ERROR),
2958 errmsg("misplaced INITIALLY DEFERRED clause")));
2961 (errcode(ERRCODE_SYNTAX_ERROR),
2962 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
2963 saw_initially = true;
2964 ((FkConstraint *) lastprimarynode)->initdeferred = true;
2967 * If only INITIALLY DEFERRED appears, assume
2970 if (!saw_deferrability)
2971 ((FkConstraint *) lastprimarynode)->deferrable = true;
2972 else if (!((FkConstraint *) lastprimarynode)->deferrable)
2974 (errcode(ERRCODE_SYNTAX_ERROR),
2975 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
2977 case CONSTR_ATTR_IMMEDIATE:
2978 if (lastprimarynode == NULL ||
2979 !IsA(lastprimarynode, FkConstraint))
2981 (errcode(ERRCODE_SYNTAX_ERROR),
2982 errmsg("misplaced INITIALLY IMMEDIATE clause")));
2985 (errcode(ERRCODE_SYNTAX_ERROR),
2986 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
2987 saw_initially = true;
2988 ((FkConstraint *) lastprimarynode)->initdeferred = false;
2991 /* Otherwise it's not an attribute */
2992 lastprimarynode = node;
2993 /* reset flags for new primary node */
2994 saw_deferrability = false;
2995 saw_initially = false;
3002 /* Build a FromExpr node */
3004 makeFromExpr(List *fromlist, Node *quals)
3006 FromExpr *f = makeNode(FromExpr);
3008 f->fromlist = fromlist;
3014 * Special handling of type definition for a column
3017 transformColumnType(ParseState *pstate, ColumnDef *column)
3020 * All we really need to do here is verify that the type is valid.
3022 Type ctype = typenameType(column->typename);
3024 ReleaseSysCache(ctype);
3028 setSchemaName(char *context_schema, char **stmt_schema_name)
3030 if (*stmt_schema_name == NULL)
3031 *stmt_schema_name = context_schema;
3032 else if (strcmp(context_schema, *stmt_schema_name) != 0)
3034 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
3035 errmsg("CREATE specifies a schema (%s) "
3036 "different from the one being created (%s)",
3037 *stmt_schema_name, context_schema)));
3041 * analyzeCreateSchemaStmt -
3042 * analyzes the "create schema" statement
3044 * Split the schema element list into individual commands and place
3045 * them in the result list in an order such that there are no forward
3046 * references (e.g. GRANT to a table created later in the list). Note
3047 * that the logic we use for determining forward references is
3048 * presently quite incomplete.
3050 * SQL92 also allows constraints to make forward references, so thumb through
3051 * the table columns and move forward references to a posterior alter-table
3054 * The result is a list of parse nodes that still need to be analyzed ---
3055 * but we can't analyze the later commands until we've executed the earlier
3056 * ones, because of possible inter-object references.
3058 * Note: Called from commands/schemacmds.c
3061 analyzeCreateSchemaStmt(CreateSchemaStmt *stmt)
3063 CreateSchemaStmtContext cxt;
3067 cxt.stmtType = "CREATE SCHEMA";
3068 cxt.schemaname = stmt->schemaname;
3069 cxt.authid = stmt->authid;
3070 cxt.sequences = NIL;
3076 cxt.fwconstraints = NIL;
3082 * Run through each schema element in the schema element list.
3083 * Separate statements by type, and do preliminary analysis.
3085 foreach(elements, stmt->schemaElts)
3087 Node *element = lfirst(elements);
3089 switch (nodeTag(element))
3091 case T_CreateSeqStmt:
3093 CreateSeqStmt *elp = (CreateSeqStmt *) element;
3095 setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
3096 cxt.sequences = lappend(cxt.sequences, element);
3102 CreateStmt *elp = (CreateStmt *) element;
3104 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3107 * XXX todo: deal with constraints
3109 cxt.tables = lappend(cxt.tables, element);
3115 ViewStmt *elp = (ViewStmt *) element;
3117 setSchemaName(cxt.schemaname, &elp->view->schemaname);
3120 * XXX todo: deal with references between views
3122 cxt.views = lappend(cxt.views, element);
3128 IndexStmt *elp = (IndexStmt *) element;
3130 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3131 cxt.indexes = lappend(cxt.indexes, element);
3135 case T_CreateTrigStmt:
3137 CreateTrigStmt *elp = (CreateTrigStmt *) element;
3139 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3140 cxt.triggers = lappend(cxt.triggers, element);
3145 cxt.grants = lappend(cxt.grants, element);
3149 elog(ERROR, "unrecognized node type: %d",
3150 (int) nodeTag(element));
3155 result = list_concat(result, cxt.sequences);
3156 result = list_concat(result, cxt.tables);
3157 result = list_concat(result, cxt.views);
3158 result = list_concat(result, cxt.indexes);
3159 result = list_concat(result, cxt.triggers);
3160 result = list_concat(result, cxt.grants);
3166 * Traverse a fully-analyzed tree to verify that parameter symbols
3167 * match their types. We need this because some Params might still
3168 * be UNKNOWN, if there wasn't anything to force their coercion,
3169 * and yet other instances seen later might have gotten coerced.
3172 check_parameter_resolution_walker(Node *node,
3173 check_parameter_resolution_context *context)
3177 if (IsA(node, Param))
3179 Param *param = (Param *) node;
3181 if (param->paramkind == PARAM_NUM)
3183 int paramno = param->paramid;
3185 if (paramno <= 0 || /* shouldn't happen, but... */
3186 paramno > context->numParams)
3188 (errcode(ERRCODE_UNDEFINED_PARAMETER),
3189 errmsg("there is no parameter $%d", paramno)));
3191 if (param->paramtype != context->paramTypes[paramno - 1])
3193 (errcode(ERRCODE_AMBIGUOUS_PARAMETER),
3194 errmsg("could not determine data type of parameter $%d",
3199 if (IsA(node, Query))
3201 /* Recurse into RTE subquery or not-yet-planned sublink subquery */
3202 return query_tree_walker((Query *) node,
3203 check_parameter_resolution_walker,
3204 (void *) context, 0);
3206 return expression_tree_walker(node, check_parameter_resolution_walker,