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.6 2007/11/15 21:14:37 momjian 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 is
142 * 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 and
150 * 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 definition.
585 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
588 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
589 char *attributeName = NameStr(attribute->attname);
593 * Ignore dropped columns in the parent.
595 if (attribute->attisdropped)
599 * Create a new column, which is marked as NOT inherited.
601 * For constraints, ONLY the NOT NULL constraint is inherited by the
602 * new column definition per SQL99.
604 def = makeNode(ColumnDef);
605 def->colname = pstrdup(attributeName);
606 def->typename = makeTypeNameFromOid(attribute->atttypid,
607 attribute->atttypmod);
609 def->is_local = true;
610 def->is_not_null = attribute->attnotnull;
611 def->raw_default = NULL;
612 def->cooked_default = NULL;
613 def->constraints = NIL;
618 cxt->columns = lappend(cxt->columns, def);
621 * Copy default, if present and the default has been requested
623 if (attribute->atthasdef && including_defaults)
625 char *this_default = NULL;
626 AttrDefault *attrdef;
629 /* Find default in constraint structure */
630 Assert(constr != NULL);
631 attrdef = constr->defval;
632 for (i = 0; i < constr->num_defval; i++)
634 if (attrdef[i].adnum == parent_attno)
636 this_default = attrdef[i].adbin;
640 Assert(this_default != NULL);
643 * If default expr could contain any vars, we'd need to fix 'em,
644 * but it can't; so default is ready to apply to child.
647 def->cooked_default = pstrdup(this_default);
652 * Copy CHECK constraints if requested, being careful to adjust attribute
655 if (including_constraints && tupleDesc->constr)
657 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
660 for (ccnum = 0; ccnum < tupleDesc->constr->num_check; ccnum++)
662 char *ccname = tupleDesc->constr->check[ccnum].ccname;
663 char *ccbin = tupleDesc->constr->check[ccnum].ccbin;
664 Node *ccbin_node = stringToNode(ccbin);
665 Constraint *n = makeNode(Constraint);
667 change_varattnos_of_a_node(ccbin_node, attmap);
669 n->contype = CONSTR_CHECK;
670 n->name = pstrdup(ccname);
672 n->cooked_expr = nodeToString(ccbin_node);
673 n->indexspace = NULL;
674 cxt->ckconstraints = lappend(cxt->ckconstraints, (Node *) n);
678 if (including_indexes && relation->rd_rel->relhasindex)
681 List *parent_indexes;
684 attmap = varattnos_map_schema(tupleDesc, cxt->columns);
685 parent_indexes = RelationGetIndexList(relation);
687 foreach(l, parent_indexes)
689 Oid parent_index_oid = lfirst_oid(l);
690 Relation parent_index;
691 IndexStmt *index_stmt;
693 parent_index = index_open(parent_index_oid, AccessShareLock);
695 /* Build CREATE INDEX statement to recreate the parent_index */
696 index_stmt = generateClonedIndexStmt(cxt, parent_index,
699 /* Add the new IndexStmt to the create context */
700 cxt->inh_indexes = lappend(cxt->inh_indexes, index_stmt);
702 /* Keep our lock on the index till xact commit */
703 index_close(parent_index, NoLock);
708 * Close the parent rel, but keep our AccessShareLock on it until xact
709 * commit. That will prevent someone else from deleting or ALTERing the
710 * parent before the child is committed.
712 heap_close(relation, NoLock);
716 * Generate an IndexStmt entry using information from an already
717 * existing index "source_idx".
719 * Note: Much of this functionality is cribbed from pg_get_indexdef.
722 generateClonedIndexStmt(CreateStmtContext *cxt, Relation source_idx,
728 Form_pg_index idxrec;
729 Form_pg_class idxrelrec;
731 List *indexprs = NIL;
732 ListCell *indexpr_item;
738 Datum indoptionDatum;
741 int2vector *indoption;
745 source_relid = RelationGetRelid(source_idx);
747 /* Fetch pg_index tuple for source index */
748 ht_idx = SearchSysCache(INDEXRELID,
749 ObjectIdGetDatum(source_relid),
751 if (!HeapTupleIsValid(ht_idx))
752 elog(ERROR, "cache lookup failed for index %u", source_relid);
753 idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
755 Assert(source_relid == idxrec->indexrelid);
756 indrelid = idxrec->indrelid;
758 index = makeNode(IndexStmt);
759 index->unique = idxrec->indisunique;
760 index->concurrent = false;
761 index->primary = idxrec->indisprimary;
762 index->relation = cxt->relation;
763 index->isconstraint = false;
766 * We don't try to preserve the name of the source index; instead, just
767 * let DefineIndex() choose a reasonable name.
769 index->idxname = NULL;
771 /* Must get indclass and indoption the hard way */
772 indclassDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
773 Anum_pg_index_indclass, &isnull);
775 indclass = (oidvector *) DatumGetPointer(indclassDatum);
776 indoptionDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
777 Anum_pg_index_indoption, &isnull);
779 indoption = (int2vector *) DatumGetPointer(indoptionDatum);
781 /* Fetch pg_class tuple of source index */
782 ht_idxrel = SearchSysCache(RELOID,
783 ObjectIdGetDatum(source_relid),
785 if (!HeapTupleIsValid(ht_idxrel))
786 elog(ERROR, "cache lookup failed for relation %u", source_relid);
789 * Store the reloptions for later use by this new index
791 reloptions = SysCacheGetAttr(RELOID, ht_idxrel,
792 Anum_pg_class_reloptions, &isnull);
794 index->src_options = flatten_reloptions(source_relid);
796 idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
798 /* Fetch pg_am tuple for the index's access method */
799 ht_am = SearchSysCache(AMOID,
800 ObjectIdGetDatum(idxrelrec->relam),
802 if (!HeapTupleIsValid(ht_am))
803 elog(ERROR, "cache lookup failed for access method %u",
805 amrec = (Form_pg_am) GETSTRUCT(ht_am);
806 index->accessMethod = pstrdup(NameStr(amrec->amname));
808 /* Get the index expressions, if any */
809 if (!heap_attisnull(ht_idx, Anum_pg_index_indexprs))
815 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
816 Anum_pg_index_indexprs, &isnull);
817 exprsString = DatumGetCString(DirectFunctionCall1(textout,
820 indexprs = (List *) stringToNode(exprsString);
823 indexpr_item = list_head(indexprs);
825 for (keyno = 0; keyno < idxrec->indnatts; keyno++)
828 AttrNumber attnum = idxrec->indkey.values[keyno];
829 int16 opt = indoption->values[keyno];
831 iparam = makeNode(IndexElem);
833 if (AttributeNumberIsValid(attnum))
835 /* Simple index column */
838 attname = get_relid_attribute_name(indrelid, attnum);
839 keycoltype = get_atttype(indrelid, attnum);
841 iparam->name = attname;
846 /* Expressional index */
849 if (indexpr_item == NULL)
850 elog(ERROR, "too few entries in indexprs list");
851 indexkey = (Node *) lfirst(indexpr_item);
852 change_varattnos_of_a_node(indexkey, attmap);
854 iparam->expr = indexkey;
856 indexpr_item = lnext(indexpr_item);
857 keycoltype = exprType(indexkey);
860 /* Add the operator class name, if non-default */
861 iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
863 iparam->ordering = SORTBY_DEFAULT;
864 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
866 /* Adjust options if necessary */
867 if (amrec->amcanorder)
869 /* If it supports sort ordering, report DESC and NULLS opts */
870 if (opt & INDOPTION_DESC)
871 iparam->ordering = SORTBY_DESC;
872 if (opt & INDOPTION_NULLS_FIRST)
873 iparam->nulls_ordering = SORTBY_NULLS_FIRST;
876 index->indexParams = lappend(index->indexParams, iparam);
879 /* Use the same tablespace as the source index */
880 index->tableSpace = get_tablespace_name(source_idx->rd_node.spcNode);
882 /* If it's a partial index, decompile and append the predicate */
883 if (!heap_attisnull(ht_idx, Anum_pg_index_indpred))
889 /* Convert text string to node tree */
890 pred_datum = SysCacheGetAttr(INDEXRELID, ht_idx,
891 Anum_pg_index_indpred, &isnull);
893 pred_str = DatumGetCString(DirectFunctionCall1(textout,
895 index->whereClause = (Node *) stringToNode(pred_str);
896 change_varattnos_of_a_node(index->whereClause, attmap);
900 ReleaseSysCache(ht_idx);
901 ReleaseSysCache(ht_idxrel);
902 ReleaseSysCache(ht_am);
908 * get_opclass - fetch name of an index operator class
910 * If the opclass is the default for the given actual_datatype, then
911 * the return value is NIL.
914 get_opclass(Oid opclass, Oid actual_datatype)
917 Form_pg_opclass opc_rec;
920 ht_opc = SearchSysCache(CLAOID,
921 ObjectIdGetDatum(opclass),
923 if (!HeapTupleIsValid(ht_opc))
924 elog(ERROR, "cache lookup failed for opclass %u", opclass);
925 opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
927 if (!OidIsValid(actual_datatype) ||
928 GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
930 char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
931 char *opc_name = NameStr(opc_rec->opcname);
933 result = list_make2(makeString(nsp_name), makeString(opc_name));
936 ReleaseSysCache(ht_opc);
942 * transformIndexConstraints
943 * Handle UNIQUE and PRIMARY KEY constraints, which create
944 * indexes. We also merge index definitions arising from
945 * LIKE ... INCLUDING INDEXES.
948 transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
951 List *indexlist = NIL;
955 * Run through the constraints that need to generate an index. For PRIMARY
956 * KEY, mark each column as NOT NULL and create an index. For UNIQUE,
957 * create an index as for PRIMARY KEY, but do not insist on NOT NULL.
959 foreach(lc, cxt->ixconstraints)
961 Constraint *constraint = (Constraint *) lfirst(lc);
963 index = transformIndexConstraint(constraint, cxt);
964 indexlist = lappend(indexlist, index);
968 * Scan the index list and remove any redundant index specifications. This
969 * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
970 * strict reading of SQL92 would suggest raising an error instead, but
971 * that strikes me as too anal-retentive. - tgl 2001-02-14
973 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
974 * pre-existing indexes, too.
976 Assert(cxt->alist == NIL);
977 if (cxt->pkey != NULL)
979 /* Make sure we keep the PKEY index in preference to others... */
980 cxt->alist = list_make1(cxt->pkey);
983 foreach(lc, indexlist)
990 /* if it's pkey, it's already in cxt->alist */
991 if (index == cxt->pkey)
994 foreach(k, cxt->alist)
996 IndexStmt *priorindex = lfirst(k);
998 if (equal(index->indexParams, priorindex->indexParams))
1001 * If the prior index is as yet unnamed, and this one is
1002 * named, then transfer the name to the prior index. This
1003 * ensures that if we have named and unnamed constraints,
1004 * we'll use (at least one of) the names for the index.
1006 if (priorindex->idxname == NULL)
1007 priorindex->idxname = index->idxname;
1014 cxt->alist = lappend(cxt->alist, index);
1017 /* Copy indexes defined by LIKE ... INCLUDING INDEXES */
1018 foreach(lc, cxt->inh_indexes)
1020 index = (IndexStmt *) lfirst(lc);
1026 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1027 errmsg("multiple primary keys for table \"%s\" are not allowed",
1028 cxt->relation->relname)));
1033 cxt->alist = lappend(cxt->alist, index);
1038 transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
1044 Assert(constraint->contype == CONSTR_PRIMARY ||
1045 constraint->contype == CONSTR_UNIQUE);
1047 index = makeNode(IndexStmt);
1048 index->unique = true;
1049 index->primary = (constraint->contype == CONSTR_PRIMARY);
1053 if (cxt->pkey != NULL)
1055 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1056 errmsg("multiple primary keys for table \"%s\" are not allowed",
1057 cxt->relation->relname)));
1061 * In ALTER TABLE case, a primary index might already exist, but
1062 * DefineIndex will check for it.
1065 index->isconstraint = true;
1067 if (constraint->name != NULL)
1068 index->idxname = pstrdup(constraint->name);
1070 index->idxname = NULL; /* DefineIndex will choose name */
1072 index->relation = cxt->relation;
1073 index->accessMethod = DEFAULT_INDEX_TYPE;
1074 index->options = constraint->options;
1075 index->tableSpace = constraint->indexspace;
1076 index->indexParams = NIL;
1077 index->whereClause = NULL;
1078 index->concurrent = false;
1081 * Make sure referenced keys exist. If we are making a PRIMARY KEY index,
1082 * also make sure they are NOT NULL, if possible. (Although we could leave
1083 * it to DefineIndex to mark the columns NOT NULL, it's more efficient to
1084 * get it right the first time.)
1086 foreach(keys, constraint->keys)
1088 char *key = strVal(lfirst(keys));
1090 ColumnDef *column = NULL;
1093 foreach(columns, cxt->columns)
1095 column = (ColumnDef *) lfirst(columns);
1096 Assert(IsA(column, ColumnDef));
1097 if (strcmp(column->colname, key) == 0)
1105 /* found column in the new table; force it to be NOT NULL */
1106 if (constraint->contype == CONSTR_PRIMARY)
1107 column->is_not_null = TRUE;
1109 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1112 * column will be a system column in the new table, so accept it.
1113 * System columns can't ever be null, so no need to worry about
1114 * PRIMARY/NOT NULL constraint.
1118 else if (cxt->inhRelations)
1120 /* try inherited tables */
1123 foreach(inher, cxt->inhRelations)
1125 RangeVar *inh = (RangeVar *) lfirst(inher);
1129 Assert(IsA(inh, RangeVar));
1130 rel = heap_openrv(inh, AccessShareLock);
1131 if (rel->rd_rel->relkind != RELKIND_RELATION)
1133 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1134 errmsg("inherited relation \"%s\" is not a table",
1136 for (count = 0; count < rel->rd_att->natts; count++)
1138 Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1139 char *inhname = NameStr(inhattr->attname);
1141 if (inhattr->attisdropped)
1143 if (strcmp(key, inhname) == 0)
1148 * We currently have no easy way to force an inherited
1149 * column to be NOT NULL at creation, if its parent
1150 * wasn't so already. We leave it to DefineIndex to
1151 * fix things up in this case.
1156 heap_close(rel, NoLock);
1163 * In the ALTER TABLE case, don't complain about index keys not
1164 * created in the command; they may well exist already. DefineIndex
1165 * will complain about them if not, and will also take care of marking
1168 if (!found && !cxt->isalter)
1170 (errcode(ERRCODE_UNDEFINED_COLUMN),
1171 errmsg("column \"%s\" named in key does not exist",
1174 /* Check for PRIMARY KEY(foo, foo) */
1175 foreach(columns, index->indexParams)
1177 iparam = (IndexElem *) lfirst(columns);
1178 if (iparam->name && strcmp(key, iparam->name) == 0)
1182 (errcode(ERRCODE_DUPLICATE_COLUMN),
1183 errmsg("column \"%s\" appears twice in primary key constraint",
1187 (errcode(ERRCODE_DUPLICATE_COLUMN),
1188 errmsg("column \"%s\" appears twice in unique constraint",
1193 /* OK, add it to the index definition */
1194 iparam = makeNode(IndexElem);
1195 iparam->name = pstrdup(key);
1196 iparam->expr = NULL;
1197 iparam->opclass = NIL;
1198 iparam->ordering = SORTBY_DEFAULT;
1199 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1200 index->indexParams = lappend(index->indexParams, iparam);
1207 * transformFKConstraints
1208 * handle FOREIGN KEY constraints
1211 transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
1212 bool skipValidation, bool isAddConstraint)
1216 if (cxt->fkconstraints == NIL)
1220 * If CREATE TABLE or adding a column with NULL default, we can safely
1221 * skip validation of the constraint.
1225 foreach(fkclist, cxt->fkconstraints)
1227 FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1229 fkconstraint->skip_validation = true;
1234 * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
1235 * CONSTRAINT command to execute after the basic command is complete. (If
1236 * called from ADD CONSTRAINT, that routine will add the FK constraints to
1237 * its own subcommand list.)
1239 * Note: the ADD CONSTRAINT command must also execute after any index
1240 * creation commands. Thus, this should run after
1241 * transformIndexConstraints, so that the CREATE INDEX commands are
1242 * already in cxt->alist.
1244 if (!isAddConstraint)
1246 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1248 alterstmt->relation = cxt->relation;
1249 alterstmt->cmds = NIL;
1250 alterstmt->relkind = OBJECT_TABLE;
1252 foreach(fkclist, cxt->fkconstraints)
1254 FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1255 AlterTableCmd *altercmd = makeNode(AlterTableCmd);
1257 altercmd->subtype = AT_ProcessedConstraint;
1258 altercmd->name = NULL;
1259 altercmd->def = (Node *) fkconstraint;
1260 alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
1263 cxt->alist = lappend(cxt->alist, alterstmt);
1268 * transformIndexStmt - parse analysis for CREATE INDEX
1270 * Note: this is a no-op for an index not using either index expressions or
1271 * a predicate expression. There are several code paths that create indexes
1272 * without bothering to call this, because they know they don't have any
1273 * such expressions to deal with.
1276 transformIndexStmt(IndexStmt *stmt, const char *queryString)
1284 * We must not scribble on the passed-in IndexStmt, so copy it. (This is
1285 * overkill, but easy.)
1287 stmt = (IndexStmt *) copyObject(stmt);
1290 * Open the parent table with appropriate locking. We must do this
1291 * because addRangeTableEntry() would acquire only AccessShareLock,
1292 * leaving DefineIndex() needing to do a lock upgrade with consequent risk
1293 * of deadlock. Make sure this stays in sync with the type of lock
1294 * DefineIndex() wants.
1296 rel = heap_openrv(stmt->relation,
1297 (stmt->concurrent ? ShareUpdateExclusiveLock : ShareLock));
1300 pstate = make_parsestate(NULL);
1301 pstate->p_sourcetext = queryString;
1304 * Put the parent table into the rtable so that the expressions can refer
1305 * to its fields without qualification.
1307 rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1309 /* no to join list, yes to namespaces */
1310 addRTEtoQuery(pstate, rte, false, true, true);
1312 /* take care of the where clause */
1313 if (stmt->whereClause)
1314 stmt->whereClause = transformWhereClause(pstate,
1318 /* take care of any index expressions */
1319 foreach(l, stmt->indexParams)
1321 IndexElem *ielem = (IndexElem *) lfirst(l);
1325 ielem->expr = transformExpr(pstate, ielem->expr);
1328 * We check only that the result type is legitimate; this is for
1329 * consistency with what transformWhereClause() checks for the
1330 * predicate. DefineIndex() will make more checks.
1332 if (expression_returns_set(ielem->expr))
1334 (errcode(ERRCODE_DATATYPE_MISMATCH),
1335 errmsg("index expression cannot return a set")));
1340 * Check that only the base rel is mentioned.
1342 if (list_length(pstate->p_rtable) != 1)
1344 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1345 errmsg("index expressions and predicates can refer only to the table being indexed")));
1347 free_parsestate(pstate);
1349 /* Close relation, but keep the lock */
1350 heap_close(rel, NoLock);
1357 * transformRuleStmt -
1358 * transform a CREATE RULE Statement. The action is a list of parse
1359 * trees which is transformed into a list of query trees, and we also
1360 * transform the WHERE clause if any.
1362 * actions and whereClause are output parameters that receive the
1363 * transformed results.
1365 * Note that we must not scribble on the passed-in RuleStmt, so we do
1366 * copyObject() on the actions and WHERE clause.
1369 transformRuleStmt(RuleStmt *stmt, const char *queryString,
1370 List **actions, Node **whereClause)
1374 RangeTblEntry *oldrte;
1375 RangeTblEntry *newrte;
1378 * To avoid deadlock, make sure the first thing we do is grab
1379 * AccessExclusiveLock on the target relation. This will be needed by
1380 * DefineQueryRewrite(), and we don't want to grab a lesser lock
1383 rel = heap_openrv(stmt->relation, AccessExclusiveLock);
1386 pstate = make_parsestate(NULL);
1387 pstate->p_sourcetext = queryString;
1390 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
1391 * Set up their RTEs in the main pstate for use in parsing the rule
1394 oldrte = addRangeTableEntryForRelation(pstate, rel,
1395 makeAlias("*OLD*", NIL),
1397 newrte = addRangeTableEntryForRelation(pstate, rel,
1398 makeAlias("*NEW*", NIL),
1400 /* Must override addRangeTableEntry's default access-check flags */
1401 oldrte->requiredPerms = 0;
1402 newrte->requiredPerms = 0;
1405 * They must be in the namespace too for lookup purposes, but only add the
1406 * one(s) that are relevant for the current kind of rule. In an UPDATE
1407 * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
1408 * there's no need to be so picky for INSERT & DELETE. We do not add them
1411 switch (stmt->event)
1414 addRTEtoQuery(pstate, oldrte, false, true, true);
1417 addRTEtoQuery(pstate, oldrte, false, true, true);
1418 addRTEtoQuery(pstate, newrte, false, true, true);
1421 addRTEtoQuery(pstate, newrte, false, true, true);
1424 addRTEtoQuery(pstate, oldrte, false, true, true);
1427 elog(ERROR, "unrecognized event type: %d",
1432 /* take care of the where clause */
1433 *whereClause = transformWhereClause(pstate,
1434 (Node *) copyObject(stmt->whereClause),
1437 if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
1439 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1440 errmsg("rule WHERE condition cannot contain references to other relations")));
1442 /* aggregates not allowed (but subselects are okay) */
1443 if (pstate->p_hasAggs)
1445 (errcode(ERRCODE_GROUPING_ERROR),
1446 errmsg("cannot use aggregate function in rule WHERE condition")));
1449 * 'instead nothing' rules with a qualification need a query rangetable so
1450 * the rewrite handler can add the negated rule qualification to the
1451 * original query. We create a query with the new command type CMD_NOTHING
1452 * here that is treated specially by the rewrite system.
1454 if (stmt->actions == NIL)
1456 Query *nothing_qry = makeNode(Query);
1458 nothing_qry->commandType = CMD_NOTHING;
1459 nothing_qry->rtable = pstate->p_rtable;
1460 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
1462 *actions = list_make1(nothing_qry);
1467 List *newactions = NIL;
1470 * transform each statement, like parse_sub_analyze()
1472 foreach(l, stmt->actions)
1474 Node *action = (Node *) lfirst(l);
1475 ParseState *sub_pstate = make_parsestate(NULL);
1482 * Since outer ParseState isn't parent of inner, have to pass down
1483 * the query text by hand.
1485 sub_pstate->p_sourcetext = queryString;
1488 * Set up OLD/NEW in the rtable for this statement. The entries
1489 * are added only to relnamespace, not varnamespace, because we
1490 * don't want them to be referred to by unqualified field names
1491 * nor "*" in the rule actions. We decide later whether to put
1492 * them in the joinlist.
1494 oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
1495 makeAlias("*OLD*", NIL),
1497 newrte = addRangeTableEntryForRelation(sub_pstate, rel,
1498 makeAlias("*NEW*", NIL),
1500 oldrte->requiredPerms = 0;
1501 newrte->requiredPerms = 0;
1502 addRTEtoQuery(sub_pstate, oldrte, false, true, false);
1503 addRTEtoQuery(sub_pstate, newrte, false, true, false);
1505 /* Transform the rule action statement */
1506 top_subqry = transformStmt(sub_pstate,
1507 (Node *) copyObject(action));
1510 * We cannot support utility-statement actions (eg NOTIFY) with
1511 * nonempty rule WHERE conditions, because there's no way to make
1512 * the utility action execute conditionally.
1514 if (top_subqry->commandType == CMD_UTILITY &&
1515 *whereClause != NULL)
1517 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1518 errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
1521 * If the action is INSERT...SELECT, OLD/NEW have been pushed down
1522 * into the SELECT, and that's what we need to look at. (Ugly
1523 * kluge ... try to fix this when we redesign querytrees.)
1525 sub_qry = getInsertSelectQuery(top_subqry, NULL);
1528 * If the sub_qry is a setop, we cannot attach any qualifications
1529 * to it, because the planner won't notice them. This could
1530 * perhaps be relaxed someday, but for now, we may as well reject
1531 * such a rule immediately.
1533 if (sub_qry->setOperations != NULL && *whereClause != NULL)
1535 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1536 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1539 * Validate action's use of OLD/NEW, qual too
1542 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
1543 rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
1545 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
1546 rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
1548 switch (stmt->event)
1553 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1554 errmsg("ON SELECT rule cannot use OLD")));
1557 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1558 errmsg("ON SELECT rule cannot use NEW")));
1566 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1567 errmsg("ON INSERT rule cannot use OLD")));
1572 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1573 errmsg("ON DELETE rule cannot use NEW")));
1576 elog(ERROR, "unrecognized event type: %d",
1582 * For efficiency's sake, add OLD to the rule action's jointree
1583 * only if it was actually referenced in the statement or qual.
1585 * For INSERT, NEW is not really a relation (only a reference to
1586 * the to-be-inserted tuple) and should never be added to the
1589 * For UPDATE, we treat NEW as being another kind of reference to
1590 * OLD, because it represents references to *transformed* tuples
1591 * of the existing relation. It would be wrong to enter NEW
1592 * separately in the jointree, since that would cause a double
1593 * join of the updated relation. It's also wrong to fail to make
1594 * a jointree entry if only NEW and not OLD is mentioned.
1596 if (has_old || (has_new && stmt->event == CMD_UPDATE))
1599 * If sub_qry is a setop, manipulating its jointree will do no
1600 * good at all, because the jointree is dummy. (This should be
1601 * a can't-happen case because of prior tests.)
1603 if (sub_qry->setOperations != NULL)
1605 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1606 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1607 /* hack so we can use addRTEtoQuery() */
1608 sub_pstate->p_rtable = sub_qry->rtable;
1609 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
1610 addRTEtoQuery(sub_pstate, oldrte, true, false, false);
1611 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
1614 newactions = lappend(newactions, top_subqry);
1616 free_parsestate(sub_pstate);
1619 *actions = newactions;
1622 free_parsestate(pstate);
1624 /* Close relation, but keep the exclusive lock */
1625 heap_close(rel, NoLock);
1630 * transformAlterTableStmt -
1631 * parse analysis for ALTER TABLE
1633 * Returns a List of utility commands to be done in sequence. One of these
1634 * will be the transformed AlterTableStmt, but there may be additional actions
1635 * to be done before and after the actual AlterTable() call.
1638 transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString)
1642 CreateStmtContext cxt;
1647 List *newcmds = NIL;
1648 bool skipValidation = true;
1649 AlterTableCmd *newcmd;
1652 * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
1653 * is overkill, but easy.)
1655 stmt = (AlterTableStmt *) copyObject(stmt);
1658 * Acquire exclusive lock on the target relation, which will be held until
1659 * end of transaction. This ensures any decisions we make here based on
1660 * the state of the relation will still be good at execution. We must get
1661 * exclusive lock now because execution will; taking a lower grade lock
1662 * now and trying to upgrade later risks deadlock.
1664 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
1667 pstate = make_parsestate(NULL);
1668 pstate->p_sourcetext = queryString;
1670 cxt.stmtType = "ALTER TABLE";
1671 cxt.relation = stmt->relation;
1673 cxt.inhRelations = NIL;
1675 cxt.hasoids = false; /* need not be right */
1677 cxt.ckconstraints = NIL;
1678 cxt.fkconstraints = NIL;
1679 cxt.ixconstraints = NIL;
1680 cxt.inh_indexes = NIL;
1686 * The only subtypes that currently require parse transformation handling
1687 * are ADD COLUMN and ADD CONSTRAINT. These largely re-use code from
1690 foreach(lcmd, stmt->cmds)
1692 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
1694 switch (cmd->subtype)
1698 ColumnDef *def = (ColumnDef *) cmd->def;
1700 Assert(IsA(cmd->def, ColumnDef));
1701 transformColumnDefinition(pstate, &cxt,
1702 (ColumnDef *) cmd->def);
1705 * If the column has a non-null default, we can't skip
1706 * validation of foreign keys.
1708 if (((ColumnDef *) cmd->def)->raw_default != NULL)
1709 skipValidation = false;
1711 newcmds = lappend(newcmds, cmd);
1714 * Convert an ADD COLUMN ... NOT NULL constraint to a
1717 if (def->is_not_null)
1719 /* Remove NOT NULL from AddColumn */
1720 def->is_not_null = false;
1722 /* Add as a separate AlterTableCmd */
1723 newcmd = makeNode(AlterTableCmd);
1724 newcmd->subtype = AT_SetNotNull;
1725 newcmd->name = pstrdup(def->colname);
1726 newcmds = lappend(newcmds, newcmd);
1730 * All constraints are processed in other ways. Remove the
1733 def->constraints = NIL;
1737 case AT_AddConstraint:
1740 * The original AddConstraint cmd node doesn't go to newcmds
1743 if (IsA(cmd->def, Constraint))
1744 transformTableConstraint(pstate, &cxt,
1745 (Constraint *) cmd->def);
1746 else if (IsA(cmd->def, FkConstraint))
1748 cxt.fkconstraints = lappend(cxt.fkconstraints, cmd->def);
1749 skipValidation = false;
1752 elog(ERROR, "unrecognized node type: %d",
1753 (int) nodeTag(cmd->def));
1756 case AT_ProcessedConstraint:
1759 * Already-transformed ADD CONSTRAINT, so just make it look
1760 * like the standard case.
1762 cmd->subtype = AT_AddConstraint;
1763 newcmds = lappend(newcmds, cmd);
1767 newcmds = lappend(newcmds, cmd);
1773 * transformIndexConstraints wants cxt.alist to contain only index
1774 * statements, so transfer anything we already have into save_alist.
1777 save_alist = cxt.alist;
1780 /* Postprocess index and FK constraints */
1781 transformIndexConstraints(pstate, &cxt);
1783 transformFKConstraints(pstate, &cxt, skipValidation, true);
1786 * Push any index-creation commands into the ALTER, so that they can be
1787 * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
1788 * the IndexStmt attached to an AT_AddIndex subcommand has already been
1789 * through transformIndexStmt.
1791 foreach(l, cxt.alist)
1793 Node *idxstmt = (Node *) lfirst(l);
1795 Assert(IsA(idxstmt, IndexStmt));
1796 newcmd = makeNode(AlterTableCmd);
1797 newcmd->subtype = AT_AddIndex;
1798 newcmd->def = (Node *) transformIndexStmt((IndexStmt *) idxstmt,
1800 newcmds = lappend(newcmds, newcmd);
1804 /* Append any CHECK or FK constraints to the commands list */
1805 foreach(l, cxt.ckconstraints)
1807 newcmd = makeNode(AlterTableCmd);
1808 newcmd->subtype = AT_AddConstraint;
1809 newcmd->def = (Node *) lfirst(l);
1810 newcmds = lappend(newcmds, newcmd);
1812 foreach(l, cxt.fkconstraints)
1814 newcmd = makeNode(AlterTableCmd);
1815 newcmd->subtype = AT_AddConstraint;
1816 newcmd->def = (Node *) lfirst(l);
1817 newcmds = lappend(newcmds, newcmd);
1820 /* Close rel but keep lock */
1821 relation_close(rel, NoLock);
1826 stmt->cmds = newcmds;
1828 result = lappend(cxt.blist, stmt);
1829 result = list_concat(result, cxt.alist);
1830 result = list_concat(result, save_alist);
1837 * Preprocess a list of column constraint clauses
1838 * to attach constraint attributes to their primary constraint nodes
1839 * and detect inconsistent/misplaced constraint attributes.
1841 * NOTE: currently, attributes are only supported for FOREIGN KEY primary
1842 * constraints, but someday they ought to be supported for other constraints.
1845 transformConstraintAttrs(List *constraintList)
1847 Node *lastprimarynode = NULL;
1848 bool saw_deferrability = false;
1849 bool saw_initially = false;
1852 foreach(clist, constraintList)
1854 Node *node = lfirst(clist);
1856 if (!IsA(node, Constraint))
1858 lastprimarynode = node;
1859 /* reset flags for new primary node */
1860 saw_deferrability = false;
1861 saw_initially = false;
1865 Constraint *con = (Constraint *) node;
1867 switch (con->contype)
1869 case CONSTR_ATTR_DEFERRABLE:
1870 if (lastprimarynode == NULL ||
1871 !IsA(lastprimarynode, FkConstraint))
1873 (errcode(ERRCODE_SYNTAX_ERROR),
1874 errmsg("misplaced DEFERRABLE clause")));
1875 if (saw_deferrability)
1877 (errcode(ERRCODE_SYNTAX_ERROR),
1878 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
1879 saw_deferrability = true;
1880 ((FkConstraint *) lastprimarynode)->deferrable = true;
1882 case CONSTR_ATTR_NOT_DEFERRABLE:
1883 if (lastprimarynode == NULL ||
1884 !IsA(lastprimarynode, FkConstraint))
1886 (errcode(ERRCODE_SYNTAX_ERROR),
1887 errmsg("misplaced NOT DEFERRABLE clause")));
1888 if (saw_deferrability)
1890 (errcode(ERRCODE_SYNTAX_ERROR),
1891 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
1892 saw_deferrability = true;
1893 ((FkConstraint *) lastprimarynode)->deferrable = false;
1894 if (saw_initially &&
1895 ((FkConstraint *) lastprimarynode)->initdeferred)
1897 (errcode(ERRCODE_SYNTAX_ERROR),
1898 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
1900 case CONSTR_ATTR_DEFERRED:
1901 if (lastprimarynode == NULL ||
1902 !IsA(lastprimarynode, FkConstraint))
1904 (errcode(ERRCODE_SYNTAX_ERROR),
1905 errmsg("misplaced INITIALLY DEFERRED clause")));
1908 (errcode(ERRCODE_SYNTAX_ERROR),
1909 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
1910 saw_initially = true;
1911 ((FkConstraint *) lastprimarynode)->initdeferred = true;
1914 * If only INITIALLY DEFERRED appears, assume DEFERRABLE
1916 if (!saw_deferrability)
1917 ((FkConstraint *) lastprimarynode)->deferrable = true;
1918 else if (!((FkConstraint *) lastprimarynode)->deferrable)
1920 (errcode(ERRCODE_SYNTAX_ERROR),
1921 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
1923 case CONSTR_ATTR_IMMEDIATE:
1924 if (lastprimarynode == NULL ||
1925 !IsA(lastprimarynode, FkConstraint))
1927 (errcode(ERRCODE_SYNTAX_ERROR),
1928 errmsg("misplaced INITIALLY IMMEDIATE clause")));
1931 (errcode(ERRCODE_SYNTAX_ERROR),
1932 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
1933 saw_initially = true;
1934 ((FkConstraint *) lastprimarynode)->initdeferred = false;
1937 /* Otherwise it's not an attribute */
1938 lastprimarynode = node;
1939 /* reset flags for new primary node */
1940 saw_deferrability = false;
1941 saw_initially = false;
1949 * Special handling of type definition for a column
1952 transformColumnType(ParseState *pstate, ColumnDef *column)
1955 * All we really need to do here is verify that the type is valid.
1957 Type ctype = typenameType(pstate, column->typename, NULL);
1959 ReleaseSysCache(ctype);
1964 * transformCreateSchemaStmt -
1965 * analyzes the CREATE SCHEMA statement
1967 * Split the schema element list into individual commands and place
1968 * them in the result list in an order such that there are no forward
1969 * references (e.g. GRANT to a table created later in the list). Note
1970 * that the logic we use for determining forward references is
1971 * presently quite incomplete.
1973 * SQL92 also allows constraints to make forward references, so thumb through
1974 * the table columns and move forward references to a posterior alter-table
1977 * The result is a list of parse nodes that still need to be analyzed ---
1978 * but we can't analyze the later commands until we've executed the earlier
1979 * ones, because of possible inter-object references.
1981 * Note: this breaks the rules a little bit by modifying schema-name fields
1982 * within passed-in structs. However, the transformation would be the same
1983 * if done over, so it should be all right to scribble on the input to this
1987 transformCreateSchemaStmt(CreateSchemaStmt *stmt)
1989 CreateSchemaStmtContext cxt;
1993 cxt.stmtType = "CREATE SCHEMA";
1994 cxt.schemaname = stmt->schemaname;
1995 cxt.authid = stmt->authid;
1996 cxt.sequences = NIL;
2004 * Run through each schema element in the schema element list. Separate
2005 * statements by type, and do preliminary analysis.
2007 foreach(elements, stmt->schemaElts)
2009 Node *element = lfirst(elements);
2011 switch (nodeTag(element))
2013 case T_CreateSeqStmt:
2015 CreateSeqStmt *elp = (CreateSeqStmt *) element;
2017 setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
2018 cxt.sequences = lappend(cxt.sequences, element);
2024 CreateStmt *elp = (CreateStmt *) element;
2026 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2029 * XXX todo: deal with constraints
2031 cxt.tables = lappend(cxt.tables, element);
2037 ViewStmt *elp = (ViewStmt *) element;
2039 setSchemaName(cxt.schemaname, &elp->view->schemaname);
2042 * XXX todo: deal with references between views
2044 cxt.views = lappend(cxt.views, element);
2050 IndexStmt *elp = (IndexStmt *) element;
2052 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2053 cxt.indexes = lappend(cxt.indexes, element);
2057 case T_CreateTrigStmt:
2059 CreateTrigStmt *elp = (CreateTrigStmt *) element;
2061 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2062 cxt.triggers = lappend(cxt.triggers, element);
2067 cxt.grants = lappend(cxt.grants, element);
2071 elog(ERROR, "unrecognized node type: %d",
2072 (int) nodeTag(element));
2077 result = list_concat(result, cxt.sequences);
2078 result = list_concat(result, cxt.tables);
2079 result = list_concat(result, cxt.views);
2080 result = list_concat(result, cxt.indexes);
2081 result = list_concat(result, cxt.triggers);
2082 result = list_concat(result, cxt.grants);
2089 * Set or check schema name in an element of a CREATE SCHEMA command
2092 setSchemaName(char *context_schema, char **stmt_schema_name)
2094 if (*stmt_schema_name == NULL)
2095 *stmt_schema_name = context_schema;
2096 else if (strcmp(context_schema, *stmt_schema_name) != 0)
2098 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
2099 errmsg("CREATE specifies a schema (%s) "
2100 "different from the one being created (%s)",
2101 *stmt_schema_name, context_schema)));