Reorganization of pgLab project
This commit is contained in:
parent
7300865c77
commit
c71fdc4af7
78 changed files with 204 additions and 148 deletions
226
pglab/querytool/QueryExplainModel.cpp
Normal file
226
pglab/querytool/QueryExplainModel.cpp
Normal file
|
|
@ -0,0 +1,226 @@
|
|||
#include "QueryExplainModel.h"
|
||||
#include <QColor>
|
||||
#include <QSize>
|
||||
#include <cmath>
|
||||
|
||||
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_ColumnShared = 7;
|
||||
const int c_NumberOfColumns = 8;
|
||||
|
||||
QueryExplainModel::QueryExplainModel(QObject *parent, ExplainRoot::SPtr 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;
|
||||
case c_ColumnShared:
|
||||
result = item->sharedBlocks.asString();
|
||||
break;
|
||||
} // end switch column
|
||||
}
|
||||
else if (role == Qt::TextAlignmentRole) {
|
||||
if (col == c_ColumnNode || col == c_ColumnDetails) {
|
||||
result = int(Qt::AlignLeft | Qt::AlignVCenter);
|
||||
}
|
||||
else {
|
||||
result = int(Qt::AlignRight | Qt::AlignVCenter);
|
||||
}
|
||||
}
|
||||
else if (role == Qt::BackgroundRole) {
|
||||
if (col == c_ColumnExclusive || col == c_ColumnInclusive) {
|
||||
float t = col == 1 ? item->exclusiveTime() : item->inclusiveTime();
|
||||
float tt = explain->plan->inclusiveTime();
|
||||
if (tt > 0.000000001f) {
|
||||
float f = t / tt;
|
||||
if (f > 0.9f) {
|
||||
result = QColor(255, 192, 192);
|
||||
}
|
||||
else if (f > 0.63f) {
|
||||
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 = std::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;
|
||||
case c_ColumnShared:
|
||||
v = "Shared";
|
||||
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 &) const
|
||||
{
|
||||
// if (parent.isValid()) {
|
||||
// return 6;//static_cast<ExplainTreeModelItem*>(parent.internalPointer())->columnCount();
|
||||
// }
|
||||
// else {
|
||||
// return 1;
|
||||
// }
|
||||
return c_NumberOfColumns;
|
||||
}
|
||||
33
pglab/querytool/QueryExplainModel.h
Normal file
33
pglab/querytool/QueryExplainModel.h
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
#pragma once
|
||||
|
||||
#include <QAbstractItemModel>
|
||||
#include <string>
|
||||
#include "ExplainTreeModelItem.h"
|
||||
|
||||
/** \brief Model class for displaying the explain of a query in a tree like format.
|
||||
*/
|
||||
class QueryExplainModel : public QAbstractItemModel
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit QueryExplainModel(QObject *parent, ExplainRoot::SPtr 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:
|
||||
ExplainRoot::SPtr explain;
|
||||
};
|
||||
57
pglab/querytool/QueryParamListController.cpp
Normal file
57
pglab/querytool/QueryParamListController.cpp
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
#include "QueryParamListController.h"
|
||||
#include "OpenDatabase.h"
|
||||
#include "catalog/PgDatabaseCatalog.h"
|
||||
#include "catalog/PgTypeContainer.h"
|
||||
#include <QTableView>
|
||||
|
||||
|
||||
QueryParamListController::QueryParamListController(QTableView *tv,
|
||||
std::shared_ptr<OpenDatabase> opendb, QWidget *parent)
|
||||
: QObject(parent)
|
||||
, paramTableView(tv)
|
||||
, m_openDatabase(opendb)
|
||||
{
|
||||
if (opendb) {
|
||||
m_typeDelegate.setTypeSelectionModel(opendb->typeSelectionModel());
|
||||
}
|
||||
|
||||
paramTableView->setModel(&m_paramList);
|
||||
paramTableView->setItemDelegateForColumn(1, &m_typeDelegate);
|
||||
}
|
||||
|
||||
Pgsql::Params QueryParamListController::params() const
|
||||
{
|
||||
Pgsql::Params params;
|
||||
auto types = m_openDatabase->catalog()->types();
|
||||
for (auto e : m_paramList.GetParams()) {
|
||||
// some types have two names that are in seperate fields
|
||||
// this function only checks one field currently :(
|
||||
// for example integer vs int4, bigint vs int8
|
||||
auto type = types->getByName(e.type);
|
||||
if (type) {
|
||||
Oid oid = type->oid();
|
||||
params.add(e.value, oid);
|
||||
}
|
||||
else
|
||||
throw std::runtime_error("missing type in parameter list");
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
bool QueryParamListController::empty() const
|
||||
{
|
||||
|
||||
return m_paramList.rowCount() == 0;
|
||||
}
|
||||
|
||||
void QueryParamListController::on_addParam()
|
||||
{
|
||||
m_paramList.insertRows(m_paramList.rowCount(), 1);
|
||||
}
|
||||
|
||||
void QueryParamListController::on_removeParam()
|
||||
{
|
||||
auto rc = m_paramList.rowCount();
|
||||
if (rc > 0)
|
||||
m_paramList.removeRows(rc-1, 1);
|
||||
}
|
||||
30
pglab/querytool/QueryParamListController.h
Normal file
30
pglab/querytool/QueryParamListController.h
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
#ifndef QUERYPARAMLISTCONTROLLER_H
|
||||
#define QUERYPARAMLISTCONTROLLER_H
|
||||
|
||||
#include <QObject>
|
||||
#include "ParamListModel.h"
|
||||
#include "ParamTypeDelegate.h"
|
||||
#include "Pgsql_Params.h"
|
||||
#include <memory>
|
||||
|
||||
class QTableView;
|
||||
class OpenDatabase;
|
||||
|
||||
class QueryParamListController : public QObject {
|
||||
Q_OBJECT
|
||||
public:
|
||||
QueryParamListController(QTableView *tv, std::shared_ptr<OpenDatabase> opendb, QWidget *parent);
|
||||
|
||||
Pgsql::Params params() const;
|
||||
bool empty() const;
|
||||
public slots:
|
||||
void on_addParam();
|
||||
void on_removeParam();
|
||||
private:
|
||||
QTableView *paramTableView;
|
||||
std::shared_ptr<OpenDatabase> m_openDatabase;
|
||||
ParamListModel m_paramList;
|
||||
ParamTypeDelegate m_typeDelegate;
|
||||
};
|
||||
|
||||
#endif // QUERYPARAMLISTCONTROLLER_H
|
||||
85
pglab/querytool/QueryResultModel.cpp
Normal file
85
pglab/querytool/QueryResultModel.cpp
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
#include "QueryResultModel.h"
|
||||
#include "ResultTableModelUtil.h"
|
||||
#include "Pgsql_declare.h"
|
||||
#include "Pgsql_oids.h"
|
||||
#include "catalog/PgDatabaseCatalog.h"
|
||||
#include "CustomDataRole.h"
|
||||
#include <QBrush>
|
||||
#include <QColor>
|
||||
|
||||
using namespace Pgsql;
|
||||
|
||||
QueryResultModel::QueryResultModel(QObject *parent, std::shared_ptr<Pgsql::Result> r
|
||||
, std::shared_ptr<PgDatabaseCatalog> cat)
|
||||
: QAbstractTableModel(parent)
|
||||
, result(std::move(r))
|
||||
, catalog(cat)
|
||||
{}
|
||||
|
||||
|
||||
int QueryResultModel::rowCount(const QModelIndex &) const
|
||||
{
|
||||
int r = result->rows();
|
||||
return r;
|
||||
}
|
||||
|
||||
int QueryResultModel::columnCount(const QModelIndex &) const
|
||||
{
|
||||
int r = result->cols();
|
||||
return r;
|
||||
}
|
||||
|
||||
QVariant QueryResultModel::data(const QModelIndex &index, int role) const
|
||||
{
|
||||
// static const QString null_str("null");
|
||||
QVariant v;
|
||||
|
||||
const int col = index.column();
|
||||
const int rij = index.row();
|
||||
const Oid oid = result->type(col);
|
||||
if (role == Qt::DisplayRole || role == Qt::EditRole) {
|
||||
if (result->null(col, rij)) {
|
||||
//v = nullptr;
|
||||
}
|
||||
else {
|
||||
Value value = result->get(col, rij);
|
||||
if (oid == bool_oid) {
|
||||
bool b = value;
|
||||
v = b;
|
||||
}
|
||||
else {
|
||||
QString s = value;
|
||||
v = s;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (role == CustomDataTypeRole) {
|
||||
v = oid;
|
||||
}
|
||||
|
||||
|
||||
return v;
|
||||
}
|
||||
|
||||
QVariant QueryResultModel::headerData(int section, Qt::Orientation orientation, int role) const
|
||||
{
|
||||
QVariant r;
|
||||
if (role == Qt::DisplayRole) {
|
||||
if (orientation == Qt::Horizontal) {
|
||||
QString s(result->getColName(section));
|
||||
s += "\n";
|
||||
s += getTypeDisplayString(*catalog, result->type(section));
|
||||
r = s;
|
||||
}
|
||||
else {
|
||||
r = QString::number(section + 1);
|
||||
}
|
||||
}
|
||||
Qt::ItemFlags f;
|
||||
return r;
|
||||
}
|
||||
|
||||
Qt::ItemFlags QueryResultModel::flags(const QModelIndex &) const
|
||||
{
|
||||
return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable;
|
||||
}
|
||||
31
pglab/querytool/QueryResultModel.h
Normal file
31
pglab/querytool/QueryResultModel.h
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
#ifndef QUERYRESULTMODEL_H
|
||||
#define QUERYRESULTMODEL_H
|
||||
|
||||
#include <QAbstractTableModel>
|
||||
#include "catalog/models/BaseTableModel.h"
|
||||
#include "Pgsql_Connection.h"
|
||||
|
||||
class PgDatabaseCatalog;
|
||||
|
||||
class QueryResultModel : public QAbstractTableModel
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
QueryResultModel(QObject *parent, std::shared_ptr<Pgsql::Result> r, std::shared_ptr<PgDatabaseCatalog> cat);
|
||||
|
||||
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
|
||||
int columnCount(const QModelIndex &parent = QModelIndex()) const override;
|
||||
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
|
||||
virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
|
||||
virtual Qt::ItemFlags flags(const QModelIndex &index) const override;
|
||||
|
||||
std::shared_ptr<const Pgsql::Result> GetPgsqlResult() const { return result; }
|
||||
protected:
|
||||
// virtual Oid getType(int column) const override;
|
||||
// virtual QVariant getData(const QModelIndex &index) const override;
|
||||
private:
|
||||
std::shared_ptr<Pgsql::Result> result;
|
||||
std::shared_ptr<PgDatabaseCatalog> catalog;
|
||||
};
|
||||
|
||||
#endif // QUERYRESULTMODEL_H
|
||||
225
pglab/querytool/QueryTab.ui
Normal file
225
pglab/querytool/QueryTab.ui
Normal file
|
|
@ -0,0 +1,225 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<ui version="4.0">
|
||||
<class>QueryTab</class>
|
||||
<widget class="QWidget" name="QueryTab">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>766</width>
|
||||
<height>667</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="windowTitle">
|
||||
<string>Form</string>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="verticalLayout_3">
|
||||
<item>
|
||||
<widget class="QSplitter" name="splitter_2">
|
||||
<property name="orientation">
|
||||
<enum>Qt::Vertical</enum>
|
||||
</property>
|
||||
<widget class="QSplitter" name="splitter">
|
||||
<property name="orientation">
|
||||
<enum>Qt::Horizontal</enum>
|
||||
</property>
|
||||
<widget class="CodeEditor" name="queryEdit"/>
|
||||
<widget class="QFrame" name="frameParams">
|
||||
<property name="frameShape">
|
||||
<enum>QFrame::StyledPanel</enum>
|
||||
</property>
|
||||
<property name="frameShadow">
|
||||
<enum>QFrame::Raised</enum>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="verticalLayout">
|
||||
<property name="leftMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="topMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="rightMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="bottomMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QFrame" name="frame_2">
|
||||
<property name="frameShape">
|
||||
<enum>QFrame::StyledPanel</enum>
|
||||
</property>
|
||||
<property name="frameShadow">
|
||||
<enum>QFrame::Raised</enum>
|
||||
</property>
|
||||
<layout class="QHBoxLayout" name="horizontalLayout">
|
||||
<property name="spacing">
|
||||
<number>6</number>
|
||||
</property>
|
||||
<property name="leftMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="topMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="rightMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="bottomMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QPushButton" name="addButton">
|
||||
<property name="text">
|
||||
<string>Add</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QPushButton" name="removeButton">
|
||||
<property name="text">
|
||||
<string>Remove</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<spacer name="horizontalSpacer">
|
||||
<property name="orientation">
|
||||
<enum>Qt::Horizontal</enum>
|
||||
</property>
|
||||
<property name="sizeHint" stdset="0">
|
||||
<size>
|
||||
<width>40</width>
|
||||
<height>20</height>
|
||||
</size>
|
||||
</property>
|
||||
</spacer>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QTableView" name="paramTableView">
|
||||
<property name="alternatingRowColors">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
</widget>
|
||||
<widget class="QTabWidget" name="tabWidget">
|
||||
<property name="currentIndex">
|
||||
<number>1</number>
|
||||
</property>
|
||||
<widget class="QWidget" name="messageTab">
|
||||
<attribute name="title">
|
||||
<string>Messages</string>
|
||||
</attribute>
|
||||
<layout class="QGridLayout" name="gridLayout_2">
|
||||
<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="QTextEdit" name="messagesEdit">
|
||||
<property name="readOnly">
|
||||
<bool>true</bool>
|
||||
</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="QLabel" name="lblTimes">
|
||||
<property name="text">
|
||||
<string/>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item row="1" 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="alternatingRowColors">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="indentation">
|
||||
<number>10</number>
|
||||
</property>
|
||||
<property name="uniformRowHeights">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
<attribute name="headerStretchLastSection">
|
||||
<bool>false</bool>
|
||||
</attribute>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
<widget class="QWidget" name="logTab">
|
||||
<attribute name="title">
|
||||
<string>Log</string>
|
||||
</attribute>
|
||||
<layout class="QVBoxLayout" name="verticalLayout_2">
|
||||
<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>
|
||||
<widget class="QPlainTextEdit" name="edtLog"/>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
</widget>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
<customwidgets>
|
||||
<customwidget>
|
||||
<class>CodeEditor</class>
|
||||
<extends>QPlainTextEdit</extends>
|
||||
<header>CodeEditor.h</header>
|
||||
</customwidget>
|
||||
</customwidgets>
|
||||
<resources/>
|
||||
<connections/>
|
||||
</ui>
|
||||
643
pglab/querytool/QueryTool.cpp
Normal file
643
pglab/querytool/QueryTool.cpp
Normal file
|
|
@ -0,0 +1,643 @@
|
|||
#include "QueryTool.h"
|
||||
#include "ui_QueryTab.h"
|
||||
#include "SqlSyntaxHighlighter.h"
|
||||
#include <QStandardPaths>
|
||||
#include <QPushButton>
|
||||
#include <QAction>
|
||||
#include <QFileDialog>
|
||||
#include <QMessageBox>
|
||||
#include <QStatusBar>
|
||||
#include <QStringConverter>
|
||||
#include <QTabWidget>
|
||||
#include <QTextDocumentFragment>
|
||||
#include <QTextStream>
|
||||
#include <QClipboard>
|
||||
#include "ExplainTreeModelItem.h"
|
||||
#include "json/json.h"
|
||||
#include "OpenDatabase.h"
|
||||
#include "catalog/PgDatabaseCatalog.h"
|
||||
#include "QueryParamListController.h"
|
||||
#include "util.h"
|
||||
#include "UserConfiguration.h"
|
||||
#include "IDatabaseWindow.h"
|
||||
|
||||
|
||||
QueryTool::QueryTool(IDatabaseWindow *context, QWidget *parent)
|
||||
: ManagedPage(parent)
|
||||
, m_context(context)
|
||||
, ui(new Ui::QueryTab)
|
||||
, m_dbConnection()
|
||||
{
|
||||
ui->setupUi(this);
|
||||
|
||||
auto db = context->openDatabase();
|
||||
m_config = db->config();
|
||||
m_catalog = db->catalog();
|
||||
|
||||
connect(&m_dbConnection, &ASyncDBConnection::onStateChanged, this, &QueryTool::connectionStateChanged);
|
||||
connect(&m_dbConnection, &ASyncDBConnection::onNotice, this, &QueryTool::receiveNotice);
|
||||
|
||||
ui->queryEdit->setFont(UserConfiguration::instance()->codeFont());
|
||||
|
||||
highlighter = new SqlSyntaxHighlighter(ui->queryEdit->document());
|
||||
auto types = m_catalog->types();
|
||||
if (types) {
|
||||
highlighter->setTypes(*types);
|
||||
}
|
||||
|
||||
connect(ui->queryEdit, &QPlainTextEdit::textChanged, this, &QueryTool::queryTextChanged);
|
||||
ui->queryEdit->setAcceptDrops(false);
|
||||
|
||||
m_queryParamListController = new QueryParamListController(ui->paramTableView, m_context->openDatabase(), this);
|
||||
connect(ui->addButton, &QPushButton::clicked, m_queryParamListController,
|
||||
&QueryParamListController::on_addParam);
|
||||
connect(ui->removeButton, &QPushButton::clicked, m_queryParamListController,
|
||||
&QueryParamListController::on_removeParam);
|
||||
|
||||
startConnect();
|
||||
}
|
||||
|
||||
QueryTool::~QueryTool()
|
||||
{
|
||||
delete ui;
|
||||
}
|
||||
|
||||
bool QueryTool::CanClose(bool prompt_user)
|
||||
{
|
||||
bool can_close;
|
||||
if (m_queryTextChanged) {
|
||||
if (prompt_user)
|
||||
can_close = continueWithoutSavingWarning();
|
||||
else
|
||||
can_close = false;
|
||||
}
|
||||
else {
|
||||
can_close = true;
|
||||
}
|
||||
return can_close;
|
||||
}
|
||||
|
||||
void QueryTool::newdoc()
|
||||
{
|
||||
ui->queryEdit->clear();
|
||||
setFileName(tr("new"));
|
||||
setQueryTextChanged(false);
|
||||
m_new = true;
|
||||
}
|
||||
|
||||
bool QueryTool::load(const QString &filename)
|
||||
{
|
||||
bool result = false;
|
||||
QFile file(filename);
|
||||
if (file.open(QIODevice::ReadOnly)) {
|
||||
QByteArray ba = file.readAll();
|
||||
auto toUtf16 = QStringDecoder(QStringDecoder::Utf8);
|
||||
QString text = toUtf16(ba);
|
||||
if (toUtf16.hasError()) {
|
||||
file.reset();
|
||||
QTextStream stream(&file);
|
||||
text = stream.readAll();
|
||||
}
|
||||
|
||||
ui->queryEdit->setPlainText(text);
|
||||
setQueryTextChanged(false);
|
||||
setFileName(filename);
|
||||
m_new = false;
|
||||
result = true;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
bool QueryTool::save()
|
||||
{
|
||||
bool result;
|
||||
if (m_fileName.isEmpty() || m_new) {
|
||||
result = saveAs();
|
||||
}
|
||||
else {
|
||||
result = saveSqlTo(m_fileName);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
bool QueryTool::saveAs()
|
||||
{
|
||||
bool result = false;
|
||||
QString filename = promptUserForSaveSqlFilename();
|
||||
if (!filename.isEmpty()) {
|
||||
result = saveSqlTo(filename);
|
||||
if (result) {
|
||||
setFileName(filename);
|
||||
m_new = false;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
void QueryTool::saveCopyAs()
|
||||
{
|
||||
QString filename = promptUserForSaveSqlFilename();
|
||||
if (!filename.isEmpty()) {
|
||||
saveSqlTo(filename);
|
||||
}
|
||||
}
|
||||
|
||||
void QueryTool::execute()
|
||||
{
|
||||
if (m_dbConnection.state() == ASyncDBConnection::State::Connected) {
|
||||
addLog("Query clicked");
|
||||
|
||||
clearResult();
|
||||
ui->messagesEdit->clear();
|
||||
|
||||
std::string cmd = getCommandUtf8();
|
||||
m_stopwatch.start();
|
||||
|
||||
auto cb = [this](Expected<std::shared_ptr<Pgsql::Result>> res, qint64 elapsedms)
|
||||
{
|
||||
if (res.valid()) {
|
||||
auto && dbresult = res.get();
|
||||
QMetaObject::invokeMethod(this, "query_ready",
|
||||
Q_ARG(std::shared_ptr<Pgsql::Result>, dbresult),
|
||||
Q_ARG(qint64, elapsedms));
|
||||
}
|
||||
else {
|
||||
/// \todo handle error
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
if (m_queryParamListController->empty())
|
||||
m_dbConnection.send(cmd, cb);
|
||||
else
|
||||
m_dbConnection.send(cmd, m_queryParamListController->params(), cb);
|
||||
}
|
||||
catch (const std::exception &ex) {
|
||||
QMessageBox msgBox;
|
||||
msgBox.setIcon(QMessageBox::Critical);
|
||||
msgBox.setText(QString("Error executing query: %1").arg(QString::fromUtf8(ex.what())));
|
||||
msgBox.setStandardButtons(QMessageBox::Close);
|
||||
msgBox.setDefaultButton(QMessageBox::Close);
|
||||
msgBox.exec();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void QueryTool::explain(bool analyze)
|
||||
{
|
||||
ui->explainTreeView->setModel(nullptr);
|
||||
explainModel.reset();
|
||||
ui->messagesEdit->clear();
|
||||
|
||||
addLog("Explain clicked");
|
||||
|
||||
std::string analyze_str;
|
||||
if (analyze) {
|
||||
analyze_str = "ANALYZE, BUFFERS, ";
|
||||
}
|
||||
m_stopwatch.start();
|
||||
std::string cmd = "EXPLAIN (" + analyze_str + "VERBOSE, FORMAT JSON) " + getCommandUtf8();
|
||||
|
||||
auto cb = [this](Expected<std::shared_ptr<Pgsql::Result>> exp_res, qint64 )
|
||||
{
|
||||
if (exp_res.valid()) {
|
||||
// Process explain data seperately
|
||||
auto res = exp_res.get();
|
||||
if (res) {
|
||||
std::thread([this,res]()
|
||||
{
|
||||
std::shared_ptr<ExplainRoot> explain;
|
||||
if (res->cols() == 1 && res->rows() == 1) {
|
||||
std::string s = res->val(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",
|
||||
Q_ARG(ExplainRoot::SPtr, explain));
|
||||
}).detach();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (m_queryParamListController->empty())
|
||||
m_dbConnection.send(cmd, cb);
|
||||
else
|
||||
m_dbConnection.send(cmd, m_queryParamListController->params(), cb);
|
||||
}
|
||||
|
||||
void QueryTool::cancel()
|
||||
{
|
||||
m_dbConnection.cancel();
|
||||
}
|
||||
|
||||
QString QueryTool::title() const
|
||||
{
|
||||
QFileInfo fileInfo(m_fileName);
|
||||
QString fn(fileInfo.fileName());
|
||||
return fn;
|
||||
}
|
||||
|
||||
void QueryTool::setFileName(const QString &filename)
|
||||
{
|
||||
m_fileName = filename;
|
||||
updateTitle();
|
||||
}
|
||||
|
||||
void QueryTool::updateTitle()
|
||||
{
|
||||
QFileInfo fileInfo(m_fileName);
|
||||
QString title = fileInfo.fileName();
|
||||
|
||||
if (m_queryTextChanged) {
|
||||
title = "*" + title;
|
||||
}
|
||||
|
||||
m_context->setTitleForWidget(this, title, m_fileName);
|
||||
}
|
||||
|
||||
bool QueryTool::continueWithoutSavingWarning()
|
||||
{
|
||||
QMessageBox msgBox;
|
||||
msgBox.setIcon(QMessageBox::Warning);
|
||||
msgBox.setText(QString("Save changes in document \"%1\" before closing?").arg(m_fileName));
|
||||
msgBox.setInformativeText("The changes will be lost when you choose Discard.");
|
||||
msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
|
||||
msgBox.setDefaultButton(QMessageBox::Cancel);
|
||||
int ret = msgBox.exec();
|
||||
if (ret == QMessageBox::Save) {
|
||||
if (!save()) {
|
||||
// save failed or was a saveAs and was cancelled, don't close!
|
||||
ret = QMessageBox::Cancel;
|
||||
}
|
||||
}
|
||||
|
||||
return ret != QMessageBox::Cancel;
|
||||
}
|
||||
|
||||
bool QueryTool::saveSqlTo(const QString &filename)
|
||||
{
|
||||
bool result = false;
|
||||
QFileInfo fileinfo(filename);
|
||||
|
||||
|
||||
QFile file(filename);
|
||||
if (file.open(QIODevice::WriteOnly)) {
|
||||
QTextStream stream(&file);
|
||||
//stream.setCodec("utf-8");
|
||||
stream.setEncoding(QStringConverter::Utf8);
|
||||
QString text = ui->queryEdit->toPlainText();
|
||||
stream << text;
|
||||
|
||||
stream.flush();
|
||||
if (stream.status() == QTextStream::Ok) {
|
||||
setQueryTextChanged(false);
|
||||
result = true;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
QString QueryTool::promptUserForSaveSqlFilename()
|
||||
{
|
||||
QString home_dir = QStandardPaths::locate(QStandardPaths::HomeLocation, "", QStandardPaths::LocateDirectory);
|
||||
return QFileDialog::getSaveFileName(this, tr("Save query"), home_dir, tr("SQL file (*.sql)"));
|
||||
}
|
||||
|
||||
void QueryTool::queryTextChanged()
|
||||
{
|
||||
setQueryTextChanged(true);
|
||||
}
|
||||
|
||||
void QueryTool::connectionStateChanged(ASyncDBConnection::State state)
|
||||
{
|
||||
QString iconname;
|
||||
switch (state) {
|
||||
case ASyncDBConnection::State::NotConnected:
|
||||
startConnect();
|
||||
iconname = "red.png";
|
||||
break;
|
||||
case ASyncDBConnection::State::Connecting:
|
||||
iconname = "red.png";
|
||||
break;
|
||||
case ASyncDBConnection::State::Connected:
|
||||
iconname = "green.png";
|
||||
break;
|
||||
case ASyncDBConnection::State::QuerySend:
|
||||
case ASyncDBConnection::State::CancelSend:
|
||||
iconname = "yellow.png";
|
||||
break;
|
||||
case ASyncDBConnection::State::Terminating:
|
||||
break;
|
||||
}
|
||||
m_context->setIconForWidget(this, QIcon(":/icons/16x16/document_" + iconname));
|
||||
}
|
||||
|
||||
void QueryTool::addLog(QString s)
|
||||
{
|
||||
QTextCursor text_cursor = QTextCursor(ui->edtLog->document());
|
||||
text_cursor.movePosition(QTextCursor::End);
|
||||
text_cursor.insertText(s + "\r\n");
|
||||
}
|
||||
|
||||
void QueryTool::receiveNotice(Pgsql::ErrorDetails notice)
|
||||
{
|
||||
ui->messagesEdit->append(QString::fromStdString(notice.errorMessage));
|
||||
|
||||
ui->messagesEdit->append(QString::fromStdString(notice.severity));
|
||||
ui->messagesEdit->append(QString("At position: %1").arg(notice.statementPosition));
|
||||
ui->messagesEdit->append(QString::fromStdString("State: " + notice.state));
|
||||
ui->messagesEdit->append(QString::fromStdString("Primary: " + notice.messagePrimary));
|
||||
ui->messagesEdit->append(QString::fromStdString("Detail: " + notice.messageDetail));
|
||||
ui->messagesEdit->append(QString::fromStdString("Hint: " + notice.messageHint));
|
||||
ui->messagesEdit->append(QString::fromStdString("Context: " + notice.context));
|
||||
// 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!
|
||||
// std::string context;
|
||||
|
||||
// int internalPosition;
|
||||
// std::string internalQuery;
|
||||
// std::string schemaName;
|
||||
// std::string tableName;
|
||||
// std::string columnName;
|
||||
// std::string datatypeName;
|
||||
// std::string constraintName;
|
||||
// std::string sourceFile;
|
||||
// std::string sourceLine;
|
||||
// std::string sourceFunction;
|
||||
|
||||
// QTextCursor cursor = ui->messagesEdit->textCursor();
|
||||
// cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);
|
||||
|
||||
// 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));
|
||||
// }
|
||||
|
||||
// syntax error at or near "limit
|
||||
// statementPosition
|
||||
}
|
||||
|
||||
void QueryTool::startConnect()
|
||||
{
|
||||
m_dbConnection.setupConnection(m_config);
|
||||
}
|
||||
|
||||
void QueryTool::explain_ready(ExplainRoot::SPtr explain)
|
||||
{
|
||||
m_stopwatch.stop();
|
||||
if (explain) {
|
||||
addLog("Explain ready");
|
||||
QString times_str;
|
||||
if (explain->totalRuntime > 0.f)
|
||||
times_str = QString("Total time: %1").arg(
|
||||
msfloatToHumanReadableString(explain->totalRuntime));
|
||||
else
|
||||
times_str = QString("Execution time: %1, Planning time: %2").arg(
|
||||
msfloatToHumanReadableString(explain->executionTime)
|
||||
, msfloatToHumanReadableString(explain->planningTime));
|
||||
ui->lblTimes->setText(times_str);
|
||||
explainModel.reset(new QueryExplainModel(nullptr, 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);
|
||||
ui->tabWidget->setCurrentWidget(ui->explainTab);
|
||||
|
||||
m_context->showStatusBarMessage(tr("Explain ready."));
|
||||
|
||||
}
|
||||
else {
|
||||
addLog(tr("Explain no result"));
|
||||
ui->tabWidget->setCurrentWidget(ui->messageTab);
|
||||
m_context->showStatusBarMessage(tr("Explain no result"));
|
||||
}
|
||||
}
|
||||
|
||||
QString QueryTool::getCommand() const
|
||||
{
|
||||
QString command;
|
||||
QTextCursor cursor = ui->queryEdit->textCursor();
|
||||
if (cursor.hasSelection()) {
|
||||
command = cursor.selection().toPlainText();
|
||||
}
|
||||
else {
|
||||
command = ui->queryEdit->toPlainText();
|
||||
}
|
||||
return command;
|
||||
}
|
||||
|
||||
std::string QueryTool::getCommandUtf8() const
|
||||
{
|
||||
return getCommand().toUtf8().data();
|
||||
}
|
||||
|
||||
void QueryTool::query_ready(std::shared_ptr<Pgsql::Result> dbres, qint64 elapsedms)
|
||||
{
|
||||
if (dbres) {
|
||||
addLog("query_ready with result");
|
||||
auto st = dbres->resultStatus();
|
||||
if (st == PGRES_TUPLES_OK) {
|
||||
//int n_rows = dbres->getRows();
|
||||
//QString rowcount_str = QString("rows: %1").arg(dbres->getRows());
|
||||
|
||||
auto result_model = std::make_shared<QueryResultModel>(nullptr , dbres,
|
||||
m_catalog);
|
||||
TuplesResultWidget *trw = new TuplesResultWidget;
|
||||
trw->setResult(result_model, elapsedms);
|
||||
resultList.push_back(trw);
|
||||
ui->tabWidget->addTab(trw, "Data");
|
||||
if (resultList.size() == 1)
|
||||
ui->tabWidget->setCurrentWidget(trw);
|
||||
|
||||
}
|
||||
else {
|
||||
if (st == PGRES_COMMAND_OK) {
|
||||
int tuples_affected = dbres->tuplesAffected();
|
||||
QString msg;
|
||||
if (tuples_affected >= 0)
|
||||
msg = tr("Query returned succesfully: %1 rows affected, execution time %2")
|
||||
.arg(QString::number(tuples_affected))
|
||||
.arg(msfloatToHumanReadableString(elapsedms));
|
||||
else
|
||||
msg = tr("Query returned succesfully, execution time %1")
|
||||
.arg(msfloatToHumanReadableString(elapsedms));
|
||||
|
||||
ui->messagesEdit->append(msg);
|
||||
|
||||
ui->tabWidget->setCurrentWidget(ui->messageTab);
|
||||
}
|
||||
else {
|
||||
// if (st == PGRES_EMPTY_QUERY) {
|
||||
// statusBar()->showMessage(tr("Empty query."));
|
||||
// }
|
||||
// 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("BAD 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..."));
|
||||
// }
|
||||
ui->tabWidget->setCurrentWidget(ui->messageTab);
|
||||
auto details = dbres->diagDetails();
|
||||
markError(details);
|
||||
receiveNotice(details);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
m_stopwatch.stop();
|
||||
addLog("query_ready with NO result");
|
||||
}
|
||||
}
|
||||
|
||||
void QueryTool::markError(const Pgsql::ErrorDetails &details)
|
||||
{
|
||||
if (details.statementPosition > 0) {
|
||||
QTextCursor cursor = ui->queryEdit->textCursor();
|
||||
|
||||
// Following finds out the start of the current selection
|
||||
// theoreticallly the selection might have changed however
|
||||
// theoretically all the text might have changed also so we ignore
|
||||
// both issues for know and we solve both when we decide it is to much of
|
||||
// a problem but in practice syntax errors come back very quickly...
|
||||
int position_offset = 0;
|
||||
if (cursor.hasSelection()) {
|
||||
position_offset = cursor.selectionStart();
|
||||
}
|
||||
|
||||
cursor.setPosition(details.statementPosition - 1 + position_offset);
|
||||
ui->queryEdit->setTextCursor(cursor);
|
||||
|
||||
int length = 0;
|
||||
if (details.state == "42703") {
|
||||
std::size_t pos = details.messagePrimary.find('"');
|
||||
if (pos != std::string::npos) {
|
||||
std::size_t pos2 = details.messagePrimary.find('"', pos+1);
|
||||
if (pos2 != std::string::npos) {
|
||||
length = static_cast<int>(pos2 - pos);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (details.state == "42P01") {
|
||||
std::size_t pos = details.messagePrimary.find('"');
|
||||
if (pos != std::string::npos) {
|
||||
std::size_t pos2 = details.messagePrimary.find('"', pos+1);
|
||||
if (pos2 != std::string::npos) {
|
||||
length = static_cast<int>(pos2 - pos);
|
||||
}
|
||||
}
|
||||
}
|
||||
ui->queryEdit->addErrorMarker(details.statementPosition - 1 + position_offset, length);
|
||||
}
|
||||
}
|
||||
|
||||
void QueryTool::clearResult()
|
||||
{
|
||||
for (auto e : resultList)
|
||||
delete e;
|
||||
resultList.clear();
|
||||
}
|
||||
|
||||
void QueryTool::copyQueryAsCString()
|
||||
{
|
||||
QString command = getCommand();
|
||||
QString cs = ConvertToMultiLineCString(command);
|
||||
QApplication::clipboard()->setText(cs);
|
||||
}
|
||||
|
||||
#include <codebuilder/CodeBuilder.h>
|
||||
#include <codebuilder/DefaultConfigs.h>
|
||||
|
||||
void QueryTool::copyQueryAsRawCppString()
|
||||
{
|
||||
QString command = getCommand();
|
||||
QString cs = ConvertToMultiLineRawCppString(command);
|
||||
QApplication::clipboard()->setText(cs);
|
||||
}
|
||||
|
||||
void QueryTool::pasteLangString()
|
||||
{
|
||||
QString s = QApplication::clipboard()->text();
|
||||
s = ConvertLangToSqlString(s);
|
||||
ui->queryEdit->insertPlainText(s);
|
||||
}
|
||||
|
||||
void QueryTool::generateCode()
|
||||
{
|
||||
QString command = getCommand();
|
||||
if (resultList.empty()) {
|
||||
QMessageBox::question(this, "pglab", tr("Please execute the query first"), QMessageBox::Ok);
|
||||
}
|
||||
if (resultList.size() == 1) {
|
||||
std::shared_ptr<const Pgsql::Result> dbres = resultList[0]->GetPgsqlResult();
|
||||
m_context->newCodeGenPage(command, dbres);
|
||||
}
|
||||
}
|
||||
|
||||
void QueryTool::exportDataToFilename(const QString &file_name)
|
||||
{
|
||||
auto widget = ui->tabWidget->currentWidget();
|
||||
auto fi = std::find(resultList.begin(), resultList.end(), widget);
|
||||
if (fi != resultList.end()) {
|
||||
TuplesResultWidget* rw = *fi;
|
||||
rw->exportData(file_name);
|
||||
}
|
||||
}
|
||||
|
||||
void QueryTool::focusEditor()
|
||||
{
|
||||
ui->queryEdit->setFocus();
|
||||
}
|
||||
|
||||
void QueryTool::exportData()
|
||||
{
|
||||
QString home_dir = QStandardPaths::locate(QStandardPaths::HomeLocation, "", QStandardPaths::LocateDirectory);
|
||||
QString file_name = QFileDialog::getSaveFileName(this,
|
||||
tr("Export data"), home_dir, tr("CSV file (*.csv)"));
|
||||
exportDataToFilename(file_name);
|
||||
}
|
||||
|
||||
void QueryTool::setQueryTextChanged(bool queryTextChanged)
|
||||
{
|
||||
if (m_queryTextChanged != queryTextChanged) {
|
||||
m_queryTextChanged = queryTextChanged;
|
||||
updateTitle();
|
||||
}
|
||||
}
|
||||
123
pglab/querytool/QueryTool.h
Normal file
123
pglab/querytool/QueryTool.h
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
#ifndef QUERYTAB_H
|
||||
#define QUERYTAB_H
|
||||
|
||||
#include "ManagedPage.h"
|
||||
#include "ASyncDBConnection.h"
|
||||
#include "QueryResultModel.h"
|
||||
#include "QueryExplainModel.h"
|
||||
#include "stopwatch.h"
|
||||
#include "tuplesresultwidget.h"
|
||||
|
||||
#include <QWidget>
|
||||
#include <memory>
|
||||
|
||||
class IDatabaseWindow;
|
||||
|
||||
namespace Ui {
|
||||
class QueryTab;
|
||||
}
|
||||
|
||||
namespace Pgsql {
|
||||
class ErrorDetails ;
|
||||
}
|
||||
|
||||
class QTableView;
|
||||
|
||||
class QTabWidget;
|
||||
class SqlSyntaxHighlighter;
|
||||
class ExplainRoot;
|
||||
class QueryResultModel;
|
||||
class QueryExplainModel;
|
||||
class PgTypeContainer;
|
||||
class OpenDatabase;
|
||||
class QueryParamListController;
|
||||
class PgDatabaseCatalog;
|
||||
|
||||
class QueryTool : public ManagedPage {
|
||||
Q_OBJECT
|
||||
public:
|
||||
QueryTool(IDatabaseWindow *context, QWidget *parent = nullptr);
|
||||
~QueryTool() override;
|
||||
|
||||
void newdoc();
|
||||
bool load(const QString &filename);
|
||||
|
||||
void explain(bool analyze);
|
||||
|
||||
bool CanClose(bool prompt_user);
|
||||
|
||||
void generateCode();
|
||||
void exportDataToFilename(const QString &filename);
|
||||
|
||||
QString fileName() const { return m_fileName; }
|
||||
bool isChanged() const { return m_queryTextChanged; }
|
||||
bool isNew() const { return m_new; }
|
||||
void focusEditor();
|
||||
|
||||
QString title() const;
|
||||
|
||||
|
||||
public slots:
|
||||
void execute();
|
||||
/// Save the document under its current name, a file save dialog will be shown if this is a new document
|
||||
bool save();
|
||||
/// Saves the document under a new name and continue editing the document under this new name.
|
||||
bool saveAs();
|
||||
/// Save the document under a new name but continue editing the document under its old name.
|
||||
void saveCopyAs();
|
||||
void copyQueryAsCString();
|
||||
void copyQueryAsRawCppString();
|
||||
void pasteLangString();
|
||||
void cancel();
|
||||
void exportData();
|
||||
|
||||
private:
|
||||
|
||||
using ResultTabContainer = std::vector<TuplesResultWidget*>;
|
||||
IDatabaseWindow *m_context;
|
||||
Ui::QueryTab *ui;
|
||||
SqlSyntaxHighlighter* highlighter;
|
||||
ConnectionConfig m_config;
|
||||
StopWatch m_stopwatch;
|
||||
|
||||
QueryParamListController *m_queryParamListController = nullptr;
|
||||
|
||||
bool m_new = true;
|
||||
QString m_fileName; ///< use setFileName function to set
|
||||
bool m_queryTextChanged = false;
|
||||
|
||||
std::shared_ptr<PgDatabaseCatalog> m_catalog;
|
||||
ASyncDBConnection m_dbConnection;
|
||||
|
||||
std::unique_ptr<QueryExplainModel> explainModel;
|
||||
ResultTabContainer resultList;
|
||||
|
||||
void setFileName(const QString &filename);
|
||||
bool continueWithoutSavingWarning();
|
||||
bool saveSqlTo(const QString &filename);
|
||||
QString promptUserForSaveSqlFilename();
|
||||
|
||||
void addLog(QString s);
|
||||
|
||||
QString getCommand() const;
|
||||
std::string getCommandUtf8() const;
|
||||
|
||||
void clearResult();
|
||||
void markError(const Pgsql::ErrorDetails &details);
|
||||
void updateTitle();
|
||||
void setQueryTextChanged(bool queryTextChanged);
|
||||
|
||||
private slots:
|
||||
|
||||
void explain_ready(ExplainRoot::SPtr explain);
|
||||
void query_ready(std::shared_ptr<Pgsql::Result>, qint64 elapsedms);
|
||||
|
||||
void queryTextChanged();
|
||||
void connectionStateChanged(ASyncDBConnection::State state);
|
||||
void receiveNotice(Pgsql::ErrorDetails notice);
|
||||
|
||||
void startConnect();
|
||||
};
|
||||
|
||||
|
||||
#endif // QUERYTAB_H
|
||||
Loading…
Add table
Add a link
Reference in a new issue