Fix EXPLAIN ANALYZE SELECT INTO
authorPavan Deolasee <[email protected]>
Fri, 12 May 2017 12:06:23 +0000 (17:36 +0530)
committerPavan Deolasee <[email protected]>
Fri, 12 May 2017 12:12:18 +0000 (17:42 +0530)
EXPLAIN ANALYZE SELECT INTO was missing the treatment that we give to a regular
SELECT INTO or CREATE TABLE AS SELECT. This patch fixes that such that even
when EXPLAIN ANALYZE is used, we first create the target table and then insert
the selected rows.

The EXPLAIN ANALYZE will only show the plan for the final transformed INSERT
INTO statement. This is not very useful right now the EXPLAIN ANALYZE doesn't
show anything below Remote Subquery Scan, but that's a separate issue and will
be fixed in a separate patch.

The regression test's expected output is updated accordingly.

This will be backpatched to XL9_5_STABLE.

src/backend/commands/explain.c
src/test/regress/expected/select_into.out

index 23496b4f8fc890aae3a4824074af29c20cc944e4..18b2404ebfdc96b64b721f9c25fcf3c7042290d5 100644 (file)
@@ -356,7 +356,22 @@ ExplainOneQuery(Query *query, IntoClause *into, ExplainState *es,
        /* planner will not cope with utility statements */
        if (query->commandType == CMD_UTILITY)
        {
-               ExplainOneUtility(query->utilityStmt, into, es, queryString, params);
+               /*
+                * If we are running EXPLAIN ANALYZE, transform the CTAS such that the
+                * target table is created first and select result is inserted into the
+                * table. The EXPLAIN ANALYZE would really just show the plan for the
+                * INSERT INTO generated by QueryRewriteCTAS, but that's OK.
+                */
+               if (es->analyze && IsA(query->utilityStmt, CreateTableAsStmt))
+               {
+                       List *rewritten = QueryRewriteCTAS(query);
+                       Assert(list_length(rewritten) == 1);
+                       ExplainOneQuery((Query *) linitial(rewritten), into, es,
+                                       queryString, params);
+               }
+               else
+                       ExplainOneUtility(query->utilityStmt, into, es,
+                                       queryString, params);
                return;
        }
 
index 8662413656f362ddd6db19b95b6b71d99c2686d9..11b61b592c1ed9a2eb065774ec50fc2d185c24c2 100644 (file)
@@ -107,8 +107,15 @@ SELECT * FROM created_table;
 ERROR:  relation "created_table" does not exist
 LINE 1: SELECT * FROM created_table;
                       ^
+-- Try EXPLAIN ANALYZE SELECT INTO, but hide the output since it won't
+-- be stable.
+DO $$
+BEGIN
+       EXECUTE 'EXPLAIN ANALYZE SELECT * INTO TABLE easi FROM int8_tbl';
+END$$;
 DROP TABLE created_table;
 ERROR:  table "created_table" does not exist
+DROP TABLE easi;
 --
 -- Disallowed uses of SELECT ... INTO.  All should fail
 --