1 /*-------------------------------------------------------------------------
4 * Perform parse analysis work for various utility commands
6 * Formerly we did this work during parse_analyze() in analyze.c. However
7 * that is fairly unsafe in the presence of querytree caching, since any
8 * database state that we depend on in making the transformations might be
9 * obsolete by the time the utility command is executed; and utility commands
10 * have no infrastructure for holding locks or rechecking plan validity.
11 * Hence these functions are now called at the start of execution of their
12 * respective utility commands.
14 * NOTE: in general we must avoid scribbling on the passed-in raw parse
15 * tree, since it might be in a plan cache. The simplest solution is
16 * a quick copyObject() call before manipulating the query tree.
19 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
20 * Portions Copyright (c) 1994, Regents of the University of California
22 * $PostgreSQL: pgsql/src/backend/parser/parse_utilcmd.c,v 2.25 2009/07/30 02:45:37 tgl Exp $
24 *-------------------------------------------------------------------------
29 #include "access/genam.h"
30 #include "access/heapam.h"
31 #include "access/reloptions.h"
32 #include "catalog/dependency.h"
33 #include "catalog/heap.h"
34 #include "catalog/index.h"
35 #include "catalog/namespace.h"
36 #include "catalog/pg_constraint.h"
37 #include "catalog/pg_opclass.h"
38 #include "catalog/pg_type.h"
39 #include "commands/defrem.h"
40 #include "commands/tablecmds.h"
41 #include "commands/tablespace.h"
42 #include "miscadmin.h"
43 #include "nodes/makefuncs.h"
44 #include "nodes/nodeFuncs.h"
45 #include "parser/analyze.h"
46 #include "parser/parse_clause.h"
47 #include "parser/parse_expr.h"
48 #include "parser/parse_relation.h"
49 #include "parser/parse_type.h"
50 #include "parser/parse_utilcmd.h"
51 #include "parser/parser.h"
52 #include "rewrite/rewriteManip.h"
53 #include "utils/acl.h"
54 #include "utils/builtins.h"
55 #include "utils/lsyscache.h"
56 #include "utils/relcache.h"
57 #include "utils/syscache.h"
60 /* State shared by transformCreateStmt and its subroutines */
63 const char *stmtType; /* "CREATE TABLE" or "ALTER TABLE" */
64 RangeVar *relation; /* relation to create */
65 Relation rel; /* opened/locked rel, if ALTER */
66 List *inhRelations; /* relations to inherit from */
67 bool isalter; /* true if altering existing table */
68 bool hasoids; /* does relation have an OID column? */
69 List *columns; /* ColumnDef items */
70 List *ckconstraints; /* CHECK constraints */
71 List *fkconstraints; /* FOREIGN KEY constraints */
72 List *ixconstraints; /* index-creating constraints */
73 List *inh_indexes; /* cloned indexes from INCLUDING INDEXES */
74 List *blist; /* "before list" of things to do before
75 * creating the table */
76 List *alist; /* "after list" of things to do after creating
78 IndexStmt *pkey; /* PRIMARY KEY index, if any */
81 /* State shared by transformCreateSchemaStmt and its subroutines */
84 const char *stmtType; /* "CREATE SCHEMA" or "ALTER SCHEMA" */
85 char *schemaname; /* name of schema */
86 char *authid; /* owner of schema */
87 List *sequences; /* CREATE SEQUENCE items */
88 List *tables; /* CREATE TABLE items */
89 List *views; /* CREATE VIEW items */
90 List *indexes; /* CREATE INDEX items */
91 List *triggers; /* CREATE TRIGGER items */
92 List *grants; /* GRANT items */
93 } CreateSchemaStmtContext;
96 static void transformColumnDefinition(ParseState *pstate,
97 CreateStmtContext *cxt,
99 static void transformTableConstraint(ParseState *pstate,
100 CreateStmtContext *cxt,
101 Constraint *constraint);
102 static void transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
103 InhRelation *inhrelation);
104 static IndexStmt *generateClonedIndexStmt(CreateStmtContext *cxt,
105 Relation parent_index, AttrNumber *attmap);
106 static List *get_opclass(Oid opclass, Oid actual_datatype);
107 static void transformIndexConstraints(ParseState *pstate,
108 CreateStmtContext *cxt);
109 static IndexStmt *transformIndexConstraint(Constraint *constraint,
110 CreateStmtContext *cxt);
111 static void transformFKConstraints(ParseState *pstate,
112 CreateStmtContext *cxt,
114 bool isAddConstraint);
115 static void transformConstraintAttrs(ParseState *pstate, List *constraintList);
116 static void transformColumnType(ParseState *pstate, ColumnDef *column);
117 static void setSchemaName(char *context_schema, char **stmt_schema_name);
121 * transformCreateStmt -
122 * parse analysis for CREATE TABLE
124 * Returns a List of utility commands to be done in sequence. One of these
125 * will be the transformed CreateStmt, but there may be additional actions
126 * to be done before and after the actual DefineRelation() call.
128 * SQL92 allows constraints to be scattered all over, so thumb through
129 * the columns and collect all constraints into one place.
130 * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
131 * then expand those into multiple IndexStmt blocks.
132 * - thomas 1997-12-02
135 transformCreateStmt(CreateStmt *stmt, const char *queryString)
138 CreateStmtContext cxt;
144 * We must not scribble on the passed-in CreateStmt, so copy it. (This is
145 * overkill, but easy.)
147 stmt = (CreateStmt *) copyObject(stmt);
150 * If the target relation name isn't schema-qualified, make it so. This
151 * prevents some corner cases in which added-on rewritten commands might
152 * think they should apply to other relations that have the same name and
153 * are earlier in the search path. "istemp" is equivalent to a
154 * specification of pg_temp, so no need for anything extra in that case.
156 if (stmt->relation->schemaname == NULL && !stmt->relation->istemp)
158 Oid namespaceid = RangeVarGetCreationNamespace(stmt->relation);
160 stmt->relation->schemaname = get_namespace_name(namespaceid);
164 pstate = make_parsestate(NULL);
165 pstate->p_sourcetext = queryString;
167 cxt.stmtType = "CREATE TABLE";
168 cxt.relation = stmt->relation;
170 cxt.inhRelations = stmt->inhRelations;
173 cxt.ckconstraints = NIL;
174 cxt.fkconstraints = NIL;
175 cxt.ixconstraints = NIL;
176 cxt.inh_indexes = NIL;
180 cxt.hasoids = interpretOidsOption(stmt->options);
183 * Run through each primary element in the table creation clause. Separate
184 * column defs from constraints, and do preliminary analysis.
186 foreach(elements, stmt->tableElts)
188 Node *element = lfirst(elements);
190 switch (nodeTag(element))
193 transformColumnDefinition(pstate, &cxt,
194 (ColumnDef *) element);
198 transformTableConstraint(pstate, &cxt,
199 (Constraint *) element);
203 transformInhRelation(pstate, &cxt,
204 (InhRelation *) element);
208 elog(ERROR, "unrecognized node type: %d",
209 (int) nodeTag(element));
215 * transformIndexConstraints wants cxt.alist to contain only index
216 * statements, so transfer anything we already have into save_alist.
218 save_alist = cxt.alist;
221 Assert(stmt->constraints == NIL);
224 * Postprocess constraints that give rise to index definitions.
226 transformIndexConstraints(pstate, &cxt);
229 * Postprocess foreign-key constraints.
231 transformFKConstraints(pstate, &cxt, true, false);
236 stmt->tableElts = cxt.columns;
237 stmt->constraints = cxt.ckconstraints;
239 result = lappend(cxt.blist, stmt);
240 result = list_concat(result, cxt.alist);
241 result = list_concat(result, save_alist);
247 * transformColumnDefinition -
248 * transform a single ColumnDef within CREATE TABLE
249 * Also used in ALTER TABLE ADD COLUMN
252 transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
258 Constraint *constraint;
261 cxt->columns = lappend(cxt->columns, column);
263 /* Check for SERIAL pseudo-types */
265 if (list_length(column->typeName->names) == 1 &&
266 !column->typeName->pct_type)
268 char *typname = strVal(linitial(column->typeName->names));
270 if (strcmp(typname, "serial") == 0 ||
271 strcmp(typname, "serial4") == 0)
274 column->typeName->names = NIL;
275 column->typeName->typeOid = INT4OID;
277 else if (strcmp(typname, "bigserial") == 0 ||
278 strcmp(typname, "serial8") == 0)
281 column->typeName->names = NIL;
282 column->typeName->typeOid = INT8OID;
286 * We have to reject "serial[]" explicitly, because once we've set
287 * typeid, LookupTypeName won't notice arrayBounds. We don't need any
288 * special coding for serial(typmod) though.
290 if (is_serial && column->typeName->arrayBounds != NIL)
292 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
293 errmsg("array of serial is not implemented"),
294 parser_errposition(pstate, column->typeName->location)));
297 /* Do necessary work on the column type declaration */
298 transformColumnType(pstate, column);
300 /* Special actions for SERIAL pseudo-types */
309 FuncCall *funccallnode;
310 CreateSeqStmt *seqstmt;
311 AlterSeqStmt *altseqstmt;
315 * Determine namespace and name to use for the sequence.
317 * Although we use ChooseRelationName, it's not guaranteed that the
318 * selected sequence name won't conflict; given sufficiently long
319 * field names, two different serial columns in the same table could
320 * be assigned the same sequence name, and we'd not notice since we
321 * aren't creating the sequence quite yet. In practice this seems
322 * quite unlikely to be a problem, especially since few people would
323 * need two serial columns in one table.
326 snamespaceid = RelationGetNamespace(cxt->rel);
328 snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
329 snamespace = get_namespace_name(snamespaceid);
330 sname = ChooseRelationName(cxt->relation->relname,
336 (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
337 cxt->stmtType, sname,
338 cxt->relation->relname, column->colname)));
341 * Build a CREATE SEQUENCE command to create the sequence object, and
342 * add it to the list of things to be done before this CREATE/ALTER
345 seqstmt = makeNode(CreateSeqStmt);
346 seqstmt->sequence = makeRangeVar(snamespace, sname, -1);
347 seqstmt->options = NIL;
349 cxt->blist = lappend(cxt->blist, seqstmt);
352 * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence
353 * as owned by this column, and add it to the list of things to be
354 * done after this CREATE/ALTER TABLE.
356 altseqstmt = makeNode(AlterSeqStmt);
357 altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
358 attnamelist = list_make3(makeString(snamespace),
359 makeString(cxt->relation->relname),
360 makeString(column->colname));
361 altseqstmt->options = list_make1(makeDefElem("owned_by",
362 (Node *) attnamelist));
364 cxt->alist = lappend(cxt->alist, altseqstmt);
367 * Create appropriate constraints for SERIAL. We do this in full,
368 * rather than shortcutting, so that we will detect any conflicting
369 * constraints the user wrote (like a different DEFAULT).
371 * Create an expression tree representing the function call
372 * nextval('sequencename'). We cannot reduce the raw tree to cooked
373 * form until after the sequence is created, but there's no need to do
376 qstring = quote_qualified_identifier(snamespace, sname);
377 snamenode = makeNode(A_Const);
378 snamenode->val.type = T_String;
379 snamenode->val.val.str = qstring;
380 snamenode->location = -1;
381 castnode = makeNode(TypeCast);
382 castnode->typeName = SystemTypeName("regclass");
383 castnode->arg = (Node *) snamenode;
384 castnode->location = -1;
385 funccallnode = makeNode(FuncCall);
386 funccallnode->funcname = SystemFuncName("nextval");
387 funccallnode->args = list_make1(castnode);
388 funccallnode->agg_star = false;
389 funccallnode->agg_distinct = false;
390 funccallnode->func_variadic = false;
391 funccallnode->over = NULL;
392 funccallnode->location = -1;
394 constraint = makeNode(Constraint);
395 constraint->contype = CONSTR_DEFAULT;
396 constraint->location = -1;
397 constraint->raw_expr = (Node *) funccallnode;
398 constraint->cooked_expr = NULL;
399 column->constraints = lappend(column->constraints, constraint);
401 constraint = makeNode(Constraint);
402 constraint->contype = CONSTR_NOTNULL;
403 constraint->location = -1;
404 column->constraints = lappend(column->constraints, constraint);
407 /* Process column constraints, if any... */
408 transformConstraintAttrs(pstate, column->constraints);
410 saw_nullable = false;
413 foreach(clist, column->constraints)
415 constraint = lfirst(clist);
416 Assert(IsA(constraint, Constraint));
418 switch (constraint->contype)
421 if (saw_nullable && column->is_not_null)
423 (errcode(ERRCODE_SYNTAX_ERROR),
424 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
425 column->colname, cxt->relation->relname),
426 parser_errposition(pstate,
427 constraint->location)));
428 column->is_not_null = FALSE;
433 if (saw_nullable && !column->is_not_null)
435 (errcode(ERRCODE_SYNTAX_ERROR),
436 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
437 column->colname, cxt->relation->relname),
438 parser_errposition(pstate,
439 constraint->location)));
440 column->is_not_null = TRUE;
447 (errcode(ERRCODE_SYNTAX_ERROR),
448 errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
449 column->colname, cxt->relation->relname),
450 parser_errposition(pstate,
451 constraint->location)));
452 column->raw_default = constraint->raw_expr;
453 Assert(constraint->cooked_expr == NULL);
459 if (constraint->keys == NIL)
460 constraint->keys = list_make1(makeString(column->colname));
461 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
465 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
470 * Fill in the current attribute's name and throw it into the
471 * list of FK constraints to be processed later.
473 constraint->fk_attrs = list_make1(makeString(column->colname));
474 cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
477 case CONSTR_ATTR_DEFERRABLE:
478 case CONSTR_ATTR_NOT_DEFERRABLE:
479 case CONSTR_ATTR_DEFERRED:
480 case CONSTR_ATTR_IMMEDIATE:
481 /* transformConstraintAttrs took care of these */
485 elog(ERROR, "unrecognized constraint type: %d",
486 constraint->contype);
493 * transformTableConstraint
494 * transform a Constraint node within CREATE TABLE or ALTER TABLE
497 transformTableConstraint(ParseState *pstate, CreateStmtContext *cxt,
498 Constraint *constraint)
500 switch (constraint->contype)
504 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
508 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
512 cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
518 case CONSTR_ATTR_DEFERRABLE:
519 case CONSTR_ATTR_NOT_DEFERRABLE:
520 case CONSTR_ATTR_DEFERRED:
521 case CONSTR_ATTR_IMMEDIATE:
522 elog(ERROR, "invalid context for constraint type %d",
523 constraint->contype);
527 elog(ERROR, "unrecognized constraint type: %d",
528 constraint->contype);
534 * transformInhRelation
536 * Change the LIKE <subtable> portion of a CREATE TABLE statement into
537 * column definitions which recreate the user defined column portions of
541 transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
542 InhRelation *inhRelation)
544 AttrNumber parent_attno;
549 bool including_defaults = false;
550 bool including_constraints = false;
551 bool including_indexes = false;
554 relation = parserOpenTable(pstate, inhRelation->relation, AccessShareLock);
556 if (relation->rd_rel->relkind != RELKIND_RELATION)
558 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
559 errmsg("inherited relation \"%s\" is not a table",
560 inhRelation->relation->relname)));
563 * Check for SELECT privilages
565 aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
567 if (aclresult != ACLCHECK_OK)
568 aclcheck_error(aclresult, ACL_KIND_CLASS,
569 RelationGetRelationName(relation));
571 tupleDesc = RelationGetDescr(relation);
572 constr = tupleDesc->constr;
574 foreach(elem, inhRelation->options)
576 int option = lfirst_int(elem);
580 case CREATE_TABLE_LIKE_INCLUDING_DEFAULTS:
581 including_defaults = true;
583 case CREATE_TABLE_LIKE_EXCLUDING_DEFAULTS:
584 including_defaults = false;
586 case CREATE_TABLE_LIKE_INCLUDING_CONSTRAINTS:
587 including_constraints = true;
589 case CREATE_TABLE_LIKE_EXCLUDING_CONSTRAINTS:
590 including_constraints = false;
592 case CREATE_TABLE_LIKE_INCLUDING_INDEXES:
593 including_indexes = true;
595 case CREATE_TABLE_LIKE_EXCLUDING_INDEXES:
596 including_indexes = false;
599 elog(ERROR, "unrecognized CREATE TABLE LIKE option: %d",
605 * Insert the copied attributes into the cxt for the new table definition.
607 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
610 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
611 char *attributeName = NameStr(attribute->attname);
615 * Ignore dropped columns in the parent.
617 if (attribute->attisdropped)
621 * Create a new column, which is marked as NOT inherited.
623 * For constraints, ONLY the NOT NULL constraint is inherited by the
624 * new column definition per SQL99.
626 def = makeNode(ColumnDef);
627 def->colname = pstrdup(attributeName);
628 def->typeName = makeTypeNameFromOid(attribute->atttypid,
629 attribute->atttypmod);
631 def->is_local = true;
632 def->is_not_null = attribute->attnotnull;
633 def->raw_default = NULL;
634 def->cooked_default = NULL;
635 def->constraints = NIL;
640 cxt->columns = lappend(cxt->columns, def);
643 * Copy default, if present and the default has been requested
645 if (attribute->atthasdef && including_defaults)
647 char *this_default = NULL;
648 AttrDefault *attrdef;
651 /* Find default in constraint structure */
652 Assert(constr != NULL);
653 attrdef = constr->defval;
654 for (i = 0; i < constr->num_defval; i++)
656 if (attrdef[i].adnum == parent_attno)
658 this_default = attrdef[i].adbin;
662 Assert(this_default != NULL);
665 * If default expr could contain any vars, we'd need to fix 'em,
666 * but it can't; so default is ready to apply to child.
669 def->cooked_default = pstrdup(this_default);
674 * Copy CHECK constraints if requested, being careful to adjust attribute
677 if (including_constraints && tupleDesc->constr)
679 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
682 for (ccnum = 0; ccnum < tupleDesc->constr->num_check; ccnum++)
684 char *ccname = tupleDesc->constr->check[ccnum].ccname;
685 char *ccbin = tupleDesc->constr->check[ccnum].ccbin;
686 Node *ccbin_node = stringToNode(ccbin);
687 Constraint *n = makeNode(Constraint);
689 change_varattnos_of_a_node(ccbin_node, attmap);
691 n->contype = CONSTR_CHECK;
693 n->conname = pstrdup(ccname);
695 n->cooked_expr = nodeToString(ccbin_node);
696 cxt->ckconstraints = lappend(cxt->ckconstraints, n);
701 * Likewise, copy indexes if requested
703 if (including_indexes && relation->rd_rel->relhasindex)
705 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
706 List *parent_indexes;
709 parent_indexes = RelationGetIndexList(relation);
711 foreach(l, parent_indexes)
713 Oid parent_index_oid = lfirst_oid(l);
714 Relation parent_index;
715 IndexStmt *index_stmt;
717 parent_index = index_open(parent_index_oid, AccessShareLock);
719 /* Build CREATE INDEX statement to recreate the parent_index */
720 index_stmt = generateClonedIndexStmt(cxt, parent_index, attmap);
722 /* Save it in the inh_indexes list for the time being */
723 cxt->inh_indexes = lappend(cxt->inh_indexes, index_stmt);
725 index_close(parent_index, AccessShareLock);
730 * Close the parent rel, but keep our AccessShareLock on it until xact
731 * commit. That will prevent someone else from deleting or ALTERing the
732 * parent before the child is committed.
734 heap_close(relation, NoLock);
738 * Generate an IndexStmt node using information from an already existing index
739 * "source_idx". Attribute numbers should be adjusted according to attmap.
742 generateClonedIndexStmt(CreateStmtContext *cxt, Relation source_idx,
745 Oid source_relid = RelationGetRelid(source_idx);
748 Form_pg_class idxrelrec;
749 Form_pg_index idxrec;
754 ListCell *indexpr_item;
762 * Fetch pg_class tuple of source index. We can't use the copy in the
763 * relcache entry because it doesn't include optional fields.
765 ht_idxrel = SearchSysCache(RELOID,
766 ObjectIdGetDatum(source_relid),
768 if (!HeapTupleIsValid(ht_idxrel))
769 elog(ERROR, "cache lookup failed for relation %u", source_relid);
770 idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
772 /* Fetch pg_index tuple for source index from relcache entry */
773 ht_idx = source_idx->rd_indextuple;
774 idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
775 indrelid = idxrec->indrelid;
777 /* Fetch pg_am tuple for source index from relcache entry */
778 amrec = source_idx->rd_am;
780 /* Must get indclass the hard way, since it's not stored in relcache */
781 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
782 Anum_pg_index_indclass, &isnull);
784 indclass = (oidvector *) DatumGetPointer(datum);
786 /* Begin building the IndexStmt */
787 index = makeNode(IndexStmt);
788 index->relation = cxt->relation;
789 index->accessMethod = pstrdup(NameStr(amrec->amname));
790 if (OidIsValid(idxrelrec->reltablespace))
791 index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
793 index->tableSpace = NULL;
794 index->unique = idxrec->indisunique;
795 index->primary = idxrec->indisprimary;
796 index->concurrent = false;
799 * We don't try to preserve the name of the source index; instead, just
800 * let DefineIndex() choose a reasonable name.
802 index->idxname = NULL;
805 * If the index is marked PRIMARY, it's certainly from a constraint; else,
806 * if it's not marked UNIQUE, it certainly isn't. If it is or might be
807 * from a constraint, we have to fetch the constraint to check for
808 * deferrability attributes.
810 if (index->primary || index->unique)
812 Oid constraintId = get_index_constraint(source_relid);
814 if (OidIsValid(constraintId))
817 Form_pg_constraint conrec;
819 ht_constr = SearchSysCache(CONSTROID,
820 ObjectIdGetDatum(constraintId),
822 if (!HeapTupleIsValid(ht_constr))
823 elog(ERROR, "cache lookup failed for constraint %u",
825 conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
827 index->isconstraint = true;
828 index->deferrable = conrec->condeferrable;
829 index->initdeferred = conrec->condeferred;
831 ReleaseSysCache(ht_constr);
834 index->isconstraint = false;
837 index->isconstraint = false;
839 /* Get the index expressions, if any */
840 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
841 Anum_pg_index_indexprs, &isnull);
846 exprsString = TextDatumGetCString(datum);
847 indexprs = (List *) stringToNode(exprsString);
852 /* Build the list of IndexElem */
853 index->indexParams = NIL;
855 indexpr_item = list_head(indexprs);
856 for (keyno = 0; keyno < idxrec->indnatts; keyno++)
859 AttrNumber attnum = idxrec->indkey.values[keyno];
860 int16 opt = source_idx->rd_indoption[keyno];
862 iparam = makeNode(IndexElem);
864 if (AttributeNumberIsValid(attnum))
866 /* Simple index column */
869 attname = get_relid_attribute_name(indrelid, attnum);
870 keycoltype = get_atttype(indrelid, attnum);
872 iparam->name = attname;
877 /* Expressional index */
880 if (indexpr_item == NULL)
881 elog(ERROR, "too few entries in indexprs list");
882 indexkey = (Node *) lfirst(indexpr_item);
883 indexpr_item = lnext(indexpr_item);
885 /* OK to modify indexkey since we are working on a private copy */
886 change_varattnos_of_a_node(indexkey, attmap);
889 iparam->expr = indexkey;
891 keycoltype = exprType(indexkey);
894 /* Add the operator class name, if non-default */
895 iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
897 iparam->ordering = SORTBY_DEFAULT;
898 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
900 /* Adjust options if necessary */
901 if (amrec->amcanorder)
904 * If it supports sort ordering, copy DESC and NULLS opts. Don't
905 * set non-default settings unnecessarily, though, so as to
906 * improve the chance of recognizing equivalence to constraint
909 if (opt & INDOPTION_DESC)
911 iparam->ordering = SORTBY_DESC;
912 if ((opt & INDOPTION_NULLS_FIRST) == 0)
913 iparam->nulls_ordering = SORTBY_NULLS_LAST;
917 if (opt & INDOPTION_NULLS_FIRST)
918 iparam->nulls_ordering = SORTBY_NULLS_FIRST;
922 index->indexParams = lappend(index->indexParams, iparam);
925 /* Copy reloptions if any */
926 datum = SysCacheGetAttr(RELOID, ht_idxrel,
927 Anum_pg_class_reloptions, &isnull);
929 index->options = untransformRelOptions(datum);
931 /* If it's a partial index, decompile and append the predicate */
932 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
933 Anum_pg_index_indpred, &isnull);
938 /* Convert text string to node tree */
939 pred_str = TextDatumGetCString(datum);
940 index->whereClause = (Node *) stringToNode(pred_str);
941 /* Adjust attribute numbers */
942 change_varattnos_of_a_node(index->whereClause, attmap);
946 ReleaseSysCache(ht_idxrel);
952 * get_opclass - fetch name of an index operator class
954 * If the opclass is the default for the given actual_datatype, then
955 * the return value is NIL.
958 get_opclass(Oid opclass, Oid actual_datatype)
961 Form_pg_opclass opc_rec;
964 ht_opc = SearchSysCache(CLAOID,
965 ObjectIdGetDatum(opclass),
967 if (!HeapTupleIsValid(ht_opc))
968 elog(ERROR, "cache lookup failed for opclass %u", opclass);
969 opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
971 if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
973 /* For simplicity, we always schema-qualify the name */
974 char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
975 char *opc_name = pstrdup(NameStr(opc_rec->opcname));
977 result = list_make2(makeString(nsp_name), makeString(opc_name));
980 ReleaseSysCache(ht_opc);
986 * transformIndexConstraints
987 * Handle UNIQUE and PRIMARY KEY constraints, which create indexes.
988 * We also merge in any index definitions arising from
989 * LIKE ... INCLUDING INDEXES.
992 transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
995 List *indexlist = NIL;
999 * Run through the constraints that need to generate an index. For PRIMARY
1000 * KEY, mark each column as NOT NULL and create an index. For UNIQUE,
1001 * create an index as for PRIMARY KEY, but do not insist on NOT NULL.
1003 foreach(lc, cxt->ixconstraints)
1005 Constraint *constraint = (Constraint *) lfirst(lc);
1007 Assert(IsA(constraint, Constraint));
1008 Assert(constraint->contype == CONSTR_PRIMARY ||
1009 constraint->contype == CONSTR_UNIQUE);
1011 index = transformIndexConstraint(constraint, cxt);
1013 indexlist = lappend(indexlist, index);
1016 /* Add in any indexes defined by LIKE ... INCLUDING INDEXES */
1017 foreach(lc, cxt->inh_indexes)
1019 index = (IndexStmt *) lfirst(lc);
1023 if (cxt->pkey != NULL)
1025 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1026 errmsg("multiple primary keys for table \"%s\" are not allowed",
1027 cxt->relation->relname)));
1031 indexlist = lappend(indexlist, index);
1035 * Scan the index list and remove any redundant index specifications. This
1036 * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
1037 * strict reading of SQL92 would suggest raising an error instead, but
1038 * that strikes me as too anal-retentive. - tgl 2001-02-14
1040 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1041 * pre-existing indexes, too.
1043 Assert(cxt->alist == NIL);
1044 if (cxt->pkey != NULL)
1046 /* Make sure we keep the PKEY index in preference to others... */
1047 cxt->alist = list_make1(cxt->pkey);
1050 foreach(lc, indexlist)
1057 /* if it's pkey, it's already in cxt->alist */
1058 if (index == cxt->pkey)
1061 foreach(k, cxt->alist)
1063 IndexStmt *priorindex = lfirst(k);
1065 if (equal(index->indexParams, priorindex->indexParams) &&
1066 equal(index->whereClause, priorindex->whereClause) &&
1067 strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
1068 index->deferrable == priorindex->deferrable &&
1069 index->initdeferred == priorindex->initdeferred)
1071 priorindex->unique |= index->unique;
1074 * If the prior index is as yet unnamed, and this one is
1075 * named, then transfer the name to the prior index. This
1076 * ensures that if we have named and unnamed constraints,
1077 * we'll use (at least one of) the names for the index.
1079 if (priorindex->idxname == NULL)
1080 priorindex->idxname = index->idxname;
1087 cxt->alist = lappend(cxt->alist, index);
1092 * transformIndexConstraint
1093 * Transform one UNIQUE or PRIMARY KEY constraint for
1094 * transformIndexConstraints.
1097 transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
1103 index = makeNode(IndexStmt);
1105 index->unique = true;
1106 index->primary = (constraint->contype == CONSTR_PRIMARY);
1109 if (cxt->pkey != NULL)
1111 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1112 errmsg("multiple primary keys for table \"%s\" are not allowed",
1113 cxt->relation->relname)));
1117 * In ALTER TABLE case, a primary index might already exist, but
1118 * DefineIndex will check for it.
1121 index->isconstraint = true;
1122 index->deferrable = constraint->deferrable;
1123 index->initdeferred = constraint->initdeferred;
1125 if (constraint->conname != NULL)
1126 index->idxname = pstrdup(constraint->conname);
1128 index->idxname = NULL; /* DefineIndex will choose name */
1130 index->relation = cxt->relation;
1131 index->accessMethod = DEFAULT_INDEX_TYPE;
1132 index->options = constraint->options;
1133 index->tableSpace = constraint->indexspace;
1134 index->indexParams = NIL;
1135 index->whereClause = NULL;
1136 index->concurrent = false;
1139 * Make sure referenced keys exist. If we are making a PRIMARY KEY index,
1140 * also make sure they are NOT NULL, if possible. (Although we could leave
1141 * it to DefineIndex to mark the columns NOT NULL, it's more efficient to
1142 * get it right the first time.)
1144 foreach(keys, constraint->keys)
1146 char *key = strVal(lfirst(keys));
1148 ColumnDef *column = NULL;
1151 foreach(columns, cxt->columns)
1153 column = (ColumnDef *) lfirst(columns);
1154 Assert(IsA(column, ColumnDef));
1155 if (strcmp(column->colname, key) == 0)
1163 /* found column in the new table; force it to be NOT NULL */
1164 if (constraint->contype == CONSTR_PRIMARY)
1165 column->is_not_null = TRUE;
1167 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1170 * column will be a system column in the new table, so accept it.
1171 * System columns can't ever be null, so no need to worry about
1172 * PRIMARY/NOT NULL constraint.
1176 else if (cxt->inhRelations)
1178 /* try inherited tables */
1181 foreach(inher, cxt->inhRelations)
1183 RangeVar *inh = (RangeVar *) lfirst(inher);
1187 Assert(IsA(inh, RangeVar));
1188 rel = heap_openrv(inh, AccessShareLock);
1189 if (rel->rd_rel->relkind != RELKIND_RELATION)
1191 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1192 errmsg("inherited relation \"%s\" is not a table",
1194 for (count = 0; count < rel->rd_att->natts; count++)
1196 Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1197 char *inhname = NameStr(inhattr->attname);
1199 if (inhattr->attisdropped)
1201 if (strcmp(key, inhname) == 0)
1206 * We currently have no easy way to force an inherited
1207 * column to be NOT NULL at creation, if its parent
1208 * wasn't so already. We leave it to DefineIndex to
1209 * fix things up in this case.
1214 heap_close(rel, NoLock);
1221 * In the ALTER TABLE case, don't complain about index keys not
1222 * created in the command; they may well exist already. DefineIndex
1223 * will complain about them if not, and will also take care of marking
1226 if (!found && !cxt->isalter)
1228 (errcode(ERRCODE_UNDEFINED_COLUMN),
1229 errmsg("column \"%s\" named in key does not exist",
1232 /* Check for PRIMARY KEY(foo, foo) */
1233 foreach(columns, index->indexParams)
1235 iparam = (IndexElem *) lfirst(columns);
1236 if (iparam->name && strcmp(key, iparam->name) == 0)
1240 (errcode(ERRCODE_DUPLICATE_COLUMN),
1241 errmsg("column \"%s\" appears twice in primary key constraint",
1245 (errcode(ERRCODE_DUPLICATE_COLUMN),
1246 errmsg("column \"%s\" appears twice in unique constraint",
1251 /* OK, add it to the index definition */
1252 iparam = makeNode(IndexElem);
1253 iparam->name = pstrdup(key);
1254 iparam->expr = NULL;
1255 iparam->opclass = NIL;
1256 iparam->ordering = SORTBY_DEFAULT;
1257 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1258 index->indexParams = lappend(index->indexParams, iparam);
1265 * transformFKConstraints
1266 * handle FOREIGN KEY constraints
1269 transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
1270 bool skipValidation, bool isAddConstraint)
1274 if (cxt->fkconstraints == NIL)
1278 * If CREATE TABLE or adding a column with NULL default, we can safely
1279 * skip validation of the constraint.
1283 foreach(fkclist, cxt->fkconstraints)
1285 Constraint *constraint = (Constraint *) lfirst(fkclist);
1287 constraint->skip_validation = true;
1292 * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
1293 * CONSTRAINT command to execute after the basic command is complete. (If
1294 * called from ADD CONSTRAINT, that routine will add the FK constraints to
1295 * its own subcommand list.)
1297 * Note: the ADD CONSTRAINT command must also execute after any index
1298 * creation commands. Thus, this should run after
1299 * transformIndexConstraints, so that the CREATE INDEX commands are
1300 * already in cxt->alist.
1302 if (!isAddConstraint)
1304 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1306 alterstmt->relation = cxt->relation;
1307 alterstmt->cmds = NIL;
1308 alterstmt->relkind = OBJECT_TABLE;
1310 foreach(fkclist, cxt->fkconstraints)
1312 Constraint *constraint = (Constraint *) lfirst(fkclist);
1313 AlterTableCmd *altercmd = makeNode(AlterTableCmd);
1315 altercmd->subtype = AT_ProcessedConstraint;
1316 altercmd->name = NULL;
1317 altercmd->def = (Node *) constraint;
1318 alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
1321 cxt->alist = lappend(cxt->alist, alterstmt);
1326 * transformIndexStmt - parse analysis for CREATE INDEX
1328 * Note: this is a no-op for an index not using either index expressions or
1329 * a predicate expression. There are several code paths that create indexes
1330 * without bothering to call this, because they know they don't have any
1331 * such expressions to deal with.
1334 transformIndexStmt(IndexStmt *stmt, const char *queryString)
1342 * We must not scribble on the passed-in IndexStmt, so copy it. (This is
1343 * overkill, but easy.)
1345 stmt = (IndexStmt *) copyObject(stmt);
1348 * Open the parent table with appropriate locking. We must do this
1349 * because addRangeTableEntry() would acquire only AccessShareLock,
1350 * leaving DefineIndex() needing to do a lock upgrade with consequent risk
1351 * of deadlock. Make sure this stays in sync with the type of lock
1352 * DefineIndex() wants.
1354 rel = heap_openrv(stmt->relation,
1355 (stmt->concurrent ? ShareUpdateExclusiveLock : ShareLock));
1358 pstate = make_parsestate(NULL);
1359 pstate->p_sourcetext = queryString;
1362 * Put the parent table into the rtable so that the expressions can refer
1363 * to its fields without qualification.
1365 rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1367 /* no to join list, yes to namespaces */
1368 addRTEtoQuery(pstate, rte, false, true, true);
1370 /* take care of the where clause */
1371 if (stmt->whereClause)
1372 stmt->whereClause = transformWhereClause(pstate,
1376 /* take care of any index expressions */
1377 foreach(l, stmt->indexParams)
1379 IndexElem *ielem = (IndexElem *) lfirst(l);
1383 ielem->expr = transformExpr(pstate, ielem->expr);
1386 * We check only that the result type is legitimate; this is for
1387 * consistency with what transformWhereClause() checks for the
1388 * predicate. DefineIndex() will make more checks.
1390 if (expression_returns_set(ielem->expr))
1392 (errcode(ERRCODE_DATATYPE_MISMATCH),
1393 errmsg("index expression cannot return a set")));
1398 * Check that only the base rel is mentioned.
1400 if (list_length(pstate->p_rtable) != 1)
1402 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1403 errmsg("index expressions and predicates can refer only to the table being indexed")));
1405 free_parsestate(pstate);
1407 /* Close relation, but keep the lock */
1408 heap_close(rel, NoLock);
1415 * transformRuleStmt -
1416 * transform a CREATE RULE Statement. The action is a list of parse
1417 * trees which is transformed into a list of query trees, and we also
1418 * transform the WHERE clause if any.
1420 * actions and whereClause are output parameters that receive the
1421 * transformed results.
1423 * Note that we must not scribble on the passed-in RuleStmt, so we do
1424 * copyObject() on the actions and WHERE clause.
1427 transformRuleStmt(RuleStmt *stmt, const char *queryString,
1428 List **actions, Node **whereClause)
1432 RangeTblEntry *oldrte;
1433 RangeTblEntry *newrte;
1436 * To avoid deadlock, make sure the first thing we do is grab
1437 * AccessExclusiveLock on the target relation. This will be needed by
1438 * DefineQueryRewrite(), and we don't want to grab a lesser lock
1441 rel = heap_openrv(stmt->relation, AccessExclusiveLock);
1444 pstate = make_parsestate(NULL);
1445 pstate->p_sourcetext = queryString;
1448 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
1449 * Set up their RTEs in the main pstate for use in parsing the rule
1452 oldrte = addRangeTableEntryForRelation(pstate, rel,
1453 makeAlias("*OLD*", NIL),
1455 newrte = addRangeTableEntryForRelation(pstate, rel,
1456 makeAlias("*NEW*", NIL),
1458 /* Must override addRangeTableEntry's default access-check flags */
1459 oldrte->requiredPerms = 0;
1460 newrte->requiredPerms = 0;
1463 * They must be in the namespace too for lookup purposes, but only add the
1464 * one(s) that are relevant for the current kind of rule. In an UPDATE
1465 * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
1466 * there's no need to be so picky for INSERT & DELETE. We do not add them
1469 switch (stmt->event)
1472 addRTEtoQuery(pstate, oldrte, false, true, true);
1475 addRTEtoQuery(pstate, oldrte, false, true, true);
1476 addRTEtoQuery(pstate, newrte, false, true, true);
1479 addRTEtoQuery(pstate, newrte, false, true, true);
1482 addRTEtoQuery(pstate, oldrte, false, true, true);
1485 elog(ERROR, "unrecognized event type: %d",
1490 /* take care of the where clause */
1491 *whereClause = transformWhereClause(pstate,
1492 (Node *) copyObject(stmt->whereClause),
1495 if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
1497 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1498 errmsg("rule WHERE condition cannot contain references to other relations")));
1500 /* aggregates not allowed (but subselects are okay) */
1501 if (pstate->p_hasAggs)
1503 (errcode(ERRCODE_GROUPING_ERROR),
1504 errmsg("cannot use aggregate function in rule WHERE condition")));
1505 if (pstate->p_hasWindowFuncs)
1507 (errcode(ERRCODE_WINDOWING_ERROR),
1508 errmsg("cannot use window function in rule WHERE condition")));
1511 * 'instead nothing' rules with a qualification need a query rangetable so
1512 * the rewrite handler can add the negated rule qualification to the
1513 * original query. We create a query with the new command type CMD_NOTHING
1514 * here that is treated specially by the rewrite system.
1516 if (stmt->actions == NIL)
1518 Query *nothing_qry = makeNode(Query);
1520 nothing_qry->commandType = CMD_NOTHING;
1521 nothing_qry->rtable = pstate->p_rtable;
1522 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
1524 *actions = list_make1(nothing_qry);
1529 List *newactions = NIL;
1532 * transform each statement, like parse_sub_analyze()
1534 foreach(l, stmt->actions)
1536 Node *action = (Node *) lfirst(l);
1537 ParseState *sub_pstate = make_parsestate(NULL);
1544 * Since outer ParseState isn't parent of inner, have to pass down
1545 * the query text by hand.
1547 sub_pstate->p_sourcetext = queryString;
1550 * Set up OLD/NEW in the rtable for this statement. The entries
1551 * are added only to relnamespace, not varnamespace, because we
1552 * don't want them to be referred to by unqualified field names
1553 * nor "*" in the rule actions. We decide later whether to put
1554 * them in the joinlist.
1556 oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
1557 makeAlias("*OLD*", NIL),
1559 newrte = addRangeTableEntryForRelation(sub_pstate, rel,
1560 makeAlias("*NEW*", NIL),
1562 oldrte->requiredPerms = 0;
1563 newrte->requiredPerms = 0;
1564 addRTEtoQuery(sub_pstate, oldrte, false, true, false);
1565 addRTEtoQuery(sub_pstate, newrte, false, true, false);
1567 /* Transform the rule action statement */
1568 top_subqry = transformStmt(sub_pstate,
1569 (Node *) copyObject(action));
1572 * We cannot support utility-statement actions (eg NOTIFY) with
1573 * nonempty rule WHERE conditions, because there's no way to make
1574 * the utility action execute conditionally.
1576 if (top_subqry->commandType == CMD_UTILITY &&
1577 *whereClause != NULL)
1579 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1580 errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
1583 * If the action is INSERT...SELECT, OLD/NEW have been pushed down
1584 * into the SELECT, and that's what we need to look at. (Ugly
1585 * kluge ... try to fix this when we redesign querytrees.)
1587 sub_qry = getInsertSelectQuery(top_subqry, NULL);
1590 * If the sub_qry is a setop, we cannot attach any qualifications
1591 * to it, because the planner won't notice them. This could
1592 * perhaps be relaxed someday, but for now, we may as well reject
1593 * such a rule immediately.
1595 if (sub_qry->setOperations != NULL && *whereClause != NULL)
1597 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1598 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1601 * Validate action's use of OLD/NEW, qual too
1604 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
1605 rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
1607 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
1608 rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
1610 switch (stmt->event)
1615 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1616 errmsg("ON SELECT rule cannot use OLD")));
1619 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1620 errmsg("ON SELECT rule cannot use NEW")));
1628 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1629 errmsg("ON INSERT rule cannot use OLD")));
1634 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1635 errmsg("ON DELETE rule cannot use NEW")));
1638 elog(ERROR, "unrecognized event type: %d",
1644 * For efficiency's sake, add OLD to the rule action's jointree
1645 * only if it was actually referenced in the statement or qual.
1647 * For INSERT, NEW is not really a relation (only a reference to
1648 * the to-be-inserted tuple) and should never be added to the
1651 * For UPDATE, we treat NEW as being another kind of reference to
1652 * OLD, because it represents references to *transformed* tuples
1653 * of the existing relation. It would be wrong to enter NEW
1654 * separately in the jointree, since that would cause a double
1655 * join of the updated relation. It's also wrong to fail to make
1656 * a jointree entry if only NEW and not OLD is mentioned.
1658 if (has_old || (has_new && stmt->event == CMD_UPDATE))
1661 * If sub_qry is a setop, manipulating its jointree will do no
1662 * good at all, because the jointree is dummy. (This should be
1663 * a can't-happen case because of prior tests.)
1665 if (sub_qry->setOperations != NULL)
1667 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1668 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1669 /* hack so we can use addRTEtoQuery() */
1670 sub_pstate->p_rtable = sub_qry->rtable;
1671 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
1672 addRTEtoQuery(sub_pstate, oldrte, true, false, false);
1673 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
1676 newactions = lappend(newactions, top_subqry);
1678 free_parsestate(sub_pstate);
1681 *actions = newactions;
1684 free_parsestate(pstate);
1686 /* Close relation, but keep the exclusive lock */
1687 heap_close(rel, NoLock);
1692 * transformAlterTableStmt -
1693 * parse analysis for ALTER TABLE
1695 * Returns a List of utility commands to be done in sequence. One of these
1696 * will be the transformed AlterTableStmt, but there may be additional actions
1697 * to be done before and after the actual AlterTable() call.
1700 transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString)
1704 CreateStmtContext cxt;
1709 List *newcmds = NIL;
1710 bool skipValidation = true;
1711 AlterTableCmd *newcmd;
1714 * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
1715 * is overkill, but easy.)
1717 stmt = (AlterTableStmt *) copyObject(stmt);
1720 * Acquire exclusive lock on the target relation, which will be held until
1721 * end of transaction. This ensures any decisions we make here based on
1722 * the state of the relation will still be good at execution. We must get
1723 * exclusive lock now because execution will; taking a lower grade lock
1724 * now and trying to upgrade later risks deadlock.
1726 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
1729 pstate = make_parsestate(NULL);
1730 pstate->p_sourcetext = queryString;
1732 cxt.stmtType = "ALTER TABLE";
1733 cxt.relation = stmt->relation;
1735 cxt.inhRelations = NIL;
1737 cxt.hasoids = false; /* need not be right */
1739 cxt.ckconstraints = NIL;
1740 cxt.fkconstraints = NIL;
1741 cxt.ixconstraints = NIL;
1742 cxt.inh_indexes = NIL;
1748 * The only subtypes that currently require parse transformation handling
1749 * are ADD COLUMN and ADD CONSTRAINT. These largely re-use code from
1752 foreach(lcmd, stmt->cmds)
1754 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
1756 switch (cmd->subtype)
1759 case AT_AddColumnToView:
1761 ColumnDef *def = (ColumnDef *) cmd->def;
1763 Assert(IsA(def, ColumnDef));
1764 transformColumnDefinition(pstate, &cxt, def);
1767 * If the column has a non-null default, we can't skip
1768 * validation of foreign keys.
1770 if (def->raw_default != NULL)
1771 skipValidation = false;
1774 * All constraints are processed in other ways. Remove the
1777 def->constraints = NIL;
1779 newcmds = lappend(newcmds, cmd);
1782 case AT_AddConstraint:
1785 * The original AddConstraint cmd node doesn't go to newcmds
1787 if (IsA(cmd->def, Constraint))
1789 transformTableConstraint(pstate, &cxt,
1790 (Constraint *) cmd->def);
1791 if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
1792 skipValidation = false;
1795 elog(ERROR, "unrecognized node type: %d",
1796 (int) nodeTag(cmd->def));
1799 case AT_ProcessedConstraint:
1802 * Already-transformed ADD CONSTRAINT, so just make it look
1803 * like the standard case.
1805 cmd->subtype = AT_AddConstraint;
1806 newcmds = lappend(newcmds, cmd);
1810 newcmds = lappend(newcmds, cmd);
1816 * transformIndexConstraints wants cxt.alist to contain only index
1817 * statements, so transfer anything we already have into save_alist
1820 save_alist = cxt.alist;
1823 /* Postprocess index and FK constraints */
1824 transformIndexConstraints(pstate, &cxt);
1826 transformFKConstraints(pstate, &cxt, skipValidation, true);
1829 * Push any index-creation commands into the ALTER, so that they can be
1830 * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
1831 * the IndexStmt attached to an AT_AddIndex subcommand has already been
1832 * through transformIndexStmt.
1834 foreach(l, cxt.alist)
1836 Node *idxstmt = (Node *) lfirst(l);
1838 Assert(IsA(idxstmt, IndexStmt));
1839 newcmd = makeNode(AlterTableCmd);
1840 newcmd->subtype = AT_AddIndex;
1841 newcmd->def = (Node *) transformIndexStmt((IndexStmt *) idxstmt,
1843 newcmds = lappend(newcmds, newcmd);
1847 /* Append any CHECK or FK constraints to the commands list */
1848 foreach(l, cxt.ckconstraints)
1850 newcmd = makeNode(AlterTableCmd);
1851 newcmd->subtype = AT_AddConstraint;
1852 newcmd->def = (Node *) lfirst(l);
1853 newcmds = lappend(newcmds, newcmd);
1855 foreach(l, cxt.fkconstraints)
1857 newcmd = makeNode(AlterTableCmd);
1858 newcmd->subtype = AT_AddConstraint;
1859 newcmd->def = (Node *) lfirst(l);
1860 newcmds = lappend(newcmds, newcmd);
1863 /* Close rel but keep lock */
1864 relation_close(rel, NoLock);
1869 stmt->cmds = newcmds;
1871 result = lappend(cxt.blist, stmt);
1872 result = list_concat(result, cxt.alist);
1873 result = list_concat(result, save_alist);
1880 * Preprocess a list of column constraint clauses
1881 * to attach constraint attributes to their primary constraint nodes
1882 * and detect inconsistent/misplaced constraint attributes.
1884 * NOTE: currently, attributes are only supported for FOREIGN KEY, UNIQUE,
1885 * and PRIMARY KEY constraints, but someday they ought to be supported
1886 * for other constraint types.
1889 transformConstraintAttrs(ParseState *pstate, List *constraintList)
1891 Constraint *lastprimarycon = NULL;
1892 bool saw_deferrability = false;
1893 bool saw_initially = false;
1896 #define SUPPORTS_ATTRS(node) \
1897 ((node) != NULL && \
1898 ((node)->contype == CONSTR_PRIMARY || \
1899 (node)->contype == CONSTR_UNIQUE || \
1900 (node)->contype == CONSTR_FOREIGN))
1902 foreach(clist, constraintList)
1904 Constraint *con = (Constraint *) lfirst(clist);
1906 if (!IsA(con, Constraint))
1907 elog(ERROR, "unrecognized node type: %d",
1908 (int) nodeTag(con));
1909 switch (con->contype)
1911 case CONSTR_ATTR_DEFERRABLE:
1912 if (!SUPPORTS_ATTRS(lastprimarycon))
1914 (errcode(ERRCODE_SYNTAX_ERROR),
1915 errmsg("misplaced DEFERRABLE clause"),
1916 parser_errposition(pstate, con->location)));
1917 if (saw_deferrability)
1919 (errcode(ERRCODE_SYNTAX_ERROR),
1920 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
1921 parser_errposition(pstate, con->location)));
1922 saw_deferrability = true;
1923 lastprimarycon->deferrable = true;
1926 case CONSTR_ATTR_NOT_DEFERRABLE:
1927 if (!SUPPORTS_ATTRS(lastprimarycon))
1929 (errcode(ERRCODE_SYNTAX_ERROR),
1930 errmsg("misplaced NOT DEFERRABLE clause"),
1931 parser_errposition(pstate, con->location)));
1932 if (saw_deferrability)
1934 (errcode(ERRCODE_SYNTAX_ERROR),
1935 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
1936 parser_errposition(pstate, con->location)));
1937 saw_deferrability = true;
1938 lastprimarycon->deferrable = false;
1939 if (saw_initially &&
1940 lastprimarycon->initdeferred)
1942 (errcode(ERRCODE_SYNTAX_ERROR),
1943 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
1944 parser_errposition(pstate, con->location)));
1947 case CONSTR_ATTR_DEFERRED:
1948 if (!SUPPORTS_ATTRS(lastprimarycon))
1950 (errcode(ERRCODE_SYNTAX_ERROR),
1951 errmsg("misplaced INITIALLY DEFERRED clause"),
1952 parser_errposition(pstate, con->location)));
1955 (errcode(ERRCODE_SYNTAX_ERROR),
1956 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
1957 parser_errposition(pstate, con->location)));
1958 saw_initially = true;
1959 lastprimarycon->initdeferred = true;
1962 * If only INITIALLY DEFERRED appears, assume DEFERRABLE
1964 if (!saw_deferrability)
1965 lastprimarycon->deferrable = true;
1966 else if (!lastprimarycon->deferrable)
1968 (errcode(ERRCODE_SYNTAX_ERROR),
1969 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
1970 parser_errposition(pstate, con->location)));
1973 case CONSTR_ATTR_IMMEDIATE:
1974 if (!SUPPORTS_ATTRS(lastprimarycon))
1976 (errcode(ERRCODE_SYNTAX_ERROR),
1977 errmsg("misplaced INITIALLY IMMEDIATE clause"),
1978 parser_errposition(pstate, con->location)));
1981 (errcode(ERRCODE_SYNTAX_ERROR),
1982 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
1983 parser_errposition(pstate, con->location)));
1984 saw_initially = true;
1985 lastprimarycon->initdeferred = false;
1989 /* Otherwise it's not an attribute */
1990 lastprimarycon = con;
1991 /* reset flags for new primary node */
1992 saw_deferrability = false;
1993 saw_initially = false;
2000 * Special handling of type definition for a column
2003 transformColumnType(ParseState *pstate, ColumnDef *column)
2006 * All we really need to do here is verify that the type is valid.
2008 Type ctype = typenameType(pstate, column->typeName, NULL);
2010 ReleaseSysCache(ctype);
2015 * transformCreateSchemaStmt -
2016 * analyzes the CREATE SCHEMA statement
2018 * Split the schema element list into individual commands and place
2019 * them in the result list in an order such that there are no forward
2020 * references (e.g. GRANT to a table created later in the list). Note
2021 * that the logic we use for determining forward references is
2022 * presently quite incomplete.
2024 * SQL92 also allows constraints to make forward references, so thumb through
2025 * the table columns and move forward references to a posterior alter-table
2028 * The result is a list of parse nodes that still need to be analyzed ---
2029 * but we can't analyze the later commands until we've executed the earlier
2030 * ones, because of possible inter-object references.
2032 * Note: this breaks the rules a little bit by modifying schema-name fields
2033 * within passed-in structs. However, the transformation would be the same
2034 * if done over, so it should be all right to scribble on the input to this
2038 transformCreateSchemaStmt(CreateSchemaStmt *stmt)
2040 CreateSchemaStmtContext cxt;
2044 cxt.stmtType = "CREATE SCHEMA";
2045 cxt.schemaname = stmt->schemaname;
2046 cxt.authid = stmt->authid;
2047 cxt.sequences = NIL;
2055 * Run through each schema element in the schema element list. Separate
2056 * statements by type, and do preliminary analysis.
2058 foreach(elements, stmt->schemaElts)
2060 Node *element = lfirst(elements);
2062 switch (nodeTag(element))
2064 case T_CreateSeqStmt:
2066 CreateSeqStmt *elp = (CreateSeqStmt *) element;
2068 setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
2069 cxt.sequences = lappend(cxt.sequences, element);
2075 CreateStmt *elp = (CreateStmt *) element;
2077 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2080 * XXX todo: deal with constraints
2082 cxt.tables = lappend(cxt.tables, element);
2088 ViewStmt *elp = (ViewStmt *) element;
2090 setSchemaName(cxt.schemaname, &elp->view->schemaname);
2093 * XXX todo: deal with references between views
2095 cxt.views = lappend(cxt.views, element);
2101 IndexStmt *elp = (IndexStmt *) element;
2103 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2104 cxt.indexes = lappend(cxt.indexes, element);
2108 case T_CreateTrigStmt:
2110 CreateTrigStmt *elp = (CreateTrigStmt *) element;
2112 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2113 cxt.triggers = lappend(cxt.triggers, element);
2118 cxt.grants = lappend(cxt.grants, element);
2122 elog(ERROR, "unrecognized node type: %d",
2123 (int) nodeTag(element));
2128 result = list_concat(result, cxt.sequences);
2129 result = list_concat(result, cxt.tables);
2130 result = list_concat(result, cxt.views);
2131 result = list_concat(result, cxt.indexes);
2132 result = list_concat(result, cxt.triggers);
2133 result = list_concat(result, cxt.grants);
2140 * Set or check schema name in an element of a CREATE SCHEMA command
2143 setSchemaName(char *context_schema, char **stmt_schema_name)
2145 if (*stmt_schema_name == NULL)
2146 *stmt_schema_name = context_schema;
2147 else if (strcmp(context_schema, *stmt_schema_name) != 0)
2149 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
2150 errmsg("CREATE specifies a schema (%s) "
2151 "different from the one being created (%s)",
2152 *stmt_schema_name, context_schema)));