Monday, January 30, 2023

Postgres: Let us see what happens to the lock acquired within a pl/pgsql with a for loop and commit

 A proc routine from postgresql guide:

CREATE PROCEDURE transaction_test1()
LANGUAGE plpgsql
AS $$
BEGIN
    LOCK table pgtst_schema.pgtst_vacuum in exclusive mode;
    FOR i IN 0..9 LOOP
    INSERT INTO pgtst_schema.pgtst_vacuum
    values (i, lpad('TST',mod(i,100),'CHK'));
    COMMIT;
    PERFORM pg_sleep(10);
    END LOOP;
END;
$$;


Actual output: -- screen 1

pgtst_db=# CREATE PROCEDURE transaction_test1()
pgtst_db-# LANGUAGE plpgsql
pgtst_db-# AS $$
pgtst_db$# BEGIN
pgtst_db$#     LOCK table pgtst_schema.pgtst_vacuum in exclusive mode;
pgtst_db$#     FOR i IN 0..9 LOOP
pgtst_db$#     INSERT INTO pgtst_schema.pgtst_vacuum
pgtst_db$#     values (i, lpad('TST',mod(i,100),'CHK'));
pgtst_db$#     COMMIT;
pgtst_db$#     PERFORM pg_sleep(10);
pgtst_db$#     END LOOP;
pgtst_db$# END;
pgtst_db$# $$;
CREATE PROCEDURE
pgtst_db=#


Data collection commands: - screen 2
psql -d pgtst_db -f query_table_data.sql -x -a -q >30jan2023_proc_table_assesment.out
psql -d pgtst_db -f othertab_query_table_data.sql -x -a -q >30jan2023_proc_othertable_assesment.out

Screen 1:
CALL transaction_test1();
pgtst_db=# CALL transaction_test1();



Try another exclusive lock on pgtst_schema.pgtst_vacuum table - screen 3; while the call is still running
pgtst_db=# begin work;
BEGIN
pgtst_db=*# LOCK table pgtst_schema.pgtst_vacuum in exclusive mode;
LOCK TABLE


Observation: The call didnt finish in screen 1, but the lock was acquired in screen 3. This means we can hold on to the lock as soon as a commit was issued even if it was executed with in a pl/pgsql procedure. 
    LOCK table pgtst_schema.pgtst_vacuum in exclusive mode;
    FOR i IN 0..9 LOOP
    INSERT INTO pgtst_schema.pgtst_vacuum
    values (i, lpad('TST',mod(i,100),'CHK'));
    COMMIT; 
                                           <<< this commit released once for all the lock acquired within the block.

No comments:

Post a Comment

Flashback data archive steps

 Objective: Ways to track DML changes in a table Detailed objective: We should be able to track the changes in the table at any point in tim...