]> granicus.if.org Git - postgresql/blobdiff - src/backend/parser/parse_utilcmd.c
Allow WITH clauses to be attached to INSERT, UPDATE, DELETE statements.
[postgresql] / src / backend / parser / parse_utilcmd.c
index 4bab055269746bcf131a83657e1d7671543aa9aa..a8aee204c74a5c66fb7bf43271bbc8d226787fc2 100644 (file)
  * a quick copyObject() call before manipulating the query tree.
  *
  *
- * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
  * Portions Copyright (c) 1994, Regents of the University of California
  *
- *     $PostgreSQL: pgsql/src/backend/parser/parse_utilcmd.c,v 2.15 2008/08/25 22:42:33 tgl Exp $
+ *     src/backend/parser/parse_utilcmd.c
  *
  *-------------------------------------------------------------------------
  */
 #include "catalog/heap.h"
 #include "catalog/index.h"
 #include "catalog/namespace.h"
+#include "catalog/pg_constraint.h"
 #include "catalog/pg_opclass.h"
+#include "catalog/pg_operator.h"
 #include "catalog/pg_type.h"
+#include "commands/comment.h"
 #include "commands/defrem.h"
 #include "commands/tablecmds.h"
 #include "commands/tablespace.h"
 #include "nodes/makefuncs.h"
 #include "nodes/nodeFuncs.h"
 #include "parser/analyze.h"
-#include "parser/gramparse.h"
 #include "parser/parse_clause.h"
 #include "parser/parse_expr.h"
 #include "parser/parse_relation.h"
+#include "parser/parse_target.h"
 #include "parser/parse_type.h"
 #include "parser/parse_utilcmd.h"
+#include "parser/parser.h"
 #include "rewrite/rewriteManip.h"
+#include "storage/lock.h"
 #include "utils/acl.h"
 #include "utils/builtins.h"
 #include "utils/lsyscache.h"
 #include "utils/relcache.h"
 #include "utils/syscache.h"
+#include "utils/typcache.h"
 
 
 /* State shared by transformCreateStmt and its subroutines */
@@ -100,6 +106,9 @@ static void transformTableConstraint(ParseState *pstate,
                                                 Constraint *constraint);
 static void transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
                                         InhRelation *inhrelation);
+static void transformOfType(ParseState *pstate, CreateStmtContext *cxt,
+                               TypeName *ofTypename);
+static char *chooseIndexName(const RangeVar *relation, IndexStmt *index_stmt);
 static IndexStmt *generateClonedIndexStmt(CreateStmtContext *cxt,
                                                Relation parent_index, AttrNumber *attmap);
 static List *get_opclass(Oid opclass, Oid actual_datatype);
@@ -111,7 +120,7 @@ static void transformFKConstraints(ParseState *pstate,
                                           CreateStmtContext *cxt,
                                           bool skipValidation,
                                           bool isAddConstraint);
-static void transformConstraintAttrs(List *constraintList);
+static void transformConstraintAttrs(ParseState *pstate, List *constraintList);
 static void transformColumnType(ParseState *pstate, ColumnDef *column);
 static void setSchemaName(char *context_schema, char **stmt_schema_name);
 
@@ -178,6 +187,11 @@ transformCreateStmt(CreateStmt *stmt, const char *queryString)
        cxt.pkey = NULL;
        cxt.hasoids = interpretOidsOption(stmt->options);
 
+       Assert(!stmt->ofTypename || !stmt->inhRelations);       /* grammar enforces */
+
+       if (stmt->ofTypename)
+               transformOfType(pstate, &cxt, stmt->ofTypename);
+
        /*
         * Run through each primary element in the table creation clause. Separate
         * column defs from constraints, and do preliminary analysis.
@@ -198,11 +212,6 @@ transformCreateStmt(CreateStmt *stmt, const char *queryString)
                                                                                 (Constraint *) element);
                                break;
 
-                       case T_FkConstraint:
-                               /* No pre-transformation needed */
-                               cxt.fkconstraints = lappend(cxt.fkconstraints, element);
-                               break;
-
                        case T_InhRelation:
                                transformInhRelation(pstate, &cxt,
                                                                         (InhRelation *) element);
@@ -266,39 +275,42 @@ transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
 
        /* Check for SERIAL pseudo-types */
        is_serial = false;
-       if (list_length(column->typename->names) == 1 &&
-               !column->typename->pct_type)
+       if (column->typeName
+               && list_length(column->typeName->names) == 1
+               && !column->typeName->pct_type)
        {
-               char       *typname = strVal(linitial(column->typename->names));
+               char       *typname = strVal(linitial(column->typeName->names));
 
                if (strcmp(typname, "serial") == 0 ||
                        strcmp(typname, "serial4") == 0)
                {
                        is_serial = true;
-                       column->typename->names = NIL;
-                       column->typename->typeid = INT4OID;
+                       column->typeName->names = NIL;
+                       column->typeName->typeOid = INT4OID;
                }
                else if (strcmp(typname, "bigserial") == 0 ||
                                 strcmp(typname, "serial8") == 0)
                {
                        is_serial = true;
-                       column->typename->names = NIL;
-                       column->typename->typeid = INT8OID;
+                       column->typeName->names = NIL;
+                       column->typeName->typeOid = INT8OID;
                }
 
                /*
-                * We have to reject "serial[]" explicitly, because once we've
-                * set typeid, LookupTypeName won't notice arrayBounds.  We don't
-                * need any special coding for serial(typmod) though.
+                * We have to reject "serial[]" explicitly, because once we've set
+                * typeid, LookupTypeName won't notice arrayBounds.  We don't need any
+                * special coding for serial(typmod) though.
                 */
-               if (is_serial && column->typename->arrayBounds != NIL)
+               if (is_serial && column->typeName->arrayBounds != NIL)
                        ereport(ERROR,
                                        (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-                                        errmsg("array of serial is not implemented")));
+                                        errmsg("array of serial is not implemented"),
+                                        parser_errposition(pstate, column->typeName->location)));
        }
 
        /* Do necessary work on the column type declaration */
-       transformColumnType(pstate, column);
+       if (column->typeName)
+               transformColumnType(pstate, column);
 
        /* Special actions for SERIAL pseudo-types */
        if (is_serial)
@@ -346,9 +358,21 @@ transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
                 * TABLE.
                 */
                seqstmt = makeNode(CreateSeqStmt);
-               seqstmt->sequence = makeRangeVar(snamespace, sname);
+               seqstmt->sequence = makeRangeVar(snamespace, sname, -1);
                seqstmt->options = NIL;
 
+               /*
+                * If this is ALTER ADD COLUMN, make sure the sequence will be owned
+                * by the table's owner.  The current user might be someone else
+                * (perhaps a superuser, or someone who's only a member of the owning
+                * role), but the SEQUENCE OWNED BY mechanisms will bleat unless
+                * table and sequence have exactly the same owning role.
+                */
+               if (cxt->rel)
+                       seqstmt->ownerId = cxt->rel->rd_rel->relowner;
+               else
+                       seqstmt->ownerId = InvalidOid;
+
                cxt->blist = lappend(cxt->blist, seqstmt);
 
                /*
@@ -357,7 +381,7 @@ transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
                 * done after this CREATE/ALTER TABLE.
                 */
                altseqstmt = makeNode(AlterSeqStmt);
-               altseqstmt->sequence = makeRangeVar(snamespace, sname);
+               altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
                attnamelist = list_make3(makeString(snamespace),
                                                                 makeString(cxt->relation->relname),
                                                                 makeString(column->colname));
@@ -380,31 +404,36 @@ transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
                snamenode = makeNode(A_Const);
                snamenode->val.type = T_String;
                snamenode->val.val.str = qstring;
+               snamenode->location = -1;
                castnode = makeNode(TypeCast);
-               castnode->typename = SystemTypeName("regclass");
+               castnode->typeName = SystemTypeName("regclass");
                castnode->arg = (Node *) snamenode;
+               castnode->location = -1;
                funccallnode = makeNode(FuncCall);
                funccallnode->funcname = SystemFuncName("nextval");
                funccallnode->args = list_make1(castnode);
+               funccallnode->agg_order = NIL;
                funccallnode->agg_star = false;
                funccallnode->agg_distinct = false;
                funccallnode->func_variadic = false;
+               funccallnode->over = NULL;
                funccallnode->location = -1;
 
                constraint = makeNode(Constraint);
                constraint->contype = CONSTR_DEFAULT;
+               constraint->location = -1;
                constraint->raw_expr = (Node *) funccallnode;
                constraint->cooked_expr = NULL;
-               constraint->keys = NIL;
                column->constraints = lappend(column->constraints, constraint);
 
                constraint = makeNode(Constraint);
                constraint->contype = CONSTR_NOTNULL;
+               constraint->location = -1;
                column->constraints = lappend(column->constraints, constraint);
        }
 
        /* Process column constraints, if any... */
-       transformConstraintAttrs(column->constraints);
+       transformConstraintAttrs(pstate, column->constraints);
 
        saw_nullable = false;
        saw_default = false;
@@ -412,21 +441,6 @@ transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
        foreach(clist, column->constraints)
        {
                constraint = lfirst(clist);
-
-               /*
-                * If this column constraint is a FOREIGN KEY constraint, then we fill
-                * in the current attribute's name and throw it into the list of FK
-                * constraints to be processed later.
-                */
-               if (IsA(constraint, FkConstraint))
-               {
-                       FkConstraint *fkconstraint = (FkConstraint *) constraint;
-
-                       fkconstraint->fk_attrs = list_make1(makeString(column->colname));
-                       cxt->fkconstraints = lappend(cxt->fkconstraints, fkconstraint);
-                       continue;
-               }
-
                Assert(IsA(constraint, Constraint));
 
                switch (constraint->contype)
@@ -436,7 +450,9 @@ transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
                                        ereport(ERROR,
                                                        (errcode(ERRCODE_SYNTAX_ERROR),
                                                         errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
-                                                                 column->colname, cxt->relation->relname)));
+                                                                       column->colname, cxt->relation->relname),
+                                                        parser_errposition(pstate,
+                                                                                               constraint->location)));
                                column->is_not_null = FALSE;
                                saw_nullable = true;
                                break;
@@ -446,7 +462,9 @@ transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
                                        ereport(ERROR,
                                                        (errcode(ERRCODE_SYNTAX_ERROR),
                                                         errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
-                                                                 column->colname, cxt->relation->relname)));
+                                                                       column->colname, cxt->relation->relname),
+                                                        parser_errposition(pstate,
+                                                                                               constraint->location)));
                                column->is_not_null = TRUE;
                                saw_nullable = true;
                                break;
@@ -456,12 +474,18 @@ transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
                                        ereport(ERROR,
                                                        (errcode(ERRCODE_SYNTAX_ERROR),
                                                         errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
-                                                                 column->colname, cxt->relation->relname)));
+                                                                       column->colname, cxt->relation->relname),
+                                                        parser_errposition(pstate,
+                                                                                               constraint->location)));
                                column->raw_default = constraint->raw_expr;
                                Assert(constraint->cooked_expr == NULL);
                                saw_default = true;
                                break;
 
+                       case CONSTR_CHECK:
+                               cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
+                               break;
+
                        case CONSTR_PRIMARY:
                        case CONSTR_UNIQUE:
                                if (constraint->keys == NIL)
@@ -469,8 +493,19 @@ transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
                                cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
                                break;
 
-                       case CONSTR_CHECK:
-                               cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
+                       case CONSTR_EXCLUSION:
+                               /* grammar does not allow EXCLUDE as a column constraint */
+                               elog(ERROR, "column exclusion constraints are not supported");
+                               break;
+
+                       case CONSTR_FOREIGN:
+
+                               /*
+                                * Fill in the current attribute's name and throw it into the
+                                * list of FK constraints to be processed later.
+                                */
+                               constraint->fk_attrs = list_make1(makeString(column->colname));
+                               cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
                                break;
 
                        case CONSTR_ATTR_DEFERRABLE:
@@ -500,6 +535,7 @@ transformTableConstraint(ParseState *pstate, CreateStmtContext *cxt,
        {
                case CONSTR_PRIMARY:
                case CONSTR_UNIQUE:
+               case CONSTR_EXCLUSION:
                        cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
                        break;
 
@@ -507,6 +543,10 @@ transformTableConstraint(ParseState *pstate, CreateStmtContext *cxt,
                        cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
                        break;
 
+               case CONSTR_FOREIGN:
+                       cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
+                       break;
+
                case CONSTR_NULL:
                case CONSTR_NOTNULL:
                case CONSTR_DEFAULT:
@@ -541,12 +581,9 @@ transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
        TupleDesc       tupleDesc;
        TupleConstr *constr;
        AclResult       aclresult;
-       bool            including_defaults = false;
-       bool            including_constraints = false;
-       bool            including_indexes = false;
-       ListCell   *elem;
+       char       *comment;
 
-       relation = heap_openrv(inhRelation->relation, AccessShareLock);
+       relation = parserOpenTable(pstate, inhRelation->relation, AccessShareLock);
 
        if (relation->rd_rel->relkind != RELKIND_RELATION)
                ereport(ERROR,
@@ -566,36 +603,6 @@ transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
        tupleDesc = RelationGetDescr(relation);
        constr = tupleDesc->constr;
 
-       foreach(elem, inhRelation->options)
-       {
-               int                     option = lfirst_int(elem);
-
-               switch (option)
-               {
-                       case CREATE_TABLE_LIKE_INCLUDING_DEFAULTS:
-                               including_defaults = true;
-                               break;
-                       case CREATE_TABLE_LIKE_EXCLUDING_DEFAULTS:
-                               including_defaults = false;
-                               break;
-                       case CREATE_TABLE_LIKE_INCLUDING_CONSTRAINTS:
-                               including_constraints = true;
-                               break;
-                       case CREATE_TABLE_LIKE_EXCLUDING_CONSTRAINTS:
-                               including_constraints = false;
-                               break;
-                       case CREATE_TABLE_LIKE_INCLUDING_INDEXES:
-                               including_indexes = true;
-                               break;
-                       case CREATE_TABLE_LIKE_EXCLUDING_INDEXES:
-                               including_indexes = false;
-                               break;
-                       default:
-                               elog(ERROR, "unrecognized CREATE TABLE LIKE option: %d",
-                                        option);
-               }
-       }
-
        /*
         * Insert the copied attributes into the cxt for the new table definition.
         */
@@ -620,7 +627,7 @@ transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
                 */
                def = makeNode(ColumnDef);
                def->colname = pstrdup(attributeName);
-               def->typename = makeTypeNameFromOid(attribute->atttypid,
+               def->typeName = makeTypeNameFromOid(attribute->atttypid,
                                                                                        attribute->atttypmod);
                def->inhcount = 0;
                def->is_local = true;
@@ -637,9 +644,10 @@ transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
                /*
                 * Copy default, if present and the default has been requested
                 */
-               if (attribute->atthasdef && including_defaults)
+               if (attribute->atthasdef &&
+                       (inhRelation->options & CREATE_TABLE_LIKE_DEFAULTS))
                {
-                       char       *this_default = NULL;
+                       Node       *this_default = NULL;
                        AttrDefault *attrdef;
                        int                     i;
 
@@ -650,7 +658,7 @@ transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
                        {
                                if (attrdef[i].adnum == parent_attno)
                                {
-                                       this_default = attrdef[i].adbin;
+                                       this_default = stringToNode(attrdef[i].adbin);
                                        break;
                                }
                        }
@@ -661,7 +669,31 @@ transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
                         * but it can't; so default is ready to apply to child.
                         */
 
-                       def->cooked_default = pstrdup(this_default);
+                       def->cooked_default = this_default;
+               }
+
+               /* Likewise, copy storage if requested */
+               if (inhRelation->options & CREATE_TABLE_LIKE_STORAGE)
+                       def->storage = attribute->attstorage;
+               else
+                       def->storage = 0;
+
+               /* Likewise, copy comment if requested */
+               if ((inhRelation->options & CREATE_TABLE_LIKE_COMMENTS) &&
+                       (comment = GetComment(attribute->attrelid,
+                                                                 RelationRelationId,
+                                                                 attribute->attnum)) != NULL)
+               {
+                       CommentStmt *stmt = makeNode(CommentStmt);
+
+                       stmt->objtype = OBJECT_COLUMN;
+                       stmt->objname = list_make3(makeString(cxt->relation->schemaname),
+                                                                          makeString(cxt->relation->relname),
+                                                                          makeString(def->colname));
+                       stmt->objargs = NIL;
+                       stmt->comment = comment;
+
+                       cxt->alist = lappend(cxt->alist, stmt);
                }
        }
 
@@ -669,7 +701,8 @@ transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
         * Copy CHECK constraints if requested, being careful to adjust attribute
         * numbers
         */
-       if (including_constraints && tupleDesc->constr)
+       if ((inhRelation->options & CREATE_TABLE_LIKE_CONSTRAINTS) &&
+               tupleDesc->constr)
        {
                AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
                int                     ccnum;
@@ -684,18 +717,38 @@ transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
                        change_varattnos_of_a_node(ccbin_node, attmap);
 
                        n->contype = CONSTR_CHECK;
-                       n->name = pstrdup(ccname);
+                       n->location = -1;
+                       n->conname = pstrdup(ccname);
                        n->raw_expr = NULL;
                        n->cooked_expr = nodeToString(ccbin_node);
-                       n->indexspace = NULL;
-                       cxt->ckconstraints = lappend(cxt->ckconstraints, (Node *) n);
+                       cxt->ckconstraints = lappend(cxt->ckconstraints, n);
+
+                       /* Copy comment on constraint */
+                       if ((inhRelation->options & CREATE_TABLE_LIKE_COMMENTS) &&
+                               (comment = GetComment(get_constraint_oid(RelationGetRelid(relation),
+                                                                                                                 n->conname, false),
+                                                                         ConstraintRelationId,
+                                                                         0)) != NULL)
+                       {
+                               CommentStmt *stmt = makeNode(CommentStmt);
+
+                               stmt->objtype = OBJECT_CONSTRAINT;
+                               stmt->objname = list_make3(makeString(cxt->relation->schemaname),
+                                                                                  makeString(cxt->relation->relname),
+                                                                                  makeString(n->conname));
+                               stmt->objargs = NIL;
+                               stmt->comment = comment;
+
+                               cxt->alist = lappend(cxt->alist, stmt);
+                       }
                }
        }
 
        /*
         * Likewise, copy indexes if requested
         */
-       if (including_indexes && relation->rd_rel->relhasindex)
+       if ((inhRelation->options & CREATE_TABLE_LIKE_INDEXES) &&
+               relation->rd_rel->relhasindex)
        {
                AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
                List       *parent_indexes;
@@ -714,6 +767,35 @@ transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
                        /* Build CREATE INDEX statement to recreate the parent_index */
                        index_stmt = generateClonedIndexStmt(cxt, parent_index, attmap);
 
+                       /* Copy comment on index */
+                       if (inhRelation->options & CREATE_TABLE_LIKE_COMMENTS)
+                       {
+                               comment = GetComment(parent_index_oid, RelationRelationId, 0);
+
+                               if (comment != NULL)
+                               {
+                                       CommentStmt *stmt;
+
+                                       /*
+                                        * We have to assign the index a name now, so that we can
+                                        * reference it in CommentStmt.
+                                        */
+                                       if (index_stmt->idxname == NULL)
+                                               index_stmt->idxname = chooseIndexName(cxt->relation,
+                                                                                                                         index_stmt);
+
+                                       stmt = makeNode(CommentStmt);
+                                       stmt->objtype = OBJECT_INDEX;
+                                       stmt->objname =
+                                               list_make2(makeString(cxt->relation->schemaname),
+                                                                  makeString(index_stmt->idxname));
+                                       stmt->objargs = NIL;
+                                       stmt->comment = comment;
+
+                                       cxt->alist = lappend(cxt->alist, stmt);
+                               }
+                       }
+
                        /* Save it in the inh_indexes list for the time being */
                        cxt->inh_indexes = lappend(cxt->inh_indexes, index_stmt);
 
@@ -729,6 +811,72 @@ transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
        heap_close(relation, NoLock);
 }
 
+static void
+transformOfType(ParseState *pstate, CreateStmtContext *cxt, TypeName *ofTypename)
+{
+       HeapTuple       tuple;
+       Form_pg_type typ;
+       TupleDesc       tupdesc;
+       int                     i;
+       Oid                     ofTypeId;
+
+       AssertArg(ofTypename);
+
+       tuple = typenameType(NULL, ofTypename, NULL);
+       typ = (Form_pg_type) GETSTRUCT(tuple);
+       ofTypeId = HeapTupleGetOid(tuple);
+       ofTypename->typeOid = ofTypeId;         /* cached for later */
+
+       if (typ->typtype != TYPTYPE_COMPOSITE)
+               ereport(ERROR,
+                               (errcode(ERRCODE_WRONG_OBJECT_TYPE),
+                                errmsg("type %s is not a composite type",
+                                               format_type_be(ofTypeId))));
+
+       tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
+       for (i = 0; i < tupdesc->natts; i++)
+       {
+               Form_pg_attribute attr = tupdesc->attrs[i];
+               ColumnDef  *n = makeNode(ColumnDef);
+
+               if (attr->attisdropped)
+                       continue;
+
+               n->colname = pstrdup(NameStr(attr->attname));
+               n->typeName = makeTypeNameFromOid(attr->atttypid, attr->atttypmod);
+               n->constraints = NULL;
+               n->is_local = true;
+               n->is_from_type = true;
+               cxt->columns = lappend(cxt->columns, n);
+       }
+       DecrTupleDescRefCount(tupdesc);
+
+       ReleaseSysCache(tuple);
+}
+
+/*
+ * chooseIndexName
+ *
+ * Compute name for an index.  This must match code in indexcmds.c.
+ *
+ * XXX this is inherently broken because the indexes aren't created
+ * immediately, so we fail to resolve conflicts when the same name is
+ * derived for multiple indexes.  However, that's a reasonably uncommon
+ * situation, so we'll live with it for now.
+ */
+static char *
+chooseIndexName(const RangeVar *relation, IndexStmt *index_stmt)
+{
+       Oid                     namespaceId;
+       List       *colnames;
+
+       namespaceId = RangeVarGetCreationNamespace(relation);
+       colnames = ChooseIndexColumnNames(index_stmt->indexParams);
+       return ChooseIndexName(relation->relname, namespaceId,
+                                                  colnames, index_stmt->excludeOpNames,
+                                                  index_stmt->primary, index_stmt->isconstraint);
+}
+
 /*
  * Generate an IndexStmt node using information from an already existing index
  * "source_idx".  Attribute numbers should be adjusted according to attmap.
@@ -738,6 +886,7 @@ generateClonedIndexStmt(CreateStmtContext *cxt, Relation source_idx,
                                                AttrNumber *attmap)
 {
        Oid                     source_relid = RelationGetRelid(source_idx);
+       Form_pg_attribute *attrs = RelationGetDescr(source_idx)->attrs;
        HeapTuple       ht_idxrel;
        HeapTuple       ht_idx;
        Form_pg_class idxrelrec;
@@ -757,9 +906,7 @@ generateClonedIndexStmt(CreateStmtContext *cxt, Relation source_idx,
         * Fetch pg_class tuple of source index.  We can't use the copy in the
         * relcache entry because it doesn't include optional fields.
         */
-       ht_idxrel = SearchSysCache(RELOID,
-                                                          ObjectIdGetDatum(source_relid),
-                                                          0, 0, 0);
+       ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(source_relid));
        if (!HeapTupleIsValid(ht_idxrel))
                elog(ERROR, "cache lookup failed for relation %u", source_relid);
        idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
@@ -772,7 +919,7 @@ generateClonedIndexStmt(CreateStmtContext *cxt, Relation source_idx,
        /* Fetch pg_am tuple for source index from relcache entry */
        amrec = source_idx->rd_am;
 
-       /* Must get indclass the hard way, since it's not stored in relcache */
+       /* Extract indclass from the pg_index tuple */
        datum = SysCacheGetAttr(INDEXRELID, ht_idx,
                                                        Anum_pg_index_indclass, &isnull);
        Assert(!isnull);
@@ -797,16 +944,84 @@ generateClonedIndexStmt(CreateStmtContext *cxt, Relation source_idx,
        index->idxname = NULL;
 
        /*
-        * If the index is marked PRIMARY, it's certainly from a constraint;
-        * else, if it's not marked UNIQUE, it certainly isn't; else, we have
-        * to search pg_depend to see if there's an associated unique constraint.
+        * If the index is marked PRIMARY or has an exclusion condition, it's
+        * certainly from a constraint; else, if it's not marked UNIQUE, it
+        * certainly isn't.  If it is or might be from a constraint, we have to
+        * fetch the pg_constraint record.
         */
-       if (index->primary)
-               index->isconstraint = true;
-       else if (!index->unique)
-               index->isconstraint = false;
+       if (index->primary || index->unique || idxrelrec->relhasexclusion)
+       {
+               Oid                     constraintId = get_index_constraint(source_relid);
+
+               if (OidIsValid(constraintId))
+               {
+                       HeapTuple       ht_constr;
+                       Form_pg_constraint conrec;
+
+                       ht_constr = SearchSysCache1(CONSTROID,
+                                                                               ObjectIdGetDatum(constraintId));
+                       if (!HeapTupleIsValid(ht_constr))
+                               elog(ERROR, "cache lookup failed for constraint %u",
+                                        constraintId);
+                       conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
+
+                       index->isconstraint = true;
+                       index->deferrable = conrec->condeferrable;
+                       index->initdeferred = conrec->condeferred;
+
+                       /* If it's an exclusion constraint, we need the operator names */
+                       if (idxrelrec->relhasexclusion)
+                       {
+                               Datum      *elems;
+                               int                     nElems;
+                               int                     i;
+
+                               Assert(conrec->contype == CONSTRAINT_EXCLUSION);
+                               /* Extract operator OIDs from the pg_constraint tuple */
+                               datum = SysCacheGetAttr(CONSTROID, ht_constr,
+                                                                               Anum_pg_constraint_conexclop,
+                                                                               &isnull);
+                               if (isnull)
+                                       elog(ERROR, "null conexclop for constraint %u",
+                                                constraintId);
+
+                               deconstruct_array(DatumGetArrayTypeP(datum),
+                                                                 OIDOID, sizeof(Oid), true, 'i',
+                                                                 &elems, NULL, &nElems);
+
+                               for (i = 0; i < nElems; i++)
+                               {
+                                       Oid                     operid = DatumGetObjectId(elems[i]);
+                                       HeapTuple       opertup;
+                                       Form_pg_operator operform;
+                                       char       *oprname;
+                                       char       *nspname;
+                                       List       *namelist;
+
+                                       opertup = SearchSysCache1(OPEROID,
+                                                                                         ObjectIdGetDatum(operid));
+                                       if (!HeapTupleIsValid(opertup))
+                                               elog(ERROR, "cache lookup failed for operator %u",
+                                                        operid);
+                                       operform = (Form_pg_operator) GETSTRUCT(opertup);
+                                       oprname = pstrdup(NameStr(operform->oprname));
+                                       /* For simplicity we always schema-qualify the op name */
+                                       nspname = get_namespace_name(operform->oprnamespace);
+                                       namelist = list_make2(makeString(nspname),
+                                                                                 makeString(oprname));
+                                       index->excludeOpNames = lappend(index->excludeOpNames,
+                                                                                                       namelist);
+                                       ReleaseSysCache(opertup);
+                               }
+                       }
+
+                       ReleaseSysCache(ht_constr);
+               }
+               else
+                       index->isconstraint = false;
+       }
        else
-               index->isconstraint = OidIsValid(get_index_constraint(source_relid));
+               index->isconstraint = false;
 
        /* Get the index expressions, if any */
        datum = SysCacheGetAttr(INDEXRELID, ht_idx,
@@ -863,6 +1078,9 @@ generateClonedIndexStmt(CreateStmtContext *cxt, Relation source_idx,
                        keycoltype = exprType(indexkey);
                }
 
+               /* Copy the original index column name */
+               iparam->indexcolname = pstrdup(NameStr(attrs[keyno]->attname));
+
                /* Add the operator class name, if non-default */
                iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
 
@@ -873,10 +1091,10 @@ generateClonedIndexStmt(CreateStmtContext *cxt, Relation source_idx,
                if (amrec->amcanorder)
                {
                        /*
-                        * If it supports sort ordering, copy DESC and NULLS opts.
-                        * Don't set non-default settings unnecessarily, though,
-                        * so as to improve the chance of recognizing equivalence
-                        * to constraint indexes.
+                        * If it supports sort ordering, copy DESC and NULLS opts. Don't
+                        * set non-default settings unnecessarily, though, so as to
+                        * improve the chance of recognizing equivalence to constraint
+                        * indexes.
                         */
                        if (opt & INDOPTION_DESC)
                        {
@@ -933,9 +1151,7 @@ get_opclass(Oid opclass, Oid actual_datatype)
        Form_pg_opclass opc_rec;
        List       *result = NIL;
 
-       ht_opc = SearchSysCache(CLAOID,
-                                                       ObjectIdGetDatum(opclass),
-                                                       0, 0, 0);
+       ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
        if (!HeapTupleIsValid(ht_opc))
                elog(ERROR, "cache lookup failed for opclass %u", opclass);
        opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
@@ -956,7 +1172,7 @@ get_opclass(Oid opclass, Oid actual_datatype)
 
 /*
  * transformIndexConstraints
- *             Handle UNIQUE and PRIMARY KEY constraints, which create indexes.
+ *             Handle UNIQUE, PRIMARY KEY, EXCLUDE constraints, which create indexes.
  *             We also merge in any index definitions arising from
  *             LIKE ... INCLUDING INDEXES.
  */
@@ -969,8 +1185,9 @@ transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
 
        /*
         * Run through the constraints that need to generate an index. For PRIMARY
-        * KEY, mark each column as NOT NULL and create an index. For UNIQUE,
-        * create an index as for PRIMARY KEY, but do not insist on NOT NULL.
+        * KEY, mark each column as NOT NULL and create an index. For UNIQUE or
+        * EXCLUDE, create an index as for PRIMARY KEY, but do not insist on NOT
+        * NULL.
         */
        foreach(lc, cxt->ixconstraints)
        {
@@ -978,7 +1195,8 @@ transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
 
                Assert(IsA(constraint, Constraint));
                Assert(constraint->contype == CONSTR_PRIMARY ||
-                          constraint->contype == CONSTR_UNIQUE);
+                          constraint->contype == CONSTR_UNIQUE ||
+                          constraint->contype == CONSTR_EXCLUSION);
 
                index = transformIndexConstraint(constraint, cxt);
 
@@ -1036,9 +1254,13 @@ transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
 
                        if (equal(index->indexParams, priorindex->indexParams) &&
                                equal(index->whereClause, priorindex->whereClause) &&
-                               strcmp(index->accessMethod, priorindex->accessMethod) == 0)
+                               equal(index->excludeOpNames, priorindex->excludeOpNames) &&
+                               strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
+                               index->deferrable == priorindex->deferrable &&
+                               index->initdeferred == priorindex->initdeferred)
                        {
                                priorindex->unique |= index->unique;
+
                                /*
                                 * If the prior index is as yet unnamed, and this one is
                                 * named, then transfer the name to the prior index. This
@@ -1059,19 +1281,18 @@ transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
 
 /*
  * transformIndexConstraint
- *             Transform one UNIQUE or PRIMARY KEY constraint for
+ *             Transform one UNIQUE, PRIMARY KEY, or EXCLUDE constraint for
  *             transformIndexConstraints.
  */
 static IndexStmt *
 transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
 {
        IndexStmt  *index;
-       ListCell   *keys;
-       IndexElem  *iparam;
+       ListCell   *lc;
 
        index = makeNode(IndexStmt);
 
-       index->unique = true;
+       index->unique = (constraint->contype != CONSTR_EXCLUSION);
        index->primary = (constraint->contype == CONSTR_PRIMARY);
        if (index->primary)
        {
@@ -1088,32 +1309,64 @@ transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
                 */
        }
        index->isconstraint = true;
+       index->deferrable = constraint->deferrable;
+       index->initdeferred = constraint->initdeferred;
 
-       if (constraint->name != NULL)
-               index->idxname = pstrdup(constraint->name);
+       if (constraint->conname != NULL)
+               index->idxname = pstrdup(constraint->conname);
        else
                index->idxname = NULL;  /* DefineIndex will choose name */
 
        index->relation = cxt->relation;
-       index->accessMethod = DEFAULT_INDEX_TYPE;
+       index->accessMethod = constraint->access_method ? constraint->access_method : DEFAULT_INDEX_TYPE;
        index->options = constraint->options;
        index->tableSpace = constraint->indexspace;
+       index->whereClause = constraint->where_clause;
        index->indexParams = NIL;
-       index->whereClause = NULL;
+       index->excludeOpNames = NIL;
        index->concurrent = false;
 
        /*
+        * If it's an EXCLUDE constraint, the grammar returns a list of pairs of
+        * IndexElems and operator names.  We have to break that apart into
+        * separate lists.
+        */
+       if (constraint->contype == CONSTR_EXCLUSION)
+       {
+               foreach(lc, constraint->exclusions)
+               {
+                       List       *pair = (List *) lfirst(lc);
+                       IndexElem  *elem;
+                       List       *opname;
+
+                       Assert(list_length(pair) == 2);
+                       elem = (IndexElem *) linitial(pair);
+                       Assert(IsA(elem, IndexElem));
+                       opname = (List *) lsecond(pair);
+                       Assert(IsA(opname, List));
+
+                       index->indexParams = lappend(index->indexParams, elem);
+                       index->excludeOpNames = lappend(index->excludeOpNames, opname);
+               }
+
+               return index;
+       }
+
+       /*
+        * For UNIQUE and PRIMARY KEY, we just have a list of column names.
+        *
         * Make sure referenced keys exist.  If we are making a PRIMARY KEY index,
         * also make sure they are NOT NULL, if possible. (Although we could leave
         * it to DefineIndex to mark the columns NOT NULL, it's more efficient to
         * get it right the first time.)
         */
-       foreach(keys, constraint->keys)
+       foreach(lc, constraint->keys)
        {
-               char       *key = strVal(lfirst(keys));
+               char       *key = strVal(lfirst(lc));
                bool            found = false;
                ColumnDef  *column = NULL;
                ListCell   *columns;
+               IndexElem  *iparam;
 
                foreach(columns, cxt->columns)
                {
@@ -1219,6 +1472,7 @@ transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
                iparam = makeNode(IndexElem);
                iparam->name = pstrdup(key);
                iparam->expr = NULL;
+               iparam->indexcolname = NULL;
                iparam->opclass = NIL;
                iparam->ordering = SORTBY_DEFAULT;
                iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
@@ -1249,9 +1503,9 @@ transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
        {
                foreach(fkclist, cxt->fkconstraints)
                {
-                       FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
+                       Constraint *constraint = (Constraint *) lfirst(fkclist);
 
-                       fkconstraint->skip_validation = true;
+                       constraint->skip_validation = true;
                }
        }
 
@@ -1276,12 +1530,12 @@ transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
 
                foreach(fkclist, cxt->fkconstraints)
                {
-                       FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
+                       Constraint *constraint = (Constraint *) lfirst(fkclist);
                        AlterTableCmd *altercmd = makeNode(AlterTableCmd);
 
                        altercmd->subtype = AT_ProcessedConstraint;
                        altercmd->name = NULL;
-                       altercmd->def = (Node *) fkconstraint;
+                       altercmd->def = (Node *) constraint;
                        alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
                }
 
@@ -1290,7 +1544,7 @@ transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
 }
 
 /*
- * transformIndexStmt - parse analysis for CREATE INDEX
+ * transformIndexStmt - parse analysis for CREATE INDEX and ALTER TABLE
  *
  * Note: this is a no-op for an index not using either index expressions or
  * a predicate expression.     There are several code paths that create indexes
@@ -1316,7 +1570,8 @@ transformIndexStmt(IndexStmt *stmt, const char *queryString)
         * because addRangeTableEntry() would acquire only AccessShareLock,
         * leaving DefineIndex() needing to do a lock upgrade with consequent risk
         * of deadlock.  Make sure this stays in sync with the type of lock
-        * DefineIndex() wants.
+        * DefineIndex() wants. If we are being called by ALTER TABLE, we will
+        * already hold a higher lock.
         */
        rel = heap_openrv(stmt->relation,
                                  (stmt->concurrent ? ShareUpdateExclusiveLock : ShareLock));
@@ -1347,6 +1602,11 @@ transformIndexStmt(IndexStmt *stmt, const char *queryString)
 
                if (ielem->expr)
                {
+                       /* Extract preliminary index col name before transforming expr */
+                       if (ielem->indexcolname == NULL)
+                               ielem->indexcolname = FigureIndexColname(ielem->expr);
+
+                       /* Now do parse transformation of the expression */
                        ielem->expr = transformExpr(pstate, ielem->expr);
 
                        /*
@@ -1417,10 +1677,10 @@ transformRuleStmt(RuleStmt *stmt, const char *queryString,
         * qualification.
         */
        oldrte = addRangeTableEntryForRelation(pstate, rel,
-                                                                                  makeAlias("*OLD*", NIL),
+                                                                                  makeAlias("old", NIL),
                                                                                   false, false);
        newrte = addRangeTableEntryForRelation(pstate, rel,
-                                                                                  makeAlias("*NEW*", NIL),
+                                                                                  makeAlias("new", NIL),
                                                                                   false, false);
        /* Must override addRangeTableEntry's default access-check flags */
        oldrte->requiredPerms = 0;
@@ -1469,6 +1729,10 @@ transformRuleStmt(RuleStmt *stmt, const char *queryString,
                ereport(ERROR,
                                (errcode(ERRCODE_GROUPING_ERROR),
                   errmsg("cannot use aggregate function in rule WHERE condition")));
+       if (pstate->p_hasWindowFuncs)
+               ereport(ERROR,
+                               (errcode(ERRCODE_WINDOWING_ERROR),
+                         errmsg("cannot use window function in rule WHERE condition")));
 
        /*
         * 'instead nothing' rules with a qualification need a query rangetable so
@@ -1517,10 +1781,10 @@ transformRuleStmt(RuleStmt *stmt, const char *queryString,
                         * them in the joinlist.
                         */
                        oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
-                                                                                                  makeAlias("*OLD*", NIL),
+                                                                                                  makeAlias("old", NIL),
                                                                                                   false, false);
                        newrte = addRangeTableEntryForRelation(sub_pstate, rel,
-                                                                                                  makeAlias("*NEW*", NIL),
+                                                                                                  makeAlias("new", NIL),
                                                                                                   false, false);
                        oldrte->requiredPerms = 0;
                        newrte->requiredPerms = 0;
@@ -1603,6 +1867,35 @@ transformRuleStmt(RuleStmt *stmt, const char *queryString,
                                        break;
                        }
 
+                       /*
+                        * OLD/NEW are not allowed in WITH queries, because they would
+                        * amount to outer references for the WITH, which we disallow.
+                        * However, they were already in the outer rangetable when we
+                        * analyzed the query, so we have to check.
+                        *
+                        * Note that in the INSERT...SELECT case, we need to examine
+                        * the CTE lists of both top_subqry and sub_qry.
+                        *
+                        * Note that we aren't digging into the body of the query
+                        * looking for WITHs in nested sub-SELECTs.  A WITH down there
+                        * can legitimately refer to OLD/NEW, because it'd be an
+                        * indirect-correlated outer reference.
+                        */
+                       if (rangeTableEntry_used((Node *) top_subqry->cteList,
+                                                                        PRS2_OLD_VARNO, 0) ||
+                               rangeTableEntry_used((Node *) sub_qry->cteList,
+                                                                         PRS2_OLD_VARNO, 0))
+                               ereport(ERROR,
+                                               (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+                                                errmsg("cannot refer to OLD within WITH query")));
+                       if (rangeTableEntry_used((Node *) top_subqry->cteList,
+                                                                        PRS2_NEW_VARNO, 0) ||
+                               rangeTableEntry_used((Node *) sub_qry->cteList,
+                                                                        PRS2_NEW_VARNO, 0))
+                               ereport(ERROR,
+                                               (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+                                                errmsg("cannot refer to NEW within WITH query")));
+
                        /*
                         * For efficiency's sake, add OLD to the rule action's jointree
                         * only if it was actually referenced in the statement or qual.
@@ -1672,6 +1965,7 @@ transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString)
        List       *newcmds = NIL;
        bool            skipValidation = true;
        AlterTableCmd *newcmd;
+       LOCKMODE        lockmode;
 
        /*
         * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
@@ -1680,13 +1974,19 @@ transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString)
        stmt = (AlterTableStmt *) copyObject(stmt);
 
        /*
-        * Acquire exclusive lock on the target relation, which will be held until
+        * Assign the appropriate lock level for this list of subcommands.
+        */
+       lockmode = AlterTableGetLockLevel(stmt->cmds);
+
+       /*
+        * Acquire appropriate lock on the target relation, which will be held until
         * end of transaction.  This ensures any decisions we make here based on
         * the state of the relation will still be good at execution. We must get
-        * exclusive lock now because execution will; taking a lower grade lock
-        * now and trying to upgrade later risks deadlock.
+        * lock now because execution will later require it; taking a lower grade lock
+        * now and trying to upgrade later risks deadlock.  Any new commands we add
+        * after this must not upgrade the lock level requested here.
         */
-       rel = relation_openrv(stmt->relation, AccessExclusiveLock);
+       rel = relation_openrv(stmt->relation, lockmode);
 
        /* Set up pstate */
        pstate = make_parsestate(NULL);
@@ -1719,6 +2019,7 @@ transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString)
                switch (cmd->subtype)
                {
                        case AT_AddColumn:
+                       case AT_AddColumnToView:
                                {
                                        ColumnDef  *def = (ColumnDef *) cmd->def;
 
@@ -1747,12 +2048,11 @@ transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString)
                                 * The original AddConstraint cmd node doesn't go to newcmds
                                 */
                                if (IsA(cmd->def, Constraint))
+                               {
                                        transformTableConstraint(pstate, &cxt,
                                                                                         (Constraint *) cmd->def);
-                               else if (IsA(cmd->def, FkConstraint))
-                               {
-                                       cxt.fkconstraints = lappend(cxt.fkconstraints, cmd->def);
-                                       skipValidation = false;
+                                       if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
+                                               skipValidation = false;
                                }
                                else
                                        elog(ERROR, "unrecognized node type: %d",
@@ -1844,109 +2144,118 @@ transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString)
  * to attach constraint attributes to their primary constraint nodes
  * and detect inconsistent/misplaced constraint attributes.
  *
- * NOTE: currently, attributes are only supported for FOREIGN KEY primary
- * constraints, but someday they ought to be supported for other constraints.
+ * NOTE: currently, attributes are only supported for FOREIGN KEY, UNIQUE,
+ * and PRIMARY KEY constraints, but someday they ought to be supported
+ * for other constraint types.
  */
 static void
-transformConstraintAttrs(List *constraintList)
+transformConstraintAttrs(ParseState *pstate, List *constraintList)
 {
-       Node       *lastprimarynode = NULL;
+       Constraint *lastprimarycon = NULL;
        bool            saw_deferrability = false;
        bool            saw_initially = false;
        ListCell   *clist;
 
+#define SUPPORTS_ATTRS(node)                           \
+       ((node) != NULL &&                                              \
+        ((node)->contype == CONSTR_PRIMARY ||  \
+         (node)->contype == CONSTR_UNIQUE ||   \
+         (node)->contype == CONSTR_EXCLUSION || \
+         (node)->contype == CONSTR_FOREIGN))
+
        foreach(clist, constraintList)
        {
-               Node       *node = lfirst(clist);
+               Constraint *con = (Constraint *) lfirst(clist);
 
-               if (!IsA(node, Constraint))
+               if (!IsA(con, Constraint))
+                       elog(ERROR, "unrecognized node type: %d",
+                                (int) nodeTag(con));
+               switch (con->contype)
                {
-                       lastprimarynode = node;
-                       /* reset flags for new primary node */
-                       saw_deferrability = false;
-                       saw_initially = false;
-               }
-               else
-               {
-                       Constraint *con = (Constraint *) node;
+                       case CONSTR_ATTR_DEFERRABLE:
+                               if (!SUPPORTS_ATTRS(lastprimarycon))
+                                       ereport(ERROR,
+                                                       (errcode(ERRCODE_SYNTAX_ERROR),
+                                                        errmsg("misplaced DEFERRABLE clause"),
+                                                        parser_errposition(pstate, con->location)));
+                               if (saw_deferrability)
+                                       ereport(ERROR,
+                                                       (errcode(ERRCODE_SYNTAX_ERROR),
+                                                        errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
+                                                        parser_errposition(pstate, con->location)));
+                               saw_deferrability = true;
+                               lastprimarycon->deferrable = true;
+                               break;
 
-                       switch (con->contype)
-                       {
-                               case CONSTR_ATTR_DEFERRABLE:
-                                       if (lastprimarynode == NULL ||
-                                               !IsA(lastprimarynode, FkConstraint))
-                                               ereport(ERROR,
-                                                               (errcode(ERRCODE_SYNTAX_ERROR),
-                                                                errmsg("misplaced DEFERRABLE clause")));
-                                       if (saw_deferrability)
-                                               ereport(ERROR,
-                                                               (errcode(ERRCODE_SYNTAX_ERROR),
-                                                                errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
-                                       saw_deferrability = true;
-                                       ((FkConstraint *) lastprimarynode)->deferrable = true;
-                                       break;
-                               case CONSTR_ATTR_NOT_DEFERRABLE:
-                                       if (lastprimarynode == NULL ||
-                                               !IsA(lastprimarynode, FkConstraint))
-                                               ereport(ERROR,
-                                                               (errcode(ERRCODE_SYNTAX_ERROR),
-                                                                errmsg("misplaced NOT DEFERRABLE clause")));
-                                       if (saw_deferrability)
-                                               ereport(ERROR,
-                                                               (errcode(ERRCODE_SYNTAX_ERROR),
-                                                                errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
-                                       saw_deferrability = true;
-                                       ((FkConstraint *) lastprimarynode)->deferrable = false;
-                                       if (saw_initially &&
-                                               ((FkConstraint *) lastprimarynode)->initdeferred)
-                                               ereport(ERROR,
-                                                               (errcode(ERRCODE_SYNTAX_ERROR),
-                                                                errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
-                                       break;
-                               case CONSTR_ATTR_DEFERRED:
-                                       if (lastprimarynode == NULL ||
-                                               !IsA(lastprimarynode, FkConstraint))
-                                               ereport(ERROR,
-                                                               (errcode(ERRCODE_SYNTAX_ERROR),
-                                                        errmsg("misplaced INITIALLY DEFERRED clause")));
-                                       if (saw_initially)
-                                               ereport(ERROR,
-                                                               (errcode(ERRCODE_SYNTAX_ERROR),
-                                                                errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
-                                       saw_initially = true;
-                                       ((FkConstraint *) lastprimarynode)->initdeferred = true;
+                       case CONSTR_ATTR_NOT_DEFERRABLE:
+                               if (!SUPPORTS_ATTRS(lastprimarycon))
+                                       ereport(ERROR,
+                                                       (errcode(ERRCODE_SYNTAX_ERROR),
+                                                        errmsg("misplaced NOT DEFERRABLE clause"),
+                                                        parser_errposition(pstate, con->location)));
+                               if (saw_deferrability)
+                                       ereport(ERROR,
+                                                       (errcode(ERRCODE_SYNTAX_ERROR),
+                                                        errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
+                                                        parser_errposition(pstate, con->location)));
+                               saw_deferrability = true;
+                               lastprimarycon->deferrable = false;
+                               if (saw_initially &&
+                                       lastprimarycon->initdeferred)
+                                       ereport(ERROR,
+                                                       (errcode(ERRCODE_SYNTAX_ERROR),
+                                                        errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
+                                                        parser_errposition(pstate, con->location)));
+                               break;
 
-                                       /*
-                                        * If only INITIALLY DEFERRED appears, assume DEFERRABLE
-                                        */
-                                       if (!saw_deferrability)
-                                               ((FkConstraint *) lastprimarynode)->deferrable = true;
-                                       else if (!((FkConstraint *) lastprimarynode)->deferrable)
-                                               ereport(ERROR,
-                                                               (errcode(ERRCODE_SYNTAX_ERROR),
-                                                                errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
-                                       break;
-                               case CONSTR_ATTR_IMMEDIATE:
-                                       if (lastprimarynode == NULL ||
-                                               !IsA(lastprimarynode, FkConstraint))
-                                               ereport(ERROR,
-                                                               (errcode(ERRCODE_SYNTAX_ERROR),
-                                                       errmsg("misplaced INITIALLY IMMEDIATE clause")));
-                                       if (saw_initially)
-                                               ereport(ERROR,
-                                                               (errcode(ERRCODE_SYNTAX_ERROR),
-                                                                errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
-                                       saw_initially = true;
-                                       ((FkConstraint *) lastprimarynode)->initdeferred = false;
-                                       break;
-                               default:
-                                       /* Otherwise it's not an attribute */
-                                       lastprimarynode = node;
-                                       /* reset flags for new primary node */
-                                       saw_deferrability = false;
-                                       saw_initially = false;
-                                       break;
-                       }
+                       case CONSTR_ATTR_DEFERRED:
+                               if (!SUPPORTS_ATTRS(lastprimarycon))
+                                       ereport(ERROR,
+                                                       (errcode(ERRCODE_SYNTAX_ERROR),
+                                                        errmsg("misplaced INITIALLY DEFERRED clause"),
+                                                        parser_errposition(pstate, con->location)));
+                               if (saw_initially)
+                                       ereport(ERROR,
+                                                       (errcode(ERRCODE_SYNTAX_ERROR),
+                                                        errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
+                                                        parser_errposition(pstate, con->location)));
+                               saw_initially = true;
+                               lastprimarycon->initdeferred = true;
+
+                               /*
+                                * If only INITIALLY DEFERRED appears, assume DEFERRABLE
+                                */
+                               if (!saw_deferrability)
+                                       lastprimarycon->deferrable = true;
+                               else if (!lastprimarycon->deferrable)
+                                       ereport(ERROR,
+                                                       (errcode(ERRCODE_SYNTAX_ERROR),
+                                                        errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
+                                                        parser_errposition(pstate, con->location)));
+                               break;
+
+                       case CONSTR_ATTR_IMMEDIATE:
+                               if (!SUPPORTS_ATTRS(lastprimarycon))
+                                       ereport(ERROR,
+                                                       (errcode(ERRCODE_SYNTAX_ERROR),
+                                                        errmsg("misplaced INITIALLY IMMEDIATE clause"),
+                                                        parser_errposition(pstate, con->location)));
+                               if (saw_initially)
+                                       ereport(ERROR,
+                                                       (errcode(ERRCODE_SYNTAX_ERROR),
+                                                        errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
+                                                        parser_errposition(pstate, con->location)));
+                               saw_initially = true;
+                               lastprimarycon->initdeferred = false;
+                               break;
+
+                       default:
+                               /* Otherwise it's not an attribute */
+                               lastprimarycon = con;
+                               /* reset flags for new primary node */
+                               saw_deferrability = false;
+                               saw_initially = false;
+                               break;
                }
        }
 }
@@ -1960,7 +2269,7 @@ transformColumnType(ParseState *pstate, ColumnDef *column)
        /*
         * All we really need to do here is verify that the type is valid.
         */
-       Type            ctype = typenameType(pstate, column->typename, NULL);
+       Type            ctype = typenameType(pstate, column->typeName, NULL);
 
        ReleaseSysCache(ctype);
 }