From f21fc7f9fc63ff86d7d77d352ae274b6e2b6e09e Mon Sep 17 00:00:00 2001
From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
Date: Thu, 24 Nov 2011 17:18:43 +0200
Subject: Preserve SQLSTATE when an SPI error is propagated through PL/python
 exception handler. This was a regression in 9.1, when the capability to catch
 specific SPI errors was added, so backpatch to 9.1.
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Mika Eloranta, with some editing by Jan Urbański.
---
 src/pl/plpython/sql/plpython_error.sql | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)

(limited to 'src/pl/plpython/sql/plpython_error.sql')

diff --git a/src/pl/plpython/sql/plpython_error.sql b/src/pl/plpython/sql/plpython_error.sql
index 4add6aaf05..502bbec38f 100644
--- a/src/pl/plpython/sql/plpython_error.sql
+++ b/src/pl/plpython/sql/plpython_error.sql
@@ -257,6 +257,26 @@ SELECT specific_exception(2);
 SELECT specific_exception(NULL);
 SELECT specific_exception(2);
 
+/* SPI errors in PL/Python functions should preserve the SQLSTATE value
+ */
+CREATE FUNCTION python_unique_violation() RETURNS void AS $$
+plpy.execute("insert into specific values (1)")
+plpy.execute("insert into specific values (1)")
+$$ LANGUAGE plpythonu;
+
+CREATE FUNCTION catch_python_unique_violation() RETURNS text AS $$
+begin
+    begin
+        perform python_unique_violation();
+    exception when unique_violation then
+        return 'ok';
+    end;
+    return 'not reached';
+end;
+$$ language plpgsql;
+
+SELECT catch_python_unique_violation();
+
 /* manually starting subtransactions - a bad idea
  */
 CREATE FUNCTION manual_subxact() RETURNS void AS $$
-- 
cgit v1.2.1

