#include "querytab.h" #include "ui_querytab.h" #include "sqlhighlighter.h" #include #include #include #include #include #include #include #include "explaintreemodelitem.h" #include "json/json.h" #include "mainwindow.h" #include "util.h" QueryTab::QueryTab(MainWindow *win, QWidget *parent) : QWidget(parent), ui(new Ui::QueryTab), m_win(win) { ui->setupUi(this); m_dbConnection.setStateCallback([this](ASyncDBConnection::State st) { m_win->QueueTask([this, st]() { connectionStateChanged(st); }); }); m_dbConnection.setNoticeCallback([this](Pgsql::ErrorDetails details) { m_win->QueueTask([this, details]() { receiveNotice(details); }); }); QFont font; font.setFamily("Source Code Pro"); font.setFixedPitch(true); font.setPointSize(10); ui->queryEdit->setFont(font); highlighter.reset(new SqlHighlighter(ui->queryEdit->document())); connect(ui->queryEdit, &QPlainTextEdit::textChanged, this, &QueryTab::queryTextChanged); // m_stopwatch.setOutputLabel(ui->lblElapsedTime); // ui->lblElapsedTime->clear(); // ui->lblRowCount->clear(); } QueryTab::~QueryTab() { m_dbConnection.closeConnection(); m_dbConnection.setStateCallback(nullptr); delete ui; } void QueryTab::setConfig(const ConnectionConfig &config) { m_config = config; // QString title = "pglab - "; // title += m_config.name().c_str(); // setWindowTitle(title); m_win->QueueTask([this]() { startConnect(); }); } bool QueryTab::canClose() { bool can_close; if (m_queryTextChanged) { can_close = continueWithoutSavingWarning(); } else { can_close = true; } return can_close; } //void QueryTab::open() //{ // if (m_queryTextChanged && !continueWithoutSavingWarning()) { // return; // } // QString home_dir = QStandardPaths::locate(QStandardPaths::HomeLocation, "", QStandardPaths::LocateDirectory); // QString file_name = QFileDialog::getOpenFileName(this, // tr("Open sql query"), home_dir, tr("SQL files (*.sql *.txt)")); // if ( ! file_name.isEmpty()) { // QFile file(file_name); // if (file.open(QIODevice::ReadWrite)) { // QTextStream stream(&file); // ui->queryEdit->clear(); // while (!stream.atEnd()){ // QString line = stream.readLine(); // ui->queryEdit->appendPlainText(line); // } // m_queryTextChanged = false; // setFileName(file_name); // } // } //} void QueryTab::newdoc() { ui->queryEdit->clear(); setFileName(QString()); m_queryTextChanged = false; } bool QueryTab::load(const QString &filename) { bool result = false; QFile file(filename); if (file.open(QIODevice::ReadOnly)) { QByteArray ba = file.readAll(); const char *ptr = ba.constData(); QTextCodec *codec = QTextCodec::codecForUtfText(ba, QTextCodec::codecForName("utf-8")); QTextCodec::ConverterState state; QString text = codec->toUnicode(ptr, ba.size(), &state); if (state.invalidChars > 0) { file.reset(); QTextStream stream(&file); text = stream.readAll(); } ui->queryEdit->setPlainText(text); m_queryTextChanged = false; setFileName(filename); result = true; } return result; } void QueryTab::save() { if (m_fileName.isEmpty()) { saveAs(); } else { saveSqlTo(m_fileName); } } void QueryTab::saveAs() { QString filename = promptUserForSaveSqlFilename(); if (!filename.isEmpty()) { saveSqlTo(filename); setFileName(filename); } } void QueryTab::saveCopyAs() { QString filename = promptUserForSaveSqlFilename(); if (!filename.isEmpty()) { saveSqlTo(filename); } } void QueryTab::execute() { if (m_dbConnection.state() == ASyncDBConnection::State::Connected) { addLog("Query clicked"); clearResult(); ui->messagesEdit->clear(); std::string cmd = getCommand(); m_stopwatch.start(); m_dbConnection.send(cmd, [this](std::shared_ptr res, qint64 elapsedms) { m_win->QueueTask([this, res, elapsedms]() { query_ready(res, elapsedms); }); }); } } void QueryTab::explain(bool analyze) { ui->explainTreeView->setModel(nullptr); explainModel.reset(); ui->messagesEdit->clear(); addLog("Explain clicked"); std::string analyze_str; if (analyze) { analyze_str = "ANALYZE, "; } m_stopwatch.start(); std::string cmd = "EXPLAIN (" + analyze_str + "VERBOSE, BUFFERS, FORMAT JSON) " + getCommand(); m_dbConnection.send(cmd, [this](std::shared_ptr res, qint64 ) { if (res) { // Process explain data seperately std::thread([this,res]() { std::shared_ptr explain; 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); } } m_win->QueueTask([this, explain]() { explain_ready(explain); }); }).detach(); } }); } void QueryTab::cancel() { m_dbConnection.cancel(); } void QueryTab::setFileName(const QString &filename) { m_fileName = filename; QFileInfo fileInfo(filename); QString fn(fileInfo.fileName()); setTabCaption(fn, m_fileName); } bool QueryTab::continueWithoutSavingWarning() { QMessageBox msgBox; msgBox.setIcon(QMessageBox::Warning); msgBox.setText("The document has been modified."); msgBox.setInformativeText("The current query has unsaved changes, do you want to continue without saving those changes?"); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::No); int ret = msgBox.exec(); return ret == QMessageBox::Yes; } bool QueryTab::saveSqlTo(const QString &filename) { bool result = false; QFile file(filename); if (file.open(QIODevice::WriteOnly)) { QTextStream stream(&file); stream.setCodec("utf-8"); QString text = ui->queryEdit->toPlainText(); stream << text; /* QTextDocument *doc = ui->queryEdit->document(); QTextBlock block = doc->firstBlock(); while (stream.status() == QTextStream::Ok && block.isValid()) { QString plain = block.text(); stream << plain << "\n"; block = block.next(); }*/ if (stream.status() == QTextStream::Ok) { m_queryTextChanged = false; result = true; } } return result; } QString QueryTab::promptUserForSaveSqlFilename() { QString home_dir = QStandardPaths::locate(QStandardPaths::HomeLocation, "", QStandardPaths::LocateDirectory); return QFileDialog::getSaveFileName(this, tr("Save query"), home_dir, tr("SQL file (*.sql)")); } void QueryTab::queryTextChanged() { m_queryTextChanged = true; } void QueryTab::connectionStateChanged(ASyncDBConnection::State state) { QString status_str; switch (state) { case ASyncDBConnection::State::NotConnected: status_str = tr("Geen verbinding"); break; case ASyncDBConnection::State::Connecting: status_str = tr("Verbinden"); break; case ASyncDBConnection::State::Connected: status_str = tr("Verbonden"); break; case ASyncDBConnection::State::QuerySend: status_str = tr("Query verstuurd"); break; case ASyncDBConnection::State::CancelSend: status_str = tr("Query geannuleerd"); break; } addLog(status_str); // statusBar()->showMessage(status_str); // bool connected = ASyncDBConnection::State::Connected == state; // ui->actionExecute_SQL->setEnabled(connected); // ui->actionExplain_Analyze->setEnabled(connected); // ui->actionCancel->setEnabled(ASyncDBConnection::State::QuerySend == state); } void QueryTab::addLog(QString s) { QTextCursor text_cursor = QTextCursor(ui->edtLog->document()); text_cursor.movePosition(QTextCursor::End); text_cursor.insertText(s + "\r\n"); } void QueryTab::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 QueryTab::startConnect() { m_dbConnection.setupConnection(m_config); } void QueryTab::explain_ready(ExplainRoot::SPtr explain) { m_stopwatch.stop(); if (explain) { addLog("Explain ready"); QString 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); // statusBar()->showMessage(tr("Explain ready.")); } else { addLog("Explain no result"); ui->tabWidget->setCurrentWidget(ui->messageTab); // statusBar()->showMessage(tr("Explain failed.")); } } std::string QueryTab::getCommand() const { QString command; QTextCursor cursor = ui->queryEdit->textCursor(); if (cursor.hasSelection()) { command = cursor.selection().toPlainText(); } else { command = ui->queryEdit->toPlainText(); } return command.toUtf8().data(); } void QueryTab::setTabCaption(const QString &caption, const QString &tooltip) { QWidget * w = parentWidget(); QWidget * p = w->parentWidget(); QTabWidget *tabwidget = dynamic_cast(p); if (tabwidget) { int i = tabwidget->indexOf(this); if (i >= 0) { tabwidget->setTabText(i, caption); tabwidget->setTabToolTip(i, tooltip); } } } void QueryTab::query_ready(std::shared_ptr 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(nullptr , dbres); TuplesResultWidget *trw = new TuplesResultWidget; trw->setResult(result_model, elapsedms); resultList.push_back(trw); ui->tabWidget->addTab(trw, "Data"); // ui->lblRowCount->setText(rowcount_str); // resultModel.reset(new QueryResultModel(nullptr , dbres)); // ui->ResultView->setModel(resultModel.get()); // ui->tabWidget->setCurrentWidget(ui->dataTab); //statusBar()->showMessage(tr("Query ready.")); } else { if (st == PGRES_COMMAND_OK) { // statusBar()->showMessage(tr("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); receiveNotice(dbres->diagDetails()); } } } else { m_stopwatch.stop(); addLog("query_ready with NO result"); // statusBar()->showMessage(tr("Query cancelled.")); } } void QueryTab::clearResult() { // ui->ResultView->setModel(nullptr); // resultModel.reset(); for (auto e : resultList) delete e; resultList.clear(); // ui->lblRowCount->clear(); }