I want to use savepoint feature inside a function in PostgreSQL. I read that savepoint cannot be used inside functions in Postgres.
But while I rollback, I want to rollback to a specific point because of which I want to use savepoint. What is the alternative way to do it?
Sample Code
CREATE or replace FUNCTION fn_loadData_Subha()
RETURNS BIGINT
AS
$$
DECLARE
batchId BIGINT;
currentTime TIMESTAMP;
processName VARCHAR(20);
BEGIN
-- Getting current date and time
select TIMESTAMP 'NOW' into currentTime;
select 'ETL_Subha' INTO processName;
SAVEPOINT first_savepoint;
-- Inserting new record into batch log table
INSERT INTO TB_HSS_BATCH_LOG
(PROCESS_NAME,START_DATE,STATUS)
SELECT processName,currentTime,'STARTED';
select currval('TB_HSS_BATCH_LOG_id_seq') INTO batchId;
-- Inserting cost data to history table
Insert into tb_hss_procedure_cost_hist1
(HOSP_SYSTEM, HOSP_FACILITY, surgeon_name, procedure_name, department, current_dept_rank, no_of_surgeons, current_imp_cost
, current_med_surg_cost, current_total_cost, annual_volume, sys_pref_cost,load_seq_no, CREATED_AT)
Select
HOSP_SYSTEM, HOSP_FACILITY,surgeon_name,procedure_name,department,current_dept_rank, no_of_surgeons, current_imp_cost
, current_med_surg_cost, current_total_cost, annual_volume, sys_pref_cost, batchId,currentTime
from tb_hss_procedure_cost_stag_in;
RELEASE SAVEPOINT first_savepoint;
RETURN 1;
EXCEPTION
WHEN PLPGSQL_ERROR THEN
RAISE EXCEPTION '% %', SQLERRM, SQLSTATE;
RAISE NOTICE '% %', SQLERRM, SQLSTATE;
RETURN 0;
WHEN OTHERS THEN
RAISE EXCEPTION '% %', SQLERRM, SQLSTATE;
RAISE NOTICE '% %', SQLERRM, SQLSTATE;
RETURN 0;
ROLLBACK TRANSACTION;
END;
$$LANGUAGE plpgsql;
rollback to first_savepoint
: postgresql.org/docs/current/static/sql-rollback-to.html – Cutlery