Search code examples
postgresqllibpq

If calling PQfinish, is there any benefit of calling PQcancel?


If calling PQFinish, which "closes the connection to the server", is there any benefit to calling PQCancel beforehand?

i.e. if the connection is closed, would the PostgreSQL server cancel any in-progress queries on this connection, just as it would with PQCancel?


Solution

  • I've given this a test with just a SELECT pg_sleep(120) query. Even after PQFinish is called, connecting in via psql and running

    SELECT pid, age(clock_timestamp(), query_start), usename, query
    FROM pg_stat_activity
    WHERE query != '<IDLE>' AND query NOT ILIKE '%pg_stat_activity%'
    ORDER BY query_start desc
    

    still showed the query to be running.

    So I think there is a benefit of running PQCancel - it would increase the chance of queries being cancelled and reducing resource use on the server.