1

I'm trying to grab a query plan for my query. However, I do not have direct access to the db and can only run SELECT statements on my end.

Is there a way to wrap SELECT around EXPLAIN, maybe even encode it as string to generate tabular data to be extracted on my end.

Note: I cannot use psql (the default command line terminal).

10
  • what fot exactly, can't you don't copy it from pgadmin`
    – nbk
    Commented Apr 22 at 22:54
  • 1
    And SQL client can send a query to you database, including the EXPLAIN command. You can even ask the database to generate json for you: postgresql.org/docs/current/sql-explain.html Commented Apr 22 at 22:54
  • I can't, no access. Only have access to SELECT in query Commented Apr 22 at 22:55
  • I understand that, I went through the documentation, but I do not have access to it and I am only restricted by SELECT statements in a query. Can't download any files either. I wasn't sure if it is possible without "psql" client Commented Apr 22 at 22:58
  • 1
    Ask the one who made your web application. That application has the option to use EXPLAIN, or not. Commented Apr 23 at 0:17

1 Answer 1

2

Basic EXPLAIN returns a set of text values. But you cannot access that with a plain SELECT. You can EXECUTE EXPLAIN with a given query string dynamically in PL/pgSQL and return the result as SETOF text. You can even pass EXPLAIN options.
Create the function once. Then you can "call" EXPLAIN via SELECT:

CREATE FUNCTION f_explain(_qry text, _options text = NULL)
  RETURNS SETOF text
  LANGUAGE plpgsql AS
$func$
BEGIN
  RETURN QUERY EXECUTE
  format('EXPLAIN %s %s', _options, _qry);
END
$func$;

Example calls:

SELECT * FROM f_explain('SELECT 1');
SELECT * FROM f_explain('SELECT 1', '(ANALYZE, BUFFERS)');

Options, if given, must be in legal syntax form.

fiddle

Careful! With the option ANALYZE, the given query string is actually executed. Also, a maliciously formed query string can do anything the executing role is allowed to do. So this is open to SQL injection. Handle with care!

Related:

Alternatively, you can get EXPLAIN output string of messages (NOTICE, WARNING, ...) See:

Not the answer you're looking for? Browse other questions tagged or ask your own question.