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-2015, PostgreSQL Global Development Group
20 * Portions Copyright (c) 1994, Regents of the University of California
22 * src/backend/parser/parse_utilcmd.c
24 *-------------------------------------------------------------------------
29 #include "access/htup_details.h"
30 #include "access/reloptions.h"
31 #include "catalog/dependency.h"
32 #include "catalog/heap.h"
33 #include "catalog/index.h"
34 #include "catalog/namespace.h"
35 #include "catalog/pg_collation.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_collate.h"
50 #include "parser/parse_expr.h"
51 #include "parser/parse_relation.h"
52 #include "parser/parse_target.h"
53 #include "parser/parse_type.h"
54 #include "parser/parse_utilcmd.h"
55 #include "parser/parser.h"
56 #include "rewrite/rewriteManip.h"
57 #include "utils/acl.h"
58 #include "utils/builtins.h"
59 #include "utils/lsyscache.h"
60 #include "utils/rel.h"
61 #include "utils/syscache.h"
62 #include "utils/typcache.h"
65 /* State shared by transformCreateStmt and its subroutines */
68 ParseState *pstate; /* overall parser state */
69 const char *stmtType; /* "CREATE [FOREIGN] TABLE" or "ALTER TABLE" */
70 RangeVar *relation; /* relation to create */
71 Relation rel; /* opened/locked rel, if ALTER */
72 List *inhRelations; /* relations to inherit from */
73 bool isforeign; /* true if CREATE/ALTER FOREIGN TABLE */
74 bool isalter; /* true if altering existing table */
75 bool hasoids; /* does relation have an OID column? */
76 List *columns; /* ColumnDef items */
77 List *ckconstraints; /* CHECK constraints */
78 List *fkconstraints; /* FOREIGN KEY constraints */
79 List *ixconstraints; /* index-creating constraints */
80 List *inh_indexes; /* cloned indexes from INCLUDING INDEXES */
81 List *blist; /* "before list" of things to do before
82 * creating the table */
83 List *alist; /* "after list" of things to do after creating
85 IndexStmt *pkey; /* PRIMARY KEY index, if any */
88 /* State shared by transformCreateSchemaStmt and its subroutines */
91 const char *stmtType; /* "CREATE SCHEMA" or "ALTER SCHEMA" */
92 char *schemaname; /* name of schema */
93 char *authid; /* owner of schema */
94 List *sequences; /* CREATE SEQUENCE items */
95 List *tables; /* CREATE TABLE items */
96 List *views; /* CREATE VIEW items */
97 List *indexes; /* CREATE INDEX items */
98 List *triggers; /* CREATE TRIGGER items */
99 List *grants; /* GRANT items */
100 } CreateSchemaStmtContext;
103 static void transformColumnDefinition(CreateStmtContext *cxt,
105 static void transformTableConstraint(CreateStmtContext *cxt,
106 Constraint *constraint);
107 static void transformTableLikeClause(CreateStmtContext *cxt,
108 TableLikeClause *table_like_clause);
109 static void transformOfType(CreateStmtContext *cxt,
110 TypeName *ofTypename);
111 static IndexStmt *generateClonedIndexStmt(CreateStmtContext *cxt,
113 const AttrNumber *attmap, int attmap_length);
114 static List *get_collation(Oid collation, Oid actual_datatype);
115 static List *get_opclass(Oid opclass, Oid actual_datatype);
116 static void transformIndexConstraints(CreateStmtContext *cxt);
117 static IndexStmt *transformIndexConstraint(Constraint *constraint,
118 CreateStmtContext *cxt);
119 static void transformFKConstraints(CreateStmtContext *cxt,
121 bool isAddConstraint);
122 static void transformConstraintAttrs(CreateStmtContext *cxt,
123 List *constraintList);
124 static void transformColumnType(CreateStmtContext *cxt, ColumnDef *column);
125 static void setSchemaName(char *context_schema, char **stmt_schema_name);
129 * transformCreateStmt -
130 * parse analysis for CREATE TABLE
132 * Returns a List of utility commands to be done in sequence. One of these
133 * will be the transformed CreateStmt, but there may be additional actions
134 * to be done before and after the actual DefineRelation() call.
136 * SQL allows constraints to be scattered all over, so thumb through
137 * the columns and collect all constraints into one place.
138 * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
139 * then expand those into multiple IndexStmt blocks.
140 * - thomas 1997-12-02
143 transformCreateStmt(CreateStmt *stmt, const char *queryString)
146 CreateStmtContext cxt;
154 * We must not scribble on the passed-in CreateStmt, so copy it. (This is
155 * overkill, but easy.)
157 stmt = (CreateStmt *) copyObject(stmt);
160 * Look up the creation namespace. This also checks permissions on the
161 * target namespace, locks it against concurrent drops, checks for a
162 * preexisting relation in that namespace with the same name, and updates
163 * stmt->relation->relpersistence if the selected namespace is temporary.
166 RangeVarGetAndCheckCreationNamespace(stmt->relation, NoLock,
170 * If the relation already exists and the user specified "IF NOT EXISTS",
171 * bail out with a NOTICE.
173 if (stmt->if_not_exists && OidIsValid(existing_relid))
176 (errcode(ERRCODE_DUPLICATE_TABLE),
177 errmsg("relation \"%s\" already exists, skipping",
178 stmt->relation->relname)));
183 * If the target relation name isn't schema-qualified, make it so. This
184 * prevents some corner cases in which added-on rewritten commands might
185 * think they should apply to other relations that have the same name and
186 * are earlier in the search path. But a local temp table is effectively
187 * specified to be in pg_temp, so no need for anything extra in that case.
189 if (stmt->relation->schemaname == NULL
190 && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
191 stmt->relation->schemaname = get_namespace_name(namespaceid);
193 /* Set up pstate and CreateStmtContext */
194 pstate = make_parsestate(NULL);
195 pstate->p_sourcetext = queryString;
198 if (IsA(stmt, CreateForeignTableStmt))
200 cxt.stmtType = "CREATE FOREIGN TABLE";
201 cxt.isforeign = true;
205 cxt.stmtType = "CREATE TABLE";
206 cxt.isforeign = false;
208 cxt.relation = stmt->relation;
210 cxt.inhRelations = stmt->inhRelations;
213 cxt.ckconstraints = NIL;
214 cxt.fkconstraints = NIL;
215 cxt.ixconstraints = NIL;
216 cxt.inh_indexes = NIL;
220 cxt.hasoids = interpretOidsOption(stmt->options, true);
222 Assert(!stmt->ofTypename || !stmt->inhRelations); /* grammar enforces */
224 if (stmt->ofTypename)
225 transformOfType(&cxt, stmt->ofTypename);
228 * Run through each primary element in the table creation clause. Separate
229 * column defs from constraints, and do preliminary analysis.
231 foreach(elements, stmt->tableElts)
233 Node *element = lfirst(elements);
235 switch (nodeTag(element))
238 transformColumnDefinition(&cxt, (ColumnDef *) element);
242 transformTableConstraint(&cxt, (Constraint *) element);
245 case T_TableLikeClause:
246 transformTableLikeClause(&cxt, (TableLikeClause *) element);
250 elog(ERROR, "unrecognized node type: %d",
251 (int) nodeTag(element));
257 * transformIndexConstraints wants cxt.alist to contain only index
258 * statements, so transfer anything we already have into save_alist.
260 save_alist = cxt.alist;
263 Assert(stmt->constraints == NIL);
266 * Postprocess constraints that give rise to index definitions.
268 transformIndexConstraints(&cxt);
271 * Postprocess foreign-key constraints.
273 transformFKConstraints(&cxt, true, false);
278 stmt->tableElts = cxt.columns;
279 stmt->constraints = cxt.ckconstraints;
281 result = lappend(cxt.blist, stmt);
282 result = list_concat(result, cxt.alist);
283 result = list_concat(result, save_alist);
289 * transformColumnDefinition -
290 * transform a single ColumnDef within CREATE TABLE
291 * Also used in ALTER TABLE ADD COLUMN
294 transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
299 Constraint *constraint;
302 cxt->columns = lappend(cxt->columns, column);
304 /* Check for SERIAL pseudo-types */
307 && list_length(column->typeName->names) == 1
308 && !column->typeName->pct_type)
310 char *typname = strVal(linitial(column->typeName->names));
312 if (strcmp(typname, "smallserial") == 0 ||
313 strcmp(typname, "serial2") == 0)
316 column->typeName->names = NIL;
317 column->typeName->typeOid = INT2OID;
319 else if (strcmp(typname, "serial") == 0 ||
320 strcmp(typname, "serial4") == 0)
323 column->typeName->names = NIL;
324 column->typeName->typeOid = INT4OID;
326 else if (strcmp(typname, "bigserial") == 0 ||
327 strcmp(typname, "serial8") == 0)
330 column->typeName->names = NIL;
331 column->typeName->typeOid = INT8OID;
335 * We have to reject "serial[]" explicitly, because once we've set
336 * typeid, LookupTypeName won't notice arrayBounds. We don't need any
337 * special coding for serial(typmod) though.
339 if (is_serial && column->typeName->arrayBounds != NIL)
341 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
342 errmsg("array of serial is not implemented"),
343 parser_errposition(cxt->pstate,
344 column->typeName->location)));
347 /* Do necessary work on the column type declaration */
348 if (column->typeName)
349 transformColumnType(cxt, column);
351 /* Special actions for SERIAL pseudo-types */
360 FuncCall *funccallnode;
361 CreateSeqStmt *seqstmt;
362 AlterSeqStmt *altseqstmt;
366 * Determine namespace and name to use for the sequence.
368 * Although we use ChooseRelationName, it's not guaranteed that the
369 * selected sequence name won't conflict; given sufficiently long
370 * field names, two different serial columns in the same table could
371 * be assigned the same sequence name, and we'd not notice since we
372 * aren't creating the sequence quite yet. In practice this seems
373 * quite unlikely to be a problem, especially since few people would
374 * need two serial columns in one table.
377 snamespaceid = RelationGetNamespace(cxt->rel);
380 snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
381 RangeVarAdjustRelationPersistence(cxt->relation, snamespaceid);
383 snamespace = get_namespace_name(snamespaceid);
384 sname = ChooseRelationName(cxt->relation->relname,
390 (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
391 cxt->stmtType, sname,
392 cxt->relation->relname, column->colname)));
395 * Build a CREATE SEQUENCE command to create the sequence object, and
396 * add it to the list of things to be done before this CREATE/ALTER
399 seqstmt = makeNode(CreateSeqStmt);
400 seqstmt->sequence = makeRangeVar(snamespace, sname, -1);
401 seqstmt->options = NIL;
404 * If this is ALTER ADD COLUMN, make sure the sequence will be owned
405 * by the table's owner. The current user might be someone else
406 * (perhaps a superuser, or someone who's only a member of the owning
407 * role), but the SEQUENCE OWNED BY mechanisms will bleat unless table
408 * and sequence have exactly the same owning role.
411 seqstmt->ownerId = cxt->rel->rd_rel->relowner;
413 seqstmt->ownerId = InvalidOid;
415 cxt->blist = lappend(cxt->blist, seqstmt);
418 * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence
419 * as owned by this column, and add it to the list of things to be
420 * done after this CREATE/ALTER TABLE.
422 altseqstmt = makeNode(AlterSeqStmt);
423 altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
424 attnamelist = list_make3(makeString(snamespace),
425 makeString(cxt->relation->relname),
426 makeString(column->colname));
427 altseqstmt->options = list_make1(makeDefElem("owned_by",
428 (Node *) attnamelist));
430 cxt->alist = lappend(cxt->alist, altseqstmt);
433 * Create appropriate constraints for SERIAL. We do this in full,
434 * rather than shortcutting, so that we will detect any conflicting
435 * constraints the user wrote (like a different DEFAULT).
437 * Create an expression tree representing the function call
438 * nextval('sequencename'). We cannot reduce the raw tree to cooked
439 * form until after the sequence is created, but there's no need to do
442 qstring = quote_qualified_identifier(snamespace, sname);
443 snamenode = makeNode(A_Const);
444 snamenode->val.type = T_String;
445 snamenode->val.val.str = qstring;
446 snamenode->location = -1;
447 castnode = makeNode(TypeCast);
448 castnode->typeName = SystemTypeName("regclass");
449 castnode->arg = (Node *) snamenode;
450 castnode->location = -1;
451 funccallnode = makeFuncCall(SystemFuncName("nextval"),
452 list_make1(castnode),
454 constraint = makeNode(Constraint);
455 constraint->contype = CONSTR_DEFAULT;
456 constraint->location = -1;
457 constraint->raw_expr = (Node *) funccallnode;
458 constraint->cooked_expr = NULL;
459 column->constraints = lappend(column->constraints, constraint);
461 constraint = makeNode(Constraint);
462 constraint->contype = CONSTR_NOTNULL;
463 constraint->location = -1;
464 column->constraints = lappend(column->constraints, constraint);
467 /* Process column constraints, if any... */
468 transformConstraintAttrs(cxt, column->constraints);
470 saw_nullable = false;
473 foreach(clist, column->constraints)
475 constraint = lfirst(clist);
476 Assert(IsA(constraint, Constraint));
478 switch (constraint->contype)
481 if (saw_nullable && column->is_not_null)
483 (errcode(ERRCODE_SYNTAX_ERROR),
484 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
485 column->colname, cxt->relation->relname),
486 parser_errposition(cxt->pstate,
487 constraint->location)));
488 column->is_not_null = FALSE;
493 if (saw_nullable && !column->is_not_null)
495 (errcode(ERRCODE_SYNTAX_ERROR),
496 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
497 column->colname, cxt->relation->relname),
498 parser_errposition(cxt->pstate,
499 constraint->location)));
500 column->is_not_null = TRUE;
507 (errcode(ERRCODE_SYNTAX_ERROR),
508 errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
509 column->colname, cxt->relation->relname),
510 parser_errposition(cxt->pstate,
511 constraint->location)));
512 column->raw_default = constraint->raw_expr;
513 Assert(constraint->cooked_expr == NULL);
518 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
524 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
525 errmsg("primary key constraints are not supported on foreign tables"),
526 parser_errposition(cxt->pstate,
527 constraint->location)));
533 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
534 errmsg("unique constraints are not supported on foreign tables"),
535 parser_errposition(cxt->pstate,
536 constraint->location)));
537 if (constraint->keys == NIL)
538 constraint->keys = list_make1(makeString(column->colname));
539 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
542 case CONSTR_EXCLUSION:
543 /* grammar does not allow EXCLUDE as a column constraint */
544 elog(ERROR, "column exclusion constraints are not supported");
550 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
551 errmsg("foreign key constraints are not supported on foreign tables"),
552 parser_errposition(cxt->pstate,
553 constraint->location)));
556 * Fill in the current attribute's name and throw it into the
557 * list of FK constraints to be processed later.
559 constraint->fk_attrs = list_make1(makeString(column->colname));
560 cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
563 case CONSTR_ATTR_DEFERRABLE:
564 case CONSTR_ATTR_NOT_DEFERRABLE:
565 case CONSTR_ATTR_DEFERRED:
566 case CONSTR_ATTR_IMMEDIATE:
567 /* transformConstraintAttrs took care of these */
571 elog(ERROR, "unrecognized constraint type: %d",
572 constraint->contype);
578 * If needed, generate ALTER FOREIGN TABLE ALTER COLUMN statement to add
579 * per-column foreign data wrapper options to this column after creation.
581 if (column->fdwoptions != NIL)
583 AlterTableStmt *stmt;
586 cmd = makeNode(AlterTableCmd);
587 cmd->subtype = AT_AlterColumnGenericOptions;
588 cmd->name = column->colname;
589 cmd->def = (Node *) column->fdwoptions;
590 cmd->behavior = DROP_RESTRICT;
591 cmd->missing_ok = false;
593 stmt = makeNode(AlterTableStmt);
594 stmt->relation = cxt->relation;
596 stmt->relkind = OBJECT_FOREIGN_TABLE;
597 stmt->cmds = lappend(stmt->cmds, cmd);
599 cxt->alist = lappend(cxt->alist, stmt);
604 * transformTableConstraint
605 * transform a Constraint node within CREATE TABLE or ALTER TABLE
608 transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
610 switch (constraint->contype)
615 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
616 errmsg("primary key constraints are not supported on foreign tables"),
617 parser_errposition(cxt->pstate,
618 constraint->location)));
619 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
625 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
626 errmsg("unique constraints are not supported on foreign tables"),
627 parser_errposition(cxt->pstate,
628 constraint->location)));
629 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
632 case CONSTR_EXCLUSION:
635 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
636 errmsg("exclusion constraints are not supported on foreign tables"),
637 parser_errposition(cxt->pstate,
638 constraint->location)));
639 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
643 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
649 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
650 errmsg("foreign key constraints are not supported on foreign tables"),
651 parser_errposition(cxt->pstate,
652 constraint->location)));
653 cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
659 case CONSTR_ATTR_DEFERRABLE:
660 case CONSTR_ATTR_NOT_DEFERRABLE:
661 case CONSTR_ATTR_DEFERRED:
662 case CONSTR_ATTR_IMMEDIATE:
663 elog(ERROR, "invalid context for constraint type %d",
664 constraint->contype);
668 elog(ERROR, "unrecognized constraint type: %d",
669 constraint->contype);
675 * transformTableLikeClause
677 * Change the LIKE <srctable> portion of a CREATE TABLE statement into
678 * column definitions which recreate the user defined column portions of
682 transformTableLikeClause(CreateStmtContext *cxt, TableLikeClause *table_like_clause)
684 AttrNumber parent_attno;
691 ParseCallbackState pcbstate;
693 setup_parser_errposition_callback(&pcbstate, cxt->pstate,
694 table_like_clause->relation->location);
696 /* we could support LIKE in many cases, but worry about it another day */
699 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
700 errmsg("LIKE is not supported for creating foreign tables")));
702 relation = relation_openrv(table_like_clause->relation, AccessShareLock);
704 if (relation->rd_rel->relkind != RELKIND_RELATION &&
705 relation->rd_rel->relkind != RELKIND_VIEW &&
706 relation->rd_rel->relkind != RELKIND_MATVIEW &&
707 relation->rd_rel->relkind != RELKIND_COMPOSITE_TYPE &&
708 relation->rd_rel->relkind != RELKIND_FOREIGN_TABLE)
710 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
711 errmsg("\"%s\" is not a table, view, materialized view, composite type, or foreign table",
712 RelationGetRelationName(relation))));
714 cancel_parser_errposition_callback(&pcbstate);
717 * Check for privileges
719 if (relation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
721 aclresult = pg_type_aclcheck(relation->rd_rel->reltype, GetUserId(),
723 if (aclresult != ACLCHECK_OK)
724 aclcheck_error(aclresult, ACL_KIND_TYPE,
725 RelationGetRelationName(relation));
729 aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
731 if (aclresult != ACLCHECK_OK)
732 aclcheck_error(aclresult, ACL_KIND_CLASS,
733 RelationGetRelationName(relation));
736 tupleDesc = RelationGetDescr(relation);
737 constr = tupleDesc->constr;
740 * Initialize column number map for map_variable_attnos(). We need this
741 * since dropped columns in the source table aren't copied, so the new
742 * table can have different column numbers.
744 attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * tupleDesc->natts);
747 * Insert the copied attributes into the cxt for the new table definition.
749 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
752 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
753 char *attributeName = NameStr(attribute->attname);
757 * Ignore dropped columns in the parent. attmap entry is left zero.
759 if (attribute->attisdropped)
763 * Create a new column, which is marked as NOT inherited.
765 * For constraints, ONLY the NOT NULL constraint is inherited by the
766 * new column definition per SQL99.
768 def = makeNode(ColumnDef);
769 def->colname = pstrdup(attributeName);
770 def->typeName = makeTypeNameFromOid(attribute->atttypid,
771 attribute->atttypmod);
773 def->is_local = true;
774 def->is_not_null = attribute->attnotnull;
775 def->is_from_type = false;
777 def->raw_default = NULL;
778 def->cooked_default = NULL;
779 def->collClause = NULL;
780 def->collOid = attribute->attcollation;
781 def->constraints = NIL;
787 cxt->columns = lappend(cxt->columns, def);
789 attmap[parent_attno - 1] = list_length(cxt->columns);
792 * Copy default, if present and the default has been requested
794 if (attribute->atthasdef &&
795 (table_like_clause->options & CREATE_TABLE_LIKE_DEFAULTS))
797 Node *this_default = NULL;
798 AttrDefault *attrdef;
801 /* Find default in constraint structure */
802 Assert(constr != NULL);
803 attrdef = constr->defval;
804 for (i = 0; i < constr->num_defval; i++)
806 if (attrdef[i].adnum == parent_attno)
808 this_default = stringToNode(attrdef[i].adbin);
812 Assert(this_default != NULL);
815 * If default expr could contain any vars, we'd need to fix 'em,
816 * but it can't; so default is ready to apply to child.
819 def->cooked_default = this_default;
822 /* Likewise, copy storage if requested */
823 if (table_like_clause->options & CREATE_TABLE_LIKE_STORAGE)
824 def->storage = attribute->attstorage;
828 /* Likewise, copy comment if requested */
829 if ((table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS) &&
830 (comment = GetComment(attribute->attrelid,
832 attribute->attnum)) != NULL)
834 CommentStmt *stmt = makeNode(CommentStmt);
836 stmt->objtype = OBJECT_COLUMN;
837 stmt->objname = list_make3(makeString(cxt->relation->schemaname),
838 makeString(cxt->relation->relname),
839 makeString(def->colname));
841 stmt->comment = comment;
843 cxt->alist = lappend(cxt->alist, stmt);
848 * Copy CHECK constraints if requested, being careful to adjust attribute
849 * numbers so they match the child.
851 if ((table_like_clause->options & CREATE_TABLE_LIKE_CONSTRAINTS) &&
856 for (ccnum = 0; ccnum < tupleDesc->constr->num_check; ccnum++)
858 char *ccname = tupleDesc->constr->check[ccnum].ccname;
859 char *ccbin = tupleDesc->constr->check[ccnum].ccbin;
860 Constraint *n = makeNode(Constraint);
862 bool found_whole_row;
864 ccbin_node = map_variable_attnos(stringToNode(ccbin),
866 attmap, tupleDesc->natts,
870 * We reject whole-row variables because the whole point of LIKE
871 * is that the new table's rowtype might later diverge from the
872 * parent's. So, while translation might be possible right now,
873 * it wouldn't be possible to guarantee it would work in future.
877 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
878 errmsg("cannot convert whole-row table reference"),
879 errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
881 RelationGetRelationName(relation))));
883 n->contype = CONSTR_CHECK;
885 n->conname = pstrdup(ccname);
887 n->cooked_expr = nodeToString(ccbin_node);
888 cxt->ckconstraints = lappend(cxt->ckconstraints, n);
890 /* Copy comment on constraint */
891 if ((table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS) &&
892 (comment = GetComment(get_relation_constraint_oid(RelationGetRelid(relation),
894 ConstraintRelationId,
897 CommentStmt *stmt = makeNode(CommentStmt);
899 stmt->objtype = OBJECT_TABCONSTRAINT;
900 stmt->objname = list_make3(makeString(cxt->relation->schemaname),
901 makeString(cxt->relation->relname),
902 makeString(n->conname));
904 stmt->comment = comment;
906 cxt->alist = lappend(cxt->alist, stmt);
912 * Likewise, copy indexes if requested
914 if ((table_like_clause->options & CREATE_TABLE_LIKE_INDEXES) &&
915 relation->rd_rel->relhasindex)
917 List *parent_indexes;
920 parent_indexes = RelationGetIndexList(relation);
922 foreach(l, parent_indexes)
924 Oid parent_index_oid = lfirst_oid(l);
925 Relation parent_index;
926 IndexStmt *index_stmt;
928 parent_index = index_open(parent_index_oid, AccessShareLock);
930 /* Build CREATE INDEX statement to recreate the parent_index */
931 index_stmt = generateClonedIndexStmt(cxt, parent_index,
932 attmap, tupleDesc->natts);
934 /* Copy comment on index, if requested */
935 if (table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS)
937 comment = GetComment(parent_index_oid, RelationRelationId, 0);
940 * We make use of IndexStmt's idxcomment option, so as not to
941 * need to know now what name the index will have.
943 index_stmt->idxcomment = comment;
946 /* Save it in the inh_indexes list for the time being */
947 cxt->inh_indexes = lappend(cxt->inh_indexes, index_stmt);
949 index_close(parent_index, AccessShareLock);
954 * Close the parent rel, but keep our AccessShareLock on it until xact
955 * commit. That will prevent someone else from deleting or ALTERing the
956 * parent before the child is committed.
958 heap_close(relation, NoLock);
962 transformOfType(CreateStmtContext *cxt, TypeName *ofTypename)
969 AssertArg(ofTypename);
971 tuple = typenameType(NULL, ofTypename, NULL);
972 check_of_type(tuple);
973 ofTypeId = HeapTupleGetOid(tuple);
974 ofTypename->typeOid = ofTypeId; /* cached for later */
976 tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
977 for (i = 0; i < tupdesc->natts; i++)
979 Form_pg_attribute attr = tupdesc->attrs[i];
982 if (attr->attisdropped)
985 n = makeNode(ColumnDef);
986 n->colname = pstrdup(NameStr(attr->attname));
987 n->typeName = makeTypeNameFromOid(attr->atttypid, attr->atttypmod);
990 n->is_not_null = false;
991 n->is_from_type = true;
993 n->raw_default = NULL;
994 n->cooked_default = NULL;
995 n->collClause = NULL;
996 n->collOid = attr->attcollation;
997 n->constraints = NIL;
999 cxt->columns = lappend(cxt->columns, n);
1001 DecrTupleDescRefCount(tupdesc);
1003 ReleaseSysCache(tuple);
1007 * Generate an IndexStmt node using information from an already existing index
1008 * "source_idx". Attribute numbers should be adjusted according to attmap.
1011 generateClonedIndexStmt(CreateStmtContext *cxt, Relation source_idx,
1012 const AttrNumber *attmap, int attmap_length)
1014 Oid source_relid = RelationGetRelid(source_idx);
1015 Form_pg_attribute *attrs = RelationGetDescr(source_idx)->attrs;
1016 HeapTuple ht_idxrel;
1018 Form_pg_class idxrelrec;
1019 Form_pg_index idxrec;
1021 oidvector *indcollation;
1022 oidvector *indclass;
1025 ListCell *indexpr_item;
1033 * Fetch pg_class tuple of source index. We can't use the copy in the
1034 * relcache entry because it doesn't include optional fields.
1036 ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(source_relid));
1037 if (!HeapTupleIsValid(ht_idxrel))
1038 elog(ERROR, "cache lookup failed for relation %u", source_relid);
1039 idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
1041 /* Fetch pg_index tuple for source index from relcache entry */
1042 ht_idx = source_idx->rd_indextuple;
1043 idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
1044 indrelid = idxrec->indrelid;
1046 /* Fetch pg_am tuple for source index from relcache entry */
1047 amrec = source_idx->rd_am;
1049 /* Extract indcollation from the pg_index tuple */
1050 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1051 Anum_pg_index_indcollation, &isnull);
1053 indcollation = (oidvector *) DatumGetPointer(datum);
1055 /* Extract indclass from the pg_index tuple */
1056 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1057 Anum_pg_index_indclass, &isnull);
1059 indclass = (oidvector *) DatumGetPointer(datum);
1061 /* Begin building the IndexStmt */
1062 index = makeNode(IndexStmt);
1063 index->relation = cxt->relation;
1064 index->accessMethod = pstrdup(NameStr(amrec->amname));
1065 if (OidIsValid(idxrelrec->reltablespace))
1066 index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
1068 index->tableSpace = NULL;
1069 index->excludeOpNames = NIL;
1070 index->idxcomment = NULL;
1071 index->indexOid = InvalidOid;
1072 index->oldNode = InvalidOid;
1073 index->unique = idxrec->indisunique;
1074 index->primary = idxrec->indisprimary;
1075 index->concurrent = false;
1078 * We don't try to preserve the name of the source index; instead, just
1079 * let DefineIndex() choose a reasonable name.
1081 index->idxname = NULL;
1084 * If the index is marked PRIMARY or has an exclusion condition, it's
1085 * certainly from a constraint; else, if it's not marked UNIQUE, it
1086 * certainly isn't. If it is or might be from a constraint, we have to
1087 * fetch the pg_constraint record.
1089 if (index->primary || index->unique || idxrec->indisexclusion)
1091 Oid constraintId = get_index_constraint(source_relid);
1093 if (OidIsValid(constraintId))
1095 HeapTuple ht_constr;
1096 Form_pg_constraint conrec;
1098 ht_constr = SearchSysCache1(CONSTROID,
1099 ObjectIdGetDatum(constraintId));
1100 if (!HeapTupleIsValid(ht_constr))
1101 elog(ERROR, "cache lookup failed for constraint %u",
1103 conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
1105 index->isconstraint = true;
1106 index->deferrable = conrec->condeferrable;
1107 index->initdeferred = conrec->condeferred;
1109 /* If it's an exclusion constraint, we need the operator names */
1110 if (idxrec->indisexclusion)
1116 Assert(conrec->contype == CONSTRAINT_EXCLUSION);
1117 /* Extract operator OIDs from the pg_constraint tuple */
1118 datum = SysCacheGetAttr(CONSTROID, ht_constr,
1119 Anum_pg_constraint_conexclop,
1122 elog(ERROR, "null conexclop for constraint %u",
1125 deconstruct_array(DatumGetArrayTypeP(datum),
1126 OIDOID, sizeof(Oid), true, 'i',
1127 &elems, NULL, &nElems);
1129 for (i = 0; i < nElems; i++)
1131 Oid operid = DatumGetObjectId(elems[i]);
1133 Form_pg_operator operform;
1138 opertup = SearchSysCache1(OPEROID,
1139 ObjectIdGetDatum(operid));
1140 if (!HeapTupleIsValid(opertup))
1141 elog(ERROR, "cache lookup failed for operator %u",
1143 operform = (Form_pg_operator) GETSTRUCT(opertup);
1144 oprname = pstrdup(NameStr(operform->oprname));
1145 /* For simplicity we always schema-qualify the op name */
1146 nspname = get_namespace_name(operform->oprnamespace);
1147 namelist = list_make2(makeString(nspname),
1148 makeString(oprname));
1149 index->excludeOpNames = lappend(index->excludeOpNames,
1151 ReleaseSysCache(opertup);
1155 ReleaseSysCache(ht_constr);
1158 index->isconstraint = false;
1161 index->isconstraint = false;
1163 /* Get the index expressions, if any */
1164 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1165 Anum_pg_index_indexprs, &isnull);
1170 exprsString = TextDatumGetCString(datum);
1171 indexprs = (List *) stringToNode(exprsString);
1176 /* Build the list of IndexElem */
1177 index->indexParams = NIL;
1179 indexpr_item = list_head(indexprs);
1180 for (keyno = 0; keyno < idxrec->indnatts; keyno++)
1183 AttrNumber attnum = idxrec->indkey.values[keyno];
1184 int16 opt = source_idx->rd_indoption[keyno];
1186 iparam = makeNode(IndexElem);
1188 if (AttributeNumberIsValid(attnum))
1190 /* Simple index column */
1193 attname = get_relid_attribute_name(indrelid, attnum);
1194 keycoltype = get_atttype(indrelid, attnum);
1196 iparam->name = attname;
1197 iparam->expr = NULL;
1201 /* Expressional index */
1203 bool found_whole_row;
1205 if (indexpr_item == NULL)
1206 elog(ERROR, "too few entries in indexprs list");
1207 indexkey = (Node *) lfirst(indexpr_item);
1208 indexpr_item = lnext(indexpr_item);
1210 /* Adjust Vars to match new table's column numbering */
1211 indexkey = map_variable_attnos(indexkey,
1213 attmap, attmap_length,
1216 /* As in transformTableLikeClause, reject whole-row variables */
1217 if (found_whole_row)
1219 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1220 errmsg("cannot convert whole-row table reference"),
1221 errdetail("Index \"%s\" contains a whole-row table reference.",
1222 RelationGetRelationName(source_idx))));
1224 iparam->name = NULL;
1225 iparam->expr = indexkey;
1227 keycoltype = exprType(indexkey);
1230 /* Copy the original index column name */
1231 iparam->indexcolname = pstrdup(NameStr(attrs[keyno]->attname));
1233 /* Add the collation name, if non-default */
1234 iparam->collation = get_collation(indcollation->values[keyno], keycoltype);
1236 /* Add the operator class name, if non-default */
1237 iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1239 iparam->ordering = SORTBY_DEFAULT;
1240 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1242 /* Adjust options if necessary */
1243 if (amrec->amcanorder)
1246 * If it supports sort ordering, copy DESC and NULLS opts. Don't
1247 * set non-default settings unnecessarily, though, so as to
1248 * improve the chance of recognizing equivalence to constraint
1251 if (opt & INDOPTION_DESC)
1253 iparam->ordering = SORTBY_DESC;
1254 if ((opt & INDOPTION_NULLS_FIRST) == 0)
1255 iparam->nulls_ordering = SORTBY_NULLS_LAST;
1259 if (opt & INDOPTION_NULLS_FIRST)
1260 iparam->nulls_ordering = SORTBY_NULLS_FIRST;
1264 index->indexParams = lappend(index->indexParams, iparam);
1267 /* Copy reloptions if any */
1268 datum = SysCacheGetAttr(RELOID, ht_idxrel,
1269 Anum_pg_class_reloptions, &isnull);
1271 index->options = untransformRelOptions(datum);
1273 /* If it's a partial index, decompile and append the predicate */
1274 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1275 Anum_pg_index_indpred, &isnull);
1280 bool found_whole_row;
1282 /* Convert text string to node tree */
1283 pred_str = TextDatumGetCString(datum);
1284 pred_tree = (Node *) stringToNode(pred_str);
1286 /* Adjust Vars to match new table's column numbering */
1287 pred_tree = map_variable_attnos(pred_tree,
1289 attmap, attmap_length,
1292 /* As in transformTableLikeClause, reject whole-row variables */
1293 if (found_whole_row)
1295 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1296 errmsg("cannot convert whole-row table reference"),
1297 errdetail("Index \"%s\" contains a whole-row table reference.",
1298 RelationGetRelationName(source_idx))));
1300 index->whereClause = pred_tree;
1304 ReleaseSysCache(ht_idxrel);
1310 * get_collation - fetch qualified name of a collation
1312 * If collation is InvalidOid or is the default for the given actual_datatype,
1313 * then the return value is NIL.
1316 get_collation(Oid collation, Oid actual_datatype)
1320 Form_pg_collation coll_rec;
1324 if (!OidIsValid(collation))
1325 return NIL; /* easy case */
1326 if (collation == get_typcollation(actual_datatype))
1327 return NIL; /* just let it default */
1329 ht_coll = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
1330 if (!HeapTupleIsValid(ht_coll))
1331 elog(ERROR, "cache lookup failed for collation %u", collation);
1332 coll_rec = (Form_pg_collation) GETSTRUCT(ht_coll);
1334 /* For simplicity, we always schema-qualify the name */
1335 nsp_name = get_namespace_name(coll_rec->collnamespace);
1336 coll_name = pstrdup(NameStr(coll_rec->collname));
1337 result = list_make2(makeString(nsp_name), makeString(coll_name));
1339 ReleaseSysCache(ht_coll);
1344 * get_opclass - fetch qualified name of an index operator class
1346 * If the opclass is the default for the given actual_datatype, then
1347 * the return value is NIL.
1350 get_opclass(Oid opclass, Oid actual_datatype)
1354 Form_pg_opclass opc_rec;
1356 ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
1357 if (!HeapTupleIsValid(ht_opc))
1358 elog(ERROR, "cache lookup failed for opclass %u", opclass);
1359 opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
1361 if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
1363 /* For simplicity, we always schema-qualify the name */
1364 char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
1365 char *opc_name = pstrdup(NameStr(opc_rec->opcname));
1367 result = list_make2(makeString(nsp_name), makeString(opc_name));
1370 ReleaseSysCache(ht_opc);
1376 * transformIndexConstraints
1377 * Handle UNIQUE, PRIMARY KEY, EXCLUDE constraints, which create indexes.
1378 * We also merge in any index definitions arising from
1379 * LIKE ... INCLUDING INDEXES.
1382 transformIndexConstraints(CreateStmtContext *cxt)
1385 List *indexlist = NIL;
1389 * Run through the constraints that need to generate an index. For PRIMARY
1390 * KEY, mark each column as NOT NULL and create an index. For UNIQUE or
1391 * EXCLUDE, create an index as for PRIMARY KEY, but do not insist on NOT
1394 foreach(lc, cxt->ixconstraints)
1396 Constraint *constraint = (Constraint *) lfirst(lc);
1398 Assert(IsA(constraint, Constraint));
1399 Assert(constraint->contype == CONSTR_PRIMARY ||
1400 constraint->contype == CONSTR_UNIQUE ||
1401 constraint->contype == CONSTR_EXCLUSION);
1403 index = transformIndexConstraint(constraint, cxt);
1405 indexlist = lappend(indexlist, index);
1408 /* Add in any indexes defined by LIKE ... INCLUDING INDEXES */
1409 foreach(lc, cxt->inh_indexes)
1411 index = (IndexStmt *) lfirst(lc);
1415 if (cxt->pkey != NULL)
1417 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1418 errmsg("multiple primary keys for table \"%s\" are not allowed",
1419 cxt->relation->relname)));
1423 indexlist = lappend(indexlist, index);
1427 * Scan the index list and remove any redundant index specifications. This
1428 * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
1429 * strict reading of SQL would suggest raising an error instead, but that
1430 * strikes me as too anal-retentive. - tgl 2001-02-14
1432 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1433 * pre-existing indexes, too.
1435 Assert(cxt->alist == NIL);
1436 if (cxt->pkey != NULL)
1438 /* Make sure we keep the PKEY index in preference to others... */
1439 cxt->alist = list_make1(cxt->pkey);
1442 foreach(lc, indexlist)
1449 /* if it's pkey, it's already in cxt->alist */
1450 if (index == cxt->pkey)
1453 foreach(k, cxt->alist)
1455 IndexStmt *priorindex = lfirst(k);
1457 if (equal(index->indexParams, priorindex->indexParams) &&
1458 equal(index->whereClause, priorindex->whereClause) &&
1459 equal(index->excludeOpNames, priorindex->excludeOpNames) &&
1460 strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
1461 index->deferrable == priorindex->deferrable &&
1462 index->initdeferred == priorindex->initdeferred)
1464 priorindex->unique |= index->unique;
1467 * If the prior index is as yet unnamed, and this one is
1468 * named, then transfer the name to the prior index. This
1469 * ensures that if we have named and unnamed constraints,
1470 * we'll use (at least one of) the names for the index.
1472 if (priorindex->idxname == NULL)
1473 priorindex->idxname = index->idxname;
1480 cxt->alist = lappend(cxt->alist, index);
1485 * transformIndexConstraint
1486 * Transform one UNIQUE, PRIMARY KEY, or EXCLUDE constraint for
1487 * transformIndexConstraints.
1490 transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
1495 index = makeNode(IndexStmt);
1497 index->unique = (constraint->contype != CONSTR_EXCLUSION);
1498 index->primary = (constraint->contype == CONSTR_PRIMARY);
1501 if (cxt->pkey != NULL)
1503 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1504 errmsg("multiple primary keys for table \"%s\" are not allowed",
1505 cxt->relation->relname),
1506 parser_errposition(cxt->pstate, constraint->location)));
1510 * In ALTER TABLE case, a primary index might already exist, but
1511 * DefineIndex will check for it.
1514 index->isconstraint = true;
1515 index->deferrable = constraint->deferrable;
1516 index->initdeferred = constraint->initdeferred;
1518 if (constraint->conname != NULL)
1519 index->idxname = pstrdup(constraint->conname);
1521 index->idxname = NULL; /* DefineIndex will choose name */
1523 index->relation = cxt->relation;
1524 index->accessMethod = constraint->access_method ? constraint->access_method : DEFAULT_INDEX_TYPE;
1525 index->options = constraint->options;
1526 index->tableSpace = constraint->indexspace;
1527 index->whereClause = constraint->where_clause;
1528 index->indexParams = NIL;
1529 index->excludeOpNames = NIL;
1530 index->idxcomment = NULL;
1531 index->indexOid = InvalidOid;
1532 index->oldNode = InvalidOid;
1533 index->concurrent = false;
1536 * If it's ALTER TABLE ADD CONSTRAINT USING INDEX, look up the index and
1537 * verify it's usable, then extract the implied column name list. (We
1538 * will not actually need the column name list at runtime, but we need it
1539 * now to check for duplicate column entries below.)
1541 if (constraint->indexname != NULL)
1543 char *index_name = constraint->indexname;
1544 Relation heap_rel = cxt->rel;
1547 Form_pg_index index_form;
1548 oidvector *indclass;
1549 Datum indclassDatum;
1553 /* Grammar should not allow this with explicit column list */
1554 Assert(constraint->keys == NIL);
1556 /* Grammar should only allow PRIMARY and UNIQUE constraints */
1557 Assert(constraint->contype == CONSTR_PRIMARY ||
1558 constraint->contype == CONSTR_UNIQUE);
1560 /* Must be ALTER, not CREATE, but grammar doesn't enforce that */
1563 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1564 errmsg("cannot use an existing index in CREATE TABLE"),
1565 parser_errposition(cxt->pstate, constraint->location)));
1567 /* Look for the index in the same schema as the table */
1568 index_oid = get_relname_relid(index_name, RelationGetNamespace(heap_rel));
1570 if (!OidIsValid(index_oid))
1572 (errcode(ERRCODE_UNDEFINED_OBJECT),
1573 errmsg("index \"%s\" does not exist", index_name),
1574 parser_errposition(cxt->pstate, constraint->location)));
1576 /* Open the index (this will throw an error if it is not an index) */
1577 index_rel = index_open(index_oid, AccessShareLock);
1578 index_form = index_rel->rd_index;
1580 /* Check that it does not have an associated constraint already */
1581 if (OidIsValid(get_index_constraint(index_oid)))
1583 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1584 errmsg("index \"%s\" is already associated with a constraint",
1586 parser_errposition(cxt->pstate, constraint->location)));
1588 /* Perform validity checks on the index */
1589 if (index_form->indrelid != RelationGetRelid(heap_rel))
1591 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1592 errmsg("index \"%s\" does not belong to table \"%s\"",
1593 index_name, RelationGetRelationName(heap_rel)),
1594 parser_errposition(cxt->pstate, constraint->location)));
1596 if (!IndexIsValid(index_form))
1598 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1599 errmsg("index \"%s\" is not valid", index_name),
1600 parser_errposition(cxt->pstate, constraint->location)));
1602 if (!index_form->indisunique)
1604 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1605 errmsg("\"%s\" is not a unique index", index_name),
1606 errdetail("Cannot create a primary key or unique constraint using such an index."),
1607 parser_errposition(cxt->pstate, constraint->location)));
1609 if (RelationGetIndexExpressions(index_rel) != NIL)
1611 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1612 errmsg("index \"%s\" contains expressions", index_name),
1613 errdetail("Cannot create a primary key or unique constraint using such an index."),
1614 parser_errposition(cxt->pstate, constraint->location)));
1616 if (RelationGetIndexPredicate(index_rel) != NIL)
1618 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1619 errmsg("\"%s\" is a partial index", index_name),
1620 errdetail("Cannot create a primary key or unique constraint using such an index."),
1621 parser_errposition(cxt->pstate, constraint->location)));
1624 * It's probably unsafe to change a deferred index to non-deferred. (A
1625 * non-constraint index couldn't be deferred anyway, so this case
1626 * should never occur; no need to sweat, but let's check it.)
1628 if (!index_form->indimmediate && !constraint->deferrable)
1630 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1631 errmsg("\"%s\" is a deferrable index", index_name),
1632 errdetail("Cannot create a non-deferrable constraint using a deferrable index."),
1633 parser_errposition(cxt->pstate, constraint->location)));
1636 * Insist on it being a btree. That's the only kind that supports
1637 * uniqueness at the moment anyway; but we must have an index that
1638 * exactly matches what you'd get from plain ADD CONSTRAINT syntax,
1639 * else dump and reload will produce a different index (breaking
1640 * pg_upgrade in particular).
1642 if (index_rel->rd_rel->relam != get_am_oid(DEFAULT_INDEX_TYPE, false))
1644 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1645 errmsg("index \"%s\" is not a btree", index_name),
1646 parser_errposition(cxt->pstate, constraint->location)));
1648 /* Must get indclass the hard way */
1649 indclassDatum = SysCacheGetAttr(INDEXRELID, index_rel->rd_indextuple,
1650 Anum_pg_index_indclass, &isnull);
1652 indclass = (oidvector *) DatumGetPointer(indclassDatum);
1654 for (i = 0; i < index_form->indnatts; i++)
1656 int16 attnum = index_form->indkey.values[i];
1657 Form_pg_attribute attform;
1662 * We shouldn't see attnum == 0 here, since we already rejected
1663 * expression indexes. If we do, SystemAttributeDefinition will
1668 Assert(attnum <= heap_rel->rd_att->natts);
1669 attform = heap_rel->rd_att->attrs[attnum - 1];
1672 attform = SystemAttributeDefinition(attnum,
1673 heap_rel->rd_rel->relhasoids);
1674 attname = pstrdup(NameStr(attform->attname));
1677 * Insist on default opclass and sort options. While the index
1678 * would still work as a constraint with non-default settings, it
1679 * might not provide exactly the same uniqueness semantics as
1680 * you'd get from a normally-created constraint; and there's also
1681 * the dump/reload problem mentioned above.
1683 defopclass = GetDefaultOpClass(attform->atttypid,
1684 index_rel->rd_rel->relam);
1685 if (indclass->values[i] != defopclass ||
1686 index_rel->rd_indoption[i] != 0)
1688 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1689 errmsg("index \"%s\" does not have default sorting behavior", index_name),
1690 errdetail("Cannot create a primary key or unique constraint using such an index."),
1691 parser_errposition(cxt->pstate, constraint->location)));
1693 constraint->keys = lappend(constraint->keys, makeString(attname));
1696 /* Close the index relation but keep the lock */
1697 relation_close(index_rel, NoLock);
1699 index->indexOid = index_oid;
1703 * If it's an EXCLUDE constraint, the grammar returns a list of pairs of
1704 * IndexElems and operator names. We have to break that apart into
1707 if (constraint->contype == CONSTR_EXCLUSION)
1709 foreach(lc, constraint->exclusions)
1711 List *pair = (List *) lfirst(lc);
1715 Assert(list_length(pair) == 2);
1716 elem = (IndexElem *) linitial(pair);
1717 Assert(IsA(elem, IndexElem));
1718 opname = (List *) lsecond(pair);
1719 Assert(IsA(opname, List));
1721 index->indexParams = lappend(index->indexParams, elem);
1722 index->excludeOpNames = lappend(index->excludeOpNames, opname);
1729 * For UNIQUE and PRIMARY KEY, we just have a list of column names.
1731 * Make sure referenced keys exist. If we are making a PRIMARY KEY index,
1732 * also make sure they are NOT NULL, if possible. (Although we could leave
1733 * it to DefineIndex to mark the columns NOT NULL, it's more efficient to
1734 * get it right the first time.)
1736 foreach(lc, constraint->keys)
1738 char *key = strVal(lfirst(lc));
1740 ColumnDef *column = NULL;
1744 foreach(columns, cxt->columns)
1746 column = (ColumnDef *) lfirst(columns);
1747 Assert(IsA(column, ColumnDef));
1748 if (strcmp(column->colname, key) == 0)
1756 /* found column in the new table; force it to be NOT NULL */
1757 if (constraint->contype == CONSTR_PRIMARY)
1758 column->is_not_null = TRUE;
1760 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1763 * column will be a system column in the new table, so accept it.
1764 * System columns can't ever be null, so no need to worry about
1765 * PRIMARY/NOT NULL constraint.
1769 else if (cxt->inhRelations)
1771 /* try inherited tables */
1774 foreach(inher, cxt->inhRelations)
1776 RangeVar *inh = (RangeVar *) lfirst(inher);
1780 Assert(IsA(inh, RangeVar));
1781 rel = heap_openrv(inh, AccessShareLock);
1782 if (rel->rd_rel->relkind != RELKIND_RELATION)
1784 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1785 errmsg("inherited relation \"%s\" is not a table",
1787 for (count = 0; count < rel->rd_att->natts; count++)
1789 Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1790 char *inhname = NameStr(inhattr->attname);
1792 if (inhattr->attisdropped)
1794 if (strcmp(key, inhname) == 0)
1799 * We currently have no easy way to force an inherited
1800 * column to be NOT NULL at creation, if its parent
1801 * wasn't so already. We leave it to DefineIndex to
1802 * fix things up in this case.
1807 heap_close(rel, NoLock);
1814 * In the ALTER TABLE case, don't complain about index keys not
1815 * created in the command; they may well exist already. DefineIndex
1816 * will complain about them if not, and will also take care of marking
1819 if (!found && !cxt->isalter)
1821 (errcode(ERRCODE_UNDEFINED_COLUMN),
1822 errmsg("column \"%s\" named in key does not exist", key),
1823 parser_errposition(cxt->pstate, constraint->location)));
1825 /* Check for PRIMARY KEY(foo, foo) */
1826 foreach(columns, index->indexParams)
1828 iparam = (IndexElem *) lfirst(columns);
1829 if (iparam->name && strcmp(key, iparam->name) == 0)
1833 (errcode(ERRCODE_DUPLICATE_COLUMN),
1834 errmsg("column \"%s\" appears twice in primary key constraint",
1836 parser_errposition(cxt->pstate, constraint->location)));
1839 (errcode(ERRCODE_DUPLICATE_COLUMN),
1840 errmsg("column \"%s\" appears twice in unique constraint",
1842 parser_errposition(cxt->pstate, constraint->location)));
1846 /* OK, add it to the index definition */
1847 iparam = makeNode(IndexElem);
1848 iparam->name = pstrdup(key);
1849 iparam->expr = NULL;
1850 iparam->indexcolname = NULL;
1851 iparam->collation = NIL;
1852 iparam->opclass = NIL;
1853 iparam->ordering = SORTBY_DEFAULT;
1854 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1855 index->indexParams = lappend(index->indexParams, iparam);
1862 * transformFKConstraints
1863 * handle FOREIGN KEY constraints
1866 transformFKConstraints(CreateStmtContext *cxt,
1867 bool skipValidation, bool isAddConstraint)
1871 if (cxt->fkconstraints == NIL)
1875 * If CREATE TABLE or adding a column with NULL default, we can safely
1876 * skip validation of FK constraints, and nonetheless mark them valid.
1877 * (This will override any user-supplied NOT VALID flag.)
1881 foreach(fkclist, cxt->fkconstraints)
1883 Constraint *constraint = (Constraint *) lfirst(fkclist);
1885 constraint->skip_validation = true;
1886 constraint->initially_valid = true;
1891 * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
1892 * CONSTRAINT command to execute after the basic command is complete. (If
1893 * called from ADD CONSTRAINT, that routine will add the FK constraints to
1894 * its own subcommand list.)
1896 * Note: the ADD CONSTRAINT command must also execute after any index
1897 * creation commands. Thus, this should run after
1898 * transformIndexConstraints, so that the CREATE INDEX commands are
1899 * already in cxt->alist.
1901 if (!isAddConstraint)
1903 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1905 alterstmt->relation = cxt->relation;
1906 alterstmt->cmds = NIL;
1907 alterstmt->relkind = OBJECT_TABLE;
1909 foreach(fkclist, cxt->fkconstraints)
1911 Constraint *constraint = (Constraint *) lfirst(fkclist);
1912 AlterTableCmd *altercmd = makeNode(AlterTableCmd);
1914 altercmd->subtype = AT_ProcessedConstraint;
1915 altercmd->name = NULL;
1916 altercmd->def = (Node *) constraint;
1917 alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
1920 cxt->alist = lappend(cxt->alist, alterstmt);
1925 * transformIndexStmt - parse analysis for CREATE INDEX and ALTER TABLE
1927 * Note: this is a no-op for an index not using either index expressions or
1928 * a predicate expression. There are several code paths that create indexes
1929 * without bothering to call this, because they know they don't have any
1930 * such expressions to deal with.
1932 * To avoid race conditions, it's important that this function rely only on
1933 * the passed-in relid (and not on stmt->relation) to determine the target
1937 transformIndexStmt(Oid relid, IndexStmt *stmt, const char *queryString)
1945 * We must not scribble on the passed-in IndexStmt, so copy it. (This is
1946 * overkill, but easy.)
1948 stmt = (IndexStmt *) copyObject(stmt);
1951 pstate = make_parsestate(NULL);
1952 pstate->p_sourcetext = queryString;
1955 * Put the parent table into the rtable so that the expressions can refer
1956 * to its fields without qualification. Caller is responsible for locking
1957 * relation, but we still need to open it.
1959 rel = relation_open(relid, NoLock);
1960 rte = addRangeTableEntryForRelation(pstate, rel, NULL, false, true);
1962 /* no to join list, yes to namespaces */
1963 addRTEtoQuery(pstate, rte, false, true, true);
1965 /* take care of the where clause */
1966 if (stmt->whereClause)
1968 stmt->whereClause = transformWhereClause(pstate,
1970 EXPR_KIND_INDEX_PREDICATE,
1972 /* we have to fix its collations too */
1973 assign_expr_collations(pstate, stmt->whereClause);
1976 /* take care of any index expressions */
1977 foreach(l, stmt->indexParams)
1979 IndexElem *ielem = (IndexElem *) lfirst(l);
1983 /* Extract preliminary index col name before transforming expr */
1984 if (ielem->indexcolname == NULL)
1985 ielem->indexcolname = FigureIndexColname(ielem->expr);
1987 /* Now do parse transformation of the expression */
1988 ielem->expr = transformExpr(pstate, ielem->expr,
1989 EXPR_KIND_INDEX_EXPRESSION);
1991 /* We have to fix its collations too */
1992 assign_expr_collations(pstate, ielem->expr);
1995 * transformExpr() should have already rejected subqueries,
1996 * aggregates, and window functions, based on the EXPR_KIND_ for
1997 * an index expression.
1999 * Also reject expressions returning sets; this is for consistency
2000 * with what transformWhereClause() checks for the predicate.
2001 * DefineIndex() will make more checks.
2003 if (expression_returns_set(ielem->expr))
2005 (errcode(ERRCODE_DATATYPE_MISMATCH),
2006 errmsg("index expression cannot return a set")));
2011 * Check that only the base rel is mentioned. (This should be dead code
2012 * now that add_missing_from is history.)
2014 if (list_length(pstate->p_rtable) != 1)
2016 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2017 errmsg("index expressions and predicates can refer only to the table being indexed")));
2019 free_parsestate(pstate);
2021 /* Close relation */
2022 heap_close(rel, NoLock);
2029 * transformRuleStmt -
2030 * transform a CREATE RULE Statement. The action is a list of parse
2031 * trees which is transformed into a list of query trees, and we also
2032 * transform the WHERE clause if any.
2034 * actions and whereClause are output parameters that receive the
2035 * transformed results.
2037 * Note that we must not scribble on the passed-in RuleStmt, so we do
2038 * copyObject() on the actions and WHERE clause.
2041 transformRuleStmt(RuleStmt *stmt, const char *queryString,
2042 List **actions, Node **whereClause)
2046 RangeTblEntry *oldrte;
2047 RangeTblEntry *newrte;
2050 * To avoid deadlock, make sure the first thing we do is grab
2051 * AccessExclusiveLock on the target relation. This will be needed by
2052 * DefineQueryRewrite(), and we don't want to grab a lesser lock
2055 rel = heap_openrv(stmt->relation, AccessExclusiveLock);
2057 if (rel->rd_rel->relkind == RELKIND_MATVIEW)
2059 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2060 errmsg("rules on materialized views are not supported")));
2063 pstate = make_parsestate(NULL);
2064 pstate->p_sourcetext = queryString;
2067 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
2068 * Set up their RTEs in the main pstate for use in parsing the rule
2071 oldrte = addRangeTableEntryForRelation(pstate, rel,
2072 makeAlias("old", NIL),
2074 newrte = addRangeTableEntryForRelation(pstate, rel,
2075 makeAlias("new", NIL),
2077 /* Must override addRangeTableEntry's default access-check flags */
2078 oldrte->requiredPerms = 0;
2079 newrte->requiredPerms = 0;
2082 * They must be in the namespace too for lookup purposes, but only add the
2083 * one(s) that are relevant for the current kind of rule. In an UPDATE
2084 * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
2085 * there's no need to be so picky for INSERT & DELETE. We do not add them
2088 switch (stmt->event)
2091 addRTEtoQuery(pstate, oldrte, false, true, true);
2094 addRTEtoQuery(pstate, oldrte, false, true, true);
2095 addRTEtoQuery(pstate, newrte, false, true, true);
2098 addRTEtoQuery(pstate, newrte, false, true, true);
2101 addRTEtoQuery(pstate, oldrte, false, true, true);
2104 elog(ERROR, "unrecognized event type: %d",
2109 /* take care of the where clause */
2110 *whereClause = transformWhereClause(pstate,
2111 (Node *) copyObject(stmt->whereClause),
2114 /* we have to fix its collations too */
2115 assign_expr_collations(pstate, *whereClause);
2117 /* this is probably dead code without add_missing_from: */
2118 if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
2120 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2121 errmsg("rule WHERE condition cannot contain references to other relations")));
2124 * 'instead nothing' rules with a qualification need a query rangetable so
2125 * the rewrite handler can add the negated rule qualification to the
2126 * original query. We create a query with the new command type CMD_NOTHING
2127 * here that is treated specially by the rewrite system.
2129 if (stmt->actions == NIL)
2131 Query *nothing_qry = makeNode(Query);
2133 nothing_qry->commandType = CMD_NOTHING;
2134 nothing_qry->rtable = pstate->p_rtable;
2135 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
2137 *actions = list_make1(nothing_qry);
2142 List *newactions = NIL;
2145 * transform each statement, like parse_sub_analyze()
2147 foreach(l, stmt->actions)
2149 Node *action = (Node *) lfirst(l);
2150 ParseState *sub_pstate = make_parsestate(NULL);
2157 * Since outer ParseState isn't parent of inner, have to pass down
2158 * the query text by hand.
2160 sub_pstate->p_sourcetext = queryString;
2163 * Set up OLD/NEW in the rtable for this statement. The entries
2164 * are added only to relnamespace, not varnamespace, because we
2165 * don't want them to be referred to by unqualified field names
2166 * nor "*" in the rule actions. We decide later whether to put
2167 * them in the joinlist.
2169 oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
2170 makeAlias("old", NIL),
2172 newrte = addRangeTableEntryForRelation(sub_pstate, rel,
2173 makeAlias("new", NIL),
2175 oldrte->requiredPerms = 0;
2176 newrte->requiredPerms = 0;
2177 addRTEtoQuery(sub_pstate, oldrte, false, true, false);
2178 addRTEtoQuery(sub_pstate, newrte, false, true, false);
2180 /* Transform the rule action statement */
2181 top_subqry = transformStmt(sub_pstate,
2182 (Node *) copyObject(action));
2185 * We cannot support utility-statement actions (eg NOTIFY) with
2186 * nonempty rule WHERE conditions, because there's no way to make
2187 * the utility action execute conditionally.
2189 if (top_subqry->commandType == CMD_UTILITY &&
2190 *whereClause != NULL)
2192 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2193 errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
2196 * If the action is INSERT...SELECT, OLD/NEW have been pushed down
2197 * into the SELECT, and that's what we need to look at. (Ugly
2198 * kluge ... try to fix this when we redesign querytrees.)
2200 sub_qry = getInsertSelectQuery(top_subqry, NULL);
2203 * If the sub_qry is a setop, we cannot attach any qualifications
2204 * to it, because the planner won't notice them. This could
2205 * perhaps be relaxed someday, but for now, we may as well reject
2206 * such a rule immediately.
2208 if (sub_qry->setOperations != NULL && *whereClause != NULL)
2210 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2211 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2214 * Validate action's use of OLD/NEW, qual too
2217 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
2218 rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
2220 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
2221 rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
2223 switch (stmt->event)
2228 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2229 errmsg("ON SELECT rule cannot use OLD")));
2232 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2233 errmsg("ON SELECT rule cannot use NEW")));
2241 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2242 errmsg("ON INSERT rule cannot use OLD")));
2247 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2248 errmsg("ON DELETE rule cannot use NEW")));
2251 elog(ERROR, "unrecognized event type: %d",
2257 * OLD/NEW are not allowed in WITH queries, because they would
2258 * amount to outer references for the WITH, which we disallow.
2259 * However, they were already in the outer rangetable when we
2260 * analyzed the query, so we have to check.
2262 * Note that in the INSERT...SELECT case, we need to examine the
2263 * CTE lists of both top_subqry and sub_qry.
2265 * Note that we aren't digging into the body of the query looking
2266 * for WITHs in nested sub-SELECTs. A WITH down there can
2267 * legitimately refer to OLD/NEW, because it'd be an
2268 * indirect-correlated outer reference.
2270 if (rangeTableEntry_used((Node *) top_subqry->cteList,
2271 PRS2_OLD_VARNO, 0) ||
2272 rangeTableEntry_used((Node *) sub_qry->cteList,
2275 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2276 errmsg("cannot refer to OLD within WITH query")));
2277 if (rangeTableEntry_used((Node *) top_subqry->cteList,
2278 PRS2_NEW_VARNO, 0) ||
2279 rangeTableEntry_used((Node *) sub_qry->cteList,
2282 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2283 errmsg("cannot refer to NEW within WITH query")));
2286 * For efficiency's sake, add OLD to the rule action's jointree
2287 * only if it was actually referenced in the statement or qual.
2289 * For INSERT, NEW is not really a relation (only a reference to
2290 * the to-be-inserted tuple) and should never be added to the
2293 * For UPDATE, we treat NEW as being another kind of reference to
2294 * OLD, because it represents references to *transformed* tuples
2295 * of the existing relation. It would be wrong to enter NEW
2296 * separately in the jointree, since that would cause a double
2297 * join of the updated relation. It's also wrong to fail to make
2298 * a jointree entry if only NEW and not OLD is mentioned.
2300 if (has_old || (has_new && stmt->event == CMD_UPDATE))
2303 * If sub_qry is a setop, manipulating its jointree will do no
2304 * good at all, because the jointree is dummy. (This should be
2305 * a can't-happen case because of prior tests.)
2307 if (sub_qry->setOperations != NULL)
2309 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2310 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2311 /* hack so we can use addRTEtoQuery() */
2312 sub_pstate->p_rtable = sub_qry->rtable;
2313 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
2314 addRTEtoQuery(sub_pstate, oldrte, true, false, false);
2315 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
2318 newactions = lappend(newactions, top_subqry);
2320 free_parsestate(sub_pstate);
2323 *actions = newactions;
2326 free_parsestate(pstate);
2328 /* Close relation, but keep the exclusive lock */
2329 heap_close(rel, NoLock);
2334 * transformAlterTableStmt -
2335 * parse analysis for ALTER TABLE
2337 * Returns a List of utility commands to be done in sequence. One of these
2338 * will be the transformed AlterTableStmt, but there may be additional actions
2339 * to be done before and after the actual AlterTable() call.
2341 * To avoid race conditions, it's important that this function rely only on
2342 * the passed-in relid (and not on stmt->relation) to determine the target
2346 transformAlterTableStmt(Oid relid, AlterTableStmt *stmt,
2347 const char *queryString)
2351 CreateStmtContext cxt;
2356 List *newcmds = NIL;
2357 bool skipValidation = true;
2358 AlterTableCmd *newcmd;
2361 * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
2362 * is overkill, but easy.)
2364 stmt = (AlterTableStmt *) copyObject(stmt);
2366 /* Caller is responsible for locking the relation */
2367 rel = relation_open(relid, NoLock);
2369 /* Set up pstate and CreateStmtContext */
2370 pstate = make_parsestate(NULL);
2371 pstate->p_sourcetext = queryString;
2373 cxt.pstate = pstate;
2374 if (stmt->relkind == OBJECT_FOREIGN_TABLE)
2376 cxt.stmtType = "ALTER FOREIGN TABLE";
2377 cxt.isforeign = true;
2381 cxt.stmtType = "ALTER TABLE";
2382 cxt.isforeign = false;
2384 cxt.relation = stmt->relation;
2386 cxt.inhRelations = NIL;
2388 cxt.hasoids = false; /* need not be right */
2390 cxt.ckconstraints = NIL;
2391 cxt.fkconstraints = NIL;
2392 cxt.ixconstraints = NIL;
2393 cxt.inh_indexes = NIL;
2399 * The only subtypes that currently require parse transformation handling
2400 * are ADD COLUMN and ADD CONSTRAINT. These largely re-use code from
2403 foreach(lcmd, stmt->cmds)
2405 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2407 switch (cmd->subtype)
2410 case AT_AddColumnToView:
2412 ColumnDef *def = (ColumnDef *) cmd->def;
2414 Assert(IsA(def, ColumnDef));
2415 transformColumnDefinition(&cxt, def);
2418 * If the column has a non-null default, we can't skip
2419 * validation of foreign keys.
2421 if (def->raw_default != NULL)
2422 skipValidation = false;
2425 * All constraints are processed in other ways. Remove the
2428 def->constraints = NIL;
2430 newcmds = lappend(newcmds, cmd);
2433 case AT_AddConstraint:
2436 * The original AddConstraint cmd node doesn't go to newcmds
2438 if (IsA(cmd->def, Constraint))
2440 transformTableConstraint(&cxt, (Constraint *) cmd->def);
2441 if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
2442 skipValidation = false;
2445 elog(ERROR, "unrecognized node type: %d",
2446 (int) nodeTag(cmd->def));
2449 case AT_ProcessedConstraint:
2452 * Already-transformed ADD CONSTRAINT, so just make it look
2453 * like the standard case.
2455 cmd->subtype = AT_AddConstraint;
2456 newcmds = lappend(newcmds, cmd);
2460 newcmds = lappend(newcmds, cmd);
2466 * transformIndexConstraints wants cxt.alist to contain only index
2467 * statements, so transfer anything we already have into save_alist
2470 save_alist = cxt.alist;
2473 /* Postprocess index and FK constraints */
2474 transformIndexConstraints(&cxt);
2476 transformFKConstraints(&cxt, skipValidation, true);
2479 * Push any index-creation commands into the ALTER, so that they can be
2480 * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
2481 * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
2482 * subcommand has already been through transformIndexStmt.
2484 foreach(l, cxt.alist)
2486 IndexStmt *idxstmt = (IndexStmt *) lfirst(l);
2488 Assert(IsA(idxstmt, IndexStmt));
2489 idxstmt = transformIndexStmt(relid, idxstmt, queryString);
2490 newcmd = makeNode(AlterTableCmd);
2491 newcmd->subtype = OidIsValid(idxstmt->indexOid) ? AT_AddIndexConstraint : AT_AddIndex;
2492 newcmd->def = (Node *) idxstmt;
2493 newcmds = lappend(newcmds, newcmd);
2497 /* Append any CHECK or FK constraints to the commands list */
2498 foreach(l, cxt.ckconstraints)
2500 newcmd = makeNode(AlterTableCmd);
2501 newcmd->subtype = AT_AddConstraint;
2502 newcmd->def = (Node *) lfirst(l);
2503 newcmds = lappend(newcmds, newcmd);
2505 foreach(l, cxt.fkconstraints)
2507 newcmd = makeNode(AlterTableCmd);
2508 newcmd->subtype = AT_AddConstraint;
2509 newcmd->def = (Node *) lfirst(l);
2510 newcmds = lappend(newcmds, newcmd);
2514 relation_close(rel, NoLock);
2519 stmt->cmds = newcmds;
2521 result = lappend(cxt.blist, stmt);
2522 result = list_concat(result, cxt.alist);
2523 result = list_concat(result, save_alist);
2530 * Preprocess a list of column constraint clauses
2531 * to attach constraint attributes to their primary constraint nodes
2532 * and detect inconsistent/misplaced constraint attributes.
2534 * NOTE: currently, attributes are only supported for FOREIGN KEY, UNIQUE,
2535 * EXCLUSION, and PRIMARY KEY constraints, but someday they ought to be
2536 * supported for other constraint types.
2539 transformConstraintAttrs(CreateStmtContext *cxt, List *constraintList)
2541 Constraint *lastprimarycon = NULL;
2542 bool saw_deferrability = false;
2543 bool saw_initially = false;
2546 #define SUPPORTS_ATTRS(node) \
2547 ((node) != NULL && \
2548 ((node)->contype == CONSTR_PRIMARY || \
2549 (node)->contype == CONSTR_UNIQUE || \
2550 (node)->contype == CONSTR_EXCLUSION || \
2551 (node)->contype == CONSTR_FOREIGN))
2553 foreach(clist, constraintList)
2555 Constraint *con = (Constraint *) lfirst(clist);
2557 if (!IsA(con, Constraint))
2558 elog(ERROR, "unrecognized node type: %d",
2559 (int) nodeTag(con));
2560 switch (con->contype)
2562 case CONSTR_ATTR_DEFERRABLE:
2563 if (!SUPPORTS_ATTRS(lastprimarycon))
2565 (errcode(ERRCODE_SYNTAX_ERROR),
2566 errmsg("misplaced DEFERRABLE clause"),
2567 parser_errposition(cxt->pstate, con->location)));
2568 if (saw_deferrability)
2570 (errcode(ERRCODE_SYNTAX_ERROR),
2571 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
2572 parser_errposition(cxt->pstate, con->location)));
2573 saw_deferrability = true;
2574 lastprimarycon->deferrable = true;
2577 case CONSTR_ATTR_NOT_DEFERRABLE:
2578 if (!SUPPORTS_ATTRS(lastprimarycon))
2580 (errcode(ERRCODE_SYNTAX_ERROR),
2581 errmsg("misplaced NOT DEFERRABLE clause"),
2582 parser_errposition(cxt->pstate, con->location)));
2583 if (saw_deferrability)
2585 (errcode(ERRCODE_SYNTAX_ERROR),
2586 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
2587 parser_errposition(cxt->pstate, con->location)));
2588 saw_deferrability = true;
2589 lastprimarycon->deferrable = false;
2590 if (saw_initially &&
2591 lastprimarycon->initdeferred)
2593 (errcode(ERRCODE_SYNTAX_ERROR),
2594 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2595 parser_errposition(cxt->pstate, con->location)));
2598 case CONSTR_ATTR_DEFERRED:
2599 if (!SUPPORTS_ATTRS(lastprimarycon))
2601 (errcode(ERRCODE_SYNTAX_ERROR),
2602 errmsg("misplaced INITIALLY DEFERRED clause"),
2603 parser_errposition(cxt->pstate, con->location)));
2606 (errcode(ERRCODE_SYNTAX_ERROR),
2607 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
2608 parser_errposition(cxt->pstate, con->location)));
2609 saw_initially = true;
2610 lastprimarycon->initdeferred = true;
2613 * If only INITIALLY DEFERRED appears, assume DEFERRABLE
2615 if (!saw_deferrability)
2616 lastprimarycon->deferrable = true;
2617 else if (!lastprimarycon->deferrable)
2619 (errcode(ERRCODE_SYNTAX_ERROR),
2620 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2621 parser_errposition(cxt->pstate, con->location)));
2624 case CONSTR_ATTR_IMMEDIATE:
2625 if (!SUPPORTS_ATTRS(lastprimarycon))
2627 (errcode(ERRCODE_SYNTAX_ERROR),
2628 errmsg("misplaced INITIALLY IMMEDIATE clause"),
2629 parser_errposition(cxt->pstate, con->location)));
2632 (errcode(ERRCODE_SYNTAX_ERROR),
2633 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
2634 parser_errposition(cxt->pstate, con->location)));
2635 saw_initially = true;
2636 lastprimarycon->initdeferred = false;
2640 /* Otherwise it's not an attribute */
2641 lastprimarycon = con;
2642 /* reset flags for new primary node */
2643 saw_deferrability = false;
2644 saw_initially = false;
2651 * Special handling of type definition for a column
2654 transformColumnType(CreateStmtContext *cxt, ColumnDef *column)
2657 * All we really need to do here is verify that the type is valid,
2658 * including any collation spec that might be present.
2660 Type ctype = typenameType(cxt->pstate, column->typeName, NULL);
2662 if (column->collClause)
2664 Form_pg_type typtup = (Form_pg_type) GETSTRUCT(ctype);
2666 LookupCollation(cxt->pstate,
2667 column->collClause->collname,
2668 column->collClause->location);
2669 /* Complain if COLLATE is applied to an uncollatable type */
2670 if (!OidIsValid(typtup->typcollation))
2672 (errcode(ERRCODE_DATATYPE_MISMATCH),
2673 errmsg("collations are not supported by type %s",
2674 format_type_be(HeapTupleGetOid(ctype))),
2675 parser_errposition(cxt->pstate,
2676 column->collClause->location)));
2679 ReleaseSysCache(ctype);
2684 * transformCreateSchemaStmt -
2685 * analyzes the CREATE SCHEMA statement
2687 * Split the schema element list into individual commands and place
2688 * them in the result list in an order such that there are no forward
2689 * references (e.g. GRANT to a table created later in the list). Note
2690 * that the logic we use for determining forward references is
2691 * presently quite incomplete.
2693 * SQL also allows constraints to make forward references, so thumb through
2694 * the table columns and move forward references to a posterior alter-table
2697 * The result is a list of parse nodes that still need to be analyzed ---
2698 * but we can't analyze the later commands until we've executed the earlier
2699 * ones, because of possible inter-object references.
2701 * Note: this breaks the rules a little bit by modifying schema-name fields
2702 * within passed-in structs. However, the transformation would be the same
2703 * if done over, so it should be all right to scribble on the input to this
2707 transformCreateSchemaStmt(CreateSchemaStmt *stmt)
2709 CreateSchemaStmtContext cxt;
2713 cxt.stmtType = "CREATE SCHEMA";
2714 cxt.schemaname = stmt->schemaname;
2715 cxt.authid = stmt->authid;
2716 cxt.sequences = NIL;
2724 * Run through each schema element in the schema element list. Separate
2725 * statements by type, and do preliminary analysis.
2727 foreach(elements, stmt->schemaElts)
2729 Node *element = lfirst(elements);
2731 switch (nodeTag(element))
2733 case T_CreateSeqStmt:
2735 CreateSeqStmt *elp = (CreateSeqStmt *) element;
2737 setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
2738 cxt.sequences = lappend(cxt.sequences, element);
2744 CreateStmt *elp = (CreateStmt *) element;
2746 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2749 * XXX todo: deal with constraints
2751 cxt.tables = lappend(cxt.tables, element);
2757 ViewStmt *elp = (ViewStmt *) element;
2759 setSchemaName(cxt.schemaname, &elp->view->schemaname);
2762 * XXX todo: deal with references between views
2764 cxt.views = lappend(cxt.views, element);
2770 IndexStmt *elp = (IndexStmt *) element;
2772 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2773 cxt.indexes = lappend(cxt.indexes, element);
2777 case T_CreateTrigStmt:
2779 CreateTrigStmt *elp = (CreateTrigStmt *) element;
2781 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2782 cxt.triggers = lappend(cxt.triggers, element);
2787 cxt.grants = lappend(cxt.grants, element);
2791 elog(ERROR, "unrecognized node type: %d",
2792 (int) nodeTag(element));
2797 result = list_concat(result, cxt.sequences);
2798 result = list_concat(result, cxt.tables);
2799 result = list_concat(result, cxt.views);
2800 result = list_concat(result, cxt.indexes);
2801 result = list_concat(result, cxt.triggers);
2802 result = list_concat(result, cxt.grants);
2809 * Set or check schema name in an element of a CREATE SCHEMA command
2812 setSchemaName(char *context_schema, char **stmt_schema_name)
2814 if (*stmt_schema_name == NULL)
2815 *stmt_schema_name = context_schema;
2816 else if (strcmp(context_schema, *stmt_schema_name) != 0)
2818 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
2819 errmsg("CREATE specifies a schema (%s) "
2820 "different from the one being created (%s)",
2821 *stmt_schema_name, context_schema)));