PL/Python custom SPI exceptions

This provides a separate exception class for each error code that the
backend defines, as well as the ability to get the SQLSTATE from the
exception object.

Jan Urbański, reviewed by Steve Singer
This commit is contained in:
Peter Eisentraut
2011-02-28 18:41:10 +02:00
parent 0ef0b30204
commit 474a42473a
12 changed files with 342 additions and 26 deletions

View File

@ -32,7 +32,7 @@ CREATE FUNCTION sql_syntax_error() RETURNS text
'plpy.execute("syntax error")'
LANGUAGE plpythonu;
SELECT sql_syntax_error();
ERROR: plpy.SPIError: syntax error at or near "syntax"
ERROR: spiexceptions.SyntaxError: syntax error at or near "syntax"
LINE 1: syntax error
^
QUERY: syntax error
@ -54,7 +54,7 @@ CREATE FUNCTION exception_index_invalid_nested() RETURNS text
return rv[0]'
LANGUAGE plpythonu;
SELECT exception_index_invalid_nested();
ERROR: plpy.SPIError: function test5(unknown) does not exist
ERROR: spiexceptions.UndefinedFunction: function test5(unknown) does not exist
LINE 1: SELECT test5('foo')
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
@ -74,7 +74,7 @@ return None
'
LANGUAGE plpythonu;
SELECT invalid_type_uncaught('rick');
ERROR: plpy.SPIError: type "test" does not exist
ERROR: spiexceptions.UndefinedObject: type "test" does not exist
CONTEXT: PL/Python function "invalid_type_uncaught"
/* for what it's worth catch the exception generated by
* the typo, and return None
@ -140,6 +140,44 @@ SELECT valid_type('rick');
(1 row)
/* check catching specific types of exceptions
*/
CREATE TABLE specific (
i integer PRIMARY KEY
);
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "specific_pkey" for table "specific"
CREATE FUNCTION specific_exception(i integer) RETURNS void AS
$$
from plpy import spiexceptions
try:
plpy.execute("insert into specific values (%s)" % (i or "NULL"));
except spiexceptions.NotNullViolation, e:
plpy.notice("Violated the NOT NULL constraint, sqlstate %s" % e.sqlstate)
except spiexceptions.UniqueViolation, e:
plpy.notice("Violated the UNIQUE constraint, sqlstate %s" % e.sqlstate)
$$ LANGUAGE plpythonu;
SELECT specific_exception(2);
specific_exception
--------------------
(1 row)
SELECT specific_exception(NULL);
NOTICE: Violated the NOT NULL constraint, sqlstate 23502
CONTEXT: PL/Python function "specific_exception"
specific_exception
--------------------
(1 row)
SELECT specific_exception(2);
NOTICE: Violated the UNIQUE constraint, sqlstate 23505
CONTEXT: PL/Python function "specific_exception"
specific_exception
--------------------
(1 row)
/* manually starting subtransactions - a bad idea
*/
CREATE FUNCTION manual_subxact() RETURNS void AS $$