简体   繁体   中英

PostgreSQL locks after 6th execution of the same query

PostgreSQL version: Postgres Plus Advanced Server 9.2
Operating system: Windows 7/8

I have a stored procedure which acts like it follows:
1. Clears table1
2. Selects from a view ( same view always ) based on a couple of parameters passed in the WHERE clause ( always same parameters for the sake of the example )
3. Inserts into table1 the results of the select above.

The body of the procedure looks as follows:

BEGIN

    PERFORM clear_table1(p_session_id);

    INSERT INTO table1 (session_id, id1, adress, x, y)
    SELECT p_session_id, id1, adress, x, y
        FROM myview
        WHERE (CONDITION)
            AND (CONDITION)
            AND (CONDITION)
            AND (lower(adress) LIKE lower(p_adress) OR p_adress IS NULL)
            LIMIT 6000;
END;

First 5 times (always 5 times) I run the exact same query with the exact same parameters, it runs as expected. Next time (6th time) it runs for an enormous amount of time, something like .. tens of minutes.

select * from myfunction('session_id',NULL,NULL,'%adress%')

In Server Status view from PostgreSQL Manager, I observed a number of locks added for the tables in which I insert along with the tables from which the view is populated

Could anyone with PostgreSQL experience tell me if there's some kind of setting to fix this behaviour OR did this or something similar happen to someone else using PG?

Thanks!!!

Later edit : - the issue always occurs only when the 6 invocations are made from the same session - we do not explicitly commit at the end of the stored procedure

Wild guess: You're using JDBC with the default prepare threshold.

See if disabling server-side prepare makes the issue go away. See the PgJDBC docs .

Failing that, if the slow call is within the function: try enabling auto_explain with processing of function bodies enabled. Then see if the plan changes for some reason on the 6th invocation.

I know this is a really old question, but yesterday I had just the exactly same problem.

It's tricky to realize it, cause it's always after the sixth time that it occurs.

I'm not able to explain the cause, however I was able to fix it.

In my case I had to change the part where it was

SELECT (sum(coalesce(debito.vl_conta,0)) ) ...

to

execute 'SELECT (sum(coalesce(debito.vl_conta,0)) ) ...

and that's it. But answering here just in case someone else suffers it too, or maybe explain why it happens.

Thanks,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM