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.321 2005/04/28 21:47:14 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 transformLocking(Query *qry, List *lockedRels, bool forUpdate);
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;
522 qry->commandType = CMD_INSERT;
523 pstate->p_is_insert = true;
526 * If a non-nil rangetable/namespace was passed in, and we are doing
527 * INSERT/SELECT, arrange to pass the rangetable/namespace down to the
528 * SELECT. This can only happen if we are inside a CREATE RULE, and
529 * in that case we want the rule's OLD and NEW rtable entries to
530 * appear as part of the SELECT's rtable, not as outer references for
531 * it. (Kluge!) The SELECT's joinlist is not affected however. We
532 * must do this before adding the target table to the INSERT's rtable.
534 if (stmt->selectStmt)
536 sub_rtable = pstate->p_rtable;
537 pstate->p_rtable = NIL;
538 sub_namespace = pstate->p_namespace;
539 pstate->p_namespace = NIL;
543 sub_rtable = NIL; /* not used, but keep compiler quiet */
548 * Must get write lock on INSERT target table before scanning SELECT,
549 * else we will grab the wrong kind of initial lock if the target
550 * table is also mentioned in the SELECT part. Note that the target
551 * table is not added to the joinlist or namespace.
553 qry->resultRelation = setTargetTable(pstate, stmt->relation,
554 false, false, ACL_INSERT);
557 * Is it INSERT ... SELECT or INSERT ... VALUES?
559 if (stmt->selectStmt)
562 * We make the sub-pstate a child of the outer pstate so that it
563 * can see any Param definitions supplied from above. Since the
564 * outer pstate's rtable and namespace are presently empty, there
565 * are no side-effects of exposing names the sub-SELECT shouldn't
568 ParseState *sub_pstate = make_parsestate(pstate);
573 * Process the source SELECT.
575 * It is important that this be handled just like a standalone
576 * SELECT; otherwise the behavior of SELECT within INSERT might be
577 * different from a stand-alone SELECT. (Indeed, Postgres up
578 * through 6.5 had bugs of just that nature...)
580 sub_pstate->p_rtable = sub_rtable;
581 sub_pstate->p_namespace = sub_namespace;
584 * Note: we are not expecting that extras_before and extras_after
585 * are going to be used by the transformation of the SELECT
588 selectQuery = transformStmt(sub_pstate, stmt->selectStmt,
589 extras_before, extras_after);
591 release_pstate_resources(sub_pstate);
594 Assert(IsA(selectQuery, Query));
595 Assert(selectQuery->commandType == CMD_SELECT);
596 if (selectQuery->into)
598 (errcode(ERRCODE_SYNTAX_ERROR),
599 errmsg("INSERT ... SELECT may not specify INTO")));
602 * Make the source be a subquery in the INSERT's rangetable, and
603 * add it to the INSERT's joinlist.
605 rte = addRangeTableEntryForSubquery(pstate,
607 makeAlias("*SELECT*", NIL),
609 rtr = makeNode(RangeTblRef);
610 /* assume new rte is at end */
611 rtr->rtindex = list_length(pstate->p_rtable);
612 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
613 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
616 * Generate a targetlist for the INSERT that selects all the
617 * non-resjunk columns from the subquery. (We need this to be
618 * separate from the subquery's tlist because we may add columns,
619 * insert datatype coercions, etc.)
621 * HACK: unknown-type constants and params in the SELECT's targetlist
622 * are copied up as-is rather than being referenced as subquery
623 * outputs. This is to ensure that when we try to coerce them to
624 * the target column's datatype, the right things happen (see
625 * special cases in coerce_type). Otherwise, this fails:
626 * INSERT INTO foo SELECT 'bar', ... FROM baz
629 qry->targetList = NIL;
630 foreach(tl, selectQuery->targetList)
632 TargetEntry *tle = (TargetEntry *) lfirst(tl);
638 (IsA(tle->expr, Const) || IsA(tle->expr, Param)) &&
639 exprType((Node *) tle->expr) == UNKNOWNOID)
642 expr = (Expr *) makeVar(rtr->rtindex,
644 exprType((Node *) tle->expr),
645 exprTypmod((Node *) tle->expr),
647 tle = makeTargetEntry(expr,
648 (AttrNumber) pstate->p_next_resno++,
651 qry->targetList = lappend(qry->targetList, tle);
657 * For INSERT ... VALUES, transform the given list of values to
658 * form a targetlist for the INSERT.
660 qry->targetList = transformTargetList(pstate, stmt->targetList);
664 * Now we are done with SELECT-like processing, and can get on with
665 * transforming the target list to match the INSERT target columns.
668 /* Prepare to assign non-conflicting resnos to resjunk attributes */
669 if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
670 pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
672 /* Validate stmt->cols list, or build default list if no list given */
673 icolumns = checkInsertTargets(pstate, stmt->cols, &attrnos);
676 * Prepare columns for assignment to target table.
678 icols = list_head(icolumns);
679 attnos = list_head(attrnos);
680 foreach(tl, qry->targetList)
682 TargetEntry *tle = (TargetEntry *) lfirst(tl);
685 if (icols == NULL || attnos == NULL)
687 (errcode(ERRCODE_SYNTAX_ERROR),
688 errmsg("INSERT has more expressions than target columns")));
690 col = (ResTarget *) lfirst(icols);
691 Assert(IsA(col, ResTarget));
693 Assert(!tle->resjunk);
694 updateTargetListEntry(pstate, tle, col->name, lfirst_int(attnos),
697 icols = lnext(icols);
698 attnos = lnext(attnos);
702 * Ensure that the targetlist has the same number of entries that were
703 * present in the columns list. Don't do the check unless an explicit
704 * columns list was given, though.
706 if (stmt->cols != NIL && (icols != NULL || attnos != NULL))
708 (errcode(ERRCODE_SYNTAX_ERROR),
709 errmsg("INSERT has more target columns than expressions")));
711 /* done building the range table and jointree */
712 qry->rtable = pstate->p_rtable;
713 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
715 qry->hasSubLinks = pstate->p_hasSubLinks;
716 qry->hasAggs = pstate->p_hasAggs;
717 if (pstate->p_hasAggs)
718 parseCheckAggregates(pstate, qry);
724 * transformCreateStmt -
725 * transforms the "create table" statement
726 * SQL92 allows constraints to be scattered all over, so thumb through
727 * the columns and collect all constraints into one place.
728 * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
729 * then expand those into multiple IndexStmt blocks.
730 * - thomas 1997-12-02
733 transformCreateStmt(ParseState *pstate, CreateStmt *stmt,
734 List **extras_before, List **extras_after)
736 CreateStmtContext cxt;
740 cxt.stmtType = "CREATE TABLE";
741 cxt.relation = stmt->relation;
742 cxt.inhRelations = stmt->inhRelations;
745 cxt.ckconstraints = NIL;
746 cxt.fkconstraints = NIL;
747 cxt.ixconstraints = NIL;
751 cxt.hasoids = interpretOidsOption(stmt->hasoids);
754 * Run through each primary element in the table creation clause.
755 * Separate column defs from constraints, and do preliminary analysis.
757 foreach(elements, stmt->tableElts)
759 Node *element = lfirst(elements);
761 switch (nodeTag(element))
764 transformColumnDefinition(pstate, &cxt,
765 (ColumnDef *) element);
769 transformTableConstraint(pstate, &cxt,
770 (Constraint *) element);
774 /* No pre-transformation needed */
775 cxt.fkconstraints = lappend(cxt.fkconstraints, element);
779 transformInhRelation(pstate, &cxt,
780 (InhRelation *) element);
784 elog(ERROR, "unrecognized node type: %d",
785 (int) nodeTag(element));
790 Assert(stmt->constraints == NIL);
793 * Postprocess constraints that give rise to index definitions.
795 transformIndexConstraints(pstate, &cxt);
798 * Postprocess foreign-key constraints.
800 transformFKConstraints(pstate, &cxt, true, false);
806 q->commandType = CMD_UTILITY;
807 q->utilityStmt = (Node *) stmt;
808 stmt->tableElts = cxt.columns;
809 stmt->constraints = cxt.ckconstraints;
810 *extras_before = list_concat(*extras_before, cxt.blist);
811 *extras_after = list_concat(cxt.alist, *extras_after);
817 transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
822 Constraint *constraint;
825 cxt->columns = lappend(cxt->columns, column);
827 /* Check for SERIAL pseudo-types */
829 if (list_length(column->typename->names) == 1)
831 char *typname = strVal(linitial(column->typename->names));
833 if (strcmp(typname, "serial") == 0 ||
834 strcmp(typname, "serial4") == 0)
837 column->typename->names = NIL;
838 column->typename->typeid = INT4OID;
840 else if (strcmp(typname, "bigserial") == 0 ||
841 strcmp(typname, "serial8") == 0)
844 column->typename->names = NIL;
845 column->typename->typeid = INT8OID;
849 /* Do necessary work on the column type declaration */
850 transformColumnType(pstate, column);
852 /* Special actions for SERIAL pseudo-types */
860 FuncCall *funccallnode;
861 CreateSeqStmt *seqstmt;
864 * Determine namespace and name to use for the sequence.
866 * Although we use ChooseRelationName, it's not guaranteed that the
867 * selected sequence name won't conflict; given sufficiently long
868 * field names, two different serial columns in the same table
869 * could be assigned the same sequence name, and we'd not notice
870 * since we aren't creating the sequence quite yet. In practice
871 * this seems quite unlikely to be a problem, especially since few
872 * people would need two serial columns in one table.
874 snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
875 snamespace = get_namespace_name(snamespaceid);
876 sname = ChooseRelationName(cxt->relation->relname,
882 (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
883 cxt->stmtType, sname,
884 cxt->relation->relname, column->colname)));
887 * Build a CREATE SEQUENCE command to create the sequence object,
888 * and add it to the list of things to be done before this
889 * CREATE/ALTER TABLE.
891 seqstmt = makeNode(CreateSeqStmt);
892 seqstmt->sequence = makeRangeVar(snamespace, sname);
893 seqstmt->options = NIL;
895 cxt->blist = lappend(cxt->blist, seqstmt);
898 * Mark the ColumnDef so that during execution, an appropriate
899 * dependency will be added from the sequence to the column.
901 column->support = makeRangeVar(snamespace, sname);
904 * Create appropriate constraints for SERIAL. We do this in full,
905 * rather than shortcutting, so that we will detect any
906 * conflicting constraints the user wrote (like a different
909 * Create an expression tree representing the function call
910 * nextval('"sequencename"')
912 qstring = quote_qualified_identifier(snamespace, sname);
913 snamenode = makeNode(A_Const);
914 snamenode->val.type = T_String;
915 snamenode->val.val.str = qstring;
916 funccallnode = makeNode(FuncCall);
917 funccallnode->funcname = SystemFuncName("nextval");
918 funccallnode->args = list_make1(snamenode);
919 funccallnode->agg_star = false;
920 funccallnode->agg_distinct = false;
922 constraint = makeNode(Constraint);
923 constraint->contype = CONSTR_DEFAULT;
924 constraint->raw_expr = (Node *) funccallnode;
925 constraint->cooked_expr = NULL;
926 constraint->keys = NIL;
927 column->constraints = lappend(column->constraints, constraint);
929 constraint = makeNode(Constraint);
930 constraint->contype = CONSTR_NOTNULL;
931 column->constraints = lappend(column->constraints, constraint);
934 /* Process column constraints, if any... */
935 transformConstraintAttrs(column->constraints);
937 saw_nullable = false;
939 foreach(clist, column->constraints)
941 constraint = lfirst(clist);
944 * If this column constraint is a FOREIGN KEY constraint, then we
945 * fill in the current attribute's name and throw it into the list
946 * of FK constraints to be processed later.
948 if (IsA(constraint, FkConstraint))
950 FkConstraint *fkconstraint = (FkConstraint *) constraint;
952 fkconstraint->fk_attrs = list_make1(makeString(column->colname));
953 cxt->fkconstraints = lappend(cxt->fkconstraints, fkconstraint);
957 Assert(IsA(constraint, Constraint));
959 switch (constraint->contype)
962 if (saw_nullable && column->is_not_null)
964 (errcode(ERRCODE_SYNTAX_ERROR),
965 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
966 column->colname, cxt->relation->relname)));
967 column->is_not_null = FALSE;
972 if (saw_nullable && !column->is_not_null)
974 (errcode(ERRCODE_SYNTAX_ERROR),
975 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
976 column->colname, cxt->relation->relname)));
977 column->is_not_null = TRUE;
982 if (column->raw_default != NULL)
984 (errcode(ERRCODE_SYNTAX_ERROR),
985 errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
986 column->colname, cxt->relation->relname)));
987 column->raw_default = constraint->raw_expr;
988 Assert(constraint->cooked_expr == NULL);
993 if (constraint->keys == NIL)
994 constraint->keys = list_make1(makeString(column->colname));
995 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
999 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
1002 case CONSTR_ATTR_DEFERRABLE:
1003 case CONSTR_ATTR_NOT_DEFERRABLE:
1004 case CONSTR_ATTR_DEFERRED:
1005 case CONSTR_ATTR_IMMEDIATE:
1006 /* transformConstraintAttrs took care of these */
1010 elog(ERROR, "unrecognized constraint type: %d",
1011 constraint->contype);
1018 transformTableConstraint(ParseState *pstate, CreateStmtContext *cxt,
1019 Constraint *constraint)
1021 switch (constraint->contype)
1023 case CONSTR_PRIMARY:
1025 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
1029 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
1033 case CONSTR_NOTNULL:
1034 case CONSTR_DEFAULT:
1035 case CONSTR_ATTR_DEFERRABLE:
1036 case CONSTR_ATTR_NOT_DEFERRABLE:
1037 case CONSTR_ATTR_DEFERRED:
1038 case CONSTR_ATTR_IMMEDIATE:
1039 elog(ERROR, "invalid context for constraint type %d",
1040 constraint->contype);
1044 elog(ERROR, "unrecognized constraint type: %d",
1045 constraint->contype);
1051 * transformInhRelation
1053 * Change the LIKE <subtable> portion of a CREATE TABLE statement into the
1054 * column definitions which recreate the user defined column portions of <subtable>.
1057 transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
1058 InhRelation *inhRelation)
1060 AttrNumber parent_attno;
1063 TupleDesc tupleDesc;
1064 TupleConstr *constr;
1065 AclResult aclresult;
1067 relation = heap_openrv(inhRelation->relation, AccessShareLock);
1069 if (relation->rd_rel->relkind != RELKIND_RELATION)
1071 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1072 errmsg("inherited relation \"%s\" is not a table",
1073 inhRelation->relation->relname)));
1076 * Check for SELECT privilages
1078 aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
1080 if (aclresult != ACLCHECK_OK)
1081 aclcheck_error(aclresult, ACL_KIND_CLASS,
1082 RelationGetRelationName(relation));
1084 tupleDesc = RelationGetDescr(relation);
1085 constr = tupleDesc->constr;
1088 * Insert the inherited attributes into the cxt for the new table
1091 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1094 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
1095 char *attributeName = NameStr(attribute->attname);
1100 * Ignore dropped columns in the parent.
1102 if (attribute->attisdropped)
1106 * Create a new inherited column.
1108 * For constraints, ONLY the NOT NULL constraint is inherited by the
1109 * new column definition per SQL99.
1111 def = makeNode(ColumnDef);
1112 def->colname = pstrdup(attributeName);
1113 typename = makeNode(TypeName);
1114 typename->typeid = attribute->atttypid;
1115 typename->typmod = attribute->atttypmod;
1116 def->typename = typename;
1118 def->is_local = false;
1119 def->is_not_null = attribute->attnotnull;
1120 def->raw_default = NULL;
1121 def->cooked_default = NULL;
1122 def->constraints = NIL;
1123 def->support = NULL;
1126 * Add to column list
1128 cxt->columns = lappend(cxt->columns, def);
1131 * Copy default if any, and the default has been requested
1133 if (attribute->atthasdef && inhRelation->including_defaults)
1135 char *this_default = NULL;
1136 AttrDefault *attrdef;
1139 /* Find default in constraint structure */
1140 Assert(constr != NULL);
1141 attrdef = constr->defval;
1142 for (i = 0; i < constr->num_defval; i++)
1144 if (attrdef[i].adnum == parent_attno)
1146 this_default = attrdef[i].adbin;
1150 Assert(this_default != NULL);
1153 * If default expr could contain any vars, we'd need to fix
1154 * 'em, but it can't; so default is ready to apply to child.
1157 def->cooked_default = pstrdup(this_default);
1162 * Close the parent rel, but keep our AccessShareLock on it until xact
1163 * commit. That will prevent someone else from deleting or ALTERing
1164 * the parent before the child is committed.
1166 heap_close(relation, NoLock);
1170 transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
1173 List *indexlist = NIL;
1178 * Run through the constraints that need to generate an index. For
1179 * PRIMARY KEY, mark each column as NOT NULL and create an index. For
1180 * UNIQUE, create an index as for PRIMARY KEY, but do not insist on
1183 foreach(listptr, cxt->ixconstraints)
1185 Constraint *constraint = lfirst(listptr);
1189 Assert(IsA(constraint, Constraint));
1190 Assert((constraint->contype == CONSTR_PRIMARY)
1191 || (constraint->contype == CONSTR_UNIQUE));
1193 index = makeNode(IndexStmt);
1195 index->unique = true;
1196 index->primary = (constraint->contype == CONSTR_PRIMARY);
1199 if (cxt->pkey != NULL)
1201 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1202 errmsg("multiple primary keys for table \"%s\" are not allowed",
1203 cxt->relation->relname)));
1207 * In ALTER TABLE case, a primary index might already exist,
1208 * but DefineIndex will check for it.
1211 index->isconstraint = true;
1213 if (constraint->name != NULL)
1214 index->idxname = pstrdup(constraint->name);
1216 index->idxname = NULL; /* DefineIndex will choose name */
1218 index->relation = cxt->relation;
1219 index->accessMethod = DEFAULT_INDEX_TYPE;
1220 index->tableSpace = constraint->indexspace;
1221 index->indexParams = NIL;
1222 index->whereClause = NULL;
1225 * Make sure referenced keys exist. If we are making a PRIMARY
1226 * KEY index, also make sure they are NOT NULL, if possible.
1227 * (Although we could leave it to DefineIndex to mark the columns
1228 * NOT NULL, it's more efficient to get it right the first time.)
1230 foreach(keys, constraint->keys)
1232 char *key = strVal(lfirst(keys));
1234 ColumnDef *column = NULL;
1237 foreach(columns, cxt->columns)
1239 column = (ColumnDef *) lfirst(columns);
1240 Assert(IsA(column, ColumnDef));
1241 if (strcmp(column->colname, key) == 0)
1249 /* found column in the new table; force it to be NOT NULL */
1250 if (constraint->contype == CONSTR_PRIMARY)
1251 column->is_not_null = TRUE;
1253 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1256 * column will be a system column in the new table, so
1257 * accept it. System columns can't ever be null, so no
1258 * need to worry about PRIMARY/NOT NULL constraint.
1262 else if (cxt->inhRelations)
1264 /* try inherited tables */
1267 foreach(inher, cxt->inhRelations)
1269 RangeVar *inh = (RangeVar *) lfirst(inher);
1273 Assert(IsA(inh, RangeVar));
1274 rel = heap_openrv(inh, AccessShareLock);
1275 if (rel->rd_rel->relkind != RELKIND_RELATION)
1277 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1278 errmsg("inherited relation \"%s\" is not a table",
1280 for (count = 0; count < rel->rd_att->natts; count++)
1282 Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1283 char *inhname = NameStr(inhattr->attname);
1285 if (inhattr->attisdropped)
1287 if (strcmp(key, inhname) == 0)
1292 * We currently have no easy way to force an
1293 * inherited column to be NOT NULL at
1294 * creation, if its parent wasn't so already.
1295 * We leave it to DefineIndex to fix things up
1301 heap_close(rel, NoLock);
1308 * In the ALTER TABLE case, don't complain about index keys
1309 * not created in the command; they may well exist already.
1310 * DefineIndex will complain about them if not, and will also
1311 * take care of marking them NOT NULL.
1313 if (!found && !cxt->isalter)
1315 (errcode(ERRCODE_UNDEFINED_COLUMN),
1316 errmsg("column \"%s\" named in key does not exist",
1319 /* Check for PRIMARY KEY(foo, foo) */
1320 foreach(columns, index->indexParams)
1322 iparam = (IndexElem *) lfirst(columns);
1323 if (iparam->name && strcmp(key, iparam->name) == 0)
1327 (errcode(ERRCODE_DUPLICATE_COLUMN),
1328 errmsg("column \"%s\" appears twice in primary key constraint",
1332 (errcode(ERRCODE_DUPLICATE_COLUMN),
1333 errmsg("column \"%s\" appears twice in unique constraint",
1338 /* OK, add it to the index definition */
1339 iparam = makeNode(IndexElem);
1340 iparam->name = pstrdup(key);
1341 iparam->expr = NULL;
1342 iparam->opclass = NIL;
1343 index->indexParams = lappend(index->indexParams, iparam);
1346 indexlist = lappend(indexlist, index);
1350 * Scan the index list and remove any redundant index specifications.
1351 * This can happen if, for instance, the user writes UNIQUE PRIMARY
1352 * KEY. A strict reading of SQL92 would suggest raising an error
1353 * instead, but that strikes me as too anal-retentive. - tgl
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
1426 * ADD CONSTRAINT command to execute after the basic command is
1427 * complete. (If called from ADD CONSTRAINT, that routine will add the
1428 * FK constraints to 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
1477 * can refer to its fields without qualification. Note that this
1478 * only works if the parent table already exists --- so we can't
1479 * easily support predicates on indexes created implicitly by
1480 * CREATE TABLE. Fortunately, that's not necessary.
1482 rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1484 /* no to join list, yes to namespace */
1485 addRTEtoQuery(pstate, rte, false, 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 namespace */
1504 addRTEtoQuery(pstate, rte, false, true);
1506 ielem->expr = transformExpr(pstate, ielem->expr);
1509 * We check only that the result type is legitimate; this is
1510 * for consistency with what transformWhereClause() checks for
1511 * the 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
1556 * 2. Set up their RTEs in the main pstate for use in parsing the
1557 * rule qualification.
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
1572 * the one(s) that are relevant for the current kind of rule. In an
1573 * UPDATE rule, quals must refer to OLD.field or NEW.field to be
1574 * unambiguous, but there's no need to be so picky for INSERT &
1575 * DELETE. (Note we marked the RTEs "inFromCl = true" above to allow
1576 * unqualified references to their fields.) We do not add them to the
1579 switch (stmt->event)
1582 addRTEtoQuery(pstate, oldrte, false, true);
1585 addRTEtoQuery(pstate, oldrte, false, true);
1586 addRTEtoQuery(pstate, newrte, false, true);
1589 addRTEtoQuery(pstate, newrte, false, true);
1592 addRTEtoQuery(pstate, oldrte, false, true);
1595 elog(ERROR, "unrecognized event type: %d",
1600 /* take care of the where clause */
1601 stmt->whereClause = transformWhereClause(pstate, stmt->whereClause,
1604 if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
1606 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1607 errmsg("rule WHERE condition may not contain references to other relations")));
1609 /* aggregates not allowed (but subselects are okay) */
1610 if (pstate->p_hasAggs)
1612 (errcode(ERRCODE_GROUPING_ERROR),
1613 errmsg("rule WHERE condition may not contain aggregate functions")));
1615 /* save info about sublinks in where clause */
1616 qry->hasSubLinks = pstate->p_hasSubLinks;
1619 * 'instead nothing' rules with a qualification need a query
1620 * rangetable so the rewrite handler can add the negated rule
1621 * qualification to the original query. We create a query with the new
1622 * command type CMD_NOTHING here that is treated specially by the
1625 if (stmt->actions == NIL)
1627 Query *nothing_qry = makeNode(Query);
1629 nothing_qry->commandType = CMD_NOTHING;
1630 nothing_qry->rtable = pstate->p_rtable;
1631 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
1633 stmt->actions = list_make1(nothing_qry);
1638 List *newactions = NIL;
1641 * transform each statement, like parse_sub_analyze()
1643 foreach(l, stmt->actions)
1645 Node *action = (Node *) lfirst(l);
1646 ParseState *sub_pstate = make_parsestate(pstate->parentParseState);
1653 * Set up OLD/NEW in the rtable for this statement. The
1654 * entries are marked not inFromCl because we don't want them
1655 * to be referred to by unqualified field names nor "*" in the
1656 * rule actions. We must add them to the namespace, however,
1657 * or they won't be accessible at all. We decide later
1658 * whether to put them in the joinlist.
1660 oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
1661 makeAlias("*OLD*", NIL),
1663 newrte = addRangeTableEntryForRelation(sub_pstate, rel,
1664 makeAlias("*NEW*", NIL),
1666 oldrte->requiredPerms = 0;
1667 newrte->requiredPerms = 0;
1668 addRTEtoQuery(sub_pstate, oldrte, false, true);
1669 addRTEtoQuery(sub_pstate, newrte, false, true);
1671 /* Transform the rule action statement */
1672 top_subqry = transformStmt(sub_pstate, action,
1673 extras_before, extras_after);
1676 * We cannot support utility-statement actions (eg NOTIFY)
1677 * with nonempty rule WHERE conditions, because there's no way
1678 * to make the utility action execute conditionally.
1680 if (top_subqry->commandType == CMD_UTILITY &&
1681 stmt->whereClause != NULL)
1683 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1684 errmsg("rules with WHERE conditions may only have SELECT, INSERT, UPDATE, or DELETE actions")));
1687 * If the action is INSERT...SELECT, OLD/NEW have been pushed
1688 * down into the SELECT, and that's what we need to look at.
1689 * (Ugly kluge ... try to fix this when we redesign
1692 sub_qry = getInsertSelectQuery(top_subqry, NULL);
1695 * If the sub_qry is a setop, we cannot attach any
1696 * qualifications to it, because the planner won't notice
1697 * them. This could perhaps be relaxed someday, but for now,
1698 * we may as well reject such a rule immediately.
1700 if (sub_qry->setOperations != NULL && stmt->whereClause != NULL)
1702 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1703 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1706 * Validate action's use of OLD/NEW, qual too
1709 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
1710 rangeTableEntry_used(stmt->whereClause, PRS2_OLD_VARNO, 0);
1712 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
1713 rangeTableEntry_used(stmt->whereClause, PRS2_NEW_VARNO, 0);
1715 switch (stmt->event)
1720 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1721 errmsg("ON SELECT rule may not use OLD")));
1724 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1725 errmsg("ON SELECT rule may not use NEW")));
1733 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1734 errmsg("ON INSERT rule may not use OLD")));
1739 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1740 errmsg("ON DELETE rule may not use NEW")));
1743 elog(ERROR, "unrecognized event type: %d",
1749 * For efficiency's sake, add OLD to the rule action's
1750 * jointree only if it was actually referenced in the
1751 * statement or qual.
1753 * For INSERT, NEW is not really a relation (only a reference to
1754 * the to-be-inserted tuple) and should never be added to the
1757 * For UPDATE, we treat NEW as being another kind of reference to
1758 * OLD, because it represents references to *transformed*
1759 * tuples of the existing relation. It would be wrong to
1760 * enter NEW separately in the jointree, since that would
1761 * cause a double join of the updated relation. It's also
1762 * wrong to fail to make a jointree entry if only NEW and not
1765 if (has_old || (has_new && stmt->event == CMD_UPDATE))
1768 * If sub_qry is a setop, manipulating its jointree will
1769 * do no good at all, because the jointree is dummy. (This
1770 * should be a can't-happen case because of prior tests.)
1772 if (sub_qry->setOperations != NULL)
1774 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1775 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1776 /* hack so we can use addRTEtoQuery() */
1777 sub_pstate->p_rtable = sub_qry->rtable;
1778 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
1779 addRTEtoQuery(sub_pstate, oldrte, true, false);
1780 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
1783 newactions = lappend(newactions, top_subqry);
1785 release_pstate_resources(sub_pstate);
1789 stmt->actions = newactions;
1792 /* Close relation, but keep the exclusive lock */
1793 heap_close(rel, NoLock);
1800 * transformSelectStmt -
1801 * transforms a Select Statement
1803 * Note: this is also used for DECLARE CURSOR statements.
1806 transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
1808 Query *qry = makeNode(Query);
1811 qry->commandType = CMD_SELECT;
1813 /* make FOR UPDATE/FOR SHARE list available to addRangeTableEntry */
1814 pstate->p_lockedRels = stmt->lockedRels;
1816 /* process the FROM clause */
1817 transformFromClause(pstate, stmt->fromClause);
1819 /* transform targetlist */
1820 qry->targetList = transformTargetList(pstate, stmt->targetList);
1822 /* handle any SELECT INTO/CREATE TABLE AS spec */
1823 qry->into = stmt->into;
1824 if (stmt->intoColNames)
1825 applyColumnNames(qry->targetList, stmt->intoColNames);
1827 qry->intoHasOids = interpretOidsOption(stmt->intoHasOids);
1829 /* mark column origins */
1830 markTargetListOrigins(pstate, qry->targetList);
1832 /* transform WHERE */
1833 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
1836 * Initial processing of HAVING clause is just like WHERE clause.
1838 qry->havingQual = transformWhereClause(pstate, stmt->havingClause,
1842 * Transform sorting/grouping stuff. Do ORDER BY first because both
1843 * transformGroupClause and transformDistinctClause need the results.
1845 qry->sortClause = transformSortClause(pstate,
1848 true /* fix unknowns */ );
1850 qry->groupClause = transformGroupClause(pstate,
1855 qry->distinctClause = transformDistinctClause(pstate,
1856 stmt->distinctClause,
1860 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
1862 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
1865 qry->rtable = pstate->p_rtable;
1866 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
1868 qry->hasSubLinks = pstate->p_hasSubLinks;
1869 qry->hasAggs = pstate->p_hasAggs;
1870 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
1871 parseCheckAggregates(pstate, qry);
1873 if (stmt->lockedRels != NIL)
1874 transformLocking(qry, stmt->lockedRels, stmt->forUpdate);
1880 * transformSetOperationsStmt -
1881 * transforms a set-operations tree
1883 * A set-operation tree is just a SELECT, but with UNION/INTERSECT/EXCEPT
1884 * structure to it. We must transform each leaf SELECT and build up a top-
1885 * level Query that contains the leaf SELECTs as subqueries in its rangetable.
1886 * The tree of set operations is converted into the setOperations field of
1887 * the top-level Query.
1890 transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
1892 Query *qry = makeNode(Query);
1893 SelectStmt *leftmostSelect;
1895 Query *leftmostQuery;
1896 SetOperationStmt *sostmt;
1905 ListCell *left_tlist,
1911 RangeTblEntry *jrte;
1915 qry->commandType = CMD_SELECT;
1918 * Find leftmost leaf SelectStmt; extract the one-time-only items from
1919 * it and from the top-level node.
1921 leftmostSelect = stmt->larg;
1922 while (leftmostSelect && leftmostSelect->op != SETOP_NONE)
1923 leftmostSelect = leftmostSelect->larg;
1924 Assert(leftmostSelect && IsA(leftmostSelect, SelectStmt) &&
1925 leftmostSelect->larg == NULL);
1926 into = leftmostSelect->into;
1927 intoColNames = leftmostSelect->intoColNames;
1929 /* clear them to prevent complaints in transformSetOperationTree() */
1930 leftmostSelect->into = NULL;
1931 leftmostSelect->intoColNames = NIL;
1934 * These are not one-time, exactly, but we want to process them here
1935 * and not let transformSetOperationTree() see them --- else it'll
1936 * just recurse right back here!
1938 sortClause = stmt->sortClause;
1939 limitOffset = stmt->limitOffset;
1940 limitCount = stmt->limitCount;
1941 lockedRels = stmt->lockedRels;
1942 forUpdate = stmt->forUpdate;
1944 stmt->sortClause = NIL;
1945 stmt->limitOffset = NULL;
1946 stmt->limitCount = NULL;
1947 stmt->lockedRels = NIL;
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 namespace 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,
2045 jrtr = makeNode(RangeTblRef);
2046 jrtr->rtindex = 1; /* only entry in dummy rtable */
2048 sv_rtable = pstate->p_rtable;
2049 pstate->p_rtable = list_make1(jrte);
2051 sv_namespace = pstate->p_namespace;
2052 pstate->p_namespace = list_make1(jrtr);
2055 * For now, we don't support resjunk sort clauses on the output of a
2056 * setOperation tree --- you can only use the SQL92-spec options of
2057 * selecting an output column by name or number. Enforce by checking
2058 * that transformSortClause doesn't add any items to tlist.
2060 tllen = list_length(qry->targetList);
2062 qry->sortClause = transformSortClause(pstate,
2065 false /* no unknowns expected */ );
2067 pstate->p_namespace = sv_namespace;
2068 pstate->p_rtable = sv_rtable;
2070 if (tllen != list_length(qry->targetList))
2072 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2073 errmsg("ORDER BY on a UNION/INTERSECT/EXCEPT result must be on one of the result columns")));
2075 qry->limitOffset = transformLimitClause(pstate, limitOffset,
2077 qry->limitCount = transformLimitClause(pstate, limitCount,
2080 qry->rtable = pstate->p_rtable;
2081 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
2083 qry->hasSubLinks = pstate->p_hasSubLinks;
2084 qry->hasAggs = pstate->p_hasAggs;
2085 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
2086 parseCheckAggregates(pstate, qry);
2088 if (lockedRels != NIL)
2089 transformLocking(qry, lockedRels, forUpdate);
2095 * transformSetOperationTree
2096 * Recursively transform leaves and internal nodes of a set-op tree
2099 transformSetOperationTree(ParseState *pstate, SelectStmt *stmt)
2103 Assert(stmt && IsA(stmt, SelectStmt));
2106 * Validity-check both leaf and internal SELECTs for disallowed ops.
2110 (errcode(ERRCODE_SYNTAX_ERROR),
2111 errmsg("INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT")));
2112 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
2113 if (stmt->lockedRels)
2115 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2116 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
2119 * If an internal node of a set-op tree has ORDER BY, UPDATE, or LIMIT
2120 * clauses attached, we need to treat it like a leaf node to generate
2121 * an independent sub-Query tree. Otherwise, it can be represented by
2122 * a SetOperationStmt node underneath the parent Query.
2124 if (stmt->op == SETOP_NONE)
2126 Assert(stmt->larg == NULL && stmt->rarg == NULL);
2131 Assert(stmt->larg != NULL && stmt->rarg != NULL);
2132 if (stmt->sortClause || stmt->limitOffset || stmt->limitCount ||
2141 /* Process leaf SELECT */
2144 char selectName[32];
2149 * Transform SelectStmt into a Query.
2151 * Note: previously transformed sub-queries don't affect the parsing
2152 * of this sub-query, because they are not in the toplevel
2153 * pstate's namespace list.
2155 selectList = parse_sub_analyze((Node *) stmt, pstate);
2157 Assert(list_length(selectList) == 1);
2158 selectQuery = (Query *) linitial(selectList);
2159 Assert(IsA(selectQuery, Query));
2162 * Check for bogus references to Vars on the current query level
2163 * (but upper-level references are okay). Normally this can't
2164 * happen because the namespace will be empty, but it could happen
2165 * if we are inside a rule.
2167 if (pstate->p_namespace)
2169 if (contain_vars_of_level((Node *) selectQuery, 1))
2171 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2172 errmsg("UNION/INTERSECT/EXCEPT member statement may not refer to other relations of same query level")));
2176 * Make the leaf query be a subquery in the top-level rangetable.
2178 snprintf(selectName, sizeof(selectName), "*SELECT* %d",
2179 list_length(pstate->p_rtable) + 1);
2180 rte = addRangeTableEntryForSubquery(pstate,
2182 makeAlias(selectName, NIL),
2186 * Return a RangeTblRef to replace the SelectStmt in the set-op
2189 rtr = makeNode(RangeTblRef);
2190 /* assume new rte is at end */
2191 rtr->rtindex = list_length(pstate->p_rtable);
2192 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
2193 return (Node *) rtr;
2197 /* Process an internal node (set operation node) */
2198 SetOperationStmt *op = makeNode(SetOperationStmt);
2203 const char *context;
2205 context = (stmt->op == SETOP_UNION ? "UNION" :
2206 (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
2210 op->all = stmt->all;
2213 * Recursively transform the child nodes.
2215 op->larg = transformSetOperationTree(pstate, stmt->larg);
2216 op->rarg = transformSetOperationTree(pstate, stmt->rarg);
2219 * Verify that the two children have the same number of non-junk
2220 * columns, and determine the types of the merged output columns.
2222 lcoltypes = getSetColTypes(pstate, op->larg);
2223 rcoltypes = getSetColTypes(pstate, op->rarg);
2224 if (list_length(lcoltypes) != list_length(rcoltypes))
2226 (errcode(ERRCODE_SYNTAX_ERROR),
2227 errmsg("each %s query must have the same number of columns",
2231 forboth(l, lcoltypes, r, rcoltypes)
2233 Oid lcoltype = lfirst_oid(l);
2234 Oid rcoltype = lfirst_oid(r);
2237 rescoltype = select_common_type(list_make2_oid(lcoltype, rcoltype),
2239 op->colTypes = lappend_oid(op->colTypes, rescoltype);
2248 * Get output column types of an (already transformed) set-op node
2251 getSetColTypes(ParseState *pstate, Node *node)
2253 if (IsA(node, RangeTblRef))
2255 RangeTblRef *rtr = (RangeTblRef *) node;
2256 RangeTblEntry *rte = rt_fetch(rtr->rtindex, pstate->p_rtable);
2257 Query *selectQuery = rte->subquery;
2261 Assert(selectQuery != NULL);
2262 /* Get types of non-junk columns */
2263 foreach(tl, selectQuery->targetList)
2265 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2269 result = lappend_oid(result, exprType((Node *) tle->expr));
2273 else if (IsA(node, SetOperationStmt))
2275 SetOperationStmt *op = (SetOperationStmt *) node;
2277 /* Result already computed during transformation of node */
2278 Assert(op->colTypes != NIL);
2279 return op->colTypes;
2283 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node));
2284 return NIL; /* keep compiler quiet */
2288 /* Attach column names from a ColumnDef list to a TargetEntry list */
2290 applyColumnNames(List *dst, List *src)
2295 if (list_length(src) > list_length(dst))
2297 (errcode(ERRCODE_SYNTAX_ERROR),
2298 errmsg("CREATE TABLE AS specifies too many column names")));
2300 forboth(dst_item, dst, src_item, src)
2302 TargetEntry *d = (TargetEntry *) lfirst(dst_item);
2303 ColumnDef *s = (ColumnDef *) lfirst(src_item);
2305 Assert(!d->resjunk);
2306 d->resname = pstrdup(s->colname);
2312 * transformUpdateStmt -
2313 * transforms an update statement
2316 transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
2318 Query *qry = makeNode(Query);
2320 ListCell *origTargetList;
2323 qry->commandType = CMD_UPDATE;
2324 pstate->p_is_update = true;
2326 qry->resultRelation = setTargetTable(pstate, stmt->relation,
2327 interpretInhOption(stmt->relation->inhOpt),
2332 * the FROM clause is non-standard SQL syntax. We used to be able to
2333 * do this with REPLACE in POSTQUEL so we keep the feature.
2335 transformFromClause(pstate, stmt->fromClause);
2337 qry->targetList = transformTargetList(pstate, stmt->targetList);
2339 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
2341 qry->rtable = pstate->p_rtable;
2342 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
2344 qry->hasSubLinks = pstate->p_hasSubLinks;
2345 qry->hasAggs = pstate->p_hasAggs;
2346 if (pstate->p_hasAggs)
2347 parseCheckAggregates(pstate, qry);
2350 * Now we are done with SELECT-like processing, and can get on with
2351 * transforming the target list to match the UPDATE target columns.
2354 /* Prepare to assign non-conflicting resnos to resjunk attributes */
2355 if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
2356 pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
2358 /* Prepare non-junk columns for assignment to target table */
2359 origTargetList = list_head(stmt->targetList);
2361 foreach(tl, qry->targetList)
2363 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2364 ResTarget *origTarget;
2369 * Resjunk nodes need no additional processing, but be sure
2370 * they have resnos that do not match any target columns; else
2371 * rewriter or planner might get confused. They don't need a
2374 tle->resno = (AttrNumber) pstate->p_next_resno++;
2375 tle->resname = NULL;
2378 if (origTargetList == NULL)
2379 elog(ERROR, "UPDATE target count mismatch --- internal error");
2380 origTarget = (ResTarget *) lfirst(origTargetList);
2381 Assert(IsA(origTarget, ResTarget));
2383 updateTargetListEntry(pstate, tle, origTarget->name,
2384 attnameAttNum(pstate->p_target_relation,
2385 origTarget->name, true),
2386 origTarget->indirection);
2388 origTargetList = lnext(origTargetList);
2390 if (origTargetList != NULL)
2391 elog(ERROR, "UPDATE target count mismatch --- internal error");
2397 * tranformAlterTableStmt -
2398 * transform an Alter Table Statement
2401 transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt,
2402 List **extras_before, List **extras_after)
2404 CreateStmtContext cxt;
2408 List *newcmds = NIL;
2409 bool skipValidation = true;
2410 AlterTableCmd *newcmd;
2412 cxt.stmtType = "ALTER TABLE";
2413 cxt.relation = stmt->relation;
2414 cxt.inhRelations = NIL;
2416 cxt.hasoids = false; /* need not be right */
2418 cxt.ckconstraints = NIL;
2419 cxt.fkconstraints = NIL;
2420 cxt.ixconstraints = NIL;
2426 * The only subtypes that currently require parse transformation
2427 * handling are ADD COLUMN and ADD CONSTRAINT. These largely re-use
2428 * code from CREATE TABLE.
2430 foreach(lcmd, stmt->cmds)
2432 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2434 switch (cmd->subtype)
2438 ColumnDef *def = (ColumnDef *) cmd->def;
2440 Assert(IsA(cmd->def, ColumnDef));
2441 transformColumnDefinition(pstate, &cxt,
2442 (ColumnDef *) cmd->def);
2445 * If the column has a non-null default, we can't skip
2446 * validation of foreign keys.
2448 if (((ColumnDef *) cmd->def)->raw_default != NULL)
2449 skipValidation = false;
2451 newcmds = lappend(newcmds, cmd);
2454 * Convert an ADD COLUMN ... NOT NULL constraint to a
2457 if (def->is_not_null)
2459 /* Remove NOT NULL from AddColumn */
2460 def->is_not_null = false;
2462 /* Add as a separate AlterTableCmd */
2463 newcmd = makeNode(AlterTableCmd);
2464 newcmd->subtype = AT_SetNotNull;
2465 newcmd->name = pstrdup(def->colname);
2466 newcmds = lappend(newcmds, newcmd);
2470 * All constraints are processed in other ways. Remove
2473 def->constraints = NIL;
2477 case AT_AddConstraint:
2480 * The original AddConstraint cmd node doesn't go to
2484 if (IsA(cmd->def, Constraint))
2485 transformTableConstraint(pstate, &cxt,
2486 (Constraint *) cmd->def);
2487 else if (IsA(cmd->def, FkConstraint))
2489 cxt.fkconstraints = lappend(cxt.fkconstraints, cmd->def);
2490 skipValidation = false;
2493 elog(ERROR, "unrecognized node type: %d",
2494 (int) nodeTag(cmd->def));
2497 case AT_ProcessedConstraint:
2500 * Already-transformed ADD CONSTRAINT, so just make it
2501 * look like the standard case.
2503 cmd->subtype = AT_AddConstraint;
2504 newcmds = lappend(newcmds, cmd);
2508 newcmds = lappend(newcmds, cmd);
2513 /* Postprocess index and FK constraints */
2514 transformIndexConstraints(pstate, &cxt);
2516 transformFKConstraints(pstate, &cxt, skipValidation, true);
2519 * Push any index-creation commands into the ALTER, so that they can
2520 * be scheduled nicely by tablecmds.c.
2522 foreach(l, cxt.alist)
2524 Node *idxstmt = (Node *) lfirst(l);
2526 Assert(IsA(idxstmt, IndexStmt));
2527 newcmd = makeNode(AlterTableCmd);
2528 newcmd->subtype = AT_AddIndex;
2529 newcmd->def = idxstmt;
2530 newcmds = lappend(newcmds, newcmd);
2534 /* Append any CHECK or FK constraints to the commands list */
2535 foreach(l, cxt.ckconstraints)
2537 newcmd = makeNode(AlterTableCmd);
2538 newcmd->subtype = AT_AddConstraint;
2539 newcmd->def = (Node *) lfirst(l);
2540 newcmds = lappend(newcmds, newcmd);
2542 foreach(l, cxt.fkconstraints)
2544 newcmd = makeNode(AlterTableCmd);
2545 newcmd->subtype = AT_AddConstraint;
2546 newcmd->def = (Node *) lfirst(l);
2547 newcmds = lappend(newcmds, newcmd);
2550 /* Update statement's commands list */
2551 stmt->cmds = newcmds;
2553 qry = makeNode(Query);
2554 qry->commandType = CMD_UTILITY;
2555 qry->utilityStmt = (Node *) stmt;
2557 *extras_before = list_concat(*extras_before, cxt.blist);
2558 *extras_after = list_concat(cxt.alist, *extras_after);
2564 transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
2566 Query *result = makeNode(Query);
2567 List *extras_before = NIL,
2568 *extras_after = NIL;
2570 result->commandType = CMD_UTILITY;
2571 result->utilityStmt = (Node *) stmt;
2574 * Don't allow both SCROLL and NO SCROLL to be specified
2576 if ((stmt->options & CURSOR_OPT_SCROLL) &&
2577 (stmt->options & CURSOR_OPT_NO_SCROLL))
2579 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
2580 errmsg("cannot specify both SCROLL and NO SCROLL")));
2582 stmt->query = (Node *) transformStmt(pstate, stmt->query,
2583 &extras_before, &extras_after);
2585 /* Shouldn't get any extras, since grammar only allows SelectStmt */
2586 if (extras_before || extras_after)
2587 elog(ERROR, "unexpected extra stuff in cursor statement");
2594 transformPrepareStmt(ParseState *pstate, PrepareStmt *stmt)
2596 Query *result = makeNode(Query);
2597 List *argtype_oids = NIL; /* argtype OIDs in a list */
2598 Oid *argtoids = NULL; /* and as an array */
2602 result->commandType = CMD_UTILITY;
2603 result->utilityStmt = (Node *) stmt;
2605 /* Transform list of TypeNames to list (and array) of type OIDs */
2606 nargs = list_length(stmt->argtypes);
2613 argtoids = (Oid *) palloc(nargs * sizeof(Oid));
2615 foreach(l, stmt->argtypes)
2617 TypeName *tn = lfirst(l);
2618 Oid toid = typenameTypeId(tn);
2620 argtype_oids = lappend_oid(argtype_oids, toid);
2621 argtoids[i++] = toid;
2625 stmt->argtype_oids = argtype_oids;
2628 * Analyze the statement using these parameter types (any parameters
2629 * passed in from above us will not be visible to it).
2631 queries = parse_analyze((Node *) stmt->query, argtoids, nargs);
2634 * Shouldn't get any extra statements, since grammar only allows
2637 if (list_length(queries) != 1)
2638 elog(ERROR, "unexpected extra stuff in prepared statement");
2640 stmt->query = linitial(queries);
2646 transformExecuteStmt(ParseState *pstate, ExecuteStmt *stmt)
2648 Query *result = makeNode(Query);
2651 result->commandType = CMD_UTILITY;
2652 result->utilityStmt = (Node *) stmt;
2654 paramtypes = FetchPreparedStatementParams(stmt->name);
2656 if (stmt->params || paramtypes)
2658 int nparams = list_length(stmt->params);
2659 int nexpected = list_length(paramtypes);
2664 if (nparams != nexpected)
2666 (errcode(ERRCODE_SYNTAX_ERROR),
2667 errmsg("wrong number of parameters for prepared statement \"%s\"",
2669 errdetail("Expected %d parameters but got %d.",
2670 nexpected, nparams)));
2672 forboth(l, stmt->params, l2, paramtypes)
2674 Node *expr = lfirst(l);
2675 Oid expected_type_id = lfirst_oid(l2);
2678 expr = transformExpr(pstate, expr);
2680 /* Cannot contain subselects or aggregates */
2681 if (pstate->p_hasSubLinks)
2683 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2684 errmsg("cannot use subquery in EXECUTE parameter")));
2685 if (pstate->p_hasAggs)
2687 (errcode(ERRCODE_GROUPING_ERROR),
2688 errmsg("cannot use aggregate function in EXECUTE parameter")));
2690 given_type_id = exprType(expr);
2692 expr = coerce_to_target_type(pstate, expr, given_type_id,
2693 expected_type_id, -1,
2694 COERCION_ASSIGNMENT,
2695 COERCE_IMPLICIT_CAST);
2699 (errcode(ERRCODE_DATATYPE_MISMATCH),
2700 errmsg("parameter $%d of type %s cannot be coerced to the expected type %s",
2702 format_type_be(given_type_id),
2703 format_type_be(expected_type_id)),
2704 errhint("You will need to rewrite or cast the expression.")));
2714 /* exported so planner can check again after rewriting, query pullup, etc */
2716 CheckSelectLocking(Query *qry, bool forUpdate)
2718 const char *operation;
2721 operation = "SELECT FOR UPDATE";
2723 operation = "SELECT FOR SHARE";
2725 if (qry->setOperations)
2727 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2728 /* translator: %s is a SQL command, like SELECT FOR UPDATE */
2729 errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT", operation)));
2730 if (qry->distinctClause != NIL)
2732 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2733 /* translator: %s is a SQL command, like SELECT FOR UPDATE */
2734 errmsg("%s is not allowed with DISTINCT clause", operation)));
2735 if (qry->groupClause != NIL)
2737 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2738 /* translator: %s is a SQL command, like SELECT FOR UPDATE */
2739 errmsg("%s is not allowed with GROUP BY clause", operation)));
2740 if (qry->havingQual != NULL)
2742 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2743 /* translator: %s is a SQL command, like SELECT FOR UPDATE */
2744 errmsg("%s is not allowed with HAVING clause", operation)));
2747 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2748 /* translator: %s is a SQL command, like SELECT FOR UPDATE */
2749 errmsg("%s is not allowed with aggregate functions", operation)));
2753 * Convert FOR UPDATE/SHARE name list into rowMarks list of integer relids
2755 * NB: if you need to change this, see also markQueryForLocking()
2756 * in rewriteHandler.c.
2759 transformLocking(Query *qry, List *lockedRels, bool forUpdate)
2766 if (qry->rowMarks && forUpdate != qry->forUpdate)
2768 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2769 errmsg("cannot use both FOR UPDATE and FOR SHARE in one query")));
2770 qry->forUpdate = forUpdate;
2772 CheckSelectLocking(qry, forUpdate);
2774 rowMarks = qry->rowMarks;
2776 if (linitial(lockedRels) == NULL)
2778 /* all regular tables used in query */
2780 foreach(rt, qry->rtable)
2782 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2785 switch (rte->rtekind)
2788 if (!list_member_int(rowMarks, i)) /* avoid duplicates */
2789 rowMarks = lappend_int(rowMarks, i);
2790 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
2795 * FOR UPDATE/SHARE of subquery is propagated to all
2796 * of subquery's rels
2798 transformLocking(rte->subquery, list_make1(NULL),
2802 /* ignore JOIN, SPECIAL, FUNCTION RTEs */
2809 /* just the named tables */
2810 foreach(l, lockedRels)
2812 char *relname = strVal(lfirst(l));
2815 foreach(rt, qry->rtable)
2817 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2820 if (strcmp(rte->eref->aliasname, relname) == 0)
2822 switch (rte->rtekind)
2825 if (!list_member_int(rowMarks, i)) /* avoid duplicates */
2826 rowMarks = lappend_int(rowMarks, i);
2827 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
2832 * FOR UPDATE/SHARE of subquery is propagated to
2833 * all of subquery's rels
2835 transformLocking(rte->subquery, list_make1(NULL),
2840 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2841 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a join")));
2845 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2846 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to NEW or OLD")));
2850 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2851 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a function")));
2854 elog(ERROR, "unrecognized RTE type: %d",
2855 (int) rte->rtekind);
2858 break; /* out of foreach loop */
2863 (errcode(ERRCODE_UNDEFINED_TABLE),
2864 errmsg("relation \"%s\" in FOR UPDATE/SHARE clause not found in FROM clause",
2869 qry->rowMarks = rowMarks;
2874 * Preprocess a list of column constraint clauses
2875 * to attach constraint attributes to their primary constraint nodes
2876 * and detect inconsistent/misplaced constraint attributes.
2878 * NOTE: currently, attributes are only supported for FOREIGN KEY primary
2879 * constraints, but someday they ought to be supported for other constraints.
2882 transformConstraintAttrs(List *constraintList)
2884 Node *lastprimarynode = NULL;
2885 bool saw_deferrability = false;
2886 bool saw_initially = false;
2889 foreach(clist, constraintList)
2891 Node *node = lfirst(clist);
2893 if (!IsA(node, Constraint))
2895 lastprimarynode = node;
2896 /* reset flags for new primary node */
2897 saw_deferrability = false;
2898 saw_initially = false;
2902 Constraint *con = (Constraint *) node;
2904 switch (con->contype)
2906 case CONSTR_ATTR_DEFERRABLE:
2907 if (lastprimarynode == NULL ||
2908 !IsA(lastprimarynode, FkConstraint))
2910 (errcode(ERRCODE_SYNTAX_ERROR),
2911 errmsg("misplaced DEFERRABLE clause")));
2912 if (saw_deferrability)
2914 (errcode(ERRCODE_SYNTAX_ERROR),
2915 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
2916 saw_deferrability = true;
2917 ((FkConstraint *) lastprimarynode)->deferrable = true;
2919 case CONSTR_ATTR_NOT_DEFERRABLE:
2920 if (lastprimarynode == NULL ||
2921 !IsA(lastprimarynode, FkConstraint))
2923 (errcode(ERRCODE_SYNTAX_ERROR),
2924 errmsg("misplaced NOT DEFERRABLE clause")));
2925 if (saw_deferrability)
2927 (errcode(ERRCODE_SYNTAX_ERROR),
2928 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
2929 saw_deferrability = true;
2930 ((FkConstraint *) lastprimarynode)->deferrable = false;
2931 if (saw_initially &&
2932 ((FkConstraint *) lastprimarynode)->initdeferred)
2934 (errcode(ERRCODE_SYNTAX_ERROR),
2935 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
2937 case CONSTR_ATTR_DEFERRED:
2938 if (lastprimarynode == NULL ||
2939 !IsA(lastprimarynode, FkConstraint))
2941 (errcode(ERRCODE_SYNTAX_ERROR),
2942 errmsg("misplaced INITIALLY DEFERRED clause")));
2945 (errcode(ERRCODE_SYNTAX_ERROR),
2946 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
2947 saw_initially = true;
2948 ((FkConstraint *) lastprimarynode)->initdeferred = true;
2951 * If only INITIALLY DEFERRED appears, assume
2954 if (!saw_deferrability)
2955 ((FkConstraint *) lastprimarynode)->deferrable = true;
2956 else if (!((FkConstraint *) lastprimarynode)->deferrable)
2958 (errcode(ERRCODE_SYNTAX_ERROR),
2959 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
2961 case CONSTR_ATTR_IMMEDIATE:
2962 if (lastprimarynode == NULL ||
2963 !IsA(lastprimarynode, FkConstraint))
2965 (errcode(ERRCODE_SYNTAX_ERROR),
2966 errmsg("misplaced INITIALLY IMMEDIATE clause")));
2969 (errcode(ERRCODE_SYNTAX_ERROR),
2970 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
2971 saw_initially = true;
2972 ((FkConstraint *) lastprimarynode)->initdeferred = false;
2975 /* Otherwise it's not an attribute */
2976 lastprimarynode = node;
2977 /* reset flags for new primary node */
2978 saw_deferrability = false;
2979 saw_initially = false;
2986 /* Build a FromExpr node */
2988 makeFromExpr(List *fromlist, Node *quals)
2990 FromExpr *f = makeNode(FromExpr);
2992 f->fromlist = fromlist;
2998 * Special handling of type definition for a column
3001 transformColumnType(ParseState *pstate, ColumnDef *column)
3004 * All we really need to do here is verify that the type is valid.
3006 Type ctype = typenameType(column->typename);
3008 ReleaseSysCache(ctype);
3012 setSchemaName(char *context_schema, char **stmt_schema_name)
3014 if (*stmt_schema_name == NULL)
3015 *stmt_schema_name = context_schema;
3016 else if (strcmp(context_schema, *stmt_schema_name) != 0)
3018 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
3019 errmsg("CREATE specifies a schema (%s) "
3020 "different from the one being created (%s)",
3021 *stmt_schema_name, context_schema)));
3025 * analyzeCreateSchemaStmt -
3026 * analyzes the "create schema" statement
3028 * Split the schema element list into individual commands and place
3029 * them in the result list in an order such that there are no forward
3030 * references (e.g. GRANT to a table created later in the list). Note
3031 * that the logic we use for determining forward references is
3032 * presently quite incomplete.
3034 * SQL92 also allows constraints to make forward references, so thumb through
3035 * the table columns and move forward references to a posterior alter-table
3038 * The result is a list of parse nodes that still need to be analyzed ---
3039 * but we can't analyze the later commands until we've executed the earlier
3040 * ones, because of possible inter-object references.
3042 * Note: Called from commands/schemacmds.c
3045 analyzeCreateSchemaStmt(CreateSchemaStmt *stmt)
3047 CreateSchemaStmtContext cxt;
3051 cxt.stmtType = "CREATE SCHEMA";
3052 cxt.schemaname = stmt->schemaname;
3053 cxt.authid = stmt->authid;
3054 cxt.sequences = NIL;
3060 cxt.fwconstraints = NIL;
3066 * Run through each schema element in the schema element list.
3067 * Separate statements by type, and do preliminary analysis.
3069 foreach(elements, stmt->schemaElts)
3071 Node *element = lfirst(elements);
3073 switch (nodeTag(element))
3075 case T_CreateSeqStmt:
3077 CreateSeqStmt *elp = (CreateSeqStmt *) element;
3079 setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
3080 cxt.sequences = lappend(cxt.sequences, element);
3086 CreateStmt *elp = (CreateStmt *) element;
3088 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3091 * XXX todo: deal with constraints
3093 cxt.tables = lappend(cxt.tables, element);
3099 ViewStmt *elp = (ViewStmt *) element;
3101 setSchemaName(cxt.schemaname, &elp->view->schemaname);
3104 * XXX todo: deal with references between views
3106 cxt.views = lappend(cxt.views, element);
3112 IndexStmt *elp = (IndexStmt *) element;
3114 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3115 cxt.indexes = lappend(cxt.indexes, element);
3119 case T_CreateTrigStmt:
3121 CreateTrigStmt *elp = (CreateTrigStmt *) element;
3123 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3124 cxt.triggers = lappend(cxt.triggers, element);
3129 cxt.grants = lappend(cxt.grants, element);
3133 elog(ERROR, "unrecognized node type: %d",
3134 (int) nodeTag(element));
3139 result = list_concat(result, cxt.sequences);
3140 result = list_concat(result, cxt.tables);
3141 result = list_concat(result, cxt.views);
3142 result = list_concat(result, cxt.indexes);
3143 result = list_concat(result, cxt.triggers);
3144 result = list_concat(result, cxt.grants);
3150 * Traverse a fully-analyzed tree to verify that parameter symbols
3151 * match their types. We need this because some Params might still
3152 * be UNKNOWN, if there wasn't anything to force their coercion,
3153 * and yet other instances seen later might have gotten coerced.
3156 check_parameter_resolution_walker(Node *node,
3157 check_parameter_resolution_context *context)
3161 if (IsA(node, Param))
3163 Param *param = (Param *) node;
3165 if (param->paramkind == PARAM_NUM)
3167 int paramno = param->paramid;
3169 if (paramno <= 0 || /* shouldn't happen, but... */
3170 paramno > context->numParams)
3172 (errcode(ERRCODE_UNDEFINED_PARAMETER),
3173 errmsg("there is no parameter $%d", paramno)));
3175 if (param->paramtype != context->paramTypes[paramno - 1])
3177 (errcode(ERRCODE_AMBIGUOUS_PARAMETER),
3178 errmsg("could not determine data type of parameter $%d",
3183 if (IsA(node, Query))
3185 /* Recurse into RTE subquery or not-yet-planned sublink subquery */
3186 return query_tree_walker((Query *) node,
3187 check_parameter_resolution_walker,
3188 (void *) context, 0);
3190 return expression_tree_walker(node, check_parameter_resolution_walker,