Commit da4ed8bf authored by Tom Lane's avatar Tom Lane

Another round of error message editing, covering backend/commands/.

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