Postgresql – How to get query output in addition to EXPLAIN ANALYZE output

postgresql

Is it possible to get EXPLAIN ANALYZE output (e.g. as a notice) in addition to the regular query output?

I am designing a client and I would like to add a feature that automatically turns all queries into EXPLAIN ANALYZE for the purpose of tracking query execution time, seq scan, etc. However, such feature would require that I am able to obtain the regular query output in addition to the EXPLAIN ANALYZE output.

How to get query output in addition to EXPLAIN ANALYZE output?

Note: I am aware of auto_explain. However, there appears to be no way to access logs from the client for the last executed statement.

Best Answer

Client can be configured to receive the auto_explain message by setting client_min_messages=log.

Example configuration:

-- Load the extension.
LOAD 'auto_explain';
-- or (if you are using AWS RDS):
LOAD '$libdir/plugins/auto_explain';

-- Enable logging of all queries.
SET auto_explain.log_analyze=true;
SET auto_explain.log_format=json;
SET auto_explain.log_min_duration=0;
SET auto_explain.log_timing=true;

-- Enables Slonik to capture auto_explain logs.
SET client_min_messages=log;

with this configuration, client will receive auto_explain log message after every query.

client Slonik uses this configuration to associate auto_explain messages with the specific queries and parse the log messages.