Skip site navigation (1) Skip section navigation (2)

Re: transactions in functions, possible bug or what I'm doing

From: Michael Fuhr <mike(at)fuhr(dot)org>
To: Richard Huxton <dev(at)archonet(dot)com>
Cc: abief_ag_-postgresql(at)yahoo(dot)com, pgsql-sql(at)postgresql(dot)org
Subject: Re: transactions in functions, possible bug or what I'm doing
Date: 2004-11-19 16:23:09
Message-ID: 20041119162309.GA77593@winnie.fuhr.org (view raw or flat)
Thread:
Lists: pgsql-sql
On Fri, Nov 19, 2004 at 12:59:07PM +0000, Richard Huxton wrote:

> You can have what are called "savepoints" in version 8.0 though, which 
> lets you trap errors and rollback to a named (saved) point in your function.

Savepoints in functions don't work as of 8.0.0beta4, unless I'm
doing something wrong:

CREATE TABLE foo (id SERIAL PRIMARY KEY, name TEXT NOT NULL);

CREATE FUNCTION fooins(TEXT) RETURNS BOOLEAN AS $$
BEGIN
    SAVEPOINT x;
    INSERT INTO foo (name) VALUES ($1);
    ROLLBACK TO x;
    RETURN TRUE;
END;
$$ LANGUAGE plpgsql;

BEGIN;
SELECT fooins('John');
ERROR:  SPI_execute_plan failed executing query "SAVEPOINT x": SPI_ERROR_TRANSACTION
CONTEXT:  PL/pgSQL function "fooins" line 2 at SQL statement

Error trapping does work, however:

CREATE FUNCTION fooins(TEXT) RETURNS BOOLEAN AS $$
BEGIN
    INSERT INTO foo (name) VALUES ($1 || '-1');

    BEGIN
        INSERT INTO foo (id, name) VALUES (currval('foo_id_seq'), $1 || '-2');
    EXCEPTION
        WHEN unique_violation THEN
            NULL;
    END;

    INSERT INTO foo (name) VALUES ($1 || '-3');

    RETURN TRUE;
END;
$$ LANGUAGE plpgsql;

SELECT fooins('John');
 fooins 
--------
 t
(1 row)

SELECT * FROM foo;
 id |  name  
----+--------
  1 | John-1
  2 | John-3
(2 rows)

-- 
Michael Fuhr
http://www.fuhr.org/~mfuhr/

In response to

Responses

pgsql-sql by date

Next:From: Tom LaneDate: 2004-11-19 17:08:50
Subject: Re: transactions in functions, possible bug or what I'm doing
Previous:From: Guy FraserDate: 2004-11-19 16:05:03
Subject: Re: Comparing Dates

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group