Added explain functionality.

Uses json format with jsoncpp as a parser. Then show it in a QTreeView.
Shows inclusive/exclusive times like explain.despesz does. Also a similar
coloring scheme as applied.
This commit is contained in:
Eelke Klein 2016-12-29 13:48:35 +01:00
parent 0d30dc9080
commit 8af6bc4ac5
14 changed files with 9089 additions and 33 deletions

View file

@ -21,14 +21,19 @@ SOURCES += main.cpp\
sqlparser.cpp \
PgsqlConn.cpp \
queryresultmodel.cpp \
sqlhighlighter.cpp
sqlhighlighter.cpp \
jsoncpp.cpp \
queryexplainmodel.cpp \
explaintreemodelitem.cpp
HEADERS += mainwindow.h \
serverproperties.h \
sqlparser.h \
PgsqlConn.h \
queryresultmodel.h \
sqlhighlighter.h
sqlhighlighter.h \
queryexplainmodel.h \
explaintreemodelitem.h
FORMS += mainwindow.ui \
serverproperties.ui

View file

@ -5,6 +5,44 @@
using namespace Pgsql;
namespace {
void set_stdstring_with_charptr(std::string &s, const char *p)
{
if (p) {
s = p;
}
else {
s.clear();
}
}
} // einde unnamed namespace
ErrorDetails ErrorDetails::createErrorDetailsFromPGresult(const PGresult *result)
{
ErrorDetails r;
set_stdstring_with_charptr(r.state, PQresultErrorField(result, PG_DIAG_SQLSTATE)); ///< PG_DIAG_SQLSTATE Error code as listed in https://www.postgresql.org/docs/9.5/static/errcodes-appendix.html
set_stdstring_with_charptr(r.severity, PQresultErrorField(result, PG_DIAG_SEVERITY));
set_stdstring_with_charptr(r.messagePrimary, PQresultErrorField(result, PG_DIAG_MESSAGE_PRIMARY));
set_stdstring_with_charptr(r.messageDetail, PQresultErrorField(result, PG_DIAG_MESSAGE_DETAIL));
set_stdstring_with_charptr(r.messageHint, PQresultErrorField(result, PG_DIAG_MESSAGE_HINT));
const char * p = PQresultErrorField(result, PG_DIAG_STATEMENT_POSITION);
r.statementPosition = p != nullptr ? atoi(p) : -1; ///< First character is one, measured in characters not bytes!
p = PQresultErrorField(result, PG_DIAG_INTERNAL_POSITION);
r.internalPosition = p != nullptr ? atoi(p) : -1;
set_stdstring_with_charptr(r.internalQuery, PQresultErrorField(result, PG_DIAG_INTERNAL_QUERY));
set_stdstring_with_charptr(r.context, PQresultErrorField(result, PG_DIAG_CONTEXT));
set_stdstring_with_charptr(r.schemaName, PQresultErrorField(result, PG_DIAG_SCHEMA_NAME));
set_stdstring_with_charptr(r.tableName, PQresultErrorField(result, PG_DIAG_TABLE_NAME));
set_stdstring_with_charptr(r.columnName, PQresultErrorField(result, PG_DIAG_COLUMN_NAME));
set_stdstring_with_charptr(r.datatypeName, PQresultErrorField(result, PG_DIAG_DATATYPE_NAME));
set_stdstring_with_charptr(r.constraintName, PQresultErrorField(result, PG_DIAG_CONSTRAINT_NAME));
set_stdstring_with_charptr(r.sourceFile, PQresultErrorField(result, PG_DIAG_SOURCE_FILE));
set_stdstring_with_charptr(r.sourceLine, PQresultErrorField(result, PG_DIAG_SOURCE_LINE));
set_stdstring_with_charptr(r.sourceFunction, PQresultErrorField(result, PG_DIAG_SOURCE_FUNCTION));
return r;
}
Result::Result(PGresult *res)
: result(res)
@ -52,6 +90,39 @@ std::string Result::getResStatus()
return "";
}
std::string Result::diagSqlState()
{
std::string s(PQresultErrorField(result, PG_DIAG_SQLSTATE));
return s;
}
ErrorDetails Result::diagDetails()
{
// ErrorDetails r;
// r.state = PQresultErrorField(result, PG_DIAG_SQLSTATE); ///< PG_DIAG_SQLSTATE Error code as listed in https://www.postgresql.org/docs/9.5/static/errcodes-appendix.html
// r.severity = PQresultErrorField(result, PG_DIAG_SEVERITY);
// r.messagePrimary = PQresultErrorField(result, PG_DIAG_MESSAGE_PRIMARY);
// r.messageDetail = PQresultErrorField(result, PG_DIAG_MESSAGE_DETAIL);
// r.messageHint = PQresultErrorField(result, PG_DIAG_MESSAGE_HINT);
// r.statementPosition = atoi(PQresultErrorField(result, PG_DIAG_STATEMENT_POSITION)); ///< First character is one, measured in characters not bytes!
// r.internalPosition = atoi(PQresultErrorField(result, PG_DIAG_INTERNAL_POSITION));
// r.internalQuery = PQresultErrorField(result, PG_DIAG_INTERNAL_QUERY);
// r.context = PQresultErrorField(result, PG_DIAG_CONTEXT);
// r.schemaName = PQresultErrorField(result, PG_DIAG_SCHEMA_NAME);
// r.tableName = PQresultErrorField(result, PG_DIAG_TABLE_NAME);
// r.columnName = PQresultErrorField(result, PG_DIAG_COLUMN_NAME);
// r.datatypeName = PQresultErrorField(result, PG_DIAG_DATATYPE_NAME);
// r.constraintName = PQresultErrorField(result, PG_DIAG_CONSTRAINT_NAME);
// r.sourceFile = PQresultErrorField(result, PG_DIAG_SOURCE_FILE);
// r.sourceLine = PQresultErrorField(result, PG_DIAG_SOURCE_LINE);
// r.sourceFunction = PQresultErrorField(result, PG_DIAG_SOURCE_FUNCTION);
// return r;
return ErrorDetails::createErrorDetailsFromPGresult(result);
}
int Result::getRows() const
{
return PQntuples(result);
@ -73,6 +144,42 @@ const char * Result::getVal(int col, int row) const
}
Canceller::Canceller(PGcancel *c)
: m_cancel(c)
{}
Canceller::Canceller(Canceller&& rhs)
: m_cancel(rhs.m_cancel)
{
rhs.m_cancel = nullptr;
}
Canceller& Canceller::operator=(Canceller&& rhs)
{
if (m_cancel) {
PQfreeCancel(m_cancel);
}
m_cancel = rhs.m_cancel;
rhs.m_cancel = nullptr;
return *this;
}
Canceller::~Canceller()
{
if (m_cancel) {
PQfreeCancel(m_cancel);
}
}
void Canceller::cancel()
{
const int errbuf_size = 256;
char errbuf[errbuf_size];
PQcancel(m_cancel, errbuf, errbuf_size);
}
Connection::Connection() = default;
Connection::~Connection()
@ -102,6 +209,11 @@ void Connection::close()
}
}
Canceller Connection::getCancel()
{
Canceller c(PQgetCancel(conn));
return c;
}
bool Connection::connect(const char *params)
{
@ -150,13 +262,8 @@ std::string Connection::getErrorMessage() const
Result Connection::query(const char * command)
{
PGresult *result = PQexec(conn, command);
if (result) {
return Result(result);
}
else {
throw std::runtime_error("Failed to allocate result object");
}
}
bool Connection::sendQuery(const char *query)
@ -187,3 +294,17 @@ bool Connection::isBusy()
int res = PQisBusy(conn);
return res == 1;
}
void Connection::setNoticeReceiver(std::function<void(const PGresult *)> callback)
{
notifyReceiver = callback;
PQsetNoticeReceiver(conn,
Connection::notifyReceiveFunc
, reinterpret_cast<void*>(this));
}
void Connection::notifyReceiveFunc(void *arg, const PGresult *result)
{
Connection *c = reinterpret_cast<Connection *>(arg);
c->notifyReceiver(result);
}

View file

@ -10,6 +10,7 @@
namespace Pgsql {
class Connection;
/*
This library has multiple layers.
@ -31,6 +32,29 @@ namespace Pgsql {
};
class ErrorDetails {
public:
static ErrorDetails createErrorDetailsFromPGresult(const PGresult *res);
std::string state; ///< PG_DIAG_SQLSTATE Error code as listed in https://www.postgresql.org/docs/9.5/static/errcodes-appendix.html
std::string severity;
std::string messagePrimary;
std::string messageDetail;
std::string messageHint;
int statementPosition; ///< First character is one, measured in characters not bytes!
int internalPosition;
std::string internalQuery;
std::string context;
std::string schemaName;
std::string tableName;
std::string columnName;
std::string datatypeName;
std::string constraintName;
std::string sourceFile;
std::string sourceLine;
std::string sourceFunction;
};
/** Non-copyable but movable wrapper for a postgresql result. */
class Result {
public:
@ -76,8 +100,19 @@ namespace Pgsql {
operator bool() const;
ExecStatusType resultStatus();
std::string getResStatus();
/** Use this to retrieve an error code when this is an error result
*
* The possible code are listed in https://www.postgresql.org/docs/9.5/static/errcodes-appendix.html
*/
std::string diagSqlState();
/** Retrieves all the error fields. */
ErrorDetails diagDetails();
int getRows() const;
int getCols() const;
@ -91,6 +126,21 @@ namespace Pgsql {
PGresult *result = nullptr;
};
class Canceller {
public:
Canceller(PGcancel *c);
Canceller(const Canceller&) = delete;
Canceller& operator=(const Canceller&) = delete;
Canceller(Canceller&& rhs);
Canceller& operator=(Canceller&& rhs);
~Canceller();
void cancel();
private:
PGcancel *m_cancel;
};
class Connection {
public:
Connection();
@ -120,6 +170,7 @@ namespace Pgsql {
int socket();
void close();
Canceller getCancel();
std::string getErrorMessage() const;
@ -140,15 +191,14 @@ namespace Pgsql {
bool consumeInput();
bool isBusy();
void setNoticeReceiver(std::function<void(const PGresult *)> callback);
private:
PGconn *conn = nullptr;
std::function<void(const PGresult *)> notifyReceiver;
static void notifyReceiveFunc(void *arg, const PGresult *result);
};
class Canceller {
public:
void Cancel();
};

383
explaintreemodelitem.cpp Normal file
View file

@ -0,0 +1,383 @@
#include "explaintreemodelitem.h"
#include "json/json.h"
#include <limits>
namespace {
ExplainTreeModelItemPtr createPlanItemFromJson(Json::Value &plan)
{
ExplainTreeModelItemPtr result = std::make_shared<ExplainTreeModelItem>();
result->setNodeType(QString::fromStdString(plan["Node Type"].asString()));
result->setStrategy(QString::fromStdString(plan["Strategy"].asString()));
result->setJoinType(QString::fromStdString(plan["Join Type"].asString()));
result->setStartupCost(plan["Startup Cost"].asFloat());
result->setTotalCost(plan["Total Cost"].asFloat());
result->setEstimatedRows(plan["Plan Rows"].asInt());
result->setPlanWidth(plan["Plan Width"].asInt());
result->setActualStartupTime(plan["Actual Startup Time"].asFloat());
result->setActualTotalTime(plan["Actual Total Time"].asFloat());
result->setActualRows(plan["Actual Rows"].asInt());
result->setActualLoops(plan["Actual Loops"].asInt());
result->setRelationName(QString::fromStdString(plan["Relation Name"].asString()));
result->setAlias(QString::fromStdString(plan["Alias"].asString()));
result->setScanDirection(QString::fromStdString(plan["Scan Direction"].asString()));
result->setIndexName(QString::fromStdString(plan["Index Name"].asString()));
result->setIndexCondition(QString::fromStdString(plan["Index Cond"].asString()));
result->setIndexRecheck(QString::fromStdString(plan["Rows Removed by Index Recheck"].asString()));
result->setFilter(QString::fromStdString(plan["Filter"].asString()));
result->setHashCondition(QString::fromStdString(plan["Hash Cond"].asString()));
result->setSortKey(QString::fromStdString(plan["Sort Key"].toStyledString()));
result->setSortMethod(QString::fromStdString(plan["Sort Method"].asString()));
if (plan.isMember("Sort Space Used")) {
const Json::Value& sm = plan["Sort Space Used"];
if (sm.isInt()) {
result->setSortSpaceUsed(sm.asInt());
}
}
result->setSortSpaceType(QString::fromStdString(plan["Sort Space Type"].asString()));
Json::Value &plans = plan["Plans"];
if (plans.isArray()) {
for (auto p : plans) {
result->appendChild(
createPlanItemFromJson(p));
}
}
return result;
}
} // END of unnamed namespace
std::unique_ptr<ExplainRoot> ExplainRoot::createFromJson(Json::Value &json)
{
auto res = std::make_unique<ExplainRoot>();
// Explain always seems to be an array with one element
if (json.isArray()) {
if (json.size() > 0) {
Json::Value &explain = json[0];
Json::Value &plan = explain["Plan"];
res->plan = createPlanItemFromJson(plan);
res->planningTime = explain["Planning Time"].asFloat();
res->executionTime = explain["Execution Time"].asFloat();
}
}
return res;
}
ExplainTreeModelItem::ExplainTreeModelItem() = default;
ExplainTreeModelItem::~ExplainTreeModelItem() = default;
void ExplainTreeModelItem::appendChild(ItemPtr child)
{
child->setParent(shared_from_this());
m_childItems.push_back(child);
}
ExplainTreeModelItemPtr ExplainTreeModelItem::child(int row)
{
return m_childItems.at(row);
}
int ExplainTreeModelItem::childCount() const
{
return m_childItems.size();
}
//int ExplainTreeModelItem::columnCount() const
//{
// return 6;
//}
//QVariant ExplainTreeModelItem::data(int column) const
//{
// QVariant r;
// if (column == 0) {
// r = nodeType;
// }
// else if (column == 1) {
// }
// return r;
//}
int ExplainTreeModelItem::row() const
{
int idx = 0;
auto p = m_parentItem.lock();
if (p) {
idx = std::find(p->m_childItems.begin(), p->m_childItems.end(), shared_from_this()) - p->m_childItems.begin();
}
return idx;
}
void ExplainTreeModelItem::setParent(ItemPtr parent)
{
m_parentItem = parent;
}
ExplainTreeModelItemPtr ExplainTreeModelItem::parent()
{
auto p = m_parentItem.lock();
return p;
}
void ExplainTreeModelItem::setNodeType(QString nt)
{
m_nodeType = std::move(nt);
}
const QString& ExplainTreeModelItem::nodeType() const
{
return m_nodeType;
}
void ExplainTreeModelItem::setStrategy(QString strat)
{
m_strategy = std::move(strat);
}
const QString& ExplainTreeModelItem::strategy() const
{
return m_strategy;
}
void ExplainTreeModelItem::setJoinType(QString jointype)
{
m_joinType = jointype;
}
QString ExplainTreeModelItem::joinType() const
{
return m_joinType;
}
void ExplainTreeModelItem::setStartupCost(float cost)
{
m_startupCost = cost;
}
void ExplainTreeModelItem::setTotalCost(float cost)
{
m_totalCost = cost;
}
void ExplainTreeModelItem::setEstimatedRows(long long estimated)
{
m_estimatedRows = estimated;
}
long long ExplainTreeModelItem::estimatedRows() const
{
return m_estimatedRows;
}
void ExplainTreeModelItem::setPlanWidth(int width)
{
m_planWidth = width;
}
void ExplainTreeModelItem::setActualStartupTime(float timems)
{
m_actualStartupTime = timems;
}
void ExplainTreeModelItem::setActualTotalTime(float timems)
{
m_actualTotalTime = timems;
}
float ExplainTreeModelItem::actualTotalTime() const
{
return m_actualTotalTime;
}
void ExplainTreeModelItem::setActualRows(long long rowcount)
{
m_actualRows = rowcount;
}
long long ExplainTreeModelItem::actualRows() const
{
return m_actualRows;
}
void ExplainTreeModelItem::setActualLoops(int loopcount)
{
m_actualLoops = loopcount;
}
int ExplainTreeModelItem::actualLoops() const
{
return m_actualLoops;
}
void ExplainTreeModelItem::setRelationName(QString n)
{
m_relationName = std::move(n);
}
void ExplainTreeModelItem::setAlias(QString a)
{
m_alias = std::move(a);
}
void ExplainTreeModelItem::setScanDirection(QString dir)
{
m_scanDirection = std::move(dir);
}
void ExplainTreeModelItem::setIndexName(QString idxname)
{
m_indexName = std::move(idxname);
}
void ExplainTreeModelItem::setIndexCondition(QString idxcond)
{
m_indexCondition = std::move(idxcond);
}
void ExplainTreeModelItem::setIndexRecheck(QString idxrecheck)
{
m_indexRecheck = std::move(idxrecheck);
}
void ExplainTreeModelItem::setFilter(QString filter)
{
m_filter = std::move(filter);
}
void ExplainTreeModelItem::setHashCondition(QString condition)
{
m_hashCondition = std::move(condition);
}
void ExplainTreeModelItem::setSortKey(QString key)
{
m_sortKey = std::move(key);
}
void ExplainTreeModelItem::setSortMethod(QString method)
{
m_sortMethod = std::move(method);
}
void ExplainTreeModelItem::setSortSpaceUsed(int space)
{
m_sortSpaceUsed = space;
}
void ExplainTreeModelItem::setSortSpaceType(QString type)
{
m_sortSpaceType = std::move(type);
}
float ExplainTreeModelItem::exclusiveTime() const
{
float tt = inclusiveTime();
for (auto c : m_childItems) {
tt -= c->inclusiveTime();
}
return tt;
}
float ExplainTreeModelItem::inclusiveTime() const
{
float t = m_actualTotalTime * m_actualLoops;
return t;
}
float ExplainTreeModelItem::estimateError() const
{
float res = 1.0;
if (m_estimatedRows > m_actualRows) {
if (m_actualRows > 0) {
res = float(m_estimatedRows) / m_actualRows;
}
else {
res = std::numeric_limits<float>::infinity();
}
}
else if (m_actualRows > m_estimatedRows) {
if (m_estimatedRows > 0) {
res = float(m_actualRows) / m_estimatedRows;
}
else {
res = std::numeric_limits<float>::infinity();
}
res = -res;
}
return res;
}
QString ExplainTreeModelItem::detailString() const
{
QString s;
if (!m_joinType.isEmpty()) {
s += m_joinType + " " + m_nodeType + " ";
}
if (!m_strategy.isEmpty()) {
s += m_strategy + " " + m_nodeType + " ";
}
if (!m_indexName.isEmpty()) {
s+= m_scanDirection + " "
+ m_nodeType + "\n";
if (!m_indexCondition.isEmpty()) {
s += "cond: " + m_indexCondition + " ";
}
if (!m_filter.isEmpty()) {
s += "filter: " + m_filter + "\n";
}
if (!m_indexRecheck.isEmpty()) {
s += "removed by recheck: " + m_indexRecheck + "\n";
}
s += "idx: " + m_indexName + " rel: " + m_alias + " ";
}
else {
if (!m_alias.isEmpty()) {
s += m_nodeType + " rel: " + m_alias + " ";
}
}
if (!m_hashCondition.isEmpty()) {
s += m_hashCondition + " ";
}
if (!m_sortMethod.isEmpty()) {
s += m_sortMethod + " " + m_sortSpaceType + " "
+ QString::number(m_sortSpaceUsed) + "kB "
+ m_sortKey + " ";
}
return s.trimmed();
}
//"Sort Key": ["pg_attribute.attname"],
//"Sort Method": "quicksort",
//"Sort Space Used": 1426,
//"Sort Space Type": "Memory",
//{
// "Node Type": "Index Scan",
// "Parent Relationship": "Inner",
// "Scan Direction": "Forward",
// "Index Name": "pg_type_oid_index",
// "Relation Name": "pg_type",
// "Alias": "pg_type",
// "Startup Cost": 0.15,
// "Total Cost": 0.18,
// "Plan Rows": 1,
// "Plan Width": 758,
// "Actual Startup Time": 0.003,
// "Actual Total Time": 0.004,
// "Actual Rows": 1,
// "Actual Loops": 100,
// "Index Cond": "(oid = pg_attribute.atttypid)",
// "Rows Removed by Index Recheck": 0
// "Filter": "actief"
//}

139
explaintreemodelitem.h Normal file
View file

@ -0,0 +1,139 @@
#pragma once
#include <QList>
//#include <QVariant>
#include <vector>
#include <memory>
namespace Json {
class Value;
}
class ExplainTreeModelItem;
typedef std::shared_ptr<ExplainTreeModelItem> ExplainTreeModelItemPtr;
/* Columns for tree
* 0. explain text
* 1. exclusive times
* 2. inclusive
* 3. rows x
* 4. rows
* 5. loops
*/
class ExplainTreeModelItem: public std::enable_shared_from_this<ExplainTreeModelItem> {
public:
typedef std::shared_ptr<ExplainTreeModelItem> ItemPtr;
ExplainTreeModelItem();
~ExplainTreeModelItem();
ExplainTreeModelItem(const ExplainTreeModelItem &rhs) = delete;
ExplainTreeModelItem &operator=(const ExplainTreeModelItem &rhs) = delete;
void appendChild(ItemPtr child);
ExplainTreeModelItemPtr child(int row);
int childCount() const;
// int columnCount() const;
// QVariant data(int column) const;
int row() const;
void setParent(ItemPtr parent);
ItemPtr parent();
void setNodeType(QString nt);
const QString& nodeType() const;
void setStrategy(QString strat);
const QString& strategy() const;
void setJoinType(QString jointype);
QString joinType() const;
void setStartupCost(float cost);
void setTotalCost(float cost);
void setEstimatedRows(long long estimated);
long long estimatedRows() const;
void setPlanWidth(int width);
void setActualStartupTime(float timems);
void setActualTotalTime(float timems);
float actualTotalTime() const;
void setActualRows(long long rowcount);
long long actualRows() const;
void setActualLoops(int loopcount);
int actualLoops() const;
void setRelationName(QString n);
void setAlias(QString a);
void setScanDirection(QString dir);
void setIndexName(QString idxname);
void setIndexCondition(QString idxcond);
void setIndexRecheck(QString idxrecheck);
void setFilter(QString filter);
void setHashCondition(QString condition);
void setSortKey(QString key);
void setSortMethod(QString method);
void setSortSpaceUsed(int space);
void setSortSpaceType(QString type);
/** ActualTotalTime minus the actual total time of it's children */
float exclusiveTime() const;
float inclusiveTime() const;
float estimateError() const;
QString detailString() const;
private:
std::vector<ItemPtr> m_childItems;
std::weak_ptr<ExplainTreeModelItem> m_parentItem;
QString m_nodeType;
QString m_strategy;
QString m_joinType;
float m_startupCost = 0.f;
float m_totalCost = 0.f;
long long m_estimatedRows = 0;
int m_planWidth = 0;
float m_actualStartupTime = 0.f;
float m_actualTotalTime = 0.f;
long long m_actualRows = 0;
int m_actualLoops = 0;
QString m_relationName;
QString m_alias;
QString m_scanDirection;
QString m_indexName;
QString m_indexCondition;
QString m_indexRecheck;
QString m_filter;
QString m_hashCondition;
QString m_sortKey;
QString m_sortMethod;
int m_sortSpaceUsed = -1;
QString m_sortSpaceType;
// "Output": ["f1.id", "f1.program", "f1.version", "f1.lic_number", "f1.callstack_crc_1", "f1.callstack_crc_2", "array_agg(f2.id)"],
// "Group Key": ["f1.id"],
// "Shared Hit Blocks": 694427,
// "Shared Read Blocks": 0,
// "Shared Dirtied Blocks": 0,
// "Shared Written Blocks": 0,
// "Local Hit Blocks": 0,
// "Local Read Blocks": 0,
// "Local Dirtied Blocks": 0,
// "Local Written Blocks": 0,
// "Temp Read Blocks": 0,
// "Temp Written Blocks": 0
// "Parent Relationship": "Outer",
};
class ExplainRoot {
public:
static std::unique_ptr<ExplainRoot> createFromJson(Json::Value &json);
ExplainTreeModelItemPtr plan;
float planningTime = 0.f;
// Triggers???
float executionTime = 0.f;
};

330
json/json-forwards.h Normal file
View file

@ -0,0 +1,330 @@
/// Json-cpp amalgated forward header (http://jsoncpp.sourceforge.net/).
/// It is intended to be used with #include "json/json-forwards.h"
/// This header provides forward declaration for all JsonCpp types.
// //////////////////////////////////////////////////////////////////////
// Beginning of content of file: LICENSE
// //////////////////////////////////////////////////////////////////////
/*
The JsonCpp library's source code, including accompanying documentation,
tests and demonstration applications, are licensed under the following
conditions...
The author (Baptiste Lepilleur) explicitly disclaims copyright in all
jurisdictions which recognize such a disclaimer. In such jurisdictions,
this software is released into the Public Domain.
In jurisdictions which do not recognize Public Domain property (e.g. Germany as of
2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is
released under the terms of the MIT License (see below).
In jurisdictions which recognize Public Domain property, the user of this
software may choose to accept it either as 1) Public Domain, 2) under the
conditions of the MIT License (see below), or 3) under the terms of dual
Public Domain/MIT License conditions described here, as they choose.
The MIT License is about as close to Public Domain as a license can get, and is
described in clear, concise terms at:
http://en.wikipedia.org/wiki/MIT_License
The full text of the MIT License follows:
========================================================================
Copyright (c) 2007-2010 Baptiste Lepilleur
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
========================================================================
(END LICENSE TEXT)
The MIT license is compatible with both the GPL and commercial
software, affording one all of the rights of Public Domain with the
minor nuisance of being required to keep the above copyright notice
and license text in the source code. Note also that by accepting the
Public Domain "license" you can re-license your copy using whatever
license you like.
*/
// //////////////////////////////////////////////////////////////////////
// End of content of file: LICENSE
// //////////////////////////////////////////////////////////////////////
#ifndef JSON_FORWARD_AMALGATED_H_INCLUDED
# define JSON_FORWARD_AMALGATED_H_INCLUDED
/// If defined, indicates that the source file is amalgated
/// to prevent private header inclusion.
#define JSON_IS_AMALGAMATION
// //////////////////////////////////////////////////////////////////////
// Beginning of content of file: include/json/config.h
// //////////////////////////////////////////////////////////////////////
// Copyright 2007-2010 Baptiste Lepilleur
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#ifndef JSON_CONFIG_H_INCLUDED
#define JSON_CONFIG_H_INCLUDED
#include <stddef.h>
#include <string> //typedef String
#include <stdint.h> //typedef int64_t, uint64_t
/// If defined, indicates that json library is embedded in CppTL library.
//# define JSON_IN_CPPTL 1
/// If defined, indicates that json may leverage CppTL library
//# define JSON_USE_CPPTL 1
/// If defined, indicates that cpptl vector based map should be used instead of
/// std::map
/// as Value container.
//# define JSON_USE_CPPTL_SMALLMAP 1
// If non-zero, the library uses exceptions to report bad input instead of C
// assertion macros. The default is to use exceptions.
#ifndef JSON_USE_EXCEPTION
#define JSON_USE_EXCEPTION 1
#endif
/// If defined, indicates that the source file is amalgated
/// to prevent private header inclusion.
/// Remarks: it is automatically defined in the generated amalgated header.
// #define JSON_IS_AMALGAMATION
#ifdef JSON_IN_CPPTL
#include <cpptl/config.h>
#ifndef JSON_USE_CPPTL
#define JSON_USE_CPPTL 1
#endif
#endif
#ifdef JSON_IN_CPPTL
#define JSON_API CPPTL_API
#elif defined(JSON_DLL_BUILD)
#if defined(_MSC_VER) || defined(__MINGW32__)
#define JSON_API __declspec(dllexport)
#define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
#endif // if defined(_MSC_VER)
#elif defined(JSON_DLL)
#if defined(_MSC_VER) || defined(__MINGW32__)
#define JSON_API __declspec(dllimport)
#define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
#endif // if defined(_MSC_VER)
#endif // ifdef JSON_IN_CPPTL
#if !defined(JSON_API)
#define JSON_API
#endif
// If JSON_NO_INT64 is defined, then Json only support C++ "int" type for
// integer
// Storages, and 64 bits integer support is disabled.
// #define JSON_NO_INT64 1
#if defined(_MSC_VER) // MSVC
# if _MSC_VER <= 1200 // MSVC 6
// Microsoft Visual Studio 6 only support conversion from __int64 to double
// (no conversion from unsigned __int64).
# define JSON_USE_INT64_DOUBLE_CONVERSION 1
// Disable warning 4786 for VS6 caused by STL (identifier was truncated to '255'
// characters in the debug information)
// All projects I've ever seen with VS6 were using this globally (not bothering
// with pragma push/pop).
# pragma warning(disable : 4786)
# endif // MSVC 6
# if _MSC_VER >= 1500 // MSVC 2008
/// Indicates that the following function is deprecated.
# define JSONCPP_DEPRECATED(message) __declspec(deprecated(message))
# endif
#endif // defined(_MSC_VER)
// In c++11 the override keyword allows you to explicity define that a function
// is intended to override the base-class version. This makes the code more
// managable and fixes a set of common hard-to-find bugs.
#if __cplusplus >= 201103L
# define JSONCPP_OVERRIDE override
# define JSONCPP_NOEXCEPT noexcept
#elif defined(_MSC_VER) && _MSC_VER > 1600 && _MSC_VER < 1900
# define JSONCPP_OVERRIDE override
# define JSONCPP_NOEXCEPT throw()
#elif defined(_MSC_VER) && _MSC_VER >= 1900
# define JSONCPP_OVERRIDE override
# define JSONCPP_NOEXCEPT noexcept
#else
# define JSONCPP_OVERRIDE
# define JSONCPP_NOEXCEPT throw()
#endif
#ifndef JSON_HAS_RVALUE_REFERENCES
#if defined(_MSC_VER) && _MSC_VER >= 1600 // MSVC >= 2010
#define JSON_HAS_RVALUE_REFERENCES 1
#endif // MSVC >= 2010
#ifdef __clang__
#if __has_feature(cxx_rvalue_references)
#define JSON_HAS_RVALUE_REFERENCES 1
#endif // has_feature
#elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
#if defined(__GXX_EXPERIMENTAL_CXX0X__) || (__cplusplus >= 201103L)
#define JSON_HAS_RVALUE_REFERENCES 1
#endif // GXX_EXPERIMENTAL
#endif // __clang__ || __GNUC__
#endif // not defined JSON_HAS_RVALUE_REFERENCES
#ifndef JSON_HAS_RVALUE_REFERENCES
#define JSON_HAS_RVALUE_REFERENCES 0
#endif
#ifdef __clang__
#elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
# if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
# define JSONCPP_DEPRECATED(message) __attribute__ ((deprecated(message)))
# elif (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
# define JSONCPP_DEPRECATED(message) __attribute__((__deprecated__))
# endif // GNUC version
#endif // __clang__ || __GNUC__
#if !defined(JSONCPP_DEPRECATED)
#define JSONCPP_DEPRECATED(message)
#endif // if !defined(JSONCPP_DEPRECATED)
#if __GNUC__ >= 6
# define JSON_USE_INT64_DOUBLE_CONVERSION 1
#endif
#if !defined(JSON_IS_AMALGAMATION)
# include "version.h"
# if JSONCPP_USING_SECURE_MEMORY
# include "allocator.h" //typedef Allocator
# endif
#endif // if !defined(JSON_IS_AMALGAMATION)
namespace Json {
typedef int Int;
typedef unsigned int UInt;
#if defined(JSON_NO_INT64)
typedef int LargestInt;
typedef unsigned int LargestUInt;
#undef JSON_HAS_INT64
#else // if defined(JSON_NO_INT64)
// For Microsoft Visual use specific types as long long is not supported
#if defined(_MSC_VER) // Microsoft Visual Studio
typedef __int64 Int64;
typedef unsigned __int64 UInt64;
#else // if defined(_MSC_VER) // Other platforms, use long long
typedef int64_t Int64;
typedef uint64_t UInt64;
#endif // if defined(_MSC_VER)
typedef Int64 LargestInt;
typedef UInt64 LargestUInt;
#define JSON_HAS_INT64
#endif // if defined(JSON_NO_INT64)
#if JSONCPP_USING_SECURE_MEMORY
#define JSONCPP_STRING std::basic_string<char, std::char_traits<char>, Json::SecureAllocator<char> >
#define JSONCPP_OSTRINGSTREAM std::basic_ostringstream<char, std::char_traits<char>, Json::SecureAllocator<char> >
#define JSONCPP_OSTREAM std::basic_ostream<char, std::char_traits<char>>
#define JSONCPP_ISTRINGSTREAM std::basic_istringstream<char, std::char_traits<char>, Json::SecureAllocator<char> >
#define JSONCPP_ISTREAM std::istream
#else
#define JSONCPP_STRING std::string
#define JSONCPP_OSTRINGSTREAM std::ostringstream
#define JSONCPP_OSTREAM std::ostream
#define JSONCPP_ISTRINGSTREAM std::istringstream
#define JSONCPP_ISTREAM std::istream
#endif // if JSONCPP_USING_SECURE_MEMORY
} // end namespace Json
#endif // JSON_CONFIG_H_INCLUDED
// //////////////////////////////////////////////////////////////////////
// End of content of file: include/json/config.h
// //////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////
// Beginning of content of file: include/json/forwards.h
// //////////////////////////////////////////////////////////////////////
// Copyright 2007-2010 Baptiste Lepilleur
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#ifndef JSON_FORWARDS_H_INCLUDED
#define JSON_FORWARDS_H_INCLUDED
#if !defined(JSON_IS_AMALGAMATION)
#include "config.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
namespace Json {
// writer.h
class FastWriter;
class StyledWriter;
// reader.h
class Reader;
// features.h
class Features;
// value.h
typedef unsigned int ArrayIndex;
class StaticString;
class Path;
class PathArgument;
class Value;
class ValueIteratorBase;
class ValueIterator;
class ValueConstIterator;
} // namespace Json
#endif // JSON_FORWARDS_H_INCLUDED
// //////////////////////////////////////////////////////////////////////
// End of content of file: include/json/forwards.h
// //////////////////////////////////////////////////////////////////////
#endif //ifndef JSON_FORWARD_AMALGATED_H_INCLUDED

2161
json/json.h Normal file

File diff suppressed because it is too large Load diff

5311
jsoncpp.cpp Normal file

File diff suppressed because it is too large Load diff

View file

@ -2,9 +2,13 @@
#include "ui_mainwindow.h"
#include "QueryResultModel.h"
#include "QueryExplainModel.h"
#include "sqlhighlighter.h"
#include <QTextTable>
#include <windows.h>
#include "json/json.h"
#include "explaintreemodelitem.h"
//#include <thread>
namespace pg = Pgsql;
@ -23,7 +27,8 @@ const char * test_query =
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
ui(new Ui::MainWindow),
queryCancel(nullptr)
{
ui->setupUi(this);
@ -44,6 +49,11 @@ MainWindow::MainWindow(QWidget *parent) :
action = ui->mainToolBar->addAction("execute");
connect(action, &QAction::triggered, this, &MainWindow::performQuery);
action = ui->mainToolBar->addAction("explain");
connect(action, &QAction::triggered, this, &MainWindow::performExplain);
action = ui->mainToolBar->addAction("cancel");
connect(action, &QAction::triggered, this, &MainWindow::cancel_query);
}
MainWindow::~MainWindow()
@ -78,6 +88,8 @@ void MainWindow::socket_activate_connect(int )
if (connectingState.poll_state == PGRES_POLLING_OK) {
connection->setNoticeReceiver(
std::bind(&MainWindow::processNotice, this, std::placeholders::_1));
statusBar()->showMessage(tr("Connected"));
connectingState.notifier.reset();
}
@ -102,6 +114,9 @@ void MainWindow::performQuery()
{
ui->ResultView->setModel(nullptr);
resultModel.reset();
ui->messagesEdit->clear();
queryCancel = std::move(connection->getCancel());
QString command = ui->queryEdit->toPlainText();
queryFuture = std::async(std::launch::async, [this,command]()-> Pgsql::Result
@ -115,12 +130,129 @@ void MainWindow::performQuery()
void MainWindow::query_ready()
{
pg::Result dbres(std::move(queryFuture.get()));
if (dbres.resultStatus() == PGRES_TUPLES_OK) {
if (dbres) {
auto st = dbres.resultStatus();
if (st == PGRES_TUPLES_OK) {
resultModel.reset(new QueryResultModel(nullptr , std::move(dbres)));
ui->ResultView->setModel(resultModel.get());
statusBar()->showMessage(tr("Query ready."));
}
else {
if (st == PGRES_EMPTY_QUERY) {
statusBar()->showMessage(tr("Empty query."));
}
else if (st == PGRES_COMMAND_OK) {
statusBar()->showMessage(tr("Command OK."));
}
else if (st == PGRES_COPY_OUT) {
statusBar()->showMessage(tr("COPY OUT."));
}
else if (st == PGRES_COPY_IN) {
statusBar()->showMessage(tr("COPY IN."));
}
else if (st == PGRES_BAD_RESPONSE) {
statusBar()->showMessage(tr("BEAD RESPONSE."));
}
else if (st == PGRES_NONFATAL_ERROR) {
statusBar()->showMessage(tr("NON FATAL ERROR."));
}
else if (st == PGRES_FATAL_ERROR) {
statusBar()->showMessage(tr("FATAL ERROR."));
}
else if (st == PGRES_COPY_BOTH) {
statusBar()->showMessage(tr("COPY BOTH shouldn't happen is for replication."));
}
else if (st == PGRES_SINGLE_TUPLE) {
statusBar()->showMessage(tr("SINGLE TUPLE result."));
}
else {
statusBar()->showMessage(tr("No tuples returned, possibly an error..."));
}
receiveNotice(dbres.diagDetails());
}
}
else {
statusBar()->showMessage(tr("Query cancelled."));
}
}
void MainWindow::performExplain()
{
ui->ResultView->setModel(nullptr);
resultModel.reset();
ui->messagesEdit->clear();
queryCancel = std::move(connection->getCancel());
QString command = "EXPLAIN (ANALYZE, VERBOSE, BUFFERS, FORMAT JSON) ";
command += ui->queryEdit->toPlainText();
explainFuture = std::async(std::launch::async, [this,command]()-> std::unique_ptr<ExplainRoot>
{
std::unique_ptr<ExplainRoot> explain;
auto res = connection->query(command);
if (res.getCols() == 1 && res.getRows() == 1) {
std::string s = res.getVal(0, 0);
Json::Value root; // will contains the root value after parsing.
Json::Reader reader;
bool parsingSuccessful = reader.parse(s, root);
if (parsingSuccessful) {
explain = ExplainRoot::createFromJson(root);
}
}
QMetaObject::invokeMethod(this, "explain_ready", Qt::QueuedConnection); // queues on main thread
return explain;
});
}
void MainWindow::explain_ready()
{
std::unique_ptr<ExplainRoot> explain(explainFuture.get());
if (explain) {
explainModel.reset(new QueryExplainModel(nullptr, std::move(explain)));
ui->explainTreeView->setModel(explainModel.get());
ui->explainTreeView->expandAll();
ui->explainTreeView->setColumnWidth(0, 200);
ui->explainTreeView->setColumnWidth(1, 80);
ui->explainTreeView->setColumnWidth(2, 80);
ui->explainTreeView->setColumnWidth(3, 80);
ui->explainTreeView->setColumnWidth(4, 80);
ui->explainTreeView->setColumnWidth(5, 80);
ui->explainTreeView->setColumnWidth(6, 600);
statusBar()->showMessage(tr("Explain ready."));
}
else {
statusBar()->showMessage(tr("Explain failed."));
}
}
void MainWindow::cancel_query()
{
queryCancel.cancel();
}
void MainWindow::processNotice(const PGresult *result)
{
qRegisterMetaType<Pgsql::ErrorDetails>("Pgsql::ErrorDetails");
pg::ErrorDetails details = pg::ErrorDetails::createErrorDetailsFromPGresult(result);
QMetaObject::invokeMethod(this, "receiveNotice", Qt::AutoConnection, Q_ARG(Pgsql::ErrorDetails, details)); // queues on main thread
}
void MainWindow::receiveNotice(Pgsql::ErrorDetails notice)
{
QTextCursor cursor = ui->messagesEdit->textCursor();
cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);
// QString msg;
// cursor.insertText("TEST\r\n");
QTextTable *table = cursor.insertTable(4, 2);
if (table) {
table->cellAt(1, 0).firstCursorPosition().insertText("State");
table->cellAt(1, 1).firstCursorPosition().insertText(QString::fromStdString(notice.state));
table->cellAt(2, 0).firstCursorPosition().insertText("Primary");
table->cellAt(2, 1).firstCursorPosition().insertText(QString::fromStdString(notice.messagePrimary));
table->cellAt(3, 0).firstCursorPosition().insertText("Detail");
table->cellAt(3, 1).firstCursorPosition().insertText(QString::fromStdString(notice.messageDetail));
}
}

View file

@ -7,7 +7,9 @@
#include <future>
#include "PgsqlConn.h"
class ExplainRoot;
class QueryResultModel;
class QueryExplainModel;
class SqlHighlighter;
namespace Ui {
@ -34,8 +36,11 @@ private:
std::unique_ptr<Pgsql::Connection> connection;
std::unique_ptr<QueryResultModel> resultModel;
std::unique_ptr<QueryExplainModel> explainModel;
Pgsql::Canceller queryCancel;
std::future<Pgsql::Result> queryFuture;
std::future<std::unique_ptr<ExplainRoot>> explainFuture;
struct {
std::unique_ptr<QSocketNotifier> notifier;
@ -47,13 +52,20 @@ private:
// std::unique_ptr<QSocketNotifier> notifierWrite;
// } queryState;
void processNotice(const PGresult *result);
private slots:
void startConnect();
void performQuery();
void performExplain();
void socket_activate_connect(int socket);
void query_ready();
void explain_ready();
void cancel_query();
void receiveNotice(Pgsql::ErrorDetails notice);
};
#endif // MAINWINDOW_H

View file

@ -15,6 +15,18 @@
</property>
<widget class="QWidget" name="centralWidget">
<layout class="QVBoxLayout" name="verticalLayout">
<property name="leftMargin">
<number>8</number>
</property>
<property name="topMargin">
<number>8</number>
</property>
<property name="rightMargin">
<number>8</number>
</property>
<property name="bottomMargin">
<number>8</number>
</property>
<item>
<widget class="QLineEdit" name="connectionStringEdit"/>
</item>
@ -24,6 +36,54 @@
<enum>Qt::Vertical</enum>
</property>
<widget class="QTextEdit" name="queryEdit"/>
<widget class="QTabWidget" name="tabWidget">
<property name="currentIndex">
<number>2</number>
</property>
<widget class="QWidget" name="messageTab">
<attribute name="title">
<string>Messages</string>
</attribute>
<layout class="QGridLayout" name="gridLayout_2">
<property name="leftMargin">
<number>4</number>
</property>
<property name="topMargin">
<number>4</number>
</property>
<property name="rightMargin">
<number>4</number>
</property>
<property name="bottomMargin">
<number>4</number>
</property>
<item row="0" column="0">
<widget class="QTextEdit" name="messagesEdit">
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="dataTab">
<attribute name="title">
<string>Data</string>
</attribute>
<layout class="QGridLayout" name="gridLayout">
<property name="leftMargin">
<number>4</number>
</property>
<property name="topMargin">
<number>4</number>
</property>
<property name="rightMargin">
<number>4</number>
</property>
<property name="bottomMargin">
<number>4</number>
</property>
<item row="0" column="0">
<widget class="QTableView" name="ResultView">
<property name="font">
<font>
@ -38,6 +98,45 @@
<enum>QAbstractItemView::ScrollPerPixel</enum>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="explainTab">
<attribute name="title">
<string>Explain</string>
</attribute>
<layout class="QGridLayout" name="gridLayout_3">
<property name="leftMargin">
<number>2</number>
</property>
<property name="topMargin">
<number>2</number>
</property>
<property name="rightMargin">
<number>2</number>
</property>
<property name="bottomMargin">
<number>2</number>
</property>
<item row="0" column="0">
<widget class="QTreeView" name="explainTreeView">
<property name="editTriggers">
<set>QAbstractItemView::NoEditTriggers</set>
</property>
<property name="showDropIndicator" stdset="0">
<bool>false</bool>
</property>
<property name="indentation">
<number>10</number>
</property>
<attribute name="headerStretchLastSection">
<bool>false</bool>
</attribute>
</widget>
</item>
</layout>
</widget>
</widget>
</widget>
</item>
</layout>

219
queryexplainmodel.cpp Normal file
View file

@ -0,0 +1,219 @@
#include "queryexplainmodel.h"
#include <QColor>
#include <QSize>
const int c_ColumnNode = 0;
const int c_ColumnExclusive = 1;
const int c_ColumnInclusive = 2;
const int c_ColumnEstErr = 3;
const int c_ColumnRowCount = 4;
const int c_ColumnLoops = 5;
const int c_ColumnDetails = 6;
const int c_NumberOfColumns = 7;
QueryExplainModel::QueryExplainModel(QObject *parent,
std::unique_ptr<ExplainRoot> exp)
: QAbstractItemModel(parent)
, explain(std::move(exp))
{}
QVariant QueryExplainModel::data(const QModelIndex &index, int role) const
{
QVariant result;
if (index.isValid()) {
int col = index.column();
ExplainTreeModelItem *item = static_cast<ExplainTreeModelItem*>(index.internalPointer());
if (role == Qt::DisplayRole) {
switch (col) {
case c_ColumnNode:
result = item->nodeType();
break;
case c_ColumnExclusive:
result = item->exclusiveTime();
break;
case c_ColumnInclusive:
result = item->inclusiveTime();
break;
case c_ColumnEstErr:
result = item->estimateError();
break;
case c_ColumnRowCount:
result = item->actualRows();
break;
case c_ColumnLoops:
result = item->actualLoops();
break;
case c_ColumnDetails:
result = item->detailString();
break;
} // end switch column
}
else if (role == Qt::TextAlignmentRole) {
if (col == c_ColumnNode || col == c_ColumnDetails) {
result = Qt::AlignLeft + Qt::AlignVCenter;
}
else {
result = Qt::AlignRight + Qt::AlignVCenter;
}
}
else if (role == Qt::BackgroundColorRole) {
if (col == c_ColumnExclusive || col == c_ColumnInclusive) {
float t = col == 1 ? item->exclusiveTime() : item->inclusiveTime();
float tt = explain->plan->inclusiveTime();
if (tt > 0.000000001) {
float f = t / tt;
if (f > 0.9) {
result = QColor(255, 192, 192);
}
else if (f > 0.63) {
result = QColor(255, 224, 192);
}
else if (f > 0.36f) {
result = QColor(255, 255, 192);
}
else if (f > 0.09f) {
result = QColor(255, 255, 224);
}
else {
result = QColor(Qt::white);
}
}
}
if (col == c_ColumnEstErr) {
float e = fabs(item->estimateError());
if (e > 1000.0f) {
result = QColor(255, 192, 192);
}
else if (e > 100.0f) {
result = QColor(255, 224, 192);
}
else if (e > 10.0f) {
result = QColor(255, 255, 192);
}
else {
result = QColor(Qt::white);
}
}
}
}
return result;
}
//Qt::ItemFlags QueryExplainModel::flags(const QModelIndex &index) const
//{
//}
QVariant QueryExplainModel::headerData(int section, Qt::Orientation orientation,
int role) const
{
QVariant v;
if (orientation == Qt::Horizontal) {
if (role == Qt::DisplayRole ) {
switch (section) {
case c_ColumnNode:
v = "Node";
break;
case c_ColumnExclusive:
v = "Exclusive";
break;
case c_ColumnInclusive:
v = "Inclusive";
break;
case c_ColumnEstErr:
v = "Est. Err";
break;
case c_ColumnRowCount:
v = "Rows";
break;
case c_ColumnLoops:
v = "Loops";
break;
case c_ColumnDetails:
v = "Details";
break;
}
}
// else if (role == Qt::SizeHintRole) {
// switch (section) {
// case 0:
// v = QSize();
// break;
// case 1:
// v = "Exclusive";
// break;
// case 2:
// v = "Inclusive";
// break;
// case 3:
// v = "Est. Err";
// break;
// }
// }
}
return v;
}
QModelIndex QueryExplainModel::index(int row, int column,
const QModelIndex &parent) const
{
QModelIndex result;
if (hasIndex(row, column, parent)) {
if (parent.isValid()) {
ExplainTreeModelItem *parentItem =
static_cast<ExplainTreeModelItem*>(parent.internalPointer());
if (parentItem) {
ExplainTreeModelItemPtr childItem = parentItem->child(row);
if (childItem) {
result = createIndex(row, column, childItem.get());
}
}
}
else {
result = createIndex(row, column, explain->plan.get());
}
}
return result;
}
QModelIndex QueryExplainModel::parent(const QModelIndex &index) const
{
QModelIndex result;
if (index.isValid()) {
ExplainTreeModelItem *childItem = static_cast<ExplainTreeModelItem*>(index.internalPointer());
auto parentItem = childItem->parent();
if (parentItem != nullptr) {
result = createIndex( parentItem->row(), 0, parentItem.get());
}
}
return result;
}
int QueryExplainModel::rowCount(const QModelIndex &parent) const
{
int result = 0;
if (parent.column() <= 0) {
if (parent.isValid()) {
auto item = static_cast<ExplainTreeModelItem*>(parent.internalPointer());
result = item->childCount();
}
else {
result = 1;
}
}
return result;
}
int QueryExplainModel::columnCount(const QModelIndex &parent) const
{
// if (parent.isValid()) {
// return 6;//static_cast<ExplainTreeModelItem*>(parent.internalPointer())->columnCount();
// }
// else {
// return 1;
// }
return c_NumberOfColumns;
}

31
queryexplainmodel.h Normal file
View file

@ -0,0 +1,31 @@
#pragma once
#include <QAbstractItemModel>
#include <string>
#include "explaintreemodelitem.h"
class QueryExplainModel : public QAbstractItemModel
{
Q_OBJECT
public:
explicit QueryExplainModel(QObject *parent, std::unique_ptr<ExplainRoot> exp);
QVariant data(const QModelIndex &index, int role) const override;
// Qt::ItemFlags flags(const QModelIndex &index) const override;
QVariant headerData(int section, Qt::Orientation orientation,
int role = Qt::DisplayRole) const override;
QModelIndex index(int row, int column,
const QModelIndex &parent = QModelIndex()) const override;
QModelIndex parent(const QModelIndex &index) const override;
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const override;
private:
std::unique_ptr<ExplainRoot> explain;
};

View file

@ -13,6 +13,7 @@
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QMainWindow>
@ -20,9 +21,11 @@
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QSplitter>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QTabWidget>
#include <QtWidgets/QTableView>
#include <QtWidgets/QTextEdit>
#include <QtWidgets/QToolBar>
#include <QtWidgets/QTreeView>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
@ -36,7 +39,16 @@ public:
QLineEdit *connectionStringEdit;
QSplitter *splitter;
QTextEdit *queryEdit;
QTabWidget *tabWidget;
QWidget *messageTab;
QGridLayout *gridLayout_2;
QTextEdit *messagesEdit;
QWidget *dataTab;
QGridLayout *gridLayout;
QTableView *ResultView;
QWidget *explainTab;
QGridLayout *gridLayout_3;
QTreeView *explainTreeView;
QMenuBar *menuBar;
QMenu *menuTest;
QToolBar *mainToolBar;
@ -53,6 +65,7 @@ public:
verticalLayout->setSpacing(6);
verticalLayout->setContentsMargins(11, 11, 11, 11);
verticalLayout->setObjectName(QStringLiteral("verticalLayout"));
verticalLayout->setContentsMargins(8, 8, 8, 8);
connectionStringEdit = new QLineEdit(centralWidget);
connectionStringEdit->setObjectName(QStringLiteral("connectionStringEdit"));
@ -64,7 +77,30 @@ public:
queryEdit = new QTextEdit(splitter);
queryEdit->setObjectName(QStringLiteral("queryEdit"));
splitter->addWidget(queryEdit);
ResultView = new QTableView(splitter);
tabWidget = new QTabWidget(splitter);
tabWidget->setObjectName(QStringLiteral("tabWidget"));
messageTab = new QWidget();
messageTab->setObjectName(QStringLiteral("messageTab"));
gridLayout_2 = new QGridLayout(messageTab);
gridLayout_2->setSpacing(6);
gridLayout_2->setContentsMargins(11, 11, 11, 11);
gridLayout_2->setObjectName(QStringLiteral("gridLayout_2"));
gridLayout_2->setContentsMargins(4, 4, 4, 4);
messagesEdit = new QTextEdit(messageTab);
messagesEdit->setObjectName(QStringLiteral("messagesEdit"));
messagesEdit->setReadOnly(true);
gridLayout_2->addWidget(messagesEdit, 0, 0, 1, 1);
tabWidget->addTab(messageTab, QString());
dataTab = new QWidget();
dataTab->setObjectName(QStringLiteral("dataTab"));
gridLayout = new QGridLayout(dataTab);
gridLayout->setSpacing(6);
gridLayout->setContentsMargins(11, 11, 11, 11);
gridLayout->setObjectName(QStringLiteral("gridLayout"));
gridLayout->setContentsMargins(4, 4, 4, 4);
ResultView = new QTableView(dataTab);
ResultView->setObjectName(QStringLiteral("ResultView"));
QFont font;
font.setFamily(QStringLiteral("Source Sans Pro"));
@ -72,7 +108,28 @@ public:
ResultView->setFont(font);
ResultView->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
ResultView->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
splitter->addWidget(ResultView);
gridLayout->addWidget(ResultView, 0, 0, 1, 1);
tabWidget->addTab(dataTab, QString());
explainTab = new QWidget();
explainTab->setObjectName(QStringLiteral("explainTab"));
gridLayout_3 = new QGridLayout(explainTab);
gridLayout_3->setSpacing(6);
gridLayout_3->setContentsMargins(11, 11, 11, 11);
gridLayout_3->setObjectName(QStringLiteral("gridLayout_3"));
gridLayout_3->setContentsMargins(2, 2, 2, 2);
explainTreeView = new QTreeView(explainTab);
explainTreeView->setObjectName(QStringLiteral("explainTreeView"));
explainTreeView->setEditTriggers(QAbstractItemView::NoEditTriggers);
explainTreeView->setProperty("showDropIndicator", QVariant(false));
explainTreeView->setIndentation(10);
explainTreeView->header()->setStretchLastSection(false);
gridLayout_3->addWidget(explainTreeView, 0, 0, 1, 1);
tabWidget->addTab(explainTab, QString());
splitter->addWidget(tabWidget);
verticalLayout->addWidget(splitter);
@ -94,12 +151,18 @@ public:
retranslateUi(MainWindow);
tabWidget->setCurrentIndex(2);
QMetaObject::connectSlotsByName(MainWindow);
} // setupUi
void retranslateUi(QMainWindow *MainWindow)
{
MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", Q_NULLPTR));
tabWidget->setTabText(tabWidget->indexOf(messageTab), QApplication::translate("MainWindow", "Messages", Q_NULLPTR));
tabWidget->setTabText(tabWidget->indexOf(dataTab), QApplication::translate("MainWindow", "Data", Q_NULLPTR));
tabWidget->setTabText(tabWidget->indexOf(explainTab), QApplication::translate("MainWindow", "Explain", Q_NULLPTR));
menuTest->setTitle(QApplication::translate("MainWindow", "test", Q_NULLPTR));
} // retranslateUi