diff --git a/src/backend/catalog/heap.c b/src/backend/catalog/heap.c
index 713c47eb60873534b17612039c7d101cb3e8ed25..b8850d0b92146d7ccbdad72570a5a68154355755 100644
--- a/src/backend/catalog/heap.c
+++ b/src/backend/catalog/heap.c
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/catalog/heap.c,v 1.246 2003/06/06 15:04:01 tgl Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/catalog/heap.c,v 1.247 2003/07/20 21:56:32 tgl Exp $
  *
  *
  * INTERFACE ROUTINES
@@ -350,8 +350,10 @@ CheckAttributeNamesTypes(TupleDesc tupdesc, char relkind)
 
 	/* Sanity check on column count */
 	if (natts < 0 || natts > MaxHeapAttributeNumber)
-		elog(ERROR, "Number of columns is out of range (0 to %d)",
-			 MaxHeapAttributeNumber);
+		ereport(ERROR,
+				(errcode(ERRCODE_TOO_MANY_COLUMNS),
+				 errmsg("tables can have at most %d columns",
+						MaxHeapAttributeNumber)));
 
 	/*
 	 * first check for collision with system attribute names
@@ -874,8 +876,7 @@ DeleteRelationTuple(Oid relid)
 						 ObjectIdGetDatum(relid),
 						 0, 0, 0);
 	if (!HeapTupleIsValid(tup))
-		elog(ERROR, "DeleteRelationTuple: cache lookup failed for relation %u",
-			 relid);
+		elog(ERROR, "cache lookup failed for relation %u", relid);
 
 	/* delete the relation tuple from pg_class, and finish up */
 	simple_heap_delete(pg_class_desc, &tup->t_self);
@@ -1082,8 +1083,7 @@ RemoveAttrDefaultById(Oid attrdefId)
 
 	tuple = systable_getnext(scan);
 	if (!HeapTupleIsValid(tuple))
-		elog(ERROR, "RemoveAttrDefaultById: cache lookup failed for attrdef %u",
-			 attrdefId);
+		elog(ERROR, "could not find tuple for attrdef %u", attrdefId);
 
 	myrelid = ((Form_pg_attrdef) GETSTRUCT(tuple))->adrelid;
 	myattnum = ((Form_pg_attrdef) GETSTRUCT(tuple))->adnum;
@@ -1105,8 +1105,8 @@ RemoveAttrDefaultById(Oid attrdefId)
 							   Int16GetDatum(myattnum),
 							   0, 0);
 	if (!HeapTupleIsValid(tuple))		/* shouldn't happen */
-		elog(ERROR, "RemoveAttrDefaultById: cache lookup failed for rel %u attr %d",
-			 myrelid, myattnum);
+		elog(ERROR, "cache lookup failed for attribute %d of relation %u",
+			 myattnum, myrelid);
 
 	((Form_pg_attribute) GETSTRUCT(tuple))->atthasdef = false;
 
@@ -1281,7 +1281,7 @@ StoreAttrDefault(Relation rel, AttrNumber attnum, char *adbin)
 								Int16GetDatum(attnum),
 								0, 0);
 	if (!HeapTupleIsValid(atttup))
-		elog(ERROR, "cache lookup of attribute %d in relation %u failed",
+		elog(ERROR, "cache lookup failed for attribute %d of relation %u",
 			 attnum, RelationGetRelid(rel));
 	attStruct = (Form_pg_attribute) GETSTRUCT(atttup);
 	if (!attStruct->atthasdef)
@@ -1539,7 +1539,7 @@ AddRelationRawConstraints(Relation rel,
 									 RelationGetRelid(rel),
 									 RelationGetNamespace(rel),
 									 ccname))
-				elog(ERROR, "constraint \"%s\" already exists for relation \"%s\"",
+				elog(ERROR, "constraint \"%s\" for relation \"%s\" already exists",
 					 ccname, RelationGetRelationName(rel));
 			/* Check against other new constraints */
 			/* Needed because we don't do CommandCounterIncrement in loop */
@@ -1672,7 +1672,7 @@ SetRelationNumChecks(Relation rel, int numchecks)
 								ObjectIdGetDatum(RelationGetRelid(rel)),
 								0, 0, 0);
 	if (!HeapTupleIsValid(reltup))
-		elog(ERROR, "cache lookup of relation %u failed",
+		elog(ERROR, "cache lookup failed for relation %u",
 			 RelationGetRelid(rel));
 	relStruct = (Form_pg_class) GETSTRUCT(reltup);
 
diff --git a/src/backend/commands/aggregatecmds.c b/src/backend/commands/aggregatecmds.c
index 8006d71898750f0eab22509d807be8dce1023fa7..088a9bf6e5c7fd39778f03d99ae2243aab3d5895 100644
--- a/src/backend/commands/aggregatecmds.c
+++ b/src/backend/commands/aggregatecmds.c
@@ -9,7 +9,7 @@
  *
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/commands/aggregatecmds.c,v 1.10 2003/07/04 02:51:33 tgl Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/commands/aggregatecmds.c,v 1.11 2003/07/20 21:56:32 tgl Exp $
  *
  * DESCRIPTION
  *	  The "DefineFoo" routines take the parse tree and pick out the
@@ -91,19 +91,27 @@ DefineAggregate(List *names, List *parameters)
 		else if (strcasecmp(defel->defname, "initcond1") == 0)
 			initval = defGetString(defel);
 		else
-			elog(WARNING, "DefineAggregate: attribute \"%s\" not recognized",
-				 defel->defname);
+			ereport(WARNING,
+					(errcode(ERRCODE_SYNTAX_ERROR),
+					 errmsg("aggregate attribute \"%s\" not recognized",
+							defel->defname)));
 	}
 
 	/*
 	 * make sure we have our required definitions
 	 */
 	if (baseType == NULL)
-		elog(ERROR, "Define: \"basetype\" unspecified");
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
+				 errmsg("aggregate basetype must be specified")));
 	if (transType == NULL)
-		elog(ERROR, "Define: \"stype\" unspecified");
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
+				 errmsg("aggregate stype must be specified")));
 	if (transfuncName == NIL)
-		elog(ERROR, "Define: \"sfunc\" unspecified");
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
+				 errmsg("aggregate sfunc must be specified")));
 
 	/*
 	 * look up the aggregate's base type (input datatype) and transtype.
@@ -112,7 +120,8 @@ DefineAggregate(List *names, List *parameters)
 	 * so we must do a case-insensitive comparison for the name ANY.  Ugh.
 	 *
 	 * basetype can be a pseudo-type, but transtype can't, since we need to
-	 * be able to store values of the transtype.
+	 * be able to store values of the transtype.  However, we can allow
+	 * polymorphic transtype in some cases (AggregateCreate will check).
 	 */
 	if (strcasecmp(TypeNameToString(baseType), "ANY") == 0)
 		baseTypeId = ANYOID;
@@ -123,8 +132,10 @@ DefineAggregate(List *names, List *parameters)
 	if (get_typtype(transTypeId) == 'p' &&
 		transTypeId != ANYARRAYOID &&
 		transTypeId != ANYELEMENTOID)
-		elog(ERROR, "Aggregate transition datatype cannot be %s",
-			 format_type_be(transTypeId));
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
+				 errmsg("aggregate transition datatype cannot be %s",
+						format_type_be(transTypeId))));
 
 	/*
 	 * Most of the argument-checking is done inside of AggregateCreate
@@ -174,8 +185,7 @@ RemoveAggregate(RemoveAggrStmt *stmt)
 						 ObjectIdGetDatum(procOid),
 						 0, 0, 0);
 	if (!HeapTupleIsValid(tup)) /* should not happen */
-		elog(ERROR, "RemoveAggregate: couldn't find pg_proc tuple for %s",
-			 NameListToString(aggName));
+		elog(ERROR, "cache lookup failed for function %u", procOid);
 
 	/* Permission check: must own agg or its namespace */
 	if (!pg_proc_ownercheck(procOid, GetUserId()) &&
@@ -204,8 +214,8 @@ RenameAggregate(List *name, TypeName *basetype, const char *newname)
 	Oid			basetypeOid;
 	Oid			procOid;
 	Oid			namespaceOid;
-	Oid			oid_array[FUNC_MAX_ARGS];
 	HeapTuple	tup;
+	Form_pg_proc procForm;
 	Relation	rel;
 	AclResult	aclresult;
 
@@ -229,26 +239,32 @@ RenameAggregate(List *name, TypeName *basetype, const char *newname)
 							 ObjectIdGetDatum(procOid),
 							 0, 0, 0);
 	if (!HeapTupleIsValid(tup)) /* should not happen */
-		elog(ERROR, "RenameAggregate: couldn't find pg_proc tuple for %s",
-			 NameListToString(name));
+		elog(ERROR, "cache lookup failed for function %u", procOid);
+	procForm = (Form_pg_proc) GETSTRUCT(tup);
 
-	namespaceOid = ((Form_pg_proc) GETSTRUCT(tup))->pronamespace;
+	namespaceOid = procForm->pronamespace;
 
 	/* make sure the new name doesn't exist */
-	MemSet(oid_array, 0, sizeof(oid_array));
-	oid_array[0] = basetypeOid;
 	if (SearchSysCacheExists(PROCNAMENSP,
 							 CStringGetDatum(newname),
-							 Int16GetDatum(1),
-							 PointerGetDatum(oid_array),
+							 Int16GetDatum(procForm->pronargs),
+							 PointerGetDatum(procForm->proargtypes),
 							 ObjectIdGetDatum(namespaceOid)))
 	{
 		if (basetypeOid == ANYOID)
-			elog(ERROR, "function %s(*) already exists in schema %s",
-				 newname, get_namespace_name(namespaceOid));
+			ereport(ERROR,
+					(errcode(ERRCODE_DUPLICATE_FUNCTION),
+					 errmsg("function %s(*) already exists in schema \"%s\"",
+							newname,
+							get_namespace_name(namespaceOid))));
 		else
-			elog(ERROR, "function %s(%s) already exists in schema %s",
-				 newname, format_type_be(basetypeOid), get_namespace_name(namespaceOid));
+			ereport(ERROR,
+					(errcode(ERRCODE_DUPLICATE_FUNCTION),
+					 errmsg("function %s already exists in schema \"%s\"",
+							funcname_signature_string(newname,
+													  procForm->pronargs,
+													  procForm->proargtypes),
+							get_namespace_name(namespaceOid))));
 	}
 
 	/* must be owner */
diff --git a/src/backend/commands/alter.c b/src/backend/commands/alter.c
index 65b27f5def38cb842e1fadb02c1ee384238d8c6e..c90a84b68f6faec7aba4c72277c1262727ffc969 100644
--- a/src/backend/commands/alter.c
+++ b/src/backend/commands/alter.c
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/commands/alter.c,v 1.1 2003/06/27 14:45:27 petere Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/commands/alter.c,v 1.2 2003/07/20 21:56:32 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -44,8 +44,8 @@ CheckOwnership(RangeVar *rel, bool noCatalogs)
 	tuple = SearchSysCache(RELOID,
 						   ObjectIdGetDatum(relOid),
 						   0, 0, 0);
-	if (!HeapTupleIsValid(tuple))
-		elog(ERROR, "Relation \"%s\" does not exist", rel->relname);
+	if (!HeapTupleIsValid(tuple)) /* should not happen */
+		elog(ERROR, "cache lookup failed for relation %u", relOid);
 
 	if (!pg_class_ownercheck(relOid, GetUserId()))
 		aclcheck_error(ACLCHECK_NOT_OWNER, rel->relname);
@@ -54,8 +54,10 @@ CheckOwnership(RangeVar *rel, bool noCatalogs)
 	{
 		if (!allowSystemTableMods &&
 			IsSystemClass((Form_pg_class) GETSTRUCT(tuple)))
-			elog(ERROR, "relation \"%s\" is a system catalog",
-				 rel->relname);
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+					 errmsg("relation \"%s\" is a system catalog",
+							rel->relname)));
 	}
 
 	ReleaseSysCache(tuple);
@@ -154,6 +156,7 @@ ExecRenameStmt(RenameStmt *stmt)
 		}
 
 		default:
-			elog(ERROR, "invalid object type for RenameStmt: %d", stmt->renameType);
+			elog(ERROR, "unrecognized rename stmt type: %d",
+				 (int) stmt->renameType);
 	}
 }
diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c
index 70d147f12073b32b58cf0d4fcece4fcab83d1b7a..5277884f1f87d3741784c89bea3bb1cd921a591b 100644
--- a/src/backend/commands/analyze.c
+++ b/src/backend/commands/analyze.c
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/commands/analyze.c,v 1.55 2003/06/27 14:45:27 petere Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/commands/analyze.c,v 1.56 2003/07/20 21:56:32 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -196,8 +196,9 @@ analyze_rel(Oid relid, VacuumStmt *vacstmt)
 	{
 		/* No need for a WARNING if we already complained during VACUUM */
 		if (!vacstmt->vacuum)
-			elog(WARNING, "Skipping \"%s\" --- only table or database owner can ANALYZE it",
-				 RelationGetRelationName(onerel));
+			ereport(WARNING,
+					(errmsg("skipping \"%s\" --- only table or database owner can ANALYZE it",
+							RelationGetRelationName(onerel))));
 		relation_close(onerel, AccessShareLock);
 		return;
 	}
@@ -210,8 +211,9 @@ analyze_rel(Oid relid, VacuumStmt *vacstmt)
 	{
 		/* No need for a WARNING if we already complained during VACUUM */
 		if (!vacstmt->vacuum)
-			elog(WARNING, "Skipping \"%s\" --- can not process indexes, views or special system tables",
-				 RelationGetRelationName(onerel));
+			ereport(WARNING,
+					(errmsg("skipping \"%s\" --- cannot ANALYZE indexes, views or special system tables",
+							RelationGetRelationName(onerel))));
 		relation_close(onerel, AccessShareLock);
 		return;
 	}
@@ -239,9 +241,10 @@ analyze_rel(Oid relid, VacuumStmt *vacstmt)
 		return;
 	}
 
-	elog(elevel, "Analyzing %s.%s",
-		 get_namespace_name(RelationGetNamespace(onerel)),
-		 RelationGetRelationName(onerel));
+	ereport(elevel,
+			(errmsg("analyzing \"%s.%s\"",
+					get_namespace_name(RelationGetNamespace(onerel)),
+					RelationGetRelationName(onerel))));
 
 	/*
 	 * Determine which columns to analyze
@@ -429,7 +432,7 @@ examine_attribute(Relation onerel, int attnum)
 							  ObjectIdGetDatum(attr->atttypid),
 							  0, 0, 0);
 	if (!HeapTupleIsValid(typtuple))
-		elog(ERROR, "cache lookup of type %u failed", attr->atttypid);
+		elog(ERROR, "cache lookup failed for type %u", attr->atttypid);
 	stats->attrtype = (Form_pg_type) palloc(sizeof(FormData_pg_type));
 	memcpy(stats->attrtype, GETSTRUCT(typtuple), sizeof(FormData_pg_type));
 	ReleaseSysCache(typtuple);
@@ -636,8 +639,7 @@ pageloop:;
 		 */
 		targbuffer = ReadBuffer(onerel, targblock);
 		if (!BufferIsValid(targbuffer))
-			elog(ERROR, "acquire_sample_rows: ReadBuffer(%s,%u) failed",
-				 RelationGetRelationName(onerel), targblock);
+			elog(ERROR, "ReadBuffer failed");
 		LockBuffer(targbuffer, BUFFER_LOCK_SHARE);
 		targpage = BufferGetPage(targbuffer);
 		maxoffset = PageGetMaxOffsetNumber(targpage);
diff --git a/src/backend/commands/async.c b/src/backend/commands/async.c
index 3ca0bde8f3b18811613be40d1b73368b271aa946..dafea7c8695baf5a7e8fc0f86818cc4537116868 100644
--- a/src/backend/commands/async.c
+++ b/src/backend/commands/async.c
@@ -7,7 +7,7 @@
  * Portions Copyright (c) 1994, Regents of the University of California
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/commands/async.c,v 1.95 2003/05/27 17:49:45 momjian Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/commands/async.c,v 1.96 2003/07/20 21:56:32 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -150,7 +150,7 @@ void
 Async_Notify(char *relname)
 {
 	if (Trace_notify)
-		elog(DEBUG1, "Async_Notify: %s", relname);
+		elog(DEBUG1, "Async_Notify(%s)", relname);
 
 	/* no point in making duplicate entries in the list ... */
 	if (!AsyncExistsPendingNotify(relname))
@@ -198,7 +198,7 @@ Async_Listen(char *relname, int pid)
 	bool		alreadyListener = false;
 
 	if (Trace_notify)
-		elog(DEBUG1, "Async_Listen: %s", relname);
+		elog(DEBUG1, "Async_Listen(%s,%d)", relname, pid);
 
 	lRel = heap_openr(ListenerRelationName, AccessExclusiveLock);
 
@@ -221,7 +221,8 @@ Async_Listen(char *relname, int pid)
 	if (alreadyListener)
 	{
 		heap_close(lRel, AccessExclusiveLock);
-		elog(WARNING, "Async_Listen: We are already listening on %s", relname);
+		ereport(WARNING,
+				(errmsg("already listening on \"%s\"", relname)));
 		return;
 	}
 
@@ -293,7 +294,7 @@ Async_Unlisten(char *relname, int pid)
 	}
 
 	if (Trace_notify)
-		elog(DEBUG1, "Async_Unlisten %s", relname);
+		elog(DEBUG1, "Async_Unlisten(%s,%d)", relname, pid);
 
 	lRel = heap_openr(ListenerRelationName, AccessExclusiveLock);
 
diff --git a/src/backend/commands/cluster.c b/src/backend/commands/cluster.c
index 87062782456854b3cdb6c3207fe80dde9f3156ab..17080fd020295fae8b2e2962374cfb6f3b9002f0 100644
--- a/src/backend/commands/cluster.c
+++ b/src/backend/commands/cluster.c
@@ -11,7 +11,7 @@
  *
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/commands/cluster.c,v 1.110 2003/05/28 16:03:56 tgl Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/commands/cluster.c,v 1.111 2003/07/20 21:56:32 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -116,8 +116,9 @@ cluster(ClusterStmt *stmt)
 
 		/* Check permissions */
 		if (!check_cluster_permitted(tableOid))
-			elog(ERROR, "CLUSTER: You do not own relation %s",
-				 stmt->relation->relname);
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+					 errmsg("permission denied")));
 
 		if (stmt->indexname == NULL)
 		{
@@ -134,8 +135,7 @@ cluster(ClusterStmt *stmt)
 										  ObjectIdGetDatum(indexOid),
 										  0, 0, 0);
 				if (!HeapTupleIsValid(idxtuple))
-					elog(ERROR, "Cache lookup failed for index %u",
-						 indexOid);
+					elog(ERROR, "cache lookup failed for index %u", indexOid);
 				indexForm = (Form_pg_index) GETSTRUCT(idxtuple);
 				if (indexForm->indisclustered)
 				{
@@ -147,8 +147,10 @@ cluster(ClusterStmt *stmt)
 			}
 
 			if (!OidIsValid(indexOid))
-				elog(ERROR, "CLUSTER: No previously clustered index found on table \"%s\"",
-					 stmt->relation->relname);
+				ereport(ERROR,
+						(errcode(ERRCODE_UNDEFINED_OBJECT),
+						 errmsg("there is no previously clustered index for table \"%s\"",
+								stmt->relation->relname)));
 		}
 		else
 		{
@@ -156,8 +158,10 @@ cluster(ClusterStmt *stmt)
 			indexOid = get_relname_relid(stmt->indexname,
 										 rel->rd_rel->relnamespace);
 			if (!OidIsValid(indexOid))
-				elog(ERROR, "CLUSTER: cannot find index \"%s\" for table \"%s\"",
-					 stmt->indexname, stmt->relation->relname);
+				ereport(ERROR,
+						(errcode(ERRCODE_UNDEFINED_OBJECT),
+						 errmsg("index \"%s\" for table \"%s\" does not exist",
+								stmt->indexname, stmt->relation->relname)));
 		}
 
 		/* All other checks are done in cluster_rel() */
@@ -310,9 +314,11 @@ cluster_rel(RelToCluster *rvtc, bool recheck)
 	 */
 	if (OldIndex->rd_index == NULL ||
 		OldIndex->rd_index->indrelid != rvtc->tableOid)
-		elog(ERROR, "CLUSTER: \"%s\" is not an index for table \"%s\"",
-			 RelationGetRelationName(OldIndex),
-			 RelationGetRelationName(OldHeap));
+		ereport(ERROR,
+				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+				 errmsg("\"%s\" is not an index for table \"%s\"",
+						RelationGetRelationName(OldIndex),
+						RelationGetRelationName(OldHeap))));
 
 	/*
 	 * Disallow clustering on incomplete indexes (those that might not index
@@ -321,7 +327,9 @@ cluster_rel(RelToCluster *rvtc, bool recheck)
 	 * expensive and tedious.
 	 */
 	if (!heap_attisnull(OldIndex->rd_indextuple, Anum_pg_index_indpred))
-		elog(ERROR, "CLUSTER: cannot cluster on partial index");
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("cannot cluster on partial index")));
 	if (!OldIndex->rd_am->amindexnulls)
 	{
 		AttrNumber	colno;
@@ -337,9 +345,11 @@ cluster_rel(RelToCluster *rvtc, bool recheck)
 		{
 			/* ordinary user attribute */
 			if (!OldHeap->rd_att->attrs[colno - 1]->attnotnull)
-				elog(ERROR, "CLUSTER: cannot cluster when index access method does not handle nulls"
-					 "\n\tYou may be able to work around this by marking column \"%s\" NOT NULL",
-					 NameStr(OldHeap->rd_att->attrs[colno - 1]->attname));
+				ereport(ERROR,
+						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+						 errmsg("cannot cluster when index access method does not handle nulls"),
+						 errhint("You may be able to work around this by marking column \"%s\" NOT NULL.",
+								 NameStr(OldHeap->rd_att->attrs[colno - 1]->attname))));
 		}
 		else if (colno < 0)
 		{
@@ -348,7 +358,9 @@ cluster_rel(RelToCluster *rvtc, bool recheck)
 		else
 		{
 			/* index expression, lose... */
-			elog(ERROR, "CLUSTER: cannot cluster on expressional index when index access method does not handle nulls");
+			ereport(ERROR,
+					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+					 errmsg("cannot cluster on expressional index when index access method does not handle nulls")));
 		}
 	}
 
@@ -360,15 +372,19 @@ cluster_rel(RelToCluster *rvtc, bool recheck)
 	 * might work for other system relations, but I ain't gonna risk it.
 	 */
 	if (IsSystemRelation(OldHeap))
-		elog(ERROR, "CLUSTER: cannot cluster system relation \"%s\"",
-			 RelationGetRelationName(OldHeap));
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("\"%s\" is a system catalog",
+						RelationGetRelationName(OldHeap))));
 
 	/*
 	 * Don't allow cluster on temp tables of other backends ... their
 	 * local buffer manager is not going to cope.
 	 */
 	if (isOtherTempNamespace(RelationGetNamespace(OldHeap)))
-		elog(ERROR, "CLUSTER cannot be used on temp tables of other processes");
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("cannot cluster temp tables of other processes")));
 
 	/* Drop relcache refcnt on OldIndex, but keep lock */
 	index_close(OldIndex);
@@ -697,14 +713,14 @@ swap_relfilenodes(Oid r1, Oid r2)
 								 ObjectIdGetDatum(r1),
 								 0, 0, 0);
 	if (!HeapTupleIsValid(reltup1))
-		elog(ERROR, "CLUSTER: Cannot find tuple for relation %u", r1);
+		elog(ERROR, "cache lookup failed for relation %u", r1);
 	relform1 = (Form_pg_class) GETSTRUCT(reltup1);
 
 	reltup2 = SearchSysCacheCopy(RELOID,
 								 ObjectIdGetDatum(r2),
 								 0, 0, 0);
 	if (!HeapTupleIsValid(reltup2))
-		elog(ERROR, "CLUSTER: Cannot find tuple for relation %u", r2);
+		elog(ERROR, "cache lookup failed for relation %u", r2);
 	relform2 = (Form_pg_class) GETSTRUCT(reltup2);
 
 	/*
@@ -716,13 +732,13 @@ swap_relfilenodes(Oid r1, Oid r2)
 	rel = relation_open(r1, NoLock);
 	i = FlushRelationBuffers(rel, 0);
 	if (i < 0)
-		elog(ERROR, "CLUSTER: FlushRelationBuffers returned %d", i);
+		elog(ERROR, "FlushRelationBuffers returned %d", i);
 	relation_close(rel, NoLock);
 
 	rel = relation_open(r2, NoLock);
 	i = FlushRelationBuffers(rel, 0);
 	if (i < 0)
-		elog(ERROR, "CLUSTER: FlushRelationBuffers returned %d", i);
+		elog(ERROR, "FlushRelationBuffers returned %d", i);
 	relation_close(rel, NoLock);
 
 	/*
@@ -784,18 +800,18 @@ swap_relfilenodes(Oid r1, Oid r2)
 		long		count;
 
 		if (!(relform1->reltoastrelid && relform2->reltoastrelid))
-			elog(ERROR, "CLUSTER: expected both swapped tables to have TOAST tables");
+			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, "CLUSTER: expected one dependency record for TOAST table, found %ld",
+			elog(ERROR, "expected one dependency record for TOAST table, found %ld",
 				 count);
 		count = deleteDependencyRecordsFor(RelOid_pg_class,
 										   relform2->reltoastrelid);
 		if (count != 1)
-			elog(ERROR, "CLUSTER: expected one dependency record for TOAST table, found %ld",
+			elog(ERROR, "expected one dependency record for TOAST table, found %ld",
 				 count);
 
 		/* Register new dependencies */
diff --git a/src/backend/commands/comment.c b/src/backend/commands/comment.c
index 13882dc6a6ed236b465d5930b311d4f404303037..62c09e3fce91abdf6c5144c3213222b7f40b7e56 100644
--- a/src/backend/commands/comment.c
+++ b/src/backend/commands/comment.c
@@ -7,7 +7,7 @@
  * Copyright (c) 1996-2001, PostgreSQL Global Development Group
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/commands/comment.c,v 1.65 2003/07/17 20:13:57 tgl Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/commands/comment.c,v 1.66 2003/07/20 21:56:32 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -108,8 +108,8 @@ CommentObject(CommentStmt *stmt)
 			CommentConstraint(stmt->objname, stmt->comment);
 			break;
 		default:
-			elog(ERROR, "An attempt was made to comment on a unknown type: %d",
-				 stmt->objtype);
+			elog(ERROR, "unrecognized object type: %d",
+				 (int) stmt->objtype);
 	}
 }
 
@@ -303,23 +303,31 @@ CommentRelation(int objtype, List *relname, char *comment)
 	{
 		case OBJECT_INDEX:
 			if (relation->rd_rel->relkind != RELKIND_INDEX)
-				elog(ERROR, "relation \"%s\" is not an index",
-					 RelationGetRelationName(relation));
+				ereport(ERROR,
+						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+						 errmsg("relation \"%s\" is not an index",
+								RelationGetRelationName(relation))));
 			break;
 		case OBJECT_SEQUENCE:
 			if (relation->rd_rel->relkind != RELKIND_SEQUENCE)
-				elog(ERROR, "relation \"%s\" is not a sequence",
-					 RelationGetRelationName(relation));
+				ereport(ERROR,
+						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+						 errmsg("relation \"%s\" is not a sequence",
+								RelationGetRelationName(relation))));
 			break;
 		case OBJECT_TABLE:
 			if (relation->rd_rel->relkind != RELKIND_RELATION)
-				elog(ERROR, "relation \"%s\" is not a table",
-					 RelationGetRelationName(relation));
+				ereport(ERROR,
+						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+						 errmsg("relation \"%s\" is not a table",
+								RelationGetRelationName(relation))));
 			break;
 		case OBJECT_VIEW:
 			if (relation->rd_rel->relkind != RELKIND_VIEW)
-				elog(ERROR, "relation \"%s\" is not a view",
-					 RelationGetRelationName(relation));
+				ereport(ERROR,
+						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+						 errmsg("relation \"%s\" is not a view",
+								RelationGetRelationName(relation))));
 			break;
 	}
 
@@ -338,8 +346,8 @@ CommentRelation(int objtype, List *relname, char *comment)
  * such as a table's column. The routine will check security
  * restrictions and then attempt to look up the specified
  * attribute. If successful, a comment is added/dropped, else an
- * elog() exception is thrown.	The parameters are the relation
- * and attribute names, and the comments
+ * ereport() exception is thrown.	The parameters are the relation
+ * and attribute names, and the comment
  */
 static void
 CommentAttribute(List *qualname, char *comment)
@@ -353,8 +361,8 @@ CommentAttribute(List *qualname, char *comment)
 
 	/* Separate relname and attr name */
 	nnames = length(qualname);
-	if (nnames < 2)
-		elog(ERROR, "CommentAttribute: must specify relation.attribute");
+	if (nnames < 2)				/* parser messed up */
+		elog(ERROR, "must specify relation and attribute");
 	relname = ltruncate(nnames - 1, listCopy(qualname));
 	attrname = strVal(nth(nnames - 1, qualname));
 
@@ -371,8 +379,10 @@ CommentAttribute(List *qualname, char *comment)
 
 	attnum = get_attnum(RelationGetRelid(relation), attrname);
 	if (attnum == InvalidAttrNumber)
-		elog(ERROR, "Relation \"%s\" has no column \"%s\"",
-			 RelationGetRelationName(relation), attrname);
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_COLUMN),
+				 errmsg("attribute \"%s\" of relation \"%s\" does not exist",
+						attrname, RelationGetRelationName(relation))));
 
 	/* Create the comment using the relation's oid */
 
@@ -400,7 +410,9 @@ CommentDatabase(List *qualname, char *comment)
 	Oid			oid;
 
 	if (length(qualname) != 1)
-		elog(ERROR, "CommentDatabase: database name may not be qualified");
+		ereport(ERROR,
+				(errcode(ERRCODE_SYNTAX_ERROR),
+				 errmsg("database name may not be qualified")));
 	database = strVal(lfirst(qualname));
 
 	/*
@@ -420,21 +432,24 @@ CommentDatabase(List *qualname, char *comment)
 	oid = get_database_oid(database);
 	if (!OidIsValid(oid))
 	{
-		elog(WARNING, "database \"%s\" does not exist", database);
+		ereport(WARNING,
+				(errcode(ERRCODE_UNDEFINED_DATABASE),
+				 errmsg("database \"%s\" does not exist", database)));
 		return;
 	}
 
 	/* Only allow comments on the current database */
 	if (oid != MyDatabaseId)
 	{
-		elog(WARNING, "database comments may only be applied to the current database");
+		ereport(WARNING,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("database comments may only be applied to the current database")));
 		return;
 	}
 
-	/* Allow if the user matches the database dba or is a superuser */
+	/* Check object security */
 	if (!pg_database_ownercheck(oid, GetUserId()))
-		elog(ERROR, "you are not permitted to comment on database \"%s\"",
-			 database);
+		aclcheck_error(ACLCHECK_NOT_OWNER, database);
 
 	/* Create the comment with the pg_database oid */
 	CreateComments(oid, RelOid_pg_database, 0, comment);
@@ -457,15 +472,18 @@ CommentNamespace(List *qualname, char *comment)
 	char	   *namespace;
 
 	if (length(qualname) != 1)
-		elog(ERROR, "CommentSchema: schema name may not be qualified");
+		ereport(ERROR,
+				(errcode(ERRCODE_SYNTAX_ERROR),
+				 errmsg("schema name may not be qualified")));
 	namespace = strVal(lfirst(qualname));
 
 	oid = GetSysCacheOid(NAMESPACENAME,
 						 CStringGetDatum(namespace),
 						 0, 0, 0);
 	if (!OidIsValid(oid))
-		elog(ERROR, "CommentSchema: Schema \"%s\" could not be found",
-			 namespace);
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_SCHEMA),
+				 errmsg("schema \"%s\" does not exist", namespace)));
 
 	/* Check object security */
 	if (!pg_namespace_ownercheck(oid, GetUserId()))
@@ -536,15 +554,18 @@ CommentRule(List *qualname, char *comment)
 		}
 		else
 		{
-			elog(ERROR, "rule \"%s\" does not exist", rulename);
+			ereport(ERROR,
+					(errcode(ERRCODE_UNDEFINED_OBJECT),
+					 errmsg("rule \"%s\" does not exist", rulename)));
 			reloid = ruleoid = 0;		/* keep compiler quiet */
 		}
 
 		if (HeapTupleIsValid(tuple = heap_getnext(scanDesc,
 												  ForwardScanDirection)))
-			elog(ERROR, "There are multiple rules \"%s\""
-			 "\n\tPlease specify a relation name as well as a rule name",
-				 rulename);
+			ereport(ERROR,
+					(errcode(ERRCODE_DUPLICATE_OBJECT),
+					 errmsg("there are multiple rules \"%s\"", rulename),
+					 errhint("Specify a relation name as well as a rule name.")));
 
 		heap_endscan(scanDesc);
 		heap_close(RewriteRelation, AccessShareLock);
@@ -570,7 +591,7 @@ CommentRule(List *qualname, char *comment)
 							   PointerGetDatum(rulename),
 							   0, 0);
 		if (!HeapTupleIsValid(tuple))
-			elog(ERROR, "rule \"%s\" does not exist", rulename);
+			elog(ERROR, "cache lookup failed for rule \"%s\"", rulename);
 		Assert(reloid == ((Form_pg_rewrite) GETSTRUCT(tuple))->ev_class);
 		ruleoid = HeapTupleGetOid(tuple);
 		ReleaseSysCache(tuple);
@@ -744,8 +765,8 @@ CommentTrigger(List *qualname, char *comment)
 
 	/* Separate relname and trig name */
 	nnames = length(qualname);
-	if (nnames < 2)
-		elog(ERROR, "CommentTrigger: must specify relation and trigger");
+	if (nnames < 2)				/* parser messed up */
+		elog(ERROR, "must specify relation and trigger");
 	relname = ltruncate(nnames - 1, listCopy(qualname));
 	trigname = strVal(nth(nnames - 1, qualname));
 
@@ -778,8 +799,10 @@ CommentTrigger(List *qualname, char *comment)
 	/* If no trigger exists for the relation specified, notify user */
 
 	if (!HeapTupleIsValid(triggertuple))
-		elog(ERROR, "trigger \"%s\" for relation \"%s\" does not exist",
-			 trigname, RelationGetRelationName(relation));
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_OBJECT),
+				 errmsg("trigger \"%s\" for relation \"%s\" does not exist",
+						trigname, RelationGetRelationName(relation))));
 
 	oid = HeapTupleGetOid(triggertuple);
 
@@ -819,8 +842,8 @@ CommentConstraint(List *qualname, char *comment)
 
 	/* Separate relname and constraint name */
 	nnames = length(qualname);
-	if (nnames < 2)
-		elog(ERROR, "CommentConstraint: must specify relation and constraint");
+	if (nnames < 2)				/* parser messed up */
+		elog(ERROR, "must specify relation and constraint");
 	relName = ltruncate(nnames - 1, listCopy(qualname));
 	conName = strVal(nth(nnames - 1, qualname));
 
@@ -854,8 +877,10 @@ CommentConstraint(List *qualname, char *comment)
 		if (strcmp(NameStr(con->conname), conName) == 0)
 		{
 			if (OidIsValid(conOid))
-				elog(ERROR, "Relation \"%s\" has multiple constraints named \"%s\"",
-					 RelationGetRelationName(relation), conName);
+				ereport(ERROR,
+						(errcode(ERRCODE_DUPLICATE_OBJECT),
+						 errmsg("relation \"%s\" has multiple constraints named \"%s\"",
+								RelationGetRelationName(relation), conName)));
 			conOid = HeapTupleGetOid(tuple);
 		}
 	}
@@ -864,8 +889,10 @@ CommentConstraint(List *qualname, char *comment)
 
 	/* If no constraint exists for the relation specified, notify user */
 	if (!OidIsValid(conOid))
-		elog(ERROR, "constraint \"%s\" for relation \"%s\" does not exist",
-			 conName, RelationGetRelationName(relation));
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_OBJECT),
+				 errmsg("constraint \"%s\" for relation \"%s\" does not exist",
+						conName, RelationGetRelationName(relation))));
 
 	/* Create the comment with the pg_constraint oid */
 	CreateComments(conOid, RelationGetRelid(pg_constraint), 0, comment);
diff --git a/src/backend/commands/conversioncmds.c b/src/backend/commands/conversioncmds.c
index e490a852c408e5395368e896658eaedce5322637..a502e9b0a07d42fdc129114a65ef219c2aab00d8 100644
--- a/src/backend/commands/conversioncmds.c
+++ b/src/backend/commands/conversioncmds.c
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/commands/conversioncmds.c,v 1.7 2003/07/04 02:51:33 tgl Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/commands/conversioncmds.c,v 1.8 2003/07/20 21:56:32 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -40,10 +40,10 @@ CreateConversionCommand(CreateConversionStmt *stmt)
 	Oid			namespaceId;
 	char	   *conversion_name;
 	AclResult	aclresult;
-	int			for_encoding;
+	int			from_encoding;
 	int			to_encoding;
 	Oid			funcoid;
-	const char *for_encoding_name = stmt->for_encoding_name;
+	const char *from_encoding_name = stmt->for_encoding_name;
 	const char *to_encoding_name = stmt->to_encoding_name;
 	List	   *func_name = stmt->func_name;
 	static Oid	funcargs[] = {INT4OID, INT4OID, CSTRINGOID, CSTRINGOID, INT4OID};
@@ -58,13 +58,19 @@ CreateConversionCommand(CreateConversionStmt *stmt)
 		aclcheck_error(aclresult, get_namespace_name(namespaceId));
 
 	/* Check the encoding names */
-	for_encoding = pg_char_to_encoding(for_encoding_name);
-	if (for_encoding < 0)
-		elog(ERROR, "Invalid for encoding name: %s", for_encoding_name);
+	from_encoding = pg_char_to_encoding(from_encoding_name);
+	if (from_encoding < 0)
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_OBJECT),
+				 errmsg("source encoding \"%s\" does not exist",
+						from_encoding_name)));
 
 	to_encoding = pg_char_to_encoding(to_encoding_name);
 	if (to_encoding < 0)
-		elog(ERROR, "Invalid to encoding name: %s", to_encoding_name);
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_OBJECT),
+				 errmsg("destination encoding \"%s\" does not exist",
+						to_encoding_name)));
 
 	/*
 	 * Check the existence of the conversion function. Function name could
@@ -83,7 +89,7 @@ CreateConversionCommand(CreateConversionStmt *stmt)
 	 * conversion name)
 	 */
 	ConversionCreate(conversion_name, namespaceId, GetUserId(),
-					 for_encoding, to_encoding, funcoid, stmt->def);
+					 from_encoding, to_encoding, funcoid, stmt->def);
 }
 
 /*
@@ -95,9 +101,11 @@ DropConversionCommand(List *name, DropBehavior behavior)
 	Oid			conversionOid;
 
 	conversionOid = FindConversionByName(name);
-
 	if (!OidIsValid(conversionOid))
-		elog(ERROR, "conversion %s not found", NameListToString(name));
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_OBJECT),
+				 errmsg("conversion \"%s\" does not exist",
+						NameListToString(name))));
 
 	ConversionDrop(conversionOid, behavior);
 }
@@ -118,14 +126,16 @@ RenameConversion(List *name, const char *newname)
 
 	conversionOid = FindConversionByName(name);
 	if (!OidIsValid(conversionOid))
-		elog(ERROR, "conversion %s not found", NameListToString(name));
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_OBJECT),
+				 errmsg("conversion \"%s\" does not exist",
+						NameListToString(name))));
 
 	tup = SearchSysCacheCopy(CONOID,
 							 ObjectIdGetDatum(conversionOid),
 							 0, 0, 0);
 	if (!HeapTupleIsValid(tup)) /* should not happen */
-		elog(ERROR, "couldn't find pg_conversion tuple for %s",
-			 NameListToString(name));
+		elog(ERROR, "cache lookup failed for conversion %u", conversionOid);
 
 	namespaceOid = ((Form_pg_conversion) GETSTRUCT(tup))->connamespace;
 
@@ -134,10 +144,10 @@ RenameConversion(List *name, const char *newname)
 							 CStringGetDatum(newname),
 							 ObjectIdGetDatum(namespaceOid),
 							 0, 0))
-	{
-		elog(ERROR, "conversion %s already exists in schema %s",
-			 newname, get_namespace_name(namespaceOid));
-	}
+		ereport(ERROR,
+				(errcode(ERRCODE_DUPLICATE_OBJECT),
+				 errmsg("conversion \"%s\" already exists in schema \"%s\"",
+						newname, get_namespace_name(namespaceOid))));
 
 	/* must be owner */
     if (!superuser() && ((Form_pg_conversion) GETSTRUCT(tup))->conowner != GetUserId())
diff --git a/src/backend/commands/copy.c b/src/backend/commands/copy.c
index b5b840504be118c55cc5456cebdd8f7b42bb746c..de2aff5dd1f87881ef1d9235433988e88d6174cf 100644
--- a/src/backend/commands/copy.c
+++ b/src/backend/commands/copy.c
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/commands/copy.c,v 1.201 2003/05/16 02:40:19 momjian Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/commands/copy.c,v 1.202 2003/07/20 21:56:32 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -171,7 +171,9 @@ SendCopyBegin(bool binary, int natts)
 	{
 		/* old way */
 		if (binary)
-			elog(ERROR, "COPY BINARY is not supported to stdout or from stdin");
+			ereport(ERROR,
+					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+					 errmsg("COPY BINARY is not supported to stdout or from stdin")));
 		pq_putemptymessage('H');
 		/* grottiness needed for old COPY OUT protocol */
 		pq_startcopyout();
@@ -181,7 +183,9 @@ SendCopyBegin(bool binary, int natts)
 	{
 		/* very old way */
 		if (binary)
-			elog(ERROR, "COPY BINARY is not supported to stdout or from stdin");
+			ereport(ERROR,
+					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+					 errmsg("COPY BINARY is not supported to stdout or from stdin")));
 		pq_putemptymessage('B');
 		/* grottiness needed for old COPY OUT protocol */
 		pq_startcopyout();
@@ -212,7 +216,9 @@ ReceiveCopyBegin(bool binary, int natts)
 	{
 		/* old way */
 		if (binary)
-			elog(ERROR, "COPY BINARY is not supported to stdout or from stdin");
+			ereport(ERROR,
+					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+					 errmsg("COPY BINARY is not supported to stdout or from stdin")));
 		pq_putemptymessage('G');
 		copy_dest = COPY_OLD_FE;
 	}
@@ -220,7 +226,9 @@ ReceiveCopyBegin(bool binary, int natts)
 	{
 		/* very old way */
 		if (binary)
-			elog(ERROR, "COPY BINARY is not supported to stdout or from stdin");
+			ereport(ERROR,
+					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+					 errmsg("COPY BINARY is not supported to stdout or from stdin")));
 		pq_putemptymessage('D');
 		copy_dest = COPY_OLD_FE;
 	}
@@ -271,13 +279,17 @@ CopySendData(void *databuf, int datasize)
 		case COPY_FILE:
 			fwrite(databuf, datasize, 1, copy_file);
 			if (ferror(copy_file))
-				elog(ERROR, "CopySendData: %m");
+				ereport(ERROR,
+						(errcode_for_file_access(),
+						 errmsg("failed to write COPY file: %m")));
 			break;
 		case COPY_OLD_FE:
 			if (pq_putbytes((char *) databuf, datasize))
 			{
 				/* no hope of recovering connection sync, so FATAL */
-				elog(FATAL, "CopySendData: connection lost");
+				ereport(FATAL,
+						(errcode(ERRCODE_CONNECTION_FAILURE),
+						 errmsg("connection lost during COPY to stdout")));
 			}
 			break;
 		case COPY_NEW_FE:
@@ -358,7 +370,9 @@ CopyGetData(void *databuf, int datasize)
 			if (pq_getbytes((char *) databuf, datasize))
 			{
 				/* Only a \. terminator is legal EOF in old protocol */
-				elog(ERROR, "unexpected EOF on client connection");
+				ereport(ERROR,
+						(errcode(ERRCODE_CONNECTION_FAILURE),
+						 errmsg("unexpected EOF on client connection")));
 			}
 			break;
 		case COPY_NEW_FE:
@@ -373,9 +387,13 @@ CopyGetData(void *databuf, int datasize)
 
 					mtype = pq_getbyte();
 					if (mtype == EOF)
-						elog(ERROR, "unexpected EOF on client connection");
+						ereport(ERROR,
+								(errcode(ERRCODE_CONNECTION_FAILURE),
+								 errmsg("unexpected EOF on client connection")));
 					if (pq_getmessage(copy_msgbuf, 0))
-						elog(ERROR, "unexpected EOF on client connection");
+						ereport(ERROR,
+								(errcode(ERRCODE_CONNECTION_FAILURE),
+								 errmsg("unexpected EOF on client connection")));
 					switch (mtype)
 					{
 						case 'd': /* CopyData */
@@ -385,12 +403,16 @@ CopyGetData(void *databuf, int datasize)
 							fe_eof = true;
 							return;
 						case 'f': /* CopyFail */
-							elog(ERROR, "COPY IN failed: %s",
-								 pq_getmsgstring(copy_msgbuf));
+							ereport(ERROR,
+									(errcode(ERRCODE_QUERY_CANCELED),
+									 errmsg("COPY from stdin failed: %s",
+											pq_getmsgstring(copy_msgbuf))));
 							break;
 						default:
-							elog(ERROR, "unexpected message type %c during COPY IN",
-								 mtype);
+							ereport(ERROR,
+									(errcode(ERRCODE_PROTOCOL_VIOLATION),
+									 errmsg("unexpected message type 0x%02X during COPY from stdin",
+											mtype)));
 							break;
 					}
 				}
@@ -420,7 +442,9 @@ CopyGetChar(void)
 			if (ch == EOF)
 			{
 				/* Only a \. terminator is legal EOF in old protocol */
-				elog(ERROR, "unexpected EOF on client connection");
+				ereport(ERROR,
+						(errcode(ERRCODE_CONNECTION_FAILURE),
+						 errmsg("unexpected EOF on client connection")));
 			}
 			break;
 		case COPY_NEW_FE:
@@ -467,7 +491,9 @@ CopyPeekChar(void)
 			if (ch == EOF)
 			{
 				/* Only a \. terminator is legal EOF in old protocol */
-				elog(ERROR, "unexpected EOF on client connection");
+				ereport(ERROR,
+						(errcode(ERRCODE_CONNECTION_FAILURE),
+						 errmsg("unexpected EOF on client connection")));
 			}
 			break;
 		case COPY_NEW_FE:
@@ -635,46 +661,52 @@ DoCopy(const CopyStmt *stmt)
 	{
 		DefElem    *defel = (DefElem *) lfirst(option);
 
-		/* XXX: Should we bother checking for doubled options? */
-
 		if (strcmp(defel->defname, "binary") == 0)
 		{
 			if (binary)
-				elog(ERROR, "COPY: BINARY option appears more than once");
-
+				ereport(ERROR,
+						(errcode(ERRCODE_SYNTAX_ERROR),
+						 errmsg("conflicting or redundant options")));
 			binary = intVal(defel->arg);
 		}
 		else if (strcmp(defel->defname, "oids") == 0)
 		{
 			if (oids)
-				elog(ERROR, "COPY: OIDS option appears more than once");
-
+				ereport(ERROR,
+						(errcode(ERRCODE_SYNTAX_ERROR),
+						 errmsg("conflicting or redundant options")));
 			oids = intVal(defel->arg);
 		}
 		else if (strcmp(defel->defname, "delimiter") == 0)
 		{
 			if (delim)
-				elog(ERROR, "COPY: DELIMITER string may only be defined once in query");
-
+				ereport(ERROR,
+						(errcode(ERRCODE_SYNTAX_ERROR),
+						 errmsg("conflicting or redundant options")));
 			delim = strVal(defel->arg);
 		}
 		else if (strcmp(defel->defname, "null") == 0)
 		{
 			if (null_print)
-				elog(ERROR, "COPY: NULL representation may only be defined once in query");
-
+				ereport(ERROR,
+						(errcode(ERRCODE_SYNTAX_ERROR),
+						 errmsg("conflicting or redundant options")));
 			null_print = strVal(defel->arg);
 		}
 		else
-			elog(ERROR, "COPY: option \"%s\" not recognized",
+			elog(ERROR, "option \"%s\" not recognized",
 				 defel->defname);
 	}
 
 	if (binary && delim)
-		elog(ERROR, "You can not specify the DELIMITER in BINARY mode.");
+		ereport(ERROR,
+				(errcode(ERRCODE_SYNTAX_ERROR),
+				 errmsg("cannot specify DELIMITER in BINARY mode")));
 
 	if (binary && null_print)
-		elog(ERROR, "You can not specify NULL in BINARY mode.");
+		ereport(ERROR,
+				(errcode(ERRCODE_SYNTAX_ERROR),
+				 errmsg("cannot specify NULL in BINARY mode")));
 
 	/* Set defaults */
 	if (!delim)
@@ -690,7 +722,9 @@ DoCopy(const CopyStmt *stmt)
 
 	/* check read-only transaction */
 	if (XactReadOnly && !is_from && !isTempNamespace(RelationGetNamespace(rel)))
-		elog(ERROR, "transaction is read-only");
+		ereport(ERROR,
+				(errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
+				 errmsg("transaction is read-only")));
 
 	/* Check permissions. */
 	aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
@@ -698,22 +732,28 @@ DoCopy(const CopyStmt *stmt)
 	if (aclresult != ACLCHECK_OK)
 		aclcheck_error(aclresult, RelationGetRelationName(rel));
 	if (!pipe && !superuser())
-		elog(ERROR, "You must have Postgres superuser privilege to do a COPY "
-			 "directly to or from a file.  Anyone can COPY to stdout or "
-			 "from stdin.  Psql's \\copy command also works for anyone.");
+		ereport(ERROR,
+				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+				 errmsg("must be superuser to COPY to or from a file"),
+				 errhint("Anyone can COPY to stdout or from stdin. "
+						 "psql's \\copy command also works for anyone.")));
 
 	/*
 	 * Presently, only single-character delimiter strings are supported.
 	 */
 	if (strlen(delim) != 1)
-		elog(ERROR, "COPY delimiter must be a single character");
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("COPY delimiter must be a single character")));
 
 	/*
 	 * Don't allow COPY w/ OIDs to or from a table without them
 	 */
 	if (oids && !rel->rd_rel->relhasoids)
-		elog(ERROR, "COPY: table \"%s\" does not have OIDs",
-			 RelationGetRelationName(rel));
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_COLUMN),
+				 errmsg("table \"%s\" does not have OIDs",
+						RelationGetRelationName(rel))));
 
 	/*
 	 * Generate or convert list of attributes to process
@@ -738,14 +778,20 @@ DoCopy(const CopyStmt *stmt)
 		if (rel->rd_rel->relkind != RELKIND_RELATION)
 		{
 			if (rel->rd_rel->relkind == RELKIND_VIEW)
-				elog(ERROR, "You cannot copy view %s",
-					 RelationGetRelationName(rel));
+				ereport(ERROR,
+						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+						 errmsg("cannot copy to view \"%s\"",
+								RelationGetRelationName(rel))));
 			else if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
-				elog(ERROR, "You cannot change sequence relation %s",
-					 RelationGetRelationName(rel));
+				ereport(ERROR,
+						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+						 errmsg("cannot copy to sequence \"%s\"",
+								RelationGetRelationName(rel))));
 			else
-				elog(ERROR, "You cannot copy object %s",
-					 RelationGetRelationName(rel));
+				ereport(ERROR,
+						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+						 errmsg("cannot copy to non-table relation \"%s\"",
+								RelationGetRelationName(rel))));
 		}
 		if (pipe)
 		{
@@ -761,23 +807,18 @@ DoCopy(const CopyStmt *stmt)
 			copy_file = AllocateFile(filename, PG_BINARY_R);
 
 			if (copy_file == NULL)
-#ifndef WIN32
-				elog(ERROR, "COPY command, running in backend with "
-					 "effective uid %d, could not open file '%s' for "
-					 "reading.  Errno = %s (%d).",
-					 (int) geteuid(), filename, strerror(errno), errno);
-#else
-				elog(ERROR, "COPY command, running in backend, "
-					 "could not open file '%s' for "
-					 "reading.  Errno = %s (%d).",
-					 filename, strerror(errno), errno);
-#endif
+				ereport(ERROR,
+						(errcode_for_file_access(),
+						 errmsg("could not open file \"%s\" for reading: %m",
+								filename)));
 
 			fstat(fileno(copy_file), &st);
 			if (S_ISDIR(st.st_mode))
 			{
 				FreeFile(copy_file);
-				elog(ERROR, "COPY: %s is a directory", filename);
+				ereport(ERROR,
+						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+						 errmsg("\"%s\" is a directory", filename)));
 			}
 		}
 		CopyFrom(rel, attnumlist, binary, oids, delim, null_print);
@@ -787,14 +828,20 @@ DoCopy(const CopyStmt *stmt)
 		if (rel->rd_rel->relkind != RELKIND_RELATION)
 		{
 			if (rel->rd_rel->relkind == RELKIND_VIEW)
-				elog(ERROR, "You cannot copy view %s",
-					 RelationGetRelationName(rel));
+				ereport(ERROR,
+						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+						 errmsg("cannot copy from view \"%s\"",
+								RelationGetRelationName(rel))));
 			else if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
-				elog(ERROR, "You cannot copy sequence %s",
-					 RelationGetRelationName(rel));
+				ereport(ERROR,
+						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+						 errmsg("cannot copy from sequence \"%s\"",
+								RelationGetRelationName(rel))));
 			else
-				elog(ERROR, "You cannot copy object %s",
-					 RelationGetRelationName(rel));
+				ereport(ERROR,
+						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+						 errmsg("cannot copy from non-table relation \"%s\"",
+								RelationGetRelationName(rel))));
 		}
 		if (pipe)
 		{
@@ -813,30 +860,27 @@ DoCopy(const CopyStmt *stmt)
 			 * oneself in the foot by overwriting a database file ...
 			 */
 			if (!is_absolute_path(filename))
-				elog(ERROR, "Relative path not allowed for server side"
-					 " COPY command");
+				ereport(ERROR,
+						(errcode(ERRCODE_INVALID_NAME),
+						 errmsg("relative path not allowed for COPY to file")));
 
 			oumask = umask((mode_t) 022);
 			copy_file = AllocateFile(filename, PG_BINARY_W);
 			umask(oumask);
 
 			if (copy_file == NULL)
-#ifndef WIN32
-				elog(ERROR, "COPY command, running in backend with "
-					 "effective uid %d, could not open file '%s' for "
-					 "writing.  Errno = %s (%d).",
-					 (int) geteuid(), filename, strerror(errno), errno);
-#else
-				elog(ERROR, "COPY command, running in backend, "
-					 "could not open file '%s' for "
-					 "writing.  Errno = %s (%d).",
-					 filename, strerror(errno), errno);
-#endif
+				ereport(ERROR,
+						(errcode_for_file_access(),
+						 errmsg("could not open file \"%s\" for writing: %m",
+								filename)));
+
 			fstat(fileno(copy_file), &st);
 			if (S_ISDIR(st.st_mode))
 			{
 				FreeFile(copy_file);
-				elog(ERROR, "COPY: %s is a directory", filename);
+				ereport(ERROR,
+						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+						 errmsg("\"%s\" is a directory", filename)));
 			}
 		}
 		CopyTo(rel, attnumlist, binary, oids, delim, null_print);
@@ -1217,25 +1261,35 @@ CopyFrom(Relation rel, List *attnumlist, bool binary, bool oids,
 		/* Signature */
 		CopyGetData(readSig, 11);
 		if (CopyGetEof() || memcmp(readSig, BinarySignature, 11) != 0)
-			elog(ERROR, "COPY BINARY: file signature not recognized");
+			ereport(ERROR,
+					(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
+					 errmsg("COPY file signature not recognized")));
 		/* Flags field */
 		tmp = CopyGetInt32();
 		if (CopyGetEof())
-			elog(ERROR, "COPY BINARY: bogus file header (missing flags)");
+			ereport(ERROR,
+					(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
+					 errmsg("invalid COPY file header (missing flags)")));
 		file_has_oids = (tmp & (1 << 16)) != 0;
 		tmp &= ~(1 << 16);
 		if ((tmp >> 16) != 0)
-			elog(ERROR, "COPY BINARY: unrecognized critical flags in header");
+			ereport(ERROR,
+					(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
+					 errmsg("unrecognized critical flags in COPY file header")));
 		/* Header extension length */
 		tmp = CopyGetInt32();
 		if (CopyGetEof() || tmp < 0)
-			elog(ERROR, "COPY BINARY: bogus file header (missing length)");
+			ereport(ERROR,
+					(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
+					 errmsg("invalid COPY file header (missing length)")));
 		/* Skip extension header, if present */
 		while (tmp-- > 0)
 		{
 			CopyGetData(readSig, 1);
 			if (CopyGetEof())
-				elog(ERROR, "COPY BINARY: bogus file header (wrong length)");
+				ereport(ERROR,
+						(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
+						 errmsg("invalid COPY file header (wrong length)")));
 		}
 	}
 
@@ -1301,13 +1355,17 @@ CopyFrom(Relation rel, List *attnumlist, bool binary, bool oids,
 				}
 
 				if (strcmp(string, null_print) == 0)
-					elog(ERROR, "NULL Oid");
+					ereport(ERROR,
+							(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
+							 errmsg("null OID in COPY data")));
 				else
 				{
 					loaded_oid = DatumGetObjectId(DirectFunctionCall1(oidin,
 											   CStringGetDatum(string)));
 					if (loaded_oid == InvalidOid)
-						elog(ERROR, "Invalid Oid");
+						ereport(ERROR,
+								(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
+								 errmsg("invalid OID in COPY data")));
 				}
 			}
 
@@ -1324,8 +1382,10 @@ CopyFrom(Relation rel, List *attnumlist, bool binary, bool oids,
 				 * complain.
 				 */
 				if (result != NORMAL_ATTR)
-					elog(ERROR, "Missing data for column \"%s\"",
-						 NameStr(attr[m]->attname));
+					ereport(ERROR,
+							(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
+							 errmsg("missing data for column \"%s\"",
+									NameStr(attr[m]->attname))));
 
 				string = CopyReadAttribute(delim, &result);
 
@@ -1368,7 +1428,9 @@ CopyFrom(Relation rel, List *attnumlist, bool binary, bool oids,
 				{
 					string = CopyReadAttribute(delim, &result);
 					if (result == NORMAL_ATTR || *string != '\0')
-						elog(ERROR, "Extra data after last expected column");
+						ereport(ERROR,
+								(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
+								 errmsg("extra data after last expected column")));
 					if (result == END_OF_FILE)
 					{
 						/* EOF at start of line: all is well */
@@ -1377,7 +1439,9 @@ CopyFrom(Relation rel, List *attnumlist, bool binary, bool oids,
 					}
 				}
 				else
-					elog(ERROR, "Extra data after last expected column");
+					ereport(ERROR,
+							(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
+							 errmsg("extra data after last expected column")));
 			}
 
 			/*
@@ -1401,8 +1465,10 @@ CopyFrom(Relation rel, List *attnumlist, bool binary, bool oids,
 			}
 
 			if (fld_count != attr_count)
-				elog(ERROR, "COPY BINARY: tuple field count is %d, expected %d",
-					 (int) fld_count, attr_count);
+				ereport(ERROR,
+						(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
+						 errmsg("row field count is %d, expected %d",
+								(int) fld_count, attr_count)));
 
 			if (file_has_oids)
 			{
@@ -1412,7 +1478,9 @@ CopyFrom(Relation rel, List *attnumlist, bool binary, bool oids,
 															 oid_in_element,
 															 &isnull));
 				if (isnull || loaded_oid == InvalidOid)
-					elog(ERROR, "COPY BINARY: Invalid Oid");
+					ereport(ERROR,
+							(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
+							 errmsg("invalid OID in COPY data")));
 			}
 
 			i = 0;
@@ -1602,9 +1670,10 @@ CopyReadAttribute(const char *delim, CopyReadResult *result)
 		if (c == '\r')
 		{
 			if (eol_type == EOL_NL)
-				elog(ERROR, "CopyReadAttribute: Literal carriage return data value\n"
-							"found in input that has newline termination; use \\r");
-
+				ereport(ERROR,
+						(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
+						 errmsg("literal carriage return found in data"),
+						 errhint("Use \"\\r\" to represent carriage return.")));
 			/*	Check for \r\n on first line, _and_ handle \r\n. */
 			if (copy_lineno == 1 || eol_type == EOL_CRNL)
 			{
@@ -1618,8 +1687,10 @@ CopyReadAttribute(const char *delim, CopyReadResult *result)
 				{
 					/* found \r, but no \n */
 					if (eol_type == EOL_CRNL)
-						elog(ERROR, "CopyReadAttribute: Literal carriage return data value\n"
-									"found in input that has carriage return/newline termination; use \\r");
+						ereport(ERROR,
+								(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
+								 errmsg("literal carriage return found in data"),
+								 errhint("Use \"\\r\" to represent carriage return.")));
 					/* if we got here, it is the first line and we didn't get \n, so put it back */
 					CopyDonePeek(c2, false);
 					eol_type = EOL_CR;
@@ -1630,12 +1701,11 @@ CopyReadAttribute(const char *delim, CopyReadResult *result)
 		}
 		if (c == '\n')
 		{
-			if (eol_type == EOL_CRNL)
-				elog(ERROR, "CopyReadAttribute: Literal newline data value found in input\n"
-							"that has carriage return/newline termination; use \\n");
-			if (eol_type == EOL_CR)
-				elog(ERROR, "CopyReadAttribute: Literal newline data value found in input\n"
-							"that has carriage return termination; use \\n");
+			if (eol_type == EOL_CR || eol_type == EOL_CRNL)
+				ereport(ERROR,
+						(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
+						 errmsg("literal newline found in data"),
+						 errhint("Use \"\\n\" to represent newline.")));
 			eol_type = EOL_NL;
 			*result = END_OF_LINE;
 			break;
@@ -1730,16 +1800,25 @@ CopyReadAttribute(const char *delim, CopyReadResult *result)
 					{
 						c = CopyGetChar();
 						if (c == '\n')
-							elog(ERROR, "CopyReadAttribute: end-of-copy termination does not match previous input");
+							ereport(ERROR,
+									(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
+									 errmsg("end-of-copy marker does not match previous newline style")));
 						if (c != '\r')
-							elog(ERROR, "CopyReadAttribute: end-of-copy marker corrupt");
+							ereport(ERROR,
+									(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
+									 errmsg("end-of-copy marker corrupt")));
 					}
 					c = CopyGetChar();
 					if (c != '\r' && c != '\n')
-						elog(ERROR, "CopyReadAttribute: end-of-copy marker corrupt");
-					if (((eol_type == EOL_NL || eol_type == EOL_CRNL) && c != '\n') ||
+						ereport(ERROR,
+								(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
+								 errmsg("end-of-copy marker corrupt")));
+					if ((eol_type == EOL_NL && c != '\n') ||
+						(eol_type == EOL_CRNL && c != '\n') ||
 					    (eol_type == EOL_CR && c != '\r'))
-						elog(ERROR, "CopyReadAttribute: end-of-copy termination does not match previous input");
+						ereport(ERROR,
+								(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
+								 errmsg("end-of-copy marker does not match previous newline style")));
 					/*
 					 * In protocol version 3, we should ignore anything after
 					 * \. up to the protocol end of copy data.  (XXX maybe
@@ -1807,14 +1886,18 @@ CopyReadBinaryAttribute(int column_no, FmgrInfo *flinfo, Oid typelem,
 
 	fld_size = CopyGetInt32();
 	if (CopyGetEof())
-		elog(ERROR, "COPY BINARY: unexpected EOF");
+		ereport(ERROR,
+				(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
+				 errmsg("unexpected EOF in COPY data")));
 	if (fld_size == -1)
 	{
 		*isnull = true;
 		return (Datum) 0;
 	}
 	if (fld_size < 0)
-		elog(ERROR, "COPY BINARY: bogus size for field %d", column_no);
+		ereport(ERROR,
+				(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
+				 errmsg("invalid size for field %d", column_no)));
 
 	/* reset attribute_buf to empty, and load raw data in it */
 	attribute_buf.len = 0;
@@ -1825,7 +1908,9 @@ CopyReadBinaryAttribute(int column_no, FmgrInfo *flinfo, Oid typelem,
 
 	CopyGetData(attribute_buf.data, fld_size);
 	if (CopyGetEof())
-		elog(ERROR, "COPY BINARY: unexpected EOF");
+		ereport(ERROR,
+				(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
+				 errmsg("unexpected EOF in COPY data")));
 
 	attribute_buf.len = fld_size;
 	attribute_buf.data[fld_size] = '\0';
@@ -1837,7 +1922,10 @@ CopyReadBinaryAttribute(int column_no, FmgrInfo *flinfo, Oid typelem,
 
 	/* Trouble if it didn't eat the whole buffer */
 	if (attribute_buf.cursor != attribute_buf.len)
-		elog(ERROR, "Improper binary format in field %d", column_no);
+		ereport(ERROR,
+				(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
+				 errmsg("incorrect binary data format in field %d",
+						column_no)));
 
 	*isnull = false;
 	return result;
@@ -1949,12 +2037,15 @@ CopyGetAttnums(Relation rel, List *attnamelist)
 			char	   *name = strVal(lfirst(l));
 			int			attnum;
 
-			/* Lookup column name, elog on failure */
+			/* Lookup column name, ereport on failure */
 			/* Note we disallow system columns here */
 			attnum = attnameAttNum(rel, name, false);
 			/* Check for duplicates */
 			if (intMember(attnum, attnums))
-				elog(ERROR, "Attribute \"%s\" specified more than once", name);
+				ereport(ERROR,
+						(errcode(ERRCODE_DUPLICATE_COLUMN),
+						 errmsg("attribute \"%s\" specified more than once",
+								name)));
 			attnums = lappendi(attnums, attnum);
 		}
 	}
diff --git a/src/backend/commands/define.c b/src/backend/commands/define.c
index 5b0624a03eae37f088d7fb57711c0237550d97dd..bf0c95a75efd74d40faa074c83e1f346cb4e627c 100644
--- a/src/backend/commands/define.c
+++ b/src/backend/commands/define.c
@@ -9,7 +9,7 @@
  *
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/commands/define.c,v 1.81 2002/09/21 18:39:25 tgl Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/commands/define.c,v 1.82 2003/07/20 21:56:32 tgl Exp $
  *
  * DESCRIPTION
  *	  The "DefineFoo" routines take the parse tree and pick out the
@@ -65,8 +65,10 @@ char *
 defGetString(DefElem *def)
 {
 	if (def->arg == NULL)
-		elog(ERROR, "Define: \"%s\" requires a parameter",
-			 def->defname);
+		ereport(ERROR,
+				(errcode(ERRCODE_SYNTAX_ERROR),
+				 errmsg("%s requires a parameter",
+						def->defname)));
 	switch (nodeTag(def->arg))
 	{
 		case T_Integer:
@@ -90,8 +92,7 @@ defGetString(DefElem *def)
 		case T_List:
 			return NameListToString((List *) def->arg);
 		default:
-			elog(ERROR, "Define: cannot interpret argument of \"%s\"",
-				 def->defname);
+			elog(ERROR, "unrecognized node type: %d", (int) nodeTag(def->arg));
 	}
 	return NULL;				/* keep compiler quiet */
 }
@@ -103,8 +104,10 @@ double
 defGetNumeric(DefElem *def)
 {
 	if (def->arg == NULL)
-		elog(ERROR, "Define: \"%s\" requires a numeric value",
-			 def->defname);
+		ereport(ERROR,
+				(errcode(ERRCODE_SYNTAX_ERROR),
+				 errmsg("%s requires a numeric value",
+						def->defname)));
 	switch (nodeTag(def->arg))
 	{
 		case T_Integer:
@@ -112,8 +115,10 @@ defGetNumeric(DefElem *def)
 		case T_Float:
 			return floatVal(def->arg);
 		default:
-			elog(ERROR, "Define: \"%s\" requires a numeric value",
-				 def->defname);
+			ereport(ERROR,
+					(errcode(ERRCODE_SYNTAX_ERROR),
+					 errmsg("%s requires a numeric value",
+							def->defname)));
 	}
 	return 0;					/* keep compiler quiet */
 }
@@ -125,8 +130,10 @@ int64
 defGetInt64(DefElem *def)
 {
 	if (def->arg == NULL)
-		elog(ERROR, "Define: \"%s\" requires a numeric value",
-			 def->defname);
+		ereport(ERROR,
+				(errcode(ERRCODE_SYNTAX_ERROR),
+				 errmsg("%s requires a numeric value",
+						def->defname)));
 	switch (nodeTag(def->arg))
 	{
 		case T_Integer:
@@ -141,8 +148,10 @@ defGetInt64(DefElem *def)
 			return DatumGetInt64(DirectFunctionCall1(int8in,
 									 CStringGetDatum(strVal(def->arg))));
 		default:
-			elog(ERROR, "Define: \"%s\" requires a numeric value",
-				 def->defname);
+			ereport(ERROR,
+					(errcode(ERRCODE_SYNTAX_ERROR),
+					 errmsg("%s requires a numeric value",
+							def->defname)));
 	}
 	return 0;					/* keep compiler quiet */
 }
@@ -154,8 +163,10 @@ List *
 defGetQualifiedName(DefElem *def)
 {
 	if (def->arg == NULL)
-		elog(ERROR, "Define: \"%s\" requires a parameter",
-			 def->defname);
+		ereport(ERROR,
+				(errcode(ERRCODE_SYNTAX_ERROR),
+				 errmsg("%s requires a parameter",
+						def->defname)));
 	switch (nodeTag(def->arg))
 	{
 		case T_TypeName:
@@ -166,8 +177,10 @@ defGetQualifiedName(DefElem *def)
 			/* Allow quoted name for backwards compatibility */
 			return makeList1(def->arg);
 		default:
-			elog(ERROR, "Define: argument of \"%s\" must be a name",
-				 def->defname);
+			ereport(ERROR,
+					(errcode(ERRCODE_SYNTAX_ERROR),
+					 errmsg("argument of %s must be a name",
+							def->defname)));
 	}
 	return NIL;					/* keep compiler quiet */
 }
@@ -182,8 +195,10 @@ TypeName *
 defGetTypeName(DefElem *def)
 {
 	if (def->arg == NULL)
-		elog(ERROR, "Define: \"%s\" requires a parameter",
-			 def->defname);
+		ereport(ERROR,
+				(errcode(ERRCODE_SYNTAX_ERROR),
+				 errmsg("%s requires a parameter",
+						def->defname)));
 	switch (nodeTag(def->arg))
 	{
 		case T_TypeName:
@@ -198,8 +213,10 @@ defGetTypeName(DefElem *def)
 				return n;
 			}
 		default:
-			elog(ERROR, "Define: argument of \"%s\" must be a type name",
-				 def->defname);
+			ereport(ERROR,
+					(errcode(ERRCODE_SYNTAX_ERROR),
+					 errmsg("argument of %s must be a type name",
+							def->defname)));
 	}
 	return NULL;				/* keep compiler quiet */
 }
@@ -212,15 +229,19 @@ int
 defGetTypeLength(DefElem *def)
 {
 	if (def->arg == NULL)
-		elog(ERROR, "Define: \"%s\" requires a parameter",
-			 def->defname);
+		ereport(ERROR,
+				(errcode(ERRCODE_SYNTAX_ERROR),
+				 errmsg("%s requires a parameter",
+						def->defname)));
 	switch (nodeTag(def->arg))
 	{
 		case T_Integer:
 			return intVal(def->arg);
 		case T_Float:
-			elog(ERROR, "Define: \"%s\" requires an integral value",
-				 def->defname);
+			ereport(ERROR,
+					(errcode(ERRCODE_SYNTAX_ERROR),
+					 errmsg("%s requires an integer value",
+							def->defname)));
 			break;
 		case T_String:
 			if (strcasecmp(strVal(def->arg), "variable") == 0)
@@ -236,10 +257,11 @@ defGetTypeLength(DefElem *def)
 			/* must be an operator name */
 			break;
 		default:
-			elog(ERROR, "Define: cannot interpret argument of \"%s\"",
-				 def->defname);
+			elog(ERROR, "unrecognized node type: %d", (int) nodeTag(def->arg));
 	}
-	elog(ERROR, "Define: invalid argument for \"%s\": \"%s\"",
-		 def->defname, defGetString(def));
+	ereport(ERROR,
+			(errcode(ERRCODE_SYNTAX_ERROR),
+			 errmsg("invalid argument for %s: \"%s\"",
+					def->defname, defGetString(def))));
 	return 0;					/* keep compiler quiet */
 }
diff --git a/src/backend/commands/explain.c b/src/backend/commands/explain.c
index 3ce00d4ad0ca32b5f01d2f85f64b81fef6b58599..bc137b0eaca49d1df95a611e56ce9e8bccf08dc2 100644
--- a/src/backend/commands/explain.c
+++ b/src/backend/commands/explain.c
@@ -7,7 +7,7 @@
  * Portions Copyright (c) 1994-5, Regents of the University of California
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/commands/explain.c,v 1.110 2003/05/28 23:06:16 tgl Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/commands/explain.c,v 1.111 2003/07/20 21:56:32 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -157,7 +157,7 @@ ExplainOneQuery(Query *query, ExplainStmt *stmt, TupOutputState *tstate)
 			Assert(query->commandType == CMD_SELECT);
 			rewritten = QueryRewrite(query);
 			if (length(rewritten) != 1)
-				elog(ERROR, "ExplainOneQuery: unexpected rewrite result");
+				elog(ERROR, "unexpected rewrite result");
 			query = (Query *) lfirst(rewritten);
 			Assert(query->commandType == CMD_SELECT);
 			/* do not actually execute the underlying query! */
@@ -1013,8 +1013,7 @@ show_sort_keys(List *tlist, int nkeys, AttrNumber *keycols,
 			}
 		}
 		if (tl == NIL)
-			elog(ERROR, "show_sort_keys: no tlist entry for key %d",
-				 keyresno);
+			elog(ERROR, "no tlist entry for key %d", keyresno);
 	}
 
 	appendStringInfo(str, "\n");
diff --git a/src/backend/commands/functioncmds.c b/src/backend/commands/functioncmds.c
index e09f48edd35bf0236a974f1107e34b7d02bca593..f351b0f2dcb4f3feaf9a6b29d8798d56b0e57b89 100644
--- a/src/backend/commands/functioncmds.c
+++ b/src/backend/commands/functioncmds.c
@@ -9,7 +9,7 @@
  *
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/commands/functioncmds.c,v 1.28 2003/07/18 23:20:32 tgl Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/commands/functioncmds.c,v 1.29 2003/07/20 21:56:32 tgl Exp $
  *
  * DESCRIPTION
  *	  These routines take the parse tree and pick out the
@@ -672,10 +672,11 @@ RenameFunction(List *name, List *argtypes, const char *newname)
 	{
 		ereport(ERROR,
 				(errcode(ERRCODE_DUPLICATE_FUNCTION),
-				 errmsg("function %s already exists",
-						func_signature_string(name,
-											  procForm->pronargs,
-											  procForm->proargtypes))));
+				 errmsg("function %s already exists in schema \"%s\"",
+						funcname_signature_string(newname,
+												  procForm->pronargs,
+												  procForm->proargtypes),
+						get_namespace_name(namespaceOid))));
 	}
 
 	/* must be owner */
diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c
index 151183c64556b195967865fe5cdaffcbd38a00ba..0f6a9e28f0d17f9ee58e7e4313c52c9b92bc92d8 100644
--- a/src/backend/commands/indexcmds.c
+++ b/src/backend/commands/indexcmds.c
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/commands/indexcmds.c,v 1.101 2003/06/27 14:45:27 petere Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/commands/indexcmds.c,v 1.102 2003/07/20 21:56:32 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -87,10 +87,14 @@ DefineIndex(RangeVar *heapRelation,
 	 */
 	numberOfAttributes = length(attributeList);
 	if (numberOfAttributes <= 0)
-		elog(ERROR, "DefineIndex: must specify at least one attribute");
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
+				 errmsg("must specify at least one attribute")));
 	if (numberOfAttributes > INDEX_MAX_KEYS)
-		elog(ERROR, "Cannot use more than %d attributes in an index",
-			 INDEX_MAX_KEYS);
+		ereport(ERROR,
+				(errcode(ERRCODE_TOO_MANY_COLUMNS),
+				 errmsg("cannot use more than %d attributes in an index",
+						INDEX_MAX_KEYS)));
 
 	/*
 	 * Open heap relation, acquire a suitable lock on it, remember its OID
@@ -100,8 +104,10 @@ DefineIndex(RangeVar *heapRelation,
 	/* Note: during bootstrap may see uncataloged relation */
 	if (rel->rd_rel->relkind != RELKIND_RELATION &&
 		rel->rd_rel->relkind != RELKIND_UNCATALOGED)
-		elog(ERROR, "DefineIndex: relation \"%s\" is not a table",
-			 heapRelation->relname);
+		ereport(ERROR,
+				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+				 errmsg("relation \"%s\" is not a table",
+						heapRelation->relname)));
 
 	relationId = RelationGetRelid(rel);
 	namespaceId = RelationGetNamespace(rel);
@@ -109,7 +115,10 @@ DefineIndex(RangeVar *heapRelation,
 	if (!IsBootstrapProcessingMode() &&
 		IsSystemRelation(rel) &&
 		!IndexesAreActive(rel))
-		elog(ERROR, "Existing indexes are inactive. REINDEX first");
+		ereport(ERROR,
+				(errcode(ERRCODE_INDEXES_DEACTIVATED),
+				 errmsg("existing indexes are inactive"),
+				 errhint("REINDEX the table first.")));
 
 	heap_close(rel, NoLock);
 
@@ -137,17 +146,23 @@ DefineIndex(RangeVar *heapRelation,
 						   PointerGetDatum(accessMethodName),
 						   0, 0, 0);
 	if (!HeapTupleIsValid(tuple))
-		elog(ERROR, "DefineIndex: access method \"%s\" not found",
-			 accessMethodName);
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_OBJECT),
+				 errmsg("access method \"%s\" does not exist",
+						accessMethodName)));
 	accessMethodId = HeapTupleGetOid(tuple);
 	accessMethodForm = (Form_pg_am) GETSTRUCT(tuple);
 
 	if (unique && !accessMethodForm->amcanunique)
-		elog(ERROR, "DefineIndex: access method \"%s\" does not support UNIQUE indexes",
-			 accessMethodName);
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("access method \"%s\" does not support UNIQUE indexes",
+						accessMethodName)));
 	if (numberOfAttributes > 1 && !accessMethodForm->amcanmulticol)
-		elog(ERROR, "DefineIndex: access method \"%s\" does not support multi-column indexes",
-			 accessMethodName);
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("access method \"%s\" does not support multi-column indexes",
+						accessMethodName)));
 
 	ReleaseSysCache(tuple);
 
@@ -158,7 +173,9 @@ DefineIndex(RangeVar *heapRelation,
 	if (rangetable != NIL)
 	{
 		if (length(rangetable) != 1 || getrelid(1, rangetable) != relationId)
-			elog(ERROR, "index expressions and predicates may refer only to the base relation");
+			ereport(ERROR,
+					(errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
+					 errmsg("index expressions and predicates may refer only to the base relation")));
 	}
 
 	/*
@@ -187,7 +204,9 @@ DefineIndex(RangeVar *heapRelation,
 			HeapTuple	atttuple;
 
 			if (!key->name)
-				elog(ERROR, "primary keys cannot be expressions");
+				ereport(ERROR,
+						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+						 errmsg("primary keys cannot be expressions")));
 
 			/* System attributes are never null, so no problem */
 			if (SystemAttributeByName(key->name, rel->rd_rel->relhasoids))
@@ -214,8 +233,10 @@ DefineIndex(RangeVar *heapRelation,
 			else
 			{
 				/* This shouldn't happen if parser did its job ... */
-				elog(ERROR, "DefineIndex: column \"%s\" named in key does not exist",
-					 key->name);
+				ereport(ERROR,
+						(errcode(ERRCODE_UNDEFINED_COLUMN),
+						 errmsg("column \"%s\" named in key does not exist",
+								key->name)));
 			}
 		}
 	}
@@ -271,16 +292,22 @@ CheckPredicate(List *predList)
 	 * restrictions.
 	 */
 	if (contain_subplans((Node *) predList))
-		elog(ERROR, "Cannot use subselect in index predicate");
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("cannot use sub-select in index predicate")));
 	if (contain_agg_clause((Node *) predList))
-		elog(ERROR, "Cannot use aggregate in index predicate");
+		ereport(ERROR,
+				(errcode(ERRCODE_GROUPING_ERROR),
+				 errmsg("cannot use aggregate in index predicate")));
 
 	/*
 	 * A predicate using mutable functions is probably wrong, for the same
 	 * reasons that we don't allow an index expression to use one.
 	 */
 	if (contain_mutable_functions((Node *) predList))
-		elog(ERROR, "Functions in index predicate must be marked IMMUTABLE");
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
+				 errmsg("functions in index predicate must be marked IMMUTABLE")));
 }
 
 static void
@@ -311,8 +338,10 @@ ComputeIndexAttrs(IndexInfo *indexInfo,
 			Assert(attribute->expr == NULL);
 			atttuple = SearchSysCacheAttName(relId, attribute->name);
 			if (!HeapTupleIsValid(atttuple))
-				elog(ERROR, "DefineIndex: attribute \"%s\" not found",
-					 attribute->name);
+				ereport(ERROR,
+						(errcode(ERRCODE_UNDEFINED_COLUMN),
+						 errmsg("attribute \"%s\" does not exist",
+								attribute->name)));
 			attform = (Form_pg_attribute) GETSTRUCT(atttuple);
 			indexInfo->ii_KeyAttrNumbers[attn] = attform->attnum;
 			atttype = attform->atttypid;
@@ -341,9 +370,13 @@ ComputeIndexAttrs(IndexInfo *indexInfo,
 			 * hence these restrictions.
 			 */
 			if (contain_subplans(attribute->expr))
-				elog(ERROR, "Cannot use subselect in index expression");
+				ereport(ERROR,
+						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+						 errmsg("cannot use sub-select in index expression")));
 			if (contain_agg_clause(attribute->expr))
-				elog(ERROR, "Cannot use aggregate in index expression");
+				ereport(ERROR,
+						(errcode(ERRCODE_GROUPING_ERROR),
+						 errmsg("cannot use aggregate in index expression")));
 
 			/*
 			 * A expression using mutable functions is probably wrong,
@@ -352,7 +385,9 @@ ComputeIndexAttrs(IndexInfo *indexInfo,
 			 * all.
 			 */
 			if (contain_mutable_functions(attribute->expr))
-				elog(ERROR, "Functions in index expression must be marked IMMUTABLE");
+				ereport(ERROR,
+						(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
+						 errmsg("functions in index expression must be marked IMMUTABLE")));
 		}
 
 		classOidP[attn] = GetIndexOpClass(attribute->opclass,
@@ -406,10 +441,11 @@ GetIndexOpClass(List *opclass, Oid attrType,
 		/* no operator class specified, so find the default */
 		opClassId = GetDefaultOpClass(attrType, accessMethodId);
 		if (!OidIsValid(opClassId))
-			elog(ERROR, "data type %s has no default operator class for access method \"%s\""
-				 "\n\tYou must specify an operator class for the index or define a"
-				 "\n\tdefault operator class for the data type",
-				 format_type_be(attrType), accessMethodName);
+			ereport(ERROR,
+					(errcode(ERRCODE_UNDEFINED_OBJECT),
+					 errmsg("data type %s has no default operator class for access method \"%s\"",
+							format_type_be(attrType), accessMethodName),
+					 errhint("You must specify an operator class for the index or define a default operator class for the data type.")));
 		return opClassId;
 	}
 
@@ -437,16 +473,20 @@ GetIndexOpClass(List *opclass, Oid attrType,
 		/* Unqualified opclass name, so search the search path */
 		opClassId = OpclassnameGetOpcid(accessMethodId, opcname);
 		if (!OidIsValid(opClassId))
-			elog(ERROR, "DefineIndex: operator class \"%s\" not supported by access method \"%s\"",
-				 opcname, accessMethodName);
+			ereport(ERROR,
+					(errcode(ERRCODE_UNDEFINED_OBJECT),
+					 errmsg("operator class \"%s\" does not exist for access method \"%s\"",
+							opcname, accessMethodName)));
 		tuple = SearchSysCache(CLAOID,
 							   ObjectIdGetDatum(opClassId),
 							   0, 0, 0);
 	}
 
 	if (!HeapTupleIsValid(tuple))
-		elog(ERROR, "DefineIndex: operator class \"%s\" not supported by access method \"%s\"",
-			 NameListToString(opclass), accessMethodName);
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_OBJECT),
+				 errmsg("operator class \"%s\" does not exist for access method \"%s\"",
+						NameListToString(opclass), accessMethodName)));
 
 	/*
 	 * Verify that the index operator class accepts this datatype.	Note
@@ -456,8 +496,10 @@ GetIndexOpClass(List *opclass, Oid attrType,
 	opInputType = ((Form_pg_opclass) GETSTRUCT(tuple))->opcintype;
 
 	if (!IsBinaryCoercible(attrType, opInputType))
-		elog(ERROR, "operator class \"%s\" does not accept data type %s",
-		 NameListToString(opclass), format_type_be(attrType));
+		ereport(ERROR,
+				(errcode(ERRCODE_DATATYPE_MISMATCH),
+				 errmsg("operator class \"%s\" does not accept data type %s",
+						NameListToString(opclass), format_type_be(attrType))));
 
 	ReleaseSysCache(tuple);
 
@@ -510,8 +552,10 @@ GetDefaultOpClass(Oid attrType, Oid accessMethodId)
 	if (nexact == 1)
 		return exactOid;
 	if (nexact != 0)
-		elog(ERROR, "pg_opclass contains multiple default opclasses for data type %s",
-			 format_type_be(attrType));
+		ereport(ERROR,
+				(errcode(ERRCODE_DUPLICATE_OBJECT),
+				 errmsg("there are multiple default operator classes for data type %s",
+						format_type_be(attrType))));
 	if (ncompatible == 1)
 		return compatibleOid;
 
@@ -532,8 +576,10 @@ RemoveIndex(RangeVar *relation, DropBehavior behavior)
 	indOid = RangeVarGetRelid(relation, false);
 	relkind = get_rel_relkind(indOid);
 	if (relkind != RELKIND_INDEX)
-		elog(ERROR, "relation \"%s\" is of type \"%c\"",
-			 relation->relname, relkind);
+		ereport(ERROR,
+				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+				 errmsg("relation \"%s\" is not an index",
+						relation->relname)));
 
 	object.classId = RelOid_pg_class;
 	object.objectId = indOid;
@@ -560,23 +606,30 @@ ReindexIndex(RangeVar *indexRelation, bool force /* currently unused */ )
 	tuple = SearchSysCache(RELOID,
 						   ObjectIdGetDatum(indOid),
 						   0, 0, 0);
-	if (!HeapTupleIsValid(tuple))
-		elog(ERROR, "index \"%s\" does not exist", indexRelation->relname);
+	if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
+		elog(ERROR, "cache lookup failed for relation %u", indOid);
 
 	if (((Form_pg_class) GETSTRUCT(tuple))->relkind != RELKIND_INDEX)
-		elog(ERROR, "relation \"%s\" is of type \"%c\"",
-			 indexRelation->relname,
-			 ((Form_pg_class) GETSTRUCT(tuple))->relkind);
+		ereport(ERROR,
+				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+				 errmsg("relation \"%s\" is not an index",
+						indexRelation->relname)));
 
 	if (IsSystemClass((Form_pg_class) GETSTRUCT(tuple)) &&
 		!IsToastClass((Form_pg_class) GETSTRUCT(tuple)))
 	{
 		if (!allowSystemTableMods)
-			elog(ERROR, "\"%s\" is a system index. call REINDEX under standalone postgres with -O -P options",
-				 indexRelation->relname);
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+					 errmsg("\"%s\" is a system index",
+							indexRelation->relname),
+					 errhint("Do REINDEX in standalone postgres with -O -P options.")));
 		if (!IsIgnoringSystemIndexes())
-			elog(ERROR, "\"%s\" is a system index. call REINDEX under standalone postgres with -P -O options",
-				 indexRelation->relname);
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+					 errmsg("\"%s\" is a system index",
+							indexRelation->relname),
+					 errhint("Do REINDEX in standalone postgres with -P -O options.")));
 	}
 
 	ReleaseSysCache(tuple);
@@ -590,7 +643,9 @@ ReindexIndex(RangeVar *indexRelation, bool force /* currently unused */ )
 		PreventTransactionChain((void *) indexRelation, "REINDEX");
 
 	if (!reindex_index(indOid, force, overwrite))
-		elog(WARNING, "index \"%s\" wasn't reindexed", indexRelation->relname);
+		ereport(WARNING,
+				(errmsg("index \"%s\" wasn't reindexed",
+						indexRelation->relname)));
 }
 
 /*
@@ -607,8 +662,10 @@ ReindexTable(RangeVar *relation, bool force)
 	relkind = get_rel_relkind(heapOid);
 
 	if (relkind != RELKIND_RELATION && relkind != RELKIND_TOASTVALUE)
-		elog(ERROR, "relation \"%s\" is of type \"%c\"",
-			 relation->relname, relkind);
+		ereport(ERROR,
+				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+				 errmsg("relation \"%s\" is not a table",
+						relation->relname)));
 
 	/*
 	 * In-place REINDEX within a transaction block is dangerous, because
@@ -622,7 +679,9 @@ ReindexTable(RangeVar *relation, bool force)
 		PreventTransactionChain((void *) relation, "REINDEX");
 
 	if (!reindex_relation(heapOid, force))
-		elog(WARNING, "table \"%s\" wasn't reindexed", relation->relname);
+		ereport(WARNING,
+				(errmsg("table \"%s\" wasn't reindexed",
+						relation->relname)));
 }
 
 /*
@@ -646,15 +705,23 @@ ReindexDatabase(const char *dbname, bool force, bool all)
 	AssertArg(dbname);
 
 	if (strcmp(dbname, get_database_name(MyDatabaseId)) != 0)
-		elog(ERROR, "REINDEX DATABASE: Can be executed only on the currently open database.");
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("can only reindex the currently open database")));
 
 	if (!pg_database_ownercheck(MyDatabaseId, GetUserId()))
-		elog(ERROR, "REINDEX DATABASE: Permission denied.");
+		ereport(ERROR,
+				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+				 errmsg("permission denied")));
 
 	if (!allowSystemTableMods)
-		elog(ERROR, "must be called under standalone postgres with -O -P options");
+		ereport(ERROR,
+				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+				 errmsg("REINDEX DATABASE must be done in standalone postgres with -O -P options")));
 	if (!IsIgnoringSystemIndexes())
-		elog(ERROR, "must be called under standalone postgres with -P -O options");
+		ereport(ERROR,
+				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+				 errmsg("REINDEX DATABASE must be done in standalone postgres with -P -O options")));
 
 	/*
 	 * We cannot run inside a user transaction block; if we were inside a
@@ -720,7 +787,8 @@ ReindexDatabase(const char *dbname, bool force, bool all)
 		StartTransactionCommand();
 		SetQuerySnapshot();		/* might be needed for functions in indexes */
 		if (reindex_relation(relids[i], force))
-			elog(NOTICE, "relation %u was reindexed", relids[i]);
+			ereport(NOTICE,
+					(errmsg("relation %u was reindexed", relids[i])));
 		CommitTransactionCommand();
 	}
 	StartTransactionCommand();
diff --git a/src/backend/commands/lockcmds.c b/src/backend/commands/lockcmds.c
index c2bb202c9c216fca90f1f9edfe2d8b44fdf045c7..a2dfb6d805b7f0a2e554841b2a7a4bd3f81b8f94 100644
--- a/src/backend/commands/lockcmds.c
+++ b/src/backend/commands/lockcmds.c
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/commands/lockcmds.c,v 1.4 2002/09/04 20:31:15 momjian Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/commands/lockcmds.c,v 1.5 2003/07/20 21:56:32 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -62,8 +62,10 @@ LockTableCommand(LockStmt *lockstmt)
 
 		/* Currently, we only allow plain tables to be locked */
 		if (rel->rd_rel->relkind != RELKIND_RELATION)
-			elog(ERROR, "LOCK TABLE: %s is not a table",
-				 relation->relname);
+			ereport(ERROR,
+					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+					 errmsg("\"%s\" is not a table",
+							relation->relname)));
 
 		relation_close(rel, NoLock);	/* close rel, keep lock */
 	}
diff --git a/src/backend/commands/opclasscmds.c b/src/backend/commands/opclasscmds.c
index fde8f95d9c3483588c291193936eecc3c96afc24..28807790d98f4156756479d5e320ebb26d2e95cc 100644
--- a/src/backend/commands/opclasscmds.c
+++ b/src/backend/commands/opclasscmds.c
@@ -9,7 +9,7 @@
  *
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/commands/opclasscmds.c,v 1.12 2003/07/18 23:20:32 tgl Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/commands/opclasscmds.c,v 1.13 2003/07/20 21:56:32 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -252,7 +252,7 @@ DefineOpClass(CreateOpClassStmt *stmt)
 							 0))
 		ereport(ERROR,
 				(errcode(ERRCODE_DUPLICATE_OBJECT),
-				 errmsg("operator class \"%s\" already exists for access method \"%s\"",
+				 errmsg("operator class \"%s\" for access method \"%s\" already exists",
 						opcname, stmt->amname)));
 
 	/*
diff --git a/src/backend/commands/operatorcmds.c b/src/backend/commands/operatorcmds.c
index 6c902b643ce06f363a9b6f3045fddb70c4ea1093..bc4724f47380f61e58f9f33e44833d8760d56c6b 100644
--- a/src/backend/commands/operatorcmds.c
+++ b/src/backend/commands/operatorcmds.c
@@ -9,7 +9,7 @@
  *
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/commands/operatorcmds.c,v 1.8 2003/07/04 02:51:33 tgl Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/commands/operatorcmds.c,v 1.9 2003/07/20 21:56:32 tgl Exp $
  *
  * DESCRIPTION
  *	  The "DefineFoo" routines take the parse tree and pick out the
@@ -100,13 +100,17 @@ DefineOperator(List *names, List *parameters)
 		{
 			typeName1 = defGetTypeName(defel);
 			if (typeName1->setof)
-				elog(ERROR, "setof type not implemented for leftarg");
+				ereport(ERROR,
+						(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
+						 errmsg("setof type not allowed for operator argument")));
 		}
 		else if (strcasecmp(defel->defname, "rightarg") == 0)
 		{
 			typeName2 = defGetTypeName(defel);
 			if (typeName2->setof)
-				elog(ERROR, "setof type not implemented for rightarg");
+				ereport(ERROR,
+						(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
+						 errmsg("setof type not allowed for operator argument")));
 		}
 		else if (strcasecmp(defel->defname, "procedure") == 0)
 			functionName = defGetQualifiedName(defel);
@@ -131,17 +135,19 @@ DefineOperator(List *names, List *parameters)
 		else if (strcasecmp(defel->defname, "gtcmp") == 0)
 			gtCompareName = defGetQualifiedName(defel);
 		else
-		{
-			elog(WARNING, "DefineOperator: attribute \"%s\" not recognized",
-				 defel->defname);
-		}
+			ereport(WARNING,
+					(errcode(ERRCODE_SYNTAX_ERROR),
+					 errmsg("operator attribute \"%s\" not recognized",
+							defel->defname)));
 	}
 
 	/*
 	 * make sure we have our required definitions
 	 */
 	if (functionName == NIL)
-		elog(ERROR, "Define: \"procedure\" unspecified");
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
+				 errmsg("operator procedure must be specified")));
 
 	/* Transform type names to type OIDs */
 	if (typeName1)
@@ -212,7 +218,7 @@ RemoveOperator(RemoveOperStmt *stmt)
 						 ObjectIdGetDatum(operOid),
 						 0, 0, 0);
 	if (!HeapTupleIsValid(tup)) /* should not happen */
-		elog(ERROR, "cache lookup of operator %u failed", operOid);
+		elog(ERROR, "cache lookup failed for operator %u", operOid);
 
 	/* Permission check: must own operator or its namespace */
 	if (!pg_oper_ownercheck(operOid, GetUserId()) &&
@@ -247,8 +253,7 @@ RemoveOperatorById(Oid operOid)
 						 ObjectIdGetDatum(operOid),
 						 0, 0, 0);
 	if (!HeapTupleIsValid(tup)) /* should not happen */
-		elog(ERROR, "RemoveOperatorById: failed to find tuple for operator %u",
-			 operOid);
+		elog(ERROR, "cache lookup failed for operator %u", operOid);
 
 	simple_heap_delete(relation, &tup->t_self);
 
diff --git a/src/backend/commands/portalcmds.c b/src/backend/commands/portalcmds.c
index f9e31c3aaa1cdba27089e36cf94328ae5710ee07..df82a4b26fa8b49f65653f091562e128320cad84 100644
--- a/src/backend/commands/portalcmds.c
+++ b/src/backend/commands/portalcmds.c
@@ -14,7 +14,7 @@
  *
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/commands/portalcmds.c,v 1.16 2003/05/08 18:16:36 tgl Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/commands/portalcmds.c,v 1.17 2003/07/20 21:56:32 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -49,7 +49,9 @@ PerformCursorOpen(DeclareCursorStmt *stmt)
 	 * unnamed portal).
 	 */
 	if (!stmt->portalname || stmt->portalname[0] == '\0')
-		elog(ERROR, "Invalid cursor name: must not be empty");
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_CURSOR_NAME),
+				 errmsg("invalid cursor name: must not be empty")));
 
 	/*
 	 * If this is a non-holdable cursor, we require that this statement
@@ -66,16 +68,20 @@ PerformCursorOpen(DeclareCursorStmt *stmt)
 	 */
 	rewritten = QueryRewrite((Query *) stmt->query);
 	if (length(rewritten) != 1 || !IsA(lfirst(rewritten), Query))
-		elog(ERROR, "PerformCursorOpen: unexpected rewrite result");
+		elog(ERROR, "unexpected rewrite result");
 	query = (Query *) lfirst(rewritten);
 	if (query->commandType != CMD_SELECT)
-		elog(ERROR, "PerformCursorOpen: unexpected rewrite result");
+		elog(ERROR, "unexpected rewrite result");
 
 	if (query->into)
-		elog(ERROR, "DECLARE CURSOR may not specify INTO");
+		ereport(ERROR,
+				(errcode(ERRCODE_SYNTAX_ERROR),
+				 errmsg("DECLARE CURSOR may not specify INTO")));
 	if (query->rowMarks != NIL)
-		elog(ERROR, "DECLARE/UPDATE is not supported"
-			 "\n\tCursors must be READ ONLY");
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("DECLARE CURSOR ... FOR UPDATE is not supported"),
+				 errdetail("Cursors must be READ ONLY.")));
 
 	plan = planner(query, true, stmt->options);
 
@@ -152,15 +158,19 @@ PerformPortalFetch(FetchStmt *stmt,
 	 * unnamed portal).
 	 */
 	if (!stmt->portalname || stmt->portalname[0] == '\0')
-		elog(ERROR, "Invalid cursor name: must not be empty");
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_CURSOR_NAME),
+				 errmsg("invalid cursor name: must not be empty")));
 
 	/* get the portal from the portal name */
 	portal = GetPortalByName(stmt->portalname);
 	if (!PortalIsValid(portal))
 	{
 		/* FIXME: shouldn't this be an ERROR? */
-		elog(WARNING, "PerformPortalFetch: portal \"%s\" not found",
-			 stmt->portalname);
+		ereport(WARNING,
+				(errcode(ERRCODE_UNDEFINED_CURSOR),
+				 errmsg("portal \"%s\" does not exist", stmt->portalname),
+				 errfunction("PerformPortalFetch"))); /* for ecpg */
 		if (completionTag)
 			strcpy(completionTag, stmt->ismove ? "MOVE 0" : "FETCH 0");
 		return;
@@ -197,7 +207,9 @@ PerformPortalClose(const char *name)
 	 * unnamed portal).
 	 */
 	if (!name || name[0] == '\0')
-		elog(ERROR, "Invalid cursor name: must not be empty");
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_CURSOR_NAME),
+				 errmsg("invalid cursor name: must not be empty")));
 
 	/*
 	 * get the portal from the portal name
@@ -205,8 +217,10 @@ PerformPortalClose(const char *name)
 	portal = GetPortalByName(name);
 	if (!PortalIsValid(portal))
 	{
-		elog(WARNING, "PerformPortalClose: portal \"%s\" not found",
-			 name);
+		ereport(WARNING,
+				(errcode(ERRCODE_UNDEFINED_CURSOR),
+				 errmsg("portal \"%s\" does not exist", name),
+				 errfunction("PerformPortalClose"))); /* for ecpg */
 		return;
 	}
 
@@ -292,7 +306,9 @@ PersistHoldablePortal(Portal portal)
 	 * Check for improper portal use, and mark portal active.
 	 */
 	if (portal->portalActive)
-		elog(ERROR, "Portal \"%s\" already active", portal->name);
+		ereport(ERROR,
+				(errcode(ERRCODE_OBJECT_IN_USE),
+				 errmsg("portal \"%s\" already active", portal->name)));
 	portal->portalActive = true;
 
 	/*
@@ -347,7 +363,9 @@ PersistHoldablePortal(Portal portal)
 		long	store_pos;
 
 		if (portal->posOverflow)		/* oops, cannot trust portalPos */
-			elog(ERROR, "Unable to reposition held cursor");
+			ereport(ERROR,
+					(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+					 errmsg("unable to reposition held cursor")));
 
 		tuplestore_rescan(portal->holdStore);
 
@@ -360,8 +378,7 @@ PersistHoldablePortal(Portal portal)
 									  &should_free);
 
 			if (tup == NULL)
-				elog(ERROR,
-					 "PersistHoldablePortal: unexpected end of tuple stream");
+				elog(ERROR, "unexpected end of tuple stream");
 
 			if (should_free)
 				pfree(tup);
diff --git a/src/backend/commands/prepare.c b/src/backend/commands/prepare.c
index dad1b7f703c6cff910aa0ba0bb83be8cc4cfdd95..ae6c45019ad4ebe2d4fbbb1338e44b77838e724b 100644
--- a/src/backend/commands/prepare.c
+++ b/src/backend/commands/prepare.c
@@ -10,7 +10,7 @@
  * Copyright (c) 2002-2003, PostgreSQL Global Development Group
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/commands/prepare.c,v 1.19 2003/07/01 00:04:31 petere Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/commands/prepare.c,v 1.20 2003/07/20 21:56:32 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -56,7 +56,9 @@ PrepareQuery(PrepareStmt *stmt)
 	 * unnamed statement).
 	 */
 	if (!stmt->name || stmt->name[0] == '\0')
-		elog(ERROR, "Invalid statement name: must not be empty");
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_PSTATEMENT_DEFINITION),
+				 errmsg("invalid statement name: must not be empty")));
 
 	switch (stmt->query->commandType)
 	{
@@ -73,7 +75,9 @@ PrepareQuery(PrepareStmt *stmt)
 			commandTag = "DELETE";
 			break;
 		default:
-			elog(ERROR, "Utility statements cannot be prepared");
+			ereport(ERROR,
+					(errcode(ERRCODE_INVALID_PSTATEMENT_DEFINITION),
+					 errmsg("utility statements cannot be prepared")));
 			commandTag = NULL;	/* keep compiler quiet */
 			break;
 	}
@@ -159,10 +163,14 @@ ExecuteQuery(ExecuteStmt *stmt, DestReceiver *dest)
 		qcontext = PortalGetHeapMemory(portal);
 
 		if (length(query_list) != 1)
-			elog(ERROR, "prepared statement is not a SELECT");
+			ereport(ERROR,
+					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+					 errmsg("prepared statement is not a SELECT")));
 		query = (Query *) lfirst(query_list);
 		if (query->commandType != CMD_SELECT)
-			elog(ERROR, "prepared statement is not a SELECT");
+			ereport(ERROR,
+					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+					 errmsg("prepared statement is not a SELECT")));
 		query->into = copyObject(stmt->into);
 
 		MemoryContextSwitchTo(oldContext);
@@ -206,9 +214,9 @@ EvaluateParams(EState *estate, List *params, List *argtypes)
 	List		   *l;
 	int				i = 0;
 
-	/* Parser should have caught this error, but check anyway */
+	/* Parser should have caught this error, but check for safety */
 	if (length(params) != nargs)
-		elog(ERROR, "EvaluateParams: wrong number of arguments");
+		elog(ERROR, "wrong number of arguments");
 
 	exprstates = (List *) ExecPrepareExpr((Expr *) params, estate);
 
@@ -256,7 +264,7 @@ InitQueryHashTable(void)
 								   HASH_ELEM);
 
 	if (!prepared_queries)
-		elog(ERROR, "InitQueryHashTable: unable to create hash table");
+		elog(ERROR, "unable to create hash table");
 }
 
 /*
@@ -295,8 +303,10 @@ StorePreparedStatement(const char *stmt_name,
 	hash_search(prepared_queries, key, HASH_FIND, &found);
 
 	if (found)
-		elog(ERROR, "Prepared statement with name \"%s\" already exists",
-			 stmt_name);
+		ereport(ERROR,
+				(errcode(ERRCODE_DUPLICATE_PSTATEMENT),
+				 errmsg("prepared statement \"%s\" already exists",
+						stmt_name)));
 
 	/* Make a permanent memory context for the hashtable entry */
 	entrycxt = AllocSetContextCreate(TopMemoryContext,
@@ -326,7 +336,7 @@ StorePreparedStatement(const char *stmt_name,
 
 	/* Shouldn't get a failure, nor a duplicate entry */
 	if (!entry || found)
-		elog(ERROR, "Unable to store prepared statement \"%s\"!",
+		elog(ERROR, "unable to store prepared statement \"%s\"",
 			 stmt_name);
 
 	/* Fill in the hash table entry with copied data */
@@ -342,7 +352,7 @@ StorePreparedStatement(const char *stmt_name,
 
 /*
  * Lookup an existing query in the hash table. If the query does not
- * actually exist, throw elog(ERROR) or return NULL per second parameter.
+ * actually exist, throw ereport(ERROR) or return NULL per second parameter.
  */
 PreparedStatement *
 FetchPreparedStatement(const char *stmt_name, bool throwError)
@@ -373,8 +383,10 @@ FetchPreparedStatement(const char *stmt_name, bool throwError)
 		entry = NULL;
 
 	if (!entry && throwError)
-		elog(ERROR, "Prepared statement with name \"%s\" does not exist",
-			 stmt_name);
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_PSTATEMENT),
+				 errmsg("prepared statement \"%s\" does not exist",
+						stmt_name)));
 
 	return entry;
 }
@@ -519,7 +531,9 @@ ExplainExecuteQuery(ExplainStmt *stmt, TupOutputState *tstate)
 			if (execstmt->into)
 			{
 				if (query->commandType != CMD_SELECT)
-					elog(ERROR, "prepared statement is not a SELECT");
+					ereport(ERROR,
+							(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+							 errmsg("prepared statement is not a SELECT")));
 
 				/* Copy the query so we can modify it */
 				query = copyObject(query);
diff --git a/src/backend/commands/sequence.c b/src/backend/commands/sequence.c
index cb4948263083b32ba23d7c423874174327259abc..fd30a33b8865b6bbaeaab70efc2edd6d5ea208c5 100644
--- a/src/backend/commands/sequence.c
+++ b/src/backend/commands/sequence.c
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/commands/sequence.c,v 1.96 2003/06/12 07:49:43 momjian Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/commands/sequence.c,v 1.97 2003/07/20 21:56:32 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -67,11 +67,10 @@ typedef SeqTableData *SeqTable;
 static SeqTable seqtab = NULL;	/* Head of list of SeqTable items */
 
 
-static void init_sequence(const char *caller, RangeVar *relation,
-			  SeqTable *p_elm, Relation *p_rel);
-static Form_pg_sequence read_info(const char *caller, SeqTable elm,
-		  Relation rel, Buffer *buf);
-static void init_params(char *caller, List *options, Form_pg_sequence new);
+static void init_sequence(RangeVar *relation,
+						  SeqTable *p_elm, Relation *p_rel);
+static Form_pg_sequence read_info(SeqTable elm, Relation rel, Buffer *buf);
+static void init_params(List *options, Form_pg_sequence new);
 static void do_setval(RangeVar *sequence, int64 next, bool iscalled);
 
 /*
@@ -104,7 +103,7 @@ DefineSequence(CreateSeqStmt *seq)
 	new.is_cycled = false; 
 
 	/* Check and set values */
-	init_params("DefineSequence", seq->options, &new);
+	init_params(seq->options, &new);
 
 	/*
 	 * Create relation (and fill *null & *value)
@@ -200,7 +199,7 @@ DefineSequence(CreateSeqStmt *seq)
 	buf = ReadBuffer(rel, P_NEW);
 
 	if (!BufferIsValid(buf))
-		elog(ERROR, "DefineSequence: ReadBuffer failed");
+		elog(ERROR, "ReadBuffer failed");
 
 	Assert(BufferGetBlockNumber(buf) == 0);
 
@@ -313,14 +312,14 @@ AlterSequence(AlterSeqStmt *stmt)
 	FormData_pg_sequence new;
 
 	/* open and AccessShareLock sequence */
-	init_sequence("setval", stmt->sequence, &elm, &seqrel);
+	init_sequence(stmt->sequence, &elm, &seqrel);
 
 	/* Allow DROP to sequence owner only*/
 	if (!pg_class_ownercheck(elm->relid, GetUserId()))
 		aclcheck_error(ACLCHECK_NOT_OWNER, stmt->sequence->relname);
 
 	/* lock page' buffer and read tuple into new sequence structure */
-	seq = read_info("nextval", elm, seqrel, &buf);
+	seq = read_info(elm, seqrel, &buf);
 	page = BufferGetPage(buf);
 
 	new.increment_by = seq->increment_by;
@@ -331,7 +330,7 @@ AlterSequence(AlterSeqStmt *stmt)
 	new.last_value = seq->last_value;
 
 	/* Check and set values */
-	init_params("AlterSequence", stmt->options, &new);
+	init_params(stmt->options, &new);
 
 	seq->increment_by = new.increment_by;
 	seq->max_value = new.max_value;
@@ -413,11 +412,13 @@ nextval(PG_FUNCTION_ARGS)
 															 "nextval"));
 
 	/* open and AccessShareLock sequence */
-	init_sequence("nextval", sequence, &elm, &seqrel);
+	init_sequence(sequence, &elm, &seqrel);
 
 	if (pg_class_aclcheck(elm->relid, GetUserId(), ACL_UPDATE) != ACLCHECK_OK)
-		elog(ERROR, "%s.nextval: you don't have permissions to set sequence %s",
-			 sequence->relname, sequence->relname);
+		ereport(ERROR,
+				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+				 errmsg("%s.nextval: permission denied",
+						sequence->relname)));
 
 	if (elm->last != elm->cached)		/* some numbers were cached */
 	{
@@ -427,7 +428,7 @@ nextval(PG_FUNCTION_ARGS)
 	}
 
 	/* lock page' buffer and read tuple */
-	seq = read_info("nextval", elm, seqrel, &buf);
+	seq = read_info(elm, seqrel, &buf);
 	page = BufferGetPage(buf);
 
 	last = next = result = seq->last_value;
@@ -491,8 +492,10 @@ nextval(PG_FUNCTION_ARGS)
 					char		buf[100];
 
 					snprintf(buf, sizeof(buf), INT64_FORMAT, maxv);
-					elog(ERROR, "%s.nextval: reached MAXVALUE (%s)",
-						 sequence->relname, buf);
+					ereport(ERROR,
+							(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+							 errmsg("%s.nextval: reached MAXVALUE (%s)",
+									sequence->relname, buf)));
 				}
 				next = minv;
 			}
@@ -512,8 +515,10 @@ nextval(PG_FUNCTION_ARGS)
 					char		buf[100];
 
 					snprintf(buf, sizeof(buf), INT64_FORMAT, minv);
-					elog(ERROR, "%s.nextval: reached MINVALUE (%s)",
-						 sequence->relname, buf);
+					ereport(ERROR,
+							(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+							 errmsg("%s.nextval: reached MINVALUE (%s)",
+									sequence->relname, buf)));
 				}
 				next = maxv;
 			}
@@ -599,15 +604,19 @@ currval(PG_FUNCTION_ARGS)
 															 "currval"));
 
 	/* open and AccessShareLock sequence */
-	init_sequence("currval", sequence, &elm, &seqrel);
+	init_sequence(sequence, &elm, &seqrel);
 
 	if (pg_class_aclcheck(elm->relid, GetUserId(), ACL_SELECT) != ACLCHECK_OK)
-		elog(ERROR, "%s.currval: you don't have permissions to read sequence %s",
-			 sequence->relname, sequence->relname);
+		ereport(ERROR,
+				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+				 errmsg("%s.currval: permission denied",
+						sequence->relname)));
 
 	if (elm->increment == 0)	/* nextval/read_info were not called */
-		elog(ERROR, "%s.currval is not yet defined in this session",
-			 sequence->relname);
+		ereport(ERROR,
+				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+				 errmsg("%s.currval is not yet defined in this session",
+						sequence->relname)));
 
 	result = elm->last;
 
@@ -638,14 +647,16 @@ do_setval(RangeVar *sequence, int64 next, bool iscalled)
 	Form_pg_sequence seq;
 
 	/* open and AccessShareLock sequence */
-	init_sequence("setval", sequence, &elm, &seqrel);
+	init_sequence(sequence, &elm, &seqrel);
 
 	if (pg_class_aclcheck(elm->relid, GetUserId(), ACL_UPDATE) != ACLCHECK_OK)
-		elog(ERROR, "%s.setval: you don't have permissions to set sequence %s",
-			 sequence->relname, sequence->relname);
+		ereport(ERROR,
+				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+				 errmsg("%s.setval: permission denied",
+						sequence->relname)));
 
 	/* lock page' buffer and read tuple */
-	seq = read_info("setval", elm, seqrel, &buf);
+	seq = read_info(elm, seqrel, &buf);
 
 	if ((next < seq->min_value) || (next > seq->max_value))
 	{
@@ -656,8 +667,10 @@ do_setval(RangeVar *sequence, int64 next, bool iscalled)
 		snprintf(bufv, sizeof(bufv), INT64_FORMAT, next);
 		snprintf(bufm, sizeof(bufm), INT64_FORMAT, seq->min_value);
 		snprintf(bufx, sizeof(bufx), INT64_FORMAT, seq->max_value);
-		elog(ERROR, "%s.setval: value %s is out of bounds (%s,%s)",
-			 sequence->relname, bufv, bufm, bufx);
+		ereport(ERROR,
+				(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
+				 errmsg("%s.setval: value %s is out of bounds (%s..%s)",
+						sequence->relname, bufv, bufm, bufx)));
 	}
 
 	/* save info in local cache */
@@ -757,8 +770,7 @@ setval_and_iscalled(PG_FUNCTION_ARGS)
  * output parameters.
  */
 static void
-init_sequence(const char *caller, RangeVar *relation,
-			  SeqTable *p_elm, Relation *p_rel)
+init_sequence(RangeVar *relation, SeqTable *p_elm, Relation *p_rel)
 {
 	Oid			relid = RangeVarGetRelid(relation, false);
 	TransactionId thisxid = GetCurrentTransactionId();
@@ -782,8 +794,10 @@ init_sequence(const char *caller, RangeVar *relation,
 		seqrel = relation_open(relid, NoLock);
 
 	if (seqrel->rd_rel->relkind != RELKIND_SEQUENCE)
-		elog(ERROR, "%s.%s: %s is not a sequence",
-			 relation->relname, caller, relation->relname);
+		ereport(ERROR,
+				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+				 errmsg("\"%s\" is not a sequence",
+						relation->relname)));
 
 	/*
 	 * Allocate new seqtable entry if we didn't find one.
@@ -800,7 +814,9 @@ init_sequence(const char *caller, RangeVar *relation,
 		 */
 		elm = (SeqTable) malloc(sizeof(SeqTableData));
 		if (elm == NULL)
-			elog(ERROR, "Memory exhausted in init_sequence");
+			ereport(ERROR,
+					(errcode(ERRCODE_OUT_OF_MEMORY),
+					 errmsg("out of memory")));
 		elm->relid = relid;
 		/* increment is set to 0 until we do read_info (see currval) */
 		elm->last = elm->cached = elm->increment = 0;
@@ -818,8 +834,7 @@ init_sequence(const char *caller, RangeVar *relation,
 
 /* Given an opened relation, lock the page buffer and find the tuple */
 static Form_pg_sequence
-read_info(const char *caller, SeqTable elm,
-		  Relation rel, Buffer *buf)
+read_info(SeqTable elm, Relation rel, Buffer *buf)
 {
 	PageHeader	page;
 	ItemId		lp;
@@ -828,13 +843,12 @@ read_info(const char *caller, SeqTable elm,
 	Form_pg_sequence seq;
 
 	if (rel->rd_nblocks > 1)
-		elog(ERROR, "%s.%s: invalid number of blocks in sequence",
-			 RelationGetRelationName(rel), caller);
+		elog(ERROR, "invalid number of blocks in sequence \"%s\"",
+			 RelationGetRelationName(rel));
 
 	*buf = ReadBuffer(rel, 0);
 	if (!BufferIsValid(*buf))
-		elog(ERROR, "%s.%s: ReadBuffer failed",
-			 RelationGetRelationName(rel), caller);
+		elog(ERROR, "ReadBuffer failed");
 
 	LockBuffer(*buf, BUFFER_LOCK_EXCLUSIVE);
 
@@ -842,8 +856,8 @@ read_info(const char *caller, SeqTable elm,
 	sm = (sequence_magic *) PageGetSpecialPointer(page);
 
 	if (sm->magic != SEQ_MAGIC)
-		elog(ERROR, "%s.%s: bad magic (%08X)",
-			 RelationGetRelationName(rel), caller, sm->magic);
+		elog(ERROR, "bad magic number (%08X) in sequence \"%s\"",
+			 sm->magic, RelationGetRelationName(rel));
 
 	lp = PageGetItemId(page, FirstOffsetNumber);
 	Assert(ItemIdIsUsed(lp));
@@ -858,7 +872,7 @@ read_info(const char *caller, SeqTable elm,
 
 
 static void
-init_params(char *caller, List *options, Form_pg_sequence new)
+init_params(List *options, Form_pg_sequence new)
 {
 	DefElem    *last_value = NULL;
 	DefElem    *increment_by = NULL;
@@ -875,49 +889,59 @@ init_params(char *caller, List *options, Form_pg_sequence new)
 		if (strcmp(defel->defname, "increment") == 0)
 		{
 			if (increment_by)
-				elog(ERROR, "%s: INCREMENT BY defined twice", caller);
-
+				ereport(ERROR,
+						(errcode(ERRCODE_SYNTAX_ERROR),
+						 errmsg("conflicting or redundant options")));
 			increment_by = defel;
-
 		}
 		/*
 		 * start is for a new sequence
 		 * restart is for alter
 		 */
-		else if ((new->last_value == 0L && strcmp(defel->defname, "start") == 0)
-			|| (new->last_value != 0 && strcmp(defel->defname, "restart") == 0))
+		else if (strcmp(defel->defname, "start") == 0 ||
+				 strcmp(defel->defname, "restart") == 0)
 		{
 			if (last_value)
-				elog(ERROR, "%s: LAST VALUE defined twice", caller);
+				ereport(ERROR,
+						(errcode(ERRCODE_SYNTAX_ERROR),
+						 errmsg("conflicting or redundant options")));
 			last_value = defel;
 		}
 		else if (strcmp(defel->defname, "maxvalue") == 0)
 		{
 			if (max_value)
-				elog(ERROR, "%s: MAX VALUE defined twice", caller);
+				ereport(ERROR,
+						(errcode(ERRCODE_SYNTAX_ERROR),
+						 errmsg("conflicting or redundant options")));
 			max_value = defel;
 		}
 		else if (strcmp(defel->defname, "minvalue") == 0)
 		{
 			if (min_value)
-				elog(ERROR, "%s: MIN VALUE defined twice", caller);
+				ereport(ERROR,
+						(errcode(ERRCODE_SYNTAX_ERROR),
+						 errmsg("conflicting or redundant options")));
 			min_value = defel;
 		}
 		else if (strcmp(defel->defname, "cache") == 0)
 		{
 			if (cache_value)
-				elog(ERROR, "%s: CACHE defined twice", caller);
+				ereport(ERROR,
+						(errcode(ERRCODE_SYNTAX_ERROR),
+						 errmsg("conflicting or redundant options")));
 			cache_value = defel;
 		}
 		else if (strcmp(defel->defname, "cycle") == 0)
 		{
 			if (is_cycled_set)
-				elog(ERROR, "%s: CYCLE defined twice", caller);
+				ereport(ERROR,
+						(errcode(ERRCODE_SYNTAX_ERROR),
+						 errmsg("conflicting or redundant options")));
 			is_cycled_set = true;
 			new->is_cycled = (defel->arg != NULL);
 		}
 		else
-			elog(ERROR, "%s: option \"%s\" not recognized", caller,
+			elog(ERROR, "option \"%s\" not recognized",
 				 defel->defname);
 	}
 
@@ -926,10 +950,11 @@ init_params(char *caller, List *options, Form_pg_sequence new)
 		new->increment_by = 1;
 	else if (increment_by != (DefElem *) NULL)
 	{
-		if (defGetInt64(increment_by) == 0)
-			elog(ERROR, "%s: can't INCREMENT by 0", caller);
-
 		new->increment_by = defGetInt64(increment_by);
+		if (new->increment_by == 0)
+			ereport(ERROR,
+					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+					 errmsg("can't INCREMENT by zero")));
 	}
 
 	/* MAXVALUE */
@@ -963,8 +988,10 @@ init_params(char *caller, List *options, Form_pg_sequence new)
 
 		snprintf(bufm, sizeof(bufm), INT64_FORMAT, new->min_value);
 		snprintf(bufx, sizeof(bufx), INT64_FORMAT, new->max_value);
-		elog(ERROR, "%s: MINVALUE (%s) must be less than MAXVALUE (%s)",
-			 caller, bufm, bufx);
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+				 errmsg("MINVALUE (%s) must be less than MAXVALUE (%s)",
+						bufm, bufx)));
 	}
 
 	/* START WITH */
@@ -985,8 +1012,10 @@ init_params(char *caller, List *options, Form_pg_sequence new)
 
 		snprintf(bufs, sizeof(bufs), INT64_FORMAT, new->last_value);
 		snprintf(bufm, sizeof(bufm), INT64_FORMAT, new->min_value);
-		elog(ERROR, "%s: START value (%s) can't be less than MINVALUE (%s)",
-			 caller, bufs, bufm);
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+				 errmsg("START value (%s) can't be less than MINVALUE (%s)",
+						bufs, bufm)));
 	}
 	if (new->last_value > new->max_value)
 	{
@@ -995,8 +1024,10 @@ init_params(char *caller, List *options, Form_pg_sequence new)
 
 		snprintf(bufs, sizeof(bufs), INT64_FORMAT, new->last_value);
 		snprintf(bufm, sizeof(bufm), INT64_FORMAT, new->max_value);
-		elog(ERROR, "%s: START value (%s) can't be greater than MAXVALUE (%s)",
-			 caller, bufs, bufm);
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+				 errmsg("START value (%s) can't be greater than MAXVALUE (%s)",
+						bufs, bufm)));
 	}
 
 	/* CACHE */
@@ -1007,8 +1038,9 @@ init_params(char *caller, List *options, Form_pg_sequence new)
 		char		buf[100];
 
 		snprintf(buf, sizeof(buf), INT64_FORMAT, new->cache_value);
-		elog(ERROR, "%s: CACHE (%s) can't be <= 0",
-			 caller, buf);
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+				 errmsg("CACHE (%s) must be greater than zero", buf)));
 	}
 }
 
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index c463c8bd1b7189bd7c9d79de5c40a9b532ec483a..11b93759b8a08e0b7f3b1c62aa28bba246c53d6c 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/commands/tablecmds.c,v 1.74 2003/06/06 15:04:01 tgl Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/commands/tablecmds.c,v 1.75 2003/07/20 21:56:32 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -79,13 +79,11 @@ static bool change_varattnos_of_a_node(Node *node, const AttrNumber *newattno);
 static void StoreCatalogInheritance(Oid relationId, List *supers);
 static int	findAttrByName(const char *attributeName, List *schema);
 static void setRelhassubclassInRelation(Oid relationId, bool relhassubclass);
-static void CheckTupleType(Form_pg_class tuple_class);
 static bool needs_toast_table(Relation rel);
 static void AlterTableAddCheckConstraint(Relation rel, Constraint *constr);
 static void AlterTableAddForeignKeyConstraint(Relation rel,
 											  FkConstraint *fkconstraint);
 static int transformColumnNameList(Oid relId, List *colList,
-								   const char *stmtname,
 								   int16 *attnums, Oid *atttypids);
 static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
 									  List **attnamelist,
@@ -146,7 +144,9 @@ DefineRelation(CreateStmt *stmt, char relkind)
 	 * Check consistency of arguments
 	 */
 	if (stmt->oncommit != ONCOMMIT_NOOP && !stmt->relation->istemp)
-		elog(ERROR, "ON COMMIT can only be used on TEMP tables");
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
+				 errmsg("ON COMMIT can only be used on TEMP tables")));
 
 	/*
 	 * Look up the namespace in which we are supposed to create the
@@ -203,8 +203,10 @@ DefineRelation(CreateStmt *stmt, char relkind)
 				for (i = 0; i < ncheck; i++)
 				{
 					if (strcmp(check[i].ccname, cdef->name) == 0)
-						elog(ERROR, "Duplicate CHECK constraint name: '%s'",
-							 cdef->name);
+						ereport(ERROR,
+								(errcode(ERRCODE_DUPLICATE_OBJECT),
+								 errmsg("duplicate CHECK constraint name \"%s\"",
+										cdef->name)));
 				}
 				check[ncheck].ccname = cdef->name;
 			}
@@ -373,33 +375,29 @@ TruncateRelation(const RangeVar *relation)
 
 	/* Only allow truncate on regular tables */
 	if (rel->rd_rel->relkind != RELKIND_RELATION)
-	{
-		/* special errors for backwards compatibility */
-		if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
-			elog(ERROR, "TRUNCATE cannot be used on sequences. '%s' is a sequence",
-				 RelationGetRelationName(rel));
-		if (rel->rd_rel->relkind == RELKIND_VIEW)
-			elog(ERROR, "TRUNCATE cannot be used on views. '%s' is a view",
-				 RelationGetRelationName(rel));
-		/* else a generic error message will do */
-		elog(ERROR, "TRUNCATE can only be used on tables. '%s' is not a table",
-			 RelationGetRelationName(rel));
-	}
+		ereport(ERROR,
+				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+				 errmsg("\"%s\" is not a table",
+						RelationGetRelationName(rel))));
 
 	/* Permissions checks */
-	if (!allowSystemTableMods && IsSystemRelation(rel))
-		elog(ERROR, "TRUNCATE cannot be used on system tables. '%s' is a system table",
-			 RelationGetRelationName(rel));
-
 	if (!pg_class_ownercheck(relid, GetUserId()))
 		aclcheck_error(ACLCHECK_NOT_OWNER, RelationGetRelationName(rel));
 
+	if (!allowSystemTableMods && IsSystemRelation(rel))
+		ereport(ERROR,
+				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+				 errmsg("\"%s\" is a system catalog",
+						RelationGetRelationName(rel))));
+
 	/*
 	 * Don't allow truncate on temp tables of other backends ... their
 	 * local buffer manager is not going to cope.
 	 */
 	if (isOtherTempNamespace(RelationGetNamespace(rel)))
-		elog(ERROR, "TRUNCATE cannot be used on temp tables of other processes");
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("cannot truncate temp tables of other processes")));
 
 	/*
 	 * Don't allow truncate on tables which are referenced by foreign keys
@@ -423,9 +421,12 @@ TruncateRelation(const RangeVar *relation)
 		Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
 
 		if (con->contype == 'f' && con->conrelid != relid)
-			elog(ERROR, "TRUNCATE cannot be used as table %s references this one via foreign key constraint %s",
-				 get_rel_name(con->conrelid),
-				 NameStr(con->conname));
+			ereport(ERROR,
+					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+					 errmsg("cannot truncate a table referenced in a foreign key constraint"),
+					 errdetail("Table \"%s\" references this one via foreign key constraint \"%s\".",
+							   get_rel_name(con->conrelid),
+							   NameStr(con->conname))));
 	}
 
 	systable_endscan(fkeyScan);
@@ -534,8 +535,10 @@ MergeAttributes(List *schema, List *supers, bool istemp,
 			ColumnDef  *restdef = lfirst(rest);
 
 			if (strcmp(coldef->colname, restdef->colname) == 0)
-				elog(ERROR, "CREATE TABLE: attribute \"%s\" duplicated",
-					 coldef->colname);
+				ereport(ERROR,
+						(errcode(ERRCODE_DUPLICATE_COLUMN),
+						 errmsg("attribute \"%s\" duplicated",
+								coldef->colname)));
 		}
 	}
 
@@ -557,12 +560,16 @@ MergeAttributes(List *schema, List *supers, bool istemp,
 		relation = heap_openrv(parent, AccessShareLock);
 
 		if (relation->rd_rel->relkind != RELKIND_RELATION)
-			elog(ERROR, "CREATE TABLE: inherited relation \"%s\" is not a table",
-				 parent->relname);
+			ereport(ERROR,
+					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+					 errmsg("inherited relation \"%s\" is not a table",
+							parent->relname)));
 		/* Permanent rels cannot inherit from temporary ones */
 		if (!istemp && isTempNamespace(RelationGetNamespace(relation)))
-			elog(ERROR, "CREATE TABLE: cannot inherit from temp relation \"%s\"",
-				 parent->relname);
+			ereport(ERROR,
+					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+					 errmsg("cannot inherit from temporary relation \"%s\"",
+							parent->relname)));
 
 		/*
 		 * We should have an UNDER permission flag for this, but for now,
@@ -576,8 +583,10 @@ MergeAttributes(List *schema, List *supers, bool istemp,
 		 * Reject duplications in the list of parents.
 		 */
 		if (oidMember(RelationGetRelid(relation), parentOids))
-			elog(ERROR, "CREATE TABLE: inherited relation \"%s\" duplicated",
-				 parent->relname);
+			ereport(ERROR,
+					(errcode(ERRCODE_DUPLICATE_TABLE),
+					 errmsg("inherited relation \"%s\" duplicated",
+							parent->relname)));
 
 		parentOids = lappendo(parentOids, RelationGetRelid(relation));
 		setRelhassubclassInRelation(RelationGetRelid(relation), true);
@@ -629,15 +638,19 @@ MergeAttributes(List *schema, List *supers, bool istemp,
 				 * Yes, try to merge the two column definitions. They must
 				 * have the same type and typmod.
 				 */
-				elog(NOTICE, "CREATE TABLE: merging multiple inherited definitions of attribute \"%s\"",
-					 attributeName);
+				ereport(NOTICE,
+						(errmsg("merging multiple inherited definitions of attribute \"%s\"",
+								attributeName)));
 				def = (ColumnDef *) nth(exist_attno - 1, inhSchema);
 				if (typenameTypeId(def->typename) != attribute->atttypid ||
 					def->typename->typmod != attribute->atttypmod)
-					elog(ERROR, "CREATE TABLE: inherited attribute \"%s\" type conflict (%s and %s)",
-						 attributeName,
-						 TypeNameToString(def->typename),
-						 format_type_be(attribute->atttypid));
+					ereport(ERROR,
+							(errcode(ERRCODE_DATATYPE_MISMATCH),
+							 errmsg("inherited attribute \"%s\" has a type conflict",
+									attributeName),
+							 errdetail("%s versus %s",
+									   TypeNameToString(def->typename),
+									   format_type_be(attribute->atttypid))));
 				def->inhcount++;
 				/* Merge of NOT NULL constraints = OR 'em together */
 				def->is_not_null |= attribute->attnotnull;
@@ -780,15 +793,19 @@ MergeAttributes(List *schema, List *supers, bool istemp,
 				 * Yes, try to merge the two column definitions. They must
 				 * have the same type and typmod.
 				 */
-				elog(NOTICE, "CREATE TABLE: merging attribute \"%s\" with inherited definition",
-					 attributeName);
+				ereport(NOTICE,
+						(errmsg("merging attribute \"%s\" with inherited definition",
+								attributeName)));
 				def = (ColumnDef *) nth(exist_attno - 1, inhSchema);
 				if (typenameTypeId(def->typename) != typenameTypeId(newdef->typename) ||
 					def->typename->typmod != newdef->typename->typmod)
-					elog(ERROR, "CREATE TABLE: attribute \"%s\" type conflict (%s and %s)",
-						 attributeName,
-						 TypeNameToString(def->typename),
-						 TypeNameToString(newdef->typename));
+					ereport(ERROR,
+							(errcode(ERRCODE_DATATYPE_MISMATCH),
+							 errmsg("attribute \"%s\" has a type conflict",
+									attributeName),
+							 errdetail("%s versus %s",
+									   TypeNameToString(def->typename),
+									   TypeNameToString(newdef->typename))));
 				/* Mark the column as locally defined */
 				def->is_local = true;
 				/* Merge of NOT NULL constraints = OR 'em together */
@@ -823,9 +840,11 @@ MergeAttributes(List *schema, List *supers, bool istemp,
 			ColumnDef  *def = lfirst(entry);
 
 			if (def->cooked_default == bogus_marker)
-				elog(ERROR, "CREATE TABLE: attribute \"%s\" inherits conflicting default values"
-					 "\n\tTo resolve the conflict, specify a default explicitly",
-					 def->colname);
+				ereport(ERROR,
+						(errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
+						 errmsg("attribute \"%s\" inherits conflicting default values",
+								def->colname),
+						 errhint("To resolve the conflict, specify a default explicitly.")));
 		}
 	}
 
@@ -1065,7 +1084,7 @@ setRelhassubclassInRelation(Oid relationId, bool relhassubclass)
 							   ObjectIdGetDatum(relationId),
 							   0, 0, 0);
 	if (!HeapTupleIsValid(tuple))
-		elog(ERROR, "setRelhassubclassInRelation: cache lookup failed for relation %u", relationId);
+		elog(ERROR, "cache lookup failed for relation %u", relationId);
 
 	((Form_pg_class) GETSTRUCT(tuple))->relhassubclass = relhassubclass;
 	simple_heap_update(relationRelation, &tuple->t_self, tuple);
@@ -1119,13 +1138,14 @@ renameatt(Oid myrelid,
 	 *
 	 * normally, only the owner of a class can change its schema.
 	 */
-	if (!allowSystemTableMods
-		&& IsSystemRelation(targetrelation))
-		elog(ERROR, "renameatt: class \"%s\" is a system catalog",
-			 RelationGetRelationName(targetrelation));
 	if (!pg_class_ownercheck(myrelid, GetUserId()))
 		aclcheck_error(ACLCHECK_NOT_OWNER,
 					   RelationGetRelationName(targetrelation));
+	if (!allowSystemTableMods && IsSystemRelation(targetrelation))
+		ereport(ERROR,
+				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+				 errmsg("\"%s\" is a system catalog",
+						RelationGetRelationName(targetrelation))));
 
 	/*
 	 * if the 'recurse' flag is set then we are supposed to rename this
@@ -1167,30 +1187,38 @@ renameatt(Oid myrelid,
 		 */
 		if (!recursing &&
 			find_inheritance_children(myrelid) != NIL)
-			elog(ERROR, "Inherited attribute \"%s\" must be renamed in child tables too",
-				 oldattname);
+			ereport(ERROR,
+					(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
+					 errmsg("inherited attribute \"%s\" must be renamed in child tables too",
+							oldattname)));
 	}
 
 	attrelation = heap_openr(AttributeRelationName, RowExclusiveLock);
 
 	atttup = SearchSysCacheCopyAttName(myrelid, oldattname);
 	if (!HeapTupleIsValid(atttup))
-		elog(ERROR, "renameatt: attribute \"%s\" does not exist",
-			 oldattname);
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_COLUMN),
+				 errmsg("attribute \"%s\" does not exist",
+						oldattname)));
 	attform = (Form_pg_attribute) GETSTRUCT(atttup);
 
 	attnum = attform->attnum;
 	if (attnum < 0)
-		elog(ERROR, "renameatt: system attribute \"%s\" may not be renamed",
-			 oldattname);
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("cannot rename system attribute \"%s\"",
+						oldattname)));
 
 	/*
 	 * if the attribute is inherited, forbid the renaming, unless we are
 	 * already inside a recursive rename.
 	 */
 	if (attform->attinhcount > 0 && !recursing)
-		elog(ERROR, "renameatt: inherited attribute \"%s\" may not be renamed",
-			 oldattname);
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
+				 errmsg("cannot rename inherited attribute \"%s\"",
+						oldattname)));
 
 	/* should not already exist */
 	/* this test is deliberately not attisdropped-aware */
@@ -1198,7 +1226,10 @@ renameatt(Oid myrelid,
 							 ObjectIdGetDatum(myrelid),
 							 PointerGetDatum(newattname),
 							 0, 0))
-		elog(ERROR, "renameatt: attribute \"%s\" exists", newattname);
+		ereport(ERROR,
+				(errcode(ERRCODE_DUPLICATE_COLUMN),
+				 errmsg("attribute \"%s\" of relation \"%s\" already exists",
+						newattname, RelationGetRelationName(targetrelation))));
 
 	namestrcpy(&(attform->attname), newattname);
 
@@ -1230,7 +1261,7 @@ renameatt(Oid myrelid,
 								  ObjectIdGetDatum(indexoid),
 								  0, 0, 0);
 		if (!HeapTupleIsValid(indextup))
-			elog(ERROR, "renameatt: can't find index id %u", indexoid);
+			elog(ERROR, "cache lookup failed for index %u", indexoid);
 		indexform = (Form_pg_index) GETSTRUCT(indextup);
 
 		for (i = 0; i < indexform->indnatts; i++)
@@ -1315,11 +1346,11 @@ renamerel(Oid myrelid, const char *newrelname)
 	oldrelname = pstrdup(RelationGetRelationName(targetrelation));
 	namespaceId = RelationGetNamespace(targetrelation);
 
-	/* Validity checks */
-	if (!allowSystemTableMods &&
-		IsSystemRelation(targetrelation))
-		elog(ERROR, "renamerel: system relation \"%s\" may not be renamed",
-			 oldrelname);
+	if (!allowSystemTableMods && IsSystemRelation(targetrelation))
+		ereport(ERROR,
+				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+				 errmsg("\"%s\" is a system catalog",
+						RelationGetRelationName(targetrelation))));
 
 	relkind = targetrelation->rd_rel->relkind;
 	relhastriggers = (targetrelation->rd_rel->reltriggers > 0);
@@ -1333,12 +1364,14 @@ renamerel(Oid myrelid, const char *newrelname)
 	reltup = SearchSysCacheCopy(RELOID,
 								PointerGetDatum(myrelid),
 								0, 0, 0);
-	if (!HeapTupleIsValid(reltup))
-		elog(ERROR, "renamerel: relation \"%s\" does not exist",
-			 oldrelname);
+	if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
+		elog(ERROR, "cache lookup failed for relation %u", myrelid);
 
 	if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
-		elog(ERROR, "renamerel: relation \"%s\" exists", newrelname);
+		ereport(ERROR,
+				(errcode(ERRCODE_DUPLICATE_TABLE),
+				 errmsg("relation \"%s\" already exists",
+						newrelname)));
 
 	/*
 	 * Update pg_class tuple with new relname.	(Scribbling on reltup is
@@ -1351,8 +1384,8 @@ renamerel(Oid myrelid, const char *newrelname)
 	/* keep the system catalog indexes current */
 	CatalogUpdateIndexes(relrelation, reltup);
 
-	heap_close(relrelation, NoLock);
 	heap_freetuple(reltup);
+	heap_close(relrelation, RowExclusiveLock);
 
 	/*
 	 * Also rename the associated type, if any.
@@ -1636,8 +1669,10 @@ AlterTableAddColumn(Oid myrelid,
 	rel = heap_open(myrelid, AccessExclusiveLock);
 
 	if (rel->rd_rel->relkind != RELKIND_RELATION)
-		elog(ERROR, "ALTER TABLE: relation \"%s\" is not a table",
-			 RelationGetRelationName(rel));
+		ereport(ERROR,
+				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+				 errmsg("\"%s\" is not a table",
+						RelationGetRelationName(rel))));
 
 	/*
 	 * permissions checking.  this would normally be done in utility.c,
@@ -1645,13 +1680,15 @@ AlterTableAddColumn(Oid myrelid,
 	 *
 	 * normally, only the owner of a class can change its schema.
 	 */
-	if (!allowSystemTableMods
-		&& IsSystemRelation(rel))
-		elog(ERROR, "ALTER TABLE: relation \"%s\" is a system catalog",
-			 RelationGetRelationName(rel));
 	if (!pg_class_ownercheck(myrelid, GetUserId()))
 		aclcheck_error(ACLCHECK_NOT_OWNER, RelationGetRelationName(rel));
 
+	if (!allowSystemTableMods && IsSystemRelation(rel))
+		ereport(ERROR,
+				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+				 errmsg("\"%s\" is a system catalog",
+						RelationGetRelationName(rel))));
+
 	/*
 	 * Recurse to add the column to child classes, if requested.
 	 *
@@ -1700,16 +1737,18 @@ AlterTableAddColumn(Oid myrelid,
 			/* Okay if child matches by type */
 			if (typenameTypeId(colDef->typename) != childatt->atttypid ||
 				colDef->typename->typmod != childatt->atttypmod)
-				elog(ERROR, "ALTER TABLE: child table \"%s\" has different type for column \"%s\"",
-					 get_rel_name(childrelid), colDef->colname);
+				ereport(ERROR,
+						(errcode(ERRCODE_DATATYPE_MISMATCH),
+						 errmsg("child table \"%s\" has different type for column \"%s\"",
+								get_rel_name(childrelid), colDef->colname)));
 
 			/*
 			 * XXX if we supported NOT NULL or defaults, would need to do
 			 * more work here to verify child matches
 			 */
-
-			elog(NOTICE, "ALTER TABLE: merging definition of column \"%s\" for child %s",
-				 colDef->colname, get_rel_name(childrelid));
+			ereport(NOTICE,
+					(errmsg("merging definition of column \"%s\" for child \"%s\"",
+							colDef->colname, get_rel_name(childrelid))));
 
 			/* Bump the existing child att's inhcount */
 			childatt->attinhcount++;
@@ -1738,7 +1777,9 @@ AlterTableAddColumn(Oid myrelid,
 		 * child tables; else the addition would put them out of step.
 		 */
 		if (find_inheritance_children(myrelid) != NIL)
-			elog(ERROR, "Attribute must be added to child tables too");
+			ereport(ERROR,
+					(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
+					 errmsg("attribute must be added to child tables too")));
 	}
 
 	/*
@@ -1755,12 +1796,16 @@ AlterTableAddColumn(Oid myrelid,
 	 * fail for NULL rows (eg, CHECK (newcol IS NOT NULL)).
 	 */
 	if (colDef->raw_default || colDef->cooked_default)
-		elog(ERROR, "Adding columns with defaults is not implemented."
-			 "\n\tAdd the column, then use ALTER TABLE SET DEFAULT.");
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("adding columns with defaults is not implemented"),
+				 errhint("Add the column, then use ALTER TABLE SET DEFAULT.")));
 
 	if (colDef->is_not_null)
-		elog(ERROR, "Adding NOT NULL columns is not implemented."
-		   "\n\tAdd the column, then use ALTER TABLE ... SET NOT NULL.");
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("adding NOT NULL columns is not implemented"),
+				 errhint("Add the column, then use ALTER TABLE SET NOT NULL.")));
 
 	pgclass = heap_openr(RelationRelationName, RowExclusiveLock);
 
@@ -1768,8 +1813,7 @@ AlterTableAddColumn(Oid myrelid,
 							ObjectIdGetDatum(myrelid),
 							0, 0, 0);
 	if (!HeapTupleIsValid(reltup))
-		elog(ERROR, "ALTER TABLE: relation \"%s\" not found",
-			 RelationGetRelationName(rel));
+		elog(ERROR, "cache lookup failed for relation %u", myrelid);
 
 	/*
 	 * this test is deliberately not attisdropped-aware, since if one
@@ -1780,14 +1824,18 @@ AlterTableAddColumn(Oid myrelid,
 							 ObjectIdGetDatum(myrelid),
 							 PointerGetDatum(colDef->colname),
 							 0, 0))
-		elog(ERROR, "ALTER TABLE: column name \"%s\" already exists in table \"%s\"",
-			 colDef->colname, RelationGetRelationName(rel));
+		ereport(ERROR,
+				(errcode(ERRCODE_DUPLICATE_COLUMN),
+				 errmsg("attribute \"%s\" of relation \"%s\" already exists",
+						colDef->colname, RelationGetRelationName(rel))));
 
 	minattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts;
 	maxatts = minattnum + 1;
 	if (maxatts > MaxHeapAttributeNumber)
-		elog(ERROR, "ALTER TABLE: relations limited to %d columns",
-			 MaxHeapAttributeNumber);
+		ereport(ERROR,
+				(errcode(ERRCODE_TOO_MANY_COLUMNS),
+				 errmsg("tables can have at most %d columns",
+						MaxHeapAttributeNumber)));
 	i = minattnum + 1;
 
 	attrdesc = heap_openr(AttributeRelationName, RowExclusiveLock);
@@ -1854,7 +1902,7 @@ AlterTableAddColumn(Oid myrelid,
 	heap_freetuple(newreltup);
 	ReleaseSysCache(reltup);
 
-	heap_close(pgclass, NoLock);
+	heap_close(pgclass, RowExclusiveLock);
 
 	heap_close(rel, NoLock);	/* close rel but keep lock! */
 
@@ -1911,17 +1959,21 @@ AlterTableAlterColumnDropNotNull(Oid myrelid, bool recurse,
 	rel = heap_open(myrelid, AccessExclusiveLock);
 
 	if (rel->rd_rel->relkind != RELKIND_RELATION)
-		elog(ERROR, "ALTER TABLE: relation \"%s\" is not a table",
-			 RelationGetRelationName(rel));
-
-	if (!allowSystemTableMods
-		&& IsSystemRelation(rel))
-		elog(ERROR, "ALTER TABLE: relation \"%s\" is a system catalog",
-			 RelationGetRelationName(rel));
+		ereport(ERROR,
+				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+				 errmsg("\"%s\" is not a table",
+						RelationGetRelationName(rel))));
 
+	/* Permissions checks */
 	if (!pg_class_ownercheck(myrelid, GetUserId()))
 		aclcheck_error(ACLCHECK_NOT_OWNER, RelationGetRelationName(rel));
 
+	if (!allowSystemTableMods && IsSystemRelation(rel))
+		ereport(ERROR,
+				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+				 errmsg("\"%s\" is a system catalog",
+						RelationGetRelationName(rel))));
+
 	/*
 	 * Propagate to children if desired
 	 */
@@ -1956,13 +2008,17 @@ AlterTableAlterColumnDropNotNull(Oid myrelid, bool recurse,
 	 */
 	attnum = get_attnum(myrelid, colName);
 	if (attnum == InvalidAttrNumber)
-		elog(ERROR, "Relation \"%s\" has no column \"%s\"",
-			 RelationGetRelationName(rel), colName);
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_COLUMN),
+				 errmsg("attribute \"%s\" of relation \"%s\" does not exist",
+						colName, RelationGetRelationName(rel))));
 
 	/* Prevent them from altering a system attribute */
 	if (attnum < 0)
-		elog(ERROR, "ALTER TABLE: Cannot alter system attribute \"%s\"",
-			 colName);
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("cannot alter system attribute \"%s\"",
+						colName)));
 
 	/*
 	 * Check that the attribute is not in a primary key
@@ -1982,8 +2038,7 @@ AlterTableAlterColumnDropNotNull(Oid myrelid, bool recurse,
 									ObjectIdGetDatum(indexoid),
 									0, 0, 0);
 		if (!HeapTupleIsValid(indexTuple))
-			elog(ERROR, "ALTER TABLE: Index %u not found",
-				 indexoid);
+			elog(ERROR, "cache lookup failed for index %u", indexoid);
 		indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
 
 		/* If the index is not a primary key, skip the check */
@@ -1996,7 +2051,10 @@ AlterTableAlterColumnDropNotNull(Oid myrelid, bool recurse,
 			for (i = 0; i < indexStruct->indnatts; i++)
 			{
 				if (indexStruct->indkey[i] == attnum)
-					elog(ERROR, "ALTER TABLE: Attribute \"%s\" is in a primary key", colName);
+					ereport(ERROR,
+							(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
+							 errmsg("attribute \"%s\" is in a primary key",
+									colName)));
 			}
 		}
 
@@ -2012,8 +2070,8 @@ AlterTableAlterColumnDropNotNull(Oid myrelid, bool recurse,
 
 	tuple = SearchSysCacheCopyAttName(myrelid, colName);
 	if (!HeapTupleIsValid(tuple))		/* shouldn't happen */
-		elog(ERROR, "ALTER TABLE: relation \"%s\" has no column \"%s\"",
-			 RelationGetRelationName(rel), colName);
+		elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
+			 colName, myrelid);
 
 	((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = FALSE;
 
@@ -2044,17 +2102,21 @@ AlterTableAlterColumnSetNotNull(Oid myrelid, bool recurse,
 	rel = heap_open(myrelid, AccessExclusiveLock);
 
 	if (rel->rd_rel->relkind != RELKIND_RELATION)
-		elog(ERROR, "ALTER TABLE: relation \"%s\" is not a table",
-			 RelationGetRelationName(rel));
-
-	if (!allowSystemTableMods
-		&& IsSystemRelation(rel))
-		elog(ERROR, "ALTER TABLE: relation \"%s\" is a system catalog",
-			 RelationGetRelationName(rel));
+		ereport(ERROR,
+				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+				 errmsg("\"%s\" is not a table",
+						RelationGetRelationName(rel))));
 
+	/* Permissions checks */
 	if (!pg_class_ownercheck(myrelid, GetUserId()))
 		aclcheck_error(ACLCHECK_NOT_OWNER, RelationGetRelationName(rel));
 
+	if (!allowSystemTableMods && IsSystemRelation(rel))
+		ereport(ERROR,
+				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+				 errmsg("\"%s\" is a system catalog",
+						RelationGetRelationName(rel))));
+
 	/*
 	 * Propagate to children if desired
 	 */
@@ -2089,13 +2151,17 @@ AlterTableAlterColumnSetNotNull(Oid myrelid, bool recurse,
 	 */
 	attnum = get_attnum(myrelid, colName);
 	if (attnum == InvalidAttrNumber)
-		elog(ERROR, "Relation \"%s\" has no column \"%s\"",
-			 RelationGetRelationName(rel), colName);
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_COLUMN),
+				 errmsg("attribute \"%s\" of relation \"%s\" does not exist",
+						colName, RelationGetRelationName(rel))));
 
 	/* Prevent them from altering a system attribute */
 	if (attnum < 0)
-		elog(ERROR, "ALTER TABLE: Cannot alter system attribute \"%s\"",
-			 colName);
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("cannot alter system attribute \"%s\"",
+						colName)));
 
 	/*
 	 * Perform a scan to ensure that there are no NULL values already in
@@ -2113,8 +2179,10 @@ AlterTableAlterColumnSetNotNull(Oid myrelid, bool recurse,
 		d = heap_getattr(tuple, attnum, tupdesc, &isnull);
 
 		if (isnull)
-			elog(ERROR, "ALTER TABLE: Attribute \"%s\" contains NULL values",
-				 colName);
+			ereport(ERROR,
+					(errcode(ERRCODE_NOT_NULL_VIOLATION),
+					 errmsg("attribute \"%s\" contains NULL values",
+							colName)));
 	}
 
 	heap_endscan(scan);
@@ -2126,8 +2194,8 @@ AlterTableAlterColumnSetNotNull(Oid myrelid, bool recurse,
 
 	tuple = SearchSysCacheCopyAttName(myrelid, colName);
 	if (!HeapTupleIsValid(tuple))		/* shouldn't happen */
-		elog(ERROR, "ALTER TABLE: relation \"%s\" has no column \"%s\"",
-			 RelationGetRelationName(rel), colName);
+		elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
+			 colName, myrelid);
 
 	((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = TRUE;
 
@@ -2161,17 +2229,21 @@ AlterTableAlterColumnDefault(Oid myrelid, bool recurse,
 	 */
 	if (rel->rd_rel->relkind != RELKIND_RELATION &&
 		rel->rd_rel->relkind != RELKIND_VIEW)
-		elog(ERROR, "ALTER TABLE: relation \"%s\" is not a table or view",
-			 RelationGetRelationName(rel));
-
-	if (!allowSystemTableMods
-		&& IsSystemRelation(rel))
-		elog(ERROR, "ALTER TABLE: relation \"%s\" is a system catalog",
-			 RelationGetRelationName(rel));
+		ereport(ERROR,
+				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+				 errmsg("\"%s\" is not a table or view",
+						RelationGetRelationName(rel))));
 
+	/* Permissions checks */
 	if (!pg_class_ownercheck(myrelid, GetUserId()))
 		aclcheck_error(ACLCHECK_NOT_OWNER, RelationGetRelationName(rel));
 
+	if (!allowSystemTableMods && IsSystemRelation(rel))
+		ereport(ERROR,
+				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+				 errmsg("\"%s\" is a system catalog",
+						RelationGetRelationName(rel))));
+
 	/*
 	 * Propagate to children if desired
 	 */
@@ -2206,13 +2278,17 @@ AlterTableAlterColumnDefault(Oid myrelid, bool recurse,
 	 */
 	attnum = get_attnum(myrelid, colName);
 	if (attnum == InvalidAttrNumber)
-		elog(ERROR, "Relation \"%s\" has no column \"%s\"",
-			 RelationGetRelationName(rel), colName);
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_COLUMN),
+				 errmsg("attribute \"%s\" of relation \"%s\" does not exist",
+						colName, RelationGetRelationName(rel))));
 
 	/* Prevent them from altering a system attribute */
 	if (attnum < 0)
-		elog(ERROR, "ALTER TABLE: Cannot alter system attribute \"%s\"",
-			 colName);
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("cannot alter system attribute \"%s\"",
+						colName)));
 
 	/*
 	 * Remove any old default for the column.  We use RESTRICT here for
@@ -2258,18 +2334,23 @@ AlterTableAlterColumnFlags(Oid myrelid, bool recurse,
 	rel = heap_open(myrelid, AccessExclusiveLock);
 
 	if (rel->rd_rel->relkind != RELKIND_RELATION)
-		elog(ERROR, "ALTER TABLE: relation \"%s\" is not a table",
-			 RelationGetRelationName(rel));
+		ereport(ERROR,
+				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+				 errmsg("\"%s\" is not a table",
+						RelationGetRelationName(rel))));
+
+	/* Permissions checks */
+	if (!pg_class_ownercheck(myrelid, GetUserId()))
+		aclcheck_error(ACLCHECK_NOT_OWNER, RelationGetRelationName(rel));
 
 	/*
 	 * we allow statistics case for system tables
 	 */
 	if (*flagType != 'S' && !allowSystemTableMods && IsSystemRelation(rel))
-		elog(ERROR, "ALTER TABLE: relation \"%s\" is a system catalog",
-			 RelationGetRelationName(rel));
-
-	if (!pg_class_ownercheck(myrelid, GetUserId()))
-		aclcheck_error(ACLCHECK_NOT_OWNER, RelationGetRelationName(rel));
+		ereport(ERROR,
+				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+				 errmsg("\"%s\" is a system catalog",
+						RelationGetRelationName(rel))));
 
 	/*
 	 * Check the supplied parameters before anything else
@@ -2285,13 +2366,18 @@ AlterTableAlterColumnFlags(Oid myrelid, bool recurse,
 		 */
 		if (newtarget < -1)
 		{
-			elog(ERROR, "ALTER TABLE: statistics target %d is too low",
-				 newtarget);
+			ereport(ERROR,
+					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+					 errmsg("statistics target %d is too low",
+							newtarget)));
 		}
 		else if (newtarget > 1000)
 		{
-			elog(WARNING, "ALTER TABLE: lowering statistics target to 1000");
 			newtarget = 1000;
+			ereport(WARNING,
+					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+					 errmsg("lowering statistics target to %d",
+							newtarget)));
 		}
 	}
 	else if (*flagType == 'M')
@@ -2311,12 +2397,14 @@ AlterTableAlterColumnFlags(Oid myrelid, bool recurse,
 		else if (strcasecmp(storagemode, "main") == 0)
 			newstorage = 'm';
 		else
-			elog(ERROR, "ALTER TABLE: \"%s\" storage not recognized",
-				 storagemode);
+			ereport(ERROR,
+					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+					 errmsg("invalid storage type \"%s\"",
+							storagemode)));
 	}
 	else
 	{
-		elog(ERROR, "ALTER TABLE: Invalid column flag: %c",
+		elog(ERROR, "unrecognized alter-column type flag: %c",
 			 (int) *flagType);
 	}
 
@@ -2353,13 +2441,17 @@ AlterTableAlterColumnFlags(Oid myrelid, bool recurse,
 
 	tuple = SearchSysCacheCopyAttName(myrelid, colName);
 	if (!HeapTupleIsValid(tuple))
-		elog(ERROR, "ALTER TABLE: relation \"%s\" has no column \"%s\"",
-			 RelationGetRelationName(rel), colName);
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_COLUMN),
+				 errmsg("attribute \"%s\" of relation \"%s\" does not exist",
+						colName, RelationGetRelationName(rel))));
 	attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
 
 	if (attrtuple->attnum < 0)
-		elog(ERROR, "ALTER TABLE: cannot change system attribute \"%s\"",
-			 colName);
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("cannot alter system attribute \"%s\"",
+						colName)));
 
 	/*
 	 * Now change the appropriate field
@@ -2375,8 +2467,10 @@ AlterTableAlterColumnFlags(Oid myrelid, bool recurse,
 		if (newstorage == 'p' || TypeIsToastable(attrtuple->atttypid))
 			attrtuple->attstorage = newstorage;
 		else
-			elog(ERROR, "ALTER TABLE: Column datatype %s can only have storage \"plain\"",
-				 format_type_be(attrtuple->atttypid));
+			ereport(ERROR,
+					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+					 errmsg("column datatype %s can only have storage \"plain\"",
+							format_type_be(attrtuple->atttypid))));
 	}
 
 	simple_heap_update(attrelation, &tuple->t_self, tuple);
@@ -2386,7 +2480,8 @@ AlterTableAlterColumnFlags(Oid myrelid, bool recurse,
 
 	heap_freetuple(tuple);
 
-	heap_close(attrelation, NoLock);
+	heap_close(attrelation, RowExclusiveLock);
+
 	heap_close(rel, NoLock);	/* close rel, but keep lock! */
 }
 
@@ -2404,38 +2499,20 @@ AlterTableAlterOids(Oid myrelid, bool recurse, bool setOid)
 	rel = heap_open(myrelid, AccessExclusiveLock);
 
 	if (rel->rd_rel->relkind != RELKIND_RELATION)
-		elog(ERROR, "ALTER TABLE: relation \"%s\" is not a table",
-			 RelationGetRelationName(rel));
-
-	if (!allowSystemTableMods
-		&& IsSystemRelation(rel))
-		elog(ERROR, "ALTER TABLE: relation \"%s\" is a system catalog",
-			 RelationGetRelationName(rel));
+		ereport(ERROR,
+				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+				 errmsg("\"%s\" is not a table",
+						RelationGetRelationName(rel))));
 
+	/* Permissions checks */
 	if (!pg_class_ownercheck(myrelid, GetUserId()))
 		aclcheck_error(ACLCHECK_NOT_OWNER, RelationGetRelationName(rel));
 
-
-	/* Get its pg_class tuple, too */
-	class_rel = heap_openr(RelationRelationName, RowExclusiveLock);
-
-	tuple = SearchSysCacheCopy(RELOID,
-							   ObjectIdGetDatum(myrelid),
-							   0, 0, 0);
-	if (!HeapTupleIsValid(tuple))
-		elog(ERROR, "ALTER TABLE: relation %u not found", myrelid);
-	tuple_class = (Form_pg_class) GETSTRUCT(tuple);
-
-	/* Can we change the ownership of this tuple? */
-	CheckTupleType(tuple_class);
-
-	/*
-	 * Okay, this is a valid tuple: check it's hasoids flag
-	 * to see if we actually need to change anything
-	 */
-	if (tuple_class->relhasoids == setOid)
-		elog(ERROR, "ALTER TABLE: Table is already %s",
-			 setOid ? "WITH OIDS" : "WITHOUT OIDS");
+	if (!allowSystemTableMods && IsSystemRelation(rel))
+		ereport(ERROR,
+				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+				 errmsg("\"%s\" is a system catalog",
+						RelationGetRelationName(rel))));
 
 	/*
 	 * Propagate to children if desired
@@ -2464,6 +2541,33 @@ AlterTableAlterOids(Oid myrelid, bool recurse, bool setOid)
 		}
 	}
 
+	/* Do the thing on this relation */
+	class_rel = heap_openr(RelationRelationName, RowExclusiveLock);
+
+	tuple = SearchSysCacheCopy(RELOID,
+							   ObjectIdGetDatum(myrelid),
+							   0, 0, 0);
+	if (!HeapTupleIsValid(tuple))
+		elog(ERROR, "cache lookup failed for relation %u", myrelid);
+	tuple_class = (Form_pg_class) GETSTRUCT(tuple);
+
+	/*
+	 * check to see if we actually need to change anything
+	 */
+	if (tuple_class->relhasoids == setOid)
+	{
+		if (setOid)
+			ereport(NOTICE,
+					(errmsg("table \"%s\" is already WITH OIDS",
+							RelationGetRelationName(rel))));
+		else
+			ereport(NOTICE,
+					(errmsg("table \"%s\" is already WITHOUT OIDS",
+							RelationGetRelationName(rel))));
+		heap_close(class_rel, RowExclusiveLock);
+		heap_close(rel, NoLock); /* close rel, but keep lock! */
+		return;
+	}
 
 	tuple_class->relhasoids = setOid;
 	simple_heap_update(class_rel, &tuple->t_self, tuple);
@@ -2471,13 +2575,15 @@ AlterTableAlterOids(Oid myrelid, bool recurse, bool setOid)
 	/* Keep the catalog indexes up to date */
 	CatalogUpdateIndexes(class_rel, tuple);
 
-
-
 	if (setOid)
+	{
 		/*
 		 * TODO: Generate the now required OID pg_attribute entry
 		 */
-		elog(ERROR, "ALTER TABLE WITH OIDS is unsupported");
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("ALTER TABLE WITH OIDS is not yet implemented")));
+	}
 	else
 	{
 		HeapTuple	atttup;
@@ -2492,19 +2598,22 @@ AlterTableAlterOids(Oid myrelid, bool recurse, bool setOid)
 		 */
 		atttup = SearchSysCache(ATTNUM,
 								ObjectIdGetDatum(myrelid),
-								ObjectIdAttributeNumber, 0, 0);
+								Int16GetDatum(ObjectIdAttributeNumber),
+								0, 0);
 		if (!HeapTupleIsValid(atttup))
-			elog(ERROR, "ALTER TABLE: relation %u doesn't have an Oid column to remove", myrelid);
+			elog(ERROR, "cache lookup failed for attribute %d of relation %u",
+				 ObjectIdAttributeNumber, myrelid);
 
 		simple_heap_delete(attrel, &atttup->t_self);
 
 		ReleaseSysCache(atttup);
 
-		heap_close(attrel, NoLock);		/* close rel, but keep lock! */
+		heap_close(attrel, RowExclusiveLock);
 	}
 
+	heap_close(class_rel, RowExclusiveLock);
+
 	heap_close(rel, NoLock);		/* close rel, but keep lock! */
-	heap_close(class_rel, NoLock);	/* close rel, but keep lock! */
 }
 
 /*
@@ -2523,36 +2632,46 @@ AlterTableDropColumn(Oid myrelid, bool recurse, bool recursing,
 	rel = heap_open(myrelid, AccessExclusiveLock);
 
 	if (rel->rd_rel->relkind != RELKIND_RELATION)
-		elog(ERROR, "ALTER TABLE: relation \"%s\" is not a table",
-			 RelationGetRelationName(rel));
-
-	if (!allowSystemTableMods
-		&& IsSystemRelation(rel))
-		elog(ERROR, "ALTER TABLE: relation \"%s\" is a system catalog",
-			 RelationGetRelationName(rel));
+		ereport(ERROR,
+				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+				 errmsg("\"%s\" is not a table",
+						RelationGetRelationName(rel))));
 
+	/* Permissions checks */
 	if (!pg_class_ownercheck(myrelid, GetUserId()))
 		aclcheck_error(ACLCHECK_NOT_OWNER, RelationGetRelationName(rel));
 
+	if (!allowSystemTableMods && IsSystemRelation(rel))
+		ereport(ERROR,
+				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+				 errmsg("\"%s\" is a system catalog",
+						RelationGetRelationName(rel))));
+
 	/*
 	 * get the number of the attribute
 	 */
 	attnum = get_attnum(myrelid, colName);
 	if (attnum == InvalidAttrNumber)
-		elog(ERROR, "Relation \"%s\" has no column \"%s\"",
-			 RelationGetRelationName(rel), colName);
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_COLUMN),
+				 errmsg("attribute \"%s\" of relation \"%s\" does not exist",
+						colName, RelationGetRelationName(rel))));
 
 	/* Can't drop a system attribute */
 	/* XXX perhaps someday allow dropping OID? */
 	if (attnum < 0)
-		elog(ERROR, "ALTER TABLE: Cannot drop system attribute \"%s\"",
-			 colName);
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("cannot drop system attribute \"%s\"",
+						colName)));
 
 	/* Don't drop inherited columns */
 	tupleDesc = RelationGetDescr(rel);
 	if (tupleDesc->attrs[attnum - 1]->attinhcount > 0 && !recursing)
-		elog(ERROR, "ALTER TABLE: Cannot drop inherited column \"%s\"",
-			 colName);
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
+				 errmsg("cannot drop inherited attribute \"%s\"",
+						colName)));
 
 	/*
 	 * If we are asked to drop ONLY in this table (no recursion), we need
@@ -2580,12 +2699,12 @@ AlterTableDropColumn(Oid myrelid, bool recurse, bool recursing,
 
 			tuple = SearchSysCacheCopyAttName(childrelid, colName);
 			if (!HeapTupleIsValid(tuple))		/* shouldn't happen */
-				elog(ERROR, "ALTER TABLE: relation %u has no column \"%s\"",
-					 childrelid, colName);
+				elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
+					 colName, childrelid);
 			childatt = (Form_pg_attribute) GETSTRUCT(tuple);
 
-			if (childatt->attinhcount <= 0)
-				elog(ERROR, "ALTER TABLE: relation %u has non-inherited column \"%s\"",
+			if (childatt->attinhcount <= 0)	/* shouldn't happen */
+				elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
 					 childrelid, colName);
 			childatt->attinhcount--;
 			childatt->attislocal = true;
@@ -2631,12 +2750,12 @@ AlterTableDropColumn(Oid myrelid, bool recurse, bool recursing,
 
 			tuple = SearchSysCacheCopyAttName(childrelid, colName);
 			if (!HeapTupleIsValid(tuple))		/* shouldn't happen */
-				elog(ERROR, "ALTER TABLE: relation %u has no column \"%s\"",
-					 childrelid, colName);
+				elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
+					 colName, childrelid);
 			childatt = (Form_pg_attribute) GETSTRUCT(tuple);
 
-			if (childatt->attinhcount <= 0)
-				elog(ERROR, "ALTER TABLE: relation %u has non-inherited column \"%s\"",
+			if (childatt->attinhcount <= 0)	/* shouldn't happen */
+				elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
 					 childrelid, colName);
 
 			if (childatt->attinhcount == 1 && !childatt->attislocal)
@@ -2693,17 +2812,21 @@ AlterTableAddConstraint(Oid myrelid, bool recurse,
 	rel = heap_open(myrelid, AccessExclusiveLock);
 
 	if (rel->rd_rel->relkind != RELKIND_RELATION)
-		elog(ERROR, "ALTER TABLE: relation \"%s\" is not a table",
-			 RelationGetRelationName(rel));
-
-	if (!allowSystemTableMods
-		&& IsSystemRelation(rel))
-		elog(ERROR, "ALTER TABLE: relation \"%s\" is a system catalog",
-			 RelationGetRelationName(rel));
+		ereport(ERROR,
+				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+				 errmsg("\"%s\" is not a table",
+						RelationGetRelationName(rel))));
 
+	/* Permissions checks */
 	if (!pg_class_ownercheck(myrelid, GetUserId()))
 		aclcheck_error(ACLCHECK_NOT_OWNER, RelationGetRelationName(rel));
 
+	if (!allowSystemTableMods && IsSystemRelation(rel))
+		ereport(ERROR,
+				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+				 errmsg("\"%s\" is a system catalog",
+						RelationGetRelationName(rel))));
+
 	if (recurse)
 	{
 		List	   *child,
@@ -2751,8 +2874,11 @@ AlterTableAddConstraint(Oid myrelid, bool recurse,
 												 RelationGetRelid(rel),
 												 RelationGetNamespace(rel),
 												 constr->name))
-							elog(ERROR, "constraint \"%s\" already exists for relation \"%s\"",
-								 constr->name, RelationGetRelationName(rel));
+							ereport(ERROR,
+									(errcode(ERRCODE_DUPLICATE_OBJECT),
+									 errmsg("constraint \"%s\" for relation \"%s\" already exists",
+											constr->name,
+											RelationGetRelationName(rel))));
 					}
 					else
 						constr->name = GenerateConstraintName(CONSTRAINT_RELATION,
@@ -2772,7 +2898,8 @@ AlterTableAddConstraint(Oid myrelid, bool recurse,
 							AlterTableAddCheckConstraint(rel, constr);
 							break;
 						default:
-							elog(ERROR, "ALTER TABLE / ADD CONSTRAINT is not implemented for that constraint type.");
+							elog(ERROR, "unrecognized constraint type: %d",
+								 (int) constr->contype);
 					}
 					break;
 				}
@@ -2789,9 +2916,11 @@ AlterTableAddConstraint(Oid myrelid, bool recurse,
 												   RelationGetRelid(rel),
 											   RelationGetNamespace(rel),
 											  fkconstraint->constr_name))
-							elog(ERROR, "constraint \"%s\" already exists for relation \"%s\"",
-								 fkconstraint->constr_name,
-								 RelationGetRelationName(rel));
+							ereport(ERROR,
+									(errcode(ERRCODE_DUPLICATE_OBJECT),
+									 errmsg("constraint \"%s\" for relation \"%s\" already exists",
+											fkconstraint->constr_name,
+											RelationGetRelationName(rel))));
 					}
 					else
 						fkconstraint->constr_name = GenerateConstraintName(CONSTRAINT_RELATION,
@@ -2804,7 +2933,8 @@ AlterTableAddConstraint(Oid myrelid, bool recurse,
 					break;
 				}
 			default:
-				elog(ERROR, "ALTER TABLE / ADD CONSTRAINT unable to determine type of constraint passed");
+				elog(ERROR, "unrecognized node type: %d",
+					 (int) nodeTag(newConstraint));
 		}
 
 		/* If we have multiple constraints to make, bump CC between 'em */
@@ -2864,16 +2994,22 @@ AlterTableAddCheckConstraint(Relation rel, Constraint *constr)
 	 * Make sure no outside relations are referred to.
 	 */
 	if (length(pstate->p_rtable) != 1)
-		elog(ERROR, "Only relation '%s' can be referenced in CHECK",
-			 RelationGetRelationName(rel));
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
+				 errmsg("CHECK constraint may only reference relation \"%s\"",
+						RelationGetRelationName(rel))));
 
 	/*
 	 * No subplans or aggregates, either...
 	 */
 	if (pstate->p_hasSubLinks)
-		elog(ERROR, "cannot use subselect in CHECK constraint expression");
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("cannot use sub-select in CHECK constraint")));
 	if (pstate->p_hasAggs)
-		elog(ERROR, "cannot use aggregate function in CHECK constraint expression");
+		ereport(ERROR,
+				(errcode(ERRCODE_GROUPING_ERROR),
+				 errmsg("cannot use aggregate in CHECK constraint")));
 
 	/*
 	 * Might as well try to reduce any constant expressions, so as to
@@ -2922,8 +3058,10 @@ AlterTableAddCheckConstraint(Relation rel, Constraint *constr)
 	FreeExecutorState(estate);
 
 	if (!successful)
-		elog(ERROR, "AlterTableAddConstraint: rejected due to CHECK constraint %s",
-			 constr->name);
+		ereport(ERROR,
+				(errcode(ERRCODE_CHECK_VIOLATION),
+				 errmsg("CHECK constraint \"%s\" is violated at some row(s)",
+						constr->name)));
 
 	/*
 	 * Call AddRelationRawConstraints to do
@@ -2945,7 +3083,6 @@ AlterTableAddCheckConstraint(Relation rel, Constraint *constr)
 static void
 AlterTableAddForeignKeyConstraint(Relation rel, FkConstraint *fkconstraint)
 {
-	const char *stmtname;
 	Relation	pkrel;
 	AclResult	aclresult;
 	int16		pkattnum[INDEX_MAX_KEYS];
@@ -2958,9 +3095,6 @@ AlterTableAddForeignKeyConstraint(Relation rel, FkConstraint *fkconstraint)
 	Oid			indexOid;
 	Oid			constrOid;
 
-	/* cheat a little to discover statement type for error messages */
-	stmtname = fkconstraint->skip_validation ? "CREATE TABLE" : "ALTER TABLE";
-
 	/*
 	 * Grab an exclusive lock on the pk table, so that
 	 * someone doesn't delete rows out from under us.
@@ -2978,19 +3112,22 @@ AlterTableAddForeignKeyConstraint(Relation rel, FkConstraint *fkconstraint)
 	 * but we may as well error out sooner instead of later.
 	 */
 	if (pkrel->rd_rel->relkind != RELKIND_RELATION)
-		elog(ERROR, "referenced relation \"%s\" is not a table",
-			 RelationGetRelationName(pkrel));
-
-	if (!allowSystemTableMods
-		&& IsSystemRelation(pkrel))
-		elog(ERROR, "%s: relation \"%s\" is a system catalog",
-			 stmtname, RelationGetRelationName(pkrel));
+		ereport(ERROR,
+				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+				 errmsg("referenced relation \"%s\" is not a table",
+						RelationGetRelationName(pkrel))));
 
 	aclresult = pg_class_aclcheck(RelationGetRelid(pkrel), GetUserId(),
 								  ACL_REFERENCES);
 	if (aclresult != ACLCHECK_OK)
 		aclcheck_error(aclresult, RelationGetRelationName(pkrel));
 
+	if (!allowSystemTableMods && IsSystemRelation(pkrel))
+		ereport(ERROR,
+				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+				 errmsg("\"%s\" is a system catalog",
+						RelationGetRelationName(pkrel))));
+
 	aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
 								  ACL_REFERENCES);
 	if (aclresult != ACLCHECK_OK)
@@ -2998,8 +3135,9 @@ AlterTableAddForeignKeyConstraint(Relation rel, FkConstraint *fkconstraint)
 
 	if (isTempNamespace(RelationGetNamespace(pkrel)) &&
 		!isTempNamespace(RelationGetNamespace(rel)))
-		elog(ERROR, "%s: Unable to reference temporary table from permanent table constraint",
-			 stmtname);
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
+				 errmsg("cannot reference temporary table from permanent table constraint")));
 
 	/*
 	 * Look up the referencing attributes to make sure they
@@ -3013,7 +3151,6 @@ AlterTableAddForeignKeyConstraint(Relation rel, FkConstraint *fkconstraint)
 
 	numfks = transformColumnNameList(RelationGetRelid(rel),
 									 fkconstraint->fk_attrs,
-									 stmtname,
 									 fkattnum, fktypoid);
 
 	/*
@@ -3032,7 +3169,6 @@ AlterTableAddForeignKeyConstraint(Relation rel, FkConstraint *fkconstraint)
 	{
 		numpks = transformColumnNameList(RelationGetRelid(pkrel),
 										 fkconstraint->pk_attrs,
-										 stmtname,
 										 pkattnum, pktypoid);
 		/* Look for an index matching the column list */
 		indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum);
@@ -3040,8 +3176,9 @@ AlterTableAddForeignKeyConstraint(Relation rel, FkConstraint *fkconstraint)
 
 	/* Be sure referencing and referenced column types are comparable */
 	if (numfks != numpks)
-		elog(ERROR, "%s: number of referencing and referenced attributes for foreign key disagree",
-			 stmtname);
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_FOREIGN_KEY),
+				 errmsg("number of referencing and referenced attributes for foreign key disagree")));
 
 	for (i = 0; i < numpks; i++)
 	{
@@ -3049,7 +3186,7 @@ AlterTableAddForeignKeyConstraint(Relation rel, FkConstraint *fkconstraint)
 		 * fktypoid[i] is the foreign key table's i'th element's type
 		 * pktypoid[i] is the primary key table's i'th element's type
 		 *
-		 * We let oper() do our work for us, including elog(ERROR) if the
+		 * We let oper() do our work for us, including ereport(ERROR) if the
 		 * types don't compare with =
 		 */
 		Operator	o = oper(makeList1(makeString("=")),
@@ -3107,7 +3244,6 @@ AlterTableAddForeignKeyConstraint(Relation rel, FkConstraint *fkconstraint)
  */
 static int
 transformColumnNameList(Oid relId, List *colList,
-						const char *stmtname,
 						int16 *attnums, Oid *atttypids)
 {
 	List	   *l;
@@ -3121,11 +3257,15 @@ transformColumnNameList(Oid relId, List *colList,
 
 		atttuple = SearchSysCacheAttName(relId, attname);
 		if (!HeapTupleIsValid(atttuple))
-			elog(ERROR, "%s: column \"%s\" referenced in foreign key constraint does not exist",
-				 stmtname, attname);
+			ereport(ERROR,
+					(errcode(ERRCODE_UNDEFINED_COLUMN),
+					 errmsg("column \"%s\" referenced in foreign key constraint does not exist",
+							attname)));
 		if (attnum >= INDEX_MAX_KEYS)
-			elog(ERROR, "Can only have %d keys in a foreign key",
-				 INDEX_MAX_KEYS);
+			ereport(ERROR,
+					(errcode(ERRCODE_TOO_MANY_COLUMNS),
+					 errmsg("cannot have more than %d keys in a foreign key",
+							INDEX_MAX_KEYS)));
 		attnums[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->attnum;
 		atttypids[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->atttypid;
 		ReleaseSysCache(atttuple);
@@ -3168,8 +3308,7 @@ transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
 									ObjectIdGetDatum(indexoid),
 									0, 0, 0);
 		if (!HeapTupleIsValid(indexTuple))
-			elog(ERROR, "transformFkeyGetPrimaryKey: index %u not found",
-				 indexoid);
+			elog(ERROR, "cache lookup failed for index %u", indexoid);
 		indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
 		if (indexStruct->indisprimary)
 		{
@@ -3186,8 +3325,10 @@ transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
 	 * Check that we found it
 	 */
 	if (indexStruct == NULL)
-		elog(ERROR, "PRIMARY KEY for referenced table \"%s\" not found",
-			 RelationGetRelationName(pkrel));
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_OBJECT),
+				 errmsg("there is no PRIMARY KEY for referenced table \"%s\"",
+						RelationGetRelationName(pkrel))));
 
 	/*
 	 * Now build the list of PK attributes from the indkey definition
@@ -3243,8 +3384,7 @@ transformFkeyCheckAttrs(Relation pkrel,
 									ObjectIdGetDatum(indexoid),
 									0, 0, 0);
 		if (!HeapTupleIsValid(indexTuple))
-			elog(ERROR, "transformFkeyCheckAttrs: index %u not found",
-				 indexoid);
+			elog(ERROR, "cache lookup failed for index %u", indexoid);
 		indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
 
 		/*
@@ -3298,8 +3438,10 @@ transformFkeyCheckAttrs(Relation pkrel,
 	}
 
 	if (!found)
-		elog(ERROR, "UNIQUE constraint matching given keys for referenced table \"%s\" not found",
-			 RelationGetRelationName(pkrel));
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_FOREIGN_KEY),
+				 errmsg("there is no UNIQUE constraint matching given keys for referenced table \"%s\"",
+			 RelationGetRelationName(pkrel))));
 
 	freeList(indexoidlist);
 
@@ -3326,7 +3468,7 @@ validateForeignKeyConstraint(FkConstraint *fkconstraint,
 	/*
 	 * Scan through each tuple, calling RI_FKey_check_ins (insert trigger)
 	 * as if that tuple had just been inserted.  If any of those fail, it
-	 * should elog(ERROR) and that's that.
+	 * should ereport(ERROR) and that's that.
 	 */
 	MemSet(&trig, 0, sizeof(trig));
 	trig.tgoid = InvalidOid;
@@ -3461,9 +3603,9 @@ createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
 	fk_attr = fkconstraint->fk_attrs;
 	pk_attr = fkconstraint->pk_attrs;
 	if (length(fk_attr) != length(pk_attr))
-		elog(ERROR, "number of key attributes in referenced table must be equal to foreign key"
-			 "\n\tIllegal FOREIGN KEY definition references \"%s\"",
-			 fkconstraint->pktable->relname);
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_FOREIGN_KEY),
+				 errmsg("number of referencing and referenced attributes for foreign key disagree")));
 
 	while (fk_attr != NIL)
 	{
@@ -3517,7 +3659,8 @@ createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
 			fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
 			break;
 		default:
-			elog(ERROR, "Unrecognized ON DELETE action for FOREIGN KEY constraint");
+			elog(ERROR, "unrecognized FK action type: %d",
+				 (int) fkconstraint->fk_del_action);
 			break;
 	}
 
@@ -3583,7 +3726,8 @@ createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
 			fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
 			break;
 		default:
-			elog(ERROR, "Unrecognized ON UPDATE action for FOREIGN KEY constraint");
+			elog(ERROR, "unrecognized FK action type: %d",
+				 (int) fkconstraint->fk_upd_action);
 			break;
 	}
 
@@ -3628,8 +3772,8 @@ fkMatchTypeToString(char match_type)
 		case FKCONSTR_MATCH_UNSPECIFIED:
 			return pstrdup("UNSPECIFIED");
 		default:
-			elog(ERROR, "fkMatchTypeToString: Unknown MATCH TYPE '%c'",
-				 match_type);
+			elog(ERROR, "unrecognized match type: %d",
+				 (int) match_type);
 	}
 	return NULL;				/* can't get here */
 }
@@ -3653,17 +3797,21 @@ AlterTableDropConstraint(Oid myrelid, bool recurse,
 
 	/* Disallow DROP CONSTRAINT on views, indexes, sequences, etc */
 	if (rel->rd_rel->relkind != RELKIND_RELATION)
-		elog(ERROR, "ALTER TABLE: relation \"%s\" is not a table",
-			 RelationGetRelationName(rel));
-
-	if (!allowSystemTableMods
-		&& IsSystemRelation(rel))
-		elog(ERROR, "ALTER TABLE: relation \"%s\" is a system catalog",
-			 RelationGetRelationName(rel));
+		ereport(ERROR,
+				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+				 errmsg("\"%s\" is not a table",
+						RelationGetRelationName(rel))));
 
+	/* Permissions checks */
 	if (!pg_class_ownercheck(myrelid, GetUserId()))
 		aclcheck_error(ACLCHECK_NOT_OWNER, RelationGetRelationName(rel));
 
+	if (!allowSystemTableMods && IsSystemRelation(rel))
+		ereport(ERROR,
+				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+				 errmsg("\"%s\" is a system catalog",
+						RelationGetRelationName(rel))));
+
 	/*
 	 * Process child tables if requested.
 	 */
@@ -3704,11 +3852,15 @@ AlterTableDropConstraint(Oid myrelid, bool recurse,
 
 	/* If zero constraints deleted, complain */
 	if (deleted == 0)
-		elog(ERROR, "ALTER TABLE / DROP CONSTRAINT: %s does not exist",
-			 constrName);
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_OBJECT),
+				 errmsg("constraint \"%s\" does not exist",
+						constrName)));
 	/* Otherwise if more than one constraint deleted, notify */
 	else if (deleted > 1)
-		elog(NOTICE, "Multiple constraints dropped");
+		ereport(NOTICE,
+				(errmsg("multiple constraints named \"%s\" were dropped",
+						constrName)));
 }
 
 /*
@@ -3733,11 +3885,25 @@ AlterTableOwner(Oid relationOid, int32 newOwnerSysId)
 							   ObjectIdGetDatum(relationOid),
 							   0, 0, 0);
 	if (!HeapTupleIsValid(tuple))
-		elog(ERROR, "ALTER TABLE: relation %u not found", relationOid);
+		elog(ERROR, "cache lookup failed for relation %u", relationOid);
 	tuple_class = (Form_pg_class) GETSTRUCT(tuple);
 
 	/* Can we change the ownership of this tuple? */
-	CheckTupleType(tuple_class);
+	switch (tuple_class->relkind)
+	{
+		case RELKIND_RELATION:
+		case RELKIND_INDEX:
+		case RELKIND_VIEW:
+		case RELKIND_SEQUENCE:
+		case RELKIND_TOASTVALUE:
+			/* ok to change owner */
+			break;
+		default:
+			ereport(ERROR,
+					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+					 errmsg("\"%s\" is not a table, TOAST table, index, view, or sequence",
+							NameStr(tuple_class->relname))));
+	}
 
 	/*
 	 * Okay, this is a valid tuple: change its ownership and write to the
@@ -3782,24 +3948,6 @@ AlterTableOwner(Oid relationOid, int32 newOwnerSysId)
 	relation_close(target_rel, NoLock);
 }
 
-static void
-CheckTupleType(Form_pg_class tuple_class)
-{
-	switch (tuple_class->relkind)
-	{
-		case RELKIND_RELATION:
-		case RELKIND_INDEX:
-		case RELKIND_VIEW:
-		case RELKIND_SEQUENCE:
-		case RELKIND_TOASTVALUE:
-			/* ok to change owner */
-			break;
-		default:
-			elog(ERROR, "ALTER TABLE: relation \"%s\" is not a table, TOAST table, index, view, or sequence",
-				 NameStr(tuple_class->relname));
-	}
-}
-
 /*
  * ALTER TABLE CLUSTER ON
  *
@@ -3820,16 +3968,16 @@ AlterTableClusterOn(Oid relOid, const char *indexName)
 	indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
 	
 	if (!OidIsValid(indexOid))
-		elog(ERROR, "ALTER TABLE: cannot find index \"%s\" for table \"%s\"",
-				indexName, NameStr(rel->rd_rel->relname));
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_OBJECT),
+				 errmsg("index \"%s\" for table \"%s\" does not exist",
+						indexName, NameStr(rel->rd_rel->relname))));
 
 	indexTuple = SearchSysCache(INDEXRELID,
 								ObjectIdGetDatum(indexOid),
 								0, 0, 0);
-
 	if (!HeapTupleIsValid(indexTuple))
-		elog(ERROR, "Cache lookup failed for index %u",
-				indexOid);
+		elog(ERROR, "cache lookup failed for index %u", indexOid);
 	indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
 
 	/*
@@ -3838,10 +3986,11 @@ AlterTableClusterOn(Oid relOid, const char *indexName)
 	 */
 	if (indexForm->indisclustered)
 	{
-		elog(NOTICE, "ALTER TABLE: table \"%s\" is already being clustered on index \"%s\"",
-				NameStr(rel->rd_rel->relname), indexName);
+		ereport(NOTICE,
+				(errmsg("table \"%s\" is already being clustered on index \"%s\"",
+						NameStr(rel->rd_rel->relname), indexName)));
 		ReleaseSysCache(indexTuple);
-		heap_close(rel, AccessExclusiveLock);
+		heap_close(rel, NoLock);
 		return;
 	}
 
@@ -3860,7 +4009,7 @@ AlterTableClusterOn(Oid relOid, const char *indexName)
 		  							  ObjectIdGetDatum(indexOid),
 									  0, 0, 0);
 		if (!HeapTupleIsValid(idxtuple))
-			elog(ERROR, "Cache lookup failed for index %u", indexOid);
+			elog(ERROR, "cache lookup failed for index %u", indexOid);
 		idxForm = (Form_pg_index) GETSTRUCT(idxtuple);
 		/*
 		 * Unset the bit if set.  We know it's wrong because we checked
@@ -3880,9 +4029,12 @@ AlterTableClusterOn(Oid relOid, const char *indexName)
 		}
 		heap_freetuple(idxtuple);
 	}
-	ReleaseSysCache(indexTuple);
-	heap_close(rel, AccessExclusiveLock);
+
 	heap_close(pg_index, RowExclusiveLock);
+
+	ReleaseSysCache(indexTuple);
+
+	heap_close(rel, NoLock);	/* close rel, but keep lock till commit */
 }
 
 /*
@@ -3911,11 +4063,13 @@ AlterTableCreateToastTable(Oid relOid, bool silent)
 	 */
 	rel = heap_open(relOid, AccessExclusiveLock);
 
-	/* Check permissions */
 	if (rel->rd_rel->relkind != RELKIND_RELATION)
-		elog(ERROR, "ALTER TABLE: relation \"%s\" is not a table",
-			 RelationGetRelationName(rel));
+		ereport(ERROR,
+				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+				 errmsg("\"%s\" is not a table",
+						RelationGetRelationName(rel))));
 
+	/* Permissions checks */
 	if (!pg_class_ownercheck(relOid, GetUserId()))
 		aclcheck_error(ACLCHECK_NOT_OWNER, RelationGetRelationName(rel));
 
@@ -3930,7 +4084,9 @@ AlterTableCreateToastTable(Oid relOid, bool silent)
 	 */
 	shared_relation = rel->rd_rel->relisshared;
 	if (shared_relation && IsUnderPostmaster)
-		elog(ERROR, "Shared relations cannot be toasted after initdb");
+		ereport(ERROR,
+				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+				 errmsg("shared relations cannot be toasted after initdb")));
 
 	/*
 	 * Is it already toasted?
@@ -3943,8 +4099,10 @@ AlterTableCreateToastTable(Oid relOid, bool silent)
 			return;
 		}
 
-		elog(ERROR, "ALTER TABLE: relation \"%s\" already has a toast table",
-			 RelationGetRelationName(rel));
+		ereport(ERROR,
+				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+				 errmsg("relation \"%s\" already has a toast table",
+						RelationGetRelationName(rel))));
 	}
 
 	/*
@@ -3958,15 +4116,19 @@ AlterTableCreateToastTable(Oid relOid, bool silent)
 			return;
 		}
 
-		elog(ERROR, "ALTER TABLE: relation \"%s\" does not need a toast table",
-			 RelationGetRelationName(rel));
+		ereport(ERROR,
+				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+				 errmsg("relation \"%s\" does not need a toast table",
+						RelationGetRelationName(rel))));
 	}
 
 	/*
 	 * Create the toast table and its index
 	 */
-	snprintf(toast_relname, sizeof(toast_relname), "pg_toast_%u", relOid);
-	snprintf(toast_idxname, sizeof(toast_idxname), "pg_toast_%u_index", relOid);
+	snprintf(toast_relname, sizeof(toast_relname),
+			 "pg_toast_%u", relOid);
+	snprintf(toast_idxname, sizeof(toast_idxname),
+			 "pg_toast_%u_index", relOid);
 
 	/* this is pretty painful...  need a tuple descriptor */
 	tupdesc = CreateTemplateTupleDesc(3, false);
@@ -4055,8 +4217,7 @@ AlterTableCreateToastTable(Oid relOid, bool silent)
 								ObjectIdGetDatum(relOid),
 								0, 0, 0);
 	if (!HeapTupleIsValid(reltup))
-		elog(ERROR, "ALTER TABLE: relation \"%s\" not found",
-			 RelationGetRelationName(rel));
+		elog(ERROR, "cache lookup failed for relation %u", relOid);
 
 	((Form_pg_class) GETSTRUCT(reltup))->reltoastrelid = toast_relid;
 
diff --git a/src/backend/commands/trigger.c b/src/backend/commands/trigger.c
index 8e8d61d77b8d3ff36dfe9a19ad823cf45b5294a5..ca594f635708dfdbf313b4ffecb9ea8eb69339c2 100644
--- a/src/backend/commands/trigger.c
+++ b/src/backend/commands/trigger.c
@@ -7,7 +7,7 @@
  * Portions Copyright (c) 1994, Regents of the University of California
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/commands/trigger.c,v 1.150 2003/07/04 02:51:33 tgl Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/commands/trigger.c,v 1.151 2003/07/20 21:56:32 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -131,17 +131,23 @@ CreateTrigger(CreateTrigStmt *stmt, bool forConstraint)
 			constrrelid = RangeVarGetRelid(rel, true);
 		}
 		if (needconstrrelid && constrrelid == InvalidOid)
-			elog(NOTICE, "Unable to find table for constraint \"%s\"",
-				 stmt->trigname);
+			ereport(NOTICE,
+					(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
+					 errmsg("unable to determine referenced table for constraint \"%s\"",
+							stmt->trigname)));
 	}
 
 	if (rel->rd_rel->relkind != RELKIND_RELATION)
-		elog(ERROR, "CreateTrigger: relation \"%s\" is not a table",
-			 stmt->relation->relname);
+		ereport(ERROR,
+				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+				 errmsg("\"%s\" is not a table",
+						RelationGetRelationName(rel))));
 
 	if (!allowSystemTableMods && IsSystemRelation(rel))
-		elog(ERROR, "CreateTrigger: can't create trigger for system relation %s",
-			 stmt->relation->relname);
+		ereport(ERROR,
+				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+				 errmsg("\"%s\" is a system catalog",
+						RelationGetRelationName(rel))));
 
 	/* permission checks */
 
@@ -207,21 +213,28 @@ CreateTrigger(CreateTrigStmt *stmt, bool forConstraint)
 		{
 			case 'i':
 				if (TRIGGER_FOR_INSERT(tgtype))
-					elog(ERROR, "CreateTrigger: double INSERT event specified");
+					ereport(ERROR,
+							(errcode(ERRCODE_SYNTAX_ERROR),
+							 errmsg("double INSERT event specified")));
 				TRIGGER_SETT_INSERT(tgtype);
 				break;
 			case 'd':
 				if (TRIGGER_FOR_DELETE(tgtype))
-					elog(ERROR, "CreateTrigger: double DELETE event specified");
+					ereport(ERROR,
+							(errcode(ERRCODE_SYNTAX_ERROR),
+							 errmsg("double DELETE event specified")));
 				TRIGGER_SETT_DELETE(tgtype);
 				break;
 			case 'u':
 				if (TRIGGER_FOR_UPDATE(tgtype))
-					elog(ERROR, "CreateTrigger: double UPDATE event specified");
+					ereport(ERROR,
+							(errcode(ERRCODE_SYNTAX_ERROR),
+							 errmsg("double UPDATE event specified")));
 				TRIGGER_SETT_UPDATE(tgtype);
 				break;
 			default:
-				elog(ERROR, "CreateTrigger: unknown event specified");
+				elog(ERROR, "unknown trigger event: %d",
+					 (int) stmt->actions[i]);
 				break;
 		}
 	}
@@ -247,8 +260,10 @@ CreateTrigger(CreateTrigStmt *stmt, bool forConstraint)
 		Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(tuple);
 
 		if (namestrcmp(&(pg_trigger->tgname), trigname) == 0)
-			elog(ERROR, "CreateTrigger: trigger %s already defined on relation %s",
-				 trigname, stmt->relation->relname);
+			ereport(ERROR,
+					(errcode(ERRCODE_DUPLICATE_OBJECT),
+					 errmsg("trigger \"%s\" for relation \"%s\" already exists",
+							trigname, stmt->relation->relname)));
 		found++;
 	}
 	systable_endscan(tgscan);
@@ -267,13 +282,16 @@ CreateTrigger(CreateTrigStmt *stmt, bool forConstraint)
 		 */
 		if (funcrettype == OPAQUEOID)
 		{
-			elog(NOTICE, "CreateTrigger: changing return type of function %s() from OPAQUE to TRIGGER",
-				 NameListToString(stmt->funcname));
+			ereport(NOTICE,
+					(errmsg("changing return type of function %s() from OPAQUE to TRIGGER",
+							NameListToString(stmt->funcname))));
 			SetFunctionReturnType(funcoid, TRIGGEROID);
 		}
 		else
-			elog(ERROR, "CreateTrigger: function %s() must return TRIGGER",
-				 NameListToString(stmt->funcname));
+			ereport(ERROR,
+					(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
+					 errmsg("function %s() must return TRIGGER",
+							NameListToString(stmt->funcname))));
 	}
 
 	/*
@@ -372,8 +390,8 @@ CreateTrigger(CreateTrigStmt *stmt, bool forConstraint)
 							   ObjectIdGetDatum(RelationGetRelid(rel)),
 							   0, 0, 0);
 	if (!HeapTupleIsValid(tuple))
-		elog(ERROR, "CreateTrigger: relation %s not found in pg_class",
-			 stmt->relation->relname);
+		elog(ERROR, "cache lookup failed for relation %u",
+			 RelationGetRelid(rel));
 
 	((Form_pg_class) GETSTRUCT(tuple))->reltriggers = found + 1;
 
@@ -457,8 +475,10 @@ DropTrigger(Oid relid, const char *trigname, DropBehavior behavior)
 	tup = systable_getnext(tgscan);
 
 	if (!HeapTupleIsValid(tup))
-		elog(ERROR, "DropTrigger: there is no trigger %s on relation %s",
-			 trigname, get_rel_name(relid));
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_OBJECT),
+				 errmsg("trigger \"%s\" on relation \"%s\" does not exist",
+						trigname, get_rel_name(relid))));
 
 	if (!pg_class_ownercheck(relid, GetUserId()))
 		aclcheck_error(ACLCHECK_NOT_OWNER, get_rel_name(relid));
@@ -506,8 +526,7 @@ RemoveTriggerById(Oid trigOid)
 
 	tup = systable_getnext(tgscan);
 	if (!HeapTupleIsValid(tup))
-		elog(ERROR, "RemoveTriggerById: Trigger %u does not exist",
-			 trigOid);
+		elog(ERROR, "could not find tuple for trigger %u", trigOid);
 
 	/*
 	 * Open and exclusive-lock the relation the trigger belongs to.
@@ -517,12 +536,16 @@ RemoveTriggerById(Oid trigOid)
 	rel = heap_open(relid, AccessExclusiveLock);
 
 	if (rel->rd_rel->relkind != RELKIND_RELATION)
-		elog(ERROR, "DropTrigger: relation \"%s\" is not a table",
-			 RelationGetRelationName(rel));
+		ereport(ERROR,
+				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+				 errmsg("\"%s\" is not a table",
+						RelationGetRelationName(rel))));
 
 	if (!allowSystemTableMods && IsSystemRelation(rel))
-		elog(ERROR, "DropTrigger: can't drop trigger for system relation %s",
-			 RelationGetRelationName(rel));
+		ereport(ERROR,
+				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+				 errmsg("\"%s\" is a system catalog",
+						RelationGetRelationName(rel))));
 
 	/*
 	 * Delete the pg_trigger tuple.
@@ -546,12 +569,11 @@ RemoveTriggerById(Oid trigOid)
 							   ObjectIdGetDatum(relid),
 							   0, 0, 0);
 	if (!HeapTupleIsValid(tuple))
-		elog(ERROR, "DropTrigger: relation %s not found in pg_class",
-			 RelationGetRelationName(rel));
+		elog(ERROR, "cache lookup failed for relation %u", relid);
 	classForm = (Form_pg_class) GETSTRUCT(tuple);
 
-	if (classForm->reltriggers == 0)
-		elog(ERROR, "DropTrigger: relation %s has reltriggers = 0",
+	if (classForm->reltriggers == 0) /* should not happen */
+		elog(ERROR, "relation \"%s\" has reltriggers = 0",
 			 RelationGetRelationName(rel));
 	classForm->reltriggers--;
 
@@ -622,8 +644,10 @@ renametrig(Oid relid,
 	tgscan = systable_beginscan(tgrel, TriggerRelidNameIndex, true,
 								SnapshotNow, 2, key);
 	if (HeapTupleIsValid(tuple = systable_getnext(tgscan)))
-		elog(ERROR, "renametrig: trigger %s already defined on relation %s",
-			 newname, RelationGetRelationName(targetrel));
+		ereport(ERROR,
+				(errcode(ERRCODE_DUPLICATE_OBJECT),
+				 errmsg("trigger \"%s\" for relation \"%s\" already exists",
+						newname, RelationGetRelationName(targetrel))));
 	systable_endscan(tgscan);
 
 	/*
@@ -663,8 +687,10 @@ renametrig(Oid relid,
 	}
 	else
 	{
-		elog(ERROR, "renametrig: trigger %s not defined on relation %s",
-			 oldname, RelationGetRelationName(targetrel));
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_OBJECT),
+				 errmsg("trigger \"%s\" for relation \"%s\" does not exist",
+						oldname, RelationGetRelationName(targetrel))));
 	}
 
 	systable_endscan(tgscan);
@@ -726,7 +752,7 @@ RelationBuildTriggers(Relation relation)
 		Trigger    *build;
 
 		if (found >= ntrigs)
-			elog(ERROR, "RelationBuildTriggers: unexpected record found for rel %s",
+			elog(ERROR, "too many trigger records found for relation \"%s\"",
 				 RelationGetRelationName(relation));
 		build = &(triggers[found]);
 
@@ -754,7 +780,7 @@ RelationBuildTriggers(Relation relation)
 										Anum_pg_trigger_tgargs,
 										tgrel->rd_att, &isnull);
 			if (isnull)
-				elog(ERROR, "RelationBuildTriggers: tgargs IS NULL for rel %s",
+				elog(ERROR, "tgargs is null in trigger for relation \"%s\"",
 					 RelationGetRelationName(relation));
 			p = (char *) VARDATA(val);
 			build->tgargs = (char **) palloc(build->tgnargs * sizeof(char *));
@@ -774,7 +800,7 @@ RelationBuildTriggers(Relation relation)
 	heap_close(tgrel, AccessShareLock);
 
 	if (found != ntrigs)
-		elog(ERROR, "RelationBuildTriggers: %d record(s) not found for rel %s",
+		elog(ERROR, "%d trigger record(s) not found for relation \"%s\"",
 			 ntrigs - found,
 			 RelationGetRelationName(relation));
 
@@ -1125,8 +1151,10 @@ ExecCallTriggerFunc(TriggerData *trigdata,
 	 * to set the isnull result flag.
 	 */
 	if (fcinfo.isnull)
-		elog(ERROR, "ExecCallTriggerFunc: function %u returned NULL",
-			 fcinfo.flinfo->fn_oid);
+		ereport(ERROR,
+				(errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
+				 errmsg("trigger function %u returned NULL",
+						fcinfo.flinfo->fn_oid)));
 
 	return (HeapTuple) DatumGetPointer(result);
 }
@@ -1175,7 +1203,9 @@ ExecBSInsertTriggers(EState *estate, ResultRelInfo *relinfo)
 									   GetPerTupleMemoryContext(estate));
 
 		if (newtuple)
-			elog(ERROR, "BEFORE STATEMENT trigger cannot return a value.");
+			ereport(ERROR,
+					(errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
+					 errmsg("BEFORE STATEMENT trigger cannot return a value")));
 	}
 }
 
@@ -1286,7 +1316,9 @@ ExecBSDeleteTriggers(EState *estate, ResultRelInfo *relinfo)
 									   GetPerTupleMemoryContext(estate));
 
 		if (newtuple)
-			elog(ERROR, "BEFORE STATEMENT trigger cannot return a value.");
+			ereport(ERROR,
+					(errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
+					 errmsg("BEFORE STATEMENT trigger cannot return a value")));
 	}
 }
 
@@ -1413,7 +1445,9 @@ ExecBSUpdateTriggers(EState *estate, ResultRelInfo *relinfo)
 									   GetPerTupleMemoryContext(estate));
 
 		if (newtuple)
-			elog(ERROR, "BEFORE STATEMENT trigger cannot return a value.");
+			ereport(ERROR,
+					(errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
+					 errmsg("BEFORE STATEMENT trigger cannot return a value")));
 	}
 }
 
@@ -1538,7 +1572,9 @@ ltrmark:;
 			case HeapTupleUpdated:
 				ReleaseBuffer(buffer);
 				if (XactIsoLevel == XACT_SERIALIZABLE)
-					elog(ERROR, "Can't serialize access due to concurrent update");
+					ereport(ERROR,
+							(errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
+							 errmsg("cannot serialize access due to concurrent update")));
 				else if (!(ItemPointerEquals(&(tuple.t_self), tid)))
 				{
 					TupleTableSlot *epqslot = EvalPlanQual(estate,
@@ -1561,8 +1597,9 @@ ltrmark:;
 
 			default:
 				ReleaseBuffer(buffer);
-				elog(ERROR, "Unknown status %u from heap_mark4update", test);
-				return NULL;
+				elog(ERROR, "unrecognized status %u from heap_mark4update",
+					 test);
+				return NULL;	/* keep compiler quiet */
 		}
 	}
 	else
@@ -1573,7 +1610,7 @@ ltrmark:;
 		buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
 
 		if (!BufferIsValid(buffer))
-			elog(ERROR, "GetTupleForTrigger: failed ReadBuffer");
+			elog(ERROR, "ReadBuffer failed");
 
 		dp = (PageHeader) BufferGetPage(buffer);
 		lp = PageGetItemId(dp, ItemPointerGetOffsetNumber(tid));
@@ -1761,14 +1798,14 @@ DeferredTriggerExecute(DeferredTriggerEvent event, int itemno,
 	{
 		ItemPointerCopy(&(event->dte_oldctid), &(oldtuple.t_self));
 		if (!heap_fetch(rel, SnapshotAny, &oldtuple, &oldbuffer, false, NULL))
-			elog(ERROR, "DeferredTriggerExecute: failed to fetch old tuple");
+			elog(ERROR, "failed to fetch old tuple for deferred trigger");
 	}
 
 	if (ItemPointerIsValid(&(event->dte_newctid)))
 	{
 		ItemPointerCopy(&(event->dte_newctid), &(newtuple.t_self));
 		if (!heap_fetch(rel, SnapshotAny, &newtuple, &newbuffer, false, NULL))
-			elog(ERROR, "DeferredTriggerExecute: failed to fetch new tuple");
+			elog(ERROR, "failed to fetch new tuple for deferred trigger");
 	}
 
 	/*
@@ -1789,7 +1826,7 @@ DeferredTriggerExecute(DeferredTriggerEvent event, int itemno,
 		}
 	}
 	if (LocTriggerData.tg_trigger == NULL)
-		elog(ERROR, "DeferredTriggerExecute: can't find trigger %u", tgoid);
+		elog(ERROR, "could not find trigger %u", tgoid);
 
 	switch (event->dte_event & TRIGGER_EVENT_OPMASK)
 	{
@@ -1948,8 +1985,8 @@ deferredTriggerInvokeEvents(bool immediate_only)
 					 */
 					trigdesc = CopyTriggerDesc(rel->trigdesc);
 
-					if (trigdesc == NULL)
-						elog(ERROR, "deferredTriggerInvokeEvents: relation %u has no triggers",
+					if (trigdesc == NULL) /* should not happen */
+						elog(ERROR, "relation %u has no triggers",
 							 event->dte_relid);
 
 					/*
@@ -2212,7 +2249,9 @@ DeferredTriggerSetState(ConstraintsSetStmt *stmt)
 			 * Check that only named constraints are set explicitly
 			 */
 			if (strlen(cname) == 0)
-				elog(ERROR, "unnamed constraints cannot be set explicitly");
+				ereport(ERROR,
+						(errcode(ERRCODE_INVALID_NAME),
+						 errmsg("unnamed constraints cannot be set explicitly")));
 
 			/*
 			 * Setup to scan pg_trigger by tgconstrname ...
@@ -2243,8 +2282,10 @@ DeferredTriggerSetState(ConstraintsSetStmt *stmt)
 				if (stmt->deferred && !pg_trigger->tgdeferrable &&
 					pg_trigger->tgfoid != F_RI_FKEY_RESTRICT_UPD &&
 					pg_trigger->tgfoid != F_RI_FKEY_RESTRICT_DEL)
-					elog(ERROR, "Constraint '%s' is not deferrable",
-						 cname);
+					ereport(ERROR,
+							(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+							 errmsg("constraint \"%s\" is not deferrable",
+									cname)));
 
 				constr_oid = HeapTupleGetOid(htup);
 				loid = lappendo(loid, constr_oid);
@@ -2257,7 +2298,9 @@ DeferredTriggerSetState(ConstraintsSetStmt *stmt)
 			 * Not found ?
 			 */
 			if (!found)
-				elog(ERROR, "Constraint '%s' does not exist", cname);
+				ereport(ERROR,
+						(errcode(ERRCODE_UNDEFINED_OBJECT),
+						 errmsg("constraint \"%s\" does not exist", cname)));
 		}
 		heap_close(tgrel, AccessShareLock);
 
@@ -2336,8 +2379,7 @@ DeferredTriggerSaveEvent(ResultRelInfo *relinfo, int event, bool row_trigger,
 	ItemPointerData newctid;
 
 	if (deferredTriggers == NULL)
-		elog(ERROR,
-			 "DeferredTriggerSaveEvent() called outside of transaction");
+		elog(ERROR, "DeferredTriggerSaveEvent() called outside of transaction");
 
 	/*
 	 * Get the CTID's of OLD and NEW
diff --git a/src/backend/commands/typecmds.c b/src/backend/commands/typecmds.c
index 94f25fb4be42bc75222af3b697db68363a3accda..9aa7f02bfd8d98f2688998bf4a959ca463c8302c 100644
--- a/src/backend/commands/typecmds.c
+++ b/src/backend/commands/typecmds.c
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/commands/typecmds.c,v 1.38 2003/07/04 02:51:33 tgl Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/commands/typecmds.c,v 1.39 2003/07/20 21:56:33 tgl Exp $
  *
  * DESCRIPTION
  *	  The "DefineFoo" routines take the parse tree and pick out the
@@ -129,8 +129,10 @@ DefineType(List *names, List *parameters)
 	 * "_".
 	 */
 	if (strlen(typeName) > (NAMEDATALEN - 2))
-		elog(ERROR, "DefineType: type names must be %d characters or less",
-			 NAMEDATALEN - 2);
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_NAME),
+				 errmsg("type names must be %d characters or less",
+						NAMEDATALEN - 2)));
 
 	foreach(pl, parameters)
 	{
@@ -159,8 +161,10 @@ DefineType(List *names, List *parameters)
 			elemType = typenameTypeId(defGetTypeName(defel));
 			/* disallow arrays of pseudotypes */
 			if (get_typtype(elemType) == 'p')
-				elog(ERROR, "Array element type cannot be %s",
-					 format_type_be(elemType));
+				ereport(ERROR,
+						(errcode(ERRCODE_DATATYPE_MISMATCH),
+						 errmsg("array element type cannot be %s",
+								format_type_be(elemType))));
 		}
 		else if (strcasecmp(defel->defname, "default") == 0)
 			defaultValue = defGetString(defel);
@@ -190,8 +194,9 @@ DefineType(List *names, List *parameters)
 					 strcasecmp(a, "pg_catalog.bpchar") == 0)
 				alignment = 'c';
 			else
-				elog(ERROR, "DefineType: \"%s\" alignment not recognized",
-					 a);
+				ereport(ERROR,
+						(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+						 errmsg("alignment \"%s\" not recognized", a)));
 		}
 		else if (strcasecmp(defel->defname, "storage") == 0)
 		{
@@ -206,23 +211,28 @@ DefineType(List *names, List *parameters)
 			else if (strcasecmp(a, "main") == 0)
 				storage = 'm';
 			else
-				elog(ERROR, "DefineType: \"%s\" storage not recognized",
-					 a);
+				ereport(ERROR,
+						(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+						 errmsg("storage \"%s\" not recognized", a)));
 		}
 		else
-		{
-			elog(WARNING, "DefineType: attribute \"%s\" not recognized",
-				 defel->defname);
-		}
+			ereport(WARNING,
+					(errcode(ERRCODE_SYNTAX_ERROR),
+					 errmsg("type attribute \"%s\" not recognized",
+							defel->defname)));
 	}
 
 	/*
 	 * make sure we have our required definitions
 	 */
 	if (inputName == NIL)
-		elog(ERROR, "Define: \"input\" unspecified");
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
+				 errmsg("type input function must be specified")));
 	if (outputName == NIL)
-		elog(ERROR, "Define: \"output\" unspecified");
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
+				 errmsg("type output function must be specified")));
 
 	/*
 	 * Look to see if type already exists (presumably as a shell; if not,
@@ -259,40 +269,52 @@ DefineType(List *names, List *parameters)
 	{
 		if (resulttype == OPAQUEOID)
 		{
-			elog(NOTICE, "TypeCreate: changing return type of function %s from OPAQUE to %s",
-				 NameListToString(inputName), typeName);
+			/* backwards-compatibility hack */
+			ereport(NOTICE,
+					(errmsg("changing return type of function %s from OPAQUE to %s",
+							NameListToString(inputName), typeName)));
 			SetFunctionReturnType(inputOid, typoid);
 		}
 		else
-			elog(ERROR, "Type input function %s must return %s",
-				 NameListToString(inputName), typeName);
+			ereport(ERROR,
+					(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
+					 errmsg("type input function %s must return %s",
+							NameListToString(inputName), typeName)));
 	}
 	resulttype = get_func_rettype(outputOid);
 	if (resulttype != CSTRINGOID)
 	{
 		if (resulttype == OPAQUEOID)
 		{
-			elog(NOTICE, "TypeCreate: changing return type of function %s from OPAQUE to CSTRING",
-				 NameListToString(outputName));
+			/* backwards-compatibility hack */
+			ereport(NOTICE,
+					(errmsg("changing return type of function %s from OPAQUE to CSTRING",
+							NameListToString(outputName))));
 			SetFunctionReturnType(outputOid, CSTRINGOID);
 		}
 		else
-			elog(ERROR, "Type output function %s must return cstring",
-				 NameListToString(outputName));
+			ereport(ERROR,
+					(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
+					 errmsg("type output function %s must return cstring",
+							NameListToString(outputName))));
 	}
 	if (receiveOid)
 	{
 		resulttype = get_func_rettype(receiveOid);
 		if (resulttype != typoid)
-			elog(ERROR, "Type receive function %s must return %s",
-				 NameListToString(receiveName), typeName);
+			ereport(ERROR,
+					(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
+					 errmsg("type receive function %s must return %s",
+							NameListToString(receiveName), typeName)));
 	}
 	if (sendOid)
 	{
 		resulttype = get_func_rettype(sendOid);
 		if (resulttype != BYTEAOID)
-			elog(ERROR, "Type send function %s must return bytea",
-				 NameListToString(sendName));
+			ereport(ERROR,
+					(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
+					 errmsg("type send function %s must return bytea",
+							NameListToString(sendName))));
 	}
 
 	/*
@@ -379,15 +401,16 @@ RemoveType(List *names, DropBehavior behavior)
 	/* Use LookupTypeName here so that shell types can be removed. */
 	typeoid = LookupTypeName(typename);
 	if (!OidIsValid(typeoid))
-		elog(ERROR, "Type \"%s\" does not exist",
-			 TypeNameToString(typename));
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_OBJECT),
+				 errmsg("type \"%s\" does not exist",
+						TypeNameToString(typename))));
 
 	tup = SearchSysCache(TYPEOID,
 						 ObjectIdGetDatum(typeoid),
 						 0, 0, 0);
 	if (!HeapTupleIsValid(tup))
-		elog(ERROR, "Type \"%s\" does not exist",
-			 TypeNameToString(typename));
+		elog(ERROR, "cache lookup failed for type %u", typeoid);
 
 	/* Permission check: must own type or its namespace */
 	if (!pg_type_ownercheck(typeoid, GetUserId()) &&
@@ -423,8 +446,7 @@ RemoveTypeById(Oid typeOid)
 						 ObjectIdGetDatum(typeOid),
 						 0, 0, 0);
 	if (!HeapTupleIsValid(tup))
-		elog(ERROR, "RemoveTypeById: type %u not found",
-			 typeOid);
+		elog(ERROR, "cache lookup failed for type %u", typeOid);
 
 	simple_heap_delete(relation, &tup->t_self);
 
@@ -483,11 +505,16 @@ DefineDomain(CreateDomainStmt *stmt)
 
 	/*
 	 * Domainnames, unlike typenames don't need to account for the '_'
-	 * prefix.	So they can be one character longer.
+	 * prefix.	So they can be one character longer.  (This test is presently
+	 * useless since the parser will have truncated the name to fit.  But
+	 * leave it here since we may someday support arrays of domains, in
+	 * which case we'll be back to needing to enforce NAMEDATALEN-2.)
 	 */
 	if (strlen(domainName) > (NAMEDATALEN - 1))
-		elog(ERROR, "CREATE DOMAIN: domain names must be %d characters or less",
-			 NAMEDATALEN - 1);
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_NAME),
+				 errmsg("domain names must be %d characters or less",
+						NAMEDATALEN - 1)));
 
 	/*
 	 * Look up the base type.
@@ -505,8 +532,10 @@ DefineDomain(CreateDomainStmt *stmt)
 	 */
 	typtype = baseType->typtype;
 	if (typtype != 'b')
-		elog(ERROR, "DefineDomain: %s is not a basetype",
-			 TypeNameToString(stmt->typename));
+		ereport(ERROR,
+				(errcode(ERRCODE_DATATYPE_MISMATCH),
+				 errmsg("\"%s\" is not a valid base type for a domain",
+						TypeNameToString(stmt->typename))));
 
 	/* passed by value */
 	byValue = baseType->typbyval;
@@ -555,20 +584,23 @@ DefineDomain(CreateDomainStmt *stmt)
 	foreach(listptr, schema)
 	{
 		Node	   *newConstraint = lfirst(listptr);
-		Constraint *colDef;
+		Constraint *constr;
 		ParseState *pstate;
 
 		/* Check for unsupported constraint types */
 		if (IsA(newConstraint, FkConstraint))
-			elog(ERROR, "CREATE DOMAIN / FOREIGN KEY constraints not supported");
+			ereport(ERROR,
+					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+					 errmsg("FOREIGN KEY constraints not supported for domains")));
 
-		/* this case should not happen */
+		/* otherwise it should be a plain Constraint */
 		if (!IsA(newConstraint, Constraint))
-			elog(ERROR, "DefineDomain: unexpected constraint node type");
+			elog(ERROR, "unrecognized node type: %d",
+				 (int) nodeTag(newConstraint));
 
-		colDef = (Constraint *) newConstraint;
+		constr = (Constraint *) newConstraint;
 
-		switch (colDef->contype)
+		switch (constr->contype)
 		{
 			case CONSTR_DEFAULT:
 				/*
@@ -576,15 +608,18 @@ DefineDomain(CreateDomainStmt *stmt)
 				 * user with the DEFAULT <expr> statement.
 				 */
 				if (defaultExpr)
-					elog(ERROR, "CREATE DOMAIN has multiple DEFAULT expressions");
+					ereport(ERROR,
+							(errcode(ERRCODE_SYNTAX_ERROR),
+							 errmsg("multiple DEFAULT expressions")));
+
 				/* Create a dummy ParseState for transformExpr */
 				pstate = make_parsestate(NULL);
 
 				/*
-				 * Cook the colDef->raw_expr into an expression. Note:
+				 * Cook the constr->raw_expr into an expression. Note:
 				 * Name is strictly for error message
 				 */
-				defaultExpr = cookDefault(pstate, colDef->raw_expr,
+				defaultExpr = cookDefault(pstate, constr->raw_expr,
 										  basetypeoid,
 										  stmt->typename->typmod,
 										  domainName);
@@ -603,14 +638,18 @@ DefineDomain(CreateDomainStmt *stmt)
 
 			case CONSTR_NOTNULL:
 				if (nullDefined && !typNotNull)
-					elog(ERROR, "CREATE DOMAIN has conflicting NULL / NOT NULL constraint");
+					ereport(ERROR,
+							(errcode(ERRCODE_SYNTAX_ERROR),
+							 errmsg("conflicting NULL/NOT NULL constraints")));
 				typNotNull = true;
 				nullDefined = true;
 				break;
 
 			case CONSTR_NULL:
 				if (nullDefined && typNotNull)
-					elog(ERROR, "CREATE DOMAIN has conflicting NULL / NOT NULL constraint");
+					ereport(ERROR,
+							(errcode(ERRCODE_SYNTAX_ERROR),
+							 errmsg("conflicting NULL/NOT NULL constraints")));
 				typNotNull = false;
 				nullDefined = true;
 		  		break;
@@ -626,23 +665,29 @@ DefineDomain(CreateDomainStmt *stmt)
 				 * All else are error cases
 				 */
 		  	case CONSTR_UNIQUE:
-		  		elog(ERROR, "CREATE DOMAIN / UNIQUE not supported");
+		  		ereport(ERROR,
+						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+						 errmsg("UNIQUE constraints not supported for domains")));
 		  		break;
 
 		  	case CONSTR_PRIMARY:
-		  		elog(ERROR, "CREATE DOMAIN / PRIMARY KEY not supported");
+		  		ereport(ERROR,
+						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+						 errmsg("PRIMARY KEY constraints not supported for domains")));
 		  		break;
 
 		  	case CONSTR_ATTR_DEFERRABLE:
 		  	case CONSTR_ATTR_NOT_DEFERRABLE:
 		  	case CONSTR_ATTR_DEFERRED:
 		  	case CONSTR_ATTR_IMMEDIATE:
-		  		elog(ERROR, "CREATE DOMAIN: DEFERRABLE, NON DEFERRABLE, DEFERRED"
-							" and IMMEDIATE not supported");
+		  		ereport(ERROR,
+						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+						 errmsg("deferrability constraints not supported for domains")));
 		  		break;
 
 			default:
-				elog(ERROR, "DefineDomain: unrecognized constraint subtype");
+				elog(ERROR, "unrecognized constraint subtype: %d",
+					 (int) constr->contype);
 				break;
 		}
 	}
@@ -729,15 +774,16 @@ RemoveDomain(List *names, DropBehavior behavior)
 	/* Use LookupTypeName here so that shell types can be removed. */
 	typeoid = LookupTypeName(typename);
 	if (!OidIsValid(typeoid))
-		elog(ERROR, "Type \"%s\" does not exist",
-			 TypeNameToString(typename));
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_OBJECT),
+				 errmsg("type \"%s\" does not exist",
+						TypeNameToString(typename))));
 
 	tup = SearchSysCache(TYPEOID,
 						 ObjectIdGetDatum(typeoid),
 						 0, 0, 0);
 	if (!HeapTupleIsValid(tup))
-		elog(ERROR, "RemoveDomain: type \"%s\" does not exist",
-			 TypeNameToString(typename));
+		elog(ERROR, "cache lookup failed for type %u", typeoid);
 
 	/* Permission check: must own type or its namespace */
 	if (!pg_type_ownercheck(typeoid, GetUserId()) &&
@@ -749,8 +795,10 @@ RemoveDomain(List *names, DropBehavior behavior)
 	typtype = ((Form_pg_type) GETSTRUCT(tup))->typtype;
 
 	if (typtype != 'd')
-		elog(ERROR, "%s is not a domain",
-			 TypeNameToString(typename));
+		ereport(ERROR,
+				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+				 errmsg("\"%s\" is not a domain",
+						TypeNameToString(typename))));
 
 	ReleaseSysCache(tup);
 
@@ -818,9 +866,9 @@ findTypeInputFunction(List *procname, Oid typeOid)
 	if (OidIsValid(procOid))
 	{
 		/* Found, but must complain and fix the pg_proc entry */
-		elog(NOTICE, "TypeCreate: changing argument type of function %s "
-			 "from OPAQUE to CSTRING",
-			 NameListToString(procname));
+		ereport(NOTICE,
+				(errmsg("changing argument type of function %s from OPAQUE to CSTRING",
+						NameListToString(procname))));
 		SetFunctionArgType(procOid, 0, CSTRINGOID);
 		/*
 		 * Need CommandCounterIncrement since DefineType will likely
@@ -834,8 +882,10 @@ findTypeInputFunction(List *procname, Oid typeOid)
 	/* Use CSTRING (preferred) in the error message */
 	argList[0] = CSTRINGOID;
 
-	elog(ERROR, "function %s does not exist",
-		 func_signature_string(procname, 1, argList));
+	ereport(ERROR,
+			(errcode(ERRCODE_UNDEFINED_FUNCTION),
+			 errmsg("function %s does not exist",
+					func_signature_string(procname, 1, argList))));
 
 	return InvalidOid;			/* keep compiler quiet */
 }
@@ -885,8 +935,9 @@ findTypeOutputFunction(List *procname, Oid typeOid)
 	if (OidIsValid(procOid))
 	{
 		/* Found, but must complain and fix the pg_proc entry */
-		elog(NOTICE, "TypeCreate: changing argument type of function %s from OPAQUE to %s",
-			 NameListToString(procname), format_type_be(typeOid));
+		ereport(NOTICE,
+				(errmsg("changing argument type of function %s from OPAQUE to %s",
+						NameListToString(procname), format_type_be(typeOid))));
 		SetFunctionArgType(procOid, 0, typeOid);
 		/*
 		 * Need CommandCounterIncrement since DefineType will likely
@@ -900,8 +951,10 @@ findTypeOutputFunction(List *procname, Oid typeOid)
 	/* Use type name, not OPAQUE, in the failure message. */
 	argList[0] = typeOid;
 
-	elog(ERROR, "function %s does not exist",
-		 func_signature_string(procname, 1, argList));
+	ereport(ERROR,
+			(errcode(ERRCODE_UNDEFINED_FUNCTION),
+			 errmsg("function %s does not exist",
+					func_signature_string(procname, 1, argList))));
 
 	return InvalidOid;			/* keep compiler quiet */
 }
@@ -930,8 +983,10 @@ findTypeReceiveFunction(List *procname, Oid typeOid)
 	if (OidIsValid(procOid))
 		return procOid;
 
-	elog(ERROR, "function %s does not exist",
-		 func_signature_string(procname, 1, argList));
+	ereport(ERROR,
+			(errcode(ERRCODE_UNDEFINED_FUNCTION),
+			 errmsg("function %s does not exist",
+					func_signature_string(procname, 1, argList))));
 
 	return InvalidOid;			/* keep compiler quiet */
 }
@@ -960,8 +1015,10 @@ findTypeSendFunction(List *procname, Oid typeOid)
 	if (OidIsValid(procOid))
 		return procOid;
 
-	elog(ERROR, "function %s does not exist",
-		 func_signature_string(procname, 1, argList));
+	ereport(ERROR,
+			(errcode(ERRCODE_UNDEFINED_FUNCTION),
+			 errmsg("function %s does not exist",
+					func_signature_string(procname, 1, argList))));
 
 	return InvalidOid;			/* keep compiler quiet */
 }
@@ -987,8 +1044,9 @@ DefineCompositeType(const RangeVar *typevar, List *coldeflist)
 	CreateStmt *createStmt = makeNode(CreateStmt);
 
 	if (coldeflist == NIL)
-		elog(ERROR, "attempted to define composite type relation with"
-			 " no attrs");
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
+				 errmsg("composite type must have at least one attribute")));
 
 	/*
 	 * now create the parameters for keys/inheritance etc. All of them are
@@ -1040,16 +1098,16 @@ AlterDomainDefault(List *names, Node *defaultRaw)
 	/* Use LookupTypeName here so that shell types can be removed. */
 	domainoid = LookupTypeName(typename);
 	if (!OidIsValid(domainoid))
-		elog(ERROR, "Type \"%s\" does not exist",
-			 TypeNameToString(typename));
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_OBJECT),
+				 errmsg("type \"%s\" does not exist",
+						TypeNameToString(typename))));
 
 	tup = SearchSysCacheCopy(TYPEOID,
 							 ObjectIdGetDatum(domainoid),
 							 0, 0, 0);
-
 	if (!HeapTupleIsValid(tup))
-		elog(ERROR, "AlterDomain: type \"%s\" does not exist",
-			 TypeNameToString(typename));
+		elog(ERROR, "cache lookup failed for type %u", domainoid);
 
 	/* Doesn't return if user isn't allowed to alter the domain */ 
 	domainOwnerCheck(tup, typename);
@@ -1157,15 +1215,16 @@ AlterDomainNotNull(List *names, bool notNull)
 	/* Use LookupTypeName here so that shell types can be found (why?). */
 	domainoid = LookupTypeName(typename);
 	if (!OidIsValid(domainoid))
-		elog(ERROR, "Type \"%s\" does not exist",
-			 TypeNameToString(typename));
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_OBJECT),
+				 errmsg("type \"%s\" does not exist",
+						TypeNameToString(typename))));
 
 	tup = SearchSysCacheCopy(TYPEOID,
 							 ObjectIdGetDatum(domainoid),
 							 0, 0, 0);
 	if (!HeapTupleIsValid(tup))
-		elog(ERROR, "AlterDomain: type \"%s\" does not exist",
-			 TypeNameToString(typename));
+		elog(ERROR, "cache lookup failed for type %u", domainoid);
 	typTup = (Form_pg_type) GETSTRUCT(tup);
 
 	/* Doesn't return if user isn't allowed to alter the domain */ 
@@ -1174,9 +1233,10 @@ AlterDomainNotNull(List *names, bool notNull)
 	/* Is the domain already set to the desired constraint? */
 	if (typTup->typnotnull == notNull)
 	{
-		elog(NOTICE, "AlterDomain: %s is already set to %s",
-			 TypeNameToString(typename),
-			 notNull ? "NOT NULL" : "NULL");
+		ereport(NOTICE,
+				(errmsg("\"%s\" is already set to %s",
+						TypeNameToString(typename),
+						notNull ? "NOT NULL" : "NULL")));
 		heap_close(typrel, RowExclusiveLock);
 		return;
 	}
@@ -1216,9 +1276,11 @@ AlterDomainNotNull(List *names, bool notNull)
 					d = heap_getattr(tuple, attnum, tupdesc, &isNull);
 
 					if (isNull)
-						elog(ERROR, "ALTER DOMAIN: Relation \"%s\" attribute \"%s\" contains NULL values",
-							 RelationGetRelationName(testrel),
-							 NameStr(tupdesc->attrs[attnum - 1]->attname));
+						ereport(ERROR,
+								(errcode(ERRCODE_NOT_NULL_VIOLATION),
+								 errmsg("relation \"%s\" attribute \"%s\" contains NULL values",
+										RelationGetRelationName(testrel),
+										NameStr(tupdesc->attrs[attnum - 1]->attname))));
 				}
 			}
 			heap_endscan(scan);
@@ -1273,16 +1335,16 @@ AlterDomainDropConstraint(List *names, const char *constrName, DropBehavior beha
 	/* Use LookupTypeName here so that shell types can be removed. */
 	domainoid = LookupTypeName(typename);
 	if (!OidIsValid(domainoid))
-		elog(ERROR, "Type \"%s\" does not exist",
-			 TypeNameToString(typename));
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_OBJECT),
+				 errmsg("type \"%s\" does not exist",
+						TypeNameToString(typename))));
 
 	tup = SearchSysCacheCopy(TYPEOID,
 							 ObjectIdGetDatum(domainoid),
 							 0, 0, 0);
-
 	if (!HeapTupleIsValid(tup))
-		elog(ERROR, "AlterDomain: type \"%s\" does not exist",
-			 TypeNameToString(typename));
+		elog(ERROR, "cache lookup failed for type %u", domainoid);
 
 	/* Doesn't return if user isn't allowed to alter the domain */ 
 	domainOwnerCheck(tup, typename);
@@ -1360,15 +1422,16 @@ AlterDomainAddConstraint(List *names, Node *newConstraint)
 	/* Use LookupTypeName here so that shell types can be found (why?). */
 	domainoid = LookupTypeName(typename);
 	if (!OidIsValid(domainoid))
-		elog(ERROR, "Type \"%s\" does not exist",
-			 TypeNameToString(typename));
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_OBJECT),
+				 errmsg("type \"%s\" does not exist",
+						TypeNameToString(typename))));
 
 	tup = SearchSysCacheCopy(TYPEOID,
 							 ObjectIdGetDatum(domainoid),
 							 0, 0, 0);
 	if (!HeapTupleIsValid(tup))
-		elog(ERROR, "AlterDomain: type \"%s\" does not exist",
-			 TypeNameToString(typename));
+		elog(ERROR, "cache lookup failed for type %u", domainoid);
 	typTup = (Form_pg_type) GETSTRUCT(tup);
 
 	/* Doesn't return if user isn't allowed to alter the domain */ 
@@ -1376,23 +1439,30 @@ AlterDomainAddConstraint(List *names, Node *newConstraint)
 
 	/* Check for unsupported constraint types */
 	if (IsA(newConstraint, FkConstraint))
-		elog(ERROR, "ALTER DOMAIN / FOREIGN KEY constraints not supported");
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("FOREIGN KEY constraints not supported for domains")));
 
-	/* this case should not happen */
+	/* otherwise it should be a plain Constraint */
 	if (!IsA(newConstraint, Constraint))
-		elog(ERROR, "AlterDomainAddConstraint: unexpected constraint node type");
+		elog(ERROR, "unrecognized node type: %d",
+			 (int) nodeTag(newConstraint));
 
 	constr = (Constraint *) newConstraint;
 
 	switch (constr->contype)
 	{
 		case CONSTR_DEFAULT:
-			elog(ERROR, "Use ALTER DOMAIN .. SET DEFAULT instead");
+			ereport(ERROR,
+					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+					 errmsg("use ALTER DOMAIN .. SET DEFAULT instead")));
 			break;
 
 		case CONSTR_NOTNULL:
 		case CONSTR_NULL:
-			elog(ERROR, "Use ALTER DOMAIN .. [ SET | DROP ] NOT NULL instead");
+			ereport(ERROR,
+					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+					 errmsg("use ALTER DOMAIN .. [ SET | DROP ] NOT NULL instead")));
 			break;
 
 	  	case CONSTR_CHECK:
@@ -1400,23 +1470,29 @@ AlterDomainAddConstraint(List *names, Node *newConstraint)
 	  		break;
 
 		case CONSTR_UNIQUE:
-			elog(ERROR, "ALTER DOMAIN / UNIQUE indexes not supported");
+			ereport(ERROR,
+					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+					 errmsg("UNIQUE constraints not supported for domains")));
 			break;
 
 		case CONSTR_PRIMARY:
-			elog(ERROR, "ALTER DOMAIN / PRIMARY KEY indexes not supported");
+			ereport(ERROR,
+					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+					 errmsg("PRIMARY KEY constraints not supported for domains")));
 			break;
 
 		case CONSTR_ATTR_DEFERRABLE:
 		case CONSTR_ATTR_NOT_DEFERRABLE:
 		case CONSTR_ATTR_DEFERRED:
 		case CONSTR_ATTR_IMMEDIATE:
-			elog(ERROR, "ALTER DOMAIN: DEFERRABLE, NON DEFERRABLE, DEFERRED"
-				 " and IMMEDIATE not supported");
+			ereport(ERROR,
+					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+					 errmsg("deferrability constraints not supported for domains")));
 			break;
 
 		default:
-			elog(ERROR, "AlterDomainAddConstraint: unrecognized constraint node type");
+			elog(ERROR, "unrecognized constraint subtype: %d",
+				 (int) constr->contype);
 			break;
 	}
 
@@ -1480,9 +1556,11 @@ AlterDomainAddConstraint(List *names, Node *newConstraint)
 													  &isNull, NULL);
 
 				if (!isNull && !DatumGetBool(conResult))
-					elog(ERROR, "ALTER DOMAIN: Relation \"%s\" attribute \"%s\" contains values that fail the new constraint",
-						 RelationGetRelationName(testrel),
-						 NameStr(tupdesc->attrs[attnum - 1]->attname));
+					ereport(ERROR,
+							(errcode(ERRCODE_CHECK_VIOLATION),
+							 errmsg("relation \"%s\" attribute \"%s\" contains values that violate the new constraint",
+									RelationGetRelationName(testrel),
+									NameStr(tupdesc->attrs[attnum - 1]->attname))));
 			}
 
 			ResetExprContext(econtext);
@@ -1641,8 +1719,10 @@ domainOwnerCheck(HeapTuple tup, TypeName *typename)
 
 	/* Check that this is actually a domain */
 	if (typTup->typtype != 'd')
-		elog(ERROR, "%s is not a domain",
-			 TypeNameToString(typename));
+		ereport(ERROR,
+				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+				 errmsg("\"%s\" is not a domain",
+						TypeNameToString(typename))));
 
 	/* Permission check: must own type */
 	if (!pg_type_ownercheck(HeapTupleGetOid(tup), GetUserId()))
@@ -1672,9 +1752,10 @@ domainAddConstraint(Oid domainOid, Oid domainNamespace, Oid baseTypeOid,
 								 domainOid,
 								 domainNamespace,
 								 constr->name))
-			elog(ERROR, "constraint \"%s\" already exists for domain \"%s\"",
-				 constr->name,
-				 domainName);
+			ereport(ERROR,
+					(errcode(ERRCODE_DUPLICATE_OBJECT),
+					 errmsg("constraint \"%s\" for domain \"%s\" already exists",
+							constr->name, domainName)));
 	}
 	else
 		constr->name = GenerateConstraintName(CONSTRAINT_DOMAIN,
@@ -1708,26 +1789,33 @@ domainAddConstraint(Oid domainOid, Oid domainNamespace, Oid baseTypeOid,
 	expr = coerce_to_boolean(pstate, expr, "CHECK");
 
 	/*
-	 * Make sure no outside relations are
-	 * referred to.
+	 * Make sure no outside relations are referred to.
 	 */
 	if (length(pstate->p_rtable) != 0)
-		elog(ERROR, "Relations cannot be referenced in domain CHECK constraint");
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
+				 errmsg("cannot use table references in domain CHECK constraint")));
 
 	/*
 	 * Domains don't allow var clauses (this should be redundant with the
 	 * above check, but make it anyway)
 	 */
 	if (contain_var_clause(expr))
-		elog(ERROR, "cannot use column references in domain CHECK clause");
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
+				 errmsg("cannot use table references in domain CHECK constraint")));
 
 	/*
 	 * No subplans or aggregates, either...
 	 */
 	if (pstate->p_hasSubLinks)
-		elog(ERROR, "cannot use subselect in CHECK constraint expression");
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("cannot use sub-select in CHECK constraint")));
 	if (pstate->p_hasAggs)
-		elog(ERROR, "cannot use aggregate function in CHECK constraint expression");
+		ereport(ERROR,
+				(errcode(ERRCODE_GROUPING_ERROR),
+				 errmsg("cannot use aggregate in CHECK constraint")));
 
 	/*
 	 * Convert to string form for storage.
@@ -1805,8 +1893,7 @@ GetDomainConstraints(Oid typeOid)
 							 ObjectIdGetDatum(typeOid),
 							 0, 0, 0);
 		if (!HeapTupleIsValid(tup))
-			elog(ERROR, "GetDomainConstraints: failed to lookup type %u",
-				 typeOid);
+			elog(ERROR, "cache lookup failed for type %u", typeOid);
 		typTup = (Form_pg_type) GETSTRUCT(tup);
 
 		/* Test for NOT NULL Constraint */
@@ -1837,7 +1924,7 @@ GetDomainConstraints(Oid typeOid)
 			val = fastgetattr(conTup, Anum_pg_constraint_conbin,
 							  conRel->rd_att, &isNull);
 			if (isNull)
-				elog(ERROR, "GetDomainConstraints: domain %s constraint %s has NULL conbin",
+				elog(ERROR, "domain \"%s\" constraint \"%s\" has NULL conbin",
 					 NameStr(typTup->typname), NameStr(c->conname));
 
 			check_expr = (Expr *)
@@ -1925,21 +2012,24 @@ AlterTypeOwner(List *names, AclId newOwnerSysId)
 	/* Use LookupTypeName here so that shell types can be processed (why?) */
 	typeOid = LookupTypeName(typename);
 	if (!OidIsValid(typeOid))
-		elog(ERROR, "Type \"%s\" does not exist",
-			 TypeNameToString(typename));
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_OBJECT),
+				 errmsg("type \"%s\" does not exist",
+						TypeNameToString(typename))));
 
 	tup = SearchSysCacheCopy(TYPEOID,
 							 ObjectIdGetDatum(typeOid),
 							 0, 0, 0);
 	if (!HeapTupleIsValid(tup))
-		elog(ERROR, "AlterDomain: type \"%s\" does not exist",
-			 TypeNameToString(typename));
+		elog(ERROR, "cache lookup failed for type %u", typeOid);
 	typTup = (Form_pg_type) GETSTRUCT(tup);
 
 	/* Check that this is actually a domain */
 	if (typTup->typtype != 'd')
-		elog(ERROR, "%s is not a domain",
-			 TypeNameToString(typename));
+		ereport(ERROR,
+				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+				 errmsg("\"%s\" is not a domain",
+						TypeNameToString(typename))));
 
 	/* Modify the owner --- okay to scribble on typTup because it's a copy */
 	typTup->typowner = newOwnerSysId;
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index a54162e24c5446cbc9f4bdb602615c831c1911c3..d23c21800612844113753face61c7f62f215cd15 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -6,7 +6,7 @@
  * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
  * Portions Copyright (c) 1994, Regents of the University of California
  *
- * $Header: /cvsroot/pgsql/src/backend/commands/user.c,v 1.119 2003/07/18 23:20:32 tgl Exp $
+ * $Header: /cvsroot/pgsql/src/backend/commands/user.c,v 1.120 2003/07/20 21:56:34 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -180,7 +180,8 @@ write_group_file(Relation grel)
 		i = strcspn(groname, "\n");
 		if (groname[i] != '\0')
 		{
-			elog(LOG, "invalid group name \"%s\"", groname);
+			ereport(LOG,
+					(errmsg("invalid group name \"%s\"", groname)));
 			continue;
 		}
 
@@ -210,7 +211,8 @@ write_group_file(Relation grel)
 				j = strcspn(usename, "\n");
 				if (usename[j] != '\0')
 				{
-					elog(LOG, "invalid user name \"%s\"", usename);
+					ereport(LOG,
+							(errmsg("invalid user name \"%s\"", usename)));
 					continue;
 				}
 
@@ -341,13 +343,15 @@ write_user_file(Relation urel)
 		i = strcspn(usename, "\n");
 		if (usename[i] != '\0')
 		{
-			elog(LOG, "invalid user name \"%s\"", usename);
+			ereport(LOG,
+					(errmsg("invalid user name \"%s\"", usename)));
 			continue;
 		}
 		i = strcspn(passwd, "\n");
 		if (passwd[i] != '\0')
 		{
-			elog(LOG, "invalid user password \"%s\"", passwd);
+			ereport(LOG,
+					(errmsg("invalid user password \"%s\"", passwd)));
 			continue;
 		}
 
diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c
index 5c4faa5da24882fc965c8eaa52553ad279e2184f..e73ace27c27398d4ddeab88d4cd69d8293f3d876 100644
--- a/src/backend/commands/vacuum.c
+++ b/src/backend/commands/vacuum.c
@@ -13,7 +13,7 @@
  *
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/commands/vacuum.c,v 1.256 2003/06/27 14:45:27 petere Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/commands/vacuum.c,v 1.257 2003/07/20 21:56:34 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -461,7 +461,9 @@ vacuum_set_xid_limits(VacuumStmt *vacstmt, bool sharedRel,
 	 */
 	if (TransactionIdFollows(limit, *oldestXmin))
 	{
-		elog(WARNING, "oldest Xmin is far in the past --- close open transactions soon to avoid wraparound problems");
+		ereport(WARNING,
+				(errmsg("oldest Xmin is far in the past"),
+				 errhint("Close open transactions soon to avoid wraparound problems.")));
 		limit = *oldestXmin;
 	}
 
@@ -583,7 +585,7 @@ vac_update_dbstats(Oid dbid,
 	tuple = heap_getnext(scan, ForwardScanDirection);
 
 	if (!HeapTupleIsValid(tuple))
-		elog(ERROR, "database %u does not exist", dbid);
+		elog(ERROR, "could not find tuple for database %u", dbid);
 
 	dbform = (Form_pg_database) GETSTRUCT(tuple);
 
@@ -667,8 +669,9 @@ vac_truncate_clog(TransactionId vacuumXID, TransactionId frozenXID)
 	 */
 	if (vacuumAlreadyWrapped)
 	{
-		elog(WARNING, "Some databases have not been vacuumed in over 2 billion transactions."
-			 "\n\tYou may have already suffered transaction-wraparound data loss.");
+		ereport(WARNING,
+				(errmsg("some databases have not been vacuumed in over 2 billion transactions"),
+				 errdetail("You may have already suffered transaction-wraparound data loss.")));
 		return;
 	}
 
@@ -678,17 +681,20 @@ vac_truncate_clog(TransactionId vacuumXID, TransactionId frozenXID)
 	/* Give warning about impending wraparound problems */
 	if (frozenAlreadyWrapped)
 	{
-		elog(WARNING, "Some databases have not been vacuumed in over 1 billion transactions."
-			 "\n\tBetter vacuum them soon, or you may have a wraparound failure.");
+		ereport(WARNING,
+				(errmsg("some databases have not been vacuumed in over 1 billion transactions"),
+				 errhint("Better vacuum them soon, or you may have a wraparound failure.")));
 	}
 	else
 	{
 		age = (int32) (myXID - frozenXID);
 		if (age > (int32) ((MaxTransactionId >> 3) * 3))
-			elog(WARNING, "Some databases have not been vacuumed in %d transactions."
-				 "\n\tBetter vacuum them within %d transactions,"
-				 "\n\tor you may have a wraparound failure.",
-				 age, (int32) (MaxTransactionId >> 1) - age);
+			ereport(WARNING,
+					(errmsg("some databases have not been vacuumed in %d transactions",
+							age),
+					 errhint("Better vacuum them within %d transactions, "
+							 "or you may have a wraparound failure.",
+							 (int32) (MaxTransactionId >> 1) - age)));
 	}
 }
 
@@ -773,8 +779,9 @@ vacuum_rel(Oid relid, VacuumStmt *vacstmt, char expected_relkind)
 	if (!(pg_class_ownercheck(RelationGetRelid(onerel), GetUserId()) ||
 		  (pg_database_ownercheck(MyDatabaseId, GetUserId()) && !onerel->rd_rel->relisshared)))
 	{
-		elog(WARNING, "Skipping \"%s\" --- only table or database owner can VACUUM it",
-			 RelationGetRelationName(onerel));
+		ereport(WARNING,
+				(errmsg("skipping \"%s\" --- only table or database owner can VACUUM it",
+						RelationGetRelationName(onerel))));
 		relation_close(onerel, lmode);
 		CommitTransactionCommand();
 		return false;
@@ -786,8 +793,9 @@ vacuum_rel(Oid relid, VacuumStmt *vacstmt, char expected_relkind)
 	 */
 	if (onerel->rd_rel->relkind != expected_relkind)
 	{
-		elog(WARNING, "Skipping \"%s\" --- can not process indexes, views or special system tables",
-			 RelationGetRelationName(onerel));
+		ereport(WARNING,
+				(errmsg("skipping \"%s\" --- cannot VACUUM indexes, views or special system tables",
+						RelationGetRelationName(onerel))));
 		relation_close(onerel, lmode);
 		CommitTransactionCommand();
 		return false;
@@ -979,8 +987,7 @@ full_vacuum_rel(Relation onerel, VacuumStmt *vacstmt)
 			 */
 			i = FlushRelationBuffers(onerel, vacrelstats->rel_pages);
 			if (i < 0)
-				elog(ERROR, "VACUUM (full_vacuum_rel): FlushRelationBuffers returned %d",
-					 i);
+				elog(ERROR, "FlushRelationBuffers returned %d", i);
 		}
 	}
 
@@ -1025,15 +1032,13 @@ scan_heap(VRelStats *vacrelstats, Relation onerel,
 	VacPage		vacpage,
 				vacpagecopy;
 	BlockNumber empty_pages,
-				new_pages,
-				changed_pages,
 				empty_end_pages;
 	double		num_tuples,
 				tups_vacuumed,
 				nkeep,
 				nunused;
-	double		free_size,
-				usable_free_size;
+	double		free_space,
+				usable_free_space;
 	Size		min_tlen = MaxTupleSize;
 	Size		max_tlen = 0;
 	int			i;
@@ -1046,13 +1051,14 @@ scan_heap(VRelStats *vacrelstats, Relation onerel,
 	vac_init_rusage(&ru0);
 
 	relname = RelationGetRelationName(onerel);
-	elog(elevel, "--Relation %s.%s--",
-		 get_namespace_name(RelationGetNamespace(onerel)),
-		 relname);
+	ereport(elevel,
+			(errmsg("vacuuming \"%s.%s\"",
+					get_namespace_name(RelationGetNamespace(onerel)),
+					relname)));
 
-	empty_pages = new_pages = changed_pages = empty_end_pages = 0;
+	empty_pages = empty_end_pages = 0;
 	num_tuples = tups_vacuumed = nkeep = nunused = 0;
-	free_size = 0;
+	free_space = 0;
 
 	nblocks = RelationGetNumberOfBlocks(onerel);
 
@@ -1080,12 +1086,13 @@ scan_heap(VRelStats *vacrelstats, Relation onerel,
 
 		if (PageIsNew(page))
 		{
-			elog(WARNING, "Rel %s: Uninitialized page %u - fixing",
-				 relname, blkno);
+			ereport(WARNING,
+					(errmsg("relation \"%s\" page %u is uninitialized --- fixing",
+							relname, blkno)));
 			PageInit(page, BufferGetPageSize(buf), 0);
 			vacpage->free = ((PageHeader) page)->pd_upper - ((PageHeader) page)->pd_lower;
-			free_size += vacpage->free;
-			new_pages++;
+			free_space += vacpage->free;
+			empty_pages++;
 			empty_end_pages++;
 			vacpagecopy = copy_vac_page(vacpage);
 			vpage_insert(vacuum_pages, vacpagecopy);
@@ -1097,7 +1104,7 @@ scan_heap(VRelStats *vacrelstats, Relation onerel,
 		if (PageIsEmpty(page))
 		{
 			vacpage->free = ((PageHeader) page)->pd_upper - ((PageHeader) page)->pd_lower;
-			free_size += vacpage->free;
+			free_space += vacpage->free;
 			empty_pages++;
 			empty_end_pages++;
 			vacpagecopy = copy_vac_page(vacpage);
@@ -1193,9 +1200,12 @@ scan_heap(VRelStats *vacrelstats, Relation onerel,
 					/*
 					 * This should not happen, since we hold exclusive
 					 * lock on the relation; shouldn't we raise an error?
+					 * (Actually, it can happen in system catalogs, since
+					 * we tend to release write lock before commit there.)
 					 */
-					elog(WARNING, "Rel %s: TID %u/%u: InsertTransactionInProgress %u - can't shrink relation",
-						 relname, blkno, offnum, HeapTupleHeaderGetXmin(tuple.t_data));
+					ereport(NOTICE,
+							(errmsg("relation \"%s\" TID %u/%u: InsertTransactionInProgress %u --- can't shrink relation",
+									relname, blkno, offnum, HeapTupleHeaderGetXmin(tuple.t_data))));
 					do_shrinking = false;
 					break;
 				case HEAPTUPLE_DELETE_IN_PROGRESS:
@@ -1203,13 +1213,16 @@ scan_heap(VRelStats *vacrelstats, Relation onerel,
 					/*
 					 * This should not happen, since we hold exclusive
 					 * lock on the relation; shouldn't we raise an error?
+					 * (Actually, it can happen in system catalogs, since
+					 * we tend to release write lock before commit there.)
 					 */
-					elog(WARNING, "Rel %s: TID %u/%u: DeleteTransactionInProgress %u - can't shrink relation",
-						 relname, blkno, offnum, HeapTupleHeaderGetXmax(tuple.t_data));
+					ereport(NOTICE,
+							(errmsg("relation \"%s\" TID %u/%u: DeleteTransactionInProgress %u --- can't shrink relation",
+									relname, blkno, offnum, HeapTupleHeaderGetXmax(tuple.t_data))));
 					do_shrinking = false;
 					break;
 				default:
-					elog(ERROR, "Unexpected HeapTupleSatisfiesVacuum result");
+					elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
 					break;
 			}
 
@@ -1222,8 +1235,8 @@ scan_heap(VRelStats *vacrelstats, Relation onerel,
 			 */
 			if (onerel->rd_rel->relhasoids &&
 				!OidIsValid(HeapTupleGetOid(&tuple)))
-				elog(WARNING, "Rel %s: TID %u/%u: OID IS INVALID. TUPGONE %d.",
-					 relname, blkno, offnum, (int) tupgone);
+				elog(WARNING, "relation \"%s\" TID %u/%u: OID is invalid",
+					 relname, blkno, offnum);
 
 			if (tupgone)
 			{
@@ -1280,7 +1293,7 @@ scan_heap(VRelStats *vacrelstats, Relation onerel,
 			do_reap = (vacpage->offsets_free > 0);
 		}
 
-		free_size += vacpage->free;
+		free_space += vacpage->free;
 
 		/*
 		 * Add the page to fraged_pages if it has a useful amount of free
@@ -1299,16 +1312,20 @@ scan_heap(VRelStats *vacrelstats, Relation onerel,
 				vpage_insert(fraged_pages, vacpagecopy);
 		}
 
+		/*
+		 * Include the page in empty_end_pages if it will be empty after
+		 * vacuuming; this is to keep us from using it as a move destination.
+		 */
 		if (notup)
+		{
+			empty_pages++;
 			empty_end_pages++;
+		}
 		else
 			empty_end_pages = 0;
 
 		if (pgchanged)
-		{
 			WriteBuffer(buf);
-			changed_pages++;
-		}
 		else
 			ReleaseBuffer(buf);
 	}
@@ -1335,14 +1352,14 @@ scan_heap(VRelStats *vacrelstats, Relation onerel,
 	{
 		Assert((BlockNumber) fraged_pages->num_pages >= empty_end_pages);
 		fraged_pages->num_pages -= empty_end_pages;
-		usable_free_size = 0;
+		usable_free_space = 0;
 		for (i = 0; i < fraged_pages->num_pages; i++)
-			usable_free_size += fraged_pages->pagedesc[i]->free;
+			usable_free_space += fraged_pages->pagedesc[i]->free;
 	}
 	else
 	{
 		fraged_pages->num_pages = 0;
-		usable_free_size = 0;
+		usable_free_space = 0;
 	}
 
 	/* don't bother to save vtlinks if we will not call repair_frag */
@@ -1360,17 +1377,24 @@ scan_heap(VRelStats *vacrelstats, Relation onerel,
 		pfree(vtlinks);
 	}
 
-	elog(elevel, "Pages %u: Changed %u, reaped %u, Empty %u, New %u; "
-		 "Tup %.0f: Vac %.0f, Keep/VTL %.0f/%u, UnUsed %.0f, MinLen %lu, "
-		 "MaxLen %lu; Re-using: Free/Avail. Space %.0f/%.0f; "
-		 "EndEmpty/Avail. Pages %u/%u.\n\t%s",
-		 nblocks, changed_pages, vacuum_pages->num_pages, empty_pages,
-		 new_pages, num_tuples, tups_vacuumed,
-		 nkeep, vacrelstats->num_vtlinks,
-		 nunused, (unsigned long) min_tlen, (unsigned long) max_tlen,
-		 free_size, usable_free_size,
-		 empty_end_pages, fraged_pages->num_pages,
-		 vac_show_rusage(&ru0));
+	ereport(elevel,
+			(errmsg("\"%s\": found %.0f removable, %.0f nonremovable tuples in %u pages",
+					RelationGetRelationName(onerel),
+					tups_vacuumed, num_tuples, nblocks),
+			 errdetail("%.0f dead tuples cannot be removed yet.\n"
+					   "Nonremovable tuples range from %lu to %lu bytes long.\n"
+					   "There were %.0f unused item pointers.\n"
+					   "Total free space (including removable tuples) is %.0f bytes.\n"
+					   "%u pages are or will become empty, including %u at the end of the table.\n"
+					   "%u pages containing %.0f free bytes are potential move destinations.\n"
+					   "%s",
+					   nkeep,
+					   (unsigned long) min_tlen, (unsigned long) max_tlen,
+					   nunused,
+					   free_space,
+					   empty_pages, empty_end_pages,
+					   fraged_pages->num_pages, usable_free_space,
+					   vac_show_rusage(&ru0))));
 }
 
 
@@ -1594,7 +1618,7 @@ repair_frag(VRelStats *vacrelstats, Relation onerel,
 				if (tuple.t_data->t_infomask & HEAP_MOVED_OFF)
 				{
 					if (HeapTupleHeaderGetXvac(tuple.t_data) != myXID)
-						elog(ERROR, "Invalid XVAC in tuple header");
+						elog(ERROR, "invalid XVAC in tuple header");
 					if (keep_tuples == 0)
 						continue;
 					if (chain_tuple_moved)		/* some chains was moved
@@ -1673,7 +1697,7 @@ repair_frag(VRelStats *vacrelstats, Relation onerel,
 				/* Quick exit if we have no vtlinks to search in */
 				if (vacrelstats->vtlinks == NULL)
 				{
-					elog(DEBUG2, "Parent item in update-chain not found - can't continue repair_frag");
+					elog(DEBUG2, "parent item in update-chain not found --- can't continue repair_frag");
 					break;		/* out of walk-along-page loop */
 				}
 
@@ -1710,7 +1734,7 @@ repair_frag(VRelStats *vacrelstats, Relation onerel,
 						 * in scan_heap(), but it's not implemented at the
 						 * moment and so we just stop shrinking here.
 						 */
-						elog(DEBUG2, "Child itemid in update-chain marked as unused - can't continue repair_frag");
+						elog(DEBUG2, "child itemid in update-chain marked as unused --- can't continue repair_frag");
 						chain_move_failed = true;
 						break;	/* out of loop to move to chain end */
 					}
@@ -1795,7 +1819,7 @@ repair_frag(VRelStats *vacrelstats, Relation onerel,
 					if (vtlp == NULL)
 					{
 						/* see discussion above */
-						elog(DEBUG2, "Parent item in update-chain not found - can't continue repair_frag");
+						elog(DEBUG2, "parent item in update-chain not found --- can't continue repair_frag");
 						chain_move_failed = true;
 						break;	/* out of check-all-items loop */
 					}
@@ -1807,7 +1831,7 @@ repair_frag(VRelStats *vacrelstats, Relation onerel,
 							   ItemPointerGetOffsetNumber(&(tp.t_self)));
 					/* this can't happen since we saw tuple earlier: */
 					if (!ItemIdIsUsed(Pitemid))
-						elog(ERROR, "Parent itemid marked as unused");
+						elog(ERROR, "parent itemid marked as unused");
 					Ptp.t_datamcxt = NULL;
 					Ptp.t_data = (HeapTupleHeader) PageGetItem(Ppage, Pitemid);
 
@@ -1831,7 +1855,7 @@ repair_frag(VRelStats *vacrelstats, Relation onerel,
 									 HeapTupleHeaderGetXmin(tp.t_data))))
 					{
 						ReleaseBuffer(Pbuf);
-						elog(DEBUG2, "Too old parent tuple found - can't continue repair_frag");
+						elog(DEBUG2, "too old parent tuple found --- can't continue repair_frag");
 						chain_move_failed = true;
 						break;	/* out of check-all-items loop */
 					}
@@ -1904,7 +1928,7 @@ repair_frag(VRelStats *vacrelstats, Relation onerel,
 					 */
 					CacheInvalidateHeapTuple(onerel, &tuple);
 
-					/* NO ELOG(ERROR) TILL CHANGES ARE LOGGED */
+					/* NO EREPORT(ERROR) TILL CHANGES ARE LOGGED */
 					START_CRIT_SECTION();
 
 					tuple.t_data->t_infomask &= ~(HEAP_XMIN_COMMITTED |
@@ -1960,7 +1984,7 @@ repair_frag(VRelStats *vacrelstats, Relation onerel,
 										 LP_USED);
 					if (newoff == InvalidOffsetNumber)
 					{
-						elog(PANIC, "moving chain: failed to add item with len = %lu to page %u",
+						elog(PANIC, "failed to add item with len = %lu to page %u while moving tuple chain",
 						  (unsigned long) tuple_len, destvacpage->blkno);
 					}
 					newitemid = PageGetItemId(ToPage, newoff);
@@ -2087,7 +2111,7 @@ repair_frag(VRelStats *vacrelstats, Relation onerel,
 			 */
 			CacheInvalidateHeapTuple(onerel, &tuple);
 
-			/* NO ELOG(ERROR) TILL CHANGES ARE LOGGED */
+			/* NO EREPORT(ERROR) TILL CHANGES ARE LOGGED */
 			START_CRIT_SECTION();
 
 			/*
@@ -2193,11 +2217,11 @@ repair_frag(VRelStats *vacrelstats, Relation onerel,
 				if (tuple.t_data->t_infomask & HEAP_XMIN_COMMITTED)
 					continue;
 				if (tuple.t_data->t_infomask & HEAP_MOVED_IN)
-					elog(ERROR, "HEAP_MOVED_IN was not expected (2)");
+					elog(ERROR, "HEAP_MOVED_IN was not expected");
 				if (tuple.t_data->t_infomask & HEAP_MOVED_OFF)
 				{
 					if (HeapTupleHeaderGetXvac(tuple.t_data) != myXID)
-						elog(ERROR, "Invalid XVAC in tuple header (4)");
+						elog(ERROR, "invalid XVAC in tuple header");
 					/* some chains was moved while */
 					if (chain_tuple_moved)
 					{			/* cleaning this page */
@@ -2222,7 +2246,7 @@ repair_frag(VRelStats *vacrelstats, Relation onerel,
 					}
 				}
 				else
-					elog(ERROR, "HEAP_MOVED_OFF was expected (2)");
+					elog(ERROR, "HEAP_MOVED_OFF was expected");
 			}
 		}
 
@@ -2335,7 +2359,7 @@ repair_frag(VRelStats *vacrelstats, Relation onerel,
 				if (!(tuple.t_data->t_infomask & HEAP_MOVED))
 					elog(ERROR, "HEAP_MOVED_OFF/HEAP_MOVED_IN was expected");
 				if (HeapTupleHeaderGetXvac(tuple.t_data) != myXID)
-					elog(ERROR, "Invalid XVAC in tuple header (2)");
+					elog(ERROR, "invalid XVAC in tuple header");
 				if (tuple.t_data->t_infomask & HEAP_MOVED_IN)
 				{
 					tuple.t_data->t_infomask |= HEAP_XMIN_COMMITTED;
@@ -2353,10 +2377,18 @@ repair_frag(VRelStats *vacrelstats, Relation onerel,
 	}
 	Assert(num_moved == checked_moved);
 
-	elog(elevel, "Rel %s: Pages: %u --> %u; Tuple(s) moved: %u.\n\t%s",
-		 RelationGetRelationName(onerel),
-		 nblocks, blkno, num_moved,
-		 vac_show_rusage(&ru0));
+	/*
+	 * It'd be cleaner to make this report at the bottom of this routine,
+	 * but then the rusage would double-count the second pass of index
+	 * vacuuming.  So do it here and ignore the relatively small amount
+	 * of processing that occurs below.
+	 */
+	ereport(elevel,
+			(errmsg("\"%s\": moved %u tuples, truncated %u to %u pages",
+					RelationGetRelationName(onerel),
+					num_moved, nblocks, blkno),
+			 errdetail("%s",
+					   vac_show_rusage(&ru0))));
 
 	/*
 	 * Reflect the motion of system tuples to catalog cache here.
@@ -2414,12 +2446,12 @@ repair_frag(VRelStats *vacrelstats, Relation onerel,
 					if (tuple.t_data->t_infomask & HEAP_MOVED_OFF)
 					{
 						if (HeapTupleHeaderGetXvac(tuple.t_data) != myXID)
-							elog(ERROR, "Invalid XVAC in tuple header (3)");
+							elog(ERROR, "invalid XVAC in tuple header");
 						itemid->lp_flags &= ~LP_USED;
 						num_tuples++;
 					}
 					else
-						elog(ERROR, "HEAP_MOVED_OFF was expected (3)");
+						elog(ERROR, "HEAP_MOVED_OFF was expected");
 				}
 
 			}
@@ -2468,8 +2500,7 @@ repair_frag(VRelStats *vacrelstats, Relation onerel,
 	 */
 	i = FlushRelationBuffers(onerel, blkno);
 	if (i < 0)
-		elog(ERROR, "VACUUM (repair_frag): FlushRelationBuffers returned %d",
-			 i);
+		elog(ERROR, "FlushRelationBuffers returned %d", i);
 
 	/* truncate relation, if needed */
 	if (blkno < nblocks)
@@ -2534,15 +2565,15 @@ vacuum_heap(VRelStats *vacrelstats, Relation onerel, VacPageList vacuum_pages)
 
 	i = FlushRelationBuffers(onerel, relblocks);
 	if (i < 0)
-		elog(ERROR, "VACUUM (vacuum_heap): FlushRelationBuffers returned %d",
-			 i);
+		elog(ERROR, "FlushRelationBuffers returned %d", i);
 
 	/* truncate relation if there are some empty end-pages */
 	if (vacuum_pages->empty_end_pages > 0)
 	{
-		elog(elevel, "Rel %s: Pages: %u --> %u.",
-			 RelationGetRelationName(onerel),
-			 vacrelstats->rel_pages, relblocks);
+		ereport(elevel,
+				(errmsg("\"%s\": truncated %u to %u pages",
+						RelationGetRelationName(onerel),
+						vacrelstats->rel_pages, relblocks)));
 		relblocks = smgrtruncate(DEFAULT_SMGR, onerel, relblocks);
 		onerel->rd_nblocks = relblocks; /* update relcache immediately */
 		onerel->rd_targblock = InvalidBlockNumber;
@@ -2631,11 +2662,15 @@ scan_index(Relation indrel, double num_tuples)
 						stats->num_pages, stats->num_index_tuples,
 						false);
 
-	elog(elevel, "Index %s: Pages %u, %u deleted, %u free; Tuples %.0f.\n\t%s",
-		 RelationGetRelationName(indrel),
-		 stats->num_pages, stats->pages_deleted, stats->pages_free,
-		 stats->num_index_tuples,
-		 vac_show_rusage(&ru0));
+	ereport(elevel,
+			(errmsg("index \"%s\" now contains %.0f tuples in %u pages",
+					RelationGetRelationName(indrel),
+					stats->num_index_tuples,
+					stats->num_pages),
+			 errdetail("%u index pages have been deleted, %u are currently reusable.\n"
+					   "%s",
+					   stats->pages_deleted, stats->pages_free,
+					   vac_show_rusage(&ru0))));
 
 	/*
 	 * Check for tuple count mismatch.	If the index is partial, then it's
@@ -2645,10 +2680,11 @@ scan_index(Relation indrel, double num_tuples)
 	{
 		if (stats->num_index_tuples > num_tuples ||
 			!vac_is_partial_index(indrel))
-			elog(WARNING, "Index %s: NUMBER OF INDEX' TUPLES (%.0f) IS NOT THE SAME AS HEAP' (%.0f)."
-				 "\n\tRecreate the index.",
-				 RelationGetRelationName(indrel),
-				 stats->num_index_tuples, num_tuples);
+			ereport(WARNING,
+					(errmsg("index \"%s\" contains %.0f tuples, but table contains %.0f tuples",
+							RelationGetRelationName(indrel),
+							stats->num_index_tuples, num_tuples),
+					 errhint("Rebuild the index with REINDEX.")));
 	}
 
 	pfree(stats);
@@ -2693,11 +2729,17 @@ vacuum_index(VacPageList vacpagelist, Relation indrel,
 						stats->num_pages, stats->num_index_tuples,
 						false);
 
-	elog(elevel, "Index %s: Pages %u, %u deleted, %u free; Tuples %.0f: Deleted %.0f.\n\t%s",
-		 RelationGetRelationName(indrel),
-		 stats->num_pages, stats->pages_deleted, stats->pages_free,
-		 stats->num_index_tuples - keep_tuples, stats->tuples_removed,
-		 vac_show_rusage(&ru0));
+	ereport(elevel,
+			(errmsg("index \"%s\" now contains %.0f tuples in %u pages",
+					RelationGetRelationName(indrel),
+					stats->num_index_tuples,
+					stats->num_pages),
+			 errdetail("%.0f index tuples were removed.\n"
+					   "%u index pages have been deleted, %u are currently reusable.\n"
+					   "%s",
+					   stats->tuples_removed,
+					   stats->pages_deleted, stats->pages_free,
+					   vac_show_rusage(&ru0))));
 
 	/*
 	 * Check for tuple count mismatch.	If the index is partial, then it's
@@ -2707,10 +2749,11 @@ vacuum_index(VacPageList vacpagelist, Relation indrel,
 	{
 		if (stats->num_index_tuples > num_tuples + keep_tuples ||
 			!vac_is_partial_index(indrel))
-			elog(WARNING, "Index %s: NUMBER OF INDEX' TUPLES (%.0f) IS NOT THE SAME AS HEAP' (%.0f)."
-				 "\n\tRecreate the index.",
-				 RelationGetRelationName(indrel),
-				 stats->num_index_tuples, num_tuples);
+			ereport(WARNING,
+					(errmsg("index \"%s\" contains %.0f tuples, but table contains %.0f tuples",
+							RelationGetRelationName(indrel),
+							stats->num_index_tuples, num_tuples + keep_tuples),
+					 errhint("Rebuild the index with REINDEX.")));
 	}
 
 	pfree(stats);
diff --git a/src/backend/commands/vacuumlazy.c b/src/backend/commands/vacuumlazy.c
index 6c072bf33a814b27befa4bce12512d786b0546af..f0be98a23ed1803fab412f59c1a2c878248ebf91 100644
--- a/src/backend/commands/vacuumlazy.c
+++ b/src/backend/commands/vacuumlazy.c
@@ -31,7 +31,7 @@
  *
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/commands/vacuumlazy.c,v 1.28 2003/05/27 17:49:45 momjian Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/commands/vacuumlazy.c,v 1.29 2003/07/20 21:56:34 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -190,8 +190,7 @@ lazy_scan_heap(Relation onerel, LVRelStats *vacrelstats,
 				blkno;
 	HeapTupleData tuple;
 	char	   *relname;
-	BlockNumber empty_pages,
-				changed_pages;
+	BlockNumber empty_pages;
 	double		num_tuples,
 				tups_vacuumed,
 				nkeep,
@@ -202,11 +201,12 @@ lazy_scan_heap(Relation onerel, LVRelStats *vacrelstats,
 	vac_init_rusage(&ru0);
 
 	relname = RelationGetRelationName(onerel);
-	elog(elevel, "--Relation %s.%s--",
-		 get_namespace_name(RelationGetNamespace(onerel)),
-		 relname);
+	ereport(elevel,
+			(errmsg("vacuuming \"%s.%s\"",
+					get_namespace_name(RelationGetNamespace(onerel)),
+					relname)));
 
-	empty_pages = changed_pages = 0;
+	empty_pages = 0;
 	num_tuples = tups_vacuumed = nkeep = nunused = 0;
 
 	nblocks = RelationGetNumberOfBlocks(onerel);
@@ -259,9 +259,11 @@ lazy_scan_heap(Relation onerel, LVRelStats *vacrelstats,
 			LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
 			if (PageIsNew(page))
 			{
-				elog(WARNING, "Rel %s: Uninitialized page %u - fixing",
-					 relname, blkno);
+				ereport(WARNING,
+						(errmsg("relation \"%s\" page %u is uninitialized --- fixing",
+								relname, blkno)));
 				PageInit(page, BufferGetPageSize(buf), 0);
+				empty_pages++;
 				lazy_record_free_space(vacrelstats, blkno,
 									   PageGetFreeSpace(page));
 			}
@@ -350,7 +352,7 @@ lazy_scan_heap(Relation onerel, LVRelStats *vacrelstats,
 					/* This is an expected case during concurrent vacuum */
 					break;
 				default:
-					elog(ERROR, "Unexpected HeapTupleSatisfiesVacuum result");
+					elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
 					break;
 			}
 
@@ -363,8 +365,8 @@ lazy_scan_heap(Relation onerel, LVRelStats *vacrelstats,
 			 */
 			if (onerel->rd_rel->relhasoids &&
 				!OidIsValid(HeapTupleGetOid(&tuple)))
-				elog(WARNING, "Rel %s: TID %u/%u: OID IS INVALID. TUPGONE %d.",
-					 relname, blkno, offnum, (int) tupgone);
+				elog(WARNING, "relation \"%s\" TID %u/%u: OID is invalid",
+					 relname, blkno, offnum);
 
 			if (tupgone)
 			{
@@ -397,10 +399,7 @@ lazy_scan_heap(Relation onerel, LVRelStats *vacrelstats,
 		LockBuffer(buf, BUFFER_LOCK_UNLOCK);
 
 		if (pgchanged)
-		{
 			SetBufferCommitInfoNeedsSave(buf);
-			changed_pages++;
-		}
 
 		ReleaseBuffer(buf);
 	}
@@ -425,10 +424,18 @@ lazy_scan_heap(Relation onerel, LVRelStats *vacrelstats,
 			lazy_scan_index(Irel[i], vacrelstats);
 	}
 
-	elog(elevel, "Pages %u: Changed %u, Empty %u; Tup %.0f: Vac %.0f, Keep %.0f, UnUsed %.0f.\n\tTotal %s",
-		 nblocks, changed_pages, empty_pages,
-		 num_tuples, tups_vacuumed, nkeep, nunused,
-		 vac_show_rusage(&ru0));
+	ereport(elevel,
+			(errmsg("\"%s\": found %.0f removable, %.0f nonremovable tuples in %u pages",
+					RelationGetRelationName(onerel),
+					tups_vacuumed, num_tuples, nblocks),
+			 errdetail("%.0f dead tuples cannot be removed yet.\n"
+					   "There were %.0f unused item pointers.\n"
+					   "%u pages are entirely empty.\n"
+					   "%s",
+					   nkeep,
+					   nunused,
+					   empty_pages,
+					   vac_show_rusage(&ru0))));
 }
 
 
@@ -475,8 +482,12 @@ lazy_vacuum_heap(Relation onerel, LVRelStats *vacrelstats)
 		npages++;
 	}
 
-	elog(elevel, "Removed %d tuples in %d pages.\n\t%s", tupindex, npages,
-		 vac_show_rusage(&ru0));
+	ereport(elevel,
+			(errmsg("\"%s\": removed %d tuples in %d pages",
+					RelationGetRelationName(onerel),
+					tupindex, npages),
+			 errdetail("%s",
+					   vac_show_rusage(&ru0))));
 }
 
 /*
@@ -582,11 +593,15 @@ lazy_scan_index(Relation indrel, LVRelStats *vacrelstats)
 						stats->num_pages, stats->num_index_tuples,
 						false);
 
-	elog(elevel, "Index %s: Pages %u, %u deleted, %u free; Tuples %.0f.\n\t%s",
-		 RelationGetRelationName(indrel),
-		 stats->num_pages, stats->pages_deleted, stats->pages_free,
-		 stats->num_index_tuples,
-		 vac_show_rusage(&ru0));
+	ereport(elevel,
+			(errmsg("index \"%s\" now contains %.0f tuples in %u pages",
+					RelationGetRelationName(indrel),
+					stats->num_index_tuples,
+					stats->num_pages),
+			 errdetail("%u index pages have been deleted, %u are currently reusable.\n"
+					   "%s",
+					   stats->pages_deleted, stats->pages_free,
+					   vac_show_rusage(&ru0))));
 
 	pfree(stats);
 }
@@ -638,11 +653,17 @@ lazy_vacuum_index(Relation indrel, LVRelStats *vacrelstats)
 						stats->num_pages, stats->num_index_tuples,
 						false);
 
-	elog(elevel, "Index %s: Pages %u, %u deleted, %u free; Tuples %.0f: Deleted %.0f.\n\t%s",
-		 RelationGetRelationName(indrel),
-		 stats->num_pages, stats->pages_deleted, stats->pages_free,
-		 stats->num_index_tuples, stats->tuples_removed,
-		 vac_show_rusage(&ru0));
+	ereport(elevel,
+			(errmsg("index \"%s\" now contains %.0f tuples in %u pages",
+					RelationGetRelationName(indrel),
+					stats->num_index_tuples,
+					stats->num_pages),
+			 errdetail("%.0f index tuples were removed.\n"
+					   "%u index pages have been deleted, %u are currently reusable.\n"
+					   "%s",
+					   stats->tuples_removed,
+					   stats->pages_deleted, stats->pages_free,
+					   vac_show_rusage(&ru0))));
 
 	pfree(stats);
 }
@@ -712,8 +733,7 @@ lazy_truncate_heap(Relation onerel, LVRelStats *vacrelstats)
 	 */
 	i = FlushRelationBuffers(onerel, new_rel_pages);
 	if (i < 0)
-		elog(ERROR, "VACUUM (lazy_truncate_heap): FlushRelationBuffers returned %d",
-			 i);
+		elog(ERROR, "FlushRelationBuffers returned %d", i);
 
 	/*
 	 * Do the physical truncation.
@@ -747,8 +767,12 @@ lazy_truncate_heap(Relation onerel, LVRelStats *vacrelstats)
 	 * We keep the exclusive lock until commit (perhaps not necessary)?
 	 */
 
-	elog(elevel, "Truncated %u --> %u pages.\n\t%s", old_rel_pages,
-		 new_rel_pages, vac_show_rusage(&ru0));
+	ereport(elevel,
+			(errmsg("\"%s\": truncated %u to %u pages",
+					RelationGetRelationName(onerel),
+					old_rel_pages, new_rel_pages),
+			 errdetail("%s",
+					   vac_show_rusage(&ru0))));
 }
 
 /*
@@ -838,7 +862,7 @@ count_nondeletable_pages(Relation onerel, LVRelStats *vacrelstats)
 					/* This is an expected case during concurrent vacuum */
 					break;
 				default:
-					elog(ERROR, "Unexpected HeapTupleSatisfiesVacuum result");
+					elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
 					break;
 			}
 
diff --git a/src/backend/commands/variable.c b/src/backend/commands/variable.c
index 9a525b14b89c52e9e48700a1d332f5ae5fb1357c..611c493c14f44f9629f70cca07b959c5d66a48e6 100644
--- a/src/backend/commands/variable.c
+++ b/src/backend/commands/variable.c
@@ -9,7 +9,7 @@
  *
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/commands/variable.c,v 1.82 2003/07/17 00:55:37 tgl Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/commands/variable.c,v 1.83 2003/07/20 21:56:34 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -70,7 +70,9 @@ assign_datestyle(const char *value, bool doit, bool interactive)
 		pfree(rawstring);
 		freeList(elemlist);
 		if (interactive)
-			elog(ERROR, "SET DATESTYLE: invalid list syntax");
+			ereport(ERROR,
+					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+					 errmsg("invalid list syntax for datestyle")));
 		return NULL;
 	}
 
@@ -149,7 +151,10 @@ assign_datestyle(const char *value, bool doit, bool interactive)
 		else
 		{
 			if (interactive)
-				elog(ERROR, "SET DATESTYLE: unrecognized keyword %s", tok);
+				ereport(ERROR,
+						(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+						 errmsg("unrecognized datestyle keyword: \"%s\"",
+								tok)));
 			ok = false;
 			break;
 		}
@@ -164,7 +169,9 @@ assign_datestyle(const char *value, bool doit, bool interactive)
 	if (!ok)
 	{
 		if (interactive)
-			elog(ERROR, "SET DATESTYLE: conflicting specifications");
+			ereport(ERROR,
+					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+					 errmsg("conflicting datestyle specifications")));
 		return NULL;
 	}
 
@@ -235,7 +242,7 @@ set_tz(const char *tz)
 	strcpy(tzbuf, "TZ=");
 	strncpy(tzbuf + 3, tz, sizeof(tzbuf) - 4);
 	if (putenv(tzbuf) != 0)		/* shouldn't happen? */
-		elog(LOG, "Unable to set TZ environment variable");
+		elog(LOG, "unable to set TZ environment variable");
 	tzset();
 }
 
@@ -261,7 +268,7 @@ clear_tz(void)
 	{
 		strcpy(tzbuf, "=");
 		if (putenv(tzbuf) != 0)
-			elog(LOG, "Unable to clear TZ environment variable");
+			elog(LOG, "unable to clear TZ environment variable");
 		tzset();
 	}
 }
@@ -293,7 +300,7 @@ clear_tz(void)
  * failure mode of adopting the system-wide default is much better than
  * a silent failure mode of adopting UTC.
  *
- * NB: this must NOT elog(ERROR).  The caller must get control back so that
+ * NB: this must NOT ereport(ERROR).  The caller must get control back so that
  * it can restore the old value of TZ if we don't like the new one.
  */
 static bool
@@ -334,7 +341,7 @@ tzset_succeeded(const char *tz)
  * We need to reject such TZ settings because they'll wreak havoc with our
  * date/time arithmetic.
  *
- * NB: this must NOT elog(ERROR).  The caller must get control back so that
+ * NB: this must NOT ereport(ERROR).  The caller must get control back so that
  * it can restore the old value of TZ if we don't like the new one.
  */
 static bool
@@ -411,7 +418,7 @@ assign_timezone(const char *value, bool doit, bool interactive)
 
 		/*
 		 * Try to parse it.  XXX an invalid interval format will result in
-		 * elog, which is not desirable for GUC.  We did what we could to
+		 * ereport, which is not desirable for GUC.  We did what we could to
 		 * guard against this in flatten_set_variable_args, but a string
 		 * coming in from postgresql.conf might contain anything.
 		 */
@@ -423,7 +430,9 @@ assign_timezone(const char *value, bool doit, bool interactive)
 		if (interval->month != 0)
 		{
 			if (interactive)
-				elog(ERROR, "SET TIME ZONE: illegal INTERVAL; month not allowed");
+				ereport(ERROR,
+						(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+						 errmsg("invalid INTERVAL for time zone: month not allowed")));
 			pfree(interval);
 			return NULL;
 		}
@@ -528,17 +537,19 @@ assign_timezone(const char *value, bool doit, bool interactive)
 				/* Complain if it was bad */
 				if (!known)
 				{
-					elog(interactive ? ERROR : LOG,
-						 "unrecognized timezone name \"%s\"",
-						 value);
+					ereport(interactive ? ERROR : LOG,
+							(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+							 errmsg("unrecognized timezone name: \"%s\"",
+									value)));
 					return NULL;
 				}
 				if (!acceptable)
 				{
-					elog(interactive ? ERROR : LOG,
-						 "timezone \"%s\" appears to use leap seconds"
-						 "\n\tPostgreSQL does not support leap seconds",
-						 value);
+					ereport(interactive ? ERROR : LOG,
+							(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+							 errmsg("timezone \"%s\" appears to use leap seconds",
+									value),
+							 errdetail("PostgreSQL does not support leap seconds")));
 					return NULL;
 				}
 			}
@@ -605,7 +616,9 @@ const char *
 assign_XactIsoLevel(const char *value, bool doit, bool interactive)
 {
 	if (doit && interactive && SerializableSnapshot != NULL)
-		elog(ERROR, "SET TRANSACTION ISOLATION LEVEL must be called before any query");
+		ereport(ERROR,
+				(errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
+				 errmsg("SET TRANSACTION ISOLATION LEVEL must be called before any query")));
 
 	if (strcmp(value, "serializable") == 0)
 	{
@@ -680,8 +693,10 @@ assign_client_encoding(const char *value, bool doit, bool interactive)
 	if (SetClientEncoding(encoding, doit) < 0)
 	{
 		if (interactive)
-			elog(ERROR, "Conversion between %s and %s is not supported",
-				 value, GetDatabaseEncodingName());
+			ereport(ERROR,
+					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+					 errmsg("conversion between \"%s\" and \"%s\" is not supported",
+							value, GetDatabaseEncodingName())));
 		return NULL;
 	}
 	return value;
@@ -743,7 +758,9 @@ assign_session_authorization(const char *value, bool doit, bool interactive)
 		if (!HeapTupleIsValid(userTup))
 		{
 			if (interactive)
-				elog(ERROR, "user \"%s\" does not exist", value);
+				ereport(ERROR,
+						(errcode(ERRCODE_UNDEFINED_OBJECT),
+						 errmsg("user \"%s\" does not exist", value)));
 			return NULL;
 		}
 
diff --git a/src/backend/commands/view.c b/src/backend/commands/view.c
index 329fd3146bb6000e0e590a023f19b20706545c92..2319e400f1fa9e843178bc1634427ba899f2cbb2 100644
--- a/src/backend/commands/view.c
+++ b/src/backend/commands/view.c
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/commands/view.c,v 1.73 2002/11/11 22:19:22 tgl Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/commands/view.c,v 1.74 2003/07/20 21:56:34 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -84,7 +84,9 @@ DefineVirtualRelation(const RangeVar *relation, List *tlist, bool replace)
 	}
 
 	if (attrList == NIL)
-		elog(ERROR, "attempted to define virtual relation with no attrs");
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
+				 errmsg("view must have at least one attribute")));
 
 	/*
 	 * Check to see if we want to replace an existing view.
@@ -106,8 +108,10 @@ DefineVirtualRelation(const RangeVar *relation, List *tlist, bool replace)
 		 * Make sure it *is* a view, and do permissions checks.
 		 */
 		if (rel->rd_rel->relkind != RELKIND_VIEW)
-			elog(ERROR, "%s is not a view",
-				 RelationGetRelationName(rel));
+			ereport(ERROR,
+					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+					 errmsg("\"%s\" is not a view",
+							RelationGetRelationName(rel))));
 
 		if (!pg_class_ownercheck(viewOid, GetUserId()))
 			aclcheck_error(ACLCHECK_NOT_OWNER, RelationGetRelationName(rel));
@@ -159,7 +163,9 @@ checkViewTupleDesc(TupleDesc newdesc, TupleDesc olddesc)
 	int			i;
 
 	if (newdesc->natts != olddesc->natts)
-		elog(ERROR, "Cannot change number of columns in view");
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
+				 errmsg("cannot change number of columns in view")));
 	/* we can ignore tdhasoid */
 
 	for (i = 0; i < newdesc->natts; i++)
@@ -169,16 +175,22 @@ checkViewTupleDesc(TupleDesc newdesc, TupleDesc olddesc)
 
 		/* XXX not right, but we don't support DROP COL on view anyway */
 		if (newattr->attisdropped != oldattr->attisdropped)
-			elog(ERROR, "Cannot change number of columns in view");
+			ereport(ERROR,
+					(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
+					 errmsg("cannot change number of columns in view")));
 
 		if (strcmp(NameStr(newattr->attname), NameStr(oldattr->attname)) != 0)
-			elog(ERROR, "Cannot change name of view column \"%s\"",
-				 NameStr(oldattr->attname));
+			ereport(ERROR,
+					(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
+					 errmsg("cannot change name of view column \"%s\"",
+							NameStr(oldattr->attname))));
 		/* XXX would it be safe to allow atttypmod to change?  Not sure */
 		if (newattr->atttypid != oldattr->atttypid ||
 			newattr->atttypmod != oldattr->atttypmod)
-			elog(ERROR, "Cannot change datatype of view column \"%s\"",
-				 NameStr(oldattr->attname));
+			ereport(ERROR,
+					(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
+					 errmsg("cannot change datatype of view column \"%s\"",
+							NameStr(oldattr->attname))));
 		/* We can ignore the remaining attributes of an attribute... */
 	}
 
diff --git a/src/backend/optimizer/prep/prepunion.c b/src/backend/optimizer/prep/prepunion.c
index d14c3c98e1f3f47fd68d93e44fdc5bffb54517ba..029227a4ca62418b33b845f80c6e930eddc1f100 100644
--- a/src/backend/optimizer/prep/prepunion.c
+++ b/src/backend/optimizer/prep/prepunion.c
@@ -14,7 +14,7 @@
  *
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/optimizer/prep/prepunion.c,v 1.98 2003/07/16 17:25:48 tgl Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/optimizer/prep/prepunion.c,v 1.99 2003/07/20 21:56:34 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -816,8 +816,8 @@ adjust_inherited_attrs_mutator(Node *node,
 
 				var->varattno = get_attnum(context->new_relid, attname);
 				if (var->varattno == InvalidAttrNumber)
-					elog(ERROR, "Relation \"%s\" has no column \"%s\"",
-						 get_rel_name(context->new_relid), attname);
+					elog(ERROR, "attribute \"%s\" of relation \"%s\" does not exist",
+						 attname, get_rel_name(context->new_relid));
 				var->varoattno = var->varattno;
 				pfree(attname);
 			}
@@ -994,8 +994,8 @@ adjust_inherited_tlist(List *tlist, Oid new_relid)
 
 		attrno = get_attnum(new_relid, resdom->resname);
 		if (attrno == InvalidAttrNumber)
-			elog(ERROR, "Relation \"%s\" has no column \"%s\"",
-				 get_rel_name(new_relid), resdom->resname);
+			elog(ERROR, "attribute \"%s\" of relation \"%s\" does not exist",
+				 resdom->resname, get_rel_name(new_relid));
 		if (resdom->resno != attrno)
 		{
 			resdom = (Resdom *) copyObject((Node *) resdom);
diff --git a/src/backend/parser/parse_func.c b/src/backend/parser/parse_func.c
index 4f90cecf2c6174d4b95d3ecb21e93eb628fa6482..b2ae0cc9271904340cac3d5abcd5ecff4144e167 100644
--- a/src/backend/parser/parse_func.c
+++ b/src/backend/parser/parse_func.c
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/parser/parse_func.c,v 1.155 2003/07/19 20:20:52 tgl Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/parser/parse_func.c,v 1.156 2003/07/20 21:56:34 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -1263,8 +1263,8 @@ setup_field_select(Node *input, char *attname, Oid relid)
 	if (attno == InvalidAttrNumber)
 		ereport(ERROR,
 				(errcode(ERRCODE_UNDEFINED_COLUMN),
-				 errmsg("relation \"%s\" has no column \"%s\"",
-						get_rel_name(relid), attname)));
+				 errmsg("attribute \"%s\" of relation \"%s\" does not exist",
+						attname, get_rel_name(relid))));
 
 	fselect->arg = (Expr *) input;
 	fselect->fieldnum = attno;
@@ -1356,7 +1356,7 @@ unknown_attribute(const char *schemaname, const char *relname,
 }
 
 /*
- * func_signature_string
+ * funcname_signature_string
  *		Build a string representing a function name, including arg types.
  *		The result is something like "foo(integer)".
  *
@@ -1364,14 +1364,15 @@ unknown_attribute(const char *schemaname, const char *relname,
  * messages.
  */
 const char *
-func_signature_string(List *funcname, int nargs, const Oid *argtypes)
+funcname_signature_string(const char *funcname,
+						  int nargs, const Oid *argtypes)
 {
 	StringInfoData argbuf;
 	int			i;
 
 	initStringInfo(&argbuf);
 
-	appendStringInfo(&argbuf, "%s(", NameListToString(funcname));
+	appendStringInfo(&argbuf, "%s(", funcname);
 
 	for (i = 0; i < nargs; i++)
 	{
@@ -1385,6 +1386,17 @@ func_signature_string(List *funcname, int nargs, const Oid *argtypes)
 	return argbuf.data;			/* return palloc'd string buffer */
 }
 
+/*
+ * func_signature_string
+ *		As above, but function name is passed as a qualified name list.
+ */
+const char *
+func_signature_string(List *funcname, int nargs, const Oid *argtypes)
+{
+	return funcname_signature_string(NameListToString(funcname),
+									 nargs, argtypes);
+}
+
 /*
  * find_aggregate_func
  *		Convenience routine to check that a function exists and is an
diff --git a/src/backend/parser/parse_relation.c b/src/backend/parser/parse_relation.c
index 85f813f10a17da5cb5d1e5aefbb36dd93fa0422e..732699e3ad766c838a4b1788e6da8ad0ae92a529 100644
--- a/src/backend/parser/parse_relation.c
+++ b/src/backend/parser/parse_relation.c
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/parser/parse_relation.c,v 1.84 2003/07/19 20:20:52 tgl Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/parser/parse_relation.c,v 1.85 2003/07/20 21:56:35 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -1587,9 +1587,9 @@ get_rte_attribute_type(RangeTblEntry *rte, AttrNumber attnum,
 				if (att_tup->attisdropped)
 					ereport(ERROR,
 							(errcode(ERRCODE_UNDEFINED_COLUMN),
-							 errmsg("relation \"%s\" has no column \"%s\"",
-									get_rel_name(rte->relid),
-									NameStr(att_tup->attname))));
+							 errmsg("attribute \"%s\" of relation \"%s\" does not exist",
+									NameStr(att_tup->attname),
+									get_rel_name(rte->relid))));
 				*vartype = att_tup->atttypid;
 				*vartypmod = att_tup->atttypmod;
 				ReleaseSysCache(tp);
@@ -1652,9 +1652,9 @@ get_rte_attribute_type(RangeTblEntry *rte, AttrNumber attnum,
 					if (att_tup->attisdropped)
 						ereport(ERROR,
 								(errcode(ERRCODE_UNDEFINED_COLUMN),
-								 errmsg("relation \"%s\" has no column \"%s\"",
-										get_rel_name(funcrelid),
-										NameStr(att_tup->attname))));
+								 errmsg("attribute \"%s\" of relation \"%s\" does not exist",
+										NameStr(att_tup->attname),
+										get_rel_name(funcrelid))));
 					*vartype = att_tup->atttypid;
 					*vartypmod = att_tup->atttypmod;
 					ReleaseSysCache(tp);
@@ -1808,8 +1808,8 @@ attnameAttNum(Relation rd, const char *attname, bool sysColOK)
 	/* on failure */
 	ereport(ERROR,
 			(errcode(ERRCODE_UNDEFINED_COLUMN),
-			 errmsg("relation \"%s\" has no column \"%s\"",
-					RelationGetRelationName(rd), attname)));
+			 errmsg("attribute \"%s\" of relation \"%s\" does not exist",
+					attname, RelationGetRelationName(rd))));
 	return InvalidAttrNumber;	/* keep compiler quiet */
 }
 
diff --git a/src/backend/parser/parse_type.c b/src/backend/parser/parse_type.c
index 78fe52d00b1b91635174d90a1f43bd406fcd2563..5d68ef14a5b87c5d2712c9a83923e1adf484168b 100644
--- a/src/backend/parser/parse_type.c
+++ b/src/backend/parser/parse_type.c
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/parser/parse_type.c,v 1.58 2003/07/19 20:20:52 tgl Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/parser/parse_type.c,v 1.59 2003/07/20 21:56:35 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -91,8 +91,8 @@ LookupTypeName(const TypeName *typename)
 		if (attnum == InvalidAttrNumber)
 			ereport(ERROR,
 					(errcode(ERRCODE_UNDEFINED_COLUMN),
-					 errmsg("relation \"%s\" has no column \"%s\"",
-							rel->relname, field)));
+					 errmsg("attribute \"%s\" of relation \"%s\" does not exist",
+							field, rel->relname)));
 		restype = get_atttype(relid, attnum);
 
 		/* this construct should never have an array indicator */
diff --git a/src/include/parser/parse_func.h b/src/include/parser/parse_func.h
index a5beb2368d2d1e5562e84d7c41ac23993a4c0284..d4046b988f088f9f34aefd1185fbdf71a6079ba6 100644
--- a/src/include/parser/parse_func.h
+++ b/src/include/parser/parse_func.h
@@ -7,7 +7,7 @@
  * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
  * Portions Copyright (c) 1994, Regents of the University of California
  *
- * $Id: parse_func.h,v 1.47 2003/07/04 02:51:34 tgl Exp $
+ * $Id: parse_func.h,v 1.48 2003/07/20 21:56:35 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -66,6 +66,8 @@ extern void make_fn_arguments(ParseState *pstate,
 							  Oid *actual_arg_types,
 							  Oid *declared_arg_types);
 
+extern const char *funcname_signature_string(const char *funcname,
+											 int nargs, const Oid *argtypes);
 extern const char *func_signature_string(List *funcname,
 										 int nargs, const Oid *argtypes);
 
diff --git a/src/include/utils/elog.h b/src/include/utils/elog.h
index ef6e50de55f256093ff33ae08f509e4ea4cdb2f2..9e497052d2fea0c2db96e9da8ebf6bdbe21b9288 100644
--- a/src/include/utils/elog.h
+++ b/src/include/utils/elog.h
@@ -7,7 +7,7 @@
  * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
  * Portions Copyright (c) 1994, Regents of the University of California
  *
- * $Id: elog.h,v 1.49 2003/07/19 20:20:52 tgl Exp $
+ * $Id: elog.h,v 1.50 2003/07/20 21:56:35 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -97,6 +97,7 @@
 #define ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION		MAKE_SQLSTATE('0','8', '0','0','1')
 #define ERRCODE_SQLSERVER_REJECTED_ESTABLISHMENT_OF_SQLCONNECTION	MAKE_SQLSTATE('0','8', '0','0','4')
 #define ERRCODE_TRANSACTION_RESOLUTION_UNKNOWN		MAKE_SQLSTATE('0','8', '0','0','7')
+#define ERRCODE_PROTOCOL_VIOLATION			MAKE_SQLSTATE('0','8', 'P','0','1')
 
 /* Class 0A - Feature Not Supported */
 #define ERRCODE_FEATURE_NOT_SUPPORTED		MAKE_SQLSTATE('0','A', '0','0','0')
@@ -106,7 +107,7 @@
 
 /* Class 0F - Locator Exception */
 #define ERRCODE_LOCATOR_EXCEPTION			MAKE_SQLSTATE('0','F', '0','0','0')
-#define ERRCODE_LOCATOR_EXCEPTION_INVALID_SPECIFICATION		MAKE_SQLSTATE('0','F', '0','0','1')
+#define ERRCODE_L_E_INVALID_SPECIFICATION	MAKE_SQLSTATE('0','F', '0','0','1')
 
 /* Class 0L - Invalid Grantor */
 #define ERRCODE_INVALID_GRANTOR				MAKE_SQLSTATE('0','L', '0','0','0')
@@ -149,10 +150,15 @@
 #define ERRCODE_TRIM_ERROR					MAKE_SQLSTATE('2','2', '0','2','7')
 #define ERRCODE_UNTERMINATED_C_STRING		MAKE_SQLSTATE('2','2', '0','2','4')
 #define ERRCODE_ZERO_LENGTH_CHARACTER_STRING		MAKE_SQLSTATE('2','2', '0','0','F')
+#define ERRCODE_BAD_COPY_FILE_FORMAT		MAKE_SQLSTATE('2','2', 'P','0','1')
 
 /* Class 23 - Integrity Constraint Violation */
 #define ERRCODE_INTEGRITY_CONSTRAINT_VIOLATION		MAKE_SQLSTATE('2','3', '0','0','0')
 #define ERRCODE_RESTRICT_VIOLATION			MAKE_SQLSTATE('2','3', '0','0','1')
+#define ERRCODE_NOT_NULL_VIOLATION			MAKE_SQLSTATE('2','3', '5','0','2')
+#define ERRCODE_FOREIGN_KEY_VALUE_NOT_FOUND	MAKE_SQLSTATE('2','3', '5','0','3')
+#define ERRCODE_UNIQUE_VIOLATION			MAKE_SQLSTATE('2','3', '5','0','5')
+#define ERRCODE_CHECK_VIOLATION				MAKE_SQLSTATE('2','3', '5','1','4')
 
 /* Class 24 - Invalid Cursor State */
 #define ERRCODE_INVALID_CURSOR_STATE		MAKE_SQLSTATE('2','4', '0','0','0')
@@ -186,25 +192,26 @@
 
 /* Class 2F - SQL Routine Exception */
 #define ERRCODE_SQL_ROUTINE_EXCEPTION		MAKE_SQLSTATE('2','F', '0','0','0')
-#define ERRCODE_FUNCTION_EXECUTED_NO_RETURN_STATEMENT		MAKE_SQLSTATE('2','F', '0','0','5')
-#define ERRCODE_MODIFYING_SQL_DATA_NOT_PERMITTED	MAKE_SQLSTATE('2','F', '0','0','2')
-#define ERRCODE_PROHIBITED_SQL_STATEMENT_ATTEMPTED	MAKE_SQLSTATE('2','F', '0','0','3')
-#define ERRCODE_READING_SQL_DATA_NOT_PERMITTED		MAKE_SQLSTATE('2','F', '0','0','4')
+#define ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT	MAKE_SQLSTATE('2','F', '0','0','5')
+#define ERRCODE_S_R_E_MODIFYING_SQL_DATA_NOT_PERMITTED		MAKE_SQLSTATE('2','F', '0','0','2')
+#define ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED	MAKE_SQLSTATE('2','F', '0','0','3')
+#define ERRCODE_S_R_E_READING_SQL_DATA_NOT_PERMITTED		MAKE_SQLSTATE('2','F', '0','0','4')
 
 /* Class 34 - Invalid Cursor Name */
 #define ERRCODE_INVALID_CURSOR_NAME			MAKE_SQLSTATE('3','4', '0','0','0')
 
 /* Class 38 - External Routine Exception */
 #define ERRCODE_EXTERNAL_ROUTINE_EXCEPTION	MAKE_SQLSTATE('3','8', '0','0','0')
-#define ERRCODE_EXTERNAL_ROUTINE_EXCEPTION_CONTAINING_SQL_NOT_PERMITTED	MAKE_SQLSTATE('3','8', '0','0','1')
-#define ERRCODE_EXTERNAL_ROUTINE_EXCEPTION_MODIFYING_SQL_DATA_NOT_PERMITTED	MAKE_SQLSTATE('3','8', '0','0','2')
-#define ERRCODE_EXTERNAL_ROUTINE_EXCEPTION_PROHIBITED_SQL_STATEMENT_ATTEMPTED	MAKE_SQLSTATE('3','8', '0','0','3')
-#define ERRCODE_EXTERNAL_ROUTINE_EXCEPTION_READING_SQL_DATA_NOT_PERMITTED	MAKE_SQLSTATE('3','8', '0','0','4')
+#define ERRCODE_E_R_E_CONTAINING_SQL_NOT_PERMITTED	MAKE_SQLSTATE('3','8', '0','0','1')
+#define ERRCODE_E_R_E_MODIFYING_SQL_DATA_NOT_PERMITTED	MAKE_SQLSTATE('3','8', '0','0','2')
+#define ERRCODE_E_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED	MAKE_SQLSTATE('3','8', '0','0','3')
+#define ERRCODE_E_R_E_READING_SQL_DATA_NOT_PERMITTED	MAKE_SQLSTATE('3','8', '0','0','4')
 
 /* Class 39 - External Routine Invocation Exception */
 #define ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION	MAKE_SQLSTATE('3','9', '0','0','0')
-#define ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION_INVALID_SQLSTATE_RETURNED	MAKE_SQLSTATE('3','9', '0','0','1')
-#define ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION_NULL_VALUE_NOT_ALLOWED	MAKE_SQLSTATE('3','9', '0','0','4')
+#define ERRCODE_E_R_I_E_INVALID_SQLSTATE_RETURNED	MAKE_SQLSTATE('3','9', '0','0','1')
+#define ERRCODE_E_R_I_E_NULL_VALUE_NOT_ALLOWED	MAKE_SQLSTATE('3','9', '0','0','4')
+#define ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED	MAKE_SQLSTATE('3','9', 'P','0','1')
 
 /* Class 3D - Invalid Catalog Name */
 #define ERRCODE_INVALID_CATALOG_NAME		MAKE_SQLSTATE('3','D', '0','0','0')
@@ -214,9 +221,9 @@
 
 /* Class 40 - Transaction Rollback */
 #define ERRCODE_TRANSACTION_ROLLBACK		MAKE_SQLSTATE('4','0', '0','0','0')
-#define ERRCODE_TRANSACTION_ROLLBACK_INTEGRITY_CONSTRAINT_VIOLATION	MAKE_SQLSTATE('4','0', '0','0','2')
-#define ERRCODE_TRANSACTION_ROLLBACK_SERIALIZATION_FAILURE	MAKE_SQLSTATE('4','0', '0','0','1')
-#define ERRCODE_TRANSACTION_ROLLBACK_STATEMENT_COMPLETION_UNKNOWN	MAKE_SQLSTATE('4','0', '0','0','3')
+#define ERRCODE_T_R_INTEGRITY_CONSTRAINT_VIOLATION	MAKE_SQLSTATE('4','0', '0','0','2')
+#define ERRCODE_T_R_SERIALIZATION_FAILURE	MAKE_SQLSTATE('4','0', '0','0','1')
+#define ERRCODE_T_R_STATEMENT_COMPLETION_UNKNOWN	MAKE_SQLSTATE('4','0', '0','0','3')
 
 /* Class 42 - Syntax Error or Access Rule Violation */
 #define ERRCODE_SYNTAX_ERROR_OR_ACCESS_RULE_VIOLATION		MAKE_SQLSTATE('4','2', '0','0','0')
@@ -294,6 +301,7 @@
 /* Class 55 - Object Not In Prerequisite State (class borrowed from DB2) */
 #define ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE	MAKE_SQLSTATE('5','5', '0','0','0')
 #define ERRCODE_OBJECT_IN_USE				MAKE_SQLSTATE('5','5', '0','0','6')
+#define ERRCODE_INDEXES_DEACTIVATED			MAKE_SQLSTATE('5','5', 'P','0','1')
 
 /* Class 57 - Operator Intervention (class borrowed from DB2) */
 #define ERRCODE_OPERATOR_INTERVENTION		MAKE_SQLSTATE('5','7', '0','0','0')
diff --git a/src/test/regress/expected/alter_table.out b/src/test/regress/expected/alter_table.out
index b11ab43487463a55c5400c80f20903b24e735769..234a3937545430a6c0d7819dfada4f3924d99cfb 100644
--- a/src/test/regress/expected/alter_table.out
+++ b/src/test/regress/expected/alter_table.out
@@ -308,11 +308,11 @@ INSERT INTO tmp3 values (5,50);
 -- Try (and fail) to add constraint due to invalid source columns
 ALTER TABLE tmp3 add constraint tmpconstr foreign key(c) references tmp2 match full;
 NOTICE:  ALTER TABLE will create implicit trigger(s) for FOREIGN KEY check(s)
-ERROR:  ALTER TABLE: column "c" referenced in foreign key constraint does not exist
+ERROR:  column "c" referenced in foreign key constraint does not exist
 -- Try (and fail) to add constraint due to invalide destination columns explicitly given
 ALTER TABLE tmp3 add constraint tmpconstr foreign key(a) references tmp2(b) match full;
 NOTICE:  ALTER TABLE will create implicit trigger(s) for FOREIGN KEY check(s)
-ERROR:  ALTER TABLE: column "b" referenced in foreign key constraint does not exist
+ERROR:  column "b" referenced in foreign key constraint does not exist
 -- Try (and fail) to add constraint due to invalid data
 ALTER TABLE tmp3 add constraint tmpconstr foreign key (a) references tmp2 match full;
 NOTICE:  ALTER TABLE will create implicit trigger(s) for FOREIGN KEY check(s)
@@ -326,7 +326,7 @@ NOTICE:  ALTER TABLE will create implicit trigger(s) for FOREIGN KEY check(s)
 -- tmp4 is a,b
 ALTER TABLE tmp5 add constraint tmpconstr foreign key(a) references tmp4(a) match full;
 NOTICE:  ALTER TABLE will create implicit trigger(s) for FOREIGN KEY check(s)
-ERROR:  UNIQUE constraint matching given keys for referenced table "tmp4" not found
+ERROR:  there is no UNIQUE constraint matching given keys for referenced table "tmp4"
 DROP TABLE tmp5;
 DROP TABLE tmp4;
 DROP TABLE tmp3;
@@ -409,7 +409,7 @@ create table atacc1 ( test int );
 insert into atacc1 (test) values (2);
 -- add a check constraint (fails)
 alter table atacc1 add constraint atacc_test1 check (test>3);
-ERROR:  AlterTableAddConstraint: rejected due to CHECK constraint atacc_test1
+ERROR:  CHECK constraint "atacc_test1" is violated at some row(s)
 insert into atacc1 (test) values (4);
 drop table atacc1;
 -- let's do one where the check fails because the column doesn't exist
@@ -567,7 +567,7 @@ 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:  ALTER TABLE: Attribute "test" contains NULL values
+ERROR:  attribute "test" contains NULL values
 insert into atacc1 (test) values (3);
 drop table atacc1;
 -- let's do one where the primary key constraint fails
@@ -614,9 +614,9 @@ drop table atacc1;
 -- alter table / alter column [set/drop] not null tests
 -- try altering system catalogs, should fail
 alter table pg_class alter column relname drop not null;
-ERROR:  ALTER TABLE: relation "pg_class" is a system catalog
+ERROR:  "pg_class" is a system catalog
 alter table pg_class alter relname set not null;
-ERROR:  ALTER TABLE: relation "pg_class" is a system catalog
+ERROR:  "pg_class" is a system catalog
 -- try altering non-existent table, should fail
 alter table non_existent alter column bar set not null;
 ERROR:  Relation "non_existent" does not exist
@@ -628,30 +628,30 @@ create table atacc1 (test int not null);
 alter table atacc1 add constraint "atacc1_pkey" primary key (test);
 NOTICE:  ALTER TABLE / ADD PRIMARY KEY will create implicit index "atacc1_pkey" for table "atacc1"
 alter table atacc1 alter column test drop not null;
-ERROR:  ALTER TABLE: Attribute "test" is in a primary key
+ERROR:  attribute "test" is in a primary key
 alter table atacc1 drop constraint "atacc1_pkey";
 alter table atacc1 alter column test drop not null;
 insert into atacc1 values (null);
 alter table atacc1 alter test set not null;
-ERROR:  ALTER TABLE: Attribute "test" contains NULL values
+ERROR:  attribute "test" contains NULL values
 delete from atacc1;
 alter table atacc1 alter test set not null;
 -- try altering a non-existent column, should fail
 alter table atacc1 alter bar set not null;
-ERROR:  Relation "atacc1" has no column "bar"
+ERROR:  attribute "bar" of relation "atacc1" does not exist
 alter table atacc1 alter bar drop not null;
-ERROR:  Relation "atacc1" has no column "bar"
+ERROR:  attribute "bar" of relation "atacc1" does not exist
 -- try altering the oid column, should fail
 alter table atacc1 alter oid set not null;
-ERROR:  ALTER TABLE: Cannot alter system attribute "oid"
+ERROR:  cannot alter system attribute "oid"
 alter table atacc1 alter oid drop not null;
-ERROR:  ALTER TABLE: Cannot alter system attribute "oid"
+ERROR:  cannot alter system attribute "oid"
 -- try creating a view and altering that, should fail
 create view myview as select * from atacc1;
 alter table myview alter column test drop not null;
-ERROR:  ALTER TABLE: relation "myview" is not a table
+ERROR:  "myview" is not a table
 alter table myview alter column test set not null;
-ERROR:  ALTER TABLE: relation "myview" is not a table
+ERROR:  "myview" is not a table
 drop view myview;
 drop table atacc1;
 -- test inheritance
@@ -666,9 +666,9 @@ alter table parent alter a drop not null;
 insert into parent values (NULL);
 insert into child (a, b) values (NULL, 'foo');
 alter table only parent alter a set not null;
-ERROR:  ALTER TABLE: Attribute "a" contains NULL values
+ERROR:  attribute "a" contains NULL values
 alter table child alter a set not null;
-ERROR:  ALTER TABLE: Attribute "a" contains NULL values
+ERROR:  attribute "a" contains NULL values
 delete from parent;
 alter table only parent alter a set not null;
 insert into parent values (NULL);
@@ -710,7 +710,7 @@ ERROR:  pg_atoi: error in "wrong_datatype": can't parse "wrong_datatype"
 alter table def_test alter column c2 set default 20;
 -- set defaults on a non-existent column: this should fail
 alter table def_test alter column c3 set default 30;
-ERROR:  Relation "def_test" has no column "c3"
+ERROR:  attribute "c3" of relation "def_test" does not exist
 -- set defaults on views: we need to create a view, add a rule
 -- to allow insertions into it, and then alter the view to add
 -- a default
@@ -741,7 +741,7 @@ drop table def_test;
 -- alter table / drop column tests
 -- try altering system catalogs, should fail
 alter table pg_class drop column relname;
-ERROR:  ALTER TABLE: relation "pg_class" is a system catalog
+ERROR:  "pg_class" is a system catalog
 -- try altering non-existent table, should fail
 alter table foo drop column bar;
 ERROR:  Relation "foo" does not exist
@@ -750,7 +750,7 @@ create table atacc1 (a int4 not null, b int4, c int4 not null, d int4);
 insert into atacc1 values (1, 2, 3, 4);
 alter table atacc1 drop a;
 alter table atacc1 drop a;
-ERROR:  Relation "atacc1" has no column "a"
+ERROR:  attribute "a" of relation "atacc1" does not exist
 -- SELECTs
 select * from atacc1;
  b | c | d 
@@ -796,11 +796,11 @@ select * from atacc1 where "........pg.dropped.1........" = 1;
 ERROR:  attribute "........pg.dropped.1........" not found
 -- UPDATEs
 update atacc1 set a = 3;
-ERROR:  relation "atacc1" has no column "a"
+ERROR:  attribute "a" of relation "atacc1" does not exist
 update atacc1 set b = 2 where a = 3;
 ERROR:  attribute "a" not found
 update atacc1 set "........pg.dropped.1........" = 3;
-ERROR:  relation "atacc1" has no column "........pg.dropped.1........"
+ERROR:  attribute "........pg.dropped.1........" of relation "atacc1" does not exist
 update atacc1 set b = 2 where "........pg.dropped.1........" = 3;
 ERROR:  attribute "........pg.dropped.1........" not found
 -- INSERTs
@@ -810,22 +810,22 @@ insert into atacc1 values (default, 11, 12, 13);
 ERROR:  INSERT has more expressions than target columns
 insert into atacc1 values (11, 12, 13);
 insert into atacc1 (a) values (10);
-ERROR:  relation "atacc1" has no column "a"
+ERROR:  attribute "a" of relation "atacc1" does not exist
 insert into atacc1 (a) values (default);
-ERROR:  relation "atacc1" has no column "a"
+ERROR:  attribute "a" of relation "atacc1" does not exist
 insert into atacc1 (a,b,c,d) values (10,11,12,13);
-ERROR:  relation "atacc1" has no column "a"
+ERROR:  attribute "a" of relation "atacc1" does not exist
 insert into atacc1 (a,b,c,d) values (default,11,12,13);
-ERROR:  relation "atacc1" has no column "a"
+ERROR:  attribute "a" of relation "atacc1" does not exist
 insert into atacc1 (b,c,d) values (11,12,13);
 insert into atacc1 ("........pg.dropped.1........") values (10);
-ERROR:  relation "atacc1" has no column "........pg.dropped.1........"
+ERROR:  attribute "........pg.dropped.1........" of relation "atacc1" does not exist
 insert into atacc1 ("........pg.dropped.1........") values (default);
-ERROR:  relation "atacc1" has no column "........pg.dropped.1........"
+ERROR:  attribute "........pg.dropped.1........" of relation "atacc1" does not exist
 insert into atacc1 ("........pg.dropped.1........",b,c,d) values (10,11,12,13);
-ERROR:  relation "atacc1" has no column "........pg.dropped.1........"
+ERROR:  attribute "........pg.dropped.1........" of relation "atacc1" does not exist
 insert into atacc1 ("........pg.dropped.1........",b,c,d) values (default,11,12,13);
-ERROR:  relation "atacc1" has no column "........pg.dropped.1........"
+ERROR:  attribute "........pg.dropped.1........" of relation "atacc1" does not exist
 -- DELETEs
 delete from atacc1 where a = 3;
 ERROR:  attribute "a" not found
@@ -834,10 +834,10 @@ ERROR:  attribute "........pg.dropped.1........" not found
 delete from atacc1;
 -- try dropping a non-existent column, should fail
 alter table atacc1 drop bar;
-ERROR:  Relation "atacc1" has no column "bar"
+ERROR:  attribute "bar" of relation "atacc1" does not exist
 -- try dropping the oid column, should fail
 alter table atacc1 drop oid;
-ERROR:  ALTER TABLE: Cannot drop system attribute "oid"
+ERROR:  cannot drop system attribute "oid"
 -- try creating a view and altering that, should fail
 create view myview as select * from atacc1;
 select * from myview;
@@ -846,49 +846,49 @@ select * from myview;
 (0 rows)
 
 alter table myview drop d;
-ERROR:  ALTER TABLE: relation "myview" is not a table
+ERROR:  "myview" is not a table
 drop view myview;
 -- test some commands to make sure they fail on the dropped column
 analyze atacc1(a);
-ERROR:  relation "atacc1" has no column "a"
+ERROR:  attribute "a" of relation "atacc1" does not exist
 analyze atacc1("........pg.dropped.1........");
-ERROR:  relation "atacc1" has no column "........pg.dropped.1........"
+ERROR:  attribute "........pg.dropped.1........" of relation "atacc1" does not exist
 vacuum analyze atacc1(a);
-ERROR:  relation "atacc1" has no column "a"
+ERROR:  attribute "a" of relation "atacc1" does not exist
 vacuum analyze atacc1("........pg.dropped.1........");
-ERROR:  relation "atacc1" has no column "........pg.dropped.1........"
+ERROR:  attribute "........pg.dropped.1........" of relation "atacc1" does not exist
 comment on column atacc1.a is 'testing';
-ERROR:  Relation "atacc1" has no column "a"
+ERROR:  attribute "a" of relation "atacc1" does not exist
 comment on column atacc1."........pg.dropped.1........" is 'testing';
-ERROR:  Relation "atacc1" has no column "........pg.dropped.1........"
+ERROR:  attribute "........pg.dropped.1........" of relation "atacc1" does not exist
 alter table atacc1 alter a set storage plain;
-ERROR:  ALTER TABLE: relation "atacc1" has no column "a"
+ERROR:  attribute "a" of relation "atacc1" does not exist
 alter table atacc1 alter "........pg.dropped.1........" set storage plain;
-ERROR:  ALTER TABLE: relation "atacc1" has no column "........pg.dropped.1........"
+ERROR:  attribute "........pg.dropped.1........" of relation "atacc1" does not exist
 alter table atacc1 alter a set statistics 0;
-ERROR:  ALTER TABLE: relation "atacc1" has no column "a"
+ERROR:  attribute "a" of relation "atacc1" does not exist
 alter table atacc1 alter "........pg.dropped.1........" set statistics 0;
-ERROR:  ALTER TABLE: relation "atacc1" has no column "........pg.dropped.1........"
+ERROR:  attribute "........pg.dropped.1........" of relation "atacc1" does not exist
 alter table atacc1 alter a set default 3;
-ERROR:  Relation "atacc1" has no column "a"
+ERROR:  attribute "a" of relation "atacc1" does not exist
 alter table atacc1 alter "........pg.dropped.1........" set default 3;
-ERROR:  Relation "atacc1" has no column "........pg.dropped.1........"
+ERROR:  attribute "........pg.dropped.1........" of relation "atacc1" does not exist
 alter table atacc1 alter a drop default;
-ERROR:  Relation "atacc1" has no column "a"
+ERROR:  attribute "a" of relation "atacc1" does not exist
 alter table atacc1 alter "........pg.dropped.1........" drop default;
-ERROR:  Relation "atacc1" has no column "........pg.dropped.1........"
+ERROR:  attribute "........pg.dropped.1........" of relation "atacc1" does not exist
 alter table atacc1 alter a set not null;
-ERROR:  Relation "atacc1" has no column "a"
+ERROR:  attribute "a" of relation "atacc1" does not exist
 alter table atacc1 alter "........pg.dropped.1........" set not null;
-ERROR:  Relation "atacc1" has no column "........pg.dropped.1........"
+ERROR:  attribute "........pg.dropped.1........" of relation "atacc1" does not exist
 alter table atacc1 alter a drop not null;
-ERROR:  Relation "atacc1" has no column "a"
+ERROR:  attribute "a" of relation "atacc1" does not exist
 alter table atacc1 alter "........pg.dropped.1........" drop not null;
-ERROR:  Relation "atacc1" has no column "........pg.dropped.1........"
+ERROR:  attribute "........pg.dropped.1........" of relation "atacc1" does not exist
 alter table atacc1 rename a to x;
-ERROR:  renameatt: attribute "a" does not exist
+ERROR:  attribute "a" does not exist
 alter table atacc1 rename "........pg.dropped.1........" to x;
-ERROR:  renameatt: attribute "........pg.dropped.1........" does not exist
+ERROR:  attribute "........pg.dropped.1........" does not exist
 alter table atacc1 add primary key(a);
 ERROR:  column "a" named in key does not exist
 alter table atacc1 add primary key("........pg.dropped.1........");
@@ -905,21 +905,21 @@ create table atacc2 (id int4 unique);
 NOTICE:  CREATE TABLE / UNIQUE will create implicit index "atacc2_id_key" for table "atacc2"
 alter table atacc1 add foreign key (a) references atacc2(id);
 NOTICE:  ALTER TABLE will create implicit trigger(s) for FOREIGN KEY check(s)
-ERROR:  ALTER TABLE: column "a" referenced in foreign key constraint does not exist
+ERROR:  column "a" referenced in foreign key constraint does not exist
 alter table atacc1 add foreign key ("........pg.dropped.1........") references atacc2(id);
 NOTICE:  ALTER TABLE will create implicit trigger(s) for FOREIGN KEY check(s)
-ERROR:  ALTER TABLE: column "........pg.dropped.1........" referenced in foreign key constraint does not exist
+ERROR:  column "........pg.dropped.1........" referenced in foreign key constraint does not exist
 alter table atacc2 add foreign key (id) references atacc1(a);
 NOTICE:  ALTER TABLE will create implicit trigger(s) for FOREIGN KEY check(s)
-ERROR:  ALTER TABLE: column "a" referenced in foreign key constraint does not exist
+ERROR:  column "a" referenced in foreign key constraint does not exist
 alter table atacc2 add foreign key (id) references atacc1("........pg.dropped.1........");
 NOTICE:  ALTER TABLE will create implicit trigger(s) for FOREIGN KEY check(s)
-ERROR:  ALTER TABLE: column "........pg.dropped.1........" referenced in foreign key constraint does not exist
+ERROR:  column "........pg.dropped.1........" referenced in foreign key constraint does not exist
 drop table atacc2;
 create index "testing_idx" on atacc1(a);
-ERROR:  DefineIndex: attribute "a" not found
+ERROR:  attribute "a" does not exist
 create index "testing_idx" on atacc1("........pg.dropped.1........");
-ERROR:  DefineIndex: attribute "........pg.dropped.1........" not found
+ERROR:  attribute "........pg.dropped.1........" does not exist
 -- test create as and select into
 insert into atacc1 values (21, 22, 23);
 create table test1 as select * from atacc1;
@@ -990,11 +990,11 @@ alter table test drop a;
 copy test to stdout;
 2	3
 copy test(a) to stdout;
-ERROR:  relation "test" has no column "a"
+ERROR:  attribute "a" of relation "test" does not exist
 copy test("........pg.dropped.1........") to stdout;
-ERROR:  relation "test" has no column "........pg.dropped.1........"
+ERROR:  attribute "........pg.dropped.1........" of relation "test" does not exist
 copy test from stdin;
-ERROR:  Extra data after last expected column
+ERROR:  extra data after last expected column
 CONTEXT:  COPY FROM, line 1
 select * from test;
  b | c 
@@ -1011,9 +1011,9 @@ select * from test;
 (2 rows)
 
 copy test(a) from stdin;
-ERROR:  relation "test" has no column "a"
+ERROR:  attribute "a" of relation "test" does not exist
 copy test("........pg.dropped.1........") from stdin;
-ERROR:  relation "test" has no column "........pg.dropped.1........"
+ERROR:  attribute "........pg.dropped.1........" of relation "test" does not exist
 copy test(b,c) from stdin;
 select * from test;
  b  | c  
@@ -1030,9 +1030,9 @@ create table dropColumnChild (c int) inherits (dropColumn);
 create table dropColumnAnother (d int) inherits (dropColumnChild);
 -- these two should fail
 alter table dropColumnchild drop column a;
-ERROR:  ALTER TABLE: Cannot drop inherited column "a"
+ERROR:  cannot drop inherited attribute "a"
 alter table only dropColumnChild drop column b;
-ERROR:  ALTER TABLE: Cannot drop inherited column "b"
+ERROR:  cannot drop inherited attribute "b"
 -- these three should work
 alter table only dropColumn drop column e;
 alter table dropColumnChild drop column c;
@@ -1042,11 +1042,11 @@ create table renameColumnChild (b int) inherits (renameColumn);
 create table renameColumnAnother (c int) inherits (renameColumnChild);
 -- these three should fail
 alter table renameColumnChild rename column a to d;
-ERROR:  renameatt: inherited attribute "a" may not be renamed
+ERROR:  cannot rename inherited attribute "a"
 alter table only renameColumnChild rename column a to d;
-ERROR:  Inherited attribute "a" must be renamed in child tables too
+ERROR:  inherited attribute "a" must be renamed in child tables too
 alter table only renameColumn rename column a to d;
-ERROR:  Inherited attribute "a" must be renamed in child tables too
+ERROR:  inherited attribute "a" must be renamed in child tables too
 -- these should work
 alter table renameColumn rename column a to d;
 alter table renameColumnChild rename column b to a;
@@ -1054,14 +1054,14 @@ alter table renameColumnChild rename column b to a;
 alter table renameColumn add column w int;
 -- this should fail
 alter table only renameColumn add column x int;
-ERROR:  Attribute must be added to child tables too
+ERROR:  attribute must be added to child tables too
 -- Test corner cases in dropping of inherited columns
 create table p1 (f1 int, f2 int);
 create table c1 (f1 int not null) inherits(p1);
-NOTICE:  CREATE TABLE: merging attribute "f1" with inherited definition
+NOTICE:  merging attribute "f1" with inherited definition
 -- should be rejected since c1.f1 is inherited
 alter table c1 drop column f1;
-ERROR:  ALTER TABLE: Cannot drop inherited column "f1"
+ERROR:  cannot drop inherited attribute "f1"
 -- should work
 alter table p1 drop column f1;
 -- c1.f1 is still there, but no longer inherited
@@ -1079,7 +1079,7 @@ create table p1 (f1 int, f2 int);
 create table c1 () inherits(p1);
 -- should be rejected since c1.f1 is inherited
 alter table c1 drop column f1;
-ERROR:  ALTER TABLE: Cannot drop inherited column "f1"
+ERROR:  cannot drop inherited attribute "f1"
 alter table p1 drop column f1;
 -- c1.f1 is dropped now, since there is no local definition for it
 select f1 from c1;
@@ -1090,7 +1090,7 @@ create table p1 (f1 int, f2 int);
 create table c1 () inherits(p1);
 -- should be rejected since c1.f1 is inherited
 alter table c1 drop column f1;
-ERROR:  ALTER TABLE: Cannot drop inherited column "f1"
+ERROR:  cannot drop inherited attribute "f1"
 alter table only p1 drop column f1;
 -- c1.f1 is NOT dropped, but must now be considered non-inherited
 alter table c1 drop column f1;
@@ -1098,10 +1098,10 @@ drop table p1 cascade;
 NOTICE:  Drop cascades to table c1
 create table p1 (f1 int, f2 int);
 create table c1 (f1 int not null) inherits(p1);
-NOTICE:  CREATE TABLE: merging attribute "f1" with inherited definition
+NOTICE:  merging attribute "f1" with inherited definition
 -- should be rejected since c1.f1 is inherited
 alter table c1 drop column f1;
-ERROR:  ALTER TABLE: Cannot drop inherited column "f1"
+ERROR:  cannot drop inherited attribute "f1"
 alter table only p1 drop column f1;
 -- c1.f1 is still there, but no longer inherited
 alter table c1 drop column f1;
@@ -1110,7 +1110,7 @@ NOTICE:  Drop cascades to table c1
 create table p1(id int, name text);
 create table p2(id2 int, name text, height int);
 create table c1(age int) inherits(p1,p2);
-NOTICE:  CREATE TABLE: merging multiple inherited definitions of attribute "name"
+NOTICE:  merging multiple inherited definitions of attribute "name"
 create table gc1() inherits (c1);
 select relname, attname, attinhcount, attislocal
 from pg_class join pg_attribute on (pg_class.oid = pg_attribute.attrelid)
@@ -1141,12 +1141,12 @@ alter table only p1 drop column name;
 alter table p2 drop column name;
 -- should be rejected since its inherited
 alter table gc1 drop column name;
-ERROR:  ALTER TABLE: Cannot drop inherited column "name"
+ERROR:  cannot drop inherited attribute "name"
 -- should work, and drop gc1.name along
 alter table c1 drop column name;
 -- should fail: column does not exist
 alter table gc1 drop column name;
-ERROR:  Relation "gc1" has no column "name"
+ERROR:  attribute "name" of relation "gc1" does not exist
 -- should work and drop the attribute in all tables
 alter table p2 drop column height;
 select relname, attname, attinhcount, attislocal
@@ -1207,7 +1207,7 @@ select oid > 0, * from altinhoid;
 
 alter table altwithoid set without oids;
 alter table altinhoid set without oids; -- fails
-ERROR:  ALTER TABLE: Table is already WITHOUT OIDS
+NOTICE:  table "altinhoid" is already WITHOUT OIDS
 select oid > 0, * from altwithoid; -- fails
 ERROR:  attribute "oid" not found
 select oid > 0, * from altinhoid; -- fails
@@ -1229,7 +1229,7 @@ create table p1 (f1 int);
 create table c1 (f2 text, f3 int) inherits (p1);
 alter table p1 add column a1 int check (a1 > 0);
 alter table p1 add column f2 text;
-NOTICE:  ALTER TABLE: merging definition of column "f2" for child c1
+NOTICE:  merging definition of column "f2" for child "c1"
 insert into p1 values (1,2,'abc');
 insert into c1 values(11,'xyz',33,0); -- should fail
 ERROR:  ExecInsert: rejected due to CHECK constraint "p1_a1" on "c1"
diff --git a/src/test/regress/expected/cluster.out b/src/test/regress/expected/cluster.out
index 151d083d3806bf7a30a5403b096ecb5295d36f93..50507fc961a5fd76937f2e87f3fc7443786d0654 100644
--- a/src/test/regress/expected/cluster.out
+++ b/src/test/regress/expected/cluster.out
@@ -316,7 +316,7 @@ INSERT INTO clstr_3 VALUES (2);
 INSERT INTO clstr_3 VALUES (1);
 -- "CLUSTER <tablename>" on a table that hasn't been clustered
 CLUSTER clstr_2;
-ERROR:  CLUSTER: No previously clustered index found on table "clstr_2"
+ERROR:  there is no previously clustered index for table "clstr_2"
 CLUSTER clstr_1_pkey ON clstr_1;
 CLUSTER clstr_2_pkey ON clstr_2;
 SELECT * FROM clstr_1 UNION ALL
diff --git a/src/test/regress/expected/copy2.out b/src/test/regress/expected/copy2.out
index 59b36fa535bd14ae206b6de184451a6c85fc64de..244c5839d68cbd3648a571b3fd68ad8ee1d5470b 100644
--- a/src/test/regress/expected/copy2.out
+++ b/src/test/regress/expected/copy2.out
@@ -28,23 +28,23 @@ COPY x (b, d) from stdin;
 COPY x (a, b, c, d, e) from stdin;
 -- non-existent column in column list: should fail
 COPY x (xyz) from stdin;
-ERROR:  relation "x" has no column "xyz"
+ERROR:  attribute "xyz" of relation "x" does not exist
 -- too many columns in column list: should fail
 COPY x (a, b, c, d, e, d, c) from stdin;
-ERROR:  Attribute "d" specified more than once
+ERROR:  attribute "d" specified more than once
 -- missing data: should fail
 COPY x from stdin;
 ERROR:  pg_atoi: zero-length string
 CONTEXT:  COPY FROM, line 1
 COPY x from stdin;
-ERROR:  Missing data for column "e"
+ERROR:  missing data for column "e"
 CONTEXT:  COPY FROM, line 1
 COPY x from stdin;
-ERROR:  Missing data for column "e"
+ERROR:  missing data for column "e"
 CONTEXT:  COPY FROM, line 1
 -- extra data: should fail
 COPY x from stdin;
-ERROR:  Extra data after last expected column
+ERROR:  extra data after last expected column
 CONTEXT:  COPY FROM, line 1
 -- various COPY options: delimiters, oids, NULL string
 COPY x (b, c, d, e) from stdin with oids delimiter ',' null 'x';
@@ -75,9 +75,9 @@ INSERT INTO no_oids (a, b) VALUES (5, 10);
 INSERT INTO no_oids (a, b) VALUES (20, 30);
 -- should fail
 COPY no_oids FROM stdin WITH OIDS;
-ERROR:  COPY: table "no_oids" does not have OIDs
+ERROR:  table "no_oids" does not have OIDs
 COPY no_oids TO stdout WITH OIDS;
-ERROR:  COPY: table "no_oids" does not have OIDs
+ERROR:  table "no_oids" does not have OIDs
 -- check copy out
 COPY x TO stdout;
 10000	21	31	41	before trigger fired
diff --git a/src/test/regress/expected/create_table.out b/src/test/regress/expected/create_table.out
index 3734960691d848c966748ed2d23c2cc32b0ec74e..5fb38f5e2928f7ff3ec24f03fe1bf53dfe031c0b 100644
--- a/src/test/regress/expected/create_table.out
+++ b/src/test/regress/expected/create_table.out
@@ -81,9 +81,9 @@ CREATE TABLE student (
 CREATE TABLE stud_emp (
 	percent 	int4
 ) INHERITS (emp, student);
-NOTICE:  CREATE TABLE: merging multiple inherited definitions of attribute "name"
-NOTICE:  CREATE TABLE: merging multiple inherited definitions of attribute "age"
-NOTICE:  CREATE TABLE: merging multiple inherited definitions of attribute "location"
+NOTICE:  merging multiple inherited definitions of attribute "name"
+NOTICE:  merging multiple inherited definitions of attribute "age"
+NOTICE:  merging multiple inherited definitions of attribute "location"
 CREATE TABLE city (
 	name		name,
 	location 	box,
@@ -135,8 +135,8 @@ CREATE TABLE c_star (
 CREATE TABLE d_star (
 	d 			float8
 ) INHERITS (b_star, c_star);
-NOTICE:  CREATE TABLE: merging multiple inherited definitions of attribute "class"
-NOTICE:  CREATE TABLE: merging multiple inherited definitions of attribute "a"
+NOTICE:  merging multiple inherited definitions of attribute "class"
+NOTICE:  merging multiple inherited definitions of attribute "a"
 CREATE TABLE e_star (
 	e 			int2
 ) INHERITS (c_star);
diff --git a/src/test/regress/expected/create_view.out b/src/test/regress/expected/create_view.out
index e4b4d7484b60d2653d2b7966ce4bf81ed16dbefb..515e5b19a44e0155bd517f3c3ea5d553b8648af8 100644
--- a/src/test/regress/expected/create_view.out
+++ b/src/test/regress/expected/create_view.out
@@ -44,14 +44,14 @@ SELECT * FROM viewtest;
 -- should fail
 CREATE OR REPLACE VIEW viewtest AS
 	SELECT a FROM viewtest_tbl WHERE a <> 20;
-ERROR:  Cannot change number of columns in view
+ERROR:  cannot change number of columns in view
 -- should fail
 CREATE OR REPLACE VIEW viewtest AS
 	SELECT 1, * FROM viewtest_tbl;
-ERROR:  Cannot change number of columns in view
+ERROR:  cannot change number of columns in view
 -- should fail
 CREATE OR REPLACE VIEW viewtest AS
 	SELECT a, b::numeric FROM viewtest_tbl;
-ERROR:  Cannot change datatype of view column "b"
+ERROR:  cannot change datatype of view column "b"
 DROP VIEW viewtest;
 DROP TABLE viewtest_tbl;
diff --git a/src/test/regress/expected/domain.out b/src/test/regress/expected/domain.out
index ef639e7dc545493d431cce7aff96b25d2f905317..cdc076da7e285144d396e01eb182a28bf198aab5 100644
--- a/src/test/regress/expected/domain.out
+++ b/src/test/regress/expected/domain.out
@@ -3,11 +3,11 @@ create domain domaindroptest int4;
 comment on domain domaindroptest is 'About to drop this..';
 -- currently this will be disallowed
 create domain basetypetest domaindroptest;
-ERROR:  DefineDomain: domaindroptest is not a basetype
+ERROR:  "domaindroptest" is not a valid base type for a domain
 drop domain domaindroptest;
 -- this should fail because already gone
 drop domain domaindroptest cascade;
-ERROR:  Type "domaindroptest" does not exist
+ERROR:  type "domaindroptest" does not exist
 -- TEST Domains.
 create domain domainvarchar varchar(5);
 create domain domainnumeric numeric(8,2);
@@ -199,19 +199,19 @@ create table domnotnull
 );
 insert into domnotnull default values;
 alter domain dnotnulltest set not null; -- fails
-ERROR:  ALTER DOMAIN: Relation "domnotnull" attribute "col1" contains NULL values
+ERROR:  relation "domnotnull" attribute "col1" contains NULL values
 update domnotnull set col1 = 5;
 alter domain dnotnulltest set not null; -- fails
-ERROR:  ALTER DOMAIN: Relation "domnotnull" attribute "col2" contains NULL values
+ERROR:  relation "domnotnull" attribute "col2" contains NULL values
 update domnotnull set col2 = 6;
 alter domain dnotnulltest set not null;
 alter domain dnotnulltest set not null; -- fails
-NOTICE:  AlterDomain: dnotnulltest is already set to NOT NULL
+NOTICE:  "dnotnulltest" is already set to NOT NULL
 update domnotnull set col1 = null; -- fails
 ERROR:  Domain dnotnulltest does not allow NULL values
 alter domain dnotnulltest drop not null;
 alter domain dnotnulltest drop not null; -- fails
-NOTICE:  AlterDomain: dnotnulltest is already set to NULL
+NOTICE:  "dnotnulltest" is already set to NULL
 update domnotnull set col1 = null;
 drop domain dnotnulltest cascade;
 NOTICE:  Drop cascades to table domnotnull column col2
@@ -251,7 +251,7 @@ create table domcontest (col1 con);
 insert into domcontest values (1);
 insert into domcontest values (2);
 alter domain con add constraint t check (VALUE < 1); -- fails
-ERROR:  ALTER DOMAIN: Relation "domcontest" attribute "col1" contains values that fail the new constraint
+ERROR:  relation "domcontest" attribute "col1" contains values that violate the new constraint
 alter domain con add constraint t check (VALUE < 34);
 alter domain con add check (VALUE > 0);
 insert into domcontest values (-5); -- fails
diff --git a/src/test/regress/expected/errors.out b/src/test/regress/expected/errors.out
index 74d03e3213c2083d43a504b06a30af5bbd0f41f4..eefdf5f20e0b20be4f6f400413bad819124482ea 100644
--- a/src/test/regress/expected/errors.out
+++ b/src/test/regress/expected/errors.out
@@ -77,23 +77,23 @@ alter table nonesuch rename to stud_emp;
 ERROR:  Relation "nonesuch" does not exist
 -- conflict 
 alter table stud_emp rename to aggtest;
-ERROR:  renamerel: relation "aggtest" exists
+ERROR:  relation "aggtest" already exists
 -- self-conflict 
 alter table stud_emp rename to stud_emp;
-ERROR:  renamerel: relation "stud_emp" exists
+ERROR:  relation "stud_emp" already exists
 -- attribute renaming 
 -- no such relation 
 alter table nonesuchrel rename column nonesuchatt to newnonesuchatt;
 ERROR:  Relation "nonesuchrel" does not exist
 -- no such attribute 
 alter table emp rename column nonesuchatt to newnonesuchatt;
-ERROR:  renameatt: attribute "nonesuchatt" does not exist
+ERROR:  attribute "nonesuchatt" does not exist
 -- conflict 
 alter table emp rename column salary to manager;
-ERROR:  renameatt: attribute "manager" exists
+ERROR:  attribute "manager" of relation "stud_emp" already exists
 -- conflict 
 alter table emp rename column salary to oid;
-ERROR:  renameatt: attribute "oid" exists
+ERROR:  attribute "oid" of relation "stud_emp" already exists
 --
 -- TRANSACTION STUFF
  
@@ -116,7 +116,7 @@ ERROR:  function int2um(integer) does not exist
 create aggregate newcnt1 (sfunc = int4inc,
 			  stype = int4,
 			  initcond = '0');
-ERROR:  Define: "basetype" unspecified
+ERROR:  aggregate basetype must be specified
 --
 -- DROP INDEX
  
@@ -173,7 +173,7 @@ drop type 314159;
 ERROR:  syntax error at or near "314159" at character 11
 -- no such type 
 drop type nonesuch;
-ERROR:  Type "nonesuch" does not exist
+ERROR:  type "nonesuch" does not exist
 --
 -- DROP OPERATOR
  
diff --git a/src/test/regress/expected/foreign_key.out b/src/test/regress/expected/foreign_key.out
index 1ea1f7110dba5e56ec131627621f7cecfd1db859..9d5c95b6ec2c233a82b1b5428d3099c7015dcd8a 100644
--- a/src/test/regress/expected/foreign_key.out
+++ b/src/test/regress/expected/foreign_key.out
@@ -689,10 +689,10 @@ CREATE TABLE PKTABLE (ptest1 int PRIMARY KEY);
 NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "pktable_pkey" for table "pktable"
 CREATE TABLE FKTABLE_FAIL1 ( ftest1 int, CONSTRAINT fkfail1 FOREIGN KEY (ftest2) REFERENCES PKTABLE);
 NOTICE:  CREATE TABLE will create implicit trigger(s) for FOREIGN KEY check(s)
-ERROR:  CREATE TABLE: column "ftest2" referenced in foreign key constraint does not exist
+ERROR:  column "ftest2" referenced in foreign key constraint does not exist
 CREATE TABLE FKTABLE_FAIL2 ( ftest1 int, CONSTRAINT fkfail1 FOREIGN KEY (ftest1) REFERENCES PKTABLE(ptest2));
 NOTICE:  CREATE TABLE will create implicit trigger(s) for FOREIGN KEY check(s)
-ERROR:  CREATE TABLE: column "ptest2" referenced in foreign key constraint does not exist
+ERROR:  column "ptest2" referenced in foreign key constraint does not exist
 DROP TABLE FKTABLE_FAIL1;
 ERROR:  table "fktable_fail1" does not exist
 DROP TABLE FKTABLE_FAIL2;
@@ -703,7 +703,7 @@ CREATE TABLE PKTABLE (ptest1 int, ptest2 int, UNIQUE(ptest1, ptest2));
 NOTICE:  CREATE TABLE / UNIQUE will create implicit index "pktable_ptest1_key" for table "pktable"
 CREATE TABLE FKTABLE_FAIL1 (ftest1 int REFERENCES pktable(ptest1));
 NOTICE:  CREATE TABLE will create implicit trigger(s) for FOREIGN KEY check(s)
-ERROR:  UNIQUE constraint matching given keys for referenced table "pktable" not found
+ERROR:  there is no UNIQUE constraint matching given keys for referenced table "pktable"
 DROP TABLE FKTABLE_FAIL1;
 ERROR:  table "fktable_fail1" does not exist
 DROP TABLE PKTABLE;
diff --git a/src/test/regress/expected/inherit.out b/src/test/regress/expected/inherit.out
index c533369683f3c13988c1b450f7b3c98de9f92f8b..8b7a631815c304a3ae6fe9ce1aa6b04e3554149d 100644
--- a/src/test/regress/expected/inherit.out
+++ b/src/test/regress/expected/inherit.out
@@ -5,8 +5,8 @@ CREATE TABLE a (aa TEXT);
 CREATE TABLE b (bb TEXT) INHERITS (a);
 CREATE TABLE c (cc TEXT) INHERITS (a);
 CREATE TABLE d (dd TEXT) INHERITS (b,c,a);
-NOTICE:  CREATE TABLE: merging multiple inherited definitions of attribute "aa"
-NOTICE:  CREATE TABLE: merging multiple inherited definitions of attribute "aa"
+NOTICE:  merging multiple inherited definitions of attribute "aa"
+NOTICE:  merging multiple inherited definitions of attribute "aa"
 INSERT INTO a(aa) VALUES('aaa');
 INSERT INTO a(aa) VALUES('aaaa');
 INSERT INTO a(aa) VALUES('aaaaa');
@@ -604,7 +604,7 @@ SELECT * FROM a; /* Has ee entry */
 (1 row)
 
 CREATE TABLE inhf (LIKE inhx, LIKE inhx); /* Throw error */
-ERROR:  CREATE TABLE: attribute "xx" duplicated
+ERROR:  attribute "xx" duplicated
 CREATE TABLE inhf (LIKE inhx INCLUDING DEFAULTS);
 INSERT INTO inhf DEFAULT VALUES;
 SELECT * FROM inhf; /* Single entry with value 'text' */
diff --git a/src/test/regress/expected/portals.out b/src/test/regress/expected/portals.out
index 1e69cff96963be1c710091870910fa18e3c1fe3c..5122f0984317582254ed2569b65112ad1403b4b5 100644
--- a/src/test/regress/expected/portals.out
+++ b/src/test/regress/expected/portals.out
@@ -737,4 +737,4 @@ DECLARE foo26 CURSOR WITH HOLD FOR SELECT * FROM tenk1;
 ROLLBACK;
 -- should fail
 FETCH FROM foo26;
-WARNING:  PerformPortalFetch: portal "foo26" not found
+WARNING:  portal "foo26" does not exist
diff --git a/src/test/regress/expected/prepare.out b/src/test/regress/expected/prepare.out
index 7bc559c4200aca8a2a6fb60e55e238b6eddd3aca..43fd8ecf56c331ffec76b47c497a0df62aa8f19a 100644
--- a/src/test/regress/expected/prepare.out
+++ b/src/test/regress/expected/prepare.out
@@ -8,7 +8,7 @@ EXECUTE q1;
 
 -- should fail
 PREPARE q1 AS SELECT 2;
-ERROR:  Prepared statement with name "q1" already exists
+ERROR:  prepared statement "q1" already exists
 -- should succeed
 DEALLOCATE q1;
 PREPARE q1 AS SELECT 2;
diff --git a/src/test/regress/expected/truncate.out b/src/test/regress/expected/truncate.out
index 8aff7d8b0190a56d3a70db393e1a22adba438352..91ea40b7929cca531e412c0c2bf5f31aff1caad4 100644
--- a/src/test/regress/expected/truncate.out
+++ b/src/test/regress/expected/truncate.out
@@ -41,7 +41,8 @@ SELECT * FROM truncate_a;
 (1 row)
 
 TRUNCATE truncate_a;
-ERROR:  TRUNCATE cannot be used as table truncate_b references this one via foreign key constraint $1
+ERROR:  cannot truncate a table referenced in a foreign key constraint
+DETAIL:  Table "truncate_b" references this one via foreign key constraint "$1".
 SELECT * FROM truncate_a;
  col1 
 ------
diff --git a/src/test/regress/output/misc.source b/src/test/regress/output/misc.source
index e52d71d232180c1228ee436eb7147d43a47d65ec..557c0f5f9d9142ea92ca817e99f138d89fe9f85c 100644
--- a/src/test/regress/output/misc.source
+++ b/src/test/regress/output/misc.source
@@ -373,7 +373,7 @@ SELECT * FROM e_star*;
 (23 rows)
 
 ALTER TABLE a_star* ADD COLUMN a text;
-NOTICE:  ALTER TABLE: merging definition of column "a" for child d_star
+NOTICE:  merging definition of column "a" for child "d_star"
 --UPDATE b_star*
 --   SET a = text 'gazpacho'
 --   WHERE aa > 4;