Commit 077db40f authored by Tom Lane's avatar Tom Lane

ALTER TABLE rewrite. New cool stuff:

* ALTER ... ADD COLUMN with defaults and NOT NULL constraints works per SQL
spec.  A default is implemented by rewriting the table with the new value
stored in each row.

* ALTER COLUMN TYPE.  You can change a column's datatype to anything you
want, so long as you can specify how to convert the old value.  Rewrites
the table.  (Possible future improvement: optimize no-op conversions such
as varchar(N) to varchar(N+1).)

* Multiple ALTER actions in a single ALTER TABLE command.  You can perform
any number of column additions, type changes, and constraint additions with
only one pass over the table contents.

Basic documentation provided in ALTER TABLE ref page, but some more docs
work is needed.

Original patch from Rod Taylor, additional work from Tom Lane.
parent 3e3cb0a1
This diff is collapsed.
......@@ -9,7 +9,7 @@
*
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/bootstrap/bootparse.y,v 1.65 2004/03/23 19:35:16 tgl Exp $
* $PostgreSQL: pgsql/src/backend/bootstrap/bootparse.y,v 1.66 2004/05/05 04:48:45 tgl Exp $
*
*-------------------------------------------------------------------------
*/
......@@ -241,7 +241,9 @@ Boot_DeclareIndexStmt:
LexIDStr($3),
LexIDStr($7),
$9,
false, false, false, NULL, NIL);
NULL, NIL,
false, false, false,
false, false, true, false);
do_end();
}
;
......@@ -255,7 +257,9 @@ Boot_DeclareUniqueIndexStmt:
LexIDStr($4),
LexIDStr($8),
$10,
true, false, false, NULL, NIL);
NULL, NIL,
true, false, false,
false, false, true, false);
do_end();
}
;
......
......@@ -8,7 +8,7 @@
* Portions Copyright (c) 1994, Regents of the University of California
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/catalog/dependency.c,v 1.34 2003/11/29 19:51:42 pgsql Exp $
* $PostgreSQL: pgsql/src/backend/catalog/dependency.c,v 1.35 2004/05/05 04:48:45 tgl Exp $
*
*-------------------------------------------------------------------------
*/
......@@ -48,25 +48,6 @@
#include "utils/syscache.h"
/* This enum covers all system catalogs whose OIDs can appear in classid. */
typedef enum ObjectClasses
{
OCLASS_CLASS, /* pg_class */
OCLASS_PROC, /* pg_proc */
OCLASS_TYPE, /* pg_type */
OCLASS_CAST, /* pg_cast */
OCLASS_CONSTRAINT, /* pg_constraint */
OCLASS_CONVERSION, /* pg_conversion */
OCLASS_DEFAULT, /* pg_attrdef */
OCLASS_LANGUAGE, /* pg_language */
OCLASS_OPERATOR, /* pg_operator */
OCLASS_OPCLASS, /* pg_opclass */
OCLASS_REWRITE, /* pg_rewrite */
OCLASS_TRIGGER, /* pg_trigger */
OCLASS_SCHEMA, /* pg_namespace */
MAX_OCLASS /* MUST BE LAST */
} ObjectClasses;
/* expansible list of ObjectAddresses */
typedef struct
{
......@@ -113,7 +94,7 @@ static bool find_expr_references_walker(Node *node,
static void eliminate_duplicate_dependencies(ObjectAddresses *addrs);
static int object_address_comparator(const void *a, const void *b);
static void init_object_addresses(ObjectAddresses *addrs);
static void add_object_address(ObjectClasses oclass, Oid objectId, int32 subId,
static void add_object_address(ObjectClass oclass, Oid objectId, int32 subId,
ObjectAddresses *addrs);
static void add_exact_object_address(const ObjectAddress *object,
ObjectAddresses *addrs);
......@@ -121,8 +102,6 @@ static bool object_address_present(const ObjectAddress *object,
ObjectAddresses *addrs);
static void term_object_addresses(ObjectAddresses *addrs);
static void init_object_classes(void);
static ObjectClasses getObjectClass(const ObjectAddress *object);
static char *getObjectDescription(const ObjectAddress *object);
static void getRelationDescription(StringInfo buffer, Oid relid);
......@@ -1238,7 +1217,7 @@ init_object_addresses(ObjectAddresses *addrs)
* by catalog OID.
*/
static void
add_object_address(ObjectClasses oclass, Oid objectId, int32 subId,
add_object_address(ObjectClass oclass, Oid objectId, int32 subId,
ObjectAddresses *addrs)
{
ObjectAddress *item;
......@@ -1350,7 +1329,7 @@ init_object_classes(void)
* This function is needed just because some of the system catalogs do
* not have hardwired-at-compile-time OIDs.
*/
static ObjectClasses
ObjectClass
getObjectClass(const ObjectAddress *object)
{
/* Easy for the bootstrapped catalogs... */
......@@ -1435,7 +1414,7 @@ getObjectClass(const ObjectAddress *object)
*
* The result is a palloc'd string.
*/
static char *
char *
getObjectDescription(const ObjectAddress *object)
{
StringInfoData buffer;
......@@ -1447,18 +1426,18 @@ getObjectDescription(const ObjectAddress *object)
case OCLASS_CLASS:
getRelationDescription(&buffer, object->objectId);
if (object->objectSubId != 0)
appendStringInfo(&buffer, " column %s",
appendStringInfo(&buffer, gettext(" column %s"),
get_relid_attribute_name(object->objectId,
object->objectSubId));
break;
case OCLASS_PROC:
appendStringInfo(&buffer, "function %s",
appendStringInfo(&buffer, gettext("function %s"),
format_procedure(object->objectId));
break;
case OCLASS_TYPE:
appendStringInfo(&buffer, "type %s",
appendStringInfo(&buffer, gettext("type %s"),
format_type_be(object->objectId));
break;
......@@ -1488,7 +1467,7 @@ getObjectDescription(const ObjectAddress *object)
castForm = (Form_pg_cast) GETSTRUCT(tup);
appendStringInfo(&buffer, "cast from %s to %s",
appendStringInfo(&buffer, gettext("cast from %s to %s"),
format_type_be(castForm->castsource),
format_type_be(castForm->casttarget));
......@@ -1525,13 +1504,13 @@ getObjectDescription(const ObjectAddress *object)
if (OidIsValid(con->conrelid))
{
appendStringInfo(&buffer, "constraint %s on ",
appendStringInfo(&buffer, gettext("constraint %s on "),
NameStr(con->conname));
getRelationDescription(&buffer, con->conrelid);
}
else
{
appendStringInfo(&buffer, "constraint %s",
appendStringInfo(&buffer, gettext("constraint %s"),
NameStr(con->conname));
}
......@@ -1550,7 +1529,7 @@ getObjectDescription(const ObjectAddress *object)
if (!HeapTupleIsValid(conTup))
elog(ERROR, "cache lookup failed for conversion %u",
object->objectId);
appendStringInfo(&buffer, "conversion %s",
appendStringInfo(&buffer, gettext("conversion %s"),
NameStr(((Form_pg_conversion) GETSTRUCT(conTup))->conname));
ReleaseSysCache(conTup);
break;
......@@ -1587,7 +1566,7 @@ getObjectDescription(const ObjectAddress *object)
colobject.objectId = attrdef->adrelid;
colobject.objectSubId = attrdef->adnum;
appendStringInfo(&buffer, "default for %s",
appendStringInfo(&buffer, gettext("default for %s"),
getObjectDescription(&colobject));
systable_endscan(adscan);
......@@ -1605,14 +1584,14 @@ getObjectDescription(const ObjectAddress *object)
if (!HeapTupleIsValid(langTup))
elog(ERROR, "cache lookup failed for language %u",
object->objectId);
appendStringInfo(&buffer, "language %s",
appendStringInfo(&buffer, gettext("language %s"),
NameStr(((Form_pg_language) GETSTRUCT(langTup))->lanname));
ReleaseSysCache(langTup);
break;
}
case OCLASS_OPERATOR:
appendStringInfo(&buffer, "operator %s",
appendStringInfo(&buffer, gettext("operator %s"),
format_operator(object->objectId));
break;
......@@ -1632,16 +1611,6 @@ getObjectDescription(const ObjectAddress *object)
object->objectId);
opcForm = (Form_pg_opclass) GETSTRUCT(opcTup);
/* Qualify the name if not visible in search path */
if (OpclassIsVisible(object->objectId))
nspname = NULL;
else
nspname = get_namespace_name(opcForm->opcnamespace);
appendStringInfo(&buffer, "operator class %s",
quote_qualified_identifier(nspname,
NameStr(opcForm->opcname)));
amTup = SearchSysCache(AMOID,
ObjectIdGetDatum(opcForm->opcamid),
0, 0, 0);
......@@ -1650,7 +1619,15 @@ getObjectDescription(const ObjectAddress *object)
opcForm->opcamid);
amForm = (Form_pg_am) GETSTRUCT(amTup);
appendStringInfo(&buffer, " for %s",
/* Qualify the name if not visible in search path */
if (OpclassIsVisible(object->objectId))
nspname = NULL;
else
nspname = get_namespace_name(opcForm->opcnamespace);
appendStringInfo(&buffer, gettext("operator class %s for %s"),
quote_qualified_identifier(nspname,
NameStr(opcForm->opcname)),
NameStr(amForm->amname));
ReleaseSysCache(amTup);
......@@ -1684,7 +1661,7 @@ getObjectDescription(const ObjectAddress *object)
rule = (Form_pg_rewrite) GETSTRUCT(tup);
appendStringInfo(&buffer, "rule %s on ",
appendStringInfo(&buffer, gettext("rule %s on "),
NameStr(rule->rulename));
getRelationDescription(&buffer, rule->ev_class);
......@@ -1719,7 +1696,7 @@ getObjectDescription(const ObjectAddress *object)
trig = (Form_pg_trigger) GETSTRUCT(tup);
appendStringInfo(&buffer, "trigger %s on ",
appendStringInfo(&buffer, gettext("trigger %s on "),
NameStr(trig->tgname));
getRelationDescription(&buffer, trig->tgrelid);
......@@ -1736,7 +1713,7 @@ getObjectDescription(const ObjectAddress *object)
if (!nspname)
elog(ERROR, "cache lookup failed for namespace %u",
object->objectId);
appendStringInfo(&buffer, "schema %s", nspname);
appendStringInfo(&buffer, gettext("schema %s"), nspname);
break;
}
......@@ -1780,40 +1757,40 @@ getRelationDescription(StringInfo buffer, Oid relid)
switch (relForm->relkind)
{
case RELKIND_RELATION:
appendStringInfo(buffer, "table %s",
appendStringInfo(buffer, gettext("table %s"),
relname);
break;
case RELKIND_INDEX:
appendStringInfo(buffer, "index %s",
appendStringInfo(buffer, gettext("index %s"),
relname);
break;
case RELKIND_SPECIAL:
appendStringInfo(buffer, "special system relation %s",
appendStringInfo(buffer, gettext("special system relation %s"),
relname);
break;
case RELKIND_SEQUENCE:
appendStringInfo(buffer, "sequence %s",
appendStringInfo(buffer, gettext("sequence %s"),
relname);
break;
case RELKIND_UNCATALOGED:
appendStringInfo(buffer, "uncataloged table %s",
appendStringInfo(buffer, gettext("uncataloged table %s"),
relname);
break;
case RELKIND_TOASTVALUE:
appendStringInfo(buffer, "toast table %s",
appendStringInfo(buffer, gettext("toast table %s"),
relname);
break;
case RELKIND_VIEW:
appendStringInfo(buffer, "view %s",
appendStringInfo(buffer, gettext("view %s"),
relname);
break;
case RELKIND_COMPOSITE_TYPE:
appendStringInfo(buffer, "composite type %s",
appendStringInfo(buffer, gettext("composite type %s"),
relname);
break;
default:
/* shouldn't get here */
appendStringInfo(buffer, "relation %s",
appendStringInfo(buffer, gettext("relation %s"),
relname);
break;
}
......
......@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/catalog/heap.c,v 1.262 2004/04/01 21:28:43 tgl Exp $
* $PostgreSQL: pgsql/src/backend/catalog/heap.c,v 1.263 2004/05/05 04:48:45 tgl Exp $
*
*
* INTERFACE ROUTINES
......@@ -72,7 +72,6 @@ static void AddNewRelationType(const char *typeName,
char new_rel_kind,
Oid new_type_oid);
static void RelationRemoveInheritance(Relation relation);
static void StoreAttrDefault(Relation rel, AttrNumber attnum, char *adbin);
static void StoreRelCheck(Relation rel, char *ccname, char *ccbin);
static void StoreConstraints(Relation rel, TupleDesc tupdesc);
static void SetRelationNumChecks(Relation rel, int numchecks);
......@@ -1246,7 +1245,7 @@ heap_drop_with_catalog(Oid rid)
* Store a default expression for column attnum of relation rel.
* The expression must be presented as a nodeToString() string.
*/
static void
void
StoreAttrDefault(Relation rel, AttrNumber attnum, char *adbin)
{
Node *expr;
......@@ -1483,16 +1482,20 @@ StoreConstraints(Relation rel, TupleDesc tupdesc)
* will be processed only if they are CONSTR_CHECK type and contain a "raw"
* expression.
*
* Returns a list of CookedConstraint nodes that shows the cooked form of
* the default and constraint expressions added to the relation.
*
* NB: caller should have opened rel with AccessExclusiveLock, and should
* hold that lock till end of transaction. Also, we assume the caller has
* done a CommandCounterIncrement if necessary to make the relation's catalog
* tuples visible.
*/
void
List *
AddRelationRawConstraints(Relation rel,
List *rawColDefaults,
List *rawConstraints)
{
List *cookedConstraints = NIL;
char *relname = RelationGetRelationName(rel);
TupleDesc tupleDesc;
TupleConstr *oldconstr;
......@@ -1504,6 +1507,7 @@ AddRelationRawConstraints(Relation rel,
int constr_name_ctr = 0;
List *listptr;
Node *expr;
CookedConstraint *cooked;
/*
* Get info about existing constraints.
......@@ -1544,7 +1548,15 @@ AddRelationRawConstraints(Relation rel,
expr = cookDefault(pstate, colDef->raw_default,
atp->atttypid, atp->atttypmod,
NameStr(atp->attname));
StoreAttrDefault(rel, colDef->attnum, nodeToString(expr));
cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
cooked->contype = CONSTR_DEFAULT;
cooked->name = NULL;
cooked->attnum = colDef->attnum;
cooked->expr = expr;
cookedConstraints = lappend(cookedConstraints, cooked);
}
/*
......@@ -1672,6 +1684,13 @@ AddRelationRawConstraints(Relation rel,
StoreRelCheck(rel, ccname, nodeToString(expr));
numchecks++;
cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
cooked->contype = CONSTR_CHECK;
cooked->name = ccname;
cooked->attnum = 0;
cooked->expr = expr;
cookedConstraints = lappend(cookedConstraints, cooked);
}
/*
......@@ -1682,6 +1701,8 @@ AddRelationRawConstraints(Relation rel,
* (This is critical if we added defaults but not constraints.)
*/
SetRelationNumChecks(rel, numchecks);
return cookedConstraints;
}
/*
......
......@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/catalog/index.c,v 1.228 2004/02/15 21:01:39 tgl Exp $
* $PostgreSQL: pgsql/src/backend/catalog/index.c,v 1.229 2004/05/05 04:48:45 tgl Exp $
*
*
* INTERFACE ROUTINES
......@@ -470,7 +470,8 @@ index_create(Oid heapRelationId,
Oid *classObjectId,
bool primary,
bool isconstraint,
bool allow_system_table_mods)
bool allow_system_table_mods,
bool skip_build)
{
Relation heapRelation;
Relation indexRelation;
......@@ -721,21 +722,31 @@ index_create(Oid heapRelationId,
* If this is bootstrap (initdb) time, then we don't actually fill in
* the index yet. We'll be creating more indexes and classes later,
* so we delay filling them in until just before we're done with
* bootstrapping. Otherwise, we call the routine that constructs the
* index.
* bootstrapping. Similarly, if the caller specified skip_build then
* filling the index is delayed till later (ALTER TABLE can save work
* in some cases with this). Otherwise, we call the AM routine that
* constructs the index.
*
* In normal processing mode, the heap and index relations are closed by
* index_build() --- but we continue to hold the ShareLock on the heap
* and the exclusive lock on the index that we acquired above, until
* end of transaction.
* In normal processing mode, the heap and index relations are closed,
* but we continue to hold the ShareLock on the heap and the exclusive
* lock on the index that we acquired above, until end of transaction.
*/
if (IsBootstrapProcessingMode())
{
index_register(heapRelationId, indexoid, indexInfo);
/* XXX shouldn't we close the heap and index rels here? */
}
else if (skip_build)
{
/* caller is responsible for filling the index later on */
relation_close(indexRelation, NoLock);
heap_close(heapRelation, NoLock);
}
else
{
index_build(heapRelation, indexRelation, indexInfo);
/* index_build closes the passed rels */
}
return indexoid;
}
......
......@@ -11,7 +11,7 @@
*
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/commands/cluster.c,v 1.120 2004/03/23 19:35:16 tgl Exp $
* $PostgreSQL: pgsql/src/backend/commands/cluster.c,v 1.121 2004/05/05 04:48:45 tgl Exp $
*
*-------------------------------------------------------------------------
*/
......@@ -64,11 +64,7 @@ typedef struct
static void cluster_rel(RelToCluster *rv, bool recheck);
static Oid make_new_heap(Oid OIDOldHeap, const char *NewName);
static void copy_heap_data(Oid OIDNewHeap, Oid OIDOldHeap, Oid OIDOldIndex);
static List *get_indexattr_list(Relation OldHeap, Oid OldIndex);
static void rebuild_indexes(Oid OIDOldHeap, List *indexes);
static void swap_relfilenodes(Oid r1, Oid r2);
static List *get_tables_to_cluster(MemoryContext cluster_context);
......@@ -479,7 +475,7 @@ rebuild_relation(Relation OldHeap, Oid indexOid)
/*
* Create the new table that we will fill with correctly-ordered data.
*/
static Oid
Oid
make_new_heap(Oid OIDOldHeap, const char *NewName)
{
TupleDesc OldHeapDesc,
......@@ -578,7 +574,7 @@ copy_heap_data(Oid OIDNewHeap, Oid OIDOldHeap, Oid OIDOldIndex)
* Get the necessary info about the indexes of the relation and
* return a list of IndexAttrs structures.
*/
static List *
List *
get_indexattr_list(Relation OldHeap, Oid OldIndex)
{
List *indexes = NIL;
......@@ -621,7 +617,7 @@ get_indexattr_list(Relation OldHeap, Oid OldIndex)
* Create new indexes and swap the filenodes with old indexes. Then drop
* the new index (carrying the old index filenode along).
*/
static void
void
rebuild_indexes(Oid OIDOldHeap, List *indexes)
{
List *elem;
......@@ -646,10 +642,15 @@ rebuild_indexes(Oid OIDOldHeap, List *indexes)
* matter: after the filenode swap the index will keep the
* constraint status of the old index.
*/
newIndexOID = index_create(OIDOldHeap, newIndexName,
attrs->indexInfo, attrs->accessMethodOID,
attrs->classOID, false,
false, allowSystemTableMods);
newIndexOID = index_create(OIDOldHeap,
newIndexName,
attrs->indexInfo,
attrs->accessMethodOID,
attrs->classOID,
false,
false,
allowSystemTableMods,
false);
CommandCounterIncrement();
/* Swap the filenodes. */
......@@ -698,7 +699,7 @@ rebuild_indexes(Oid OIDOldHeap, List *indexes)
* Also swap any TOAST links, so that the toast data moves along with
* the main-table data.
*/
static void
void
swap_relfilenodes(Oid r1, Oid r2)
{
Relation relRelation,
......@@ -789,9 +790,9 @@ swap_relfilenodes(Oid r1, Oid r2)
* their new owning relations. Otherwise the wrong one will get
* dropped ...
*
* NOTE: for now, we can assume the new table will have a TOAST table if
* and only if the old one does. This logic might need work if we get
* smarter about dropped columns.
* NOTE: it is possible that only one table has a toast table; this
* can happen in CLUSTER if there were dropped columns in the old table,
* and in ALTER TABLE when adding or changing type of columns.
*
* NOTE: at present, a TOAST table's only dependency is the one on its
* owning table. If more are ever created, we'd need to use something
......@@ -804,35 +805,43 @@ swap_relfilenodes(Oid r1, Oid r2)
toastobject;
long count;
if (!(relform1->reltoastrelid && relform2->reltoastrelid))
elog(ERROR, "expected both swapped tables to have TOAST tables");
/* Delete old dependencies */
count = deleteDependencyRecordsFor(RelOid_pg_class,
relform1->reltoastrelid);
if (count != 1)
elog(ERROR, "expected one dependency record for TOAST table, found %ld",
count);
count = deleteDependencyRecordsFor(RelOid_pg_class,
relform2->reltoastrelid);
if (count != 1)
elog(ERROR, "expected one dependency record for TOAST table, found %ld",
count);
if (relform1->reltoastrelid)
{
count = deleteDependencyRecordsFor(RelOid_pg_class,
relform1->reltoastrelid);
if (count != 1)
elog(ERROR, "expected one dependency record for TOAST table, found %ld",
count);
}
if (relform2->reltoastrelid)
{
count = deleteDependencyRecordsFor(RelOid_pg_class,
relform2->reltoastrelid);
if (count != 1)
elog(ERROR, "expected one dependency record for TOAST table, found %ld",
count);
}
/* Register new dependencies */
baseobject.classId = RelOid_pg_class;
baseobject.objectId = r1;
baseobject.objectSubId = 0;
toastobject.classId = RelOid_pg_class;
toastobject.objectId = relform1->reltoastrelid;
toastobject.objectSubId = 0;
recordDependencyOn(&toastobject, &baseobject, DEPENDENCY_INTERNAL);
baseobject.objectId = r2;
toastobject.objectId = relform2->reltoastrelid;
if (relform1->reltoastrelid)
{
baseobject.objectId = r1;
toastobject.objectId = relform1->reltoastrelid;
recordDependencyOn(&toastobject, &baseobject, DEPENDENCY_INTERNAL);
}
recordDependencyOn(&toastobject, &baseobject, DEPENDENCY_INTERNAL);
if (relform2->reltoastrelid)
{
baseobject.objectId = r2;
toastobject.objectId = relform2->reltoastrelid;
recordDependencyOn(&toastobject, &baseobject, DEPENDENCY_INTERNAL);
}
}
/*
......
This diff is collapsed.
This diff is collapsed.
......@@ -15,7 +15,7 @@
* Portions Copyright (c) 1994, Regents of the University of California
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/nodes/copyfuncs.c,v 1.279 2004/03/17 20:48:42 tgl Exp $
* $PostgreSQL: pgsql/src/backend/nodes/copyfuncs.c,v 1.280 2004/05/05 04:48:45 tgl Exp $
*
*-------------------------------------------------------------------------
*/
......@@ -1674,10 +1674,21 @@ _copyAlterTableStmt(AlterTableStmt *from)
{
AlterTableStmt *newnode = makeNode(AlterTableStmt);
COPY_SCALAR_FIELD(subtype);
COPY_NODE_FIELD(relation);
COPY_NODE_FIELD(cmds);
return newnode;
}
static AlterTableCmd *
_copyAlterTableCmd(AlterTableCmd *from)
{
AlterTableCmd *newnode = makeNode(AlterTableCmd);
COPY_SCALAR_FIELD(subtype);
COPY_STRING_FIELD(name);
COPY_NODE_FIELD(def);
COPY_NODE_FIELD(transform);
COPY_SCALAR_FIELD(behavior);
return newnode;
......@@ -2773,6 +2784,9 @@ copyObject(void *from)
case T_AlterTableStmt:
retval = _copyAlterTableStmt(from);
break;
case T_AlterTableCmd:
retval = _copyAlterTableCmd(from);
break;
case T_AlterDomainStmt:
retval = _copyAlterDomainStmt(from);
break;
......
......@@ -18,7 +18,7 @@
* Portions Copyright (c) 1994, Regents of the University of California
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/nodes/equalfuncs.c,v 1.218 2004/03/17 20:48:42 tgl Exp $
* $PostgreSQL: pgsql/src/backend/nodes/equalfuncs.c,v 1.219 2004/05/05 04:48:45 tgl Exp $
*
*-------------------------------------------------------------------------
*/
......@@ -710,10 +710,19 @@ _equalSetOperationStmt(SetOperationStmt *a, SetOperationStmt *b)
static bool
_equalAlterTableStmt(AlterTableStmt *a, AlterTableStmt *b)
{
COMPARE_SCALAR_FIELD(subtype);
COMPARE_NODE_FIELD(relation);
COMPARE_NODE_FIELD(cmds);
return true;
}
static bool
_equalAlterTableCmd(AlterTableCmd *a, AlterTableCmd *b)
{
COMPARE_SCALAR_FIELD(subtype);
COMPARE_STRING_FIELD(name);
COMPARE_NODE_FIELD(def);
COMPARE_NODE_FIELD(transform);
COMPARE_SCALAR_FIELD(behavior);
return true;
......@@ -1846,6 +1855,9 @@ equal(void *a, void *b)
case T_AlterTableStmt:
retval = _equalAlterTableStmt(a, b);
break;
case T_AlterTableCmd:
retval = _equalAlterTableCmd(a, b);
break;
case T_AlterDomainStmt:
retval = _equalAlterDomainStmt(a, b);
break;
......
This diff is collapsed.
......@@ -11,7 +11,7 @@
*
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/parser/gram.y,v 2.452 2004/04/21 00:34:18 momjian Exp $
* $PostgreSQL: pgsql/src/backend/parser/gram.y,v 2.453 2004/05/05 04:48:46 tgl Exp $
*
* HISTORY
* AUTHOR DATE MAJOR EVENT
......@@ -158,9 +158,12 @@ static void doNegateFloat(Value *v);
%type <node> select_no_parens select_with_parens select_clause
simple_select
%type <node> alter_column_default opclass_item
%type <node> alter_column_default opclass_item alter_using
%type <ival> add_drop
%type <node> alter_table_cmd
%type <list> alter_table_cmds
%type <dbehavior> opt_drop_behavior
%type <list> createdb_opt_list copy_opt_list
......@@ -199,7 +202,7 @@ static void doNegateFloat(Value *v);
%type <range> qualified_name OptConstrFromTable
%type <str> all_Op MathOp opt_name SpecialRuleRelation
%type <str> all_Op MathOp SpecialRuleRelation
%type <str> iso_level opt_encoding
%type <node> grantee
......@@ -1127,127 +1130,139 @@ CheckPointStmt:
*****************************************************************************/
AlterTableStmt:
/* ALTER TABLE <relation> ADD [COLUMN] <coldef> */
ALTER TABLE relation_expr ADD opt_column columnDef
ALTER TABLE relation_expr alter_table_cmds
{
AlterTableStmt *n = makeNode(AlterTableStmt);
n->subtype = 'A';
n->relation = $3;
n->def = $6;
n->cmds = $4;
$$ = (Node *)n;
}
;
alter_table_cmds:
alter_table_cmd { $$ = makeList1($1); }
| alter_table_cmds ',' alter_table_cmd { $$ = lappend($1, $3); }
;
alter_table_cmd:
/* ALTER TABLE <relation> ADD [COLUMN] <coldef> */
ADD opt_column columnDef
{
AlterTableCmd *n = makeNode(AlterTableCmd);
n->subtype = AT_AddColumn;
n->def = $3;
$$ = (Node *)n;
}
/* ALTER TABLE <relation> ALTER [COLUMN] <colname> {SET DEFAULT <expr>|DROP DEFAULT} */
| ALTER TABLE relation_expr ALTER opt_column ColId alter_column_default
| ALTER opt_column ColId alter_column_default
{
AlterTableStmt *n = makeNode(AlterTableStmt);
n->subtype = 'T';
n->relation = $3;
n->name = $6;
n->def = $7;
AlterTableCmd *n = makeNode(AlterTableCmd);
n->subtype = AT_ColumnDefault;
n->name = $3;
n->def = $4;
$$ = (Node *)n;
}
/* ALTER TABLE <relation> ALTER [COLUMN] <colname> DROP NOT NULL */
| ALTER TABLE relation_expr ALTER opt_column ColId DROP NOT NULL_P
| ALTER opt_column ColId DROP NOT NULL_P
{
AlterTableStmt *n = makeNode(AlterTableStmt);
n->subtype = 'N';
n->relation = $3;
n->name = $6;
AlterTableCmd *n = makeNode(AlterTableCmd);
n->subtype = AT_DropNotNull;
n->name = $3;
$$ = (Node *)n;
}
/* ALTER TABLE <relation> ALTER [COLUMN] <colname> SET NOT NULL */
| ALTER TABLE relation_expr ALTER opt_column ColId SET NOT NULL_P
| ALTER opt_column ColId SET NOT NULL_P
{
AlterTableStmt *n = makeNode(AlterTableStmt);
n->subtype = 'n';
n->relation = $3;
n->name = $6;
AlterTableCmd *n = makeNode(AlterTableCmd);
n->subtype = AT_SetNotNull;
n->name = $3;
$$ = (Node *)n;
}
/* ALTER TABLE <relation> ALTER [COLUMN] <colname> SET STATISTICS <IntegerOnly> */
| ALTER TABLE relation_expr ALTER opt_column ColId SET STATISTICS IntegerOnly
| ALTER opt_column ColId SET STATISTICS IntegerOnly
{
AlterTableStmt *n = makeNode(AlterTableStmt);
n->subtype = 'S';
n->relation = $3;
n->name = $6;
n->def = (Node *) $9;
AlterTableCmd *n = makeNode(AlterTableCmd);
n->subtype = AT_SetStatistics;
n->name = $3;
n->def = (Node *) $6;
$$ = (Node *)n;
}
/* ALTER TABLE <relation> ALTER [COLUMN] <colname> SET STORAGE <storagemode> */
| ALTER TABLE relation_expr ALTER opt_column ColId
SET STORAGE ColId
| ALTER opt_column ColId SET STORAGE ColId
{
AlterTableStmt *n = makeNode(AlterTableStmt);
n->subtype = 'M';
n->relation = $3;
n->name = $6;
n->def = (Node *) makeString($9);
AlterTableCmd *n = makeNode(AlterTableCmd);
n->subtype = AT_SetStorage;
n->name = $3;
n->def = (Node *) makeString($6);
$$ = (Node *)n;
}
/* ALTER TABLE <relation> DROP [COLUMN] <colname> [RESTRICT|CASCADE] */
| ALTER TABLE relation_expr DROP opt_column ColId opt_drop_behavior
| DROP opt_column ColId opt_drop_behavior
{
AlterTableStmt *n = makeNode(AlterTableStmt);
n->subtype = 'D';
n->relation = $3;
n->name = $6;
n->behavior = $7;
AlterTableCmd *n = makeNode(AlterTableCmd);
n->subtype = AT_DropColumn;
n->name = $3;
n->behavior = $4;
$$ = (Node *)n;
}
/*
* ALTER TABLE <relation> ALTER [COLUMN] <colname> TYPE <typename>
* [ USING <expression> ]
*/
| ALTER opt_column ColId TYPE_P Typename alter_using
{
AlterTableCmd *n = makeNode(AlterTableCmd);
n->subtype = AT_AlterColumnType;
n->name = $3;
n->def = (Node *) $5;
n->transform = $6;
$$ = (Node *)n;
}
/* ALTER TABLE <relation> ADD CONSTRAINT ... */
| ALTER TABLE relation_expr ADD TableConstraint
| ADD TableConstraint
{
AlterTableStmt *n = makeNode(AlterTableStmt);
n->subtype = 'C';
n->relation = $3;
n->def = $5;
AlterTableCmd *n = makeNode(AlterTableCmd);
n->subtype = AT_AddConstraint;
n->def = $2;
$$ = (Node *)n;
}
/* ALTER TABLE <relation> DROP CONSTRAINT <name> [RESTRICT|CASCADE] */
| ALTER TABLE relation_expr DROP CONSTRAINT name opt_drop_behavior
| DROP CONSTRAINT name opt_drop_behavior
{
AlterTableStmt *n = makeNode(AlterTableStmt);
n->subtype = 'X';
n->relation = $3;
n->name = $6;
n->behavior = $7;
AlterTableCmd *n = makeNode(AlterTableCmd);
n->subtype = AT_DropConstraint;
n->name = $3;
n->behavior = $4;
$$ = (Node *)n;
}
/* ALTER TABLE <relation> SET WITHOUT OIDS */
| ALTER TABLE relation_expr SET WITHOUT OIDS
| SET WITHOUT OIDS
{
AlterTableStmt *n = makeNode(AlterTableStmt);
n->relation = $3;
n->subtype = 'o';
AlterTableCmd *n = makeNode(AlterTableCmd);
n->subtype = AT_DropOids;
$$ = (Node *)n;
}
/* ALTER TABLE <name> CREATE TOAST TABLE */
| ALTER TABLE qualified_name CREATE TOAST TABLE
/* ALTER TABLE <name> CREATE TOAST TABLE -- ONLY */
| CREATE TOAST TABLE
{
AlterTableStmt *n = makeNode(AlterTableStmt);
n->subtype = 'E';
$3->inhOpt = INH_NO;
n->relation = $3;
AlterTableCmd *n = makeNode(AlterTableCmd);
n->subtype = AT_ToastTable;
$$ = (Node *)n;
}
/* ALTER TABLE <name> OWNER TO UserId */
| ALTER TABLE qualified_name OWNER TO UserId
| OWNER TO UserId
{
AlterTableStmt *n = makeNode(AlterTableStmt);
n->subtype = 'U';
$3->inhOpt = INH_NO;
n->relation = $3;
n->name = $6;
AlterTableCmd *n = makeNode(AlterTableCmd);
n->subtype = AT_ChangeOwner;
n->name = $3;
$$ = (Node *)n;
}
/* ALTER TABLE <name> CLUSTER ON <indexname> */
| ALTER TABLE qualified_name CLUSTER ON name
| CLUSTER ON name
{
AlterTableStmt *n = makeNode(AlterTableStmt);
n->subtype = 'L';
n->relation = $3;
n->name = $6;
AlterTableCmd *n = makeNode(AlterTableCmd);
n->subtype = AT_ClusterOn;
n->name = $3;
$$ = (Node *)n;
}
;
......@@ -1261,7 +1276,7 @@ alter_column_default:
else
$$ = $3;
}
| DROP DEFAULT { $$ = NULL; }
| DROP DEFAULT { $$ = NULL; }
;
opt_drop_behavior:
......@@ -1270,6 +1285,10 @@ opt_drop_behavior:
| /* EMPTY */ { $$ = DROP_RESTRICT; /* default */ }
;
alter_using:
USING a_expr { $$ = $2; }
| /* EMPTY */ { $$ = NULL; }
;
/*****************************************************************************
*
......@@ -3525,16 +3544,22 @@ RenameStmt: ALTER AGGREGATE func_name '(' aggr_argtype ')' RENAME TO name
n->newname = $6;
$$ = (Node *)n;
}
| ALTER TABLE relation_expr RENAME opt_column opt_name TO name
| ALTER TABLE relation_expr RENAME TO name
{
RenameStmt *n = makeNode(RenameStmt);
n->renameType = OBJECT_TABLE;
n->relation = $3;
n->subname = NULL;
n->newname = $6;
$$ = (Node *)n;
}
| ALTER TABLE relation_expr RENAME opt_column name TO name
{
RenameStmt *n = makeNode(RenameStmt);
n->renameType = OBJECT_COLUMN;
n->relation = $3;
n->subname = $6;
n->newname = $8;
if ($6 == NULL)
n->renameType = OBJECT_TABLE;
else
n->renameType = OBJECT_COLUMN;
$$ = (Node *)n;
}
| ALTER TRIGGER name ON relation_expr RENAME TO name
......@@ -3556,10 +3581,6 @@ RenameStmt: ALTER AGGREGATE func_name '(' aggr_argtype ')' RENAME TO name
}
;
opt_name: name { $$ = $1; }
| /*EMPTY*/ { $$ = NULL; }
;
opt_column: COLUMN { $$ = COLUMN; }
| /*EMPTY*/ { $$ = 0; }
;
......
......@@ -10,7 +10,7 @@
*
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/tcop/utility.c,v 1.213 2004/04/22 02:58:20 momjian Exp $
* $PostgreSQL: pgsql/src/backend/tcop/utility.c,v 1.214 2004/05/05 04:48:46 tgl Exp $
*
*-------------------------------------------------------------------------
*/
......@@ -43,7 +43,6 @@
#include "commands/view.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "parser/parse_clause.h"
#include "parser/parse_expr.h"
#include "parser/parse_type.h"
#include "rewrite/rewriteDefine.h"
......@@ -497,126 +496,8 @@ ProcessUtility(Node *parsetree,
ExecRenameStmt((RenameStmt *) parsetree);
break;
/* various Alter Table forms */
case T_AlterTableStmt:
{
AlterTableStmt *stmt = (AlterTableStmt *) parsetree;
Oid relid;
relid = RangeVarGetRelid(stmt->relation, false);
/*
* Some or all of these functions are recursive to cover
* inherited things, so permission checks are done there.
*/
switch (stmt->subtype)
{
case 'A': /* ADD COLUMN */
/*
* Recursively add column to table and, if
* requested, to descendants
*/
AlterTableAddColumn(relid,
interpretInhOption(stmt->relation->inhOpt),
(ColumnDef *) stmt->def);
break;
case 'T': /* ALTER COLUMN DEFAULT */
/*
* Recursively alter column default for table and,
* if requested, for descendants
*/
AlterTableAlterColumnDefault(relid,
interpretInhOption(stmt->relation->inhOpt),
stmt->name,
stmt->def);
break;
case 'N': /* ALTER COLUMN DROP NOT NULL */
AlterTableAlterColumnDropNotNull(relid,
interpretInhOption(stmt->relation->inhOpt),
stmt->name);
break;
case 'n': /* ALTER COLUMN SET NOT NULL */
AlterTableAlterColumnSetNotNull(relid,
interpretInhOption(stmt->relation->inhOpt),
stmt->name);
break;
case 'S': /* ALTER COLUMN STATISTICS */
case 'M': /* ALTER COLUMN STORAGE */
/*
* Recursively alter column statistics for table
* and, if requested, for descendants
*/
AlterTableAlterColumnFlags(relid,
interpretInhOption(stmt->relation->inhOpt),
stmt->name,
stmt->def,
&(stmt->subtype));
break;
case 'D': /* DROP COLUMN */
/*
* Recursively drop column from table and, if
* requested, from descendants
*/
AlterTableDropColumn(relid,
interpretInhOption(stmt->relation->inhOpt),
false,
stmt->name,
stmt->behavior);
break;
case 'C': /* ADD CONSTRAINT */
/*
* Recursively add constraint to table and, if
* requested, to descendants
*/
AlterTableAddConstraint(relid,
interpretInhOption(stmt->relation->inhOpt),
(List *) stmt->def);
break;
case 'X': /* DROP CONSTRAINT */
/*
* Recursively drop constraint from table and, if
* requested, from descendants
*/
AlterTableDropConstraint(relid,
interpretInhOption(stmt->relation->inhOpt),
stmt->name,
stmt->behavior);
break;
case 'E': /* CREATE TOAST TABLE */
AlterTableCreateToastTable(relid, false);
break;
case 'U': /* ALTER OWNER */
/* check that we are the superuser */
if (!superuser())
ereport(ERROR,
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("must be superuser to alter owner")));
/* get_usesysid raises an error if no such user */
AlterTableOwner(relid,
get_usesysid(stmt->name));
break;
case 'L': /* CLUSTER ON */
AlterTableClusterOn(relid, stmt->name);
break;
case 'o': /* SET WITHOUT OIDS */
AlterTableAlterOids(relid,
false,
interpretInhOption(stmt->relation->inhOpt),
DROP_RESTRICT);
break;
default: /* oops */
elog(ERROR, "unrecognized alter table type: %d",
(int) stmt->subtype);
break;
}
}
AlterTable((AlterTableStmt *) parsetree);
break;
case T_AlterDomainStmt:
......@@ -736,11 +617,15 @@ ProcessUtility(Node *parsetree,
stmt->idxname, /* index name */
stmt->accessMethod, /* am name */
stmt->indexParams, /* parameters */
(Expr *) stmt->whereClause,
stmt->rangetable,
stmt->unique,
stmt->primary,
stmt->isconstraint,
(Expr *) stmt->whereClause,
stmt->rangetable);
false, /* is_alter_table */
true, /* check_rights */
false, /* skip_build */
false); /* quiet */
}
break;
......
This diff is collapsed.
......@@ -7,7 +7,7 @@
* Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* $PostgreSQL: pgsql/src/include/catalog/dependency.h,v 1.11 2003/11/29 22:40:58 pgsql Exp $
* $PostgreSQL: pgsql/src/include/catalog/dependency.h,v 1.12 2004/05/05 04:48:47 tgl Exp $
*
*-------------------------------------------------------------------------
*/
......@@ -17,7 +17,7 @@
#include "nodes/parsenodes.h" /* for DropBehavior */
/*
/*----------
* Precise semantics of a dependency relationship are specified by the
* DependencyType code (which is stored in a "char" field in pg_depend,
* so we assign ASCII-code values to the enumeration members).
......@@ -56,6 +56,7 @@
* contain zeroes.
*
* Other dependency flavors may be needed in future.
*----------
*/
typedef enum DependencyType
......@@ -79,6 +80,28 @@ typedef struct ObjectAddress
} ObjectAddress;
/*
* This enum covers all system catalogs whose OIDs can appear in classId.
*/
typedef enum ObjectClass
{
OCLASS_CLASS, /* pg_class */
OCLASS_PROC, /* pg_proc */
OCLASS_TYPE, /* pg_type */
OCLASS_CAST, /* pg_cast */
OCLASS_CONSTRAINT, /* pg_constraint */
OCLASS_CONVERSION, /* pg_conversion */
OCLASS_DEFAULT, /* pg_attrdef */
OCLASS_LANGUAGE, /* pg_language */
OCLASS_OPERATOR, /* pg_operator */
OCLASS_OPCLASS, /* pg_opclass */
OCLASS_REWRITE, /* pg_rewrite */
OCLASS_TRIGGER, /* pg_trigger */
OCLASS_SCHEMA, /* pg_namespace */
MAX_OCLASS /* MUST BE LAST */
} ObjectClass;
/* in dependency.c */
extern void performDeletion(const ObjectAddress *object,
......@@ -96,6 +119,10 @@ extern void recordDependencyOnSingleRelExpr(const ObjectAddress *depender,
DependencyType behavior,
DependencyType self_behavior);
extern ObjectClass getObjectClass(const ObjectAddress *object);
extern char *getObjectDescription(const ObjectAddress *object);
/* in pg_depend.c */
extern void recordDependencyOn(const ObjectAddress *depender,
......
......@@ -7,7 +7,7 @@
* Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* $PostgreSQL: pgsql/src/include/catalog/heap.h,v 1.65 2004/03/23 19:35:17 tgl Exp $
* $PostgreSQL: pgsql/src/include/catalog/heap.h,v 1.66 2004/05/05 04:48:47 tgl Exp $
*
*-------------------------------------------------------------------------
*/
......@@ -27,6 +27,14 @@ typedef struct RawColumnDefault
* tree) */
} RawColumnDefault;
typedef struct CookedConstraint
{
ConstrType contype; /* CONSTR_DEFAULT or CONSTR_CHECK */
char *name; /* name, or NULL if none */
AttrNumber attnum; /* which attr (only for DEFAULT) */
Node *expr; /* transformed default or check expr */
} CookedConstraint;
extern Relation heap_create(const char *relname,
Oid relnamespace,
TupleDesc tupDesc,
......@@ -52,10 +60,12 @@ extern void heap_truncate(Oid rid);
extern void heap_truncate_check_FKs(Relation rel);
extern void AddRelationRawConstraints(Relation rel,
extern List *AddRelationRawConstraints(Relation rel,
List *rawColDefaults,
List *rawConstraints);
extern void StoreAttrDefault(Relation rel, AttrNumber attnum, char *adbin);
extern Node *cookDefault(ParseState *pstate,
Node *raw_default,
Oid atttypid,
......
......@@ -7,7 +7,7 @@
* Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* $PostgreSQL: pgsql/src/include/catalog/index.h,v 1.54 2003/11/29 22:40:58 pgsql Exp $
* $PostgreSQL: pgsql/src/include/catalog/index.h,v 1.55 2004/05/05 04:48:47 tgl Exp $
*
*-------------------------------------------------------------------------
*/
......@@ -37,7 +37,8 @@ extern Oid index_create(Oid heapRelationId,
Oid *classObjectId,
bool primary,
bool isconstraint,
bool allow_system_table_mods);
bool allow_system_table_mods,
bool skip_build);
extern void index_drop(Oid indexId);
......
......@@ -6,7 +6,7 @@
* Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
* Portions Copyright (c) 1994-5, Regents of the University of California
*
* $PostgreSQL: pgsql/src/include/commands/cluster.h,v 1.20 2003/11/29 22:40:59 pgsql Exp $
* $PostgreSQL: pgsql/src/include/commands/cluster.h,v 1.21 2004/05/05 04:48:47 tgl Exp $
*
*-------------------------------------------------------------------------
*/
......@@ -20,5 +20,9 @@
extern void cluster(ClusterStmt *stmt);
extern void rebuild_relation(Relation OldHeap, Oid indexOid);
extern Oid make_new_heap(Oid OIDOldHeap, const char *NewName);
extern List *get_indexattr_list(Relation OldHeap, Oid OldIndex);
extern void rebuild_indexes(Oid OIDOldHeap, List *indexes);
extern void swap_relfilenodes(Oid r1, Oid r2);
#endif /* CLUSTER_H */
......@@ -7,7 +7,7 @@
* Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* $PostgreSQL: pgsql/src/include/commands/defrem.h,v 1.54 2004/02/21 00:34:53 tgl Exp $
* $PostgreSQL: pgsql/src/include/commands/defrem.h,v 1.55 2004/05/05 04:48:47 tgl Exp $
*
*-------------------------------------------------------------------------
*/
......@@ -22,11 +22,15 @@ extern void DefineIndex(RangeVar *heapRelation,
char *indexRelationName,
char *accessMethodName,
List *attributeList,
Expr *predicate,
List *rangetable,
bool unique,
bool primary,
bool isconstraint,
Expr *predicate,
List *rangetable);
bool is_alter_table,
bool check_rights,
bool skip_build,
bool quiet);
extern void RemoveIndex(RangeVar *relation, DropBehavior behavior);
extern void ReindexIndex(RangeVar *indexRelation, bool force);
extern void ReindexTable(RangeVar *relation, bool force);
......
......@@ -7,7 +7,7 @@
* Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* $PostgreSQL: pgsql/src/include/commands/tablecmds.h,v 1.15 2004/03/23 19:35:17 tgl Exp $
* $PostgreSQL: pgsql/src/include/commands/tablecmds.h,v 1.16 2004/05/05 04:48:47 tgl Exp $
*
*-------------------------------------------------------------------------
*/
......@@ -16,46 +16,17 @@
#include "nodes/parsenodes.h"
extern void AlterTableAddColumn(Oid myrelid, bool recurse, ColumnDef *colDef);
extern void AlterTableAlterColumnDropNotNull(Oid myrelid, bool recurse,
const char *colName);
extern void AlterTableAlterColumnSetNotNull(Oid myrelid, bool recurse,
const char *colName);
extern void AlterTableAlterColumnDefault(Oid myrelid, bool recurse,
const char *colName,
Node *newDefault);
extern void AlterTableAlterColumnFlags(Oid myrelid, bool recurse,
const char *colName,
Node *flagValue, const char *flagType);
extern void AlterTableDropColumn(Oid myrelid, bool recurse, bool recursing,
const char *colName,
DropBehavior behavior);
extern Oid DefineRelation(CreateStmt *stmt, char relkind);
extern void AlterTableAddConstraint(Oid myrelid, bool recurse,
List *newConstraints);
extern void RemoveRelation(const RangeVar *relation, DropBehavior behavior);
extern void AlterTableDropConstraint(Oid myrelid, bool recurse,
const char *constrName,
DropBehavior behavior);
extern void AlterTable(AlterTableStmt *stmt);
extern void AlterTableClusterOn(Oid relOid, const char *indexName);
extern void AlterTableInternal(Oid relid, List *cmds, bool recurse);
extern void AlterTableCreateToastTable(Oid relOid, bool silent);
extern void AlterTableOwner(Oid relationOid, int32 newOwnerSysId);
extern void AlterTableAlterOids(Oid myrelid, bool setOid, bool recurse,
DropBehavior behavior);
extern Oid DefineRelation(CreateStmt *stmt, char relkind);
extern void RemoveRelation(const RangeVar *relation, DropBehavior behavior);
extern void TruncateRelation(const RangeVar *relation);
extern void renameatt(Oid myrelid,
......
......@@ -7,7 +7,7 @@
* Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* $PostgreSQL: pgsql/src/include/nodes/nodes.h,v 1.152 2004/04/01 21:28:46 tgl Exp $
* $PostgreSQL: pgsql/src/include/nodes/nodes.h,v 1.153 2004/05/05 04:48:47 tgl Exp $
*
*-------------------------------------------------------------------------
*/
......@@ -200,6 +200,7 @@ typedef enum NodeTag
T_UpdateStmt,
T_SelectStmt,
T_AlterTableStmt,
T_AlterTableCmd,
T_AlterDomainStmt,
T_SetOperationStmt,
T_GrantStmt,
......
......@@ -7,7 +7,7 @@
* Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* $PostgreSQL: pgsql/src/include/nodes/parsenodes.h,v 1.254 2004/03/11 01:47:41 ishii Exp $
* $PostgreSQL: pgsql/src/include/nodes/parsenodes.h,v 1.255 2004/05/05 04:48:47 tgl Exp $
*
*-------------------------------------------------------------------------
*/
......@@ -762,44 +762,58 @@ typedef enum DropBehavior
/* ----------------------
* Alter Table
*
* The fields are used in different ways by the different variants of
* this command.
* ----------------------
*/
typedef struct AlterTableStmt
{
NodeTag type;
char subtype; /*------------
* A = add column
* T = alter column default
* N = alter column drop not null
* n = alter column set not null
* S = alter column statistics
* M = alter column storage
* D = drop column
* C = add constraint
* c = pre-processed add constraint
* (local in parser/analyze.c)
* X = drop constraint
* E = create toast table
* U = change owner
* L = CLUSTER ON
* o = DROP OIDS
*------------
*/
RangeVar *relation; /* table to work on */
List *cmds; /* list of subcommands */
} AlterTableStmt;
typedef enum AlterTableType
{
AT_AddColumn, /* add column */
AT_ColumnDefault, /* alter column default */
AT_DropNotNull, /* alter column drop not null */
AT_SetNotNull, /* alter column set not null */
AT_SetStatistics, /* alter column statistics */
AT_SetStorage, /* alter column storage */
AT_DropColumn, /* drop column */
AT_DropColumnRecurse, /* internal to commands/tablecmds.c */
AT_AddIndex, /* add index */
AT_ReAddIndex, /* internal to commands/tablecmds.c */
AT_AddConstraint, /* add constraint */
AT_ProcessedConstraint, /* pre-processed add constraint
* (local in parser/analyze.c) */
AT_DropConstraint, /* drop constraint */
AT_DropConstraintQuietly, /* drop constraint, no error/warning
* (local in commands/tablecmds.c) */
AT_AlterColumnType, /* alter column type */
AT_ToastTable, /* create toast table */
AT_ChangeOwner, /* change owner */
AT_ClusterOn, /* CLUSTER ON */
AT_DropOids /* SET WITHOUT OIDS */
} AlterTableType;
typedef struct AlterTableCmd /* one subcommand of an ALTER TABLE */
{
NodeTag type;
AlterTableType subtype; /* Type of table alteration to apply */
char *name; /* column or constraint name to act on, or
* new owner */
Node *def; /* definition of new column or constraint */
Node *def; /* definition of new column, column type,
* index, or constraint */
Node *transform; /* transformation expr for ALTER TYPE */
DropBehavior behavior; /* RESTRICT or CASCADE for DROP cases */
} AlterTableStmt;
} AlterTableCmd;
/* ----------------------
* Alter Domain
*
* The fields are used in different ways by the different variants of
* this command. Subtypes should match AlterTable subtypes where possible.
* this command.
* ----------------------
*/
typedef struct AlterDomainStmt
......@@ -814,7 +828,7 @@ typedef struct AlterDomainStmt
* U = change owner
*------------
*/
List *typename; /* table to work on */
List *typename; /* domain to work on */
char *name; /* column or constraint name to act on, or
* new owner */
Node *def; /* definition of default or constraint */
......@@ -922,6 +936,8 @@ typedef struct CreateStmt
* Definitions for plain (non-FOREIGN KEY) constraints in CreateStmt
*
* XXX probably these ought to be unified with FkConstraints at some point?
* To this end we include CONSTR_FOREIGN in the ConstrType enum, even though
* the parser does not generate it.
*
* For constraints that use expressions (CONSTR_DEFAULT, CONSTR_CHECK)
* we may have the expression in either "raw" form (an untransformed
......@@ -944,6 +960,7 @@ typedef enum ConstrType /* types of constraints */
CONSTR_NOTNULL,
CONSTR_DEFAULT,
CONSTR_CHECK,
CONSTR_FOREIGN,
CONSTR_PRIMARY,
CONSTR_UNIQUE,
CONSTR_ATTR_DEFERRABLE, /* attributes for previous constraint node */
......@@ -1291,7 +1308,7 @@ typedef struct FetchStmt
typedef struct IndexStmt
{
NodeTag type;
char *idxname; /* name of the index */
char *idxname; /* name of new index, or NULL for default */
RangeVar *relation; /* relation to build index on */
char *accessMethod; /* name of access method (eg. btree) */
List *indexParams; /* a list of IndexElem */
......
......@@ -6,7 +6,7 @@
* Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* $PostgreSQL: pgsql/src/include/parser/analyze.h,v 1.25 2004/01/23 02:13:12 neilc Exp $
* $PostgreSQL: pgsql/src/include/parser/analyze.h,v 1.26 2004/05/05 04:48:47 tgl Exp $
*
*-------------------------------------------------------------------------
*/
......@@ -22,6 +22,9 @@ extern List *parse_analyze_varparams(Node *parseTree, Oid **paramTypes,
extern List *parse_sub_analyze(Node *parseTree, ParseState *parentParseState);
extern List *analyzeCreateSchemaStmt(CreateSchemaStmt *stmt);
extern char *makeObjectName(const char *name1, const char *name2,
const char *typename);
extern void CheckSelectForUpdate(Query *qry);
#endif /* ANALYZE_H */
......@@ -7,7 +7,7 @@
* Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* $PostgreSQL: pgsql/src/include/utils/builtins.h,v 1.236 2004/04/01 21:28:46 tgl Exp $
* $PostgreSQL: pgsql/src/include/utils/builtins.h,v 1.237 2004/05/05 04:48:47 tgl Exp $
*
*-------------------------------------------------------------------------
*/
......@@ -463,9 +463,11 @@ extern Datum pg_get_viewdef_name(PG_FUNCTION_ARGS);
extern Datum pg_get_viewdef_name_ext(PG_FUNCTION_ARGS);
extern Datum pg_get_indexdef(PG_FUNCTION_ARGS);
extern Datum pg_get_indexdef_ext(PG_FUNCTION_ARGS);
extern char *pg_get_indexdef_string(Oid indexrelid);
extern Datum pg_get_triggerdef(PG_FUNCTION_ARGS);
extern Datum pg_get_constraintdef(PG_FUNCTION_ARGS);
extern Datum pg_get_constraintdef_ext(PG_FUNCTION_ARGS);
extern char *pg_get_constraintdef_string(Oid constraintId);
extern Datum pg_get_userbyid(PG_FUNCTION_ARGS);
extern Datum pg_get_expr(PG_FUNCTION_ARGS);
extern Datum pg_get_expr_ext(PG_FUNCTION_ARGS);
......
......@@ -7,7 +7,7 @@ COMMENT ON TABLE tmp_wrong IS 'table comment';
ERROR: relation "tmp_wrong" does not exist
COMMENT ON TABLE tmp IS 'table comment';
COMMENT ON TABLE tmp IS NULL;
ALTER TABLE tmp ADD COLUMN a int4;
ALTER TABLE tmp ADD COLUMN a int4 default 3;
ALTER TABLE tmp ADD COLUMN b name;
ALTER TABLE tmp ADD COLUMN c text;
ALTER TABLE tmp ADD COLUMN d float8;
......@@ -419,7 +419,6 @@ create table atacc1 ( test int );
insert into atacc1 (test) values (NULL);
-- add a primary key (fails)
alter table atacc1 add constraint atacc_test1 primary key (test);
NOTICE: ALTER TABLE / ADD PRIMARY KEY will create implicit index "atacc_test1" for table "atacc1"
ERROR: column "test" contains null values
insert into atacc1 (test) values (3);
drop table atacc1;
......@@ -1143,3 +1142,96 @@ select f3,max(f1) from foo group by f3;
zz | qq
(1 row)
-- Simple tests for alter table column type
alter table foo alter f1 TYPE integer; -- fails
ERROR: column "f1" cannot be cast to type "pg_catalog.int4"
alter table foo alter f1 TYPE varchar(10);
create table anothertab (atcol1 serial8, atcol2 boolean,
constraint anothertab_chk check (atcol1 <= 3));
NOTICE: CREATE TABLE will create implicit sequence "anothertab_atcol1_seq" for "serial" column "anothertab.atcol1"
insert into anothertab (atcol1, atcol2) values (default, true);
insert into anothertab (atcol1, atcol2) values (default, false);
select * from anothertab;
atcol1 | atcol2
--------+--------
1 | t
2 | f
(2 rows)
alter table anothertab alter column atcol1 type boolean; -- fails
ERROR: column "atcol1" cannot be cast to type "pg_catalog.bool"
alter table anothertab alter column atcol1 type integer;
select * from anothertab;
atcol1 | atcol2
--------+--------
1 | t
2 | f
(2 rows)
insert into anothertab (atcol1, atcol2) values (45, null); -- fails
ERROR: new row for relation "anothertab" violates check constraint "anothertab_chk"
insert into anothertab (atcol1, atcol2) values (default, null);
select * from anothertab;
atcol1 | atcol2
--------+--------
1 | t
2 | f
3 |
(3 rows)
alter table anothertab alter column atcol2 type text
using case when atcol2 is true then 'IT WAS TRUE'
when atcol2 is false then 'IT WAS FALSE'
else 'IT WAS NULL!' end;
select * from anothertab;
atcol1 | atcol2
--------+--------------
1 | IT WAS TRUE
2 | IT WAS FALSE
3 | IT WAS NULL!
(3 rows)
alter table anothertab alter column atcol1 type boolean
using case when atcol1 % 2 = 0 then true else false end; -- fails
ERROR: default for column "atcol1" cannot be cast to type "pg_catalog.bool"
alter table anothertab alter column atcol1 drop default;
alter table anothertab alter column atcol1 type boolean
using case when atcol1 % 2 = 0 then true else false end; -- fails
ERROR: operator does not exist: boolean <= integer
HINT: No operator matches the given name and argument type(s). You may need to add explicit type casts.
alter table anothertab drop constraint anothertab_chk;
alter table anothertab alter column atcol1 type boolean
using case when atcol1 % 2 = 0 then true else false end;
select * from anothertab;
atcol1 | atcol2
--------+--------------
f | IT WAS TRUE
t | IT WAS FALSE
f | IT WAS NULL!
(3 rows)
drop table anothertab;
create table another (f1 int, f2 text);
insert into another values(1, 'one');
insert into another values(2, 'two');
insert into another values(3, 'three');
select * from another;
f1 | f2
----+-------
1 | one
2 | two
3 | three
(3 rows)
alter table another
alter f1 type text using f2 || ' more',
alter f2 type bigint using f1 * 10;
select * from another;
f1 | f2
------------+----
one more | 10
two more | 20
three more | 30
(3 rows)
drop table another;
......@@ -145,6 +145,28 @@ SELECT * FROM FKTABLE;
| | 8
(5 rows)
-- Try altering the column type where foreign keys are involved
ALTER TABLE PKTABLE ALTER COLUMN ptest1 TYPE bigint;
ALTER TABLE FKTABLE ALTER COLUMN ftest1 TYPE bigint;
SELECT * FROM PKTABLE;
ptest1 | ptest2 | ptest3
--------+--------+---------
1 | 3 | Test1-2
3 | 6 | Test3
4 | 8 | Test4
1 | 4 | Test2
(4 rows)
SELECT * FROM FKTABLE;
ftest1 | ftest2 | ftest3
--------+--------+--------
1 | 3 | 5
3 | 6 | 12
| | 0
| | 4
| | 8
(5 rows)
DROP TABLE PKTABLE CASCADE;
NOTICE: drop cascades to constraint constrname on table fktable
DROP TABLE FKTABLE;
......
......@@ -613,3 +613,12 @@ SELECT * FROM inhf; /* Single entry with value 'text' */
text
(1 row)
-- Test changing the type of inherited columns
insert into d values('test','one','two','three');
alter table a alter column aa type integer using bit_length(aa);
select * from d;
aa | bb | cc | dd
----+-----+-----+-------
32 | one | two | three
(1 row)
......@@ -9,7 +9,7 @@ COMMENT ON TABLE tmp_wrong IS 'table comment';
COMMENT ON TABLE tmp IS 'table comment';
COMMENT ON TABLE tmp IS NULL;
ALTER TABLE tmp ADD COLUMN a int4;
ALTER TABLE tmp ADD COLUMN a int4 default 3;
ALTER TABLE tmp ADD COLUMN b name;
......@@ -918,3 +918,60 @@ select * from foo;
update foo set f3 = 'zz';
select * from foo;
select f3,max(f1) from foo group by f3;
-- Simple tests for alter table column type
alter table foo alter f1 TYPE integer; -- fails
alter table foo alter f1 TYPE varchar(10);
create table anothertab (atcol1 serial8, atcol2 boolean,
constraint anothertab_chk check (atcol1 <= 3));
insert into anothertab (atcol1, atcol2) values (default, true);
insert into anothertab (atcol1, atcol2) values (default, false);
select * from anothertab;
alter table anothertab alter column atcol1 type boolean; -- fails
alter table anothertab alter column atcol1 type integer;
select * from anothertab;
insert into anothertab (atcol1, atcol2) values (45, null); -- fails
insert into anothertab (atcol1, atcol2) values (default, null);
select * from anothertab;
alter table anothertab alter column atcol2 type text
using case when atcol2 is true then 'IT WAS TRUE'
when atcol2 is false then 'IT WAS FALSE'
else 'IT WAS NULL!' end;
select * from anothertab;
alter table anothertab alter column atcol1 type boolean
using case when atcol1 % 2 = 0 then true else false end; -- fails
alter table anothertab alter column atcol1 drop default;
alter table anothertab alter column atcol1 type boolean
using case when atcol1 % 2 = 0 then true else false end; -- fails
alter table anothertab drop constraint anothertab_chk;
alter table anothertab alter column atcol1 type boolean
using case when atcol1 % 2 = 0 then true else false end;
select * from anothertab;
drop table anothertab;
create table another (f1 int, f2 text);
insert into another values(1, 'one');
insert into another values(2, 'two');
insert into another values(3, 'three');
select * from another;
alter table another
alter f1 type text using f2 || ' more',
alter f2 type bigint using f1 * 10;
select * from another;
drop table another;
......@@ -97,6 +97,12 @@ UPDATE PKTABLE SET ptest1=1 WHERE ptest1=2;
-- Check FKTABLE for update of matched row
SELECT * FROM FKTABLE;
-- Try altering the column type where foreign keys are involved
ALTER TABLE PKTABLE ALTER COLUMN ptest1 TYPE bigint;
ALTER TABLE FKTABLE ALTER COLUMN ftest1 TYPE bigint;
SELECT * FROM PKTABLE;
SELECT * FROM FKTABLE;
DROP TABLE PKTABLE CASCADE;
DROP TABLE FKTABLE;
......
......@@ -142,3 +142,10 @@ CREATE TABLE inhf (LIKE inhx, LIKE inhx); /* Throw error */
CREATE TABLE inhf (LIKE inhx INCLUDING DEFAULTS);
INSERT INTO inhf DEFAULT VALUES;
SELECT * FROM inhf; /* Single entry with value 'text' */
-- Test changing the type of inherited columns
insert into d values('test','one','two','three');
alter table a alter column aa type integer using bit_length(aa);
select * from d;
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment