Question

I tried to write a trigger in PostgreSQL 9.1 database, something like:

CREATE FUNCTION test_trigger()
RETURNS trigger AS
BEGIN
IF () THEN INSERT INTO...;
ELSEIF ()...;
...
...
END IF;
RETURN NULL;
END

Then I got this error:

Cannot commit when autoCommit is enabled error

So I tried to disable it using set autocommit=off; but then got this message:

ERROR:  SET AUTOCOMMIT TO OFF is no longer supported

One suggested solution was to use BEGIN to start a transaction, but I have no idea how to edit my trigger function to do that.

UPDATE

I tried this to disable autocommit with trigger creation as follows:

BEGIN;
CREATE FUNCTION test_trigger()
RETURNS trigger AS
$func$
BEGIN
IF () THEN INSERT INTO...;
ELSEIF ()...;
...
...
END IF;
RETURN NULL;
END
COMMIT; 
$func$ 
LANGUAGE plpgsql;

but the connection closed every time i run this.

Was it helpful?

Solution

This might be a misunderstanding. Autocommit doesn't seem to be the problem.

The function body is a string, you need to quote it. Typically you would use dollar-quoting to make your live easier:

CREATE FUNCTION test_trigger()
RETURNS trigger AS
$func$
BEGIN
IF () THEN INSERT INTO...;
ELSEIF ()...;
...
...
END IF;
RETURN NULL;
END
$func$ LANGUAGE plpgsql;

Apart from that, to "disable" autocommit, start a transaction. That's what the suggested solution in your last line aims for:

BEGIN;               -- starts transaction
UPDATE tbl ...;      -- not commited yet
CREATE FUNCTION ...; -- not commited yet
COMMIT;              -- *now* we commit
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top