#include "dbms_xplan.hpp"
|
|
extern "C"
|
{
|
#include "access/xact.h"
|
#include "catalog/namespace.h"
|
#include "funcapi.h"
|
#include "executor/spi.h"
|
#include "nodes/makefuncs.h"
|
#include "nodes/nodeFuncs.h"
|
#include "nodes/plannodes.h"
|
#include "parser/parsetree.h"
|
#include "tcop/tcopprot.h"
|
#include "utils/builtins.h"
|
#include "utils/tuplestore.h"
|
}
|
|
extern "C"
|
{
|
|
PG_FUNCTION_INFO_V1(dbms_xplan_display_cursor);
|
PG_FUNCTION_INFO_V1(dbms_xplan_display_awr);
|
PG_FUNCTION_INFO_V1(dbms_xplan_display_workload_repository);
|
PG_FUNCTION_INFO_V1(dbms_xplan_display_sqlset);
|
PG_FUNCTION_INFO_V1(dbms_xplan_display_sql_plan_baseline);
|
PG_FUNCTION_INFO_V1(dbms_xplan_diff_plan);
|
PG_FUNCTION_INFO_V1(dbms_xplan_display);
|
PG_FUNCTION_INFO_V1(dbms_xplan_display_plan);
|
PG_FUNCTION_INFO_V1(dbms_xplan_compare_plans);
|
|
/*
|
* Одна строка plan_table_output или пустой набор. line == NULL — ноль строк.
|
* Колонка одна: её имя задаёт OUT plan_table_output.
|
*/
|
static void
|
xplan_emit(FunctionCallInfo fcinfo, const char *what, const char *line)
|
{
|
ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
|
Datum values[1];
|
bool nulls[1];
|
|
ereport(LOG,
|
(errmsg("dbms_xplan: %s", what),
|
errdetail_internal("Output: [Status: %s]",
|
line != NULL ? line : "empty")));
|
|
if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
|
ereport(ERROR,
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
errmsg("set-valued function called in context that cannot accept a set")));
|
|
InitMaterializedSRF(fcinfo, MAT_SRF_USE_EXPECTED_DESC | MAT_SRF_BLESS);
|
|
if (line == NULL)
|
return;
|
|
if (rsinfo->setDesc->natts != 1)
|
elog(ERROR, "dbms_xplan: expected one output column");
|
|
values[0] = CStringGetTextDatum(line);
|
nulls[0] = false;
|
tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
|
}
|
|
/* sql_id NULL — NOT VALID. Чужой awr_location — NOT VALID. Иначе пусто. */
|
static void
|
xplan_awr_lines(FunctionCallInfo fcinfo, const char *what)
|
{
|
const char *sql_id = NULL;
|
const char *location = NULL;
|
const int location_arg = 5;
|
|
if (PG_NARGS() > 0 && !PG_ARGISNULL(0))
|
sql_id = text_to_cstring(PG_GETARG_TEXT_PP(0));
|
if (location_arg < PG_NARGS() && !PG_ARGISNULL(location_arg))
|
location = text_to_cstring(PG_GETARG_TEXT_PP(location_arg));
|
|
if (sql_id == NULL)
|
xplan_emit(fcinfo, what, "SQL_ID is not valid");
|
else if (location != NULL &&
|
pg_strcasecmp(location, "AWR_ROOT") != 0 &&
|
pg_strcasecmp(location, "AWR_PDB") != 0)
|
xplan_emit(fcinfo, what, "AWR_LOCATION is not valid");
|
else
|
xplan_emit(fcinfo, what, NULL);
|
}
|
|
Datum
|
dbms_xplan_display_cursor(PG_FUNCTION_ARGS)
|
{
|
xplan_emit(fcinfo, "display_cursor",
|
"User has no SELECT privilege on V$SESSION");
|
PG_RETURN_NULL();
|
}
|
|
Datum
|
dbms_xplan_display_awr(PG_FUNCTION_ARGS)
|
{
|
xplan_awr_lines(fcinfo, "display_awr");
|
PG_RETURN_NULL();
|
}
|
|
Datum
|
dbms_xplan_display_workload_repository(PG_FUNCTION_ARGS)
|
{
|
xplan_awr_lines(fcinfo, "display_workload_repository");
|
PG_RETURN_NULL();
|
}
|
|
Datum
|
dbms_xplan_display_sqlset(PG_FUNCTION_ARGS)
|
{
|
xplan_emit(fcinfo, "display_sqlset",
|
"Error: cannot fetch explain plan for the specified SQL tuning set and sql_id");
|
PG_RETURN_NULL();
|
}
|
|
Datum
|
dbms_xplan_display_sql_plan_baseline(PG_FUNCTION_ARGS)
|
{
|
bool handle_null = PG_NARGS() < 1 || PG_ARGISNULL(0);
|
bool plan_null = PG_NARGS() < 2 || PG_ARGISNULL(1);
|
char *handle = NULL;
|
char buf[256];
|
|
if (handle_null && plan_null)
|
{
|
xplan_emit(fcinfo, "display_sql_plan_baseline",
|
"neither SQL handle nor plan name is specified");
|
PG_RETURN_NULL();
|
}
|
|
if (!handle_null)
|
handle = text_to_cstring(PG_GETARG_TEXT_PP(0));
|
else
|
handle = text_to_cstring(PG_GETARG_TEXT_PP(1));
|
|
snprintf(buf, sizeof(buf),
|
"Error: specified SQL handle %s does not exist", handle);
|
xplan_emit(fcinfo, "display_sql_plan_baseline", buf);
|
PG_RETURN_NULL();
|
}
|
|
Datum
|
dbms_xplan_diff_plan(PG_FUNCTION_ARGS)
|
{
|
(void) fcinfo;
|
ereport(ERROR,
|
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
|
errmsg("the current user has not been granted the ADVISOR privilege")));
|
PG_RETURN_NULL();
|
}
|
|
typedef struct XPlanRow
|
{
|
int id;
|
int parent_id;
|
bool parent_null;
|
int depth;
|
const char *operation;
|
const char *options;
|
char *object_name;
|
char *cost;
|
char *cardinality;
|
char *bytes;
|
const char *qblock_name;
|
} XPlanRow;
|
|
static void
|
xplan_operation(Plan *plan, const char **operation, const char **options)
|
{
|
*options = NULL;
|
switch (nodeTag(plan))
|
{
|
case T_SeqScan:
|
case T_SampleScan:
|
case T_TidScan:
|
case T_TidRangeScan:
|
*operation = "TABLE ACCESS";
|
*options = "FULL";
|
break;
|
case T_BitmapHeapScan:
|
*operation = "TABLE ACCESS";
|
*options = "BY INDEX ROWID";
|
break;
|
case T_IndexScan:
|
case T_IndexOnlyScan:
|
case T_BitmapIndexScan:
|
*operation = "INDEX";
|
*options = "RANGE SCAN";
|
break;
|
case T_NestLoop:
|
*operation = "NESTED LOOPS";
|
break;
|
case T_HashJoin:
|
*operation = "HASH JOIN";
|
break;
|
case T_MergeJoin:
|
*operation = "MERGE JOIN";
|
break;
|
case T_Hash:
|
*operation = "HASH";
|
break;
|
case T_Sort:
|
*operation = "SORT";
|
break;
|
case T_Agg:
|
*operation = "HASH";
|
*options = "GROUP BY";
|
break;
|
case T_Limit:
|
*operation = "COUNT";
|
*options = "STOPKEY";
|
break;
|
default:
|
*operation = "VIEW";
|
break;
|
}
|
}
|
|
static char *
|
xplan_object_name(Plan *plan, List *rtable)
|
{
|
Index relid = 0;
|
RangeTblEntry *rte;
|
|
switch (nodeTag(plan))
|
{
|
case T_SeqScan:
|
case T_SampleScan:
|
case T_TidScan:
|
case T_TidRangeScan:
|
case T_BitmapHeapScan:
|
case T_IndexScan:
|
case T_IndexOnlyScan:
|
case T_BitmapIndexScan:
|
relid = ((Scan *) plan)->scanrelid;
|
break;
|
default:
|
return NULL;
|
}
|
if (relid == 0 || relid > (Index) list_length(rtable))
|
return NULL;
|
rte = rt_fetch(relid, rtable);
|
if (rte->eref && rte->eref->aliasname)
|
return pstrdup(rte->eref->aliasname);
|
return NULL;
|
}
|
|
static XPlanRow *
|
xplan_make_row(Plan *plan, List *rtable, int id, int parent_id, bool parent_null,
|
int depth, const char *qblock)
|
{
|
XPlanRow *row = (XPlanRow *) palloc0(sizeof(XPlanRow));
|
const char *operation;
|
const char *options;
|
|
xplan_operation(plan, &operation, &options);
|
row->id = id;
|
row->parent_id = parent_id;
|
row->parent_null = parent_null;
|
row->depth = depth;
|
row->operation = operation;
|
row->options = options;
|
row->object_name = xplan_object_name(plan, rtable);
|
row->cost = psprintf("%.0f", plan->total_cost);
|
row->cardinality = psprintf("%.0f", plan->plan_rows);
|
row->bytes = psprintf("%lld",
|
(long long) plan->plan_width * (long long) plan->plan_rows);
|
row->qblock_name = qblock;
|
return row;
|
}
|
|
static void
|
xplan_collect(Plan *plan, List *rtable, int parent_id, int depth,
|
int *next_id, List **rows)
|
{
|
int my_id = (*next_id)++;
|
ListCell *lc;
|
|
*rows = lappend(*rows, xplan_make_row(plan, rtable, my_id, parent_id,
|
false, depth, NULL));
|
|
if (IsA(plan, Append))
|
{
|
foreach(lc, ((Append *) plan)->appendplans)
|
xplan_collect((Plan *) lfirst(lc), rtable, my_id, depth + 1,
|
next_id, rows);
|
return;
|
}
|
if (IsA(plan, MergeAppend))
|
{
|
foreach(lc, ((MergeAppend *) plan)->mergeplans)
|
xplan_collect((Plan *) lfirst(lc), rtable, my_id, depth + 1,
|
next_id, rows);
|
return;
|
}
|
if (IsA(plan, BitmapAnd))
|
{
|
foreach(lc, ((BitmapAnd *) plan)->bitmapplans)
|
xplan_collect((Plan *) lfirst(lc), rtable, my_id, depth + 1,
|
next_id, rows);
|
return;
|
}
|
if (IsA(plan, BitmapOr))
|
{
|
foreach(lc, ((BitmapOr *) plan)->bitmapplans)
|
xplan_collect((Plan *) lfirst(lc), rtable, my_id, depth + 1,
|
next_id, rows);
|
return;
|
}
|
if (IsA(plan, SubqueryScan))
|
{
|
xplan_collect(((SubqueryScan *) plan)->subplan, rtable, my_id, depth + 1,
|
next_id, rows);
|
return;
|
}
|
if (plan->lefttree)
|
xplan_collect(plan->lefttree, rtable, my_id, depth + 1, next_id, rows);
|
if (plan->righttree)
|
xplan_collect(plan->righttree, rtable, my_id, depth + 1, next_id, rows);
|
}
|
|
static char *
|
xplan_quoted_rel(const char *rel)
|
{
|
const char *dot = strchr(rel, '.');
|
|
if (dot == NULL)
|
return pstrdup(quote_identifier(rel));
|
|
{
|
char *schema = pnstrdup(rel, dot - rel);
|
char *name = pstrdup(dot + 1);
|
char *quoted = psprintf("%s.%s",
|
quote_identifier(schema),
|
quote_identifier(name));
|
|
pfree(schema);
|
pfree(name);
|
return quoted;
|
}
|
}
|
|
static void
|
xplan_insert_row(const char *sql, const char *statement_id, XPlanRow *row)
|
{
|
Oid argtypes[11];
|
Datum values[11];
|
char nulls[11];
|
int i;
|
int rc;
|
|
for (i = 0; i < 11; i++)
|
{
|
argtypes[i] = TEXTOID;
|
nulls[i] = ' ';
|
values[i] = (Datum) 0;
|
}
|
|
values[0] = CStringGetTextDatum(statement_id);
|
values[1] = CStringGetTextDatum(psprintf("%d", row->id));
|
if (row->parent_null)
|
nulls[2] = 'n';
|
else
|
values[2] = CStringGetTextDatum(psprintf("%d", row->parent_id));
|
values[3] = CStringGetTextDatum(psprintf("%d", row->depth));
|
values[4] = CStringGetTextDatum(row->operation);
|
if (row->options)
|
values[5] = CStringGetTextDatum(row->options);
|
else
|
nulls[5] = 'n';
|
if (row->object_name)
|
values[6] = CStringGetTextDatum(row->object_name);
|
else
|
nulls[6] = 'n';
|
values[7] = CStringGetTextDatum(row->cost);
|
values[8] = CStringGetTextDatum(row->cardinality);
|
values[9] = CStringGetTextDatum(row->bytes);
|
if (row->qblock_name)
|
values[10] = CStringGetTextDatum(row->qblock_name);
|
else
|
nulls[10] = 'n';
|
|
rc = SPI_execute_with_args(sql, 11, argtypes, values, nulls, false, 0);
|
if (rc != SPI_OK_INSERT)
|
elog(ERROR, "dbms_xplan: could not insert plan row");
|
}
|
|
void
|
dbms_xplan_store_plan(Query *query, const char *query_string,
|
const char *statement_id, const char *into_rel)
|
{
|
PlannedStmt *planned;
|
List *rows = NIL;
|
int next_id = 1;
|
XPlanRow root;
|
const char *target;
|
char *quoted;
|
char *insert_sql;
|
char *delete_sql;
|
ListCell *lc;
|
int rc;
|
const char *create_sql =
|
"CREATE TABLE IF NOT EXISTS plan_table ("
|
"statement_id text, plan_id numeric, timestamp timestamp, remarks text, "
|
"operation text, options text, object_node text, object_owner text, "
|
"object_name text, object_alias text, object_instance numeric, "
|
"object_type text, optimizer text, search_columns numeric, "
|
"id numeric, parent_id numeric, depth numeric, position numeric, "
|
"cost numeric, cardinality numeric, bytes numeric, other_tag text, "
|
"partition_start text, partition_stop text, partition_id numeric, "
|
"other text, other_xml text, distribution text, cpu_cost numeric, "
|
"io_cost numeric, temp_space numeric, access_predicates text, "
|
"filter_predicates text, projection text, time numeric, qblock_name text)";
|
|
if (query->commandType == CMD_UTILITY)
|
return;
|
|
planned = pg_plan_query(query, query_string, CURSOR_OPT_PARALLEL_OK, NULL, NULL);
|
if (planned == NULL || planned->planTree == NULL)
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("EXPLAIN PLAN could not build a plan")));
|
|
memset(&root, 0, sizeof(root));
|
root.id = 0;
|
root.parent_null = true;
|
root.depth = 0;
|
root.qblock_name = "SEL$1";
|
switch (query->commandType)
|
{
|
case CMD_INSERT:
|
root.operation = "INSERT STATEMENT";
|
break;
|
case CMD_UPDATE:
|
root.operation = "UPDATE STATEMENT";
|
break;
|
case CMD_DELETE:
|
root.operation = "DELETE STATEMENT";
|
break;
|
default:
|
root.operation = "SELECT STATEMENT";
|
break;
|
}
|
root.cost = psprintf("%.0f", planned->planTree->total_cost);
|
root.cardinality = psprintf("%.0f", planned->planTree->plan_rows);
|
root.bytes = psprintf("%lld",
|
(long long) planned->planTree->plan_width *
|
(long long) planned->planTree->plan_rows);
|
rows = list_make1(&root);
|
xplan_collect(planned->planTree, planned->rtable, 0, 1, &next_id, &rows);
|
|
target = (into_rel != NULL && into_rel[0] != '\0') ? into_rel : "plan_table";
|
quoted = xplan_quoted_rel(target);
|
|
if (SPI_connect() != SPI_OK_CONNECT)
|
elog(ERROR, "dbms_xplan: SPI_connect failed");
|
|
PG_TRY();
|
{
|
if (into_rel == NULL)
|
{
|
int save_messages = client_min_messages;
|
|
client_min_messages = WARNING;
|
rc = SPI_execute(create_sql, false, 0);
|
client_min_messages = save_messages;
|
if (rc != SPI_OK_UTILITY)
|
elog(ERROR, "dbms_xplan: could not create PLAN_TABLE");
|
}
|
|
delete_sql = psprintf("DELETE FROM %s WHERE statement_id = $1", quoted);
|
{
|
Oid argtypes[1] = {TEXTOID};
|
Datum values[1];
|
char nulls[1] = {' '};
|
|
values[0] = CStringGetTextDatum(statement_id);
|
rc = SPI_execute_with_args(delete_sql, 1, argtypes, values, nulls, false, 0);
|
if (rc != SPI_OK_DELETE)
|
elog(ERROR, "dbms_xplan: could not replace plan rows");
|
}
|
|
insert_sql = psprintf(
|
"INSERT INTO %s (statement_id, plan_id, \"timestamp\", id, parent_id, depth, "
|
"operation, options, object_name, cost, cardinality, bytes, qblock_name) "
|
"VALUES ($1, 1, clock_timestamp(), $2::numeric, $3::numeric, $4::numeric, $5, $6, $7, "
|
"$8::numeric, $9::numeric, $10::numeric, $11)",
|
quoted);
|
foreach(lc, rows)
|
xplan_insert_row(insert_sql, statement_id, (XPlanRow *) lfirst(lc));
|
|
ereport(LOG,
|
(errmsg("dbms_xplan: explain plan"),
|
errdetail_internal("statement_id=%s into=%s rows=%d",
|
statement_id, target, list_length(rows))));
|
SPI_finish();
|
}
|
PG_CATCH();
|
{
|
SPI_finish();
|
PG_RE_THROW();
|
}
|
PG_END_TRY();
|
}
|
|
typedef struct XPlanFmt
|
{
|
bool show_rows;
|
bool show_bytes;
|
bool show_cost;
|
bool show_projection;
|
bool warn_stats;
|
} XPlanFmt;
|
|
typedef struct XPlanFetched
|
{
|
int id;
|
int depth;
|
char *operation;
|
char *options;
|
char *object_name;
|
char *cardinality;
|
char *bytes;
|
char *cost;
|
} XPlanFetched;
|
|
static char *
|
xplan_text_arg(FunctionCallInfo fcinfo, int argn)
|
{
|
char *value;
|
|
if (PG_NARGS() <= argn || PG_ARGISNULL(argn))
|
return NULL;
|
value = text_to_cstring(PG_GETARG_TEXT_PP(argn));
|
if (value[0] == '\0')
|
{
|
pfree(value);
|
return NULL;
|
}
|
return value;
|
}
|
|
static char *
|
xplan_upper_dup(const char *src)
|
{
|
char *out;
|
char *p;
|
|
if (src == NULL)
|
return NULL;
|
out = pstrdup(src);
|
for (p = out; *p; p++)
|
*p = pg_toupper((unsigned char) *p);
|
return out;
|
}
|
|
static void
|
xplan_parse_format(const char *format, XPlanFmt *fmt)
|
{
|
char *copy;
|
char *tokens[32];
|
int n = 0;
|
int i;
|
char *p;
|
|
fmt->show_rows = true;
|
fmt->show_bytes = true;
|
fmt->show_cost = true;
|
fmt->show_projection = false;
|
fmt->warn_stats = false;
|
if (format == NULL)
|
return;
|
|
copy = xplan_upper_dup(format);
|
for (p = copy; *p; p++)
|
{
|
if (*p == ',' || *p == '\t' || *p == '\n' || *p == '\r')
|
*p = ' ';
|
}
|
p = copy;
|
while (*p && n < 32)
|
{
|
while (*p == ' ')
|
p++;
|
if (*p == '\0')
|
break;
|
tokens[n++] = p;
|
while (*p && *p != ' ')
|
p++;
|
if (*p)
|
{
|
*p = '\0';
|
p++;
|
}
|
}
|
|
for (i = 0; i < n; i++)
|
{
|
if (strcmp(tokens[i], "BASIC") == 0)
|
{
|
fmt->show_rows = false;
|
fmt->show_bytes = false;
|
fmt->show_cost = false;
|
fmt->show_projection = false;
|
}
|
else if (strcmp(tokens[i], "ALL") == 0)
|
{
|
fmt->show_rows = true;
|
fmt->show_bytes = true;
|
fmt->show_cost = true;
|
fmt->show_projection = true;
|
}
|
else if (strcmp(tokens[i], "TYPICAL") == 0)
|
{
|
fmt->show_rows = true;
|
fmt->show_bytes = true;
|
fmt->show_cost = true;
|
fmt->show_projection = false;
|
}
|
}
|
|
for (i = 0; i < n; i++)
|
{
|
const char *key = tokens[i];
|
bool enable = true;
|
|
if (strcmp(key, "BASIC") == 0 || strcmp(key, "TYPICAL") == 0 ||
|
strcmp(key, "ALL") == 0)
|
continue;
|
if (key[0] == '+' || key[0] == '-')
|
{
|
enable = (key[0] == '+');
|
key++;
|
}
|
if (strcmp(key, "ROWS") == 0)
|
fmt->show_rows = enable;
|
else if (strcmp(key, "BYTES") == 0)
|
fmt->show_bytes = enable;
|
else if (strcmp(key, "COST") == 0)
|
fmt->show_cost = enable;
|
else if (strcmp(key, "PROJECTION") == 0)
|
fmt->show_projection = enable;
|
else if (strcmp(key, "IOSTATS") == 0 || strcmp(key, "MEMSTATS") == 0 ||
|
strcmp(key, "ALLSTATS") == 0)
|
fmt->warn_stats = true;
|
}
|
pfree(copy);
|
}
|
|
static void
|
xplan_lines(FunctionCallInfo fcinfo, const char *what, List *lines)
|
{
|
ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
|
ListCell *lc;
|
const char *status = "empty";
|
|
if (lines != NIL)
|
status = (const char *) linitial(lines);
|
ereport(LOG,
|
(errmsg("dbms_xplan: %s", what),
|
errdetail_internal("Output: [Status: %s, rows: %d]",
|
status, list_length(lines))));
|
|
if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
|
ereport(ERROR,
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
errmsg("set-valued function called in context that cannot accept a set")));
|
|
InitMaterializedSRF(fcinfo, MAT_SRF_USE_EXPECTED_DESC | MAT_SRF_BLESS);
|
if (rsinfo->setDesc->natts != 1)
|
elog(ERROR, "dbms_xplan: expected one output column");
|
|
foreach(lc, lines)
|
{
|
Datum values[1];
|
bool nulls[1];
|
|
values[0] = CStringGetTextDatum((char *) lfirst(lc));
|
nulls[0] = false;
|
tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
|
}
|
}
|
|
static char *
|
xplan_fold_rel(const char *table_arg)
|
{
|
char *copy;
|
char *p;
|
|
if (table_arg == NULL)
|
return pstrdup("plan_table");
|
copy = pstrdup(table_arg);
|
for (p = copy; *p; p++)
|
*p = pg_tolower((unsigned char) *p);
|
return copy;
|
}
|
|
static bool
|
xplan_rel_exists(const char *rel)
|
{
|
const char *dot = strchr(rel, '.');
|
RangeVar *rv;
|
Oid relid;
|
|
if (dot != NULL)
|
{
|
char *schema = pnstrdup(rel, dot - rel);
|
char *name = pstrdup(dot + 1);
|
|
rv = makeRangeVar(schema, name, -1);
|
}
|
else
|
rv = makeRangeVar(NULL, pstrdup(rel), -1);
|
relid = RangeVarGetRelid(rv, NoLock, true);
|
return OidIsValid(relid);
|
}
|
|
static bool
|
xplan_filter_unsafe(const char *filter)
|
{
|
bool in_quote = false;
|
|
for (; filter && *filter; filter++)
|
{
|
if (*filter == '\'')
|
{
|
if (in_quote && filter[1] == '\'')
|
{
|
filter++;
|
continue;
|
}
|
in_quote = !in_quote;
|
}
|
else if (!in_quote && *filter == ';')
|
return true;
|
}
|
return false;
|
}
|
|
static char *
|
xplan_quoted_ident(const char *message)
|
{
|
const char *open;
|
const char *close;
|
char *ident;
|
char *p;
|
|
if (message == NULL)
|
return pstrdup("UNKNOWN");
|
open = strchr(message, '"');
|
if (open == NULL)
|
return pstrdup("UNKNOWN");
|
close = strchr(open + 1, '"');
|
if (close == NULL || close == open + 1)
|
return pstrdup("UNKNOWN");
|
ident = pnstrdup(open + 1, close - open - 1);
|
for (p = ident; *p; p++)
|
*p = pg_toupper((unsigned char) *p);
|
return ident;
|
}
|
|
static List *
|
xplan_format_lines(List *rows, const XPlanFmt *fmt)
|
{
|
List *lines = NIL;
|
StringInfoData buf;
|
ListCell *lc;
|
|
initStringInfo(&buf);
|
appendStringInfoString(&buf, "| Id | Operation | Name |");
|
if (fmt->show_rows)
|
appendStringInfoString(&buf, " Rows |");
|
if (fmt->show_bytes)
|
appendStringInfoString(&buf, " Bytes |");
|
if (fmt->show_cost)
|
appendStringInfoString(&buf, " Cost |");
|
lines = lappend(lines, pstrdup(buf.data));
|
|
foreach(lc, rows)
|
{
|
XPlanFetched *row = (XPlanFetched *) lfirst(lc);
|
char *name = xplan_upper_dup(row->object_name);
|
const char *op = row->operation != NULL ? row->operation : "";
|
int depth;
|
|
resetStringInfo(&buf);
|
appendStringInfo(&buf, "| %d | ", row->id);
|
for (depth = 0; depth < row->depth; depth++)
|
appendStringInfoChar(&buf, ' ');
|
appendStringInfoString(&buf, op);
|
if (row->options != NULL && row->options[0] != '\0')
|
appendStringInfo(&buf, " %s", row->options);
|
appendStringInfo(&buf, " | %s |", name != NULL ? name : "");
|
if (fmt->show_rows)
|
appendStringInfo(&buf, " %s |",
|
row->cardinality != NULL ? row->cardinality : "");
|
if (fmt->show_bytes)
|
appendStringInfo(&buf, " %s |",
|
row->bytes != NULL ? row->bytes : "");
|
if (fmt->show_cost)
|
appendStringInfo(&buf, " %s |",
|
row->cost != NULL ? row->cost : "");
|
lines = lappend(lines, pstrdup(buf.data));
|
if (name != NULL)
|
pfree(name);
|
}
|
|
if (fmt->show_projection)
|
lines = lappend(lines,
|
pstrdup("Column Projection Information (identified by operation id):"));
|
if (fmt->warn_stats)
|
lines = lappend(lines, pstrdup("BASIC PLAN STATISTICS NOT AVAILABLE"));
|
pfree(buf.data);
|
return lines;
|
}
|
|
static char *
|
xplan_copy_field(HeapTuple tuple, TupleDesc tupdesc, int fnumber)
|
{
|
char *value = SPI_getvalue(tuple, tupdesc, fnumber);
|
|
if (value == NULL)
|
return NULL;
|
return pstrdup(value);
|
}
|
|
static List *
|
xplan_missing_lines(const char *relname, const char *statement_id, const char *filter)
|
{
|
if (strcmp(relname, "plan_table") != 0)
|
return list_make1(pstrdup("ORA-00942: table or view does not exist"));
|
if (filter != NULL)
|
return list_make1(psprintf("ORA-00904: \"%s\": invalid identifier",
|
xplan_upper_dup(filter)));
|
if (statement_id != NULL)
|
return list_make1(psprintf("Error: cannot fetch plan for statement_id '%s'",
|
statement_id));
|
return list_make1(pstrdup("Error: cannot fetch last explain plan from PLAN_TABLE"));
|
}
|
|
typedef struct XPlanLoad
|
{
|
bool ok;
|
List *rows;
|
char *detail;
|
} XPlanLoad;
|
|
static XPlanLoad
|
xplan_load(const char *relname, const char *statement_id, const char *filter)
|
{
|
XPlanLoad load;
|
char *quoted;
|
char *where_sql;
|
char *query_sql;
|
MemoryContext caller = CurrentMemoryContext;
|
volatile int failed = 0;
|
volatile int sqlerrcode = 0;
|
char *errmsg = NULL;
|
|
memset(&load, 0, sizeof(load));
|
load.rows = NIL;
|
|
if (xplan_filter_unsafe(filter) || !xplan_rel_exists(relname))
|
{
|
List *lines = xplan_filter_unsafe(filter)
|
? list_make1(pstrdup("ORA-00936: missing expression"))
|
: xplan_missing_lines(relname, statement_id, filter);
|
|
load.detail = (char *) linitial(lines);
|
return load;
|
}
|
|
quoted = xplan_quoted_rel(relname);
|
if (filter != NULL && statement_id != NULL)
|
where_sql = psprintf("(%s) AND statement_id = $1", filter);
|
else if (filter != NULL)
|
where_sql = psprintf("(%s)", filter);
|
else if (statement_id != NULL)
|
where_sql = pstrdup("statement_id = $1");
|
else
|
where_sql = psprintf(
|
"statement_id IS NOT DISTINCT FROM (SELECT statement_id FROM %s "
|
"ORDER BY \"timestamp\" DESC NULLS LAST, ctid DESC LIMIT 1)",
|
quoted);
|
query_sql = psprintf(
|
"SELECT id, depth, operation, options, object_name, cardinality, bytes, cost "
|
"FROM %s WHERE %s ORDER BY id",
|
quoted, where_sql);
|
|
BeginInternalSubTransaction(NULL);
|
PG_TRY();
|
{
|
int rc;
|
uint64 i;
|
MemoryContext spi_ctx;
|
|
if (SPI_connect() != SPI_OK_CONNECT)
|
elog(ERROR, "dbms_xplan: SPI_connect failed");
|
|
if (statement_id != NULL)
|
{
|
Oid argtypes[1] = {TEXTOID};
|
Datum values[1];
|
char nulls[1] = {' '};
|
|
values[0] = CStringGetTextDatum(statement_id);
|
rc = SPI_execute_with_args(query_sql, 1, argtypes, values, nulls, true, 0);
|
}
|
else
|
rc = SPI_execute(query_sql, true, 0);
|
|
if (rc != SPI_OK_SELECT)
|
elog(ERROR, "dbms_xplan: could not read plan table");
|
|
spi_ctx = CurrentMemoryContext;
|
MemoryContextSwitchTo(caller);
|
for (i = 0; i < SPI_processed; i++)
|
{
|
HeapTuple tuple = SPI_tuptable->vals[i];
|
TupleDesc tupdesc = SPI_tuptable->tupdesc;
|
XPlanFetched *row = (XPlanFetched *) palloc0(sizeof(XPlanFetched));
|
char *id_text = SPI_getvalue(tuple, tupdesc, 1);
|
char *depth_text = SPI_getvalue(tuple, tupdesc, 2);
|
|
if (id_text != NULL)
|
row->id = atoi(id_text);
|
if (depth_text != NULL)
|
row->depth = atoi(depth_text);
|
row->operation = xplan_copy_field(tuple, tupdesc, 3);
|
row->options = xplan_copy_field(tuple, tupdesc, 4);
|
row->object_name = xplan_copy_field(tuple, tupdesc, 5);
|
row->cardinality = xplan_copy_field(tuple, tupdesc, 6);
|
row->bytes = xplan_copy_field(tuple, tupdesc, 7);
|
row->cost = xplan_copy_field(tuple, tupdesc, 8);
|
load.rows = lappend(load.rows, row);
|
}
|
MemoryContextSwitchTo(spi_ctx);
|
SPI_finish();
|
ReleaseCurrentSubTransaction();
|
}
|
PG_CATCH();
|
{
|
ErrorData *edata;
|
|
MemoryContextSwitchTo(caller);
|
edata = CopyErrorData();
|
sqlerrcode = edata->sqlerrcode;
|
errmsg = pstrdup(edata->message != NULL ? edata->message : "");
|
FreeErrorData(edata);
|
FlushErrorState();
|
RollbackAndReleaseCurrentSubTransaction();
|
failed = 1;
|
}
|
PG_END_TRY();
|
MemoryContextSwitchTo(caller);
|
|
if (failed)
|
{
|
if (sqlerrcode == ERRCODE_UNDEFINED_TABLE)
|
load.detail = pstrdup("ORA-00942: table or view does not exist");
|
else if (sqlerrcode == ERRCODE_UNDEFINED_COLUMN)
|
load.detail = psprintf("ORA-00904: \"%s\": invalid identifier",
|
xplan_quoted_ident(errmsg));
|
else if (sqlerrcode == ERRCODE_SYNTAX_ERROR)
|
load.detail = pstrdup("ORA-00936: missing expression");
|
else
|
load.detail = errmsg != NULL ? errmsg : pstrdup("ORA-00936: missing expression");
|
load.rows = NIL;
|
return load;
|
}
|
|
if (load.rows == NIL)
|
{
|
if (statement_id != NULL)
|
load.detail = psprintf("Error: cannot fetch plan for statement_id '%s'",
|
statement_id);
|
else if (filter != NULL)
|
load.detail = pstrdup("Error: cannot fetch specified explain plan from PLAN_TABLE");
|
else
|
load.detail = pstrdup("Error: cannot fetch last explain plan from PLAN_TABLE");
|
return load;
|
}
|
|
load.ok = true;
|
return load;
|
}
|
|
static void
|
xplan_xml_text(StringInfo buf, const char *src)
|
{
|
for (; src != NULL && *src != '\0'; src++)
|
{
|
if (*src == '<')
|
appendStringInfoString(buf, "<");
|
else if (*src == '>')
|
appendStringInfoString(buf, ">");
|
else if (*src == '&')
|
appendStringInfoString(buf, "&");
|
else
|
appendStringInfoChar(buf, *src);
|
}
|
}
|
|
static char *
|
xplan_report_xml(List *rows, const XPlanFmt *fmt)
|
{
|
StringInfoData buf;
|
ListCell *lc;
|
|
initStringInfo(&buf);
|
appendStringInfoString(&buf, "<report>");
|
foreach(lc, rows)
|
{
|
XPlanFetched *row = (XPlanFetched *) lfirst(lc);
|
char *name = xplan_upper_dup(row->object_name);
|
|
appendStringInfoString(&buf, "<operation>");
|
xplan_xml_text(&buf, row->operation);
|
if (row->options != NULL && row->options[0] != '\0')
|
{
|
appendStringInfoChar(&buf, ' ');
|
xplan_xml_text(&buf, row->options);
|
}
|
appendStringInfoString(&buf, "</operation>");
|
if (name != NULL)
|
{
|
appendStringInfoString(&buf, "<object>");
|
xplan_xml_text(&buf, name);
|
appendStringInfoString(&buf, "</object>");
|
pfree(name);
|
}
|
if (fmt->show_cost && row->cost != NULL)
|
{
|
appendStringInfoString(&buf, "<cost>");
|
xplan_xml_text(&buf, row->cost);
|
appendStringInfoString(&buf, "</cost>");
|
}
|
}
|
appendStringInfoString(&buf, "</report>");
|
return buf.data;
|
}
|
|
Datum
|
dbms_xplan_display(PG_FUNCTION_ARGS)
|
{
|
char *table_arg = xplan_text_arg(fcinfo, 0);
|
char *statement_id = xplan_text_arg(fcinfo, 1);
|
char *format = xplan_text_arg(fcinfo, 2);
|
char *filter = xplan_text_arg(fcinfo, 3);
|
char *relname = xplan_fold_rel(table_arg);
|
XPlanFmt fmt;
|
XPlanLoad load;
|
List *lines;
|
|
xplan_parse_format(format, &fmt);
|
load = xplan_load(relname, statement_id, filter);
|
if (!load.ok)
|
lines = list_make1(load.detail);
|
else
|
lines = xplan_format_lines(load.rows, &fmt);
|
xplan_lines(fcinfo, "display", lines);
|
PG_RETURN_NULL();
|
}
|
|
Datum
|
dbms_xplan_display_plan(PG_FUNCTION_ARGS)
|
{
|
char *table_arg = xplan_text_arg(fcinfo, 0);
|
char *statement_id = xplan_text_arg(fcinfo, 1);
|
char *format = xplan_text_arg(fcinfo, 2);
|
char *filter = xplan_text_arg(fcinfo, 3);
|
char *type_arg = xplan_text_arg(fcinfo, 4);
|
char *type_up = type_arg != NULL ? xplan_upper_dup(type_arg) : NULL;
|
char *relname = xplan_fold_rel(table_arg);
|
XPlanFmt fmt;
|
XPlanLoad load;
|
char *result;
|
|
xplan_parse_format(format, &fmt);
|
|
if (type_up != NULL && strcmp(type_up, "HTML") == 0)
|
{
|
ereport(LOG,
|
(errmsg("dbms_xplan: display_plan"),
|
errdetail_internal("Output: [Status: empty, type: HTML]")));
|
PG_RETURN_NULL();
|
}
|
|
load = xplan_load(relname, statement_id, filter);
|
if (!load.ok)
|
result = load.detail;
|
else if (type_up != NULL && strcmp(type_up, "TEXT") == 0)
|
result = pstrdup("ORA-31011: XML parsing failed");
|
else if (type_up != NULL && strcmp(type_up, "ACTIVE") == 0)
|
result = pstrdup("<html></html>");
|
else
|
result = xplan_report_xml(load.rows, &fmt);
|
|
ereport(LOG,
|
(errmsg("dbms_xplan: display_plan"),
|
errdetail_internal("Output: [Status: %s]", result)));
|
PG_RETURN_TEXT_P(cstring_to_text(result));
|
}
|
|
Datum
|
dbms_xplan_compare_plans(PG_FUNCTION_ARGS)
|
{
|
(void) fcinfo;
|
ereport(ERROR,
|
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
|
errmsg("the advisor task has not produced a result")));
|
PG_RETURN_NULL();
|
}
|
|
}
|