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-2016, 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/amapi.h"
30 #include "access/htup_details.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_am.h"
37 #include "catalog/pg_collation.h"
38 #include "catalog/pg_constraint.h"
39 #include "catalog/pg_constraint_fn.h"
40 #include "catalog/pg_opclass.h"
41 #include "catalog/pg_operator.h"
42 #include "catalog/pg_type.h"
43 #include "commands/comment.h"
44 #include "commands/defrem.h"
45 #include "commands/tablecmds.h"
46 #include "commands/tablespace.h"
47 #include "miscadmin.h"
48 #include "nodes/makefuncs.h"
49 #include "nodes/nodeFuncs.h"
50 #include "parser/analyze.h"
51 #include "parser/parse_clause.h"
52 #include "parser/parse_collate.h"
53 #include "parser/parse_expr.h"
54 #include "parser/parse_relation.h"
55 #include "parser/parse_target.h"
56 #include "parser/parse_type.h"
57 #include "parser/parse_utilcmd.h"
58 #include "parser/parser.h"
59 #include "rewrite/rewriteManip.h"
60 #include "utils/acl.h"
61 #include "utils/builtins.h"
62 #include "utils/guc.h"
63 #include "utils/lsyscache.h"
64 #include "utils/rel.h"
65 #include "utils/syscache.h"
66 #include "utils/typcache.h"
69 /* State shared by transformCreateStmt and its subroutines */
72 ParseState *pstate; /* overall parser state */
73 const char *stmtType; /* "CREATE [FOREIGN] TABLE" or "ALTER TABLE" */
74 RangeVar *relation; /* relation to create */
75 Relation rel; /* opened/locked rel, if ALTER */
76 List *inhRelations; /* relations to inherit from */
77 bool isforeign; /* true if CREATE/ALTER FOREIGN TABLE */
78 bool isalter; /* true if altering existing table */
79 bool hasoids; /* does relation have an OID column? */
80 List *columns; /* ColumnDef items */
81 List *ckconstraints; /* CHECK constraints */
82 List *fkconstraints; /* FOREIGN KEY constraints */
83 List *ixconstraints; /* index-creating constraints */
84 List *inh_indexes; /* cloned indexes from INCLUDING INDEXES */
85 List *blist; /* "before list" of things to do before
86 * creating the table */
87 List *alist; /* "after list" of things to do after creating
89 IndexStmt *pkey; /* PRIMARY KEY index, if any */
92 /* State shared by transformCreateSchemaStmt and its subroutines */
95 const char *stmtType; /* "CREATE SCHEMA" or "ALTER SCHEMA" */
96 char *schemaname; /* name of schema */
97 RoleSpec *authrole; /* owner of schema */
98 List *sequences; /* CREATE SEQUENCE items */
99 List *tables; /* CREATE TABLE items */
100 List *views; /* CREATE VIEW items */
101 List *indexes; /* CREATE INDEX items */
102 List *triggers; /* CREATE TRIGGER items */
103 List *grants; /* GRANT items */
104 } CreateSchemaStmtContext;
107 static void transformColumnDefinition(CreateStmtContext *cxt,
109 static void transformTableConstraint(CreateStmtContext *cxt,
110 Constraint *constraint);
111 static void transformTableLikeClause(CreateStmtContext *cxt,
112 TableLikeClause *table_like_clause);
113 static void transformOfType(CreateStmtContext *cxt,
114 TypeName *ofTypename);
115 static IndexStmt *generateClonedIndexStmt(CreateStmtContext *cxt,
117 const AttrNumber *attmap, int attmap_length);
118 static List *get_collation(Oid collation, Oid actual_datatype);
119 static List *get_opclass(Oid opclass, Oid actual_datatype);
120 static void transformIndexConstraints(CreateStmtContext *cxt);
121 static IndexStmt *transformIndexConstraint(Constraint *constraint,
122 CreateStmtContext *cxt);
123 static void transformFKConstraints(CreateStmtContext *cxt,
125 bool isAddConstraint);
126 static void transformCheckConstraints(CreateStmtContext *cxt,
127 bool skipValidation);
128 static void transformConstraintAttrs(CreateStmtContext *cxt,
129 List *constraintList);
130 static void transformColumnType(CreateStmtContext *cxt, ColumnDef *column);
131 static void setSchemaName(char *context_schema, char **stmt_schema_name);
135 * transformCreateStmt -
136 * parse analysis for CREATE TABLE
138 * Returns a List of utility commands to be done in sequence. One of these
139 * will be the transformed CreateStmt, but there may be additional actions
140 * to be done before and after the actual DefineRelation() call.
142 * SQL allows constraints to be scattered all over, so thumb through
143 * the columns and collect all constraints into one place.
144 * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
145 * then expand those into multiple IndexStmt blocks.
146 * - thomas 1997-12-02
149 transformCreateStmt(CreateStmt *stmt, const char *queryString)
152 CreateStmtContext cxt;
158 ParseCallbackState pcbstate;
159 bool like_found = false;
162 * We must not scribble on the passed-in CreateStmt, so copy it. (This is
163 * overkill, but easy.)
165 stmt = (CreateStmt *) copyObject(stmt);
168 pstate = make_parsestate(NULL);
169 pstate->p_sourcetext = queryString;
172 * Look up the creation namespace. This also checks permissions on the
173 * target namespace, locks it against concurrent drops, checks for a
174 * preexisting relation in that namespace with the same name, and updates
175 * stmt->relation->relpersistence if the selected namespace is temporary.
177 setup_parser_errposition_callback(&pcbstate, pstate,
178 stmt->relation->location);
180 RangeVarGetAndCheckCreationNamespace(stmt->relation, NoLock,
182 cancel_parser_errposition_callback(&pcbstate);
185 * If the relation already exists and the user specified "IF NOT EXISTS",
186 * bail out with a NOTICE.
188 if (stmt->if_not_exists && OidIsValid(existing_relid))
191 (errcode(ERRCODE_DUPLICATE_TABLE),
192 errmsg("relation \"%s\" already exists, skipping",
193 stmt->relation->relname)));
198 * If the target relation name isn't schema-qualified, make it so. This
199 * prevents some corner cases in which added-on rewritten commands might
200 * think they should apply to other relations that have the same name and
201 * are earlier in the search path. But a local temp table is effectively
202 * specified to be in pg_temp, so no need for anything extra in that case.
204 if (stmt->relation->schemaname == NULL
205 && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
206 stmt->relation->schemaname = get_namespace_name(namespaceid);
208 /* Set up CreateStmtContext */
210 if (IsA(stmt, CreateForeignTableStmt))
212 cxt.stmtType = "CREATE FOREIGN TABLE";
213 cxt.isforeign = true;
217 cxt.stmtType = "CREATE TABLE";
218 cxt.isforeign = false;
220 cxt.relation = stmt->relation;
222 cxt.inhRelations = stmt->inhRelations;
225 cxt.ckconstraints = NIL;
226 cxt.fkconstraints = NIL;
227 cxt.ixconstraints = NIL;
228 cxt.inh_indexes = NIL;
234 * Notice that we allow OIDs here only for plain tables, even though
235 * foreign tables also support them. This is necessary because the
236 * default_with_oids GUC must apply only to plain tables and not any other
237 * relkind; doing otherwise would break existing pg_dump files. We could
238 * allow explicit "WITH OIDS" while not allowing default_with_oids to
239 * affect other relkinds, but it would complicate interpretOidsOption(),
240 * and right now there's no WITH OIDS option in CREATE FOREIGN TABLE
243 cxt.hasoids = interpretOidsOption(stmt->options, !cxt.isforeign);
245 Assert(!stmt->ofTypename || !stmt->inhRelations); /* grammar enforces */
247 if (stmt->ofTypename)
248 transformOfType(&cxt, stmt->ofTypename);
251 * Run through each primary element in the table creation clause. Separate
252 * column defs from constraints, and do preliminary analysis. We have to
253 * process column-defining clauses first because it can control the
254 * presence of columns which are referenced by columns referenced by
257 foreach(elements, stmt->tableElts)
259 Node *element = lfirst(elements);
261 switch (nodeTag(element))
264 transformColumnDefinition(&cxt, (ColumnDef *) element);
267 case T_TableLikeClause:
273 transformTableLikeClause(&cxt, (TableLikeClause *) element);
281 elog(ERROR, "unrecognized node type: %d",
282 (int) nodeTag(element));
290 * To match INHERITS, the existence of any LIKE table with OIDs
291 * causes the new table to have oids. For the same reason,
292 * WITH/WITHOUT OIDs is also ignored with LIKE. We prepend
293 * because the first oid option list entry is honored. Our
294 * prepended WITHOUT OIDS clause will be overridden if an
295 * inherited table has oids.
297 stmt->options = lcons(makeDefElem("oids",
298 (Node *)makeInteger(cxt.hasoids)), stmt->options);
301 foreach(elements, stmt->tableElts)
303 Node *element = lfirst(elements);
305 if (nodeTag(element) == T_Constraint)
306 transformTableConstraint(&cxt, (Constraint *) element);
309 * transformIndexConstraints wants cxt.alist to contain only index
310 * statements, so transfer anything we already have into save_alist.
312 save_alist = cxt.alist;
315 Assert(stmt->constraints == NIL);
318 * Postprocess constraints that give rise to index definitions.
320 transformIndexConstraints(&cxt);
323 * Postprocess foreign-key constraints.
325 transformFKConstraints(&cxt, true, false);
328 * Postprocess check constraints.
330 transformCheckConstraints(&cxt, true);
335 stmt->tableElts = cxt.columns;
336 stmt->constraints = cxt.ckconstraints;
338 result = lappend(cxt.blist, stmt);
339 result = list_concat(result, cxt.alist);
340 result = list_concat(result, save_alist);
346 * transformColumnDefinition -
347 * transform a single ColumnDef within CREATE TABLE
348 * Also used in ALTER TABLE ADD COLUMN
351 transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
356 Constraint *constraint;
359 cxt->columns = lappend(cxt->columns, column);
361 /* Check for SERIAL pseudo-types */
364 && list_length(column->typeName->names) == 1
365 && !column->typeName->pct_type)
367 char *typname = strVal(linitial(column->typeName->names));
369 if (strcmp(typname, "smallserial") == 0 ||
370 strcmp(typname, "serial2") == 0)
373 column->typeName->names = NIL;
374 column->typeName->typeOid = INT2OID;
376 else if (strcmp(typname, "serial") == 0 ||
377 strcmp(typname, "serial4") == 0)
380 column->typeName->names = NIL;
381 column->typeName->typeOid = INT4OID;
383 else if (strcmp(typname, "bigserial") == 0 ||
384 strcmp(typname, "serial8") == 0)
387 column->typeName->names = NIL;
388 column->typeName->typeOid = INT8OID;
392 * We have to reject "serial[]" explicitly, because once we've set
393 * typeid, LookupTypeName won't notice arrayBounds. We don't need any
394 * special coding for serial(typmod) though.
396 if (is_serial && column->typeName->arrayBounds != NIL)
398 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
399 errmsg("array of serial is not implemented"),
400 parser_errposition(cxt->pstate,
401 column->typeName->location)));
404 /* Do necessary work on the column type declaration */
405 if (column->typeName)
406 transformColumnType(cxt, column);
408 /* Special actions for SERIAL pseudo-types */
417 FuncCall *funccallnode;
418 CreateSeqStmt *seqstmt;
419 AlterSeqStmt *altseqstmt;
423 * Determine namespace and name to use for the sequence.
425 * Although we use ChooseRelationName, it's not guaranteed that the
426 * selected sequence name won't conflict; given sufficiently long
427 * field names, two different serial columns in the same table could
428 * be assigned the same sequence name, and we'd not notice since we
429 * aren't creating the sequence quite yet. In practice this seems
430 * quite unlikely to be a problem, especially since few people would
431 * need two serial columns in one table.
434 snamespaceid = RelationGetNamespace(cxt->rel);
437 snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
438 RangeVarAdjustRelationPersistence(cxt->relation, snamespaceid);
440 snamespace = get_namespace_name(snamespaceid);
441 sname = ChooseRelationName(cxt->relation->relname,
447 (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
448 cxt->stmtType, sname,
449 cxt->relation->relname, column->colname)));
452 * Build a CREATE SEQUENCE command to create the sequence object, and
453 * add it to the list of things to be done before this CREATE/ALTER
456 seqstmt = makeNode(CreateSeqStmt);
457 seqstmt->sequence = makeRangeVar(snamespace, sname, -1);
458 seqstmt->options = NIL;
461 * If this is ALTER ADD COLUMN, make sure the sequence will be owned
462 * by the table's owner. The current user might be someone else
463 * (perhaps a superuser, or someone who's only a member of the owning
464 * role), but the SEQUENCE OWNED BY mechanisms will bleat unless table
465 * and sequence have exactly the same owning role.
468 seqstmt->ownerId = cxt->rel->rd_rel->relowner;
470 seqstmt->ownerId = InvalidOid;
472 cxt->blist = lappend(cxt->blist, seqstmt);
475 * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence
476 * as owned by this column, and add it to the list of things to be
477 * done after this CREATE/ALTER TABLE.
479 altseqstmt = makeNode(AlterSeqStmt);
480 altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
481 attnamelist = list_make3(makeString(snamespace),
482 makeString(cxt->relation->relname),
483 makeString(column->colname));
484 altseqstmt->options = list_make1(makeDefElem("owned_by",
485 (Node *) attnamelist));
487 cxt->alist = lappend(cxt->alist, altseqstmt);
490 * Create appropriate constraints for SERIAL. We do this in full,
491 * rather than shortcutting, so that we will detect any conflicting
492 * constraints the user wrote (like a different DEFAULT).
494 * Create an expression tree representing the function call
495 * nextval('sequencename'). We cannot reduce the raw tree to cooked
496 * form until after the sequence is created, but there's no need to do
499 qstring = quote_qualified_identifier(snamespace, sname);
500 snamenode = makeNode(A_Const);
501 snamenode->val.type = T_String;
502 snamenode->val.val.str = qstring;
503 snamenode->location = -1;
504 castnode = makeNode(TypeCast);
505 castnode->typeName = SystemTypeName("regclass");
506 castnode->arg = (Node *) snamenode;
507 castnode->location = -1;
508 funccallnode = makeFuncCall(SystemFuncName("nextval"),
509 list_make1(castnode),
511 constraint = makeNode(Constraint);
512 constraint->contype = CONSTR_DEFAULT;
513 constraint->location = -1;
514 constraint->raw_expr = (Node *) funccallnode;
515 constraint->cooked_expr = NULL;
516 column->constraints = lappend(column->constraints, constraint);
518 constraint = makeNode(Constraint);
519 constraint->contype = CONSTR_NOTNULL;
520 constraint->location = -1;
521 column->constraints = lappend(column->constraints, constraint);
524 /* Process column constraints, if any... */
525 transformConstraintAttrs(cxt, column->constraints);
527 saw_nullable = false;
530 foreach(clist, column->constraints)
532 constraint = lfirst(clist);
533 Assert(IsA(constraint, Constraint));
535 switch (constraint->contype)
538 if (saw_nullable && column->is_not_null)
540 (errcode(ERRCODE_SYNTAX_ERROR),
541 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
542 column->colname, cxt->relation->relname),
543 parser_errposition(cxt->pstate,
544 constraint->location)));
545 column->is_not_null = FALSE;
550 if (saw_nullable && !column->is_not_null)
552 (errcode(ERRCODE_SYNTAX_ERROR),
553 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
554 column->colname, cxt->relation->relname),
555 parser_errposition(cxt->pstate,
556 constraint->location)));
557 column->is_not_null = TRUE;
564 (errcode(ERRCODE_SYNTAX_ERROR),
565 errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
566 column->colname, cxt->relation->relname),
567 parser_errposition(cxt->pstate,
568 constraint->location)));
569 column->raw_default = constraint->raw_expr;
570 Assert(constraint->cooked_expr == NULL);
575 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
581 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
582 errmsg("primary key constraints are not supported on foreign tables"),
583 parser_errposition(cxt->pstate,
584 constraint->location)));
590 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
591 errmsg("unique constraints are not supported on foreign tables"),
592 parser_errposition(cxt->pstate,
593 constraint->location)));
594 if (constraint->keys == NIL)
595 constraint->keys = list_make1(makeString(column->colname));
596 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
599 case CONSTR_EXCLUSION:
600 /* grammar does not allow EXCLUDE as a column constraint */
601 elog(ERROR, "column exclusion constraints are not supported");
607 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
608 errmsg("foreign key constraints are not supported on foreign tables"),
609 parser_errposition(cxt->pstate,
610 constraint->location)));
613 * Fill in the current attribute's name and throw it into the
614 * list of FK constraints to be processed later.
616 constraint->fk_attrs = list_make1(makeString(column->colname));
617 cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
620 case CONSTR_ATTR_DEFERRABLE:
621 case CONSTR_ATTR_NOT_DEFERRABLE:
622 case CONSTR_ATTR_DEFERRED:
623 case CONSTR_ATTR_IMMEDIATE:
624 /* transformConstraintAttrs took care of these */
628 elog(ERROR, "unrecognized constraint type: %d",
629 constraint->contype);
635 * If needed, generate ALTER FOREIGN TABLE ALTER COLUMN statement to add
636 * per-column foreign data wrapper options to this column after creation.
638 if (column->fdwoptions != NIL)
640 AlterTableStmt *stmt;
643 cmd = makeNode(AlterTableCmd);
644 cmd->subtype = AT_AlterColumnGenericOptions;
645 cmd->name = column->colname;
646 cmd->def = (Node *) column->fdwoptions;
647 cmd->behavior = DROP_RESTRICT;
648 cmd->missing_ok = false;
650 stmt = makeNode(AlterTableStmt);
651 stmt->relation = cxt->relation;
653 stmt->relkind = OBJECT_FOREIGN_TABLE;
654 stmt->cmds = lappend(stmt->cmds, cmd);
656 cxt->alist = lappend(cxt->alist, stmt);
661 * transformTableConstraint
662 * transform a Constraint node within CREATE TABLE or ALTER TABLE
665 transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
667 switch (constraint->contype)
672 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
673 errmsg("primary key constraints are not supported on foreign tables"),
674 parser_errposition(cxt->pstate,
675 constraint->location)));
676 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
682 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
683 errmsg("unique constraints are not supported on foreign tables"),
684 parser_errposition(cxt->pstate,
685 constraint->location)));
686 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
689 case CONSTR_EXCLUSION:
692 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
693 errmsg("exclusion constraints are not supported on foreign tables"),
694 parser_errposition(cxt->pstate,
695 constraint->location)));
696 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
700 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
706 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
707 errmsg("foreign key constraints are not supported on foreign tables"),
708 parser_errposition(cxt->pstate,
709 constraint->location)));
710 cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
716 case CONSTR_ATTR_DEFERRABLE:
717 case CONSTR_ATTR_NOT_DEFERRABLE:
718 case CONSTR_ATTR_DEFERRED:
719 case CONSTR_ATTR_IMMEDIATE:
720 elog(ERROR, "invalid context for constraint type %d",
721 constraint->contype);
725 elog(ERROR, "unrecognized constraint type: %d",
726 constraint->contype);
732 * transformTableLikeClause
734 * Change the LIKE <srctable> portion of a CREATE TABLE statement into
735 * column definitions which recreate the user defined column portions of
739 transformTableLikeClause(CreateStmtContext *cxt, TableLikeClause *table_like_clause)
741 AttrNumber parent_attno;
748 ParseCallbackState pcbstate;
750 setup_parser_errposition_callback(&pcbstate, cxt->pstate,
751 table_like_clause->relation->location);
753 /* we could support LIKE in many cases, but worry about it another day */
756 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
757 errmsg("LIKE is not supported for creating foreign tables")));
759 relation = relation_openrv(table_like_clause->relation, AccessShareLock);
761 if (relation->rd_rel->relkind != RELKIND_RELATION &&
762 relation->rd_rel->relkind != RELKIND_VIEW &&
763 relation->rd_rel->relkind != RELKIND_MATVIEW &&
764 relation->rd_rel->relkind != RELKIND_COMPOSITE_TYPE &&
765 relation->rd_rel->relkind != RELKIND_FOREIGN_TABLE)
767 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
768 errmsg("\"%s\" is not a table, view, materialized view, composite type, or foreign table",
769 RelationGetRelationName(relation))));
771 cancel_parser_errposition_callback(&pcbstate);
774 * Check for privileges
776 if (relation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
778 aclresult = pg_type_aclcheck(relation->rd_rel->reltype, GetUserId(),
780 if (aclresult != ACLCHECK_OK)
781 aclcheck_error(aclresult, ACL_KIND_TYPE,
782 RelationGetRelationName(relation));
786 aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
788 if (aclresult != ACLCHECK_OK)
789 aclcheck_error(aclresult, ACL_KIND_CLASS,
790 RelationGetRelationName(relation));
793 tupleDesc = RelationGetDescr(relation);
794 constr = tupleDesc->constr;
797 * Initialize column number map for map_variable_attnos(). We need this
798 * since dropped columns in the source table aren't copied, so the new
799 * table can have different column numbers.
801 attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * tupleDesc->natts);
804 * Insert the copied attributes into the cxt for the new table definition.
806 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
809 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
810 char *attributeName = NameStr(attribute->attname);
814 * Ignore dropped columns in the parent. attmap entry is left zero.
816 if (attribute->attisdropped)
820 * Create a new column, which is marked as NOT inherited.
822 * For constraints, ONLY the NOT NULL constraint is inherited by the
823 * new column definition per SQL99.
825 def = makeNode(ColumnDef);
826 def->colname = pstrdup(attributeName);
827 def->typeName = makeTypeNameFromOid(attribute->atttypid,
828 attribute->atttypmod);
830 def->is_local = true;
831 def->is_not_null = attribute->attnotnull;
832 def->is_from_type = false;
834 def->raw_default = NULL;
835 def->cooked_default = NULL;
836 def->collClause = NULL;
837 def->collOid = attribute->attcollation;
838 def->constraints = NIL;
844 cxt->columns = lappend(cxt->columns, def);
846 attmap[parent_attno - 1] = list_length(cxt->columns);
849 * Copy default, if present and the default has been requested
851 if (attribute->atthasdef &&
852 (table_like_clause->options & CREATE_TABLE_LIKE_DEFAULTS))
854 Node *this_default = NULL;
855 AttrDefault *attrdef;
858 /* Find default in constraint structure */
859 Assert(constr != NULL);
860 attrdef = constr->defval;
861 for (i = 0; i < constr->num_defval; i++)
863 if (attrdef[i].adnum == parent_attno)
865 this_default = stringToNode(attrdef[i].adbin);
869 Assert(this_default != NULL);
872 * If default expr could contain any vars, we'd need to fix 'em,
873 * but it can't; so default is ready to apply to child.
876 def->cooked_default = this_default;
879 /* Likewise, copy storage if requested */
880 if (table_like_clause->options & CREATE_TABLE_LIKE_STORAGE)
881 def->storage = attribute->attstorage;
885 /* Likewise, copy comment if requested */
886 if ((table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS) &&
887 (comment = GetComment(attribute->attrelid,
889 attribute->attnum)) != NULL)
891 CommentStmt *stmt = makeNode(CommentStmt);
893 stmt->objtype = OBJECT_COLUMN;
894 stmt->objname = list_make3(makeString(cxt->relation->schemaname),
895 makeString(cxt->relation->relname),
896 makeString(def->colname));
898 stmt->comment = comment;
900 cxt->alist = lappend(cxt->alist, stmt);
904 /* We use oids if at least one LIKE'ed table has oids. */
905 cxt->hasoids = cxt->hasoids || relation->rd_rel->relhasoids;
908 * Copy CHECK constraints if requested, being careful to adjust attribute
909 * numbers so they match the child.
911 if ((table_like_clause->options & CREATE_TABLE_LIKE_CONSTRAINTS) &&
916 for (ccnum = 0; ccnum < tupleDesc->constr->num_check; ccnum++)
918 char *ccname = tupleDesc->constr->check[ccnum].ccname;
919 char *ccbin = tupleDesc->constr->check[ccnum].ccbin;
920 Constraint *n = makeNode(Constraint);
922 bool found_whole_row;
924 ccbin_node = map_variable_attnos(stringToNode(ccbin),
926 attmap, tupleDesc->natts,
930 * We reject whole-row variables because the whole point of LIKE
931 * is that the new table's rowtype might later diverge from the
932 * parent's. So, while translation might be possible right now,
933 * it wouldn't be possible to guarantee it would work in future.
937 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
938 errmsg("cannot convert whole-row table reference"),
939 errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
941 RelationGetRelationName(relation))));
943 n->contype = CONSTR_CHECK;
945 n->conname = pstrdup(ccname);
947 n->cooked_expr = nodeToString(ccbin_node);
948 cxt->ckconstraints = lappend(cxt->ckconstraints, n);
950 /* Copy comment on constraint */
951 if ((table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS) &&
952 (comment = GetComment(get_relation_constraint_oid(RelationGetRelid(relation),
954 ConstraintRelationId,
957 CommentStmt *stmt = makeNode(CommentStmt);
959 stmt->objtype = OBJECT_TABCONSTRAINT;
960 stmt->objname = list_make3(makeString(cxt->relation->schemaname),
961 makeString(cxt->relation->relname),
962 makeString(n->conname));
964 stmt->comment = comment;
966 cxt->alist = lappend(cxt->alist, stmt);
972 * Likewise, copy indexes if requested
974 if ((table_like_clause->options & CREATE_TABLE_LIKE_INDEXES) &&
975 relation->rd_rel->relhasindex)
977 List *parent_indexes;
980 parent_indexes = RelationGetIndexList(relation);
982 foreach(l, parent_indexes)
984 Oid parent_index_oid = lfirst_oid(l);
985 Relation parent_index;
986 IndexStmt *index_stmt;
988 parent_index = index_open(parent_index_oid, AccessShareLock);
990 /* Build CREATE INDEX statement to recreate the parent_index */
991 index_stmt = generateClonedIndexStmt(cxt, parent_index,
992 attmap, tupleDesc->natts);
994 /* Copy comment on index, if requested */
995 if (table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS)
997 comment = GetComment(parent_index_oid, RelationRelationId, 0);
1000 * We make use of IndexStmt's idxcomment option, so as not to
1001 * need to know now what name the index will have.
1003 index_stmt->idxcomment = comment;
1006 /* Save it in the inh_indexes list for the time being */
1007 cxt->inh_indexes = lappend(cxt->inh_indexes, index_stmt);
1009 index_close(parent_index, AccessShareLock);
1014 * Close the parent rel, but keep our AccessShareLock on it until xact
1015 * commit. That will prevent someone else from deleting or ALTERing the
1016 * parent before the child is committed.
1018 heap_close(relation, NoLock);
1022 transformOfType(CreateStmtContext *cxt, TypeName *ofTypename)
1029 AssertArg(ofTypename);
1031 tuple = typenameType(NULL, ofTypename, NULL);
1032 check_of_type(tuple);
1033 ofTypeId = HeapTupleGetOid(tuple);
1034 ofTypename->typeOid = ofTypeId; /* cached for later */
1036 tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
1037 for (i = 0; i < tupdesc->natts; i++)
1039 Form_pg_attribute attr = tupdesc->attrs[i];
1042 if (attr->attisdropped)
1045 n = makeNode(ColumnDef);
1046 n->colname = pstrdup(NameStr(attr->attname));
1047 n->typeName = makeTypeNameFromOid(attr->atttypid, attr->atttypmod);
1050 n->is_not_null = false;
1051 n->is_from_type = true;
1053 n->raw_default = NULL;
1054 n->cooked_default = NULL;
1055 n->collClause = NULL;
1056 n->collOid = attr->attcollation;
1057 n->constraints = NIL;
1059 cxt->columns = lappend(cxt->columns, n);
1061 DecrTupleDescRefCount(tupdesc);
1063 ReleaseSysCache(tuple);
1067 * Generate an IndexStmt node using information from an already existing index
1068 * "source_idx". Attribute numbers should be adjusted according to attmap.
1071 generateClonedIndexStmt(CreateStmtContext *cxt, Relation source_idx,
1072 const AttrNumber *attmap, int attmap_length)
1074 Oid source_relid = RelationGetRelid(source_idx);
1075 Form_pg_attribute *attrs = RelationGetDescr(source_idx)->attrs;
1076 HeapTuple ht_idxrel;
1079 Form_pg_class idxrelrec;
1080 Form_pg_index idxrec;
1082 oidvector *indcollation;
1083 oidvector *indclass;
1086 ListCell *indexpr_item;
1094 * Fetch pg_class tuple of source index. We can't use the copy in the
1095 * relcache entry because it doesn't include optional fields.
1097 ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(source_relid));
1098 if (!HeapTupleIsValid(ht_idxrel))
1099 elog(ERROR, "cache lookup failed for relation %u", source_relid);
1100 idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
1102 /* Fetch pg_index tuple for source index from relcache entry */
1103 ht_idx = source_idx->rd_indextuple;
1104 idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
1105 indrelid = idxrec->indrelid;
1107 /* Fetch the pg_am tuple of the index' access method */
1108 ht_am = SearchSysCache1(AMOID, ObjectIdGetDatum(idxrelrec->relam));
1109 if (!HeapTupleIsValid(ht_am))
1110 elog(ERROR, "cache lookup failed for access method %u",
1112 amrec = (Form_pg_am) GETSTRUCT(ht_am);
1114 /* Extract indcollation from the pg_index tuple */
1115 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1116 Anum_pg_index_indcollation, &isnull);
1118 indcollation = (oidvector *) DatumGetPointer(datum);
1120 /* Extract indclass from the pg_index tuple */
1121 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1122 Anum_pg_index_indclass, &isnull);
1124 indclass = (oidvector *) DatumGetPointer(datum);
1126 /* Begin building the IndexStmt */
1127 index = makeNode(IndexStmt);
1128 index->relation = cxt->relation;
1129 index->accessMethod = pstrdup(NameStr(amrec->amname));
1130 if (OidIsValid(idxrelrec->reltablespace))
1131 index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
1133 index->tableSpace = NULL;
1134 index->excludeOpNames = NIL;
1135 index->idxcomment = NULL;
1136 index->indexOid = InvalidOid;
1137 index->oldNode = InvalidOid;
1138 index->unique = idxrec->indisunique;
1139 index->primary = idxrec->indisprimary;
1140 index->transformed = true; /* don't need transformIndexStmt */
1141 index->concurrent = false;
1142 index->if_not_exists = false;
1145 * We don't try to preserve the name of the source index; instead, just
1146 * let DefineIndex() choose a reasonable name.
1148 index->idxname = NULL;
1151 * If the index is marked PRIMARY or has an exclusion condition, it's
1152 * certainly from a constraint; else, if it's not marked UNIQUE, it
1153 * certainly isn't. If it is or might be from a constraint, we have to
1154 * fetch the pg_constraint record.
1156 if (index->primary || index->unique || idxrec->indisexclusion)
1158 Oid constraintId = get_index_constraint(source_relid);
1160 if (OidIsValid(constraintId))
1162 HeapTuple ht_constr;
1163 Form_pg_constraint conrec;
1165 ht_constr = SearchSysCache1(CONSTROID,
1166 ObjectIdGetDatum(constraintId));
1167 if (!HeapTupleIsValid(ht_constr))
1168 elog(ERROR, "cache lookup failed for constraint %u",
1170 conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
1172 index->isconstraint = true;
1173 index->deferrable = conrec->condeferrable;
1174 index->initdeferred = conrec->condeferred;
1176 /* If it's an exclusion constraint, we need the operator names */
1177 if (idxrec->indisexclusion)
1183 Assert(conrec->contype == CONSTRAINT_EXCLUSION);
1184 /* Extract operator OIDs from the pg_constraint tuple */
1185 datum = SysCacheGetAttr(CONSTROID, ht_constr,
1186 Anum_pg_constraint_conexclop,
1189 elog(ERROR, "null conexclop for constraint %u",
1192 deconstruct_array(DatumGetArrayTypeP(datum),
1193 OIDOID, sizeof(Oid), true, 'i',
1194 &elems, NULL, &nElems);
1196 for (i = 0; i < nElems; i++)
1198 Oid operid = DatumGetObjectId(elems[i]);
1200 Form_pg_operator operform;
1205 opertup = SearchSysCache1(OPEROID,
1206 ObjectIdGetDatum(operid));
1207 if (!HeapTupleIsValid(opertup))
1208 elog(ERROR, "cache lookup failed for operator %u",
1210 operform = (Form_pg_operator) GETSTRUCT(opertup);
1211 oprname = pstrdup(NameStr(operform->oprname));
1212 /* For simplicity we always schema-qualify the op name */
1213 nspname = get_namespace_name(operform->oprnamespace);
1214 namelist = list_make2(makeString(nspname),
1215 makeString(oprname));
1216 index->excludeOpNames = lappend(index->excludeOpNames,
1218 ReleaseSysCache(opertup);
1222 ReleaseSysCache(ht_constr);
1225 index->isconstraint = false;
1228 index->isconstraint = false;
1230 /* Get the index expressions, if any */
1231 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1232 Anum_pg_index_indexprs, &isnull);
1237 exprsString = TextDatumGetCString(datum);
1238 indexprs = (List *) stringToNode(exprsString);
1243 /* Build the list of IndexElem */
1244 index->indexParams = NIL;
1245 index->indexIncludingParams = NIL;
1247 indexpr_item = list_head(indexprs);
1248 for (keyno = 0; keyno < idxrec->indnkeyatts; keyno++)
1251 AttrNumber attnum = idxrec->indkey.values[keyno];
1252 int16 opt = source_idx->rd_indoption[keyno];
1253 iparam = makeNode(IndexElem);
1255 if (AttributeNumberIsValid(attnum))
1257 /* Simple index column */
1260 attname = get_relid_attribute_name(indrelid, attnum);
1261 keycoltype = get_atttype(indrelid, attnum);
1263 iparam->name = attname;
1264 iparam->expr = NULL;
1268 /* Expressional index */
1270 bool found_whole_row;
1272 if (indexpr_item == NULL)
1273 elog(ERROR, "too few entries in indexprs list");
1274 indexkey = (Node *) lfirst(indexpr_item);
1275 indexpr_item = lnext(indexpr_item);
1277 /* Adjust Vars to match new table's column numbering */
1278 indexkey = map_variable_attnos(indexkey,
1280 attmap, attmap_length,
1283 /* As in transformTableLikeClause, reject whole-row variables */
1284 if (found_whole_row)
1286 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1287 errmsg("cannot convert whole-row table reference"),
1288 errdetail("Index \"%s\" contains a whole-row table reference.",
1289 RelationGetRelationName(source_idx))));
1291 iparam->name = NULL;
1292 iparam->expr = indexkey;
1294 keycoltype = exprType(indexkey);
1297 /* Copy the original index column name */
1298 iparam->indexcolname = pstrdup(NameStr(attrs[keyno]->attname));
1300 /* Add the collation name, if non-default */
1301 iparam->collation = get_collation(indcollation->values[keyno], keycoltype);
1303 /* Add the operator class name, if non-default */
1304 iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1306 iparam->ordering = SORTBY_DEFAULT;
1307 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1309 /* Adjust options if necessary */
1310 if (source_idx->rd_amroutine->amcanorder)
1313 * If it supports sort ordering, copy DESC and NULLS opts. Don't
1314 * set non-default settings unnecessarily, though, so as to
1315 * improve the chance of recognizing equivalence to constraint
1318 if (opt & INDOPTION_DESC)
1320 iparam->ordering = SORTBY_DESC;
1321 if ((opt & INDOPTION_NULLS_FIRST) == 0)
1322 iparam->nulls_ordering = SORTBY_NULLS_LAST;
1326 if (opt & INDOPTION_NULLS_FIRST)
1327 iparam->nulls_ordering = SORTBY_NULLS_FIRST;
1331 index->indexParams = lappend(index->indexParams, iparam);
1334 /* Handle included columns separately */
1335 for (keyno = idxrec->indnkeyatts; keyno < idxrec->indnatts; keyno++)
1338 AttrNumber attnum = idxrec->indkey.values[keyno];
1340 iparam = makeNode(IndexElem);
1342 if (AttributeNumberIsValid(attnum))
1344 /* Simple index column */
1347 attname = get_relid_attribute_name(indrelid, attnum);
1348 keycoltype = get_atttype(indrelid, attnum);
1350 iparam->name = attname;
1351 iparam->expr = NULL;
1355 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1356 errmsg("expressions are not supported in included columns")));
1358 /* Copy the original index column name */
1359 iparam->indexcolname = pstrdup(NameStr(attrs[keyno]->attname));
1361 /* Add the collation name, if non-default */
1362 iparam->collation = get_collation(indcollation->values[keyno], keycoltype);
1364 index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
1366 /* Copy reloptions if any */
1367 datum = SysCacheGetAttr(RELOID, ht_idxrel,
1368 Anum_pg_class_reloptions, &isnull);
1370 index->options = untransformRelOptions(datum);
1372 /* If it's a partial index, decompile and append the predicate */
1373 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1374 Anum_pg_index_indpred, &isnull);
1379 bool found_whole_row;
1381 /* Convert text string to node tree */
1382 pred_str = TextDatumGetCString(datum);
1383 pred_tree = (Node *) stringToNode(pred_str);
1385 /* Adjust Vars to match new table's column numbering */
1386 pred_tree = map_variable_attnos(pred_tree,
1388 attmap, attmap_length,
1391 /* As in transformTableLikeClause, reject whole-row variables */
1392 if (found_whole_row)
1394 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1395 errmsg("cannot convert whole-row table reference"),
1396 errdetail("Index \"%s\" contains a whole-row table reference.",
1397 RelationGetRelationName(source_idx))));
1399 index->whereClause = pred_tree;
1403 ReleaseSysCache(ht_idxrel);
1404 ReleaseSysCache(ht_am);
1410 * get_collation - fetch qualified name of a collation
1412 * If collation is InvalidOid or is the default for the given actual_datatype,
1413 * then the return value is NIL.
1416 get_collation(Oid collation, Oid actual_datatype)
1420 Form_pg_collation coll_rec;
1424 if (!OidIsValid(collation))
1425 return NIL; /* easy case */
1426 if (collation == get_typcollation(actual_datatype))
1427 return NIL; /* just let it default */
1429 ht_coll = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
1430 if (!HeapTupleIsValid(ht_coll))
1431 elog(ERROR, "cache lookup failed for collation %u", collation);
1432 coll_rec = (Form_pg_collation) GETSTRUCT(ht_coll);
1434 /* For simplicity, we always schema-qualify the name */
1435 nsp_name = get_namespace_name(coll_rec->collnamespace);
1436 coll_name = pstrdup(NameStr(coll_rec->collname));
1437 result = list_make2(makeString(nsp_name), makeString(coll_name));
1439 ReleaseSysCache(ht_coll);
1444 * get_opclass - fetch qualified name of an index operator class
1446 * If the opclass is the default for the given actual_datatype, then
1447 * the return value is NIL.
1450 get_opclass(Oid opclass, Oid actual_datatype)
1454 Form_pg_opclass opc_rec;
1456 ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
1457 if (!HeapTupleIsValid(ht_opc))
1458 elog(ERROR, "cache lookup failed for opclass %u", opclass);
1459 opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
1461 if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
1463 /* For simplicity, we always schema-qualify the name */
1464 char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
1465 char *opc_name = pstrdup(NameStr(opc_rec->opcname));
1467 result = list_make2(makeString(nsp_name), makeString(opc_name));
1470 ReleaseSysCache(ht_opc);
1476 * transformIndexConstraints
1477 * Handle UNIQUE, PRIMARY KEY, EXCLUDE constraints, which create indexes.
1478 * We also merge in any index definitions arising from
1479 * LIKE ... INCLUDING INDEXES.
1482 transformIndexConstraints(CreateStmtContext *cxt)
1485 List *indexlist = NIL;
1489 * Run through the constraints that need to generate an index. For PRIMARY
1490 * KEY, mark each column as NOT NULL and create an index. For UNIQUE or
1491 * EXCLUDE, create an index as for PRIMARY KEY, but do not insist on NOT
1494 foreach(lc, cxt->ixconstraints)
1496 Constraint *constraint = (Constraint *) lfirst(lc);
1498 Assert(IsA(constraint, Constraint));
1499 Assert(constraint->contype == CONSTR_PRIMARY ||
1500 constraint->contype == CONSTR_UNIQUE ||
1501 constraint->contype == CONSTR_EXCLUSION);
1503 index = transformIndexConstraint(constraint, cxt);
1505 indexlist = lappend(indexlist, index);
1508 /* Add in any indexes defined by LIKE ... INCLUDING INDEXES */
1509 foreach(lc, cxt->inh_indexes)
1511 index = (IndexStmt *) lfirst(lc);
1515 if (cxt->pkey != NULL)
1517 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1518 errmsg("multiple primary keys for table \"%s\" are not allowed",
1519 cxt->relation->relname)));
1523 indexlist = lappend(indexlist, index);
1527 * Scan the index list and remove any redundant index specifications. This
1528 * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
1529 * strict reading of SQL would suggest raising an error instead, but that
1530 * strikes me as too anal-retentive. - tgl 2001-02-14
1532 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1533 * pre-existing indexes, too.
1535 Assert(cxt->alist == NIL);
1536 if (cxt->pkey != NULL)
1538 /* Make sure we keep the PKEY index in preference to others... */
1539 cxt->alist = list_make1(cxt->pkey);
1542 foreach(lc, indexlist)
1549 /* if it's pkey, it's already in cxt->alist */
1550 if (index == cxt->pkey)
1553 foreach(k, cxt->alist)
1555 IndexStmt *priorindex = lfirst(k);
1557 if (equal(index->indexParams, priorindex->indexParams) &&
1558 equal(index->indexIncludingParams, priorindex->indexIncludingParams) &&
1559 equal(index->whereClause, priorindex->whereClause) &&
1560 equal(index->excludeOpNames, priorindex->excludeOpNames) &&
1561 strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
1562 index->deferrable == priorindex->deferrable &&
1563 index->initdeferred == priorindex->initdeferred)
1565 priorindex->unique |= index->unique;
1568 * If the prior index is as yet unnamed, and this one is
1569 * named, then transfer the name to the prior index. This
1570 * ensures that if we have named and unnamed constraints,
1571 * we'll use (at least one of) the names for the index.
1573 if (priorindex->idxname == NULL)
1574 priorindex->idxname = index->idxname;
1581 cxt->alist = lappend(cxt->alist, index);
1586 * transformIndexConstraint
1587 * Transform one UNIQUE, PRIMARY KEY, or EXCLUDE constraint for
1588 * transformIndexConstraints.
1591 transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
1596 index = makeNode(IndexStmt);
1598 index->unique = (constraint->contype != CONSTR_EXCLUSION);
1599 index->primary = (constraint->contype == CONSTR_PRIMARY);
1602 if (cxt->pkey != NULL)
1604 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1605 errmsg("multiple primary keys for table \"%s\" are not allowed",
1606 cxt->relation->relname),
1607 parser_errposition(cxt->pstate, constraint->location)));
1611 * In ALTER TABLE case, a primary index might already exist, but
1612 * DefineIndex will check for it.
1615 index->isconstraint = true;
1616 index->deferrable = constraint->deferrable;
1617 index->initdeferred = constraint->initdeferred;
1619 if (constraint->conname != NULL)
1620 index->idxname = pstrdup(constraint->conname);
1622 index->idxname = NULL; /* DefineIndex will choose name */
1624 index->relation = cxt->relation;
1625 index->accessMethod = constraint->access_method ? constraint->access_method : DEFAULT_INDEX_TYPE;
1626 index->options = constraint->options;
1627 index->tableSpace = constraint->indexspace;
1628 index->whereClause = constraint->where_clause;
1629 index->indexParams = NIL;
1630 index->indexIncludingParams = NIL;
1631 index->excludeOpNames = NIL;
1632 index->idxcomment = NULL;
1633 index->indexOid = InvalidOid;
1634 index->oldNode = InvalidOid;
1635 index->transformed = false;
1636 index->concurrent = false;
1637 index->if_not_exists = false;
1640 * If it's ALTER TABLE ADD CONSTRAINT USING INDEX, look up the index and
1641 * verify it's usable, then extract the implied column name list. (We
1642 * will not actually need the column name list at runtime, but we need it
1643 * now to check for duplicate column entries below.)
1645 if (constraint->indexname != NULL)
1647 char *index_name = constraint->indexname;
1648 Relation heap_rel = cxt->rel;
1651 Form_pg_index index_form;
1652 oidvector *indclass;
1653 Datum indclassDatum;
1657 /* Grammar should not allow this with explicit column list */
1658 Assert(constraint->keys == NIL);
1660 /* Grammar should only allow PRIMARY and UNIQUE constraints */
1661 Assert(constraint->contype == CONSTR_PRIMARY ||
1662 constraint->contype == CONSTR_UNIQUE);
1664 /* Must be ALTER, not CREATE, but grammar doesn't enforce that */
1667 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1668 errmsg("cannot use an existing index in CREATE TABLE"),
1669 parser_errposition(cxt->pstate, constraint->location)));
1671 /* Look for the index in the same schema as the table */
1672 index_oid = get_relname_relid(index_name, RelationGetNamespace(heap_rel));
1674 if (!OidIsValid(index_oid))
1676 (errcode(ERRCODE_UNDEFINED_OBJECT),
1677 errmsg("index \"%s\" does not exist", index_name),
1678 parser_errposition(cxt->pstate, constraint->location)));
1680 /* Open the index (this will throw an error if it is not an index) */
1681 index_rel = index_open(index_oid, AccessShareLock);
1682 index_form = index_rel->rd_index;
1684 /* Check that it does not have an associated constraint already */
1685 if (OidIsValid(get_index_constraint(index_oid)))
1687 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1688 errmsg("index \"%s\" is already associated with a constraint",
1690 parser_errposition(cxt->pstate, constraint->location)));
1692 /* Perform validity checks on the index */
1693 if (index_form->indrelid != RelationGetRelid(heap_rel))
1695 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1696 errmsg("index \"%s\" does not belong to table \"%s\"",
1697 index_name, RelationGetRelationName(heap_rel)),
1698 parser_errposition(cxt->pstate, constraint->location)));
1700 if (!IndexIsValid(index_form))
1702 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1703 errmsg("index \"%s\" is not valid", index_name),
1704 parser_errposition(cxt->pstate, constraint->location)));
1706 if (!index_form->indisunique)
1708 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1709 errmsg("\"%s\" is not a unique index", index_name),
1710 errdetail("Cannot create a primary key or unique constraint using such an index."),
1711 parser_errposition(cxt->pstate, constraint->location)));
1713 if (RelationGetIndexExpressions(index_rel) != NIL)
1715 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1716 errmsg("index \"%s\" contains expressions", index_name),
1717 errdetail("Cannot create a primary key or unique constraint using such an index."),
1718 parser_errposition(cxt->pstate, constraint->location)));
1720 if (RelationGetIndexPredicate(index_rel) != NIL)
1722 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1723 errmsg("\"%s\" is a partial index", index_name),
1724 errdetail("Cannot create a primary key or unique constraint using such an index."),
1725 parser_errposition(cxt->pstate, constraint->location)));
1728 * It's probably unsafe to change a deferred index to non-deferred. (A
1729 * non-constraint index couldn't be deferred anyway, so this case
1730 * should never occur; no need to sweat, but let's check it.)
1732 if (!index_form->indimmediate && !constraint->deferrable)
1734 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1735 errmsg("\"%s\" is a deferrable index", index_name),
1736 errdetail("Cannot create a non-deferrable constraint using a deferrable index."),
1737 parser_errposition(cxt->pstate, constraint->location)));
1740 * Insist on it being a btree. That's the only kind that supports
1741 * uniqueness at the moment anyway; but we must have an index that
1742 * exactly matches what you'd get from plain ADD CONSTRAINT syntax,
1743 * else dump and reload will produce a different index (breaking
1744 * pg_upgrade in particular).
1746 if (index_rel->rd_rel->relam != get_index_am_oid(DEFAULT_INDEX_TYPE, false))
1748 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1749 errmsg("index \"%s\" is not a btree", index_name),
1750 parser_errposition(cxt->pstate, constraint->location)));
1752 /* Must get indclass the hard way */
1753 indclassDatum = SysCacheGetAttr(INDEXRELID, index_rel->rd_indextuple,
1754 Anum_pg_index_indclass, &isnull);
1756 indclass = (oidvector *) DatumGetPointer(indclassDatum);
1758 for (i = 0; i < index_form->indnatts; i++)
1760 int16 attnum = index_form->indkey.values[i];
1761 Form_pg_attribute attform;
1766 * We shouldn't see attnum == 0 here, since we already rejected
1767 * expression indexes. If we do, SystemAttributeDefinition will
1772 Assert(attnum <= heap_rel->rd_att->natts);
1773 attform = heap_rel->rd_att->attrs[attnum - 1];
1776 attform = SystemAttributeDefinition(attnum,
1777 heap_rel->rd_rel->relhasoids);
1778 attname = pstrdup(NameStr(attform->attname));
1780 if (i < index_form->indnkeyatts)
1783 * Insist on default opclass and sort options. While the index
1784 * would still work as a constraint with non-default settings, it
1785 * might not provide exactly the same uniqueness semantics as
1786 * you'd get from a normally-created constraint; and there's also
1787 * the dump/reload problem mentioned above.
1789 defopclass = GetDefaultOpClass(attform->atttypid,
1790 index_rel->rd_rel->relam);
1791 if (indclass->values[i] != defopclass ||
1792 index_rel->rd_indoption[i] != 0)
1794 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1795 errmsg("index \"%s\" does not have default sorting behavior", index_name),
1796 errdetail("Cannot create a primary key or unique constraint using such an index."),
1797 parser_errposition(cxt->pstate, constraint->location)));
1799 constraint->keys = lappend(constraint->keys, makeString(attname));
1802 constraint->including = lappend(constraint->including, makeString(attname));
1806 /* Close the index relation but keep the lock */
1807 relation_close(index_rel, NoLock);
1809 index->indexOid = index_oid;
1813 * If it's an EXCLUDE constraint, the grammar returns a list of pairs of
1814 * IndexElems and operator names. We have to break that apart into
1816 * NOTE that exclusion constraints don't support included nonkey attributes
1818 if (constraint->contype == CONSTR_EXCLUSION)
1820 foreach(lc, constraint->exclusions)
1822 List *pair = (List *) lfirst(lc);
1826 Assert(list_length(pair) == 2);
1827 elem = (IndexElem *) linitial(pair);
1828 Assert(IsA(elem, IndexElem));
1829 opname = (List *) lsecond(pair);
1830 Assert(IsA(opname, List));
1832 index->indexParams = lappend(index->indexParams, elem);
1833 index->excludeOpNames = lappend(index->excludeOpNames, opname);
1840 * For UNIQUE and PRIMARY KEY, we just have a list of column names.
1842 * Make sure referenced keys exist. If we are making a PRIMARY KEY index,
1843 * also make sure they are NOT NULL, if possible. (Although we could leave
1844 * it to DefineIndex to mark the columns NOT NULL, it's more efficient to
1845 * get it right the first time.)
1847 foreach(lc, constraint->keys)
1849 char *key = strVal(lfirst(lc));
1851 ColumnDef *column = NULL;
1855 foreach(columns, cxt->columns)
1857 column = (ColumnDef *) lfirst(columns);
1858 Assert(IsA(column, ColumnDef));
1859 if (strcmp(column->colname, key) == 0)
1867 /* found column in the new table; force it to be NOT NULL */
1868 if (constraint->contype == CONSTR_PRIMARY)
1869 column->is_not_null = TRUE;
1871 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1874 * column will be a system column in the new table, so accept it.
1875 * System columns can't ever be null, so no need to worry about
1876 * PRIMARY/NOT NULL constraint.
1880 else if (cxt->inhRelations)
1882 /* try inherited tables */
1885 foreach(inher, cxt->inhRelations)
1887 RangeVar *inh = (RangeVar *) lfirst(inher);
1891 Assert(IsA(inh, RangeVar));
1892 rel = heap_openrv(inh, AccessShareLock);
1893 /* check user requested inheritance from valid relkind */
1894 if (rel->rd_rel->relkind != RELKIND_RELATION &&
1895 rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE)
1897 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1898 errmsg("inherited relation \"%s\" is not a table or foreign table",
1900 for (count = 0; count < rel->rd_att->natts; count++)
1902 Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1903 char *inhname = NameStr(inhattr->attname);
1905 if (inhattr->attisdropped)
1907 if (strcmp(key, inhname) == 0)
1912 * We currently have no easy way to force an inherited
1913 * column to be NOT NULL at creation, if its parent
1914 * wasn't so already. We leave it to DefineIndex to
1915 * fix things up in this case.
1920 heap_close(rel, NoLock);
1927 * In the ALTER TABLE case, don't complain about index keys not
1928 * created in the command; they may well exist already. DefineIndex
1929 * will complain about them if not, and will also take care of marking
1932 if (!found && !cxt->isalter)
1934 (errcode(ERRCODE_UNDEFINED_COLUMN),
1935 errmsg("column \"%s\" named in key does not exist", key),
1936 parser_errposition(cxt->pstate, constraint->location)));
1938 /* Check for PRIMARY KEY(foo, foo) */
1939 foreach(columns, index->indexParams)
1941 iparam = (IndexElem *) lfirst(columns);
1942 if (iparam->name && strcmp(key, iparam->name) == 0)
1946 (errcode(ERRCODE_DUPLICATE_COLUMN),
1947 errmsg("column \"%s\" appears twice in primary key constraint",
1949 parser_errposition(cxt->pstate, constraint->location)));
1952 (errcode(ERRCODE_DUPLICATE_COLUMN),
1953 errmsg("column \"%s\" appears twice in unique constraint",
1955 parser_errposition(cxt->pstate, constraint->location)));
1959 /* OK, add it to the index definition */
1960 iparam = makeNode(IndexElem);
1961 iparam->name = pstrdup(key);
1962 iparam->expr = NULL;
1963 iparam->indexcolname = NULL;
1964 iparam->collation = NIL;
1965 iparam->opclass = NIL;
1966 iparam->ordering = SORTBY_DEFAULT;
1967 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1968 index->indexParams = lappend(index->indexParams, iparam);
1971 /* Here is some ugly code duplication. But we do need it. */
1972 foreach(lc, constraint->including)
1974 char *key = strVal(lfirst(lc));
1976 ColumnDef *column = NULL;
1980 foreach(columns, cxt->columns)
1982 column = (ColumnDef *) lfirst(columns);
1983 Assert(IsA(column, ColumnDef));
1984 if (strcmp(column->colname, key) == 0)
1992 * In the ALTER TABLE case, don't complain about index keys not
1993 * created in the command; they may well exist already. DefineIndex
1994 * will complain about them if not, and will also take care of marking
1997 if (!found && !cxt->isalter)
1999 (errcode(ERRCODE_UNDEFINED_COLUMN),
2000 errmsg("column \"%s\" named in key does not exist", key),
2001 parser_errposition(cxt->pstate, constraint->location)));
2003 /* OK, add it to the index definition */
2004 iparam = makeNode(IndexElem);
2005 iparam->name = pstrdup(key);
2006 iparam->expr = NULL;
2007 iparam->indexcolname = NULL;
2008 iparam->collation = NIL;
2009 iparam->opclass = NIL;
2010 index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
2017 * transformCheckConstraints
2018 * handle CHECK constraints
2020 * Right now, there's nothing to do here when called from ALTER TABLE,
2021 * but the other constraint-transformation functions are called in both
2022 * the CREATE TABLE and ALTER TABLE paths, so do the same here, and just
2023 * don't do anything if we're not authorized to skip validation.
2026 transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)
2030 if (cxt->ckconstraints == NIL)
2034 * If creating a new table, we can safely skip validation of check
2035 * constraints, and nonetheless mark them valid. (This will override
2036 * any user-supplied NOT VALID flag.)
2040 foreach(ckclist, cxt->ckconstraints)
2042 Constraint *constraint = (Constraint *) lfirst(ckclist);
2044 constraint->skip_validation = true;
2045 constraint->initially_valid = true;
2051 * transformFKConstraints
2052 * handle FOREIGN KEY constraints
2055 transformFKConstraints(CreateStmtContext *cxt,
2056 bool skipValidation, bool isAddConstraint)
2060 if (cxt->fkconstraints == NIL)
2064 * If CREATE TABLE or adding a column with NULL default, we can safely
2065 * skip validation of FK constraints, and nonetheless mark them valid.
2066 * (This will override any user-supplied NOT VALID flag.)
2070 foreach(fkclist, cxt->fkconstraints)
2072 Constraint *constraint = (Constraint *) lfirst(fkclist);
2074 constraint->skip_validation = true;
2075 constraint->initially_valid = true;
2080 * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
2081 * CONSTRAINT command to execute after the basic command is complete. (If
2082 * called from ADD CONSTRAINT, that routine will add the FK constraints to
2083 * its own subcommand list.)
2085 * Note: the ADD CONSTRAINT command must also execute after any index
2086 * creation commands. Thus, this should run after
2087 * transformIndexConstraints, so that the CREATE INDEX commands are
2088 * already in cxt->alist.
2090 if (!isAddConstraint)
2092 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
2094 alterstmt->relation = cxt->relation;
2095 alterstmt->cmds = NIL;
2096 alterstmt->relkind = OBJECT_TABLE;
2098 foreach(fkclist, cxt->fkconstraints)
2100 Constraint *constraint = (Constraint *) lfirst(fkclist);
2101 AlterTableCmd *altercmd = makeNode(AlterTableCmd);
2103 altercmd->subtype = AT_ProcessedConstraint;
2104 altercmd->name = NULL;
2105 altercmd->def = (Node *) constraint;
2106 alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
2109 cxt->alist = lappend(cxt->alist, alterstmt);
2114 * transformIndexStmt - parse analysis for CREATE INDEX and ALTER TABLE
2116 * Note: this is a no-op for an index not using either index expressions or
2117 * a predicate expression. There are several code paths that create indexes
2118 * without bothering to call this, because they know they don't have any
2119 * such expressions to deal with.
2121 * To avoid race conditions, it's important that this function rely only on
2122 * the passed-in relid (and not on stmt->relation) to determine the target
2126 transformIndexStmt(Oid relid, IndexStmt *stmt, const char *queryString)
2133 /* Nothing to do if statement already transformed. */
2134 if (stmt->transformed)
2138 * We must not scribble on the passed-in IndexStmt, so copy it. (This is
2139 * overkill, but easy.)
2141 stmt = (IndexStmt *) copyObject(stmt);
2144 pstate = make_parsestate(NULL);
2145 pstate->p_sourcetext = queryString;
2148 * Put the parent table into the rtable so that the expressions can refer
2149 * to its fields without qualification. Caller is responsible for locking
2150 * relation, but we still need to open it.
2152 rel = relation_open(relid, NoLock);
2153 rte = addRangeTableEntryForRelation(pstate, rel, NULL, false, true);
2155 /* no to join list, yes to namespaces */
2156 addRTEtoQuery(pstate, rte, false, true, true);
2158 /* take care of the where clause */
2159 if (stmt->whereClause)
2161 stmt->whereClause = transformWhereClause(pstate,
2163 EXPR_KIND_INDEX_PREDICATE,
2165 /* we have to fix its collations too */
2166 assign_expr_collations(pstate, stmt->whereClause);
2169 /* take care of any index expressions */
2170 foreach(l, stmt->indexParams)
2172 IndexElem *ielem = (IndexElem *) lfirst(l);
2176 /* Extract preliminary index col name before transforming expr */
2177 if (ielem->indexcolname == NULL)
2178 ielem->indexcolname = FigureIndexColname(ielem->expr);
2180 /* Now do parse transformation of the expression */
2181 ielem->expr = transformExpr(pstate, ielem->expr,
2182 EXPR_KIND_INDEX_EXPRESSION);
2184 /* We have to fix its collations too */
2185 assign_expr_collations(pstate, ielem->expr);
2188 * transformExpr() should have already rejected subqueries,
2189 * aggregates, and window functions, based on the EXPR_KIND_ for
2190 * an index expression.
2192 * Also reject expressions returning sets; this is for consistency
2193 * with what transformWhereClause() checks for the predicate.
2194 * DefineIndex() will make more checks.
2196 if (expression_returns_set(ielem->expr))
2198 (errcode(ERRCODE_DATATYPE_MISMATCH),
2199 errmsg("index expression cannot return a set")));
2204 * Check that only the base rel is mentioned. (This should be dead code
2205 * now that add_missing_from is history.)
2207 if (list_length(pstate->p_rtable) != 1)
2209 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2210 errmsg("index expressions and predicates can refer only to the table being indexed")));
2212 free_parsestate(pstate);
2214 /* Close relation */
2215 heap_close(rel, NoLock);
2217 /* Mark statement as successfully transformed */
2218 stmt->transformed = true;
2225 * transformRuleStmt -
2226 * transform a CREATE RULE Statement. The action is a list of parse
2227 * trees which is transformed into a list of query trees, and we also
2228 * transform the WHERE clause if any.
2230 * actions and whereClause are output parameters that receive the
2231 * transformed results.
2233 * Note that we must not scribble on the passed-in RuleStmt, so we do
2234 * copyObject() on the actions and WHERE clause.
2237 transformRuleStmt(RuleStmt *stmt, const char *queryString,
2238 List **actions, Node **whereClause)
2242 RangeTblEntry *oldrte;
2243 RangeTblEntry *newrte;
2246 * To avoid deadlock, make sure the first thing we do is grab
2247 * AccessExclusiveLock on the target relation. This will be needed by
2248 * DefineQueryRewrite(), and we don't want to grab a lesser lock
2251 rel = heap_openrv(stmt->relation, AccessExclusiveLock);
2253 if (rel->rd_rel->relkind == RELKIND_MATVIEW)
2255 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2256 errmsg("rules on materialized views are not supported")));
2259 pstate = make_parsestate(NULL);
2260 pstate->p_sourcetext = queryString;
2263 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
2264 * Set up their RTEs in the main pstate for use in parsing the rule
2267 oldrte = addRangeTableEntryForRelation(pstate, rel,
2268 makeAlias("old", NIL),
2270 newrte = addRangeTableEntryForRelation(pstate, rel,
2271 makeAlias("new", NIL),
2273 /* Must override addRangeTableEntry's default access-check flags */
2274 oldrte->requiredPerms = 0;
2275 newrte->requiredPerms = 0;
2278 * They must be in the namespace too for lookup purposes, but only add the
2279 * one(s) that are relevant for the current kind of rule. In an UPDATE
2280 * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
2281 * there's no need to be so picky for INSERT & DELETE. We do not add them
2284 switch (stmt->event)
2287 addRTEtoQuery(pstate, oldrte, false, true, true);
2290 addRTEtoQuery(pstate, oldrte, false, true, true);
2291 addRTEtoQuery(pstate, newrte, false, true, true);
2294 addRTEtoQuery(pstate, newrte, false, true, true);
2297 addRTEtoQuery(pstate, oldrte, false, true, true);
2300 elog(ERROR, "unrecognized event type: %d",
2305 /* take care of the where clause */
2306 *whereClause = transformWhereClause(pstate,
2307 (Node *) copyObject(stmt->whereClause),
2310 /* we have to fix its collations too */
2311 assign_expr_collations(pstate, *whereClause);
2313 /* this is probably dead code without add_missing_from: */
2314 if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
2316 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2317 errmsg("rule WHERE condition cannot contain references to other relations")));
2320 * 'instead nothing' rules with a qualification need a query rangetable so
2321 * the rewrite handler can add the negated rule qualification to the
2322 * original query. We create a query with the new command type CMD_NOTHING
2323 * here that is treated specially by the rewrite system.
2325 if (stmt->actions == NIL)
2327 Query *nothing_qry = makeNode(Query);
2329 nothing_qry->commandType = CMD_NOTHING;
2330 nothing_qry->rtable = pstate->p_rtable;
2331 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
2333 *actions = list_make1(nothing_qry);
2338 List *newactions = NIL;
2341 * transform each statement, like parse_sub_analyze()
2343 foreach(l, stmt->actions)
2345 Node *action = (Node *) lfirst(l);
2346 ParseState *sub_pstate = make_parsestate(NULL);
2353 * Since outer ParseState isn't parent of inner, have to pass down
2354 * the query text by hand.
2356 sub_pstate->p_sourcetext = queryString;
2359 * Set up OLD/NEW in the rtable for this statement. The entries
2360 * are added only to relnamespace, not varnamespace, because we
2361 * don't want them to be referred to by unqualified field names
2362 * nor "*" in the rule actions. We decide later whether to put
2363 * them in the joinlist.
2365 oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
2366 makeAlias("old", NIL),
2368 newrte = addRangeTableEntryForRelation(sub_pstate, rel,
2369 makeAlias("new", NIL),
2371 oldrte->requiredPerms = 0;
2372 newrte->requiredPerms = 0;
2373 addRTEtoQuery(sub_pstate, oldrte, false, true, false);
2374 addRTEtoQuery(sub_pstate, newrte, false, true, false);
2376 /* Transform the rule action statement */
2377 top_subqry = transformStmt(sub_pstate,
2378 (Node *) copyObject(action));
2381 * We cannot support utility-statement actions (eg NOTIFY) with
2382 * nonempty rule WHERE conditions, because there's no way to make
2383 * the utility action execute conditionally.
2385 if (top_subqry->commandType == CMD_UTILITY &&
2386 *whereClause != NULL)
2388 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2389 errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
2392 * If the action is INSERT...SELECT, OLD/NEW have been pushed down
2393 * into the SELECT, and that's what we need to look at. (Ugly
2394 * kluge ... try to fix this when we redesign querytrees.)
2396 sub_qry = getInsertSelectQuery(top_subqry, NULL);
2399 * If the sub_qry is a setop, we cannot attach any qualifications
2400 * to it, because the planner won't notice them. This could
2401 * perhaps be relaxed someday, but for now, we may as well reject
2402 * such a rule immediately.
2404 if (sub_qry->setOperations != NULL && *whereClause != NULL)
2406 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2407 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2410 * Validate action's use of OLD/NEW, qual too
2413 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
2414 rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
2416 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
2417 rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
2419 switch (stmt->event)
2424 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2425 errmsg("ON SELECT rule cannot use OLD")));
2428 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2429 errmsg("ON SELECT rule cannot use NEW")));
2437 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2438 errmsg("ON INSERT rule cannot use OLD")));
2443 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2444 errmsg("ON DELETE rule cannot use NEW")));
2447 elog(ERROR, "unrecognized event type: %d",
2453 * OLD/NEW are not allowed in WITH queries, because they would
2454 * amount to outer references for the WITH, which we disallow.
2455 * However, they were already in the outer rangetable when we
2456 * analyzed the query, so we have to check.
2458 * Note that in the INSERT...SELECT case, we need to examine the
2459 * CTE lists of both top_subqry and sub_qry.
2461 * Note that we aren't digging into the body of the query looking
2462 * for WITHs in nested sub-SELECTs. A WITH down there can
2463 * legitimately refer to OLD/NEW, because it'd be an
2464 * indirect-correlated outer reference.
2466 if (rangeTableEntry_used((Node *) top_subqry->cteList,
2467 PRS2_OLD_VARNO, 0) ||
2468 rangeTableEntry_used((Node *) sub_qry->cteList,
2471 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2472 errmsg("cannot refer to OLD within WITH query")));
2473 if (rangeTableEntry_used((Node *) top_subqry->cteList,
2474 PRS2_NEW_VARNO, 0) ||
2475 rangeTableEntry_used((Node *) sub_qry->cteList,
2478 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2479 errmsg("cannot refer to NEW within WITH query")));
2482 * For efficiency's sake, add OLD to the rule action's jointree
2483 * only if it was actually referenced in the statement or qual.
2485 * For INSERT, NEW is not really a relation (only a reference to
2486 * the to-be-inserted tuple) and should never be added to the
2489 * For UPDATE, we treat NEW as being another kind of reference to
2490 * OLD, because it represents references to *transformed* tuples
2491 * of the existing relation. It would be wrong to enter NEW
2492 * separately in the jointree, since that would cause a double
2493 * join of the updated relation. It's also wrong to fail to make
2494 * a jointree entry if only NEW and not OLD is mentioned.
2496 if (has_old || (has_new && stmt->event == CMD_UPDATE))
2499 * If sub_qry is a setop, manipulating its jointree will do no
2500 * good at all, because the jointree is dummy. (This should be
2501 * a can't-happen case because of prior tests.)
2503 if (sub_qry->setOperations != NULL)
2505 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2506 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2507 /* hack so we can use addRTEtoQuery() */
2508 sub_pstate->p_rtable = sub_qry->rtable;
2509 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
2510 addRTEtoQuery(sub_pstate, oldrte, true, false, false);
2511 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
2514 newactions = lappend(newactions, top_subqry);
2516 free_parsestate(sub_pstate);
2519 *actions = newactions;
2522 free_parsestate(pstate);
2524 /* Close relation, but keep the exclusive lock */
2525 heap_close(rel, NoLock);
2530 * transformAlterTableStmt -
2531 * parse analysis for ALTER TABLE
2533 * Returns a List of utility commands to be done in sequence. One of these
2534 * will be the transformed AlterTableStmt, but there may be additional actions
2535 * to be done before and after the actual AlterTable() call.
2537 * To avoid race conditions, it's important that this function rely only on
2538 * the passed-in relid (and not on stmt->relation) to determine the target
2542 transformAlterTableStmt(Oid relid, AlterTableStmt *stmt,
2543 const char *queryString)
2547 CreateStmtContext cxt;
2552 List *newcmds = NIL;
2553 bool skipValidation = true;
2554 AlterTableCmd *newcmd;
2558 * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
2559 * is overkill, but easy.)
2561 stmt = (AlterTableStmt *) copyObject(stmt);
2563 /* Caller is responsible for locking the relation */
2564 rel = relation_open(relid, NoLock);
2567 pstate = make_parsestate(NULL);
2568 pstate->p_sourcetext = queryString;
2569 rte = addRangeTableEntryForRelation(pstate,
2574 addRTEtoQuery(pstate, rte, false, true, true);
2576 /* Set up CreateStmtContext */
2577 cxt.pstate = pstate;
2578 if (stmt->relkind == OBJECT_FOREIGN_TABLE)
2580 cxt.stmtType = "ALTER FOREIGN TABLE";
2581 cxt.isforeign = true;
2585 cxt.stmtType = "ALTER TABLE";
2586 cxt.isforeign = false;
2588 cxt.relation = stmt->relation;
2590 cxt.inhRelations = NIL;
2592 cxt.hasoids = false; /* need not be right */
2594 cxt.ckconstraints = NIL;
2595 cxt.fkconstraints = NIL;
2596 cxt.ixconstraints = NIL;
2597 cxt.inh_indexes = NIL;
2603 * The only subtypes that currently require parse transformation handling
2604 * are ADD COLUMN, ADD CONSTRAINT and SET DATA TYPE. These largely re-use
2605 * code from CREATE TABLE.
2607 foreach(lcmd, stmt->cmds)
2609 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2611 switch (cmd->subtype)
2614 case AT_AddColumnToView:
2616 ColumnDef *def = (ColumnDef *) cmd->def;
2618 Assert(IsA(def, ColumnDef));
2619 transformColumnDefinition(&cxt, def);
2622 * If the column has a non-null default, we can't skip
2623 * validation of foreign keys.
2625 if (def->raw_default != NULL)
2626 skipValidation = false;
2629 * All constraints are processed in other ways. Remove the
2632 def->constraints = NIL;
2634 newcmds = lappend(newcmds, cmd);
2638 case AT_AddConstraint:
2641 * The original AddConstraint cmd node doesn't go to newcmds
2643 if (IsA(cmd->def, Constraint))
2645 transformTableConstraint(&cxt, (Constraint *) cmd->def);
2646 if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
2647 skipValidation = false;
2650 elog(ERROR, "unrecognized node type: %d",
2651 (int) nodeTag(cmd->def));
2654 case AT_ProcessedConstraint:
2657 * Already-transformed ADD CONSTRAINT, so just make it look
2658 * like the standard case.
2660 cmd->subtype = AT_AddConstraint;
2661 newcmds = lappend(newcmds, cmd);
2664 case AT_AlterColumnType:
2666 ColumnDef *def = (ColumnDef *) cmd->def;
2669 * For ALTER COLUMN TYPE, transform the USING clause if
2670 * one was specified.
2672 if (def->raw_default)
2674 def->cooked_default =
2675 transformExpr(pstate, def->raw_default,
2676 EXPR_KIND_ALTER_COL_TRANSFORM);
2678 /* it can't return a set */
2679 if (expression_returns_set(def->cooked_default))
2681 (errcode(ERRCODE_DATATYPE_MISMATCH),
2682 errmsg("transform expression must not return a set")));
2685 newcmds = lappend(newcmds, cmd);
2690 newcmds = lappend(newcmds, cmd);
2696 * transformIndexConstraints wants cxt.alist to contain only index
2697 * statements, so transfer anything we already have into save_alist
2700 save_alist = cxt.alist;
2703 /* Postprocess constraints */
2704 transformIndexConstraints(&cxt);
2705 transformFKConstraints(&cxt, skipValidation, true);
2706 transformCheckConstraints(&cxt, false);
2709 * Push any index-creation commands into the ALTER, so that they can be
2710 * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
2711 * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
2712 * subcommand has already been through transformIndexStmt.
2714 foreach(l, cxt.alist)
2716 IndexStmt *idxstmt = (IndexStmt *) lfirst(l);
2718 Assert(IsA(idxstmt, IndexStmt));
2719 idxstmt = transformIndexStmt(relid, idxstmt, queryString);
2720 newcmd = makeNode(AlterTableCmd);
2721 newcmd->subtype = OidIsValid(idxstmt->indexOid) ? AT_AddIndexConstraint : AT_AddIndex;
2722 newcmd->def = (Node *) idxstmt;
2723 newcmds = lappend(newcmds, newcmd);
2727 /* Append any CHECK or FK constraints to the commands list */
2728 foreach(l, cxt.ckconstraints)
2730 newcmd = makeNode(AlterTableCmd);
2731 newcmd->subtype = AT_AddConstraint;
2732 newcmd->def = (Node *) lfirst(l);
2733 newcmds = lappend(newcmds, newcmd);
2735 foreach(l, cxt.fkconstraints)
2737 newcmd = makeNode(AlterTableCmd);
2738 newcmd->subtype = AT_AddConstraint;
2739 newcmd->def = (Node *) lfirst(l);
2740 newcmds = lappend(newcmds, newcmd);
2744 relation_close(rel, NoLock);
2749 stmt->cmds = newcmds;
2751 result = lappend(cxt.blist, stmt);
2752 result = list_concat(result, cxt.alist);
2753 result = list_concat(result, save_alist);
2760 * Preprocess a list of column constraint clauses
2761 * to attach constraint attributes to their primary constraint nodes
2762 * and detect inconsistent/misplaced constraint attributes.
2764 * NOTE: currently, attributes are only supported for FOREIGN KEY, UNIQUE,
2765 * EXCLUSION, and PRIMARY KEY constraints, but someday they ought to be
2766 * supported for other constraint types.
2769 transformConstraintAttrs(CreateStmtContext *cxt, List *constraintList)
2771 Constraint *lastprimarycon = NULL;
2772 bool saw_deferrability = false;
2773 bool saw_initially = false;
2776 #define SUPPORTS_ATTRS(node) \
2777 ((node) != NULL && \
2778 ((node)->contype == CONSTR_PRIMARY || \
2779 (node)->contype == CONSTR_UNIQUE || \
2780 (node)->contype == CONSTR_EXCLUSION || \
2781 (node)->contype == CONSTR_FOREIGN))
2783 foreach(clist, constraintList)
2785 Constraint *con = (Constraint *) lfirst(clist);
2787 if (!IsA(con, Constraint))
2788 elog(ERROR, "unrecognized node type: %d",
2789 (int) nodeTag(con));
2790 switch (con->contype)
2792 case CONSTR_ATTR_DEFERRABLE:
2793 if (!SUPPORTS_ATTRS(lastprimarycon))
2795 (errcode(ERRCODE_SYNTAX_ERROR),
2796 errmsg("misplaced DEFERRABLE clause"),
2797 parser_errposition(cxt->pstate, con->location)));
2798 if (saw_deferrability)
2800 (errcode(ERRCODE_SYNTAX_ERROR),
2801 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
2802 parser_errposition(cxt->pstate, con->location)));
2803 saw_deferrability = true;
2804 lastprimarycon->deferrable = true;
2807 case CONSTR_ATTR_NOT_DEFERRABLE:
2808 if (!SUPPORTS_ATTRS(lastprimarycon))
2810 (errcode(ERRCODE_SYNTAX_ERROR),
2811 errmsg("misplaced NOT DEFERRABLE clause"),
2812 parser_errposition(cxt->pstate, con->location)));
2813 if (saw_deferrability)
2815 (errcode(ERRCODE_SYNTAX_ERROR),
2816 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
2817 parser_errposition(cxt->pstate, con->location)));
2818 saw_deferrability = true;
2819 lastprimarycon->deferrable = false;
2820 if (saw_initially &&
2821 lastprimarycon->initdeferred)
2823 (errcode(ERRCODE_SYNTAX_ERROR),
2824 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2825 parser_errposition(cxt->pstate, con->location)));
2828 case CONSTR_ATTR_DEFERRED:
2829 if (!SUPPORTS_ATTRS(lastprimarycon))
2831 (errcode(ERRCODE_SYNTAX_ERROR),
2832 errmsg("misplaced INITIALLY DEFERRED clause"),
2833 parser_errposition(cxt->pstate, con->location)));
2836 (errcode(ERRCODE_SYNTAX_ERROR),
2837 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
2838 parser_errposition(cxt->pstate, con->location)));
2839 saw_initially = true;
2840 lastprimarycon->initdeferred = true;
2843 * If only INITIALLY DEFERRED appears, assume DEFERRABLE
2845 if (!saw_deferrability)
2846 lastprimarycon->deferrable = true;
2847 else if (!lastprimarycon->deferrable)
2849 (errcode(ERRCODE_SYNTAX_ERROR),
2850 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2851 parser_errposition(cxt->pstate, con->location)));
2854 case CONSTR_ATTR_IMMEDIATE:
2855 if (!SUPPORTS_ATTRS(lastprimarycon))
2857 (errcode(ERRCODE_SYNTAX_ERROR),
2858 errmsg("misplaced INITIALLY IMMEDIATE clause"),
2859 parser_errposition(cxt->pstate, con->location)));
2862 (errcode(ERRCODE_SYNTAX_ERROR),
2863 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
2864 parser_errposition(cxt->pstate, con->location)));
2865 saw_initially = true;
2866 lastprimarycon->initdeferred = false;
2870 /* Otherwise it's not an attribute */
2871 lastprimarycon = con;
2872 /* reset flags for new primary node */
2873 saw_deferrability = false;
2874 saw_initially = false;
2881 * Special handling of type definition for a column
2884 transformColumnType(CreateStmtContext *cxt, ColumnDef *column)
2887 * All we really need to do here is verify that the type is valid,
2888 * including any collation spec that might be present.
2890 Type ctype = typenameType(cxt->pstate, column->typeName, NULL);
2892 if (column->collClause)
2894 Form_pg_type typtup = (Form_pg_type) GETSTRUCT(ctype);
2896 LookupCollation(cxt->pstate,
2897 column->collClause->collname,
2898 column->collClause->location);
2899 /* Complain if COLLATE is applied to an uncollatable type */
2900 if (!OidIsValid(typtup->typcollation))
2902 (errcode(ERRCODE_DATATYPE_MISMATCH),
2903 errmsg("collations are not supported by type %s",
2904 format_type_be(HeapTupleGetOid(ctype))),
2905 parser_errposition(cxt->pstate,
2906 column->collClause->location)));
2909 ReleaseSysCache(ctype);
2914 * transformCreateSchemaStmt -
2915 * analyzes the CREATE SCHEMA statement
2917 * Split the schema element list into individual commands and place
2918 * them in the result list in an order such that there are no forward
2919 * references (e.g. GRANT to a table created later in the list). Note
2920 * that the logic we use for determining forward references is
2921 * presently quite incomplete.
2923 * SQL also allows constraints to make forward references, so thumb through
2924 * the table columns and move forward references to a posterior alter-table
2927 * The result is a list of parse nodes that still need to be analyzed ---
2928 * but we can't analyze the later commands until we've executed the earlier
2929 * ones, because of possible inter-object references.
2931 * Note: this breaks the rules a little bit by modifying schema-name fields
2932 * within passed-in structs. However, the transformation would be the same
2933 * if done over, so it should be all right to scribble on the input to this
2937 transformCreateSchemaStmt(CreateSchemaStmt *stmt)
2939 CreateSchemaStmtContext cxt;
2943 cxt.stmtType = "CREATE SCHEMA";
2944 cxt.schemaname = stmt->schemaname;
2945 cxt.authrole = (RoleSpec *) stmt->authrole;
2946 cxt.sequences = NIL;
2954 * Run through each schema element in the schema element list. Separate
2955 * statements by type, and do preliminary analysis.
2957 foreach(elements, stmt->schemaElts)
2959 Node *element = lfirst(elements);
2961 switch (nodeTag(element))
2963 case T_CreateSeqStmt:
2965 CreateSeqStmt *elp = (CreateSeqStmt *) element;
2967 setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
2968 cxt.sequences = lappend(cxt.sequences, element);
2974 CreateStmt *elp = (CreateStmt *) element;
2976 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2979 * XXX todo: deal with constraints
2981 cxt.tables = lappend(cxt.tables, element);
2987 ViewStmt *elp = (ViewStmt *) element;
2989 setSchemaName(cxt.schemaname, &elp->view->schemaname);
2992 * XXX todo: deal with references between views
2994 cxt.views = lappend(cxt.views, element);
3000 IndexStmt *elp = (IndexStmt *) element;
3002 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3003 cxt.indexes = lappend(cxt.indexes, element);
3007 case T_CreateTrigStmt:
3009 CreateTrigStmt *elp = (CreateTrigStmt *) element;
3011 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3012 cxt.triggers = lappend(cxt.triggers, element);
3017 cxt.grants = lappend(cxt.grants, element);
3021 elog(ERROR, "unrecognized node type: %d",
3022 (int) nodeTag(element));
3027 result = list_concat(result, cxt.sequences);
3028 result = list_concat(result, cxt.tables);
3029 result = list_concat(result, cxt.views);
3030 result = list_concat(result, cxt.indexes);
3031 result = list_concat(result, cxt.triggers);
3032 result = list_concat(result, cxt.grants);
3039 * Set or check schema name in an element of a CREATE SCHEMA command
3042 setSchemaName(char *context_schema, char **stmt_schema_name)
3044 if (*stmt_schema_name == NULL)
3045 *stmt_schema_name = context_schema;
3046 else if (strcmp(context_schema, *stmt_schema_name) != 0)
3048 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
3049 errmsg("CREATE specifies a schema (%s) "
3050 "different from the one being created (%s)",
3051 *stmt_schema_name, context_schema)));