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.7 2007/12/01 23:44:44 tgl Exp $
24 *-------------------------------------------------------------------------
29 #include "access/genam.h"
30 #include "access/heapam.h"
31 #include "access/reloptions.h"
32 #include "catalog/dependency.h"
33 #include "catalog/heap.h"
34 #include "catalog/index.h"
35 #include "catalog/namespace.h"
36 #include "catalog/pg_opclass.h"
37 #include "catalog/pg_type.h"
38 #include "commands/defrem.h"
39 #include "commands/tablecmds.h"
40 #include "commands/tablespace.h"
41 #include "miscadmin.h"
42 #include "nodes/makefuncs.h"
43 #include "optimizer/clauses.h"
44 #include "parser/analyze.h"
45 #include "parser/gramparse.h"
46 #include "parser/parse_clause.h"
47 #include "parser/parse_expr.h"
48 #include "parser/parse_relation.h"
49 #include "parser/parse_type.h"
50 #include "parser/parse_utilcmd.h"
51 #include "rewrite/rewriteManip.h"
52 #include "utils/acl.h"
53 #include "utils/builtins.h"
54 #include "utils/lsyscache.h"
55 #include "utils/relcache.h"
56 #include "utils/syscache.h"
59 /* State shared by transformCreateStmt and its subroutines */
62 const char *stmtType; /* "CREATE TABLE" or "ALTER TABLE" */
63 RangeVar *relation; /* relation to create */
64 Relation rel; /* opened/locked rel, if ALTER */
65 List *inhRelations; /* relations to inherit from */
66 bool isalter; /* true if altering existing table */
67 bool hasoids; /* does relation have an OID column? */
68 List *columns; /* ColumnDef items */
69 List *ckconstraints; /* CHECK constraints */
70 List *fkconstraints; /* FOREIGN KEY constraints */
71 List *ixconstraints; /* index-creating constraints */
72 List *inh_indexes; /* cloned indexes from INCLUDING INDEXES */
73 List *blist; /* "before list" of things to do before
74 * creating the table */
75 List *alist; /* "after list" of things to do after creating
77 IndexStmt *pkey; /* PRIMARY KEY index, if any */
80 /* State shared by transformCreateSchemaStmt and its subroutines */
83 const char *stmtType; /* "CREATE SCHEMA" or "ALTER SCHEMA" */
84 char *schemaname; /* name of schema */
85 char *authid; /* owner of schema */
86 List *sequences; /* CREATE SEQUENCE items */
87 List *tables; /* CREATE TABLE items */
88 List *views; /* CREATE VIEW items */
89 List *indexes; /* CREATE INDEX items */
90 List *triggers; /* CREATE TRIGGER items */
91 List *grants; /* GRANT items */
92 } CreateSchemaStmtContext;
95 static void transformColumnDefinition(ParseState *pstate,
96 CreateStmtContext *cxt,
98 static void transformTableConstraint(ParseState *pstate,
99 CreateStmtContext *cxt,
100 Constraint *constraint);
101 static void transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
102 InhRelation *inhrelation);
103 static IndexStmt *generateClonedIndexStmt(CreateStmtContext *cxt,
104 Relation parent_index, AttrNumber *attmap);
105 static List *get_opclass(Oid opclass, Oid actual_datatype);
106 static void transformIndexConstraints(ParseState *pstate,
107 CreateStmtContext *cxt);
108 static IndexStmt *transformIndexConstraint(Constraint *constraint,
109 CreateStmtContext *cxt);
110 static void transformFKConstraints(ParseState *pstate,
111 CreateStmtContext *cxt,
113 bool isAddConstraint);
114 static void transformConstraintAttrs(List *constraintList);
115 static void transformColumnType(ParseState *pstate, ColumnDef *column);
116 static void setSchemaName(char *context_schema, char **stmt_schema_name);
120 * transformCreateStmt -
121 * parse analysis for CREATE TABLE
123 * Returns a List of utility commands to be done in sequence. One of these
124 * will be the transformed CreateStmt, but there may be additional actions
125 * to be done before and after the actual DefineRelation() call.
127 * SQL92 allows constraints to be scattered all over, so thumb through
128 * the columns and collect all constraints into one place.
129 * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
130 * then expand those into multiple IndexStmt blocks.
131 * - thomas 1997-12-02
134 transformCreateStmt(CreateStmt *stmt, const char *queryString)
137 CreateStmtContext cxt;
143 * We must not scribble on the passed-in CreateStmt, so copy it. (This is
144 * overkill, but easy.)
146 stmt = (CreateStmt *) copyObject(stmt);
149 * If the target relation name isn't schema-qualified, make it so. This
150 * prevents some corner cases in which added-on rewritten commands might
151 * think they should apply to other relations that have the same name and
152 * are earlier in the search path. "istemp" is equivalent to a
153 * specification of pg_temp, so no need for anything extra in that case.
155 if (stmt->relation->schemaname == NULL && !stmt->relation->istemp)
157 Oid namespaceid = RangeVarGetCreationNamespace(stmt->relation);
159 stmt->relation->schemaname = get_namespace_name(namespaceid);
163 pstate = make_parsestate(NULL);
164 pstate->p_sourcetext = queryString;
166 cxt.stmtType = "CREATE TABLE";
167 cxt.relation = stmt->relation;
169 cxt.inhRelations = stmt->inhRelations;
172 cxt.ckconstraints = NIL;
173 cxt.fkconstraints = NIL;
174 cxt.ixconstraints = NIL;
175 cxt.inh_indexes = NIL;
179 cxt.hasoids = interpretOidsOption(stmt->options);
182 * Run through each primary element in the table creation clause. Separate
183 * column defs from constraints, and do preliminary analysis.
185 foreach(elements, stmt->tableElts)
187 Node *element = lfirst(elements);
189 switch (nodeTag(element))
192 transformColumnDefinition(pstate, &cxt,
193 (ColumnDef *) element);
197 transformTableConstraint(pstate, &cxt,
198 (Constraint *) element);
202 /* No pre-transformation needed */
203 cxt.fkconstraints = lappend(cxt.fkconstraints, element);
207 transformInhRelation(pstate, &cxt,
208 (InhRelation *) element);
212 elog(ERROR, "unrecognized node type: %d",
213 (int) nodeTag(element));
219 * transformIndexConstraints wants cxt.alist to contain only index
220 * statements, so transfer anything we already have into save_alist.
222 save_alist = cxt.alist;
225 Assert(stmt->constraints == NIL);
228 * Postprocess constraints that give rise to index definitions.
230 transformIndexConstraints(pstate, &cxt);
233 * Postprocess foreign-key constraints.
235 transformFKConstraints(pstate, &cxt, true, false);
240 stmt->tableElts = cxt.columns;
241 stmt->constraints = cxt.ckconstraints;
243 result = lappend(cxt.blist, stmt);
244 result = list_concat(result, cxt.alist);
245 result = list_concat(result, save_alist);
251 * transformColumnDefinition -
252 * transform a single ColumnDef within CREATE TABLE
253 * Also used in ALTER TABLE ADD COLUMN
256 transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
262 Constraint *constraint;
265 cxt->columns = lappend(cxt->columns, column);
267 /* Check for SERIAL pseudo-types */
269 if (list_length(column->typename->names) == 1)
271 char *typname = strVal(linitial(column->typename->names));
273 if (strcmp(typname, "serial") == 0 ||
274 strcmp(typname, "serial4") == 0)
277 column->typename->names = NIL;
278 column->typename->typeid = INT4OID;
280 else if (strcmp(typname, "bigserial") == 0 ||
281 strcmp(typname, "serial8") == 0)
284 column->typename->names = NIL;
285 column->typename->typeid = INT8OID;
289 /* Do necessary work on the column type declaration */
290 transformColumnType(pstate, column);
292 /* Special actions for SERIAL pseudo-types */
300 FuncCall *funccallnode;
301 CreateSeqStmt *seqstmt;
302 AlterSeqStmt *altseqstmt;
306 * Determine namespace and name to use for the sequence.
308 * Although we use ChooseRelationName, it's not guaranteed that the
309 * selected sequence name won't conflict; given sufficiently long
310 * field names, two different serial columns in the same table could
311 * be assigned the same sequence name, and we'd not notice since we
312 * aren't creating the sequence quite yet. In practice this seems
313 * quite unlikely to be a problem, especially since few people would
314 * need two serial columns in one table.
317 snamespaceid = RelationGetNamespace(cxt->rel);
319 snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
320 snamespace = get_namespace_name(snamespaceid);
321 sname = ChooseRelationName(cxt->relation->relname,
327 (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
328 cxt->stmtType, sname,
329 cxt->relation->relname, column->colname)));
332 * Build a CREATE SEQUENCE command to create the sequence object, and
333 * add it to the list of things to be done before this CREATE/ALTER
336 seqstmt = makeNode(CreateSeqStmt);
337 seqstmt->sequence = makeRangeVar(snamespace, sname);
338 seqstmt->options = NIL;
340 cxt->blist = lappend(cxt->blist, seqstmt);
343 * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence
344 * as owned by this column, and add it to the list of things to be
345 * done after this CREATE/ALTER TABLE.
347 altseqstmt = makeNode(AlterSeqStmt);
348 altseqstmt->sequence = makeRangeVar(snamespace, sname);
349 attnamelist = list_make3(makeString(snamespace),
350 makeString(cxt->relation->relname),
351 makeString(column->colname));
352 altseqstmt->options = list_make1(makeDefElem("owned_by",
353 (Node *) attnamelist));
355 cxt->alist = lappend(cxt->alist, altseqstmt);
358 * Create appropriate constraints for SERIAL. We do this in full,
359 * rather than shortcutting, so that we will detect any conflicting
360 * constraints the user wrote (like a different DEFAULT).
362 * Create an expression tree representing the function call
363 * nextval('sequencename'). We cannot reduce the raw tree to cooked
364 * form until after the sequence is created, but there's no need to do
367 qstring = quote_qualified_identifier(snamespace, sname);
368 snamenode = makeNode(A_Const);
369 snamenode->val.type = T_String;
370 snamenode->val.val.str = qstring;
371 snamenode->typename = SystemTypeName("regclass");
372 funccallnode = makeNode(FuncCall);
373 funccallnode->funcname = SystemFuncName("nextval");
374 funccallnode->args = list_make1(snamenode);
375 funccallnode->agg_star = false;
376 funccallnode->agg_distinct = false;
377 funccallnode->location = -1;
379 constraint = makeNode(Constraint);
380 constraint->contype = CONSTR_DEFAULT;
381 constraint->raw_expr = (Node *) funccallnode;
382 constraint->cooked_expr = NULL;
383 constraint->keys = NIL;
384 column->constraints = lappend(column->constraints, constraint);
386 constraint = makeNode(Constraint);
387 constraint->contype = CONSTR_NOTNULL;
388 column->constraints = lappend(column->constraints, constraint);
391 /* Process column constraints, if any... */
392 transformConstraintAttrs(column->constraints);
394 saw_nullable = false;
397 foreach(clist, column->constraints)
399 constraint = lfirst(clist);
402 * If this column constraint is a FOREIGN KEY constraint, then we fill
403 * in the current attribute's name and throw it into the list of FK
404 * constraints to be processed later.
406 if (IsA(constraint, FkConstraint))
408 FkConstraint *fkconstraint = (FkConstraint *) constraint;
410 fkconstraint->fk_attrs = list_make1(makeString(column->colname));
411 cxt->fkconstraints = lappend(cxt->fkconstraints, fkconstraint);
415 Assert(IsA(constraint, Constraint));
417 switch (constraint->contype)
420 if (saw_nullable && column->is_not_null)
422 (errcode(ERRCODE_SYNTAX_ERROR),
423 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
424 column->colname, cxt->relation->relname)));
425 column->is_not_null = FALSE;
430 if (saw_nullable && !column->is_not_null)
432 (errcode(ERRCODE_SYNTAX_ERROR),
433 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
434 column->colname, cxt->relation->relname)));
435 column->is_not_null = TRUE;
442 (errcode(ERRCODE_SYNTAX_ERROR),
443 errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
444 column->colname, cxt->relation->relname)));
445 column->raw_default = constraint->raw_expr;
446 Assert(constraint->cooked_expr == NULL);
452 if (constraint->keys == NIL)
453 constraint->keys = list_make1(makeString(column->colname));
454 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
458 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
461 case CONSTR_ATTR_DEFERRABLE:
462 case CONSTR_ATTR_NOT_DEFERRABLE:
463 case CONSTR_ATTR_DEFERRED:
464 case CONSTR_ATTR_IMMEDIATE:
465 /* transformConstraintAttrs took care of these */
469 elog(ERROR, "unrecognized constraint type: %d",
470 constraint->contype);
477 * transformTableConstraint
478 * transform a Constraint node within CREATE TABLE or ALTER TABLE
481 transformTableConstraint(ParseState *pstate, CreateStmtContext *cxt,
482 Constraint *constraint)
484 switch (constraint->contype)
488 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
492 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
498 case CONSTR_ATTR_DEFERRABLE:
499 case CONSTR_ATTR_NOT_DEFERRABLE:
500 case CONSTR_ATTR_DEFERRED:
501 case CONSTR_ATTR_IMMEDIATE:
502 elog(ERROR, "invalid context for constraint type %d",
503 constraint->contype);
507 elog(ERROR, "unrecognized constraint type: %d",
508 constraint->contype);
514 * transformInhRelation
516 * Change the LIKE <subtable> portion of a CREATE TABLE statement into
517 * column definitions which recreate the user defined column portions of
521 transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
522 InhRelation *inhRelation)
524 AttrNumber parent_attno;
529 bool including_defaults = false;
530 bool including_constraints = false;
531 bool including_indexes = false;
534 relation = heap_openrv(inhRelation->relation, AccessShareLock);
536 if (relation->rd_rel->relkind != RELKIND_RELATION)
538 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
539 errmsg("inherited relation \"%s\" is not a table",
540 inhRelation->relation->relname)));
543 * Check for SELECT privilages
545 aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
547 if (aclresult != ACLCHECK_OK)
548 aclcheck_error(aclresult, ACL_KIND_CLASS,
549 RelationGetRelationName(relation));
551 tupleDesc = RelationGetDescr(relation);
552 constr = tupleDesc->constr;
554 foreach(elem, inhRelation->options)
556 int option = lfirst_int(elem);
560 case CREATE_TABLE_LIKE_INCLUDING_DEFAULTS:
561 including_defaults = true;
563 case CREATE_TABLE_LIKE_EXCLUDING_DEFAULTS:
564 including_defaults = false;
566 case CREATE_TABLE_LIKE_INCLUDING_CONSTRAINTS:
567 including_constraints = true;
569 case CREATE_TABLE_LIKE_EXCLUDING_CONSTRAINTS:
570 including_constraints = false;
572 case CREATE_TABLE_LIKE_INCLUDING_INDEXES:
573 including_indexes = true;
575 case CREATE_TABLE_LIKE_EXCLUDING_INDEXES:
576 including_indexes = false;
579 elog(ERROR, "unrecognized CREATE TABLE LIKE option: %d",
585 * Insert the copied attributes into the cxt for the new table definition.
587 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
590 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
591 char *attributeName = NameStr(attribute->attname);
595 * Ignore dropped columns in the parent.
597 if (attribute->attisdropped)
601 * Create a new column, which is marked as NOT inherited.
603 * For constraints, ONLY the NOT NULL constraint is inherited by the
604 * new column definition per SQL99.
606 def = makeNode(ColumnDef);
607 def->colname = pstrdup(attributeName);
608 def->typename = makeTypeNameFromOid(attribute->atttypid,
609 attribute->atttypmod);
611 def->is_local = true;
612 def->is_not_null = attribute->attnotnull;
613 def->raw_default = NULL;
614 def->cooked_default = NULL;
615 def->constraints = NIL;
620 cxt->columns = lappend(cxt->columns, def);
623 * Copy default, if present and the default has been requested
625 if (attribute->atthasdef && including_defaults)
627 char *this_default = NULL;
628 AttrDefault *attrdef;
631 /* Find default in constraint structure */
632 Assert(constr != NULL);
633 attrdef = constr->defval;
634 for (i = 0; i < constr->num_defval; i++)
636 if (attrdef[i].adnum == parent_attno)
638 this_default = attrdef[i].adbin;
642 Assert(this_default != NULL);
645 * If default expr could contain any vars, we'd need to fix 'em,
646 * but it can't; so default is ready to apply to child.
649 def->cooked_default = pstrdup(this_default);
654 * Copy CHECK constraints if requested, being careful to adjust attribute
657 if (including_constraints && tupleDesc->constr)
659 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
662 for (ccnum = 0; ccnum < tupleDesc->constr->num_check; ccnum++)
664 char *ccname = tupleDesc->constr->check[ccnum].ccname;
665 char *ccbin = tupleDesc->constr->check[ccnum].ccbin;
666 Node *ccbin_node = stringToNode(ccbin);
667 Constraint *n = makeNode(Constraint);
669 change_varattnos_of_a_node(ccbin_node, attmap);
671 n->contype = CONSTR_CHECK;
672 n->name = pstrdup(ccname);
674 n->cooked_expr = nodeToString(ccbin_node);
675 n->indexspace = NULL;
676 cxt->ckconstraints = lappend(cxt->ckconstraints, (Node *) n);
681 * Likewise, copy indexes if requested
683 if (including_indexes && relation->rd_rel->relhasindex)
685 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
686 List *parent_indexes;
689 parent_indexes = RelationGetIndexList(relation);
691 foreach(l, parent_indexes)
693 Oid parent_index_oid = lfirst_oid(l);
694 Relation parent_index;
695 IndexStmt *index_stmt;
697 parent_index = index_open(parent_index_oid, AccessShareLock);
699 /* Build CREATE INDEX statement to recreate the parent_index */
700 index_stmt = generateClonedIndexStmt(cxt, parent_index, attmap);
702 /* Save it in the inh_indexes list for the time being */
703 cxt->inh_indexes = lappend(cxt->inh_indexes, index_stmt);
705 index_close(parent_index, AccessShareLock);
710 * Close the parent rel, but keep our AccessShareLock on it until xact
711 * commit. That will prevent someone else from deleting or ALTERing the
712 * parent before the child is committed.
714 heap_close(relation, NoLock);
718 * Generate an IndexStmt node using information from an already existing index
719 * "source_idx". Attribute numbers should be adjusted according to attmap.
722 generateClonedIndexStmt(CreateStmtContext *cxt, Relation source_idx,
725 Oid source_relid = RelationGetRelid(source_idx);
728 Form_pg_class idxrelrec;
729 Form_pg_index idxrec;
734 ListCell *indexpr_item;
742 * Fetch pg_class tuple of source index. We can't use the copy in the
743 * relcache entry because it doesn't include optional fields.
745 ht_idxrel = SearchSysCache(RELOID,
746 ObjectIdGetDatum(source_relid),
748 if (!HeapTupleIsValid(ht_idxrel))
749 elog(ERROR, "cache lookup failed for relation %u", source_relid);
750 idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
752 /* Fetch pg_index tuple for source index from relcache entry */
753 ht_idx = source_idx->rd_indextuple;
754 idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
755 indrelid = idxrec->indrelid;
757 /* Fetch pg_am tuple for source index from relcache entry */
758 amrec = source_idx->rd_am;
760 /* Must get indclass the hard way, since it's not stored in relcache */
761 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
762 Anum_pg_index_indclass, &isnull);
764 indclass = (oidvector *) DatumGetPointer(datum);
766 /* Begin building the IndexStmt */
767 index = makeNode(IndexStmt);
768 index->relation = cxt->relation;
769 index->accessMethod = pstrdup(NameStr(amrec->amname));
770 index->tableSpace = get_tablespace_name(source_idx->rd_node.spcNode);
771 index->unique = idxrec->indisunique;
772 index->primary = idxrec->indisprimary;
773 index->concurrent = false;
776 * We don't try to preserve the name of the source index; instead, just
777 * let DefineIndex() choose a reasonable name.
779 index->idxname = NULL;
782 * If the index is marked PRIMARY, it's certainly from a constraint;
783 * else, if it's not marked UNIQUE, it certainly isn't; else, we have
784 * to search pg_depend to see if there's an associated unique constraint.
787 index->isconstraint = true;
788 else if (!index->unique)
789 index->isconstraint = false;
791 index->isconstraint = OidIsValid(get_index_constraint(source_relid));
793 /* Get the index expressions, if any */
794 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
795 Anum_pg_index_indexprs, &isnull);
800 exprsString = DatumGetCString(DirectFunctionCall1(textout, datum));
801 indexprs = (List *) stringToNode(exprsString);
806 /* Build the list of IndexElem */
807 index->indexParams = NIL;
809 indexpr_item = list_head(indexprs);
810 for (keyno = 0; keyno < idxrec->indnatts; keyno++)
813 AttrNumber attnum = idxrec->indkey.values[keyno];
814 int16 opt = source_idx->rd_indoption[keyno];
816 iparam = makeNode(IndexElem);
818 if (AttributeNumberIsValid(attnum))
820 /* Simple index column */
823 attname = get_relid_attribute_name(indrelid, attnum);
824 keycoltype = get_atttype(indrelid, attnum);
826 iparam->name = attname;
831 /* Expressional index */
834 if (indexpr_item == NULL)
835 elog(ERROR, "too few entries in indexprs list");
836 indexkey = (Node *) lfirst(indexpr_item);
837 indexpr_item = lnext(indexpr_item);
839 /* OK to modify indexkey since we are working on a private copy */
840 change_varattnos_of_a_node(indexkey, attmap);
843 iparam->expr = indexkey;
845 keycoltype = exprType(indexkey);
848 /* Add the operator class name, if non-default */
849 iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
851 iparam->ordering = SORTBY_DEFAULT;
852 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
854 /* Adjust options if necessary */
855 if (amrec->amcanorder)
858 * If it supports sort ordering, copy DESC and NULLS opts.
859 * Don't set non-default settings unnecessarily, though,
860 * so as to improve the chance of recognizing equivalence
861 * to constraint indexes.
863 if (opt & INDOPTION_DESC)
865 iparam->ordering = SORTBY_DESC;
866 if ((opt & INDOPTION_NULLS_FIRST) == 0)
867 iparam->nulls_ordering = SORTBY_NULLS_LAST;
871 if (opt & INDOPTION_NULLS_FIRST)
872 iparam->nulls_ordering = SORTBY_NULLS_FIRST;
876 index->indexParams = lappend(index->indexParams, iparam);
879 /* Copy reloptions if any */
880 datum = SysCacheGetAttr(RELOID, ht_idxrel,
881 Anum_pg_class_reloptions, &isnull);
883 index->options = untransformRelOptions(datum);
885 /* If it's a partial index, decompile and append the predicate */
886 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
887 Anum_pg_index_indpred, &isnull);
892 /* Convert text string to node tree */
893 pred_str = DatumGetCString(DirectFunctionCall1(textout, datum));
894 index->whereClause = (Node *) stringToNode(pred_str);
895 /* Adjust attribute numbers */
896 change_varattnos_of_a_node(index->whereClause, attmap);
900 ReleaseSysCache(ht_idxrel);
906 * get_opclass - fetch name of an index operator class
908 * If the opclass is the default for the given actual_datatype, then
909 * the return value is NIL.
912 get_opclass(Oid opclass, Oid actual_datatype)
915 Form_pg_opclass opc_rec;
918 ht_opc = SearchSysCache(CLAOID,
919 ObjectIdGetDatum(opclass),
921 if (!HeapTupleIsValid(ht_opc))
922 elog(ERROR, "cache lookup failed for opclass %u", opclass);
923 opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
925 if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
927 /* For simplicity, we always schema-qualify the name */
928 char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
929 char *opc_name = pstrdup(NameStr(opc_rec->opcname));
931 result = list_make2(makeString(nsp_name), makeString(opc_name));
934 ReleaseSysCache(ht_opc);
940 * transformIndexConstraints
941 * Handle UNIQUE and PRIMARY KEY constraints, which create indexes.
942 * We also merge in any index definitions arising from
943 * LIKE ... INCLUDING INDEXES.
946 transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
949 List *indexlist = NIL;
953 * Run through the constraints that need to generate an index. For PRIMARY
954 * KEY, mark each column as NOT NULL and create an index. For UNIQUE,
955 * create an index as for PRIMARY KEY, but do not insist on NOT NULL.
957 foreach(lc, cxt->ixconstraints)
959 Constraint *constraint = (Constraint *) lfirst(lc);
961 Assert(IsA(constraint, Constraint));
962 Assert(constraint->contype == CONSTR_PRIMARY ||
963 constraint->contype == CONSTR_UNIQUE);
965 index = transformIndexConstraint(constraint, cxt);
967 indexlist = lappend(indexlist, index);
970 /* Add in any indexes defined by LIKE ... INCLUDING INDEXES */
971 foreach(lc, cxt->inh_indexes)
973 index = (IndexStmt *) lfirst(lc);
977 if (cxt->pkey != NULL)
979 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
980 errmsg("multiple primary keys for table \"%s\" are not allowed",
981 cxt->relation->relname)));
985 indexlist = lappend(indexlist, index);
989 * Scan the index list and remove any redundant index specifications. This
990 * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
991 * strict reading of SQL92 would suggest raising an error instead, but
992 * that strikes me as too anal-retentive. - tgl 2001-02-14
994 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
995 * pre-existing indexes, too.
997 Assert(cxt->alist == NIL);
998 if (cxt->pkey != NULL)
1000 /* Make sure we keep the PKEY index in preference to others... */
1001 cxt->alist = list_make1(cxt->pkey);
1004 foreach(lc, indexlist)
1011 /* if it's pkey, it's already in cxt->alist */
1012 if (index == cxt->pkey)
1015 foreach(k, cxt->alist)
1017 IndexStmt *priorindex = lfirst(k);
1019 if (equal(index->indexParams, priorindex->indexParams) &&
1020 equal(index->whereClause, priorindex->whereClause) &&
1021 strcmp(index->accessMethod, priorindex->accessMethod) == 0)
1023 priorindex->unique |= index->unique;
1025 * If the prior index is as yet unnamed, and this one is
1026 * named, then transfer the name to the prior index. This
1027 * ensures that if we have named and unnamed constraints,
1028 * we'll use (at least one of) the names for the index.
1030 if (priorindex->idxname == NULL)
1031 priorindex->idxname = index->idxname;
1038 cxt->alist = lappend(cxt->alist, index);
1043 * transformIndexConstraint
1044 * Transform one UNIQUE or PRIMARY KEY constraint for
1045 * transformIndexConstraints.
1048 transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
1054 index = makeNode(IndexStmt);
1056 index->unique = true;
1057 index->primary = (constraint->contype == CONSTR_PRIMARY);
1060 if (cxt->pkey != NULL)
1062 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1063 errmsg("multiple primary keys for table \"%s\" are not allowed",
1064 cxt->relation->relname)));
1068 * In ALTER TABLE case, a primary index might already exist, but
1069 * DefineIndex will check for it.
1072 index->isconstraint = true;
1074 if (constraint->name != NULL)
1075 index->idxname = pstrdup(constraint->name);
1077 index->idxname = NULL; /* DefineIndex will choose name */
1079 index->relation = cxt->relation;
1080 index->accessMethod = DEFAULT_INDEX_TYPE;
1081 index->options = constraint->options;
1082 index->tableSpace = constraint->indexspace;
1083 index->indexParams = NIL;
1084 index->whereClause = NULL;
1085 index->concurrent = false;
1088 * Make sure referenced keys exist. If we are making a PRIMARY KEY index,
1089 * also make sure they are NOT NULL, if possible. (Although we could leave
1090 * it to DefineIndex to mark the columns NOT NULL, it's more efficient to
1091 * get it right the first time.)
1093 foreach(keys, constraint->keys)
1095 char *key = strVal(lfirst(keys));
1097 ColumnDef *column = NULL;
1100 foreach(columns, cxt->columns)
1102 column = (ColumnDef *) lfirst(columns);
1103 Assert(IsA(column, ColumnDef));
1104 if (strcmp(column->colname, key) == 0)
1112 /* found column in the new table; force it to be NOT NULL */
1113 if (constraint->contype == CONSTR_PRIMARY)
1114 column->is_not_null = TRUE;
1116 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1119 * column will be a system column in the new table, so accept it.
1120 * System columns can't ever be null, so no need to worry about
1121 * PRIMARY/NOT NULL constraint.
1125 else if (cxt->inhRelations)
1127 /* try inherited tables */
1130 foreach(inher, cxt->inhRelations)
1132 RangeVar *inh = (RangeVar *) lfirst(inher);
1136 Assert(IsA(inh, RangeVar));
1137 rel = heap_openrv(inh, AccessShareLock);
1138 if (rel->rd_rel->relkind != RELKIND_RELATION)
1140 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1141 errmsg("inherited relation \"%s\" is not a table",
1143 for (count = 0; count < rel->rd_att->natts; count++)
1145 Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1146 char *inhname = NameStr(inhattr->attname);
1148 if (inhattr->attisdropped)
1150 if (strcmp(key, inhname) == 0)
1155 * We currently have no easy way to force an inherited
1156 * column to be NOT NULL at creation, if its parent
1157 * wasn't so already. We leave it to DefineIndex to
1158 * fix things up in this case.
1163 heap_close(rel, NoLock);
1170 * In the ALTER TABLE case, don't complain about index keys not
1171 * created in the command; they may well exist already. DefineIndex
1172 * will complain about them if not, and will also take care of marking
1175 if (!found && !cxt->isalter)
1177 (errcode(ERRCODE_UNDEFINED_COLUMN),
1178 errmsg("column \"%s\" named in key does not exist",
1181 /* Check for PRIMARY KEY(foo, foo) */
1182 foreach(columns, index->indexParams)
1184 iparam = (IndexElem *) lfirst(columns);
1185 if (iparam->name && strcmp(key, iparam->name) == 0)
1189 (errcode(ERRCODE_DUPLICATE_COLUMN),
1190 errmsg("column \"%s\" appears twice in primary key constraint",
1194 (errcode(ERRCODE_DUPLICATE_COLUMN),
1195 errmsg("column \"%s\" appears twice in unique constraint",
1200 /* OK, add it to the index definition */
1201 iparam = makeNode(IndexElem);
1202 iparam->name = pstrdup(key);
1203 iparam->expr = NULL;
1204 iparam->opclass = NIL;
1205 iparam->ordering = SORTBY_DEFAULT;
1206 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1207 index->indexParams = lappend(index->indexParams, iparam);
1214 * transformFKConstraints
1215 * handle FOREIGN KEY constraints
1218 transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
1219 bool skipValidation, bool isAddConstraint)
1223 if (cxt->fkconstraints == NIL)
1227 * If CREATE TABLE or adding a column with NULL default, we can safely
1228 * skip validation of the constraint.
1232 foreach(fkclist, cxt->fkconstraints)
1234 FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1236 fkconstraint->skip_validation = true;
1241 * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
1242 * CONSTRAINT command to execute after the basic command is complete. (If
1243 * called from ADD CONSTRAINT, that routine will add the FK constraints to
1244 * its own subcommand list.)
1246 * Note: the ADD CONSTRAINT command must also execute after any index
1247 * creation commands. Thus, this should run after
1248 * transformIndexConstraints, so that the CREATE INDEX commands are
1249 * already in cxt->alist.
1251 if (!isAddConstraint)
1253 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1255 alterstmt->relation = cxt->relation;
1256 alterstmt->cmds = NIL;
1257 alterstmt->relkind = OBJECT_TABLE;
1259 foreach(fkclist, cxt->fkconstraints)
1261 FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1262 AlterTableCmd *altercmd = makeNode(AlterTableCmd);
1264 altercmd->subtype = AT_ProcessedConstraint;
1265 altercmd->name = NULL;
1266 altercmd->def = (Node *) fkconstraint;
1267 alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
1270 cxt->alist = lappend(cxt->alist, alterstmt);
1275 * transformIndexStmt - parse analysis for CREATE INDEX
1277 * Note: this is a no-op for an index not using either index expressions or
1278 * a predicate expression. There are several code paths that create indexes
1279 * without bothering to call this, because they know they don't have any
1280 * such expressions to deal with.
1283 transformIndexStmt(IndexStmt *stmt, const char *queryString)
1291 * We must not scribble on the passed-in IndexStmt, so copy it. (This is
1292 * overkill, but easy.)
1294 stmt = (IndexStmt *) copyObject(stmt);
1297 * Open the parent table with appropriate locking. We must do this
1298 * because addRangeTableEntry() would acquire only AccessShareLock,
1299 * leaving DefineIndex() needing to do a lock upgrade with consequent risk
1300 * of deadlock. Make sure this stays in sync with the type of lock
1301 * DefineIndex() wants.
1303 rel = heap_openrv(stmt->relation,
1304 (stmt->concurrent ? ShareUpdateExclusiveLock : ShareLock));
1307 pstate = make_parsestate(NULL);
1308 pstate->p_sourcetext = queryString;
1311 * Put the parent table into the rtable so that the expressions can refer
1312 * to its fields without qualification.
1314 rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1316 /* no to join list, yes to namespaces */
1317 addRTEtoQuery(pstate, rte, false, true, true);
1319 /* take care of the where clause */
1320 if (stmt->whereClause)
1321 stmt->whereClause = transformWhereClause(pstate,
1325 /* take care of any index expressions */
1326 foreach(l, stmt->indexParams)
1328 IndexElem *ielem = (IndexElem *) lfirst(l);
1332 ielem->expr = transformExpr(pstate, ielem->expr);
1335 * We check only that the result type is legitimate; this is for
1336 * consistency with what transformWhereClause() checks for the
1337 * predicate. DefineIndex() will make more checks.
1339 if (expression_returns_set(ielem->expr))
1341 (errcode(ERRCODE_DATATYPE_MISMATCH),
1342 errmsg("index expression cannot return a set")));
1347 * Check that only the base rel is mentioned.
1349 if (list_length(pstate->p_rtable) != 1)
1351 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1352 errmsg("index expressions and predicates can refer only to the table being indexed")));
1354 free_parsestate(pstate);
1356 /* Close relation, but keep the lock */
1357 heap_close(rel, NoLock);
1364 * transformRuleStmt -
1365 * transform a CREATE RULE Statement. The action is a list of parse
1366 * trees which is transformed into a list of query trees, and we also
1367 * transform the WHERE clause if any.
1369 * actions and whereClause are output parameters that receive the
1370 * transformed results.
1372 * Note that we must not scribble on the passed-in RuleStmt, so we do
1373 * copyObject() on the actions and WHERE clause.
1376 transformRuleStmt(RuleStmt *stmt, const char *queryString,
1377 List **actions, Node **whereClause)
1381 RangeTblEntry *oldrte;
1382 RangeTblEntry *newrte;
1385 * To avoid deadlock, make sure the first thing we do is grab
1386 * AccessExclusiveLock on the target relation. This will be needed by
1387 * DefineQueryRewrite(), and we don't want to grab a lesser lock
1390 rel = heap_openrv(stmt->relation, AccessExclusiveLock);
1393 pstate = make_parsestate(NULL);
1394 pstate->p_sourcetext = queryString;
1397 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
1398 * Set up their RTEs in the main pstate for use in parsing the rule
1401 oldrte = addRangeTableEntryForRelation(pstate, rel,
1402 makeAlias("*OLD*", NIL),
1404 newrte = addRangeTableEntryForRelation(pstate, rel,
1405 makeAlias("*NEW*", NIL),
1407 /* Must override addRangeTableEntry's default access-check flags */
1408 oldrte->requiredPerms = 0;
1409 newrte->requiredPerms = 0;
1412 * They must be in the namespace too for lookup purposes, but only add the
1413 * one(s) that are relevant for the current kind of rule. In an UPDATE
1414 * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
1415 * there's no need to be so picky for INSERT & DELETE. We do not add them
1418 switch (stmt->event)
1421 addRTEtoQuery(pstate, oldrte, false, true, true);
1424 addRTEtoQuery(pstate, oldrte, false, true, true);
1425 addRTEtoQuery(pstate, newrte, false, true, true);
1428 addRTEtoQuery(pstate, newrte, false, true, true);
1431 addRTEtoQuery(pstate, oldrte, false, true, true);
1434 elog(ERROR, "unrecognized event type: %d",
1439 /* take care of the where clause */
1440 *whereClause = transformWhereClause(pstate,
1441 (Node *) copyObject(stmt->whereClause),
1444 if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
1446 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1447 errmsg("rule WHERE condition cannot contain references to other relations")));
1449 /* aggregates not allowed (but subselects are okay) */
1450 if (pstate->p_hasAggs)
1452 (errcode(ERRCODE_GROUPING_ERROR),
1453 errmsg("cannot use aggregate function in rule WHERE condition")));
1456 * 'instead nothing' rules with a qualification need a query rangetable so
1457 * the rewrite handler can add the negated rule qualification to the
1458 * original query. We create a query with the new command type CMD_NOTHING
1459 * here that is treated specially by the rewrite system.
1461 if (stmt->actions == NIL)
1463 Query *nothing_qry = makeNode(Query);
1465 nothing_qry->commandType = CMD_NOTHING;
1466 nothing_qry->rtable = pstate->p_rtable;
1467 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
1469 *actions = list_make1(nothing_qry);
1474 List *newactions = NIL;
1477 * transform each statement, like parse_sub_analyze()
1479 foreach(l, stmt->actions)
1481 Node *action = (Node *) lfirst(l);
1482 ParseState *sub_pstate = make_parsestate(NULL);
1489 * Since outer ParseState isn't parent of inner, have to pass down
1490 * the query text by hand.
1492 sub_pstate->p_sourcetext = queryString;
1495 * Set up OLD/NEW in the rtable for this statement. The entries
1496 * are added only to relnamespace, not varnamespace, because we
1497 * don't want them to be referred to by unqualified field names
1498 * nor "*" in the rule actions. We decide later whether to put
1499 * them in the joinlist.
1501 oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
1502 makeAlias("*OLD*", NIL),
1504 newrte = addRangeTableEntryForRelation(sub_pstate, rel,
1505 makeAlias("*NEW*", NIL),
1507 oldrte->requiredPerms = 0;
1508 newrte->requiredPerms = 0;
1509 addRTEtoQuery(sub_pstate, oldrte, false, true, false);
1510 addRTEtoQuery(sub_pstate, newrte, false, true, false);
1512 /* Transform the rule action statement */
1513 top_subqry = transformStmt(sub_pstate,
1514 (Node *) copyObject(action));
1517 * We cannot support utility-statement actions (eg NOTIFY) with
1518 * nonempty rule WHERE conditions, because there's no way to make
1519 * the utility action execute conditionally.
1521 if (top_subqry->commandType == CMD_UTILITY &&
1522 *whereClause != NULL)
1524 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1525 errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
1528 * If the action is INSERT...SELECT, OLD/NEW have been pushed down
1529 * into the SELECT, and that's what we need to look at. (Ugly
1530 * kluge ... try to fix this when we redesign querytrees.)
1532 sub_qry = getInsertSelectQuery(top_subqry, NULL);
1535 * If the sub_qry is a setop, we cannot attach any qualifications
1536 * to it, because the planner won't notice them. This could
1537 * perhaps be relaxed someday, but for now, we may as well reject
1538 * such a rule immediately.
1540 if (sub_qry->setOperations != NULL && *whereClause != NULL)
1542 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1543 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1546 * Validate action's use of OLD/NEW, qual too
1549 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
1550 rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
1552 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
1553 rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
1555 switch (stmt->event)
1560 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1561 errmsg("ON SELECT rule cannot use OLD")));
1564 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1565 errmsg("ON SELECT rule cannot use NEW")));
1573 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1574 errmsg("ON INSERT rule cannot use OLD")));
1579 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1580 errmsg("ON DELETE rule cannot use NEW")));
1583 elog(ERROR, "unrecognized event type: %d",
1589 * For efficiency's sake, add OLD to the rule action's jointree
1590 * only if it was actually referenced in the statement or qual.
1592 * For INSERT, NEW is not really a relation (only a reference to
1593 * the to-be-inserted tuple) and should never be added to the
1596 * For UPDATE, we treat NEW as being another kind of reference to
1597 * OLD, because it represents references to *transformed* tuples
1598 * of the existing relation. It would be wrong to enter NEW
1599 * separately in the jointree, since that would cause a double
1600 * join of the updated relation. It's also wrong to fail to make
1601 * a jointree entry if only NEW and not OLD is mentioned.
1603 if (has_old || (has_new && stmt->event == CMD_UPDATE))
1606 * If sub_qry is a setop, manipulating its jointree will do no
1607 * good at all, because the jointree is dummy. (This should be
1608 * a can't-happen case because of prior tests.)
1610 if (sub_qry->setOperations != NULL)
1612 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1613 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1614 /* hack so we can use addRTEtoQuery() */
1615 sub_pstate->p_rtable = sub_qry->rtable;
1616 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
1617 addRTEtoQuery(sub_pstate, oldrte, true, false, false);
1618 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
1621 newactions = lappend(newactions, top_subqry);
1623 free_parsestate(sub_pstate);
1626 *actions = newactions;
1629 free_parsestate(pstate);
1631 /* Close relation, but keep the exclusive lock */
1632 heap_close(rel, NoLock);
1637 * transformAlterTableStmt -
1638 * parse analysis for ALTER TABLE
1640 * Returns a List of utility commands to be done in sequence. One of these
1641 * will be the transformed AlterTableStmt, but there may be additional actions
1642 * to be done before and after the actual AlterTable() call.
1645 transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString)
1649 CreateStmtContext cxt;
1654 List *newcmds = NIL;
1655 bool skipValidation = true;
1656 AlterTableCmd *newcmd;
1659 * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
1660 * is overkill, but easy.)
1662 stmt = (AlterTableStmt *) copyObject(stmt);
1665 * Acquire exclusive lock on the target relation, which will be held until
1666 * end of transaction. This ensures any decisions we make here based on
1667 * the state of the relation will still be good at execution. We must get
1668 * exclusive lock now because execution will; taking a lower grade lock
1669 * now and trying to upgrade later risks deadlock.
1671 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
1674 pstate = make_parsestate(NULL);
1675 pstate->p_sourcetext = queryString;
1677 cxt.stmtType = "ALTER TABLE";
1678 cxt.relation = stmt->relation;
1680 cxt.inhRelations = NIL;
1682 cxt.hasoids = false; /* need not be right */
1684 cxt.ckconstraints = NIL;
1685 cxt.fkconstraints = NIL;
1686 cxt.ixconstraints = NIL;
1687 cxt.inh_indexes = NIL;
1693 * The only subtypes that currently require parse transformation handling
1694 * are ADD COLUMN and ADD CONSTRAINT. These largely re-use code from
1697 foreach(lcmd, stmt->cmds)
1699 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
1701 switch (cmd->subtype)
1705 ColumnDef *def = (ColumnDef *) cmd->def;
1707 Assert(IsA(cmd->def, ColumnDef));
1708 transformColumnDefinition(pstate, &cxt,
1709 (ColumnDef *) cmd->def);
1712 * If the column has a non-null default, we can't skip
1713 * validation of foreign keys.
1715 if (((ColumnDef *) cmd->def)->raw_default != NULL)
1716 skipValidation = false;
1718 newcmds = lappend(newcmds, cmd);
1721 * Convert an ADD COLUMN ... NOT NULL constraint to a
1724 if (def->is_not_null)
1726 /* Remove NOT NULL from AddColumn */
1727 def->is_not_null = false;
1729 /* Add as a separate AlterTableCmd */
1730 newcmd = makeNode(AlterTableCmd);
1731 newcmd->subtype = AT_SetNotNull;
1732 newcmd->name = pstrdup(def->colname);
1733 newcmds = lappend(newcmds, newcmd);
1737 * All constraints are processed in other ways. Remove the
1740 def->constraints = NIL;
1744 case AT_AddConstraint:
1747 * The original AddConstraint cmd node doesn't go to newcmds
1750 if (IsA(cmd->def, Constraint))
1751 transformTableConstraint(pstate, &cxt,
1752 (Constraint *) cmd->def);
1753 else if (IsA(cmd->def, FkConstraint))
1755 cxt.fkconstraints = lappend(cxt.fkconstraints, cmd->def);
1756 skipValidation = false;
1759 elog(ERROR, "unrecognized node type: %d",
1760 (int) nodeTag(cmd->def));
1763 case AT_ProcessedConstraint:
1766 * Already-transformed ADD CONSTRAINT, so just make it look
1767 * like the standard case.
1769 cmd->subtype = AT_AddConstraint;
1770 newcmds = lappend(newcmds, cmd);
1774 newcmds = lappend(newcmds, cmd);
1780 * transformIndexConstraints wants cxt.alist to contain only index
1781 * statements, so transfer anything we already have into save_alist
1784 save_alist = cxt.alist;
1787 /* Postprocess index and FK constraints */
1788 transformIndexConstraints(pstate, &cxt);
1790 transformFKConstraints(pstate, &cxt, skipValidation, true);
1793 * Push any index-creation commands into the ALTER, so that they can be
1794 * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
1795 * the IndexStmt attached to an AT_AddIndex subcommand has already been
1796 * through transformIndexStmt.
1798 foreach(l, cxt.alist)
1800 Node *idxstmt = (Node *) lfirst(l);
1802 Assert(IsA(idxstmt, IndexStmt));
1803 newcmd = makeNode(AlterTableCmd);
1804 newcmd->subtype = AT_AddIndex;
1805 newcmd->def = (Node *) transformIndexStmt((IndexStmt *) idxstmt,
1807 newcmds = lappend(newcmds, newcmd);
1811 /* Append any CHECK or FK constraints to the commands list */
1812 foreach(l, cxt.ckconstraints)
1814 newcmd = makeNode(AlterTableCmd);
1815 newcmd->subtype = AT_AddConstraint;
1816 newcmd->def = (Node *) lfirst(l);
1817 newcmds = lappend(newcmds, newcmd);
1819 foreach(l, cxt.fkconstraints)
1821 newcmd = makeNode(AlterTableCmd);
1822 newcmd->subtype = AT_AddConstraint;
1823 newcmd->def = (Node *) lfirst(l);
1824 newcmds = lappend(newcmds, newcmd);
1827 /* Close rel but keep lock */
1828 relation_close(rel, NoLock);
1833 stmt->cmds = newcmds;
1835 result = lappend(cxt.blist, stmt);
1836 result = list_concat(result, cxt.alist);
1837 result = list_concat(result, save_alist);
1844 * Preprocess a list of column constraint clauses
1845 * to attach constraint attributes to their primary constraint nodes
1846 * and detect inconsistent/misplaced constraint attributes.
1848 * NOTE: currently, attributes are only supported for FOREIGN KEY primary
1849 * constraints, but someday they ought to be supported for other constraints.
1852 transformConstraintAttrs(List *constraintList)
1854 Node *lastprimarynode = NULL;
1855 bool saw_deferrability = false;
1856 bool saw_initially = false;
1859 foreach(clist, constraintList)
1861 Node *node = lfirst(clist);
1863 if (!IsA(node, Constraint))
1865 lastprimarynode = node;
1866 /* reset flags for new primary node */
1867 saw_deferrability = false;
1868 saw_initially = false;
1872 Constraint *con = (Constraint *) node;
1874 switch (con->contype)
1876 case CONSTR_ATTR_DEFERRABLE:
1877 if (lastprimarynode == NULL ||
1878 !IsA(lastprimarynode, FkConstraint))
1880 (errcode(ERRCODE_SYNTAX_ERROR),
1881 errmsg("misplaced DEFERRABLE clause")));
1882 if (saw_deferrability)
1884 (errcode(ERRCODE_SYNTAX_ERROR),
1885 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
1886 saw_deferrability = true;
1887 ((FkConstraint *) lastprimarynode)->deferrable = true;
1889 case CONSTR_ATTR_NOT_DEFERRABLE:
1890 if (lastprimarynode == NULL ||
1891 !IsA(lastprimarynode, FkConstraint))
1893 (errcode(ERRCODE_SYNTAX_ERROR),
1894 errmsg("misplaced NOT DEFERRABLE clause")));
1895 if (saw_deferrability)
1897 (errcode(ERRCODE_SYNTAX_ERROR),
1898 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
1899 saw_deferrability = true;
1900 ((FkConstraint *) lastprimarynode)->deferrable = false;
1901 if (saw_initially &&
1902 ((FkConstraint *) lastprimarynode)->initdeferred)
1904 (errcode(ERRCODE_SYNTAX_ERROR),
1905 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
1907 case CONSTR_ATTR_DEFERRED:
1908 if (lastprimarynode == NULL ||
1909 !IsA(lastprimarynode, FkConstraint))
1911 (errcode(ERRCODE_SYNTAX_ERROR),
1912 errmsg("misplaced INITIALLY DEFERRED clause")));
1915 (errcode(ERRCODE_SYNTAX_ERROR),
1916 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
1917 saw_initially = true;
1918 ((FkConstraint *) lastprimarynode)->initdeferred = true;
1921 * If only INITIALLY DEFERRED appears, assume DEFERRABLE
1923 if (!saw_deferrability)
1924 ((FkConstraint *) lastprimarynode)->deferrable = true;
1925 else if (!((FkConstraint *) lastprimarynode)->deferrable)
1927 (errcode(ERRCODE_SYNTAX_ERROR),
1928 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
1930 case CONSTR_ATTR_IMMEDIATE:
1931 if (lastprimarynode == NULL ||
1932 !IsA(lastprimarynode, FkConstraint))
1934 (errcode(ERRCODE_SYNTAX_ERROR),
1935 errmsg("misplaced INITIALLY IMMEDIATE clause")));
1938 (errcode(ERRCODE_SYNTAX_ERROR),
1939 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
1940 saw_initially = true;
1941 ((FkConstraint *) lastprimarynode)->initdeferred = false;
1944 /* Otherwise it's not an attribute */
1945 lastprimarynode = node;
1946 /* reset flags for new primary node */
1947 saw_deferrability = false;
1948 saw_initially = false;
1956 * Special handling of type definition for a column
1959 transformColumnType(ParseState *pstate, ColumnDef *column)
1962 * All we really need to do here is verify that the type is valid.
1964 Type ctype = typenameType(pstate, column->typename, NULL);
1966 ReleaseSysCache(ctype);
1971 * transformCreateSchemaStmt -
1972 * analyzes the CREATE SCHEMA statement
1974 * Split the schema element list into individual commands and place
1975 * them in the result list in an order such that there are no forward
1976 * references (e.g. GRANT to a table created later in the list). Note
1977 * that the logic we use for determining forward references is
1978 * presently quite incomplete.
1980 * SQL92 also allows constraints to make forward references, so thumb through
1981 * the table columns and move forward references to a posterior alter-table
1984 * The result is a list of parse nodes that still need to be analyzed ---
1985 * but we can't analyze the later commands until we've executed the earlier
1986 * ones, because of possible inter-object references.
1988 * Note: this breaks the rules a little bit by modifying schema-name fields
1989 * within passed-in structs. However, the transformation would be the same
1990 * if done over, so it should be all right to scribble on the input to this
1994 transformCreateSchemaStmt(CreateSchemaStmt *stmt)
1996 CreateSchemaStmtContext cxt;
2000 cxt.stmtType = "CREATE SCHEMA";
2001 cxt.schemaname = stmt->schemaname;
2002 cxt.authid = stmt->authid;
2003 cxt.sequences = NIL;
2011 * Run through each schema element in the schema element list. Separate
2012 * statements by type, and do preliminary analysis.
2014 foreach(elements, stmt->schemaElts)
2016 Node *element = lfirst(elements);
2018 switch (nodeTag(element))
2020 case T_CreateSeqStmt:
2022 CreateSeqStmt *elp = (CreateSeqStmt *) element;
2024 setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
2025 cxt.sequences = lappend(cxt.sequences, element);
2031 CreateStmt *elp = (CreateStmt *) element;
2033 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2036 * XXX todo: deal with constraints
2038 cxt.tables = lappend(cxt.tables, element);
2044 ViewStmt *elp = (ViewStmt *) element;
2046 setSchemaName(cxt.schemaname, &elp->view->schemaname);
2049 * XXX todo: deal with references between views
2051 cxt.views = lappend(cxt.views, element);
2057 IndexStmt *elp = (IndexStmt *) element;
2059 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2060 cxt.indexes = lappend(cxt.indexes, element);
2064 case T_CreateTrigStmt:
2066 CreateTrigStmt *elp = (CreateTrigStmt *) element;
2068 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2069 cxt.triggers = lappend(cxt.triggers, element);
2074 cxt.grants = lappend(cxt.grants, element);
2078 elog(ERROR, "unrecognized node type: %d",
2079 (int) nodeTag(element));
2084 result = list_concat(result, cxt.sequences);
2085 result = list_concat(result, cxt.tables);
2086 result = list_concat(result, cxt.views);
2087 result = list_concat(result, cxt.indexes);
2088 result = list_concat(result, cxt.triggers);
2089 result = list_concat(result, cxt.grants);
2096 * Set or check schema name in an element of a CREATE SCHEMA command
2099 setSchemaName(char *context_schema, char **stmt_schema_name)
2101 if (*stmt_schema_name == NULL)
2102 *stmt_schema_name = context_schema;
2103 else if (strcmp(context_schema, *stmt_schema_name) != 0)
2105 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
2106 errmsg("CREATE specifies a schema (%s) "
2107 "different from the one being created (%s)",
2108 *stmt_schema_name, context_schema)));