2

Can you please guide what is wrong with below code which gives an issue with below error:

ERROR: invalid transaction termination.

CREATE OR REPLACE PROCEDURE "app"."sproc_data_create"
( name varchar(100))
LANGUAGE plpgsql
AS
$$
Declare idIdentity int;
 BEGIN

 INSERT INTO data(Name) VALUES (name) RETURNING Id into idIdentity;
 INSERT INTO relationalData(dataId) VALUES (idIdentity);
  
 COMMIT; 
 END

For below scenarios, this does not work executing commit for one insert statement and expected to rollback second insert statement. This rollback both insert statements.

BEGIN
    
     INSERT INTO data(Name) VALUES (name) RETURNING Id into idIdentity;
     COMMIT;
    INSERT INTO relationalData(dataId) VALUES (idIdentity);
END

Execute below script:

/*
do
begin
    CALL "app"."sproc_data_create"("name field")
    
end
*/    
//invalid transaction termination
    CONTEXT: PL/pgSQL function
dsi
  • 3,199
  • 12
  • 59
  • 102
  • ERROR: "ididentity" is not a known variable – jjanes Apr 13 '22 at 21:25
  • ERROR: column "name field" does not exist – jjanes Apr 13 '22 at 21:26
  • Apologies, have not created online sandbox. But this same scenario happen with my procedure and raising "invalid transaction termination" issue. By searching I found, "commit" outside of END statement but still that not worked. In SQL Server, it went so easy and I am new to postgres. – dsi Apr 13 '22 at 21:28

2 Answers2

2

Found an issue, I was executing "call" procedure statement inside DO BEGIN/END statement and that creates parent transaction scope.

As found on below post. (Basically, "call" has parent transaction scope and I use commit/rollback under subTransaction scope within procedure. By removing DO BEGIN/END wrapper from "call" statement, it resolves the issue.

Can a Postgres Commit Exist in Procedure that has an Exception Block?

Thanks

dsi
  • 3,199
  • 12
  • 59
  • 102
0

This error happened after trying to execute the stored procedure using sqlalchemy with python.

The main reason of this error was I created the stored procedure with including COMMIT; statement after INSERT/UPDATE statement, so replacing the stored procedure without using the COMMIT; statement solved the issue.

CREATE OR REPLACE PROCEDURE insert_files(
    file_id text)
LANGUAGE 'plpgsql'
AS $BODY$
BEGIN 
INSERT INTO files(file_id)
                    VALUES (file_id);
        
-- AVOID USING COMMIT; HERE
    
END
$BODY$;

ALTER PROCEDURE insert_files(text)
    OWNER TO user;

Prakash Dahal
  • 4,388
  • 2
  • 11
  • 25