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-2007, 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.5 2007/11/11 19:22:49 tgl Exp $
24 *-------------------------------------------------------------------------
29 #include "access/genam.h"
30 #include "access/heapam.h"
31 #include "catalog/heap.h"
32 #include "catalog/index.h"
33 #include "catalog/namespace.h"
34 #include "catalog/pg_opclass.h"
35 #include "catalog/pg_type.h"
36 #include "commands/defrem.h"
37 #include "commands/tablecmds.h"
38 #include "commands/tablespace.h"
39 #include "miscadmin.h"
40 #include "nodes/makefuncs.h"
41 #include "optimizer/clauses.h"
42 #include "parser/analyze.h"
43 #include "parser/gramparse.h"
44 #include "parser/parse_clause.h"
45 #include "parser/parse_expr.h"
46 #include "parser/parse_relation.h"
47 #include "parser/parse_type.h"
48 #include "parser/parse_utilcmd.h"
49 #include "rewrite/rewriteManip.h"
50 #include "utils/acl.h"
51 #include "utils/builtins.h"
52 #include "utils/lsyscache.h"
53 #include "utils/relcache.h"
54 #include "utils/syscache.h"
57 /* State shared by transformCreateStmt and its subroutines */
60 const char *stmtType; /* "CREATE TABLE" or "ALTER TABLE" */
61 RangeVar *relation; /* relation to create */
62 Relation rel; /* opened/locked rel, if ALTER */
63 List *inhRelations; /* relations to inherit from */
64 bool isalter; /* true if altering existing table */
65 bool hasoids; /* does relation have an OID column? */
66 List *columns; /* ColumnDef items */
67 List *ckconstraints; /* CHECK constraints */
68 List *fkconstraints; /* FOREIGN KEY constraints */
69 List *ixconstraints; /* index-creating constraints */
70 List *inh_indexes; /* cloned indexes from INCLUDING INDEXES */
71 List *blist; /* "before list" of things to do before
72 * creating the table */
73 List *alist; /* "after list" of things to do after creating
75 IndexStmt *pkey; /* PRIMARY KEY index, if any */
78 /* State shared by transformCreateSchemaStmt and its subroutines */
81 const char *stmtType; /* "CREATE SCHEMA" or "ALTER SCHEMA" */
82 char *schemaname; /* name of schema */
83 char *authid; /* owner of schema */
84 List *sequences; /* CREATE SEQUENCE items */
85 List *tables; /* CREATE TABLE items */
86 List *views; /* CREATE VIEW items */
87 List *indexes; /* CREATE INDEX items */
88 List *triggers; /* CREATE TRIGGER items */
89 List *grants; /* GRANT items */
90 } CreateSchemaStmtContext;
93 static void transformColumnDefinition(ParseState *pstate,
94 CreateStmtContext *cxt,
96 static void transformTableConstraint(ParseState *pstate,
97 CreateStmtContext *cxt,
98 Constraint *constraint);
99 static void transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
100 InhRelation *inhrelation);
101 static IndexStmt *generateClonedIndexStmt(CreateStmtContext *cxt,
102 Relation parent_index, AttrNumber *attmap);
103 static List *get_opclass(Oid opclass, Oid actual_datatype);
104 static void transformIndexConstraints(ParseState *pstate,
105 CreateStmtContext *cxt);
106 static IndexStmt *transformIndexConstraint(Constraint *constraint,
107 CreateStmtContext *cxt);
108 static void transformFKConstraints(ParseState *pstate,
109 CreateStmtContext *cxt,
111 bool isAddConstraint);
112 static void transformConstraintAttrs(List *constraintList);
113 static void transformColumnType(ParseState *pstate, ColumnDef *column);
114 static void setSchemaName(char *context_schema, char **stmt_schema_name);
118 * transformCreateStmt -
119 * parse analysis for CREATE TABLE
121 * Returns a List of utility commands to be done in sequence. One of these
122 * will be the transformed CreateStmt, but there may be additional actions
123 * to be done before and after the actual DefineRelation() call.
125 * SQL92 allows constraints to be scattered all over, so thumb through
126 * the columns and collect all constraints into one place.
127 * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
128 * then expand those into multiple IndexStmt blocks.
129 * - thomas 1997-12-02
132 transformCreateStmt(CreateStmt *stmt, const char *queryString)
135 CreateStmtContext cxt;
141 * We must not scribble on the passed-in CreateStmt, so copy it. (This
142 * is overkill, but easy.)
144 stmt = (CreateStmt *) copyObject(stmt);
147 * If the target relation name isn't schema-qualified, make it so. This
148 * prevents some corner cases in which added-on rewritten commands might
149 * think they should apply to other relations that have the same name
150 * and are earlier in the search path. "istemp" is equivalent to a
151 * specification of pg_temp, so no need for anything extra in that case.
153 if (stmt->relation->schemaname == NULL && !stmt->relation->istemp)
155 Oid namespaceid = RangeVarGetCreationNamespace(stmt->relation);
157 stmt->relation->schemaname = get_namespace_name(namespaceid);
161 pstate = make_parsestate(NULL);
162 pstate->p_sourcetext = queryString;
164 cxt.stmtType = "CREATE TABLE";
165 cxt.relation = stmt->relation;
167 cxt.inhRelations = stmt->inhRelations;
170 cxt.ckconstraints = NIL;
171 cxt.fkconstraints = NIL;
172 cxt.ixconstraints = NIL;
173 cxt.inh_indexes = NIL;
177 cxt.hasoids = interpretOidsOption(stmt->options);
180 * Run through each primary element in the table creation clause. Separate
181 * column defs from constraints, and do preliminary analysis.
183 foreach(elements, stmt->tableElts)
185 Node *element = lfirst(elements);
187 switch (nodeTag(element))
190 transformColumnDefinition(pstate, &cxt,
191 (ColumnDef *) element);
195 transformTableConstraint(pstate, &cxt,
196 (Constraint *) element);
200 /* No pre-transformation needed */
201 cxt.fkconstraints = lappend(cxt.fkconstraints, element);
205 transformInhRelation(pstate, &cxt,
206 (InhRelation *) element);
210 elog(ERROR, "unrecognized node type: %d",
211 (int) nodeTag(element));
217 * transformIndexConstraints wants cxt.alist to contain only index
218 * statements, so transfer anything we already have into save_alist.
220 save_alist = cxt.alist;
223 Assert(stmt->constraints == NIL);
226 * Postprocess constraints that give rise to index definitions.
228 transformIndexConstraints(pstate, &cxt);
231 * Postprocess foreign-key constraints.
233 transformFKConstraints(pstate, &cxt, true, false);
238 stmt->tableElts = cxt.columns;
239 stmt->constraints = cxt.ckconstraints;
241 result = lappend(cxt.blist, stmt);
242 result = list_concat(result, cxt.alist);
243 result = list_concat(result, save_alist);
249 * transformColumnDefinition -
250 * transform a single ColumnDef within CREATE TABLE
251 * Also used in ALTER TABLE ADD COLUMN
254 transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
260 Constraint *constraint;
263 cxt->columns = lappend(cxt->columns, column);
265 /* Check for SERIAL pseudo-types */
267 if (list_length(column->typename->names) == 1)
269 char *typname = strVal(linitial(column->typename->names));
271 if (strcmp(typname, "serial") == 0 ||
272 strcmp(typname, "serial4") == 0)
275 column->typename->names = NIL;
276 column->typename->typeid = INT4OID;
278 else if (strcmp(typname, "bigserial") == 0 ||
279 strcmp(typname, "serial8") == 0)
282 column->typename->names = NIL;
283 column->typename->typeid = INT8OID;
287 /* Do necessary work on the column type declaration */
288 transformColumnType(pstate, column);
290 /* Special actions for SERIAL pseudo-types */
298 FuncCall *funccallnode;
299 CreateSeqStmt *seqstmt;
300 AlterSeqStmt *altseqstmt;
304 * Determine namespace and name to use for the sequence.
306 * Although we use ChooseRelationName, it's not guaranteed that the
307 * selected sequence name won't conflict; given sufficiently long
308 * field names, two different serial columns in the same table could
309 * be assigned the same sequence name, and we'd not notice since we
310 * aren't creating the sequence quite yet. In practice this seems
311 * quite unlikely to be a problem, especially since few people would
312 * need two serial columns in one table.
315 snamespaceid = RelationGetNamespace(cxt->rel);
317 snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
318 snamespace = get_namespace_name(snamespaceid);
319 sname = ChooseRelationName(cxt->relation->relname,
325 (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
326 cxt->stmtType, sname,
327 cxt->relation->relname, column->colname)));
330 * Build a CREATE SEQUENCE command to create the sequence object, and
331 * add it to the list of things to be done before this CREATE/ALTER
334 seqstmt = makeNode(CreateSeqStmt);
335 seqstmt->sequence = makeRangeVar(snamespace, sname);
336 seqstmt->options = NIL;
338 cxt->blist = lappend(cxt->blist, seqstmt);
341 * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence
342 * as owned by this column, and add it to the list of things to be
343 * done after this CREATE/ALTER TABLE.
345 altseqstmt = makeNode(AlterSeqStmt);
346 altseqstmt->sequence = makeRangeVar(snamespace, sname);
347 attnamelist = list_make3(makeString(snamespace),
348 makeString(cxt->relation->relname),
349 makeString(column->colname));
350 altseqstmt->options = list_make1(makeDefElem("owned_by",
351 (Node *) attnamelist));
353 cxt->alist = lappend(cxt->alist, altseqstmt);
356 * Create appropriate constraints for SERIAL. We do this in full,
357 * rather than shortcutting, so that we will detect any conflicting
358 * constraints the user wrote (like a different DEFAULT).
360 * Create an expression tree representing the function call
361 * nextval('sequencename'). We cannot reduce the raw tree to cooked
362 * form until after the sequence is created, but there's no need to do
365 qstring = quote_qualified_identifier(snamespace, sname);
366 snamenode = makeNode(A_Const);
367 snamenode->val.type = T_String;
368 snamenode->val.val.str = qstring;
369 snamenode->typename = SystemTypeName("regclass");
370 funccallnode = makeNode(FuncCall);
371 funccallnode->funcname = SystemFuncName("nextval");
372 funccallnode->args = list_make1(snamenode);
373 funccallnode->agg_star = false;
374 funccallnode->agg_distinct = false;
375 funccallnode->location = -1;
377 constraint = makeNode(Constraint);
378 constraint->contype = CONSTR_DEFAULT;
379 constraint->raw_expr = (Node *) funccallnode;
380 constraint->cooked_expr = NULL;
381 constraint->keys = NIL;
382 column->constraints = lappend(column->constraints, constraint);
384 constraint = makeNode(Constraint);
385 constraint->contype = CONSTR_NOTNULL;
386 column->constraints = lappend(column->constraints, constraint);
389 /* Process column constraints, if any... */
390 transformConstraintAttrs(column->constraints);
392 saw_nullable = false;
395 foreach(clist, column->constraints)
397 constraint = lfirst(clist);
400 * If this column constraint is a FOREIGN KEY constraint, then we fill
401 * in the current attribute's name and throw it into the list of FK
402 * constraints to be processed later.
404 if (IsA(constraint, FkConstraint))
406 FkConstraint *fkconstraint = (FkConstraint *) constraint;
408 fkconstraint->fk_attrs = list_make1(makeString(column->colname));
409 cxt->fkconstraints = lappend(cxt->fkconstraints, fkconstraint);
413 Assert(IsA(constraint, Constraint));
415 switch (constraint->contype)
418 if (saw_nullable && column->is_not_null)
420 (errcode(ERRCODE_SYNTAX_ERROR),
421 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
422 column->colname, cxt->relation->relname)));
423 column->is_not_null = FALSE;
428 if (saw_nullable && !column->is_not_null)
430 (errcode(ERRCODE_SYNTAX_ERROR),
431 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
432 column->colname, cxt->relation->relname)));
433 column->is_not_null = TRUE;
440 (errcode(ERRCODE_SYNTAX_ERROR),
441 errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
442 column->colname, cxt->relation->relname)));
443 column->raw_default = constraint->raw_expr;
444 Assert(constraint->cooked_expr == NULL);
450 if (constraint->keys == NIL)
451 constraint->keys = list_make1(makeString(column->colname));
452 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
456 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
459 case CONSTR_ATTR_DEFERRABLE:
460 case CONSTR_ATTR_NOT_DEFERRABLE:
461 case CONSTR_ATTR_DEFERRED:
462 case CONSTR_ATTR_IMMEDIATE:
463 /* transformConstraintAttrs took care of these */
467 elog(ERROR, "unrecognized constraint type: %d",
468 constraint->contype);
475 * transformTableConstraint
476 * transform a Constraint node within CREATE TABLE or ALTER TABLE
479 transformTableConstraint(ParseState *pstate, CreateStmtContext *cxt,
480 Constraint *constraint)
482 switch (constraint->contype)
486 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
490 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
496 case CONSTR_ATTR_DEFERRABLE:
497 case CONSTR_ATTR_NOT_DEFERRABLE:
498 case CONSTR_ATTR_DEFERRED:
499 case CONSTR_ATTR_IMMEDIATE:
500 elog(ERROR, "invalid context for constraint type %d",
501 constraint->contype);
505 elog(ERROR, "unrecognized constraint type: %d",
506 constraint->contype);
512 * transformInhRelation
514 * Change the LIKE <subtable> portion of a CREATE TABLE statement into
515 * column definitions which recreate the user defined column portions of
519 transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
520 InhRelation *inhRelation)
522 AttrNumber parent_attno;
527 bool including_defaults = false;
528 bool including_constraints = false;
529 bool including_indexes = false;
532 relation = heap_openrv(inhRelation->relation, AccessShareLock);
534 if (relation->rd_rel->relkind != RELKIND_RELATION)
536 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
537 errmsg("inherited relation \"%s\" is not a table",
538 inhRelation->relation->relname)));
541 * Check for SELECT privilages
543 aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
545 if (aclresult != ACLCHECK_OK)
546 aclcheck_error(aclresult, ACL_KIND_CLASS,
547 RelationGetRelationName(relation));
549 tupleDesc = RelationGetDescr(relation);
550 constr = tupleDesc->constr;
552 foreach(elem, inhRelation->options)
554 int option = lfirst_int(elem);
558 case CREATE_TABLE_LIKE_INCLUDING_DEFAULTS:
559 including_defaults = true;
561 case CREATE_TABLE_LIKE_EXCLUDING_DEFAULTS:
562 including_defaults = false;
564 case CREATE_TABLE_LIKE_INCLUDING_CONSTRAINTS:
565 including_constraints = true;
567 case CREATE_TABLE_LIKE_EXCLUDING_CONSTRAINTS:
568 including_constraints = false;
570 case CREATE_TABLE_LIKE_INCLUDING_INDEXES:
571 including_indexes = true;
573 case CREATE_TABLE_LIKE_EXCLUDING_INDEXES:
574 including_indexes = false;
577 elog(ERROR, "unrecognized CREATE TABLE LIKE option: %d",
583 * Insert the copied attributes into the cxt for the new table
586 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
589 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
590 char *attributeName = NameStr(attribute->attname);
594 * Ignore dropped columns in the parent.
596 if (attribute->attisdropped)
600 * Create a new column, which is marked as NOT inherited.
602 * For constraints, ONLY the NOT NULL constraint is inherited by the
603 * new column definition per SQL99.
605 def = makeNode(ColumnDef);
606 def->colname = pstrdup(attributeName);
607 def->typename = makeTypeNameFromOid(attribute->atttypid,
608 attribute->atttypmod);
610 def->is_local = true;
611 def->is_not_null = attribute->attnotnull;
612 def->raw_default = NULL;
613 def->cooked_default = NULL;
614 def->constraints = NIL;
619 cxt->columns = lappend(cxt->columns, def);
622 * Copy default, if present and the default has been requested
624 if (attribute->atthasdef && including_defaults)
626 char *this_default = NULL;
627 AttrDefault *attrdef;
630 /* Find default in constraint structure */
631 Assert(constr != NULL);
632 attrdef = constr->defval;
633 for (i = 0; i < constr->num_defval; i++)
635 if (attrdef[i].adnum == parent_attno)
637 this_default = attrdef[i].adbin;
641 Assert(this_default != NULL);
644 * If default expr could contain any vars, we'd need to fix 'em,
645 * but it can't; so default is ready to apply to child.
648 def->cooked_default = pstrdup(this_default);
653 * Copy CHECK constraints if requested, being careful to adjust
656 if (including_constraints && tupleDesc->constr)
658 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
661 for (ccnum = 0; ccnum < tupleDesc->constr->num_check; ccnum++)
663 char *ccname = tupleDesc->constr->check[ccnum].ccname;
664 char *ccbin = tupleDesc->constr->check[ccnum].ccbin;
665 Node *ccbin_node = stringToNode(ccbin);
666 Constraint *n = makeNode(Constraint);
668 change_varattnos_of_a_node(ccbin_node, attmap);
670 n->contype = CONSTR_CHECK;
671 n->name = pstrdup(ccname);
673 n->cooked_expr = nodeToString(ccbin_node);
674 n->indexspace = NULL;
675 cxt->ckconstraints = lappend(cxt->ckconstraints, (Node *) n);
679 if (including_indexes && relation->rd_rel->relhasindex)
682 List *parent_indexes;
685 attmap = varattnos_map_schema(tupleDesc, cxt->columns);
686 parent_indexes = RelationGetIndexList(relation);
688 foreach(l, parent_indexes)
690 Oid parent_index_oid = lfirst_oid(l);
691 Relation parent_index;
692 IndexStmt *index_stmt;
694 parent_index = index_open(parent_index_oid, AccessShareLock);
696 /* Build CREATE INDEX statement to recreate the parent_index */
697 index_stmt = generateClonedIndexStmt(cxt, parent_index,
700 /* Add the new IndexStmt to the create context */
701 cxt->inh_indexes = lappend(cxt->inh_indexes, index_stmt);
703 /* Keep our lock on the index till xact commit */
704 index_close(parent_index, NoLock);
709 * Close the parent rel, but keep our AccessShareLock on it until xact
710 * commit. That will prevent someone else from deleting or ALTERing the
711 * parent before the child is committed.
713 heap_close(relation, NoLock);
717 * Generate an IndexStmt entry using information from an already
718 * existing index "source_idx".
720 * Note: Much of this functionality is cribbed from pg_get_indexdef.
723 generateClonedIndexStmt(CreateStmtContext *cxt, Relation source_idx,
729 Form_pg_index idxrec;
730 Form_pg_class idxrelrec;
732 List *indexprs = NIL;
733 ListCell *indexpr_item;
739 Datum indoptionDatum;
742 int2vector *indoption;
746 source_relid = RelationGetRelid(source_idx);
748 /* Fetch pg_index tuple for source index */
749 ht_idx = SearchSysCache(INDEXRELID,
750 ObjectIdGetDatum(source_relid),
752 if (!HeapTupleIsValid(ht_idx))
753 elog(ERROR, "cache lookup failed for index %u", source_relid);
754 idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
756 Assert(source_relid == idxrec->indexrelid);
757 indrelid = idxrec->indrelid;
759 index = makeNode(IndexStmt);
760 index->unique = idxrec->indisunique;
761 index->concurrent = false;
762 index->primary = idxrec->indisprimary;
763 index->relation = cxt->relation;
764 index->isconstraint = false;
767 * We don't try to preserve the name of the source index; instead, just
768 * let DefineIndex() choose a reasonable name.
770 index->idxname = NULL;
772 /* Must get indclass and indoption the hard way */
773 indclassDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
774 Anum_pg_index_indclass, &isnull);
776 indclass = (oidvector *) DatumGetPointer(indclassDatum);
777 indoptionDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
778 Anum_pg_index_indoption, &isnull);
780 indoption = (int2vector *) DatumGetPointer(indoptionDatum);
782 /* Fetch pg_class tuple of source index */
783 ht_idxrel = SearchSysCache(RELOID,
784 ObjectIdGetDatum(source_relid),
786 if (!HeapTupleIsValid(ht_idxrel))
787 elog(ERROR, "cache lookup failed for relation %u", source_relid);
790 * Store the reloptions for later use by this new index
792 reloptions = SysCacheGetAttr(RELOID, ht_idxrel,
793 Anum_pg_class_reloptions, &isnull);
795 index->src_options = flatten_reloptions(source_relid);
797 idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
799 /* Fetch pg_am tuple for the index's access method */
800 ht_am = SearchSysCache(AMOID,
801 ObjectIdGetDatum(idxrelrec->relam),
803 if (!HeapTupleIsValid(ht_am))
804 elog(ERROR, "cache lookup failed for access method %u",
806 amrec = (Form_pg_am) GETSTRUCT(ht_am);
807 index->accessMethod = pstrdup(NameStr(amrec->amname));
809 /* Get the index expressions, if any */
810 if (!heap_attisnull(ht_idx, Anum_pg_index_indexprs))
816 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
817 Anum_pg_index_indexprs, &isnull);
818 exprsString = DatumGetCString(DirectFunctionCall1(textout,
821 indexprs = (List *) stringToNode(exprsString);
824 indexpr_item = list_head(indexprs);
826 for (keyno = 0; keyno < idxrec->indnatts; keyno++)
829 AttrNumber attnum = idxrec->indkey.values[keyno];
830 int16 opt = indoption->values[keyno];
832 iparam = makeNode(IndexElem);
834 if (AttributeNumberIsValid(attnum))
836 /* Simple index column */
839 attname = get_relid_attribute_name(indrelid, attnum);
840 keycoltype = get_atttype(indrelid, attnum);
842 iparam->name = attname;
847 /* Expressional index */
850 if (indexpr_item == NULL)
851 elog(ERROR, "too few entries in indexprs list");
852 indexkey = (Node *) lfirst(indexpr_item);
853 change_varattnos_of_a_node(indexkey, attmap);
855 iparam->expr = indexkey;
857 indexpr_item = lnext(indexpr_item);
858 keycoltype = exprType(indexkey);
861 /* Add the operator class name, if non-default */
862 iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
864 iparam->ordering = SORTBY_DEFAULT;
865 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
867 /* Adjust options if necessary */
868 if (amrec->amcanorder)
870 /* If it supports sort ordering, report DESC and NULLS opts */
871 if (opt & INDOPTION_DESC)
872 iparam->ordering = SORTBY_DESC;
873 if (opt & INDOPTION_NULLS_FIRST)
874 iparam->nulls_ordering = SORTBY_NULLS_FIRST;
877 index->indexParams = lappend(index->indexParams, iparam);
880 /* Use the same tablespace as the source index */
881 index->tableSpace = get_tablespace_name(source_idx->rd_node.spcNode);
883 /* If it's a partial index, decompile and append the predicate */
884 if (!heap_attisnull(ht_idx, Anum_pg_index_indpred))
890 /* Convert text string to node tree */
891 pred_datum = SysCacheGetAttr(INDEXRELID, ht_idx,
892 Anum_pg_index_indpred, &isnull);
894 pred_str = DatumGetCString(DirectFunctionCall1(textout,
896 index->whereClause = (Node *) stringToNode(pred_str);
897 change_varattnos_of_a_node(index->whereClause, attmap);
901 ReleaseSysCache(ht_idx);
902 ReleaseSysCache(ht_idxrel);
903 ReleaseSysCache(ht_am);
909 * get_opclass - fetch name of an index operator class
911 * If the opclass is the default for the given actual_datatype, then
912 * the return value is NIL.
915 get_opclass(Oid opclass, Oid actual_datatype)
918 Form_pg_opclass opc_rec;
921 ht_opc = SearchSysCache(CLAOID,
922 ObjectIdGetDatum(opclass),
924 if (!HeapTupleIsValid(ht_opc))
925 elog(ERROR, "cache lookup failed for opclass %u", opclass);
926 opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
928 if (!OidIsValid(actual_datatype) ||
929 GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
931 char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
932 char *opc_name = NameStr(opc_rec->opcname);
934 result = list_make2(makeString(nsp_name), makeString(opc_name));
937 ReleaseSysCache(ht_opc);
943 * transformIndexConstraints
944 * Handle UNIQUE and PRIMARY KEY constraints, which create
945 * indexes. We also merge index definitions arising from
946 * LIKE ... INCLUDING INDEXES.
949 transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
952 List *indexlist = NIL;
956 * Run through the constraints that need to generate an index. For PRIMARY
957 * KEY, mark each column as NOT NULL and create an index. For UNIQUE,
958 * create an index as for PRIMARY KEY, but do not insist on NOT NULL.
960 foreach(lc, cxt->ixconstraints)
962 Constraint *constraint = (Constraint *) lfirst(lc);
964 index = transformIndexConstraint(constraint, cxt);
965 indexlist = lappend(indexlist, index);
969 * Scan the index list and remove any redundant index specifications. This
970 * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
971 * strict reading of SQL92 would suggest raising an error instead, but
972 * that strikes me as too anal-retentive. - tgl 2001-02-14
974 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
975 * pre-existing indexes, too.
977 Assert(cxt->alist == NIL);
978 if (cxt->pkey != NULL)
980 /* Make sure we keep the PKEY index in preference to others... */
981 cxt->alist = list_make1(cxt->pkey);
984 foreach(lc, indexlist)
991 /* if it's pkey, it's already in cxt->alist */
992 if (index == cxt->pkey)
995 foreach(k, cxt->alist)
997 IndexStmt *priorindex = lfirst(k);
999 if (equal(index->indexParams, priorindex->indexParams))
1002 * If the prior index is as yet unnamed, and this one is
1003 * named, then transfer the name to the prior index. This
1004 * ensures that if we have named and unnamed constraints,
1005 * we'll use (at least one of) the names for the index.
1007 if (priorindex->idxname == NULL)
1008 priorindex->idxname = index->idxname;
1015 cxt->alist = lappend(cxt->alist, index);
1018 /* Copy indexes defined by LIKE ... INCLUDING INDEXES */
1019 foreach(lc, cxt->inh_indexes)
1021 index = (IndexStmt *) lfirst(lc);
1027 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1028 errmsg("multiple primary keys for table \"%s\" are not allowed",
1029 cxt->relation->relname)));
1034 cxt->alist = lappend(cxt->alist, index);
1039 transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
1045 Assert(constraint->contype == CONSTR_PRIMARY ||
1046 constraint->contype == CONSTR_UNIQUE);
1048 index = makeNode(IndexStmt);
1049 index->unique = true;
1050 index->primary = (constraint->contype == CONSTR_PRIMARY);
1054 if (cxt->pkey != NULL)
1056 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1057 errmsg("multiple primary keys for table \"%s\" are not allowed",
1058 cxt->relation->relname)));
1062 * In ALTER TABLE case, a primary index might already exist, but
1063 * DefineIndex will check for it.
1066 index->isconstraint = true;
1068 if (constraint->name != NULL)
1069 index->idxname = pstrdup(constraint->name);
1071 index->idxname = NULL; /* DefineIndex will choose name */
1073 index->relation = cxt->relation;
1074 index->accessMethod = DEFAULT_INDEX_TYPE;
1075 index->options = constraint->options;
1076 index->tableSpace = constraint->indexspace;
1077 index->indexParams = NIL;
1078 index->whereClause = NULL;
1079 index->concurrent = false;
1082 * Make sure referenced keys exist. If we are making a PRIMARY KEY
1083 * index, also make sure they are NOT NULL, if possible. (Although we
1084 * could leave it to DefineIndex to mark the columns NOT NULL, it's
1085 * more efficient to get it right the first time.)
1087 foreach(keys, constraint->keys)
1089 char *key = strVal(lfirst(keys));
1091 ColumnDef *column = NULL;
1094 foreach(columns, cxt->columns)
1096 column = (ColumnDef *) lfirst(columns);
1097 Assert(IsA(column, ColumnDef));
1098 if (strcmp(column->colname, key) == 0)
1106 /* found column in the new table; force it to be NOT NULL */
1107 if (constraint->contype == CONSTR_PRIMARY)
1108 column->is_not_null = TRUE;
1110 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1113 * column will be a system column in the new table, so accept
1114 * it. System columns can't ever be null, so no need to worry
1115 * about PRIMARY/NOT NULL constraint.
1119 else if (cxt->inhRelations)
1121 /* try inherited tables */
1124 foreach(inher, cxt->inhRelations)
1126 RangeVar *inh = (RangeVar *) lfirst(inher);
1130 Assert(IsA(inh, RangeVar));
1131 rel = heap_openrv(inh, AccessShareLock);
1132 if (rel->rd_rel->relkind != RELKIND_RELATION)
1134 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1135 errmsg("inherited relation \"%s\" is not a table",
1137 for (count = 0; count < rel->rd_att->natts; count++)
1139 Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1140 char *inhname = NameStr(inhattr->attname);
1142 if (inhattr->attisdropped)
1144 if (strcmp(key, inhname) == 0)
1149 * We currently have no easy way to force an
1150 * inherited column to be NOT NULL at creation, if
1151 * its parent wasn't so already. We leave it to
1152 * DefineIndex to fix things up in this case.
1157 heap_close(rel, NoLock);
1164 * In the ALTER TABLE case, don't complain about index keys not
1165 * created in the command; they may well exist already.
1166 * DefineIndex will complain about them if not, and will also take
1167 * care of marking them NOT NULL.
1169 if (!found && !cxt->isalter)
1171 (errcode(ERRCODE_UNDEFINED_COLUMN),
1172 errmsg("column \"%s\" named in key does not exist",
1175 /* Check for PRIMARY KEY(foo, foo) */
1176 foreach(columns, index->indexParams)
1178 iparam = (IndexElem *) lfirst(columns);
1179 if (iparam->name && strcmp(key, iparam->name) == 0)
1183 (errcode(ERRCODE_DUPLICATE_COLUMN),
1184 errmsg("column \"%s\" appears twice in primary key constraint",
1188 (errcode(ERRCODE_DUPLICATE_COLUMN),
1189 errmsg("column \"%s\" appears twice in unique constraint",
1194 /* OK, add it to the index definition */
1195 iparam = makeNode(IndexElem);
1196 iparam->name = pstrdup(key);
1197 iparam->expr = NULL;
1198 iparam->opclass = NIL;
1199 iparam->ordering = SORTBY_DEFAULT;
1200 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1201 index->indexParams = lappend(index->indexParams, iparam);
1208 * transformFKConstraints
1209 * handle FOREIGN KEY constraints
1212 transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
1213 bool skipValidation, bool isAddConstraint)
1217 if (cxt->fkconstraints == NIL)
1221 * If CREATE TABLE or adding a column with NULL default, we can safely
1222 * skip validation of the constraint.
1226 foreach(fkclist, cxt->fkconstraints)
1228 FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1230 fkconstraint->skip_validation = true;
1235 * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
1236 * CONSTRAINT command to execute after the basic command is complete. (If
1237 * called from ADD CONSTRAINT, that routine will add the FK constraints to
1238 * its own subcommand list.)
1240 * Note: the ADD CONSTRAINT command must also execute after any index
1241 * creation commands. Thus, this should run after
1242 * transformIndexConstraints, so that the CREATE INDEX commands are
1243 * already in cxt->alist.
1245 if (!isAddConstraint)
1247 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1249 alterstmt->relation = cxt->relation;
1250 alterstmt->cmds = NIL;
1251 alterstmt->relkind = OBJECT_TABLE;
1253 foreach(fkclist, cxt->fkconstraints)
1255 FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1256 AlterTableCmd *altercmd = makeNode(AlterTableCmd);
1258 altercmd->subtype = AT_ProcessedConstraint;
1259 altercmd->name = NULL;
1260 altercmd->def = (Node *) fkconstraint;
1261 alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
1264 cxt->alist = lappend(cxt->alist, alterstmt);
1269 * transformIndexStmt - parse analysis for CREATE INDEX
1271 * Note: this is a no-op for an index not using either index expressions or
1272 * a predicate expression. There are several code paths that create indexes
1273 * without bothering to call this, because they know they don't have any
1274 * such expressions to deal with.
1277 transformIndexStmt(IndexStmt *stmt, const char *queryString)
1285 * We must not scribble on the passed-in IndexStmt, so copy it. (This
1286 * is overkill, but easy.)
1288 stmt = (IndexStmt *) copyObject(stmt);
1291 * Open the parent table with appropriate locking. We must do this
1292 * because addRangeTableEntry() would acquire only AccessShareLock,
1293 * leaving DefineIndex() needing to do a lock upgrade with consequent
1294 * risk of deadlock. Make sure this stays in sync with the type of
1295 * lock DefineIndex() wants.
1297 rel = heap_openrv(stmt->relation,
1298 (stmt->concurrent ? ShareUpdateExclusiveLock : ShareLock));
1301 pstate = make_parsestate(NULL);
1302 pstate->p_sourcetext = queryString;
1305 * Put the parent table into the rtable so that the expressions can
1306 * refer to its fields without qualification.
1308 rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1310 /* no to join list, yes to namespaces */
1311 addRTEtoQuery(pstate, rte, false, true, true);
1313 /* take care of the where clause */
1314 if (stmt->whereClause)
1315 stmt->whereClause = transformWhereClause(pstate,
1319 /* take care of any index expressions */
1320 foreach(l, stmt->indexParams)
1322 IndexElem *ielem = (IndexElem *) lfirst(l);
1326 ielem->expr = transformExpr(pstate, ielem->expr);
1329 * We check only that the result type is legitimate; this is for
1330 * consistency with what transformWhereClause() checks for the
1331 * predicate. DefineIndex() will make more checks.
1333 if (expression_returns_set(ielem->expr))
1335 (errcode(ERRCODE_DATATYPE_MISMATCH),
1336 errmsg("index expression cannot return a set")));
1341 * Check that only the base rel is mentioned.
1343 if (list_length(pstate->p_rtable) != 1)
1345 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1346 errmsg("index expressions and predicates can refer only to the table being indexed")));
1348 free_parsestate(pstate);
1350 /* Close relation, but keep the lock */
1351 heap_close(rel, NoLock);
1358 * transformRuleStmt -
1359 * transform a CREATE RULE Statement. The action is a list of parse
1360 * trees which is transformed into a list of query trees, and we also
1361 * transform the WHERE clause if any.
1363 * actions and whereClause are output parameters that receive the
1364 * transformed results.
1366 * Note that we must not scribble on the passed-in RuleStmt, so we do
1367 * copyObject() on the actions and WHERE clause.
1370 transformRuleStmt(RuleStmt *stmt, const char *queryString,
1371 List **actions, Node **whereClause)
1375 RangeTblEntry *oldrte;
1376 RangeTblEntry *newrte;
1379 * To avoid deadlock, make sure the first thing we do is grab
1380 * AccessExclusiveLock on the target relation. This will be needed by
1381 * DefineQueryRewrite(), and we don't want to grab a lesser lock
1384 rel = heap_openrv(stmt->relation, AccessExclusiveLock);
1387 pstate = make_parsestate(NULL);
1388 pstate->p_sourcetext = queryString;
1391 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
1392 * Set up their RTEs in the main pstate for use in parsing the rule
1395 oldrte = addRangeTableEntryForRelation(pstate, rel,
1396 makeAlias("*OLD*", NIL),
1398 newrte = addRangeTableEntryForRelation(pstate, rel,
1399 makeAlias("*NEW*", NIL),
1401 /* Must override addRangeTableEntry's default access-check flags */
1402 oldrte->requiredPerms = 0;
1403 newrte->requiredPerms = 0;
1406 * They must be in the namespace too for lookup purposes, but only add the
1407 * one(s) that are relevant for the current kind of rule. In an UPDATE
1408 * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
1409 * there's no need to be so picky for INSERT & DELETE. We do not add them
1412 switch (stmt->event)
1415 addRTEtoQuery(pstate, oldrte, false, true, true);
1418 addRTEtoQuery(pstate, oldrte, false, true, true);
1419 addRTEtoQuery(pstate, newrte, false, true, true);
1422 addRTEtoQuery(pstate, newrte, false, true, true);
1425 addRTEtoQuery(pstate, oldrte, false, true, true);
1428 elog(ERROR, "unrecognized event type: %d",
1433 /* take care of the where clause */
1434 *whereClause = transformWhereClause(pstate,
1435 (Node *) copyObject(stmt->whereClause),
1438 if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
1440 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1441 errmsg("rule WHERE condition cannot contain references to other relations")));
1443 /* aggregates not allowed (but subselects are okay) */
1444 if (pstate->p_hasAggs)
1446 (errcode(ERRCODE_GROUPING_ERROR),
1447 errmsg("cannot use aggregate function in rule WHERE condition")));
1450 * 'instead nothing' rules with a qualification need a query rangetable so
1451 * the rewrite handler can add the negated rule qualification to the
1452 * original query. We create a query with the new command type CMD_NOTHING
1453 * here that is treated specially by the rewrite system.
1455 if (stmt->actions == NIL)
1457 Query *nothing_qry = makeNode(Query);
1459 nothing_qry->commandType = CMD_NOTHING;
1460 nothing_qry->rtable = pstate->p_rtable;
1461 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
1463 *actions = list_make1(nothing_qry);
1468 List *newactions = NIL;
1471 * transform each statement, like parse_sub_analyze()
1473 foreach(l, stmt->actions)
1475 Node *action = (Node *) lfirst(l);
1476 ParseState *sub_pstate = make_parsestate(NULL);
1483 * Since outer ParseState isn't parent of inner, have to pass
1484 * down the query text by hand.
1486 sub_pstate->p_sourcetext = queryString;
1489 * Set up OLD/NEW in the rtable for this statement. The entries
1490 * are added only to relnamespace, not varnamespace, because we
1491 * don't want them to be referred to by unqualified field names
1492 * nor "*" in the rule actions. We decide later whether to put
1493 * them in the joinlist.
1495 oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
1496 makeAlias("*OLD*", NIL),
1498 newrte = addRangeTableEntryForRelation(sub_pstate, rel,
1499 makeAlias("*NEW*", NIL),
1501 oldrte->requiredPerms = 0;
1502 newrte->requiredPerms = 0;
1503 addRTEtoQuery(sub_pstate, oldrte, false, true, false);
1504 addRTEtoQuery(sub_pstate, newrte, false, true, false);
1506 /* Transform the rule action statement */
1507 top_subqry = transformStmt(sub_pstate,
1508 (Node *) copyObject(action));
1511 * We cannot support utility-statement actions (eg NOTIFY) with
1512 * nonempty rule WHERE conditions, because there's no way to make
1513 * the utility action execute conditionally.
1515 if (top_subqry->commandType == CMD_UTILITY &&
1516 *whereClause != NULL)
1518 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1519 errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
1522 * If the action is INSERT...SELECT, OLD/NEW have been pushed down
1523 * into the SELECT, and that's what we need to look at. (Ugly
1524 * kluge ... try to fix this when we redesign querytrees.)
1526 sub_qry = getInsertSelectQuery(top_subqry, NULL);
1529 * If the sub_qry is a setop, we cannot attach any qualifications
1530 * to it, because the planner won't notice them. This could
1531 * perhaps be relaxed someday, but for now, we may as well reject
1532 * such a rule immediately.
1534 if (sub_qry->setOperations != NULL && *whereClause != NULL)
1536 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1537 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1540 * Validate action's use of OLD/NEW, qual too
1543 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
1544 rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
1546 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
1547 rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
1549 switch (stmt->event)
1554 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1555 errmsg("ON SELECT rule cannot use OLD")));
1558 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1559 errmsg("ON SELECT rule cannot use NEW")));
1567 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1568 errmsg("ON INSERT rule cannot use OLD")));
1573 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1574 errmsg("ON DELETE rule cannot use NEW")));
1577 elog(ERROR, "unrecognized event type: %d",
1583 * For efficiency's sake, add OLD to the rule action's jointree
1584 * only if it was actually referenced in the statement or qual.
1586 * For INSERT, NEW is not really a relation (only a reference to
1587 * the to-be-inserted tuple) and should never be added to the
1590 * For UPDATE, we treat NEW as being another kind of reference to
1591 * OLD, because it represents references to *transformed* tuples
1592 * of the existing relation. It would be wrong to enter NEW
1593 * separately in the jointree, since that would cause a double
1594 * join of the updated relation. It's also wrong to fail to make
1595 * a jointree entry if only NEW and not OLD is mentioned.
1597 if (has_old || (has_new && stmt->event == CMD_UPDATE))
1600 * If sub_qry is a setop, manipulating its jointree will do no
1601 * good at all, because the jointree is dummy. (This should be
1602 * a can't-happen case because of prior tests.)
1604 if (sub_qry->setOperations != NULL)
1606 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1607 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1608 /* hack so we can use addRTEtoQuery() */
1609 sub_pstate->p_rtable = sub_qry->rtable;
1610 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
1611 addRTEtoQuery(sub_pstate, oldrte, true, false, false);
1612 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
1615 newactions = lappend(newactions, top_subqry);
1617 free_parsestate(sub_pstate);
1620 *actions = newactions;
1623 free_parsestate(pstate);
1625 /* Close relation, but keep the exclusive lock */
1626 heap_close(rel, NoLock);
1631 * transformAlterTableStmt -
1632 * parse analysis for ALTER TABLE
1634 * Returns a List of utility commands to be done in sequence. One of these
1635 * will be the transformed AlterTableStmt, but there may be additional actions
1636 * to be done before and after the actual AlterTable() call.
1639 transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString)
1643 CreateStmtContext cxt;
1648 List *newcmds = NIL;
1649 bool skipValidation = true;
1650 AlterTableCmd *newcmd;
1653 * We must not scribble on the passed-in AlterTableStmt, so copy it.
1654 * (This is overkill, but easy.)
1656 stmt = (AlterTableStmt *) copyObject(stmt);
1659 * Acquire exclusive lock on the target relation, which will be held
1660 * until end of transaction. This ensures any decisions we make here
1661 * based on the state of the relation will still be good at execution.
1662 * We must get exclusive lock now because execution will; taking a lower
1663 * grade lock now and trying to upgrade later risks deadlock.
1665 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
1668 pstate = make_parsestate(NULL);
1669 pstate->p_sourcetext = queryString;
1671 cxt.stmtType = "ALTER TABLE";
1672 cxt.relation = stmt->relation;
1674 cxt.inhRelations = NIL;
1676 cxt.hasoids = false; /* need not be right */
1678 cxt.ckconstraints = NIL;
1679 cxt.fkconstraints = NIL;
1680 cxt.ixconstraints = NIL;
1681 cxt.inh_indexes = NIL;
1687 * The only subtypes that currently require parse transformation handling
1688 * are ADD COLUMN and ADD CONSTRAINT. These largely re-use code from
1691 foreach(lcmd, stmt->cmds)
1693 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
1695 switch (cmd->subtype)
1699 ColumnDef *def = (ColumnDef *) cmd->def;
1701 Assert(IsA(cmd->def, ColumnDef));
1702 transformColumnDefinition(pstate, &cxt,
1703 (ColumnDef *) cmd->def);
1706 * If the column has a non-null default, we can't skip
1707 * validation of foreign keys.
1709 if (((ColumnDef *) cmd->def)->raw_default != NULL)
1710 skipValidation = false;
1712 newcmds = lappend(newcmds, cmd);
1715 * Convert an ADD COLUMN ... NOT NULL constraint to a
1718 if (def->is_not_null)
1720 /* Remove NOT NULL from AddColumn */
1721 def->is_not_null = false;
1723 /* Add as a separate AlterTableCmd */
1724 newcmd = makeNode(AlterTableCmd);
1725 newcmd->subtype = AT_SetNotNull;
1726 newcmd->name = pstrdup(def->colname);
1727 newcmds = lappend(newcmds, newcmd);
1731 * All constraints are processed in other ways. Remove the
1734 def->constraints = NIL;
1738 case AT_AddConstraint:
1741 * The original AddConstraint cmd node doesn't go to newcmds
1744 if (IsA(cmd->def, Constraint))
1745 transformTableConstraint(pstate, &cxt,
1746 (Constraint *) cmd->def);
1747 else if (IsA(cmd->def, FkConstraint))
1749 cxt.fkconstraints = lappend(cxt.fkconstraints, cmd->def);
1750 skipValidation = false;
1753 elog(ERROR, "unrecognized node type: %d",
1754 (int) nodeTag(cmd->def));
1757 case AT_ProcessedConstraint:
1760 * Already-transformed ADD CONSTRAINT, so just make it look
1761 * like the standard case.
1763 cmd->subtype = AT_AddConstraint;
1764 newcmds = lappend(newcmds, cmd);
1768 newcmds = lappend(newcmds, cmd);
1774 * transformIndexConstraints wants cxt.alist to contain only index
1775 * statements, so transfer anything we already have into save_alist.
1778 save_alist = cxt.alist;
1781 /* Postprocess index and FK constraints */
1782 transformIndexConstraints(pstate, &cxt);
1784 transformFKConstraints(pstate, &cxt, skipValidation, true);
1787 * Push any index-creation commands into the ALTER, so that they can be
1788 * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
1789 * the IndexStmt attached to an AT_AddIndex subcommand has already been
1790 * through transformIndexStmt.
1792 foreach(l, cxt.alist)
1794 Node *idxstmt = (Node *) lfirst(l);
1796 Assert(IsA(idxstmt, IndexStmt));
1797 newcmd = makeNode(AlterTableCmd);
1798 newcmd->subtype = AT_AddIndex;
1799 newcmd->def = (Node *) transformIndexStmt((IndexStmt *) idxstmt,
1801 newcmds = lappend(newcmds, newcmd);
1805 /* Append any CHECK or FK constraints to the commands list */
1806 foreach(l, cxt.ckconstraints)
1808 newcmd = makeNode(AlterTableCmd);
1809 newcmd->subtype = AT_AddConstraint;
1810 newcmd->def = (Node *) lfirst(l);
1811 newcmds = lappend(newcmds, newcmd);
1813 foreach(l, cxt.fkconstraints)
1815 newcmd = makeNode(AlterTableCmd);
1816 newcmd->subtype = AT_AddConstraint;
1817 newcmd->def = (Node *) lfirst(l);
1818 newcmds = lappend(newcmds, newcmd);
1821 /* Close rel but keep lock */
1822 relation_close(rel, NoLock);
1827 stmt->cmds = newcmds;
1829 result = lappend(cxt.blist, stmt);
1830 result = list_concat(result, cxt.alist);
1831 result = list_concat(result, save_alist);
1838 * Preprocess a list of column constraint clauses
1839 * to attach constraint attributes to their primary constraint nodes
1840 * and detect inconsistent/misplaced constraint attributes.
1842 * NOTE: currently, attributes are only supported for FOREIGN KEY primary
1843 * constraints, but someday they ought to be supported for other constraints.
1846 transformConstraintAttrs(List *constraintList)
1848 Node *lastprimarynode = NULL;
1849 bool saw_deferrability = false;
1850 bool saw_initially = false;
1853 foreach(clist, constraintList)
1855 Node *node = lfirst(clist);
1857 if (!IsA(node, Constraint))
1859 lastprimarynode = node;
1860 /* reset flags for new primary node */
1861 saw_deferrability = false;
1862 saw_initially = false;
1866 Constraint *con = (Constraint *) node;
1868 switch (con->contype)
1870 case CONSTR_ATTR_DEFERRABLE:
1871 if (lastprimarynode == NULL ||
1872 !IsA(lastprimarynode, FkConstraint))
1874 (errcode(ERRCODE_SYNTAX_ERROR),
1875 errmsg("misplaced DEFERRABLE clause")));
1876 if (saw_deferrability)
1878 (errcode(ERRCODE_SYNTAX_ERROR),
1879 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
1880 saw_deferrability = true;
1881 ((FkConstraint *) lastprimarynode)->deferrable = true;
1883 case CONSTR_ATTR_NOT_DEFERRABLE:
1884 if (lastprimarynode == NULL ||
1885 !IsA(lastprimarynode, FkConstraint))
1887 (errcode(ERRCODE_SYNTAX_ERROR),
1888 errmsg("misplaced NOT DEFERRABLE clause")));
1889 if (saw_deferrability)
1891 (errcode(ERRCODE_SYNTAX_ERROR),
1892 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
1893 saw_deferrability = true;
1894 ((FkConstraint *) lastprimarynode)->deferrable = false;
1895 if (saw_initially &&
1896 ((FkConstraint *) lastprimarynode)->initdeferred)
1898 (errcode(ERRCODE_SYNTAX_ERROR),
1899 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
1901 case CONSTR_ATTR_DEFERRED:
1902 if (lastprimarynode == NULL ||
1903 !IsA(lastprimarynode, FkConstraint))
1905 (errcode(ERRCODE_SYNTAX_ERROR),
1906 errmsg("misplaced INITIALLY DEFERRED clause")));
1909 (errcode(ERRCODE_SYNTAX_ERROR),
1910 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
1911 saw_initially = true;
1912 ((FkConstraint *) lastprimarynode)->initdeferred = true;
1915 * If only INITIALLY DEFERRED appears, assume DEFERRABLE
1917 if (!saw_deferrability)
1918 ((FkConstraint *) lastprimarynode)->deferrable = true;
1919 else if (!((FkConstraint *) lastprimarynode)->deferrable)
1921 (errcode(ERRCODE_SYNTAX_ERROR),
1922 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
1924 case CONSTR_ATTR_IMMEDIATE:
1925 if (lastprimarynode == NULL ||
1926 !IsA(lastprimarynode, FkConstraint))
1928 (errcode(ERRCODE_SYNTAX_ERROR),
1929 errmsg("misplaced INITIALLY IMMEDIATE clause")));
1932 (errcode(ERRCODE_SYNTAX_ERROR),
1933 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
1934 saw_initially = true;
1935 ((FkConstraint *) lastprimarynode)->initdeferred = false;
1938 /* Otherwise it's not an attribute */
1939 lastprimarynode = node;
1940 /* reset flags for new primary node */
1941 saw_deferrability = false;
1942 saw_initially = false;
1950 * Special handling of type definition for a column
1953 transformColumnType(ParseState *pstate, ColumnDef *column)
1956 * All we really need to do here is verify that the type is valid.
1958 Type ctype = typenameType(pstate, column->typename, NULL);
1960 ReleaseSysCache(ctype);
1965 * transformCreateSchemaStmt -
1966 * analyzes the CREATE SCHEMA statement
1968 * Split the schema element list into individual commands and place
1969 * them in the result list in an order such that there are no forward
1970 * references (e.g. GRANT to a table created later in the list). Note
1971 * that the logic we use for determining forward references is
1972 * presently quite incomplete.
1974 * SQL92 also allows constraints to make forward references, so thumb through
1975 * the table columns and move forward references to a posterior alter-table
1978 * The result is a list of parse nodes that still need to be analyzed ---
1979 * but we can't analyze the later commands until we've executed the earlier
1980 * ones, because of possible inter-object references.
1982 * Note: this breaks the rules a little bit by modifying schema-name fields
1983 * within passed-in structs. However, the transformation would be the same
1984 * if done over, so it should be all right to scribble on the input to this
1988 transformCreateSchemaStmt(CreateSchemaStmt *stmt)
1990 CreateSchemaStmtContext cxt;
1994 cxt.stmtType = "CREATE SCHEMA";
1995 cxt.schemaname = stmt->schemaname;
1996 cxt.authid = stmt->authid;
1997 cxt.sequences = NIL;
2005 * Run through each schema element in the schema element list. Separate
2006 * statements by type, and do preliminary analysis.
2008 foreach(elements, stmt->schemaElts)
2010 Node *element = lfirst(elements);
2012 switch (nodeTag(element))
2014 case T_CreateSeqStmt:
2016 CreateSeqStmt *elp = (CreateSeqStmt *) element;
2018 setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
2019 cxt.sequences = lappend(cxt.sequences, element);
2025 CreateStmt *elp = (CreateStmt *) element;
2027 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2030 * XXX todo: deal with constraints
2032 cxt.tables = lappend(cxt.tables, element);
2038 ViewStmt *elp = (ViewStmt *) element;
2040 setSchemaName(cxt.schemaname, &elp->view->schemaname);
2043 * XXX todo: deal with references between views
2045 cxt.views = lappend(cxt.views, element);
2051 IndexStmt *elp = (IndexStmt *) element;
2053 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2054 cxt.indexes = lappend(cxt.indexes, element);
2058 case T_CreateTrigStmt:
2060 CreateTrigStmt *elp = (CreateTrigStmt *) element;
2062 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2063 cxt.triggers = lappend(cxt.triggers, element);
2068 cxt.grants = lappend(cxt.grants, element);
2072 elog(ERROR, "unrecognized node type: %d",
2073 (int) nodeTag(element));
2078 result = list_concat(result, cxt.sequences);
2079 result = list_concat(result, cxt.tables);
2080 result = list_concat(result, cxt.views);
2081 result = list_concat(result, cxt.indexes);
2082 result = list_concat(result, cxt.triggers);
2083 result = list_concat(result, cxt.grants);
2090 * Set or check schema name in an element of a CREATE SCHEMA command
2093 setSchemaName(char *context_schema, char **stmt_schema_name)
2095 if (*stmt_schema_name == NULL)
2096 *stmt_schema_name = context_schema;
2097 else if (strcmp(context_schema, *stmt_schema_name) != 0)
2099 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
2100 errmsg("CREATE specifies a schema (%s) "
2101 "different from the one being created (%s)",
2102 *stmt_schema_name, context_schema)));