1 /*-------------------------------------------------------------------------
4 * Perform parse analysis work for various utility commands
6 * Formerly we did this work during parse_analyze() in analyze.c. However
7 * that is fairly unsafe in the presence of querytree caching, since any
8 * database state that we depend on in making the transformations might be
9 * obsolete by the time the utility command is executed; and utility commands
10 * have no infrastructure for holding locks or rechecking plan validity.
11 * Hence these functions are now called at the start of execution of their
12 * respective utility commands.
14 * NOTE: in general we must avoid scribbling on the passed-in raw parse
15 * tree, since it might be in a plan cache. The simplest solution is
16 * a quick copyObject() call before manipulating the query tree.
19 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
20 * Portions Copyright (c) 1994, Regents of the University of California
22 * $PostgreSQL: pgsql/src/backend/parser/parse_utilcmd.c,v 2.31 2009/12/07 05:22:22 tgl Exp $
24 *-------------------------------------------------------------------------
29 #include "access/genam.h"
30 #include "access/heapam.h"
31 #include "access/reloptions.h"
32 #include "catalog/dependency.h"
33 #include "catalog/heap.h"
34 #include "catalog/index.h"
35 #include "catalog/namespace.h"
36 #include "catalog/pg_constraint.h"
37 #include "catalog/pg_opclass.h"
38 #include "catalog/pg_operator.h"
39 #include "catalog/pg_type.h"
40 #include "commands/comment.h"
41 #include "commands/defrem.h"
42 #include "commands/tablecmds.h"
43 #include "commands/tablespace.h"
44 #include "miscadmin.h"
45 #include "nodes/makefuncs.h"
46 #include "nodes/nodeFuncs.h"
47 #include "parser/analyze.h"
48 #include "parser/parse_clause.h"
49 #include "parser/parse_expr.h"
50 #include "parser/parse_relation.h"
51 #include "parser/parse_type.h"
52 #include "parser/parse_utilcmd.h"
53 #include "parser/parser.h"
54 #include "rewrite/rewriteManip.h"
55 #include "utils/acl.h"
56 #include "utils/builtins.h"
57 #include "utils/lsyscache.h"
58 #include "utils/relcache.h"
59 #include "utils/syscache.h"
62 /* State shared by transformCreateStmt and its subroutines */
65 const char *stmtType; /* "CREATE TABLE" or "ALTER TABLE" */
66 RangeVar *relation; /* relation to create */
67 Relation rel; /* opened/locked rel, if ALTER */
68 List *inhRelations; /* relations to inherit from */
69 bool isalter; /* true if altering existing table */
70 bool hasoids; /* does relation have an OID column? */
71 List *columns; /* ColumnDef items */
72 List *ckconstraints; /* CHECK constraints */
73 List *fkconstraints; /* FOREIGN KEY constraints */
74 List *ixconstraints; /* index-creating constraints */
75 List *inh_indexes; /* cloned indexes from INCLUDING INDEXES */
76 List *blist; /* "before list" of things to do before
77 * creating the table */
78 List *alist; /* "after list" of things to do after creating
80 IndexStmt *pkey; /* PRIMARY KEY index, if any */
83 /* State shared by transformCreateSchemaStmt and its subroutines */
86 const char *stmtType; /* "CREATE SCHEMA" or "ALTER SCHEMA" */
87 char *schemaname; /* name of schema */
88 char *authid; /* owner of schema */
89 List *sequences; /* CREATE SEQUENCE items */
90 List *tables; /* CREATE TABLE items */
91 List *views; /* CREATE VIEW items */
92 List *indexes; /* CREATE INDEX items */
93 List *triggers; /* CREATE TRIGGER items */
94 List *grants; /* GRANT items */
95 } CreateSchemaStmtContext;
98 static void transformColumnDefinition(ParseState *pstate,
99 CreateStmtContext *cxt,
101 static void transformTableConstraint(ParseState *pstate,
102 CreateStmtContext *cxt,
103 Constraint *constraint);
104 static void transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
105 InhRelation *inhrelation);
106 static char *chooseIndexName(const RangeVar *relation, IndexStmt *index_stmt);
107 static IndexStmt *generateClonedIndexStmt(CreateStmtContext *cxt,
108 Relation parent_index, AttrNumber *attmap);
109 static List *get_opclass(Oid opclass, Oid actual_datatype);
110 static void transformIndexConstraints(ParseState *pstate,
111 CreateStmtContext *cxt);
112 static IndexStmt *transformIndexConstraint(Constraint *constraint,
113 CreateStmtContext *cxt);
114 static void transformFKConstraints(ParseState *pstate,
115 CreateStmtContext *cxt,
117 bool isAddConstraint);
118 static void transformConstraintAttrs(ParseState *pstate, List *constraintList);
119 static void transformColumnType(ParseState *pstate, ColumnDef *column);
120 static void setSchemaName(char *context_schema, char **stmt_schema_name);
124 * transformCreateStmt -
125 * parse analysis for CREATE TABLE
127 * Returns a List of utility commands to be done in sequence. One of these
128 * will be the transformed CreateStmt, but there may be additional actions
129 * to be done before and after the actual DefineRelation() call.
131 * SQL92 allows constraints to be scattered all over, so thumb through
132 * the columns and collect all constraints into one place.
133 * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
134 * then expand those into multiple IndexStmt blocks.
135 * - thomas 1997-12-02
138 transformCreateStmt(CreateStmt *stmt, const char *queryString)
141 CreateStmtContext cxt;
147 * We must not scribble on the passed-in CreateStmt, so copy it. (This is
148 * overkill, but easy.)
150 stmt = (CreateStmt *) copyObject(stmt);
153 * If the target relation name isn't schema-qualified, make it so. This
154 * prevents some corner cases in which added-on rewritten commands might
155 * think they should apply to other relations that have the same name and
156 * are earlier in the search path. "istemp" is equivalent to a
157 * specification of pg_temp, so no need for anything extra in that case.
159 if (stmt->relation->schemaname == NULL && !stmt->relation->istemp)
161 Oid namespaceid = RangeVarGetCreationNamespace(stmt->relation);
163 stmt->relation->schemaname = get_namespace_name(namespaceid);
167 pstate = make_parsestate(NULL);
168 pstate->p_sourcetext = queryString;
170 cxt.stmtType = "CREATE TABLE";
171 cxt.relation = stmt->relation;
173 cxt.inhRelations = stmt->inhRelations;
176 cxt.ckconstraints = NIL;
177 cxt.fkconstraints = NIL;
178 cxt.ixconstraints = NIL;
179 cxt.inh_indexes = NIL;
183 cxt.hasoids = interpretOidsOption(stmt->options);
186 * Run through each primary element in the table creation clause. Separate
187 * column defs from constraints, and do preliminary analysis.
189 foreach(elements, stmt->tableElts)
191 Node *element = lfirst(elements);
193 switch (nodeTag(element))
196 transformColumnDefinition(pstate, &cxt,
197 (ColumnDef *) element);
201 transformTableConstraint(pstate, &cxt,
202 (Constraint *) element);
206 transformInhRelation(pstate, &cxt,
207 (InhRelation *) element);
211 elog(ERROR, "unrecognized node type: %d",
212 (int) nodeTag(element));
218 * transformIndexConstraints wants cxt.alist to contain only index
219 * statements, so transfer anything we already have into save_alist.
221 save_alist = cxt.alist;
224 Assert(stmt->constraints == NIL);
227 * Postprocess constraints that give rise to index definitions.
229 transformIndexConstraints(pstate, &cxt);
232 * Postprocess foreign-key constraints.
234 transformFKConstraints(pstate, &cxt, true, false);
239 stmt->tableElts = cxt.columns;
240 stmt->constraints = cxt.ckconstraints;
242 result = lappend(cxt.blist, stmt);
243 result = list_concat(result, cxt.alist);
244 result = list_concat(result, save_alist);
250 * transformColumnDefinition -
251 * transform a single ColumnDef within CREATE TABLE
252 * Also used in ALTER TABLE ADD COLUMN
255 transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
261 Constraint *constraint;
264 cxt->columns = lappend(cxt->columns, column);
266 /* Check for SERIAL pseudo-types */
268 if (list_length(column->typeName->names) == 1 &&
269 !column->typeName->pct_type)
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->typeOid = INT4OID;
280 else if (strcmp(typname, "bigserial") == 0 ||
281 strcmp(typname, "serial8") == 0)
284 column->typeName->names = NIL;
285 column->typeName->typeOid = INT8OID;
289 * We have to reject "serial[]" explicitly, because once we've set
290 * typeid, LookupTypeName won't notice arrayBounds. We don't need any
291 * special coding for serial(typmod) though.
293 if (is_serial && column->typeName->arrayBounds != NIL)
295 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
296 errmsg("array of serial is not implemented"),
297 parser_errposition(pstate, column->typeName->location)));
300 /* Do necessary work on the column type declaration */
301 transformColumnType(pstate, column);
303 /* Special actions for SERIAL pseudo-types */
312 FuncCall *funccallnode;
313 CreateSeqStmt *seqstmt;
314 AlterSeqStmt *altseqstmt;
318 * Determine namespace and name to use for the sequence.
320 * Although we use ChooseRelationName, it's not guaranteed that the
321 * selected sequence name won't conflict; given sufficiently long
322 * field names, two different serial columns in the same table could
323 * be assigned the same sequence name, and we'd not notice since we
324 * aren't creating the sequence quite yet. In practice this seems
325 * quite unlikely to be a problem, especially since few people would
326 * need two serial columns in one table.
329 snamespaceid = RelationGetNamespace(cxt->rel);
331 snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
332 snamespace = get_namespace_name(snamespaceid);
333 sname = ChooseRelationName(cxt->relation->relname,
339 (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
340 cxt->stmtType, sname,
341 cxt->relation->relname, column->colname)));
344 * Build a CREATE SEQUENCE command to create the sequence object, and
345 * add it to the list of things to be done before this CREATE/ALTER
348 seqstmt = makeNode(CreateSeqStmt);
349 seqstmt->sequence = makeRangeVar(snamespace, sname, -1);
350 seqstmt->options = NIL;
352 cxt->blist = lappend(cxt->blist, seqstmt);
355 * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence
356 * as owned by this column, and add it to the list of things to be
357 * done after this CREATE/ALTER TABLE.
359 altseqstmt = makeNode(AlterSeqStmt);
360 altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
361 attnamelist = list_make3(makeString(snamespace),
362 makeString(cxt->relation->relname),
363 makeString(column->colname));
364 altseqstmt->options = list_make1(makeDefElem("owned_by",
365 (Node *) attnamelist));
367 cxt->alist = lappend(cxt->alist, altseqstmt);
370 * Create appropriate constraints for SERIAL. We do this in full,
371 * rather than shortcutting, so that we will detect any conflicting
372 * constraints the user wrote (like a different DEFAULT).
374 * Create an expression tree representing the function call
375 * nextval('sequencename'). We cannot reduce the raw tree to cooked
376 * form until after the sequence is created, but there's no need to do
379 qstring = quote_qualified_identifier(snamespace, sname);
380 snamenode = makeNode(A_Const);
381 snamenode->val.type = T_String;
382 snamenode->val.val.str = qstring;
383 snamenode->location = -1;
384 castnode = makeNode(TypeCast);
385 castnode->typeName = SystemTypeName("regclass");
386 castnode->arg = (Node *) snamenode;
387 castnode->location = -1;
388 funccallnode = makeNode(FuncCall);
389 funccallnode->funcname = SystemFuncName("nextval");
390 funccallnode->args = list_make1(castnode);
391 funccallnode->agg_star = false;
392 funccallnode->agg_distinct = false;
393 funccallnode->func_variadic = false;
394 funccallnode->over = NULL;
395 funccallnode->location = -1;
397 constraint = makeNode(Constraint);
398 constraint->contype = CONSTR_DEFAULT;
399 constraint->location = -1;
400 constraint->raw_expr = (Node *) funccallnode;
401 constraint->cooked_expr = NULL;
402 column->constraints = lappend(column->constraints, constraint);
404 constraint = makeNode(Constraint);
405 constraint->contype = CONSTR_NOTNULL;
406 constraint->location = -1;
407 column->constraints = lappend(column->constraints, constraint);
410 /* Process column constraints, if any... */
411 transformConstraintAttrs(pstate, column->constraints);
413 saw_nullable = false;
416 foreach(clist, column->constraints)
418 constraint = lfirst(clist);
419 Assert(IsA(constraint, Constraint));
421 switch (constraint->contype)
424 if (saw_nullable && column->is_not_null)
426 (errcode(ERRCODE_SYNTAX_ERROR),
427 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
428 column->colname, cxt->relation->relname),
429 parser_errposition(pstate,
430 constraint->location)));
431 column->is_not_null = FALSE;
436 if (saw_nullable && !column->is_not_null)
438 (errcode(ERRCODE_SYNTAX_ERROR),
439 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
440 column->colname, cxt->relation->relname),
441 parser_errposition(pstate,
442 constraint->location)));
443 column->is_not_null = TRUE;
450 (errcode(ERRCODE_SYNTAX_ERROR),
451 errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
452 column->colname, cxt->relation->relname),
453 parser_errposition(pstate,
454 constraint->location)));
455 column->raw_default = constraint->raw_expr;
456 Assert(constraint->cooked_expr == NULL);
461 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
466 if (constraint->keys == NIL)
467 constraint->keys = list_make1(makeString(column->colname));
468 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
471 case CONSTR_EXCLUSION:
472 /* grammar does not allow EXCLUDE as a column constraint */
473 elog(ERROR, "column exclusion constraints are not supported");
478 * Fill in the current attribute's name and throw it into the
479 * list of FK constraints to be processed later.
481 constraint->fk_attrs = list_make1(makeString(column->colname));
482 cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
485 case CONSTR_ATTR_DEFERRABLE:
486 case CONSTR_ATTR_NOT_DEFERRABLE:
487 case CONSTR_ATTR_DEFERRED:
488 case CONSTR_ATTR_IMMEDIATE:
489 /* transformConstraintAttrs took care of these */
493 elog(ERROR, "unrecognized constraint type: %d",
494 constraint->contype);
501 * transformTableConstraint
502 * transform a Constraint node within CREATE TABLE or ALTER TABLE
505 transformTableConstraint(ParseState *pstate, CreateStmtContext *cxt,
506 Constraint *constraint)
508 switch (constraint->contype)
512 case CONSTR_EXCLUSION:
513 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
517 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
521 cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
527 case CONSTR_ATTR_DEFERRABLE:
528 case CONSTR_ATTR_NOT_DEFERRABLE:
529 case CONSTR_ATTR_DEFERRED:
530 case CONSTR_ATTR_IMMEDIATE:
531 elog(ERROR, "invalid context for constraint type %d",
532 constraint->contype);
536 elog(ERROR, "unrecognized constraint type: %d",
537 constraint->contype);
543 * transformInhRelation
545 * Change the LIKE <subtable> portion of a CREATE TABLE statement into
546 * column definitions which recreate the user defined column portions of
550 transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
551 InhRelation *inhRelation)
553 AttrNumber parent_attno;
560 relation = parserOpenTable(pstate, inhRelation->relation, AccessShareLock);
562 if (relation->rd_rel->relkind != RELKIND_RELATION)
564 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
565 errmsg("inherited relation \"%s\" is not a table",
566 inhRelation->relation->relname)));
569 * Check for SELECT privilages
571 aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
573 if (aclresult != ACLCHECK_OK)
574 aclcheck_error(aclresult, ACL_KIND_CLASS,
575 RelationGetRelationName(relation));
577 tupleDesc = RelationGetDescr(relation);
578 constr = tupleDesc->constr;
581 * Insert the copied attributes into the cxt for the new table definition.
583 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
586 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
587 char *attributeName = NameStr(attribute->attname);
591 * Ignore dropped columns in the parent.
593 if (attribute->attisdropped)
597 * Create a new column, which is marked as NOT inherited.
599 * For constraints, ONLY the NOT NULL constraint is inherited by the
600 * new column definition per SQL99.
602 def = makeNode(ColumnDef);
603 def->colname = pstrdup(attributeName);
604 def->typeName = makeTypeNameFromOid(attribute->atttypid,
605 attribute->atttypmod);
607 def->is_local = true;
608 def->is_not_null = attribute->attnotnull;
609 def->raw_default = NULL;
610 def->cooked_default = NULL;
611 def->constraints = NIL;
616 cxt->columns = lappend(cxt->columns, def);
619 * Copy default, if present and the default has been requested
621 if (attribute->atthasdef &&
622 (inhRelation->options & CREATE_TABLE_LIKE_DEFAULTS))
624 Node *this_default = NULL;
625 AttrDefault *attrdef;
628 /* Find default in constraint structure */
629 Assert(constr != NULL);
630 attrdef = constr->defval;
631 for (i = 0; i < constr->num_defval; i++)
633 if (attrdef[i].adnum == parent_attno)
635 this_default = stringToNode(attrdef[i].adbin);
639 Assert(this_default != NULL);
642 * If default expr could contain any vars, we'd need to fix 'em,
643 * but it can't; so default is ready to apply to child.
646 def->cooked_default = this_default;
649 /* Likewise, copy storage if requested */
650 if (inhRelation->options & CREATE_TABLE_LIKE_STORAGE)
651 def->storage = attribute->attstorage;
655 /* Likewise, copy comment if requested */
656 if ((inhRelation->options & CREATE_TABLE_LIKE_COMMENTS) &&
657 (comment = GetComment(attribute->attrelid,
659 attribute->attnum)) != NULL)
661 CommentStmt *stmt = makeNode(CommentStmt);
663 stmt->objtype = OBJECT_COLUMN;
664 stmt->objname = list_make3(makeString(cxt->relation->schemaname),
665 makeString(cxt->relation->relname),
666 makeString(def->colname));
668 stmt->comment = comment;
670 cxt->alist = lappend(cxt->alist, stmt);
675 * Copy CHECK constraints if requested, being careful to adjust attribute
678 if ((inhRelation->options & CREATE_TABLE_LIKE_CONSTRAINTS) &&
681 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
684 for (ccnum = 0; ccnum < tupleDesc->constr->num_check; ccnum++)
686 char *ccname = tupleDesc->constr->check[ccnum].ccname;
687 char *ccbin = tupleDesc->constr->check[ccnum].ccbin;
688 Node *ccbin_node = stringToNode(ccbin);
689 Constraint *n = makeNode(Constraint);
691 change_varattnos_of_a_node(ccbin_node, attmap);
693 n->contype = CONSTR_CHECK;
695 n->conname = pstrdup(ccname);
697 n->cooked_expr = nodeToString(ccbin_node);
698 cxt->ckconstraints = lappend(cxt->ckconstraints, n);
700 /* Copy comment on constraint */
701 if ((inhRelation->options & CREATE_TABLE_LIKE_COMMENTS) &&
702 (comment = GetComment(GetConstraintByName(RelationGetRelid(relation),
704 ConstraintRelationId,
707 CommentStmt *stmt = makeNode(CommentStmt);
709 stmt->objtype = OBJECT_CONSTRAINT;
710 stmt->objname = list_make3(makeString(cxt->relation->schemaname),
711 makeString(cxt->relation->relname),
712 makeString(n->conname));
714 stmt->comment = comment;
716 cxt->alist = lappend(cxt->alist, stmt);
722 * Likewise, copy indexes if requested
724 if ((inhRelation->options & CREATE_TABLE_LIKE_INDEXES) &&
725 relation->rd_rel->relhasindex)
727 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
728 List *parent_indexes;
731 parent_indexes = RelationGetIndexList(relation);
733 foreach(l, parent_indexes)
735 Oid parent_index_oid = lfirst_oid(l);
736 Relation parent_index;
737 IndexStmt *index_stmt;
739 parent_index = index_open(parent_index_oid, AccessShareLock);
741 /* Build CREATE INDEX statement to recreate the parent_index */
742 index_stmt = generateClonedIndexStmt(cxt, parent_index, attmap);
744 /* Copy comment on index */
745 if (inhRelation->options & CREATE_TABLE_LIKE_COMMENTS)
751 comment = GetComment(parent_index_oid, RelationRelationId, 0);
755 /* Assign name for index because CommentStmt requires name. */
756 if (index_stmt->idxname == NULL)
757 index_stmt->idxname = chooseIndexName(cxt->relation, index_stmt);
759 stmt = makeNode(CommentStmt);
760 stmt->objtype = OBJECT_INDEX;
761 stmt->objname = list_make2(makeString(cxt->relation->schemaname),
762 makeString(index_stmt->idxname));
764 stmt->comment = comment;
766 cxt->alist = lappend(cxt->alist, stmt);
769 /* Copy comment on index's columns */
771 foreach(lc, index_stmt->indexParams)
776 comment = GetComment(parent_index_oid, RelationRelationId, i);
780 /* Assign name for index because CommentStmt requires name. */
781 if (index_stmt->idxname == NULL)
782 index_stmt->idxname = chooseIndexName(cxt->relation, index_stmt);
784 attname = ((IndexElem *) lfirst(lc))->name;
786 /* expression index has a dummy column name */
789 attname = palloc(NAMEDATALEN);
790 sprintf(attname, "pg_expression_%d", i);
793 stmt = makeNode(CommentStmt);
794 stmt->objtype = OBJECT_COLUMN;
795 stmt->objname = list_make3(
796 makeString(cxt->relation->schemaname),
797 makeString(index_stmt->idxname),
798 makeString(attname));
800 stmt->comment = comment;
802 cxt->alist = lappend(cxt->alist, stmt);
806 /* Save it in the inh_indexes list for the time being */
807 cxt->inh_indexes = lappend(cxt->inh_indexes, index_stmt);
809 index_close(parent_index, AccessShareLock);
814 * Close the parent rel, but keep our AccessShareLock on it until xact
815 * commit. That will prevent someone else from deleting or ALTERing the
816 * parent before the child is committed.
818 heap_close(relation, NoLock);
824 * Set name for unnamed index. See also the same logic in DefineIndex.
827 chooseIndexName(const RangeVar *relation, IndexStmt *index_stmt)
831 namespaceId = RangeVarGetCreationNamespace(relation);
832 if (index_stmt->primary)
834 /* no need for column list with pkey */
835 return ChooseRelationName(relation->relname, NULL,
836 "pkey", namespaceId);
838 else if (index_stmt->excludeOpNames != NIL)
840 IndexElem *iparam = (IndexElem *) linitial(index_stmt->indexParams);
842 return ChooseRelationName(relation->relname, iparam->name,
843 "exclusion", namespaceId);
847 IndexElem *iparam = (IndexElem *) linitial(index_stmt->indexParams);
849 return ChooseRelationName(relation->relname, iparam->name,
855 * Generate an IndexStmt node using information from an already existing index
856 * "source_idx". Attribute numbers should be adjusted according to attmap.
859 generateClonedIndexStmt(CreateStmtContext *cxt, Relation source_idx,
862 Oid source_relid = RelationGetRelid(source_idx);
865 Form_pg_class idxrelrec;
866 Form_pg_index idxrec;
871 ListCell *indexpr_item;
879 * Fetch pg_class tuple of source index. We can't use the copy in the
880 * relcache entry because it doesn't include optional fields.
882 ht_idxrel = SearchSysCache(RELOID,
883 ObjectIdGetDatum(source_relid),
885 if (!HeapTupleIsValid(ht_idxrel))
886 elog(ERROR, "cache lookup failed for relation %u", source_relid);
887 idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
889 /* Fetch pg_index tuple for source index from relcache entry */
890 ht_idx = source_idx->rd_indextuple;
891 idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
892 indrelid = idxrec->indrelid;
894 /* Fetch pg_am tuple for source index from relcache entry */
895 amrec = source_idx->rd_am;
897 /* Extract indclass from the pg_index tuple */
898 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
899 Anum_pg_index_indclass, &isnull);
901 indclass = (oidvector *) DatumGetPointer(datum);
903 /* Begin building the IndexStmt */
904 index = makeNode(IndexStmt);
905 index->relation = cxt->relation;
906 index->accessMethod = pstrdup(NameStr(amrec->amname));
907 if (OidIsValid(idxrelrec->reltablespace))
908 index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
910 index->tableSpace = NULL;
911 index->unique = idxrec->indisunique;
912 index->primary = idxrec->indisprimary;
913 index->concurrent = false;
916 * We don't try to preserve the name of the source index; instead, just
917 * let DefineIndex() choose a reasonable name.
919 index->idxname = NULL;
922 * If the index is marked PRIMARY or has an exclusion condition, it's
923 * certainly from a constraint; else, if it's not marked UNIQUE, it
924 * certainly isn't. If it is or might be from a constraint, we have to
925 * fetch the pg_constraint record.
927 if (index->primary || index->unique || idxrelrec->relhasexclusion)
929 Oid constraintId = get_index_constraint(source_relid);
931 if (OidIsValid(constraintId))
934 Form_pg_constraint conrec;
936 ht_constr = SearchSysCache(CONSTROID,
937 ObjectIdGetDatum(constraintId),
939 if (!HeapTupleIsValid(ht_constr))
940 elog(ERROR, "cache lookup failed for constraint %u",
942 conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
944 index->isconstraint = true;
945 index->deferrable = conrec->condeferrable;
946 index->initdeferred = conrec->condeferred;
948 /* If it's an exclusion constraint, we need the operator names */
949 if (idxrelrec->relhasexclusion)
955 Assert(conrec->contype == CONSTRAINT_EXCLUSION);
956 /* Extract operator OIDs from the pg_constraint tuple */
957 datum = SysCacheGetAttr(CONSTROID, ht_constr,
958 Anum_pg_constraint_conexclop,
961 elog(ERROR, "null conexclop for constraint %u",
964 deconstruct_array(DatumGetArrayTypeP(datum),
965 OIDOID, sizeof(Oid), true, 'i',
966 &elems, NULL, &nElems);
968 for (i = 0; i < nElems; i++)
970 Oid operid = DatumGetObjectId(elems[i]);
972 Form_pg_operator operform;
977 opertup = SearchSysCache(OPEROID,
978 ObjectIdGetDatum(operid),
980 if (!HeapTupleIsValid(opertup))
981 elog(ERROR, "cache lookup failed for operator %u",
983 operform = (Form_pg_operator) GETSTRUCT(opertup);
984 oprname = pstrdup(NameStr(operform->oprname));
985 /* For simplicity we always schema-qualify the op name */
986 nspname = get_namespace_name(operform->oprnamespace);
987 namelist = list_make2(makeString(nspname),
988 makeString(oprname));
989 index->excludeOpNames = lappend(index->excludeOpNames,
991 ReleaseSysCache(opertup);
995 ReleaseSysCache(ht_constr);
998 index->isconstraint = false;
1001 index->isconstraint = false;
1003 /* Get the index expressions, if any */
1004 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1005 Anum_pg_index_indexprs, &isnull);
1010 exprsString = TextDatumGetCString(datum);
1011 indexprs = (List *) stringToNode(exprsString);
1016 /* Build the list of IndexElem */
1017 index->indexParams = NIL;
1019 indexpr_item = list_head(indexprs);
1020 for (keyno = 0; keyno < idxrec->indnatts; keyno++)
1023 AttrNumber attnum = idxrec->indkey.values[keyno];
1024 int16 opt = source_idx->rd_indoption[keyno];
1026 iparam = makeNode(IndexElem);
1028 if (AttributeNumberIsValid(attnum))
1030 /* Simple index column */
1033 attname = get_relid_attribute_name(indrelid, attnum);
1034 keycoltype = get_atttype(indrelid, attnum);
1036 iparam->name = attname;
1037 iparam->expr = NULL;
1041 /* Expressional index */
1044 if (indexpr_item == NULL)
1045 elog(ERROR, "too few entries in indexprs list");
1046 indexkey = (Node *) lfirst(indexpr_item);
1047 indexpr_item = lnext(indexpr_item);
1049 /* OK to modify indexkey since we are working on a private copy */
1050 change_varattnos_of_a_node(indexkey, attmap);
1052 iparam->name = NULL;
1053 iparam->expr = indexkey;
1055 keycoltype = exprType(indexkey);
1058 /* Add the operator class name, if non-default */
1059 iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1061 iparam->ordering = SORTBY_DEFAULT;
1062 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1064 /* Adjust options if necessary */
1065 if (amrec->amcanorder)
1068 * If it supports sort ordering, copy DESC and NULLS opts. Don't
1069 * set non-default settings unnecessarily, though, so as to
1070 * improve the chance of recognizing equivalence to constraint
1073 if (opt & INDOPTION_DESC)
1075 iparam->ordering = SORTBY_DESC;
1076 if ((opt & INDOPTION_NULLS_FIRST) == 0)
1077 iparam->nulls_ordering = SORTBY_NULLS_LAST;
1081 if (opt & INDOPTION_NULLS_FIRST)
1082 iparam->nulls_ordering = SORTBY_NULLS_FIRST;
1086 index->indexParams = lappend(index->indexParams, iparam);
1089 /* Copy reloptions if any */
1090 datum = SysCacheGetAttr(RELOID, ht_idxrel,
1091 Anum_pg_class_reloptions, &isnull);
1093 index->options = untransformRelOptions(datum);
1095 /* If it's a partial index, decompile and append the predicate */
1096 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1097 Anum_pg_index_indpred, &isnull);
1102 /* Convert text string to node tree */
1103 pred_str = TextDatumGetCString(datum);
1104 index->whereClause = (Node *) stringToNode(pred_str);
1105 /* Adjust attribute numbers */
1106 change_varattnos_of_a_node(index->whereClause, attmap);
1110 ReleaseSysCache(ht_idxrel);
1116 * get_opclass - fetch name of an index operator class
1118 * If the opclass is the default for the given actual_datatype, then
1119 * the return value is NIL.
1122 get_opclass(Oid opclass, Oid actual_datatype)
1125 Form_pg_opclass opc_rec;
1128 ht_opc = SearchSysCache(CLAOID,
1129 ObjectIdGetDatum(opclass),
1131 if (!HeapTupleIsValid(ht_opc))
1132 elog(ERROR, "cache lookup failed for opclass %u", opclass);
1133 opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
1135 if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
1137 /* For simplicity, we always schema-qualify the name */
1138 char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
1139 char *opc_name = pstrdup(NameStr(opc_rec->opcname));
1141 result = list_make2(makeString(nsp_name), makeString(opc_name));
1144 ReleaseSysCache(ht_opc);
1150 * transformIndexConstraints
1151 * Handle UNIQUE, PRIMARY KEY, EXCLUDE constraints, which create indexes.
1152 * We also merge in any index definitions arising from
1153 * LIKE ... INCLUDING INDEXES.
1156 transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
1159 List *indexlist = NIL;
1163 * Run through the constraints that need to generate an index. For PRIMARY
1164 * KEY, mark each column as NOT NULL and create an index. For UNIQUE or
1165 * EXCLUDE, create an index as for PRIMARY KEY, but do not insist on NOT
1168 foreach(lc, cxt->ixconstraints)
1170 Constraint *constraint = (Constraint *) lfirst(lc);
1172 Assert(IsA(constraint, Constraint));
1173 Assert(constraint->contype == CONSTR_PRIMARY ||
1174 constraint->contype == CONSTR_UNIQUE ||
1175 constraint->contype == CONSTR_EXCLUSION);
1177 index = transformIndexConstraint(constraint, cxt);
1179 indexlist = lappend(indexlist, index);
1182 /* Add in any indexes defined by LIKE ... INCLUDING INDEXES */
1183 foreach(lc, cxt->inh_indexes)
1185 index = (IndexStmt *) lfirst(lc);
1189 if (cxt->pkey != NULL)
1191 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1192 errmsg("multiple primary keys for table \"%s\" are not allowed",
1193 cxt->relation->relname)));
1197 indexlist = lappend(indexlist, index);
1201 * Scan the index list and remove any redundant index specifications. This
1202 * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
1203 * strict reading of SQL92 would suggest raising an error instead, but
1204 * that strikes me as too anal-retentive. - tgl 2001-02-14
1206 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1207 * pre-existing indexes, too.
1209 Assert(cxt->alist == NIL);
1210 if (cxt->pkey != NULL)
1212 /* Make sure we keep the PKEY index in preference to others... */
1213 cxt->alist = list_make1(cxt->pkey);
1216 foreach(lc, indexlist)
1223 /* if it's pkey, it's already in cxt->alist */
1224 if (index == cxt->pkey)
1227 foreach(k, cxt->alist)
1229 IndexStmt *priorindex = lfirst(k);
1231 if (equal(index->indexParams, priorindex->indexParams) &&
1232 equal(index->whereClause, priorindex->whereClause) &&
1233 equal(index->excludeOpNames, priorindex->excludeOpNames) &&
1234 strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
1235 index->deferrable == priorindex->deferrable &&
1236 index->initdeferred == priorindex->initdeferred)
1238 priorindex->unique |= index->unique;
1241 * If the prior index is as yet unnamed, and this one is
1242 * named, then transfer the name to the prior index. This
1243 * ensures that if we have named and unnamed constraints,
1244 * we'll use (at least one of) the names for the index.
1246 if (priorindex->idxname == NULL)
1247 priorindex->idxname = index->idxname;
1254 cxt->alist = lappend(cxt->alist, index);
1259 * transformIndexConstraint
1260 * Transform one UNIQUE, PRIMARY KEY, or EXCLUDE constraint for
1261 * transformIndexConstraints.
1264 transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
1269 index = makeNode(IndexStmt);
1271 index->unique = (constraint->contype != CONSTR_EXCLUSION);
1272 index->primary = (constraint->contype == CONSTR_PRIMARY);
1275 if (cxt->pkey != NULL)
1277 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1278 errmsg("multiple primary keys for table \"%s\" are not allowed",
1279 cxt->relation->relname)));
1283 * In ALTER TABLE case, a primary index might already exist, but
1284 * DefineIndex will check for it.
1287 index->isconstraint = true;
1288 index->deferrable = constraint->deferrable;
1289 index->initdeferred = constraint->initdeferred;
1291 if (constraint->conname != NULL)
1292 index->idxname = pstrdup(constraint->conname);
1294 index->idxname = NULL; /* DefineIndex will choose name */
1296 index->relation = cxt->relation;
1297 index->accessMethod = constraint->access_method ? constraint->access_method : DEFAULT_INDEX_TYPE;
1298 index->options = constraint->options;
1299 index->tableSpace = constraint->indexspace;
1300 index->whereClause = constraint->where_clause;
1301 index->indexParams = NIL;
1302 index->excludeOpNames = NIL;
1303 index->concurrent = false;
1306 * If it's an EXCLUDE constraint, the grammar returns a list of pairs
1307 * of IndexElems and operator names. We have to break that apart into
1310 if (constraint->contype == CONSTR_EXCLUSION)
1312 foreach(lc, constraint->exclusions)
1314 List *pair = (List *) lfirst(lc);
1318 Assert(list_length(pair) == 2);
1319 elem = (IndexElem *) linitial(pair);
1320 Assert(IsA(elem, IndexElem));
1321 opname = (List *) lsecond(pair);
1322 Assert(IsA(opname, List));
1324 index->indexParams = lappend(index->indexParams, elem);
1325 index->excludeOpNames = lappend(index->excludeOpNames, opname);
1332 * For UNIQUE and PRIMARY KEY, we just have a list of column names.
1334 * Make sure referenced keys exist. If we are making a PRIMARY KEY index,
1335 * also make sure they are NOT NULL, if possible. (Although we could leave
1336 * it to DefineIndex to mark the columns NOT NULL, it's more efficient to
1337 * get it right the first time.)
1339 foreach(lc, constraint->keys)
1341 char *key = strVal(lfirst(lc));
1343 ColumnDef *column = NULL;
1347 foreach(columns, cxt->columns)
1349 column = (ColumnDef *) lfirst(columns);
1350 Assert(IsA(column, ColumnDef));
1351 if (strcmp(column->colname, key) == 0)
1359 /* found column in the new table; force it to be NOT NULL */
1360 if (constraint->contype == CONSTR_PRIMARY)
1361 column->is_not_null = TRUE;
1363 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1366 * column will be a system column in the new table, so accept it.
1367 * System columns can't ever be null, so no need to worry about
1368 * PRIMARY/NOT NULL constraint.
1372 else if (cxt->inhRelations)
1374 /* try inherited tables */
1377 foreach(inher, cxt->inhRelations)
1379 RangeVar *inh = (RangeVar *) lfirst(inher);
1383 Assert(IsA(inh, RangeVar));
1384 rel = heap_openrv(inh, AccessShareLock);
1385 if (rel->rd_rel->relkind != RELKIND_RELATION)
1387 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1388 errmsg("inherited relation \"%s\" is not a table",
1390 for (count = 0; count < rel->rd_att->natts; count++)
1392 Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1393 char *inhname = NameStr(inhattr->attname);
1395 if (inhattr->attisdropped)
1397 if (strcmp(key, inhname) == 0)
1402 * We currently have no easy way to force an inherited
1403 * column to be NOT NULL at creation, if its parent
1404 * wasn't so already. We leave it to DefineIndex to
1405 * fix things up in this case.
1410 heap_close(rel, NoLock);
1417 * In the ALTER TABLE case, don't complain about index keys not
1418 * created in the command; they may well exist already. DefineIndex
1419 * will complain about them if not, and will also take care of marking
1422 if (!found && !cxt->isalter)
1424 (errcode(ERRCODE_UNDEFINED_COLUMN),
1425 errmsg("column \"%s\" named in key does not exist",
1428 /* Check for PRIMARY KEY(foo, foo) */
1429 foreach(columns, index->indexParams)
1431 iparam = (IndexElem *) lfirst(columns);
1432 if (iparam->name && strcmp(key, iparam->name) == 0)
1436 (errcode(ERRCODE_DUPLICATE_COLUMN),
1437 errmsg("column \"%s\" appears twice in primary key constraint",
1441 (errcode(ERRCODE_DUPLICATE_COLUMN),
1442 errmsg("column \"%s\" appears twice in unique constraint",
1447 /* OK, add it to the index definition */
1448 iparam = makeNode(IndexElem);
1449 iparam->name = pstrdup(key);
1450 iparam->expr = NULL;
1451 iparam->opclass = NIL;
1452 iparam->ordering = SORTBY_DEFAULT;
1453 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1454 index->indexParams = lappend(index->indexParams, iparam);
1461 * transformFKConstraints
1462 * handle FOREIGN KEY constraints
1465 transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
1466 bool skipValidation, bool isAddConstraint)
1470 if (cxt->fkconstraints == NIL)
1474 * If CREATE TABLE or adding a column with NULL default, we can safely
1475 * skip validation of the constraint.
1479 foreach(fkclist, cxt->fkconstraints)
1481 Constraint *constraint = (Constraint *) lfirst(fkclist);
1483 constraint->skip_validation = true;
1488 * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
1489 * CONSTRAINT command to execute after the basic command is complete. (If
1490 * called from ADD CONSTRAINT, that routine will add the FK constraints to
1491 * its own subcommand list.)
1493 * Note: the ADD CONSTRAINT command must also execute after any index
1494 * creation commands. Thus, this should run after
1495 * transformIndexConstraints, so that the CREATE INDEX commands are
1496 * already in cxt->alist.
1498 if (!isAddConstraint)
1500 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1502 alterstmt->relation = cxt->relation;
1503 alterstmt->cmds = NIL;
1504 alterstmt->relkind = OBJECT_TABLE;
1506 foreach(fkclist, cxt->fkconstraints)
1508 Constraint *constraint = (Constraint *) lfirst(fkclist);
1509 AlterTableCmd *altercmd = makeNode(AlterTableCmd);
1511 altercmd->subtype = AT_ProcessedConstraint;
1512 altercmd->name = NULL;
1513 altercmd->def = (Node *) constraint;
1514 alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
1517 cxt->alist = lappend(cxt->alist, alterstmt);
1522 * transformIndexStmt - parse analysis for CREATE INDEX
1524 * Note: this is a no-op for an index not using either index expressions or
1525 * a predicate expression. There are several code paths that create indexes
1526 * without bothering to call this, because they know they don't have any
1527 * such expressions to deal with.
1530 transformIndexStmt(IndexStmt *stmt, const char *queryString)
1538 * We must not scribble on the passed-in IndexStmt, so copy it. (This is
1539 * overkill, but easy.)
1541 stmt = (IndexStmt *) copyObject(stmt);
1544 * Open the parent table with appropriate locking. We must do this
1545 * because addRangeTableEntry() would acquire only AccessShareLock,
1546 * leaving DefineIndex() needing to do a lock upgrade with consequent risk
1547 * of deadlock. Make sure this stays in sync with the type of lock
1548 * DefineIndex() wants.
1550 rel = heap_openrv(stmt->relation,
1551 (stmt->concurrent ? ShareUpdateExclusiveLock : ShareLock));
1554 pstate = make_parsestate(NULL);
1555 pstate->p_sourcetext = queryString;
1558 * Put the parent table into the rtable so that the expressions can refer
1559 * to its fields without qualification.
1561 rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1563 /* no to join list, yes to namespaces */
1564 addRTEtoQuery(pstate, rte, false, true, true);
1566 /* take care of the where clause */
1567 if (stmt->whereClause)
1568 stmt->whereClause = transformWhereClause(pstate,
1572 /* take care of any index expressions */
1573 foreach(l, stmt->indexParams)
1575 IndexElem *ielem = (IndexElem *) lfirst(l);
1579 ielem->expr = transformExpr(pstate, ielem->expr);
1582 * We check only that the result type is legitimate; this is for
1583 * consistency with what transformWhereClause() checks for the
1584 * predicate. DefineIndex() will make more checks.
1586 if (expression_returns_set(ielem->expr))
1588 (errcode(ERRCODE_DATATYPE_MISMATCH),
1589 errmsg("index expression cannot return a set")));
1594 * Check that only the base rel is mentioned.
1596 if (list_length(pstate->p_rtable) != 1)
1598 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1599 errmsg("index expressions and predicates can refer only to the table being indexed")));
1601 free_parsestate(pstate);
1603 /* Close relation, but keep the lock */
1604 heap_close(rel, NoLock);
1611 * transformRuleStmt -
1612 * transform a CREATE RULE Statement. The action is a list of parse
1613 * trees which is transformed into a list of query trees, and we also
1614 * transform the WHERE clause if any.
1616 * actions and whereClause are output parameters that receive the
1617 * transformed results.
1619 * Note that we must not scribble on the passed-in RuleStmt, so we do
1620 * copyObject() on the actions and WHERE clause.
1623 transformRuleStmt(RuleStmt *stmt, const char *queryString,
1624 List **actions, Node **whereClause)
1628 RangeTblEntry *oldrte;
1629 RangeTblEntry *newrte;
1632 * To avoid deadlock, make sure the first thing we do is grab
1633 * AccessExclusiveLock on the target relation. This will be needed by
1634 * DefineQueryRewrite(), and we don't want to grab a lesser lock
1637 rel = heap_openrv(stmt->relation, AccessExclusiveLock);
1640 pstate = make_parsestate(NULL);
1641 pstate->p_sourcetext = queryString;
1644 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
1645 * Set up their RTEs in the main pstate for use in parsing the rule
1648 oldrte = addRangeTableEntryForRelation(pstate, rel,
1649 makeAlias("old", NIL),
1651 newrte = addRangeTableEntryForRelation(pstate, rel,
1652 makeAlias("new", NIL),
1654 /* Must override addRangeTableEntry's default access-check flags */
1655 oldrte->requiredPerms = 0;
1656 newrte->requiredPerms = 0;
1659 * They must be in the namespace too for lookup purposes, but only add the
1660 * one(s) that are relevant for the current kind of rule. In an UPDATE
1661 * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
1662 * there's no need to be so picky for INSERT & DELETE. We do not add them
1665 switch (stmt->event)
1668 addRTEtoQuery(pstate, oldrte, false, true, true);
1671 addRTEtoQuery(pstate, oldrte, false, true, true);
1672 addRTEtoQuery(pstate, newrte, false, true, true);
1675 addRTEtoQuery(pstate, newrte, false, true, true);
1678 addRTEtoQuery(pstate, oldrte, false, true, true);
1681 elog(ERROR, "unrecognized event type: %d",
1686 /* take care of the where clause */
1687 *whereClause = transformWhereClause(pstate,
1688 (Node *) copyObject(stmt->whereClause),
1691 if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
1693 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1694 errmsg("rule WHERE condition cannot contain references to other relations")));
1696 /* aggregates not allowed (but subselects are okay) */
1697 if (pstate->p_hasAggs)
1699 (errcode(ERRCODE_GROUPING_ERROR),
1700 errmsg("cannot use aggregate function in rule WHERE condition")));
1701 if (pstate->p_hasWindowFuncs)
1703 (errcode(ERRCODE_WINDOWING_ERROR),
1704 errmsg("cannot use window function in rule WHERE condition")));
1707 * 'instead nothing' rules with a qualification need a query rangetable so
1708 * the rewrite handler can add the negated rule qualification to the
1709 * original query. We create a query with the new command type CMD_NOTHING
1710 * here that is treated specially by the rewrite system.
1712 if (stmt->actions == NIL)
1714 Query *nothing_qry = makeNode(Query);
1716 nothing_qry->commandType = CMD_NOTHING;
1717 nothing_qry->rtable = pstate->p_rtable;
1718 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
1720 *actions = list_make1(nothing_qry);
1725 List *newactions = NIL;
1728 * transform each statement, like parse_sub_analyze()
1730 foreach(l, stmt->actions)
1732 Node *action = (Node *) lfirst(l);
1733 ParseState *sub_pstate = make_parsestate(NULL);
1740 * Since outer ParseState isn't parent of inner, have to pass down
1741 * the query text by hand.
1743 sub_pstate->p_sourcetext = queryString;
1746 * Set up OLD/NEW in the rtable for this statement. The entries
1747 * are added only to relnamespace, not varnamespace, because we
1748 * don't want them to be referred to by unqualified field names
1749 * nor "*" in the rule actions. We decide later whether to put
1750 * them in the joinlist.
1752 oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
1753 makeAlias("old", NIL),
1755 newrte = addRangeTableEntryForRelation(sub_pstate, rel,
1756 makeAlias("new", NIL),
1758 oldrte->requiredPerms = 0;
1759 newrte->requiredPerms = 0;
1760 addRTEtoQuery(sub_pstate, oldrte, false, true, false);
1761 addRTEtoQuery(sub_pstate, newrte, false, true, false);
1763 /* Transform the rule action statement */
1764 top_subqry = transformStmt(sub_pstate,
1765 (Node *) copyObject(action));
1768 * We cannot support utility-statement actions (eg NOTIFY) with
1769 * nonempty rule WHERE conditions, because there's no way to make
1770 * the utility action execute conditionally.
1772 if (top_subqry->commandType == CMD_UTILITY &&
1773 *whereClause != NULL)
1775 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1776 errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
1779 * If the action is INSERT...SELECT, OLD/NEW have been pushed down
1780 * into the SELECT, and that's what we need to look at. (Ugly
1781 * kluge ... try to fix this when we redesign querytrees.)
1783 sub_qry = getInsertSelectQuery(top_subqry, NULL);
1786 * If the sub_qry is a setop, we cannot attach any qualifications
1787 * to it, because the planner won't notice them. This could
1788 * perhaps be relaxed someday, but for now, we may as well reject
1789 * such a rule immediately.
1791 if (sub_qry->setOperations != NULL && *whereClause != NULL)
1793 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1794 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1797 * Validate action's use of OLD/NEW, qual too
1800 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
1801 rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
1803 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
1804 rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
1806 switch (stmt->event)
1811 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1812 errmsg("ON SELECT rule cannot use OLD")));
1815 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1816 errmsg("ON SELECT rule cannot use NEW")));
1824 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1825 errmsg("ON INSERT rule cannot use OLD")));
1830 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1831 errmsg("ON DELETE rule cannot use NEW")));
1834 elog(ERROR, "unrecognized event type: %d",
1840 * For efficiency's sake, add OLD to the rule action's jointree
1841 * only if it was actually referenced in the statement or qual.
1843 * For INSERT, NEW is not really a relation (only a reference to
1844 * the to-be-inserted tuple) and should never be added to the
1847 * For UPDATE, we treat NEW as being another kind of reference to
1848 * OLD, because it represents references to *transformed* tuples
1849 * of the existing relation. It would be wrong to enter NEW
1850 * separately in the jointree, since that would cause a double
1851 * join of the updated relation. It's also wrong to fail to make
1852 * a jointree entry if only NEW and not OLD is mentioned.
1854 if (has_old || (has_new && stmt->event == CMD_UPDATE))
1857 * If sub_qry is a setop, manipulating its jointree will do no
1858 * good at all, because the jointree is dummy. (This should be
1859 * a can't-happen case because of prior tests.)
1861 if (sub_qry->setOperations != NULL)
1863 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1864 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1865 /* hack so we can use addRTEtoQuery() */
1866 sub_pstate->p_rtable = sub_qry->rtable;
1867 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
1868 addRTEtoQuery(sub_pstate, oldrte, true, false, false);
1869 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
1872 newactions = lappend(newactions, top_subqry);
1874 free_parsestate(sub_pstate);
1877 *actions = newactions;
1880 free_parsestate(pstate);
1882 /* Close relation, but keep the exclusive lock */
1883 heap_close(rel, NoLock);
1888 * transformAlterTableStmt -
1889 * parse analysis for ALTER TABLE
1891 * Returns a List of utility commands to be done in sequence. One of these
1892 * will be the transformed AlterTableStmt, but there may be additional actions
1893 * to be done before and after the actual AlterTable() call.
1896 transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString)
1900 CreateStmtContext cxt;
1905 List *newcmds = NIL;
1906 bool skipValidation = true;
1907 AlterTableCmd *newcmd;
1910 * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
1911 * is overkill, but easy.)
1913 stmt = (AlterTableStmt *) copyObject(stmt);
1916 * Acquire exclusive lock on the target relation, which will be held until
1917 * end of transaction. This ensures any decisions we make here based on
1918 * the state of the relation will still be good at execution. We must get
1919 * exclusive lock now because execution will; taking a lower grade lock
1920 * now and trying to upgrade later risks deadlock.
1922 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
1925 pstate = make_parsestate(NULL);
1926 pstate->p_sourcetext = queryString;
1928 cxt.stmtType = "ALTER TABLE";
1929 cxt.relation = stmt->relation;
1931 cxt.inhRelations = NIL;
1933 cxt.hasoids = false; /* need not be right */
1935 cxt.ckconstraints = NIL;
1936 cxt.fkconstraints = NIL;
1937 cxt.ixconstraints = NIL;
1938 cxt.inh_indexes = NIL;
1944 * The only subtypes that currently require parse transformation handling
1945 * are ADD COLUMN and ADD CONSTRAINT. These largely re-use code from
1948 foreach(lcmd, stmt->cmds)
1950 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
1952 switch (cmd->subtype)
1955 case AT_AddColumnToView:
1957 ColumnDef *def = (ColumnDef *) cmd->def;
1959 Assert(IsA(def, ColumnDef));
1960 transformColumnDefinition(pstate, &cxt, def);
1963 * If the column has a non-null default, we can't skip
1964 * validation of foreign keys.
1966 if (def->raw_default != NULL)
1967 skipValidation = false;
1970 * All constraints are processed in other ways. Remove the
1973 def->constraints = NIL;
1975 newcmds = lappend(newcmds, cmd);
1978 case AT_AddConstraint:
1981 * The original AddConstraint cmd node doesn't go to newcmds
1983 if (IsA(cmd->def, Constraint))
1985 transformTableConstraint(pstate, &cxt,
1986 (Constraint *) cmd->def);
1987 if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
1988 skipValidation = false;
1991 elog(ERROR, "unrecognized node type: %d",
1992 (int) nodeTag(cmd->def));
1995 case AT_ProcessedConstraint:
1998 * Already-transformed ADD CONSTRAINT, so just make it look
1999 * like the standard case.
2001 cmd->subtype = AT_AddConstraint;
2002 newcmds = lappend(newcmds, cmd);
2006 newcmds = lappend(newcmds, cmd);
2012 * transformIndexConstraints wants cxt.alist to contain only index
2013 * statements, so transfer anything we already have into save_alist
2016 save_alist = cxt.alist;
2019 /* Postprocess index and FK constraints */
2020 transformIndexConstraints(pstate, &cxt);
2022 transformFKConstraints(pstate, &cxt, skipValidation, true);
2025 * Push any index-creation commands into the ALTER, so that they can be
2026 * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
2027 * the IndexStmt attached to an AT_AddIndex subcommand has already been
2028 * through transformIndexStmt.
2030 foreach(l, cxt.alist)
2032 Node *idxstmt = (Node *) lfirst(l);
2034 Assert(IsA(idxstmt, IndexStmt));
2035 newcmd = makeNode(AlterTableCmd);
2036 newcmd->subtype = AT_AddIndex;
2037 newcmd->def = (Node *) transformIndexStmt((IndexStmt *) idxstmt,
2039 newcmds = lappend(newcmds, newcmd);
2043 /* Append any CHECK or FK constraints to the commands list */
2044 foreach(l, cxt.ckconstraints)
2046 newcmd = makeNode(AlterTableCmd);
2047 newcmd->subtype = AT_AddConstraint;
2048 newcmd->def = (Node *) lfirst(l);
2049 newcmds = lappend(newcmds, newcmd);
2051 foreach(l, cxt.fkconstraints)
2053 newcmd = makeNode(AlterTableCmd);
2054 newcmd->subtype = AT_AddConstraint;
2055 newcmd->def = (Node *) lfirst(l);
2056 newcmds = lappend(newcmds, newcmd);
2059 /* Close rel but keep lock */
2060 relation_close(rel, NoLock);
2065 stmt->cmds = newcmds;
2067 result = lappend(cxt.blist, stmt);
2068 result = list_concat(result, cxt.alist);
2069 result = list_concat(result, save_alist);
2076 * Preprocess a list of column constraint clauses
2077 * to attach constraint attributes to their primary constraint nodes
2078 * and detect inconsistent/misplaced constraint attributes.
2080 * NOTE: currently, attributes are only supported for FOREIGN KEY, UNIQUE,
2081 * and PRIMARY KEY constraints, but someday they ought to be supported
2082 * for other constraint types.
2085 transformConstraintAttrs(ParseState *pstate, List *constraintList)
2087 Constraint *lastprimarycon = NULL;
2088 bool saw_deferrability = false;
2089 bool saw_initially = false;
2092 #define SUPPORTS_ATTRS(node) \
2093 ((node) != NULL && \
2094 ((node)->contype == CONSTR_PRIMARY || \
2095 (node)->contype == CONSTR_UNIQUE || \
2096 (node)->contype == CONSTR_EXCLUSION || \
2097 (node)->contype == CONSTR_FOREIGN))
2099 foreach(clist, constraintList)
2101 Constraint *con = (Constraint *) lfirst(clist);
2103 if (!IsA(con, Constraint))
2104 elog(ERROR, "unrecognized node type: %d",
2105 (int) nodeTag(con));
2106 switch (con->contype)
2108 case CONSTR_ATTR_DEFERRABLE:
2109 if (!SUPPORTS_ATTRS(lastprimarycon))
2111 (errcode(ERRCODE_SYNTAX_ERROR),
2112 errmsg("misplaced DEFERRABLE clause"),
2113 parser_errposition(pstate, con->location)));
2114 if (saw_deferrability)
2116 (errcode(ERRCODE_SYNTAX_ERROR),
2117 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
2118 parser_errposition(pstate, con->location)));
2119 saw_deferrability = true;
2120 lastprimarycon->deferrable = true;
2123 case CONSTR_ATTR_NOT_DEFERRABLE:
2124 if (!SUPPORTS_ATTRS(lastprimarycon))
2126 (errcode(ERRCODE_SYNTAX_ERROR),
2127 errmsg("misplaced NOT DEFERRABLE clause"),
2128 parser_errposition(pstate, con->location)));
2129 if (saw_deferrability)
2131 (errcode(ERRCODE_SYNTAX_ERROR),
2132 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
2133 parser_errposition(pstate, con->location)));
2134 saw_deferrability = true;
2135 lastprimarycon->deferrable = false;
2136 if (saw_initially &&
2137 lastprimarycon->initdeferred)
2139 (errcode(ERRCODE_SYNTAX_ERROR),
2140 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2141 parser_errposition(pstate, con->location)));
2144 case CONSTR_ATTR_DEFERRED:
2145 if (!SUPPORTS_ATTRS(lastprimarycon))
2147 (errcode(ERRCODE_SYNTAX_ERROR),
2148 errmsg("misplaced INITIALLY DEFERRED clause"),
2149 parser_errposition(pstate, con->location)));
2152 (errcode(ERRCODE_SYNTAX_ERROR),
2153 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
2154 parser_errposition(pstate, con->location)));
2155 saw_initially = true;
2156 lastprimarycon->initdeferred = true;
2159 * If only INITIALLY DEFERRED appears, assume DEFERRABLE
2161 if (!saw_deferrability)
2162 lastprimarycon->deferrable = true;
2163 else if (!lastprimarycon->deferrable)
2165 (errcode(ERRCODE_SYNTAX_ERROR),
2166 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2167 parser_errposition(pstate, con->location)));
2170 case CONSTR_ATTR_IMMEDIATE:
2171 if (!SUPPORTS_ATTRS(lastprimarycon))
2173 (errcode(ERRCODE_SYNTAX_ERROR),
2174 errmsg("misplaced INITIALLY IMMEDIATE clause"),
2175 parser_errposition(pstate, con->location)));
2178 (errcode(ERRCODE_SYNTAX_ERROR),
2179 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
2180 parser_errposition(pstate, con->location)));
2181 saw_initially = true;
2182 lastprimarycon->initdeferred = false;
2186 /* Otherwise it's not an attribute */
2187 lastprimarycon = con;
2188 /* reset flags for new primary node */
2189 saw_deferrability = false;
2190 saw_initially = false;
2197 * Special handling of type definition for a column
2200 transformColumnType(ParseState *pstate, ColumnDef *column)
2203 * All we really need to do here is verify that the type is valid.
2205 Type ctype = typenameType(pstate, column->typeName, NULL);
2207 ReleaseSysCache(ctype);
2212 * transformCreateSchemaStmt -
2213 * analyzes the CREATE SCHEMA statement
2215 * Split the schema element list into individual commands and place
2216 * them in the result list in an order such that there are no forward
2217 * references (e.g. GRANT to a table created later in the list). Note
2218 * that the logic we use for determining forward references is
2219 * presently quite incomplete.
2221 * SQL92 also allows constraints to make forward references, so thumb through
2222 * the table columns and move forward references to a posterior alter-table
2225 * The result is a list of parse nodes that still need to be analyzed ---
2226 * but we can't analyze the later commands until we've executed the earlier
2227 * ones, because of possible inter-object references.
2229 * Note: this breaks the rules a little bit by modifying schema-name fields
2230 * within passed-in structs. However, the transformation would be the same
2231 * if done over, so it should be all right to scribble on the input to this
2235 transformCreateSchemaStmt(CreateSchemaStmt *stmt)
2237 CreateSchemaStmtContext cxt;
2241 cxt.stmtType = "CREATE SCHEMA";
2242 cxt.schemaname = stmt->schemaname;
2243 cxt.authid = stmt->authid;
2244 cxt.sequences = NIL;
2252 * Run through each schema element in the schema element list. Separate
2253 * statements by type, and do preliminary analysis.
2255 foreach(elements, stmt->schemaElts)
2257 Node *element = lfirst(elements);
2259 switch (nodeTag(element))
2261 case T_CreateSeqStmt:
2263 CreateSeqStmt *elp = (CreateSeqStmt *) element;
2265 setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
2266 cxt.sequences = lappend(cxt.sequences, element);
2272 CreateStmt *elp = (CreateStmt *) element;
2274 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2277 * XXX todo: deal with constraints
2279 cxt.tables = lappend(cxt.tables, element);
2285 ViewStmt *elp = (ViewStmt *) element;
2287 setSchemaName(cxt.schemaname, &elp->view->schemaname);
2290 * XXX todo: deal with references between views
2292 cxt.views = lappend(cxt.views, element);
2298 IndexStmt *elp = (IndexStmt *) element;
2300 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2301 cxt.indexes = lappend(cxt.indexes, element);
2305 case T_CreateTrigStmt:
2307 CreateTrigStmt *elp = (CreateTrigStmt *) element;
2309 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2310 cxt.triggers = lappend(cxt.triggers, element);
2315 cxt.grants = lappend(cxt.grants, element);
2319 elog(ERROR, "unrecognized node type: %d",
2320 (int) nodeTag(element));
2325 result = list_concat(result, cxt.sequences);
2326 result = list_concat(result, cxt.tables);
2327 result = list_concat(result, cxt.views);
2328 result = list_concat(result, cxt.indexes);
2329 result = list_concat(result, cxt.triggers);
2330 result = list_concat(result, cxt.grants);
2337 * Set or check schema name in an element of a CREATE SCHEMA command
2340 setSchemaName(char *context_schema, char **stmt_schema_name)
2342 if (*stmt_schema_name == NULL)
2343 *stmt_schema_name = context_schema;
2344 else if (strcmp(context_schema, *stmt_schema_name) != 0)
2346 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
2347 errmsg("CREATE specifies a schema (%s) "
2348 "different from the one being created (%s)",
2349 *stmt_schema_name, context_schema)));