Skip to content

A native macOS / windows / Linux database IDE built with Swift and AppKit. Connect to PostgreSQL, MySQL, SQLite, and Redis from a single app with a fast, keyboard-driven interface.

C++

Add explain plan visualizer (#81)

haidang181073407243ed80
diff --git a/linux/src/Presentation/CMakeLists.txt b/linux/src/Presentation/CMakeLists.txt
index 57c0bec..1a34b25 100644
--- a/linux/src/Presentation/CMakeLists.txt
+++ b/linux/src/Presentation/CMakeLists.txt
@@ -25,6 +25,12 @@ qt_add_library(gridex-presentation STATIC
Views/Main/WorkspaceView.cpp
Views/QueryEditor/QueryEditorView.cpp
Views/QueryEditor/SqlHighlighter.cpp
+ Views/ExplainVisualizer/ExplainPlanParser.cpp
+ Views/ExplainVisualizer/ExplainPlanHeuristics.cpp
+ Views/ExplainVisualizer/ExplainCards.cpp
+ Views/ExplainVisualizer/ExplainVisualizerWidget.cpp
+ Views/ExplainVisualizer/PlanNodeRow.cpp
+ Views/ExplainVisualizer/ExplainExtension.cpp
Views/Settings/SettingsDialog.cpp
Views/Chrome/GxToolbar.cpp
Views/Chrome/GxStatusBar.cpp
diff --git a/linux/src/Presentation/Views/ExplainVisualizer/ExplainCards.cpp b/linux/src/Presentation/Views/ExplainVisualizer/ExplainCards.cpp
new file mode 100644
index 0000000..2c053d4
--- /dev/null
+++ b/linux/src/Presentation/Views/ExplainVisualizer/ExplainCards.cpp
@@ -0,0 +1,229 @@
+#include "Presentation/Views/ExplainVisualizer/ExplainCards.h"
+#include "Presentation/Views/ExplainVisualizer/ExplainColors.h"
+#include "Presentation/Views/ExplainVisualizer/ExplainFormat.h"
+
+#include <QGuiApplication>
+#include <QHBoxLayout>
+#include <QLabel>
+#include <QProgressBar>
+#include <QPushButton>
+#include <QSizePolicy>
+#include <QVBoxLayout>
+
+namespace gridex::explain {
+
+// ── MetricCard ────────────────────────────────────────────────────────
+MetricCard::MetricCard(const QString& glyph,
+ const QString& label,
+ const QString& value,
+ const QString& unit,
+ const QString& delta,
+ double barPct,
+ ::gridex::explainviz::NodeLevel tone,
+ QWidget* parent)
+ : QFrame(parent)
+{
+ setFrameShape(QFrame::StyledPanel);
+ setLineWidth(1);
+ setStyleSheet(QStringLiteral(
+ "MetricCard { %1 %2 border-radius: 8px; }")
+ .arg(cardBgCss(), cardBorderCss()));
+
+ auto* lay = new QVBoxLayout(this);
+ lay->setContentsMargins(12, 10, 12, 10);
+ lay->setSpacing(4);
+
+ auto* header = new QHBoxLayout();
+ header->setSpacing(6);
+ auto* glyphLbl = new QLabel(glyph, this);
+ auto f = glyphLbl->font(); f.setPointSize(f.pointSize() + 1); glyphLbl->setFont(f);
+ auto* lblLbl = new QLabel(label, this);
+ lblLbl->setStyleSheet(mutedTextCss());
+ header->addWidget(glyphLbl);
+ header->addWidget(lblLbl, 1);
+ lay->addLayout(header);
+
+ auto* valueRow = new QHBoxLayout();
+ valueRow->setSpacing(4);
+ auto* valLbl = new QLabel(value, this);
+ auto vf = valLbl->font(); vf.setPointSize(vf.pointSize() + 4); vf.setBold(true);
+ valLbl->setFont(vf);
+ valueRow->addWidget(valLbl);
+ if (!unit.isEmpty()) {
+ auto* unitLbl = new QLabel(unit, this);
+ unitLbl->setStyleSheet(mutedTextCss());
+ valueRow->addWidget(unitLbl);
+ }
+ valueRow->addStretch(1);
+ if (!delta.isEmpty()) {
+ auto* deltaLbl = new QLabel(delta, this);
+ deltaLbl->setStyleSheet(QStringLiteral("color: %1;").arg(heatColor(tone).name()));
+ valueRow->addWidget(deltaLbl);
+ }
+ lay->addLayout(valueRow);
+
+ if (barPct > 0.0) {
+ auto* bar = new QProgressBar(this);
+ bar->setRange(0, 100);
+ bar->setValue(qBound(0, int(barPct * 100), 100));
+ bar->setTextVisible(false);
+ bar->setFixedHeight(4);
+ bar->setStyleSheet(QStringLiteral(
+ "QProgressBar { background: %1; border: 0; border-radius: 2px; }"
+ "QProgressBar::chunk { background: %2; border-radius: 2px; }")
+ .arg(trackBgHex(), heatColor(tone).name()));
+ lay->addWidget(bar);
+ }
+}
+
+// ── InfoBarLite ───────────────────────────────────────────────────────
+InfoBarLite::InfoBarLite(QWidget* parent) : QFrame(parent) {
+ setFrameShape(QFrame::StyledPanel);
+ auto* lay = new QVBoxLayout(this);
+ lay->setContentsMargins(12, 8, 12, 8);
+ lay->setSpacing(2);
+ titleLbl_ = new QLabel(this);
+ auto tf = titleLbl_->font(); tf.setBold(true); titleLbl_->setFont(tf);
+ detailLbl_ = new QLabel(this);
+ detailLbl_->setWordWrap(true);
+ lay->addWidget(titleLbl_);
+ lay->addWidget(detailLbl_);
+ setMessage({}, {}, ::gridex::explainviz::IssueSeverity::Warn);
+ hide();
+}
+
+void InfoBarLite::setMessage(const QString& title,
+ const QString& detail,
+ ::gridex::explainviz::IssueSeverity sev) {
+ using S = ::gridex::explainviz::IssueSeverity;
+ using L = ::gridex::explainviz::NodeLevel;
+ L tone = (sev == S::Bad) ? L::Bad : (sev == S::Info ? L::Good : L::Warn);
+ setStyleSheet(QStringLiteral(
+ "InfoBarLite { background: %1; border: 1px solid %2; border-radius: 6px; color: %2; }")
+ .arg(heatBgRgba(tone, 64), heatColor(tone).name()));
+ if (titleLbl_) titleLbl_->setStyleSheet(QStringLiteral("color: %1;").arg(heatColor(tone).name()));
+ if (detailLbl_) detailLbl_->setStyleSheet(QStringLiteral("color: %1;").arg(heatColor(tone).name()));
+ titleLbl_->setText(title);
+ detailLbl_->setText(detail);
+ detailLbl_->setVisible(!detail.isEmpty());
+ setVisible(!title.isEmpty());
+}
+
+void InfoBarLite::clear() { hide(); }
+
+// ── RecCard ───────────────────────────────────────────────────────────
+RecCard::RecCard(const ::gridex::explainviz::Recommendation& r, QWidget* parent)
+ : QFrame(parent), sql_(toQ(r.previewSql))
+{
+ setFrameShape(QFrame::StyledPanel);
+ using L = ::gridex::explainviz::NodeLevel;
+ using S = ::gridex::explainviz::IssueSeverity;
+ L tone = (r.severity == S::Bad) ? L::Bad : (r.severity == S::Info ? L::Good : L::Warn);
+ setStyleSheet(QStringLiteral(
+ "RecCard { %1 border-left: 4px solid %2; %3 border-radius: 6px; }")
+ .arg(cardBgCss(), heatColor(tone).name(), cardBorderCss()));
+
+ auto* lay = new QVBoxLayout(this);
+ lay->setContentsMargins(14, 10, 14, 10);
+ lay->setSpacing(4);
+
+ auto* titleLbl = new QLabel(toQ(r.title), this);
+ auto tf = titleLbl->font(); tf.setBold(true); titleLbl->setFont(tf);
+ titleLbl->setWordWrap(true);
+ auto* rationaleLbl = new QLabel(toQ(r.rationale), this);
+ rationaleLbl->setWordWrap(true);
+ rationaleLbl->setStyleSheet(mutedTextCss());
+ lay->addWidget(titleLbl);
+ lay->addWidget(rationaleLbl);
+
+ if (!sql_.isEmpty()) {
+ auto* btn = new QPushButton(tr("Preview SQL"), this);
+ btn->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Fixed);
+ connect(btn, &QPushButton::clicked, this, [this]() { emit previewRequested(sql_); });
+ lay->addWidget(btn, 0, Qt::AlignLeft);
+ }
+}
+
+// ── WaterfallRow ──────────────────────────────────────────────────────
+WaterfallRow::WaterfallRow(const QString& glyph,
+ const QString& label,
+ double startMs,
+ double durMs,
+ double maxMs,
+ ::gridex::explainviz::NodeLevel level,
+ QWidget* parent)
+ : QFrame(parent)
+{
+ auto* lay = new QHBoxLayout(this);
+ lay->setContentsMargins(0, 3, 0, 3);
+ lay->setSpacing(0);
+
+ // 220px name column = glyph (24x20 tinted badge) + label (ellipsized).
+ auto* name = new QWidget(this);
+ name->setFixedWidth(220);
+ auto* nameLay = new QHBoxLayout(name);
+ nameLay->setContentsMargins(0, 0, 8, 0);
+ nameLay->setSpacing(6);
+ auto* glyphBox = new QLabel(glyph, name);
+ glyphBox->setFixedSize(24, 20);
+ glyphBox->setAlignment(Qt::AlignCenter);
+ {
+ auto gf = glyphBox->font(); gf.setBold(true);
+ gf.setPointSize(qMax(8, gf.pointSize() - 1));
+ glyphBox->setFont(gf);
+ }
+ glyphBox->setStyleSheet(QStringLiteral(
+ "background: %1; color: %2; border-radius: 4px;")
+ .arg(heatBgRgba(level, 64), heatColor(level).name()));
+ auto* labelLbl = new QLabel(label, name);
+ auto lf = labelLbl->font();
+ lf.setPointSize(qMax(8, lf.pointSize() - 1));
+ labelLbl->setFont(lf);
+ labelLbl->setStyleSheet(mutedTextCss());
+ labelLbl->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);
+ nameLay->addWidget(glyphBox);
+ nameLay->addWidget(labelLbl, 1);
+ lay->addWidget(name);
+
+ // Star bar track: 16px track with neutral bg + 10px colored bar
+ // positioned by margins for start offset and width for duration.
+ double total = maxMs > 0.0 ? maxMs : 1.0;
+ double startFrac = qBound(0.0, startMs / total, 1.0);
+ double durFrac = qBound(0.001, durMs / total, 1.0);
+
+ auto* track = new QWidget(this);
+ track->setFixedHeight(16);
+ track->setStyleSheet(QStringLiteral(
+ "background: %1; border-radius: 3px;")
+ .arg(isDarkPalette() ? QStringLiteral("rgba(255,255,255,0.06)")
+ : QStringLiteral("rgba(0,0,0,0.05)")));
+ auto* trackLay = new QHBoxLayout(track);
+ trackLay->setContentsMargins(0, 0, 0, 0);
+ trackLay->setSpacing(0);
+ // Use spacer/widget ratios — startFrac : durFrac : (1-startFrac-durFrac).
+ int s = qMax(0, int(startFrac * 1000));
+ int d = qMax(2, int(durFrac * 1000));
+ int t = qMax(0, 1000 - s - d);
+ if (s > 0) trackLay->addStretch(s);
+ auto* fill = new QFrame(track);
+ fill->setMinimumHeight(10);
+ fill->setMaximumHeight(10);
+ fill->setStyleSheet(QStringLiteral(
+ "background: %1; border-radius: 2px;")
+ .arg(heatColor(level).name()));
+ trackLay->addWidget(fill, d, Qt::AlignVCenter);
+ if (t > 0) trackLay->addStretch(t);
+ lay->addWidget(track, 1);
+
+ // 70px duration column right-aligned.
+ auto* msLbl = new QLabel(QStringLiteral("%1 ms").arg(fmtMs(durMs)), this);
+ msLbl->setFixedWidth(70);
+ msLbl->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ msLbl->setStyleSheet(mutedTextCss());
+ auto mf = msLbl->font();
+ mf.setPointSize(qMax(8, mf.pointSize() - 1));
+ msLbl->setFont(mf);
+ lay->addWidget(msLbl);
+}
+
+}
diff --git a/linux/src/Presentation/Views/ExplainVisualizer/ExplainCards.h b/linux/src/Presentation/Views/ExplainVisualizer/ExplainCards.h
new file mode 100644
index 0000000..09cbab8
--- /dev/null
+++ b/linux/src/Presentation/Views/ExplainVisualizer/ExplainCards.h
@@ -0,0 +1,69 @@
+#pragma once
+// Small framed widgets used by the Explain Visualizer's loaded state:
+// summary metric cards, the warning InfoBar, recommendation cards, and
+// timing waterfall rows. Each is a thin QFrame composition — no custom
+// paintEvent so they pick up the system palette without extra work.
+
+#include "Presentation/Views/ExplainVisualizer/ExplainPlanTypes.h"
+#include "Presentation/Views/ExplainVisualizer/ExplainPlanHeuristics.h"
+
+#include <QFrame>
+#include <QString>
+
+class QLabel;
+class QPushButton;
+class QProgressBar;
+
+namespace gridex::explain {
+
+class MetricCard : public QFrame {
+ Q_OBJECT
+public:
+ MetricCard(const QString& glyph,
+ const QString& label,
+ const QString& value,
+ const QString& unit,
+ const QString& delta,
+ double barPct,
+ ::gridex::explainviz::NodeLevel tone,
+ QWidget* parent = nullptr);
+};
+
+class InfoBarLite : public QFrame {
+ Q_OBJECT
+public:
+ explicit InfoBarLite(QWidget* parent = nullptr);
+ // Show an issue or hide if title is empty.
+ void setMessage(const QString& title,
+ const QString& detail,
+ ::gridex::explainviz::IssueSeverity sev);
+ void clear();
+private:
+ QLabel* titleLbl_ = nullptr;
+ QLabel* detailLbl_ = nullptr;
+};
+
+class RecCard : public QFrame {
+ Q_OBJECT
+public:
+ explicit RecCard(const ::gridex::explainviz::Recommendation& r,
+ QWidget* parent = nullptr);
+signals:
+ void previewRequested(const QString& sql);
+private:
+ QString sql_;
+};
+
+class WaterfallRow : public QFrame {
+ Q_OBJECT
+public:
+ WaterfallRow(const QString& glyph,
+ const QString& label,
+ double startMs,
+ double durMs,
+ double maxMs,
+ ::gridex::explainviz::NodeLevel level,
+ QWidget* parent = nullptr);
+};
+
+}
diff --git a/linux/src/Presentation/Views/ExplainVisualizer/ExplainColors.h b/linux/src/Presentation/Views/ExplainVisualizer/ExplainColors.h
new file mode 100644
index 0000000..2b3e9e0
--- /dev/null
+++ b/linux/src/Presentation/Views/ExplainVisualizer/ExplainColors.h
@@ -0,0 +1,137 @@
+#pragma once
+// Theme-aware color palette + glyph mapping for the Explain Visualizer.
+// The strategy:
+// • heat accents (red/amber/green) stay saturated so they read on any
+// theme — they're the focal point of the visualization
+// • backgrounds for tinted regions use the accent color at ~18% alpha
+// so they blend over whatever palette base is set by the active qss
+// • text on tinted backgrounds uses the saturated accent — high
+// contrast on both light pastels and dark translucent fills
+// • neutral surfaces (cards, borders, muted text) use the gx skin
+// tokens — same hex values the style-gx[-light].qss files use — so
+// the visualizer blends into the rest of the IDE chrome
+
+#include "Presentation/Views/ExplainVisualizer/ExplainPlanTypes.h"
+
+#include <QColor>
+#include <QGuiApplication>
+#include <QSettings>
+#include <QString>
+#include <QStyleHints>
+
+namespace gridex::explain {
+
+// QSS doesn't update QPalette, so checking palette(Window) drifts from
+// what the user actually sees. Mirror ThemeManager's source of truth:
+// the `ui/theme` QSettings key (set by ThemeManager::setMode), falling
+// back to the system color scheme when Auto.
+inline bool isDarkPalette() {
+ const QString saved = QSettings().value(QStringLiteral("ui/theme"),
+ QStringLiteral("Auto")).toString();
+ if (saved == QLatin1String("Light")) return false;
+ if (saved == QLatin1String("Dark")) return true;
+ const Qt::ColorScheme s = QGuiApplication::styleHints()->colorScheme();
+ return (s == Qt::ColorScheme::Dark) || (s == Qt::ColorScheme::Unknown);
+}
+
+// Saturated accent. Picked separately for light vs dark so the contrast
+// against the page background stays readable.
+inline QColor heatColor(::gridex::explainviz::NodeLevel l) {
+ using L = ::gridex::explainviz::NodeLevel;
+ if (isDarkPalette()) {
+ switch (l) {
+ case L::Bad: return QColor(0xF3, 0x8B, 0xA8); // pink (Catppuccin Mocha red)
+ case L::Warn: return QColor(0xF9, 0xE2, 0xAF); // peach
+ case L::Good: return QColor(0xA6, 0xE3, 0xA1); // green
+ }
+ return QColor(0xBA, 0xC2, 0xDE);
+ }
+ switch (l) {
+ case L::Bad: return QColor(0xC4, 0x2B, 0x1C);
+ case L::Warn: return QColor(0xCA, 0x5C, 0x00);
+ case L::Good: return QColor(0x10, 0x7C, 0x10);
+ }
+ return QColor(0x70, 0x70, 0x70);
+}
+
+// Translucent fill — sits on top of whatever the qss sets as the panel
+// background. Returns an rgba() css string so widgets can drop it
+// straight into setStyleSheet without computing rgba themselves.
+inline QString heatBgRgba(::gridex::explainviz::NodeLevel l, int alpha = 46) {
+ QColor c = heatColor(l);
+ return QStringLiteral("rgba(%1, %2, %3, %4)")
+ .arg(c.red()).arg(c.green()).arg(c.blue()).arg(alpha);
+}
+
+// Muted text — secondary label color from the gx skin (--gx-text-2 dark,
+// equivalent low-contrast gray on light).
+inline QString mutedTextCss() {
+ return isDarkPalette()
+ ? QStringLiteral("color: #7d8185;") // gx --gx-text-3
+ : QStringLiteral("color: #5c6066;");
+}
+
+// Card-style background — matches QFrame[gxRole="card"] in the gx qss
+// (--gx-bg-2 dark / light) so the visualizer surfaces blend with the
+// rest of the IDE chrome.
+inline QString cardBgCss() {
+ return isDarkPalette()
+ ? QStringLiteral("background: #171c22;") // gx --gx-bg-2 dark
+ : QStringLiteral("background: #e9ebef;"); // gx --gx-bg-2 light
+}
+
+inline QString cardBorderCss() {
+ return isDarkPalette()
+ ? QStringLiteral("border: 1px solid #2e3339;") // gx border-1 dark
+ : QStringLiteral("border: 1px solid #c5cad1;"); // gx border-1 light
+}
+
+// Page background — what QWidget {} resolves to in the gx qss. Use as
+// the track color for progress bars / inline meters so the chunk pops
+// against a surface one step darker than the card.
+inline QString trackBgHex() {
+ return isDarkPalette()
+ ? QStringLiteral("#11151a") // gx --gx-bg-1 dark
+ : QStringLiteral("#f4f5f7"); // gx --gx-bg-1 light
+}
+
+// One-char Unicode glyph per node kind. Windows uses Segoe MDL2 private-
+// use area; on Linux we pick widely-available Unicode symbols instead so
+// the visualizer renders cleanly with the system default font.
+inline QString kindGlyph(::gridex::explainviz::NodeKind k) {
+ using K = ::gridex::explainviz::NodeKind;
+ switch (k) {
+ case K::Limit: return QStringLiteral("↤");
+ case K::Sort: return QStringLiteral("⇵");
+ case K::HashJoin: return QStringLiteral("⋈");
+ case K::MergeJoin: return QStringLiteral("⋈");
+ case K::NestedLoop: return QStringLiteral("↻");
+ case K::SeqScan: return QStringLiteral("☰");
+ case K::IndexScan: return QStringLiteral("⧉");
+ case K::IndexOnlyScan: return QStringLiteral("⧉");
+ case K::BitmapHeapScan: return QStringLiteral("▦");
+ case K::BitmapIndexScan: return QStringLiteral("▦");
+ case K::Hash: return QStringLiteral("⌗");
+ case K::Aggregate: return QStringLiteral("∑");
+ case K::GroupAggregate: return QStringLiteral("∑");
+ case K::HashAggregate: return QStringLiteral("∑");
+ case K::WindowAgg: return QStringLiteral("▣");
+ case K::Materialize: return QStringLiteral("□");
+ case K::Gather: return QStringLiteral("▼");
+ case K::GatherMerge: return QStringLiteral("▼");
+ case K::Append: return QStringLiteral("⊕");
+ case K::Result: return QStringLiteral("↳");
+ case K::SubqueryScan: return QStringLiteral("⁐");
+ case K::CteScan: return QStringLiteral("⦵");
+ case K::Unique: return QStringLiteral("♠");
+ case K::Memoize: return QStringLiteral("◉");
+ case K::Other: return QStringLiteral("•");
+ }
+ return QStringLiteral("•");
+}
+
+inline QString toQ(const std::wstring& w) {
+ return QString::fromWCharArray(w.data(), static_cast<int>(w.size()));
+}
+
+}
diff --git a/linux/src/Presentation/Views/ExplainVisualizer/ExplainExtension.cpp b/linux/src/Presentation/Views/ExplainVisualizer/ExplainExtension.cpp
new file mode 100644
index 0000000..51d6510
--- /dev/null
+++ b/linux/src/Presentation/Views/ExplainVisualizer/ExplainExtension.cpp
@@ -0,0 +1,156 @@
+#include "Presentation/Views/ExplainVisualizer/ExplainExtension.h"
+
+#include "Core/Enums/DatabaseType.h"
+#include "Core/Models/Database/RowValue.h"
+#include "Core/Models/Query/QueryResult.h"
+#include "Core/Protocols/Database/IDatabaseAdapter.h"
+#include "Presentation/Views/QueryEditor/QueryEditorView.h"
+
+#include "Presentation/Views/ExplainVisualizer/ExplainPlanParser.h"
+#include "Presentation/Views/ExplainVisualizer/ExplainVisualizerWidget.h"
+
+#include <QClipboard>
+#include <QDialog>
+#include <QGuiApplication>
+#include <QHBoxLayout>
+#include <QMessageBox>
+#include <QPushButton>
+#include <QString>
+#include <QVBoxLayout>
+
+#include <atomic>
+#include <memory>
+
+namespace gridex::explain {
+
+namespace {
+
+void runExplain(::gridex::QueryEditorView* editor, ExplainVisualizerWidget* w);
+
+// One reusable dialog per editor. Created lazily on first click and
+// stored via QObject's dynamic-property bag (cast through QObject* so we
+// don't need Q_DECLARE_METATYPE(QDialog*) anywhere).
+QDialog* getOrCreateDialog(::gridex::QueryEditorView* editor,
+ ExplainVisualizerWidget*& outWidget) {
+ static const char* kProp = "gridex.explain.dialog";
+ if (auto* obj = editor->property(kProp).value<QObject*>()) {
+ if (auto* existing = qobject_cast<QDialog*>(obj)) {
+ outWidget = existing->findChild<ExplainVisualizerWidget*>();
+ return existing;
+ }
+ }
+ auto* dlg = new QDialog(editor->window());
+ dlg->setWindowTitle(QObject::tr("Explain plan"));
+ dlg->resize(1100, 800);
+ auto* lay = new QVBoxLayout(dlg);
+ lay->setContentsMargins(0, 0, 0, 0);
+ auto* w = new ExplainVisualizerWidget(dlg);
+ lay->addWidget(w);
+ outWidget = w;
+ editor->setProperty(kProp, QVariant::fromValue<QObject*>(dlg));
+ QObject::connect(w, &ExplainVisualizerWidget::copyPlanRequested,
+ [](const QString& json) {
+ QGuiApplication::clipboard()->setText(json);
+ });
+ QObject::connect(w, &ExplainVisualizerWidget::previewSqlRequested,
+ editor, [editor](const QString& sql) {
+ editor->setSql(sql);
+ });
+ QObject::connect(w, &ExplainVisualizerWidget::runRequested,
+ editor, [editor, w]() {
+ runExplain(editor, w);
+ });
+ return dlg;
+}
+
+// Run EXPLAIN against the active adapter and push to the widget. PG-only;
+// for any other engine we surface a friendly message.
+void runExplain(::gridex::QueryEditorView* editor, ExplainVisualizerWidget* w) {
+ auto* adapter = editor->adapter();
+ if (!adapter) {
+ w->showError(QObject::tr("Connect to a Postgres database first."));
+ return;
+ }
+ if (adapter->databaseType() != ::gridex::DatabaseType::PostgreSQL) {
+ w->showError(QObject::tr("Explain Visualizer currently supports PostgreSQL only."));
+ return;
+ }
+ const QString sql = editor->currentSql().trimmed();
+ if (sql.isEmpty()) {
+ w->showError(QObject::tr("Editor is empty — type a query first."));
+ return;
+ }
+ w->showLoading();
+
+ // Synchronous execution — runs on the UI thread for now to mirror the
+ // existing Run button path. A future improvement: move to a worker
+ // via QtConcurrent so the spinner stays animated.
+ std::string wrapped = "EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ";
+ // Strip trailing semicolon: PG dislikes "EXPLAIN ... SELECT 1;" in
+ // some client paths (treated as two statements by the protocol).
+ QString clean = sql;
+ while (clean.endsWith(';')) clean.chop(1);
+ wrapped += clean.toStdString();
+ try {
+ auto result = adapter->executeRaw(wrapped);
+ if (result.rows.empty() || result.rows.front().empty()) {
+ w->showError(QObject::tr("EXPLAIN returned no rows."));
+ return;
+ }
+ // PG returns the plan in column 0 of the single row. The PG
+ // adapter may surface it as either a plain string or our Json
+ // RowValue variant — accept both.
+ const auto& cell = result.rows.front().front();
+ std::string jsonUtf8;
+ if (cell.isString()) jsonUtf8 = cell.asString();
+ else if (cell.isJson()) jsonUtf8 = cell.asJson();
+ else {
+ w->showError(QObject::tr("EXPLAIN returned unexpected cell type."));
+ return;
+ }
+ // UTF-8 → wstring. ASCII bytes (the only kind in EXPLAIN JSON
+ // for typical workloads) map 1:1. Non-ASCII relation names would
+ // need a proper UTF-8 → UTF-32 decode; deferred until reported.
+ std::wstring jsonW = QString::fromUtf8(jsonUtf8).toStdWString();
+
+ auto doc = std::make_shared<::gridex::explainviz::PlanDocument>();
+ doc->originalSql = sql.toStdWString();
+ std::wstring err;
+ if (!::gridex::explainviz::ExplainPlanParser::parse(jsonW, *doc, err)) {
+ w->showError(QObject::tr("Parse failed: %1")
+ .arg(QString::fromWCharArray(err.data(), int(err.size()))));
+ return;
+ }
+ w->setPlan(doc);
+ } catch (const std::exception& e) {
+ w->showError(QString::fromUtf8(e.what()));
+ } catch (...) {
+ w->showError(QObject::tr("EXPLAIN failed with an unknown error."));
+ }
+}
+
+} // namespace
+
+void registerQueryEditorExtension() {
+ static std::atomic<bool> registered{false};
+ bool expected = false;
+ if (!registered.compare_exchange_strong(expected, true)) return;
+
+ ::gridex::QueryEditorView::registerExtension(
+ [](::gridex::QueryEditorView* editor) {
+ auto* btn = new QPushButton(QObject::tr("📊 Explain"), editor);
+ btn->setToolTip(QObject::tr("Run EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) and visualize the plan"));
+ QObject::connect(btn, &QPushButton::clicked, editor, [editor]() {
+ ExplainVisualizerWidget* w = nullptr;
+ auto* dlg = getOrCreateDialog(editor, w);
+ if (!w) return;
+ runExplain(editor, w);
+ if (!dlg->isVisible()) dlg->show();
+ dlg->raise();
+ dlg->activateWindow();
+ });
+ editor->addToolbarWidget(btn);
+ });
+}
+
+} // namespace gridex::explain
diff --git a/linux/src/Presentation/Views/ExplainVisualizer/ExplainExtension.h b/linux/src/Presentation/Views/ExplainVisualizer/ExplainExtension.h
new file mode 100644
index 0000000..795c870
--- /dev/null
+++ b/linux/src/Presentation/Views/ExplainVisualizer/ExplainExtension.h
@@ -0,0 +1,12 @@
+#pragma once
+// Application bootstrap: registers an "Explain" button on every QueryEditorView.
+// Called once from main() before MainWindow is constructed.
+
+namespace gridex::explain {
+
+// Register the toolbar extension. Safe to call multiple times — only
+// the first call wins. The hook is process-wide; new editors created
+// after this call pick it up automatically.
+void registerQueryEditorExtension();
+
+}
diff --git a/linux/src/Presentation/Views/ExplainVisualizer/ExplainFormat.h b/linux/src/Presentation/Views/ExplainVisualizer/ExplainFormat.h
new file mode 100644
index 0000000..bf36bc1
--- /dev/null
+++ b/linux/src/Presentation/Views/ExplainVisualizer/ExplainFormat.h
@@ -0,0 +1,45 @@
+#pragma once
+// Number / time / byte formatters used by the visualizer. Match the
+// Windows control's helpers exactly so labels line up across platforms.
+
+#include <QFontDatabase>
+#include <QString>
+#include <cmath>
+#include <cstdint>
+
+namespace gridex::explain {
+
+// Time: 2 decimals up to 100ms, then 1 decimal, then integer.
+inline QString fmtMs(double ms) {
+ if (ms < 10.0) return QString::number(ms, 'f', 3);
+ if (ms < 100.0) return QString::number(ms, 'f', 2);
+ if (ms < 10000) return QString::number(ms, 'f', 1);
+ return QString::number(ms, 'f', 0);
+}
+// Row counts / generic numbers — thousands suffix.
+inline QString fmtNum(double n) {
+ double abs = std::abs(n);
+ if (abs >= 1e9) return QString::number(n / 1e9, 'f', 1) + QStringLiteral("B");
+ if (abs >= 1e6) return QString::number(n / 1e6, 'f', 1) + QStringLiteral("M");
+ if (abs >= 1e3) return QString::number(n / 1e3, 'f', 1) + QStringLiteral("k");
+ return QString::number(static_cast<qint64>(n));
+}
+
+// Buffers: bytes → human readable.
+inline QString fmtBytes(quint64 b) {
+ constexpr quint64 KB = 1024;
+ constexpr quint64 MB = KB * 1024;
+ constexpr quint64 GB = MB * 1024;
+ if (b >= GB) return QString::number(double(b) / GB, 'f', 2) + QStringLiteral(" GB");
+ if (b >= MB) return QString::number(double(b) / MB, 'f', 1) + QStringLiteral(" MB");
+ if (b >= KB) return QString::number(double(b) / KB, 'f', 1) + QStringLiteral(" KB");
+ return QString::number(b) + QStringLiteral(" B");
+}
+
+inline QFont monospaceFont(int pointSize = 0) {
+ QFont f = QFontDatabase::systemFont(QFontDatabase::FixedFont);
+ if (pointSize > 0) f.setPointSize(pointSize);
+ return f;
+}
+
+}
diff --git a/linux/src/Presentation/Views/ExplainVisualizer/ExplainPlanHeuristics.cpp b/linux/src/Presentation/Views/ExplainVisualizer/ExplainPlanHeuristics.cpp
new file mode 100644
index 0000000..7d6b1d5
--- /dev/null
+++ b/linux/src/Presentation/Views/ExplainVisualizer/ExplainPlanHeuristics.cpp
@@ -0,0 +1,233 @@
+#include "ExplainPlanHeuristics.h"
+
+#include <algorithm>
+#include <cmath>
+#include <functional>
+#include <sstream>
+
+namespace gridex::explainviz
+{
+ // Threshold knobs — kept here for easy review.
+ static constexpr double SEQ_SCAN_FILTER_RATIO = 0.5; // ≥50% rows discarded → suggest index
+ static constexpr int SEQ_SCAN_MIN_REMOVED = 5000; // small tables not worth indexing
+ static constexpr double EST_VS_ACTUAL_FACTOR = 5.0; // |est−actual|/min > 5× → ANALYZE
+ static constexpr double EST_MIN_ROWS_FOR_ALERT = 100; // ignore tiny dev datasets
+ static constexpr int HASH_BATCH_THRESHOLD = 1; // >1 batch = spill
+ static constexpr double NESTED_LOOP_ROW_FACTOR = 1000; // outer rows × loops above this is suspicious
+
+ namespace
+ {
+ // Walk depth-first; first arg pre-order index lets caller process
+ // parents before children (tree label tagging) but isn't required.
+ void walk(const std::shared_ptr<PlanNode>& n,
+ const std::function<void(PlanNode&)>& fn)
+ {
+ if (!n) return;
+ fn(*n);
+ for (auto& c : n->children) walk(c, fn);
+ }
+
+ // Format a row count compactly (1.2k / 4.3M).
+ std::wstring fmtRows(double r)
+ {
+ std::wstringstream ss;
+ if (r >= 1e6) ss << (r / 1e6) << L"M";
+ else if (r >= 1e3) ss << (r / 1e3) << L"k";
+ else ss << static_cast<int>(r);
+ return ss.str();
+ }
+ }
+
+ std::vector<Issue> ExplainPlanHeuristics::analyze(PlanDocument& doc)
+ {
+ std::vector<Issue> issues;
+ if (!doc.root) return issues;
+
+ walk(doc.root, [&](PlanNode& n) {
+ // ── Rule 1: Sequential scan with high filter rejection.
+ // Reading a big table end-to-end and discarding most rows
+ // is the textbook case for "add an index".
+ if (n.kind == NodeKind::SeqScan && n.rowsRemovedByFilter > 0) {
+ double scanned = n.actualRows + n.rowsRemovedByFilter;
+ double rejectRatio = scanned > 0 ? n.rowsRemovedByFilter / scanned : 0.0;
+ if (rejectRatio >= SEQ_SCAN_FILTER_RATIO &&
+ n.rowsRemovedByFilter >= SEQ_SCAN_MIN_REMOVED)
+ {
+ Issue i;
+ i.nodeId = n.id;
+ i.severity = IssueSeverity::Bad;
+ i.title = L"Sequential scan rejecting " + fmtRows(n.rowsRemovedByFilter)
+ + L" rows on " + (n.relation.empty() ? L"a table" : n.relation);
+ std::wstringstream d;
+ d << L"The planner is reading "
+ << (n.relation.empty() ? L"the table" : n.relation)
+ << L" end-to-end and filtering " << static_cast<int>(rejectRatio * 100)
+ << L"% of rows. An index covering the WHERE clause would likely make this query much faster.";
+ i.detail = d.str();
+ issues.push_back(i);
+ n.level = NodeLevel::Bad;
+ }
+ }
+
+ // ── Rule 2: External-merge sort (spilled to disk).
+ if (n.kind == NodeKind::Sort && n.sortSpaceType == L"Disk") {
+ Issue i;
+ i.nodeId = n.id;
+ i.severity = IssueSeverity::Warn;
+ i.title = L"Sort spilled to disk (" + n.sortSpaceUsed + L")";
+ i.detail = L"work_mem was too small for the sort. Raising it for the session "
+ L"will keep the sort in memory.";
+ issues.push_back(i);
+ if (n.level == NodeLevel::Good) n.level = NodeLevel::Warn;
+ }
+
+ // ── Rule 3: Hash join with multiple batches.
+ if (n.kind == NodeKind::HashJoin && n.hashBatches > HASH_BATCH_THRESHOLD) {
+ Issue i;
+ i.nodeId = n.id;
+ i.severity = IssueSeverity::Warn;
+ i.title = L"Hash join spilled across " + std::to_wstring(n.hashBatches) + L" batches";
+ i.detail = L"The hash table didn't fit in work_mem. Larger work_mem prevents the spill.";
+ issues.push_back(i);
+ if (n.level == NodeLevel::Good) n.level = NodeLevel::Warn;
+ }
+
+ // ── Rule 4: Estimated vs. actual row mismatch — stale ANALYZE.
+ if (n.analyzed && n.planRows >= EST_MIN_ROWS_FOR_ALERT &&
+ n.actualRows >= EST_MIN_ROWS_FOR_ALERT)
+ {
+ double est = n.planRows;
+ double act = n.actualRows;
+ double factor = std::max(est, act) / std::max(1.0, std::min(est, act));
+ if (factor >= EST_VS_ACTUAL_FACTOR && !n.relation.empty()) {
+ Issue i;
+ i.nodeId = n.id;
+ i.severity = IssueSeverity::Warn;
+ std::wstringstream t;
+ t << L"Planner row estimate off by " << static_cast<int>(factor)
+ << L"× on " << n.relation;
+ i.title = t.str();
+ i.detail = L"Run ANALYZE to refresh table statistics — costing decisions "
+ L"depend on accurate row counts.";
+ issues.push_back(i);
+ // Keep tree pill consistent with InfoBar callout.
+ if (n.level == NodeLevel::Good) n.level = NodeLevel::Warn;
+ }
+ }
+
+ // ── Rule 5: Nested Loop with very large outer scan.
+ if (n.kind == NodeKind::NestedLoop && n.children.size() >= 2) {
+ double outerRows = n.children[0]->actualRows;
+ if (outerRows * n.actualLoops > NESTED_LOOP_ROW_FACTOR && n.actualTotal > 100) {
+ Issue i;
+ i.nodeId = n.id;
+ i.severity = IssueSeverity::Warn;
+ i.title = L"Nested Loop driving " + fmtRows(outerRows) + L" outer rows";
+ i.detail = L"For high outer counts a Hash Join or Merge Join is usually faster. "
+ L"Check that join columns are indexed and stats are fresh.";
+ issues.push_back(i);
+ if (n.level == NodeLevel::Good) n.level = NodeLevel::Warn;
+ }
+ }
+ });
+
+ // Stable order: Bad → Warn → Info, then plan order (already DFS).
+ std::stable_sort(issues.begin(), issues.end(),
+ [](const Issue& a, const Issue& b) {
+ return static_cast<int>(a.severity) > static_cast<int>(b.severity);
+ });
+ return issues;
+ }
+
+ std::vector<Recommendation> ExplainPlanHeuristics::recommend(
+ const PlanDocument& doc, const std::vector<Issue>& issues)
+ {
+ std::vector<Recommendation> recs;
+ if (!doc.root) return recs;
+
+ // Track which seq-scan tables we've already recommended an index
+ // for so we don't duplicate when there are multiple offending
+ // filters on the same relation.
+ std::vector<std::wstring> indexSuggested;
+
+ // Walk to find seq scans flagged Bad → suggest index. We pull the
+ // filter expression as-is; user reviews + edits the SQL preview.
+ std::function<void(const std::shared_ptr<PlanNode>&)> walk =
+ [&](const std::shared_ptr<PlanNode>& n) {
+ if (!n) return;
+ if (n->kind == NodeKind::SeqScan && n->level == NodeLevel::Bad &&
+ !n->relation.empty() && !n->filter.empty())
+ {
+ if (std::find(indexSuggested.begin(), indexSuggested.end(),
+ n->relation) == indexSuggested.end())
+ {
+ Recommendation r;
+ r.severity = IssueSeverity::Bad;
+ r.title = L"Create index on " + n->relation;
+ r.rationale = L"Eliminates the Seq Scan that filters out "
+ + fmtRows(n->rowsRemovedByFilter) + L" rows.";
+ // Best-effort SQL — extract the leftmost identifier
+ // from the filter as the candidate column.
+ std::wstring col;
+ for (auto c : n->filter) {
+ if (iswalnum(c) || c == L'_' || c == L'.') col += c;
+ else if (!col.empty()) break;
+ }
+ if (col.empty()) col = L"<column>";
+ r.previewSql = L"CREATE INDEX ON " + n->relation + L" (" + col + L");";
+ recs.push_back(r);
+ indexSuggested.push_back(n->relation);
+ }
+ }
+ for (auto& c : n->children) walk(c);
+ };
+ walk(doc.root);
+
+ // Spilling sort → raise work_mem.
+ bool sortSpilled = false;
+ bool hashSpilled = false;
+ std::function<void(const std::shared_ptr<PlanNode>&)> walk2 =
+ [&](const std::shared_ptr<PlanNode>& n) {
+ if (!n) return;
+ if (n->kind == NodeKind::Sort && n->sortSpaceType == L"Disk") sortSpilled = true;
+ if (n->kind == NodeKind::HashJoin && n->hashBatches > 1) hashSpilled = true;
+ for (auto& c : n->children) walk2(c);
+ };
+ walk2(doc.root);
+ if (sortSpilled || hashSpilled) {
+ Recommendation r;
+ r.severity = IssueSeverity::Warn;
+ r.title = L"Raise work_mem for this session";
+ r.rationale = sortSpilled
+ ? L"The sort spilled to disk — bigger work_mem keeps it in memory."
+ : L"The hash join spilled across batches — bigger work_mem prevents the spill.";
+ r.previewSql = L"SET LOCAL work_mem = '64MB';";
+ recs.push_back(r);
+ }
+
+ // ANALYZE recommendation: collect distinct relations from estimate-mismatch issues.
+ std::vector<std::wstring> staleRels;
+ for (const auto& i : issues) {
+ if (i.title.find(L"Planner row estimate off") != std::wstring::npos) {
+ // Pull relation off the title's last word — ugly but cheap;
+ // we can wire a structured field through later if needed.
+ auto pos = i.title.rfind(L' ');
+ if (pos != std::wstring::npos) {
+ auto rel = i.title.substr(pos + 1);
+ if (std::find(staleRels.begin(), staleRels.end(), rel) == staleRels.end())
+ staleRels.push_back(rel);
+ }
+ }
+ }
+ for (const auto& rel : staleRels) {
+ Recommendation r;
+ r.severity = IssueSeverity::Info;
+ r.title = L"Run ANALYZE " + rel;
+ r.rationale = L"Planner stats are stale — refresh row estimates.";
+ r.previewSql = L"ANALYZE " + rel + L";";
+ recs.push_back(r);
+ }
+
+ return recs;
+ }
+}
diff --git a/linux/src/Presentation/Views/ExplainVisualizer/ExplainPlanHeuristics.h b/linux/src/Presentation/Views/ExplainVisualizer/ExplainPlanHeuristics.h
new file mode 100644
index 0000000..a672861
--- /dev/null
+++ b/linux/src/Presentation/Views/ExplainVisualizer/ExplainPlanHeuristics.h
@@ -0,0 +1,50 @@
+#pragma once
+// Pure-function heuristics over a parsed PlanDocument. Two outputs:
+// • Warnings — short, single-issue callouts shown inline (the InfoBar)
+// and as `pill` badges on offending tree nodes.
+// • Recommendations — actionable suggestions surfaced in the bottom
+// "Recommendations" card (ANALYZE, raise work_mem, add index...).
+//
+// Rules are intentionally simple + transparent. We bias toward false
+// negatives (no nag) over false positives — every recommendation must
+// be a thing a senior DBA would also say after one glance at the plan.
+
+#include "ExplainPlanTypes.h"
+
+#include <string>
+#include <vector>
+
+namespace gridex::explainviz
+{
+ enum class IssueSeverity { Info, Warn, Bad };
+
+ struct Issue
+ {
+ std::wstring nodeId; // PlanNode.id this issue points at
+ std::wstring title; // short summary (used in InfoBar header)
+ std::wstring detail; // longer body
+ IssueSeverity severity = IssueSeverity::Warn;
+ };
+
+ struct Recommendation
+ {
+ std::wstring title; // bold lead, e.g. "Create index on admissions(admit_date)"
+ std::wstring rationale; // single-sentence justification
+ std::wstring previewSql; // SQL to copy/preview when user clicks
+ IssueSeverity severity = IssueSeverity::Warn;
+ };
+
+ class ExplainPlanHeuristics
+ {
+ public:
+ // Walks the plan and returns the issues found. Sets level=Bad on
+ // any node tagged with a Bad-severity issue (mutates in place so
+ // the tree's heat coloring matches the InfoBar).
+ static std::vector<Issue> analyze(PlanDocument& doc);
+
+ // Build recommendation cards from the same pass. Caller can run
+ // this after analyze() so the same data is reused.
+ static std::vector<Recommendation> recommend(const PlanDocument& doc,
+ const std::vector<Issue>& issues);
+ };
+}
diff --git a/linux/src/Presentation/Views/ExplainVisualizer/ExplainPlanParser.cpp b/linux/src/Presentation/Views/ExplainVisualizer/ExplainPlanParser.cpp
new file mode 100644
index 0000000..5e572ce
--- /dev/null
+++ b/linux/src/Presentation/Views/ExplainVisualizer/ExplainPlanParser.cpp
@@ -0,0 +1,477 @@
+#include "ExplainPlanParser.h"
+
+#include <cctype>
+#include <cwctype>
+#include <sstream>
+
+namespace gridex::explainviz
+{
+ // ── Mini wstring JSON tokenizer ───────────────────────────────
+ // Tiny scanner over wide chars — only what we need to walk arrays
+ // and objects in PG's EXPLAIN output. Whitespace tolerant; assumes
+ // valid UTF-16 produced by Postgres.
+ namespace
+ {
+ struct Reader
+ {
+ const wchar_t* p;
+ const wchar_t* end;
+
+ void skipWs()
+ {
+ while (p < end && std::iswspace(*p)) ++p;
+ }
+ bool eof() const { return p >= end; }
+ wchar_t peek() { skipWs(); return p < end ? *p : 0; }
+
+ bool match(wchar_t c)
+ {
+ skipWs();
+ if (p < end && *p == c) { ++p; return true; }
+ return false;
+ }
+
+ bool parseString(std::wstring& out)
+ {
+ skipWs();
+ if (p >= end || *p != L'"') return false;
+ ++p;
+ out.clear();
+ while (p < end && *p != L'"') {
+ if (*p == L'\\' && p + 1 < end) {
+ wchar_t n = p[1];
+ switch (n) {
+ case L'n': out += L'\n'; break;
+ case L't': out += L'\t'; break;
+ case L'r': out += L'\r'; break;
+ case L'"': out += L'"'; break;
+ case L'\\': out += L'\\'; break;
+ case L'/': out += L'/'; break;
+ case L'b': out += L'\b'; break;
+ case L'f': out += L'\f'; break;
+ case L'u': {
+ // \uXXXX consumes 6 chars (\, u, 4 hex). Guard
+ // against truncated escapes so we don't loop.
+ if (p + 6 <= end) {
+ wchar_t hex[5] = { p[2], p[3], p[4], p[5], 0 };
+ out += static_cast<wchar_t>(std::wcstoul(hex, nullptr, 16));
+ p += 6;
+ } else {
+ p = end;
+ }
+ continue; // skip the unified `p += 2` below
+ }
+ default: out += n; break;
+ }
+ p += 2;
+ } else {
+ out += *p; ++p;
+ }
+ }
+ if (p < end && *p == L'"') ++p;
+ return true;
+ }
+
+ // Hand-rolled JSON number parser. Locale-independent — unlike
+ // std::wcstod, which honors LC_NUMERIC and breaks on locales
+ // (e.g. vi_VN, de_DE) where the decimal separator is ',' not
+ // '.'. QApplication switches the process locale on startup,
+ // so the C-library parser misreads "0.00" as just "0" and the
+ // Plan tree falls apart mid-parse.
+ bool parseNumber(double& out)
+ {
+ skipWs();
+ const wchar_t* start = p;
+ bool neg = false;
+ if (p < end && *p == L'-') { neg = true; ++p; }
+ else if (p < end && *p == L'+') ++p;
+
+ bool seenDigit = false;
+ double intPart = 0.0;
+ while (p < end && *p >= L'0' && *p <= L'9') {
+ intPart = intPart * 10.0 + double(*p - L'0');
+ ++p; seenDigit = true;
+ }
+
+ double fracPart = 0.0;
+ double fracScale = 1.0;
+ if (p < end && *p == L'.') {
+ ++p;
+ while (p < end && *p >= L'0' && *p <= L'9') {
+ fracPart = fracPart * 10.0 + double(*p - L'0');
+ fracScale *= 10.0;
+ ++p; seenDigit = true;
+ }
+ }
+
+ int expSign = 1, expVal = 0;
+ if (p < end && (*p == L'e' || *p == L'E')) {
+ ++p;
+ if (p < end && *p == L'-') { expSign = -1; ++p; }
+ else if (p < end && *p == L'+') ++p;
+ while (p < end && *p >= L'0' && *p <= L'9') {
+ expVal = expVal * 10 + int(*p - L'0');
+ ++p;
+ }
+ }
+
+ if (!seenDigit) { p = start; return false; }
+ double v = intPart + fracPart / fracScale;
+ if (neg) v = -v;
+ if (expVal != 0) {
+ double m = 1.0;
+ for (int i = 0; i < expVal; ++i) m *= 10.0;
+ v = (expSign > 0) ? v * m : v / m;
+ }
+ out = v;
+ return true;
+ }
+
+ // Skip a value (object / array / string / number / bool / null)
+ // without parsing it — used for unknown keys.
+ bool skipValue()
+ {
+ skipWs();
+ if (p >= end) return false;
+ if (*p == L'"') { std::wstring tmp; return parseString(tmp); }
+ if (*p == L'{' || *p == L'[') {
+ wchar_t open = *p;
+ wchar_t close = (open == L'{') ? L'}' : L']';
+ int depth = 0; ++p;
+ bool inStr = false, esc = false;
+ while (p < end) {
+ wchar_t c = *p;
+ if (inStr) {
+ if (esc) esc = false;
+ else if (c == L'\\') esc = true;
+ else if (c == L'"') inStr = false;
+ } else {
+ if (c == L'"') inStr = true;
+ else if (c == open) ++depth;
+ else if (c == close) {
+ if (depth == 0) { ++p; return true; }
+ --depth;
+ }
+ }
+ ++p;
+ }
+ return false;
+ }
+ // bool / null / number — eat until comma or close.
+ while (p < end && *p != L',' && *p != L'}' && *p != L']') ++p;
+ return true;
+ }
+ };
+
+ // Forward decl
+ std::shared_ptr<PlanNode> parsePlanNode(Reader& r);
+
+ // Map the "Node Type" string from EXPLAIN to our enum.
+ NodeKind mapKind(const std::wstring& s)
+ {
+ if (s == L"Limit") return NodeKind::Limit;
+ if (s == L"Sort") return NodeKind::Sort;
+ if (s == L"Hash Join") return NodeKind::HashJoin;
+ if (s == L"Merge Join") return NodeKind::MergeJoin;
+ if (s == L"Nested Loop") return NodeKind::NestedLoop;
+ if (s == L"Seq Scan") return NodeKind::SeqScan;
+ if (s == L"Index Scan") return NodeKind::IndexScan;
+ if (s == L"Index Only Scan") return NodeKind::IndexOnlyScan;
+ if (s == L"Bitmap Heap Scan") return NodeKind::BitmapHeapScan;
+ if (s == L"Bitmap Index Scan") return NodeKind::BitmapIndexScan;
+ if (s == L"Hash") return NodeKind::Hash;
+ if (s == L"Aggregate") return NodeKind::Aggregate;
+ if (s == L"GroupAggregate") return NodeKind::GroupAggregate;
+ if (s == L"HashAggregate") return NodeKind::HashAggregate;
+ if (s == L"WindowAgg") return NodeKind::WindowAgg;
+ if (s == L"Materialize") return NodeKind::Materialize;
+ if (s == L"Gather") return NodeKind::Gather;
+ if (s == L"Gather Merge") return NodeKind::GatherMerge;
+ if (s == L"Append") return NodeKind::Append;
+ if (s == L"Result") return NodeKind::Result;
+ if (s == L"Subquery Scan") return NodeKind::SubqueryScan;
+ if (s == L"CTE Scan") return NodeKind::CteScan;
+ if (s == L"Unique") return NodeKind::Unique;
+ if (s == L"Memoize") return NodeKind::Memoize;
+ return NodeKind::Other;
+ }
+
+ // Build a one-liner detail string from a parsed node — what to show
+ // next to the op label in the tree. Mirrors the design's "detail"
+ // column without dumping every field.
+ std::wstring buildDetail(const PlanNode& n)
+ {
+ std::wstringstream ss;
+ bool first = true;
+ auto sep = [&]() { if (!first) ss << L" · "; first = false; };
+
+ if (!n.indexName.empty()) {
+ sep(); ss << L"using " << n.indexName;
+ }
+ if (!n.joinType.empty()) {
+ sep(); ss << n.joinType;
+ }
+ if (!n.strategy.empty()) {
+ sep(); ss << n.strategy;
+ }
+ if (!n.indexCond.empty()) {
+ sep(); ss << L"cond: " << n.indexCond;
+ }
+ if (!n.filter.empty()) {
+ sep(); ss << L"filter: " << n.filter;
+ }
+ if (!n.sortMethod.empty()) {
+ sep(); ss << n.sortMethod;
+ if (!n.sortSpaceUsed.empty())
+ ss << L" (" << n.sortSpaceUsed << L" " << n.sortSpaceType << L")";
+ }
+ if (n.hashBatches > 0 || !n.hashMemKb.empty()) {
+ sep();
+ if (n.hashBuckets > 0) ss << L"buckets " << n.hashBuckets;
+ if (n.hashBatches > 1) ss << L" batches " << n.hashBatches;
+ if (!n.hashMemKb.empty()) ss << L" mem " << n.hashMemKb << L" KB";
+ }
+ return ss.str();
+ }
+
+ // Walk a plan-object's keys filling our PlanNode. We skip unknown
+ // keys; PG occasionally adds new ones across versions and we don't
+ // want to fail because of them.
+ std::shared_ptr<PlanNode> parsePlanObject(Reader& r)
+ {
+ if (!r.match(L'{')) return nullptr;
+ auto node = std::make_shared<PlanNode>();
+ std::wstring schema, alias;
+
+ while (!r.eof()) {
+ r.skipWs();
+ if (r.match(L'}')) break;
+ std::wstring key;
+ if (!r.parseString(key)) return nullptr;
+ if (!r.match(L':')) return nullptr;
+ r.skipWs();
+
+ if (key == L"Node Type") {
+ r.parseString(node->op);
+ node->kind = mapKind(node->op);
+ }
+ else if (key == L"Relation Name") r.parseString(node->relation);
+ else if (key == L"Schema") r.parseString(schema);
+ else if (key == L"Alias") r.parseString(node->alias);
+ else if (key == L"Index Name") r.parseString(node->indexName);
+ else if (key == L"Index Cond") r.parseString(node->indexCond);
+ else if (key == L"Filter") r.parseString(node->filter);
+ else if (key == L"Sort Method") r.parseString(node->sortMethod);
+ else if (key == L"Sort Space Used") {
+ double v; if (r.parseNumber(v))
+ node->sortSpaceUsed = std::to_wstring(static_cast<int>(v)) + L" KB";
+ }
+ else if (key == L"Sort Space Type") r.parseString(node->sortSpaceType);
+ else if (key == L"Join Type") r.parseString(node->joinType);
+ else if (key == L"Strategy") r.parseString(node->strategy);
+ else if (key == L"Hash Buckets") {
+ double v; if (r.parseNumber(v)) node->hashBuckets = static_cast<int>(v);
+ }
+ else if (key == L"Hash Batches") {
+ double v; if (r.parseNumber(v)) node->hashBatches = static_cast<int>(v);
+ }
+ else if (key == L"Original Hash Batches") { double v; r.parseNumber(v); }
+ else if (key == L"Peak Memory Usage") {
+ double v; if (r.parseNumber(v)) node->hashMemKb = std::to_wstring(static_cast<int>(v));
+ }
+ else if (key == L"Startup Cost") r.parseNumber(node->startupCost);
+ else if (key == L"Total Cost") r.parseNumber(node->totalCost);
+ else if (key == L"Plan Rows") r.parseNumber(node->planRows);
+ else if (key == L"Plan Width") {
+ double v; if (r.parseNumber(v)) node->planWidth = static_cast<int>(v);
+ }
+ else if (key == L"Actual Startup Time") {
+ r.parseNumber(node->actualStartup);
+ node->analyzed = true;
+ }
+ else if (key == L"Actual Total Time") {
+ r.parseNumber(node->actualTotal);
+ node->analyzed = true;
+ }
+ else if (key == L"Actual Rows") r.parseNumber(node->actualRows);
+ else if (key == L"Actual Loops") {
+ double v; if (r.parseNumber(v)) node->actualLoops = static_cast<int>(v);
+ }
+ else if (key == L"Rows Removed by Filter") {
+ double v; if (r.parseNumber(v)) node->rowsRemovedByFilter = static_cast<int>(v);
+ }
+ else if (key == L"Rows Removed by Index Recheck") {
+ double v; if (r.parseNumber(v)) node->rowsRemovedByIndexRecheck = static_cast<int>(v);
+ }
+ else if (key == L"Shared Hit Blocks") {
+ double v; if (r.parseNumber(v)) node->sharedHit = static_cast<int64_t>(v);
+ }
+ else if (key == L"Shared Read Blocks") {
+ double v; if (r.parseNumber(v)) node->sharedRead = static_cast<int64_t>(v);
+ }
+ else if (key == L"Shared Dirtied Blocks") {
+ double v; if (r.parseNumber(v)) node->sharedDirtied = static_cast<int64_t>(v);
+ }
+ else if (key == L"Shared Written Blocks") {
+ double v; if (r.parseNumber(v)) node->sharedWritten = static_cast<int64_t>(v);
+ }
+ else if (key == L"Temp Read Blocks") {
+ double v; if (r.parseNumber(v)) node->tempRead = static_cast<int64_t>(v);
+ }
+ else if (key == L"Temp Written Blocks") {
+ double v; if (r.parseNumber(v)) node->tempWritten = static_cast<int64_t>(v);
+ }
+ else if (key == L"Output") {
+ // array of strings
+ if (r.match(L'[')) {
+ while (!r.eof()) {
+ r.skipWs();
+ if (r.match(L']')) break;
+ std::wstring col;
+ if (r.parseString(col)) node->outputCols.push_back(col);
+ r.skipWs(); r.match(L',');
+ }
+ } else {
+ r.skipValue();
+ }
+ }
+ else if (key == L"Plans") {
+ if (r.match(L'[')) {
+ while (!r.eof()) {
+ r.skipWs();
+ if (r.match(L']')) break;
+ auto child = parsePlanObject(r);
+ if (child) node->children.push_back(child);
+ r.skipWs(); r.match(L',');
+ }
+ } else {
+ r.skipValue();
+ }
+ }
+ else {
+ r.skipValue();
+ }
+
+ r.skipWs();
+ r.match(L',');
+ }
+
+ // Compose qualified relation name (schema.table).
+ if (!schema.empty() && !node->relation.empty()) {
+ node->relation = schema + L"." + node->relation;
+ }
+ // Detail composed last so all parts are available.
+ node->detail = buildDetail(*node);
+ return node;
+ }
+
+ std::shared_ptr<PlanNode> parsePlanNode(Reader& r)
+ {
+ return parsePlanObject(r);
+ }
+
+ // Generate ids by depth-first walk so siblings get distinct names.
+ void assignIds(PlanNode& n, int& counter)
+ {
+ n.id = L"n" + std::to_wstring(counter++);
+ for (auto& c : n.children) assignIds(*c, counter);
+ }
+
+ double sumSubtreeOwn(const PlanNode& n)
+ {
+ double total = (n.actualTotal * n.actualLoops);
+ // own = total - sum(children total). We compute own at parent
+ // level — nothing to do recursively here; classifyTimings does
+ // the second pass once we know the grand total.
+ return total;
+ }
+
+ void classifyTimings(PlanNode& n, double grandTotalMs)
+ {
+ double childrenTotal = 0.0;
+ for (auto& c : n.children) {
+ childrenTotal += c->actualTotal * c->actualLoops;
+ classifyTimings(*c, grandTotalMs);
+ }
+ n.ownMs = std::max(0.0, n.actualTotal * n.actualLoops - childrenTotal);
+ n.pctOfTotal = grandTotalMs > 0 ? (n.ownMs / grandTotalMs) * 100.0 : 0.0;
+
+ // Default heat classification — heuristics module may upgrade
+ // to Bad on issues even if the percentage is small.
+ if (n.pctOfTotal >= 25.0) n.level = NodeLevel::Bad;
+ else if (n.pctOfTotal >= 5.0) n.level = NodeLevel::Warn;
+ else n.level = NodeLevel::Good;
+
+ // Sort spilling to disk should always show as Warn at minimum.
+ if (n.sortSpaceType == L"Disk" && n.level == NodeLevel::Good)
+ n.level = NodeLevel::Warn;
+ }
+ } // anon namespace
+
+ void ExplainPlanParser::postProcess(PlanDocument& doc)
+ {
+ if (!doc.root) return;
+ int counter = 0;
+ assignIds(*doc.root, counter);
+ // Grand total = root's actualTotal*loops, fallback to summed if root
+ // wasn't analyzed (shouldn't happen with ANALYZE but defensive).
+ double total = doc.root->actualTotal * doc.root->actualLoops;
+ if (total <= 0.0) total = sumSubtreeOwn(*doc.root);
+ doc.executionMs = total;
+ classifyTimings(*doc.root, total);
+ }
+
+ bool ExplainPlanParser::parse(const std::wstring& json,
+ PlanDocument& out,
+ std::wstring& err)
+ {
+ if (json.empty()) { err = L"Empty plan JSON."; return false; }
+ out.rawJson = json;
+
+ Reader r{ json.c_str(), json.c_str() + json.size() };
+
+ // EXPLAIN FORMAT JSON returns a top-level array. Pop into the first
+ // element which is an object containing "Plan", "Planning Time" etc.
+ r.skipWs();
+ if (!r.match(L'[')) { err = L"Plan JSON must be an array."; return false; }
+ r.skipWs();
+ if (!r.match(L'{')) { err = L"Plan JSON missing root object."; return false; }
+
+ while (!r.eof()) {
+ r.skipWs();
+ if (r.match(L'}')) break;
+ std::wstring key;
+ if (!r.parseString(key)) { err = L"Bad key in plan."; return false; }
+ if (!r.match(L':')) { err = L"Missing ':' in plan."; return false; }
+ r.skipWs();
+ if (key == L"Plan") {
+ out.root = parsePlanObject(r);
+ }
+ else if (key == L"Planning Time") {
+ r.parseNumber(out.planningMs);
+ }
+ else if (key == L"Execution Time") {
+ r.parseNumber(out.executionMs);
+ }
+ else {
+ r.skipValue();
+ }
+ r.skipWs();
+ r.match(L',');
+ }
+
+ if (!out.root) { err = L"Plan JSON had no Plan object."; return false; }
+
+ out.analyzed = out.root->analyzed;
+ postProcess(out);
+
+ // executionMs from `Execution Time` (when present) takes priority
+ // — that's the wall-clock for the whole query, more accurate than
+ // root node totals on parallel plans.
+ // postProcess already used root total; if Execution Time is bigger
+ // (e.g., parallel workers), keep the root-derived sum for share %
+ // but expose Execution Time separately via planningMs/executionMs
+ // accessors. We accept the slight drift.
+ return true;
+ }
+}
diff --git a/linux/src/Presentation/Views/ExplainVisualizer/ExplainPlanParser.h b/linux/src/Presentation/Views/ExplainVisualizer/ExplainPlanParser.h
new file mode 100644
index 0000000..72fca66
--- /dev/null
+++ b/linux/src/Presentation/Views/ExplainVisualizer/ExplainPlanParser.h
@@ -0,0 +1,30 @@
+#pragma once
+// Parser for Postgres `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)` output.
+// We hand-roll a tiny JSON consumer (no nlohmann dependency to match the
+// rest of the codebase) — only the subset of PG's plan schema we
+// actually surface in the UI is read; unknown keys are skipped.
+
+#include "ExplainPlanTypes.h"
+
+#include <string>
+
+namespace gridex::explainviz
+{
+ class ExplainPlanParser
+ {
+ public:
+ // Parses the JSON string returned in the single text cell of an
+ // `EXPLAIN (FORMAT JSON)` query. Returns true on success and fills
+ // `out`. On failure returns false and writes a human-readable
+ // explanation into `err`.
+ static bool parse(const std::wstring& json,
+ PlanDocument& out,
+ std::wstring& err);
+
+ // Convenience: re-walk the doc and recompute derived values
+ // (NodeLevel, pctOfTotal, ownMs, generated ids). Called automatically
+ // at the end of `parse`; exposed for tests and re-classification
+ // after heuristics tweak any node-level fields.
+ static void postProcess(PlanDocument& doc);
+ };
+}
diff --git a/linux/src/Presentation/Views/ExplainVisualizer/ExplainPlanTypes.h b/linux/src/Presentation/Views/ExplainVisualizer/ExplainPlanTypes.h
new file mode 100644
index 0000000..96d02cc
--- /dev/null
+++ b/linux/src/Presentation/Views/ExplainVisualizer/ExplainPlanTypes.h
@@ -0,0 +1,125 @@
+#pragma once
+// Pure-C++ value types for the Explain Plan Visualizer. Mirrors the shape
+// returned by `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)` on Postgres so a
+// JSON node maps 1:1 onto a PlanNode in our tree.
+
+#include <cstdint>
+#include <memory>
+#include <string>
+#include <vector>
+
+namespace gridex::explainviz
+{
+ // Heuristic-derived severity used by the heat bar + node coloring.
+ enum class NodeLevel
+ {
+ Good, // <5% of total time, no warnings
+ Warn, // sort spill, partial spill, low-confidence stats
+ Bad // hot path: >25% of total time, or seq scan w/ heavy filter
+ };
+
+ // What kind of operation the node represents — drives the glyph and
+ // colored badge in the UI. Keep small + extend as needed.
+ enum class NodeKind
+ {
+ Other,
+ Limit,
+ Sort,
+ HashJoin,
+ MergeJoin,
+ NestedLoop,
+ SeqScan,
+ IndexScan,
+ IndexOnlyScan,
+ BitmapHeapScan,
+ BitmapIndexScan,
+ Hash,
+ Aggregate,
+ GroupAggregate,
+ HashAggregate,
+ WindowAgg,
+ Materialize,
+ Gather,
+ GatherMerge,
+ Append,
+ Result,
+ SubqueryScan,
+ CteScan,
+ Unique,
+ Memoize
+ };
+
+ struct PlanNode
+ {
+ std::wstring id; // generated, used for UI selection (e.g. "n0")
+ std::wstring op; // raw "Node Type" from EXPLAIN
+ NodeKind kind = NodeKind::Other;
+ std::wstring relation; // table name when applicable
+ std::wstring alias;
+ std::wstring detail; // human-readable extras (filter, sort key, join cond...)
+
+ // Cost numbers from the planner.
+ double startupCost = 0.0;
+ double totalCost = 0.0;
+ double planRows = 0.0;
+ int planWidth = 0;
+
+ // Actual measurements when ANALYZE was used.
+ bool analyzed = false;
+ double actualStartup = 0.0;
+ double actualTotal = 0.0; // ms per loop
+ double actualRows = 0.0;
+ int actualLoops = 1;
+ double pctOfTotal = 0.0; // own-time share of grand total ms
+ double ownMs = 0.0; // own-time = actualTotal*loops − Σ children own-time
+
+ // Buffer accounting (int64 — large plans can touch billions of blocks).
+ int64_t sharedHit = 0;
+ int64_t sharedRead = 0;
+ int64_t sharedDirtied = 0;
+ int64_t sharedWritten = 0;
+ int64_t tempRead = 0;
+ int64_t tempWritten = 0;
+
+ // Sort-specific
+ std::wstring sortMethod; // "external merge", "quicksort", ...
+ std::wstring sortSpaceUsed;
+ std::wstring sortSpaceType; // "Memory" or "Disk"
+
+ // Hash-specific
+ int hashBuckets = 0;
+ int hashBatches = 0;
+ std::wstring hashMemKb; // raw value, formatted later
+
+ // Index-specific
+ std::wstring indexName;
+ std::wstring indexCond;
+
+ // Filter accounting
+ std::wstring filter;
+ int rowsRemovedByFilter = 0;
+ int rowsRemovedByIndexRecheck = 0;
+ std::wstring joinType;
+ std::wstring strategy;
+
+ std::vector<std::wstring> outputCols;
+
+ NodeLevel level = NodeLevel::Good;
+
+ std::vector<std::shared_ptr<PlanNode>> children;
+ };
+
+ // Top-level container for one parsed EXPLAIN output.
+ struct PlanDocument
+ {
+ std::shared_ptr<PlanNode> root;
+ double planningMs = 0.0;
+ double executionMs = 0.0; // grand total ms (ANALYZE)
+ std::wstring rawJson; // kept so flyout / Copy plan works
+ std::wstring originalSql; // SQL that generated this plan
+ std::wstring databaseName;
+ std::wstring serverVersion;
+ bool analyzed = false;
+ bool buffers = false;
+ };
+}
diff --git a/linux/src/Presentation/Views/ExplainVisualizer/ExplainVisualizerWidget.cpp b/linux/src/Presentation/Views/ExplainVisualizer/ExplainVisualizerWidget.cpp
new file mode 100644
index 0000000..f2a03f9
--- /dev/null
+++ b/linux/src/Presentation/Views/ExplainVisualizer/ExplainVisualizerWidget.cpp
@@ -0,0 +1,693 @@
+#include "Presentation/Views/ExplainVisualizer/ExplainVisualizerWidget.h"
+#include "Presentation/Views/ExplainVisualizer/ExplainCards.h"
+#include "Presentation/Views/ExplainVisualizer/ExplainColors.h"
+#include "Presentation/Views/ExplainVisualizer/ExplainFormat.h"
+#include "Presentation/Views/ExplainVisualizer/PlanNodeRow.h"
+
+#include <QCheckBox>
+#include <QGridLayout>
+#include <QHBoxLayout>
+#include <QLabel>
+#include <QPushButton>
+#include <QScrollArea>
+#include <QStackedWidget>
+#include <QVBoxLayout>
+
+#include <algorithm>
+#include <cmath>
+#include <functional>
+#include <utility>
+#include <vector>
+
+namespace gridex::explain {
+
+namespace {
+using namespace ::gridex::explainviz;
+
+// Walk plan tree.
+template <typename Fn>
+void walkPlan(const std::shared_ptr<PlanNode>& n, Fn&& fn) {
+ if (!n) return;
+ fn(*n);
+ for (const auto& c : n->children) walkPlan(c, fn);
+}
+
+bool hasHotDescendant(const std::shared_ptr<PlanNode>& n) {
+ if (!n) return false;
+ if (n->level != NodeLevel::Good) return true;
+ for (const auto& c : n->children)
+ if (hasHotDescendant(c)) return true;
+ return false;
+}
+
+NodeLevel toneFromMs(double ms) {
+ if (ms > 1000.0) return NodeLevel::Bad;
+ if (ms > 250.0) return NodeLevel::Warn;
+ return NodeLevel::Good;
+}
+
+NodeLevel toneFromFactor(double f) {
+ if (f >= 5.0) return NodeLevel::Bad;
+ if (f >= 2.0) return NodeLevel::Warn;
+ return NodeLevel::Good;
+}
+
+} // namespace
+
+ExplainVisualizerWidget::ExplainVisualizerWidget(QWidget* parent) : QWidget(parent) {
+ buildUi();
+ showEmpty();
+}
+
+// ── State scaffolding ────────────────────────────────────────────────
+void ExplainVisualizerWidget::buildUi() {
+ auto* root = new QVBoxLayout(this);
+ root->setContentsMargins(0, 0, 0, 0);
+ stack_ = new QStackedWidget(this);
+ stack_->addWidget(buildEmptyState()); // 0
+ stack_->addWidget(buildLoadingState()); // 1
+ stack_->addWidget(buildErrorState()); // 2
+ stack_->addWidget(buildLoadedState()); // 3
+ root->addWidget(stack_);
+}
+
+QWidget* ExplainVisualizerWidget::buildEmptyState() {
+ auto* w = new QWidget();
+ auto* outer = new QVBoxLayout(w);
+ outer->addStretch(1);
+ auto* inner = new QVBoxLayout();
+ inner->setSpacing(12);
+ inner->setAlignment(Qt::AlignCenter);
+
+ auto* glyph = new QLabel(QStringLiteral("📊"), w);
+ auto gf = glyph->font(); gf.setPointSize(gf.pointSize() + 14); glyph->setFont(gf);
+ glyph->setAlignment(Qt::AlignCenter);
+
+ auto* title = new QLabel(tr("Visualize execution plan"), w);
+ auto tf = title->font(); tf.setPointSize(tf.pointSize() + 4); tf.setBold(true); title->setFont(tf);
+ title->setAlignment(Qt::AlignCenter);
+
+ auto* body = new QLabel(
+ tr("Run your query with EXPLAIN ANALYZE and we'll render the plan tree, hot paths, and tuning recommendations."), w);
+ body->setWordWrap(true);
+ body->setAlignment(Qt::AlignCenter);
+ body->setMaximumWidth(520);
+ body->setStyleSheet(mutedTextCss());
+
+ auto* runBtn = new QPushButton(tr("▶ Run with Explain Analyze"), w);
+ connect(runBtn, &QPushButton::clicked, this, &ExplainVisualizerWidget::runRequested);
+
+ auto* hint = new QLabel(tr("Postgres only — MySQL coming soon."), w);
+ hint->setAlignment(Qt::AlignCenter);
+ hint->setStyleSheet(mutedTextCss());
+
+ inner->addWidget(glyph);
+ inner->addWidget(title);
+ inner->addWidget(body);
+ inner->addWidget(runBtn, 0, Qt::AlignCenter);
+ inner->addWidget(hint);
+ outer->addLayout(inner);
+ outer->addStretch(1);
+ return w;
+}
+
+QWidget* ExplainVisualizerWidget::buildLoadingState() {
+ auto* w = new QWidget();
+ auto* lay = new QVBoxLayout(w);
+ lay->setAlignment(Qt::AlignCenter);
+ loadingLbl_ = new QLabel(tr("Running EXPLAIN ANALYZE…"), w);
+ auto f = loadingLbl_->font(); f.setPointSize(f.pointSize() + 1); loadingLbl_->setFont(f);
+ loadingLbl_->setStyleSheet(mutedTextCss());
+ loadingLbl_->setAlignment(Qt::AlignCenter);
+ lay->addWidget(loadingLbl_);
+ return w;
+}
+
+QWidget* ExplainVisualizerWidget::buildErrorState() {
+ auto* w = new QWidget();
+ auto* outer = new QVBoxLayout(w);
+ outer->addStretch(1);
+ auto* inner = new QVBoxLayout();
+ inner->setAlignment(Qt::AlignCenter);
+ inner->setSpacing(10);
+
+ auto* glyph = new QLabel(QStringLiteral("⚠"), w);
+ auto gf = glyph->font(); gf.setPointSize(gf.pointSize() + 10); glyph->setFont(gf);
+ glyph->setAlignment(Qt::AlignCenter);
+ glyph->setStyleSheet(QStringLiteral("color: %1;")
+ .arg(heatColor(::gridex::explainviz::NodeLevel::Bad).name()));
+
+ auto* title = new QLabel(tr("Couldn't run EXPLAIN ANALYZE"), w);
+ auto tf = title->font(); tf.setBold(true); tf.setPointSize(tf.pointSize() + 2); title->setFont(tf);
+ title->setAlignment(Qt::AlignCenter);
+
+ errorLbl_ = new QLabel(w);
+ errorLbl_->setWordWrap(true);
+ errorLbl_->setAlignment(Qt::AlignCenter);
+ errorLbl_->setMaximumWidth(520);
+ errorLbl_->setStyleSheet(mutedTextCss());
+
+ auto* tryBtn = new QPushButton(tr("Try again"), w);
+ connect(tryBtn, &QPushButton::clicked, this, &ExplainVisualizerWidget::runRequested);
+
+ inner->addWidget(glyph);
+ inner->addWidget(title);
+ inner->addWidget(errorLbl_);
+ inner->addWidget(tryBtn, 0, Qt::AlignCenter);
+ outer->addLayout(inner);
+ outer->addStretch(1);
+ return w;
+}
+
+QWidget* ExplainVisualizerWidget::buildLoadedState() {
+ auto* scroll = new QScrollArea();
+ scroll->setWidgetResizable(true);
+ scroll->setFrameShape(QFrame::NoFrame);
+ auto* body = new QWidget();
+ auto* lay = new QVBoxLayout(body);
+ lay->setContentsMargins(20, 16, 20, 28);
+ lay->setSpacing(18);
+
+ // Toolbar.
+ {
+ auto* row = new QHBoxLayout();
+ row->setSpacing(8);
+ auto* rerunBtn = new QPushButton(tr("⟳ Re-run"), body);
+ connect(rerunBtn, &QPushButton::clicked, this, &ExplainVisualizerWidget::runRequested);
+ auto* copyBtn = new QPushButton(tr("⧉ Copy plan"), body);
+ connect(copyBtn, &QPushButton::clicked, this, [this]() {
+ if (doc_) emit copyPlanRequested(toQ(doc_->rawJson));
+ });
+ metaLbl_ = new QLabel(body);
+ metaLbl_->setStyleSheet(mutedTextCss());
+ row->addWidget(rerunBtn);
+ row->addWidget(copyBtn);
+ row->addSpacing(8);
+ row->addWidget(metaLbl_, 1);
+ lay->addLayout(row);
+ }
+
+ // InfoBar.
+ infoBar_ = new InfoBarLite(body);
+ lay->addWidget(infoBar_);
+
+ // Metrics row.
+ metricsCard_ = new QFrame(body);
+ metricsLay_ = new QVBoxLayout(metricsCard_);
+ metricsLay_->setContentsMargins(0, 0, 0, 0);
+ lay->addWidget(metricsCard_);
+
+ // Plan section header.
+ {
+ auto* row = new QHBoxLayout();
+ auto* title = new QLabel(tr("Execution plan"), body);
+ auto tf = title->font(); tf.setBold(true); tf.setPointSize(tf.pointSize() + 2); title->setFont(tf);
+ planCountLbl_ = new QLabel(body);
+ planCountLbl_->setStyleSheet(mutedTextCss());
+ hotOnlyChk_ = new QCheckBox(tr("Show only hot"), body);
+ connect(hotOnlyChk_, &QCheckBox::toggled, this, [this](bool) { renderPlanTree(); });
+ row->addWidget(title);
+ row->addSpacing(12);
+ row->addWidget(planCountLbl_);
+ row->addStretch(1);
+ row->addWidget(hotOnlyChk_);
+ lay->addLayout(row);
+ }
+
+ // Plan tree + flyout (two cols).
+ {
+ auto* row = new QHBoxLayout();
+ row->setSpacing(12);
+ treeCard_ = new QFrame(body);
+ treeCard_->setFrameShape(QFrame::StyledPanel);
+ treeCard_->setStyleSheet(QStringLiteral(
+ "QFrame { %1 %2 border-radius: 8px; }")
+ .arg(cardBgCss(), cardBorderCss()));
+ treeLay_ = new QVBoxLayout(treeCard_);
+ treeLay_->setContentsMargins(6, 8, 6, 8);
+ treeLay_->setSpacing(2);
+
+ flyoutCard_ = new QFrame(body);
+ flyoutCard_->setFrameShape(QFrame::StyledPanel);
+ flyoutCard_->setFixedWidth(340);
+ flyoutCard_->setStyleSheet(QStringLiteral(
+ "QFrame { %1 %2 border-radius: 8px; }")
+ .arg(cardBgCss(), cardBorderCss()));
+ flyoutLay_ = new QVBoxLayout(flyoutCard_);
+ flyoutLay_->setContentsMargins(14, 12, 14, 12);
+ flyoutLay_->setSpacing(8);
+
+ row->addWidget(treeCard_, 1);
+ row->addWidget(flyoutCard_);
+ lay->addLayout(row);
+ }
+
+ // Waterfall.
+ {
+ auto* title = new QLabel(tr("Timing waterfall"), body);
+ auto tf = title->font(); tf.setBold(true); tf.setPointSize(tf.pointSize() + 2); title->setFont(tf);
+ auto* hint = new QLabel(tr("Actual time per node, in execution order."), body);
+ hint->setStyleSheet(mutedTextCss());
+ auto* card = new QFrame(body);
+ card->setFrameShape(QFrame::StyledPanel);
+ card->setStyleSheet(QStringLiteral(
+ "QFrame { %1 %2 border-radius: 8px; }")
+ .arg(cardBgCss(), cardBorderCss()));
+ waterfallLay_ = new QVBoxLayout(card);
+ waterfallLay_->setContentsMargins(12, 12, 12, 12);
+ waterfallLay_->setSpacing(4);
+ lay->addWidget(title);
+ lay->addWidget(hint);
+ lay->addWidget(card);
+ }
+
+ // Recommendations.
+ {
+ auto* title = new QLabel(tr("Recommendations"), body);
+ auto tf = title->font(); tf.setBold(true); tf.setPointSize(tf.pointSize() + 2); title->setFont(tf);
+ auto* hint = new QLabel(
+ tr("Suggestions are derived from the plan above. Click Preview to copy the SQL."), body);
+ hint->setStyleSheet(mutedTextCss());
+ auto* host = new QWidget(body);
+ recsLay_ = new QVBoxLayout(host);
+ recsLay_->setContentsMargins(0, 0, 0, 0);
+ recsLay_->setSpacing(8);
+ lay->addWidget(title);
+ lay->addWidget(hint);
+ lay->addWidget(host);
+ }
+
+ scroll->setWidget(body);
+ return scroll;
+}
+
+// ── Public API ────────────────────────────────────────────────────────
+void ExplainVisualizerWidget::showEmpty() { stack_->setCurrentIndex(0); }
+
+void ExplainVisualizerWidget::showLoading(const QString& text) {
+ if (loadingLbl_ && !text.isEmpty()) loadingLbl_->setText(text);
+ stack_->setCurrentIndex(1);
+}
+
+void ExplainVisualizerWidget::showError(const QString& message) {
+ if (errorLbl_) errorLbl_->setText(message);
+ stack_->setCurrentIndex(2);
+}
+
+void ExplainVisualizerWidget::setPlan(std::shared_ptr<::gridex::explainviz::PlanDocument> doc) {
+ doc_ = std::move(doc);
+ issues_.clear();
+ recs_.clear();
+ selectedNodeId_.clear();
+ if (doc_) {
+ issues_ = ::gridex::explainviz::ExplainPlanHeuristics::analyze(*doc_);
+ recs_ = ::gridex::explainviz::ExplainPlanHeuristics::recommend(*doc_, issues_);
+ }
+ renderInfoBar();
+ renderMetrics();
+ renderPlanTree();
+ renderFlyout();
+ renderWaterfall();
+ renderRecs();
+
+ if (doc_ && metaLbl_) {
+ metaLbl_->setText(
+ tr("Postgres · execution %1 ms · planning %2 ms")
+ .arg(fmtMs(doc_->executionMs))
+ .arg(fmtMs(doc_->planningMs)));
+ }
+ stack_->setCurrentIndex(3);
+}
+
+// ── Render passes ────────────────────────────────────────────────────
+void ExplainVisualizerWidget::clearLayout(QVBoxLayout* lay) {
+ if (!lay) return;
+ while (auto* item = lay->takeAt(0)) {
+ if (auto* w = item->widget()) w->deleteLater();
+ delete item;
+ }
+}
+
+void ExplainVisualizerWidget::renderInfoBar() {
+ if (!infoBar_) return;
+ if (issues_.empty()) { infoBar_->clear(); return; }
+ // Pick the most severe issue for the InfoBar.
+ const auto* pick = &issues_.front();
+ for (const auto& i : issues_)
+ if (int(i.severity) > int(pick->severity)) pick = &i;
+ infoBar_->setMessage(toQ(pick->title), toQ(pick->detail), pick->severity);
+}
+
+void ExplainVisualizerWidget::renderMetrics() {
+ clearLayout(metricsLay_);
+ if (!doc_ || !doc_->root) return;
+ using namespace ::gridex::explainviz;
+
+ const double total = doc_->executionMs > 0 ? doc_->executionMs : 0.0;
+ const double planning = doc_->planningMs;
+
+ // ── Total time ───────────────────────────────
+ const NodeLevel timeTone = toneFromMs(total);
+ QString timeDelta = planning > 0
+ ? tr("planning %1 ms · execution %2 ms").arg(fmtMs(planning), fmtMs(total))
+ : tr("execution %1 ms").arg(fmtMs(total));
+
+ // ── Rows ─────────────────────────────────────
+ double rowsActual = doc_->root->actualRows;
+ double rowsScanned = 0.0;
+ walkPlan(doc_->root, [&](const PlanNode& n) {
+ if (n.kind == NodeKind::SeqScan || n.kind == NodeKind::IndexScan ||
+ n.kind == NodeKind::IndexOnlyScan || n.kind == NodeKind::BitmapHeapScan)
+ rowsScanned += n.actualRows + n.rowsRemovedByFilter;
+ });
+ QString rowsUnit = rowsScanned > 0
+ ? tr(" / %1 scanned").arg(fmtNum(rowsScanned)) : QString();
+ QString rowsDelta = rowsScanned > 0
+ ? tr("selectivity %1%").arg(fmtMs(rowsActual / rowsScanned * 100)) : QString();
+ double rowsBar = rowsScanned > 0
+ ? std::min(1.0, rowsActual / rowsScanned) : 0.0;
+
+ // ── Buffers ──────────────────────────────────
+ quint64 totalHit = 0, totalRead = 0;
+ walkPlan(doc_->root, [&](const PlanNode& n) {
+ totalHit += n.sharedHit;
+ totalRead += n.sharedRead;
+ });
+ quint64 bufBytes = (totalHit + totalRead) * 8ULL * 1024; // 8KB pages
+ QString bufDelta = tr("%1 hit · %2 read").arg(totalHit).arg(totalRead);
+ NodeLevel bufTone = totalRead > 1000 ? NodeLevel::Warn : NodeLevel::Good;
+ double bufBar = totalRead > 1000 ? 0.7 : 0.3;
+
+ // ── Accuracy (worst-case est/actual ratio) ──
+ double worst = 1.0;
+ walkPlan(doc_->root, [&](const PlanNode& n) {
+ if (n.planRows >= 100 && n.actualRows >= 100) {
+ double f = std::max(n.planRows, n.actualRows) /
+ std::max(1.0, std::min(n.planRows, n.actualRows));
+ if (f > worst) worst = f;
+ }
+ });
+ NodeLevel accTone = toneFromFactor(worst);
+ QString accDelta = tr("%1× worst-case error").arg(QString::number(worst, 'f', 1));
+ double accBar = std::min(1.0, (worst - 1) / 5.0);
+
+ // Build the 4 cards in a row.
+ auto* host = new QWidget(metricsCard_);
+ auto* row = new QHBoxLayout(host);
+ row->setSpacing(8);
+ row->setContentsMargins(0, 0, 0, 0);
+ row->addWidget(new MetricCard(
+ QStringLiteral("⏱"), tr("Total time"), fmtMs(total), QStringLiteral("ms"),
+ timeDelta, std::min(1.0, total / 1000.0 * 0.5), timeTone));
+ row->addWidget(new MetricCard(
+ QStringLiteral("≡"), tr("Rows returned"), fmtNum(rowsActual), rowsUnit,
+ rowsDelta, rowsBar, NodeLevel::Good));
+ row->addWidget(new MetricCard(
+ QStringLiteral("▢"), tr("Buffers"), fmtBytes(bufBytes), QString(),
+ bufDelta, bufBar, bufTone));
+ row->addWidget(new MetricCard(
+ QStringLiteral("◎"), tr("Planner accuracy"),
+ QString::number(worst, 'f', 1), QStringLiteral("×"),
+ accDelta, accBar, accTone));
+ metricsLay_->addWidget(host);
+}
+
+void ExplainVisualizerWidget::buildNodeRowRecursive(
+ const std::shared_ptr<::gridex::explainviz::PlanNode>& node,
+ int depth)
+{
+ if (!node) return;
+ using L = ::gridex::explainviz::NodeLevel;
+ bool hotOnly = hotOnlyChk_ && hotOnlyChk_->isChecked();
+ // Keep nodes that are hot themselves OR have hot descendants (matches Win).
+ bool render = !hotOnly || node->level != L::Good || hasHotDescendant(node);
+ if (render) {
+ auto* row = new PlanNodeRow(node, depth, treeCard_);
+ connect(row, &PlanNodeRow::clicked, this, &ExplainVisualizerWidget::selectNode);
+ treeLay_->addWidget(row);
+ treeRows_.push_back(row);
+ }
+ for (const auto& c : node->children) buildNodeRowRecursive(c, depth + 1);
+}
+
+void ExplainVisualizerWidget::renderPlanTree() {
+ clearLayout(treeLay_);
+ treeRows_.clear();
+ if (!doc_ || !doc_->root) return;
+
+ int count = 0;
+ walkPlan(doc_->root, [&](const ::gridex::explainviz::PlanNode&) { ++count; });
+ if (planCountLbl_) {
+ planCountLbl_->setText(tr("%1 nodes · planner cost %2")
+ .arg(count).arg(fmtMs(doc_->root->totalCost)));
+ }
+
+ buildNodeRowRecursive(doc_->root, 0);
+ treeLay_->addStretch(1);
+
+ if (!doc_->root->id.empty()) selectNode(toQ(doc_->root->id));
+}
+
+void ExplainVisualizerWidget::renderFlyout() {
+ clearLayout(flyoutLay_);
+ if (!doc_) return;
+ using namespace ::gridex::explainviz;
+ std::function<std::shared_ptr<PlanNode>(const std::shared_ptr<PlanNode>&)> find =
+ [&](const std::shared_ptr<PlanNode>& n) -> std::shared_ptr<PlanNode> {
+ if (!n) return nullptr;
+ if (toQ(n->id) == selectedNodeId_) return n;
+ for (const auto& c : n->children) if (auto m = find(c)) return m;
+ return nullptr;
+ };
+ auto sel = find(doc_->root);
+ if (!sel) sel = doc_->root;
+ if (!sel) {
+ auto* hint = new QLabel(tr("Click a node to inspect."), flyoutCard_);
+ hint->setStyleSheet(mutedTextCss());
+ hint->setWordWrap(true);
+ flyoutLay_->addWidget(hint);
+ return;
+ }
+
+ // Header: glyph badge (42×36) + title + detail.
+ auto* head = new QHBoxLayout();
+ head->setSpacing(10);
+ auto* glyph = new QLabel(kindGlyph(sel->kind), flyoutCard_);
+ glyph->setFixedSize(42, 36);
+ glyph->setAlignment(Qt::AlignCenter);
+ { auto gf = glyph->font(); gf.setBold(true); gf.setPointSize(gf.pointSize() + 4); glyph->setFont(gf); }
+ glyph->setStyleSheet(QStringLiteral(
+ "background: %1; color: %2; border-radius: 7px;")
+ .arg(heatBgRgba(sel->level, 64), heatColor(sel->level).name()));
+ auto* htext = new QVBoxLayout();
+ htext->setSpacing(0);
+ QString title = toQ(sel->op);
+ if (!sel->relation.empty()) title += QStringLiteral(" · ") + toQ(sel->relation);
+ auto* titleLbl = new QLabel(title, flyoutCard_);
+ auto tf = titleLbl->font(); tf.setBold(true); tf.setPointSize(tf.pointSize() + 2); titleLbl->setFont(tf);
+ htext->addWidget(titleLbl);
+ if (!sel->detail.empty()) {
+ auto* det = new QLabel(toQ(sel->detail), flyoutCard_);
+ det->setStyleSheet(mutedTextCss());
+ det->setWordWrap(true);
+ htext->addWidget(det);
+ }
+ head->addWidget(glyph, 0, Qt::AlignTop);
+ head->addLayout(htext, 1);
+ auto* headHost = new QWidget(flyoutCard_);
+ headHost->setLayout(head);
+ flyoutLay_->addWidget(headHost);
+
+ // Section helper.
+ auto addSection = [&](const QString& title,
+ const std::vector<std::pair<QString, QString>>& kv) {
+ auto* s = new QWidget(flyoutCard_);
+ auto* sl = new QVBoxLayout(s);
+ sl->setContentsMargins(0, 8, 0, 0);
+ sl->setSpacing(2);
+ auto* t = new QLabel(title.toUpper(), s);
+ auto tff = t->font(); tff.setBold(true); tff.setPointSize(qMax(8, tff.pointSize() - 2)); t->setFont(tff);
+ t->setStyleSheet(mutedTextCss() + QStringLiteral(" letter-spacing: 1px;"));
+ sl->addWidget(t);
+ for (const auto& [k, v] : kv) {
+ auto* row = new QHBoxLayout();
+ row->setContentsMargins(0, 2, 0, 2);
+ row->setSpacing(8);
+ auto* kl = new QLabel(k, s);
+ kl->setStyleSheet(mutedTextCss());
+ kl->setFixedWidth(120);
+ auto* vl = new QLabel(v, s);
+ vl->setWordWrap(true);
+ row->addWidget(kl);
+ row->addWidget(vl, 1);
+ sl->addLayout(row);
+ }
+ flyoutLay_->addWidget(s);
+ };
+
+ // TIMING
+ addSection(tr("Timing"), {
+ { tr("Startup cost"), fmtMs(sel->startupCost) },
+ { tr("Total cost"), fmtMs(sel->totalCost) },
+ { tr("Actual time"), fmtMs(sel->actualTotal) + QStringLiteral(" ms") },
+ { tr("Loops"), QString::number(sel->actualLoops) },
+ { tr("% of total"), QStringLiteral("%1%").arg(sel->pctOfTotal, 0, 'f', 1) },
+ });
+
+ // ROWS
+ QString estErr = QStringLiteral("—");
+ if (sel->planRows >= 1 && sel->actualRows >= 1) {
+ double f = std::max(sel->planRows, sel->actualRows) /
+ std::max(1.0, std::min(sel->planRows, sel->actualRows));
+ estErr = QStringLiteral("%1× %2")
+ .arg(QString::number(f, 'f', 1),
+ sel->actualRows > sel->planRows ? tr("under") : tr("over"));
+ }
+ addSection(tr("Rows"), {
+ { tr("Estimated"), fmtNum(sel->planRows) },
+ { tr("Actual"), fmtNum(sel->actualRows) },
+ { tr("Estimation error"), estErr },
+ { tr("Rows removed"), fmtNum(sel->rowsRemovedByFilter) },
+ { tr("Width"), QString::number(sel->planWidth) + QStringLiteral(" bytes") },
+ });
+
+ // BUFFERS — only if non-zero.
+ if (sel->sharedHit > 0 || sel->sharedRead > 0 || sel->tempRead > 0 || sel->tempWritten > 0) {
+ addSection(tr("Buffers"), {
+ { tr("Shared hit"), fmtNum(sel->sharedHit) + QStringLiteral(" blocks") },
+ { tr("Shared read"), fmtNum(sel->sharedRead) + QStringLiteral(" blocks") },
+ { tr("Shared dirtied"), fmtNum(sel->sharedDirtied) },
+ { tr("Temp read"), fmtNum(sel->tempRead) },
+ { tr("Temp written"),fmtNum(sel->tempWritten) },
+ });
+ }
+
+ // OUTPUT — chips.
+ if (!sel->outputCols.empty()) {
+ auto* s = new QWidget(flyoutCard_);
+ auto* sl = new QVBoxLayout(s);
+ sl->setContentsMargins(0, 8, 0, 0);
+ sl->setSpacing(4);
+ auto* t = new QLabel(tr("OUTPUT"), s);
+ auto tff = t->font(); tff.setBold(true); tff.setPointSize(qMax(8, tff.pointSize() - 2)); t->setFont(tff);
+ t->setStyleSheet(mutedTextCss() + QStringLiteral(" letter-spacing: 1px;"));
+ sl->addWidget(t);
+ // Chips in a wrapping row via QGridLayout.
+ auto* chipHost = new QWidget(s);
+ auto* fl = new QGridLayout(chipHost);
+ fl->setContentsMargins(0, 0, 0, 0);
+ fl->setHorizontalSpacing(4);
+ fl->setVerticalSpacing(4);
+ const size_t cap = std::min<size_t>(sel->outputCols.size(), 12);
+ for (size_t i = 0; i < cap; ++i) {
+ auto* chip = new QLabel(toQ(sel->outputCols[i]), chipHost);
+ chip->setContentsMargins(6, 2, 6, 2);
+ auto cf = chip->font(); cf.setPointSize(qMax(8, cf.pointSize() - 2)); chip->setFont(cf);
+ chip->setStyleSheet(QStringLiteral(
+ "background: %1; border-radius: 8px; color: %2;")
+ .arg(isDarkPalette() ? QStringLiteral("rgba(255,255,255,0.08)")
+ : QStringLiteral("rgba(0,0,0,0.05)"),
+ isDarkPalette() ? QStringLiteral("#cdd6f4") : QStringLiteral("#3c3c3c")));
+ fl->addWidget(chip, int(i / 3), int(i % 3));
+ }
+ sl->addWidget(chipHost);
+ flyoutLay_->addWidget(s);
+ }
+
+ flyoutLay_->addStretch(1);
+}
+
+void ExplainVisualizerWidget::renderWaterfall() {
+ clearLayout(waterfallLay_);
+ if (!doc_ || !doc_->root) return;
+ using namespace ::gridex::explainviz;
+
+ // Build steps in execution order: post-order DFS, children before parents.
+ // Each step gets cumulative start = sum of preceding step durations.
+ struct Step {
+ QString label;
+ QString glyph;
+ double startMs;
+ double durMs;
+ NodeLevel level;
+ };
+ std::vector<Step> seq;
+ double cursor = 0.0;
+ std::function<double(const std::shared_ptr<PlanNode>&)> visit =
+ [&](const std::shared_ptr<PlanNode>& n) -> double {
+ if (!n) return 0.0;
+ double childrenSum = 0.0;
+ for (const auto& c : n->children) {
+ visit(c);
+ if (c) childrenSum += c->actualTotal * c->actualLoops;
+ }
+ double dur = std::max(0.0, n->actualTotal * n->actualLoops - childrenSum);
+ QString label = toQ(n->op);
+ if (!n->relation.empty()) label += QStringLiteral(" · ") + toQ(n->relation);
+ seq.push_back({ label, kindGlyph(n->kind), cursor, dur, n->level });
+ cursor += dur;
+ return dur;
+ };
+ visit(doc_->root);
+
+ const double maxMs = std::max(1.0, doc_->executionMs > 0 ? doc_->executionMs : cursor);
+
+ // Axis row: 220px "Node" | star (5 tick labels) | 70px "Duration".
+ {
+ auto* row = new QWidget();
+ auto* lay = new QHBoxLayout(row);
+ lay->setContentsMargins(0, 0, 0, 4);
+ lay->setSpacing(0);
+ auto* nlbl = new QLabel(tr("Node"));
+ nlbl->setFixedWidth(220);
+ nlbl->setStyleSheet(mutedTextCss());
+ lay->addWidget(nlbl);
+ auto* tickHost = new QWidget();
+ auto* tickLay = new QHBoxLayout(tickHost);
+ tickLay->setContentsMargins(0, 0, 0, 0);
+ tickLay->setSpacing(0);
+ for (int i = 0; i <= 4; ++i) {
+ auto* t = new QLabel(QStringLiteral("%1 ms").arg(fmtMs(maxMs * i / 4)));
+ t->setStyleSheet(mutedTextCss());
+ if (i == 0) t->setAlignment(Qt::AlignLeft);
+ else if (i == 4) t->setAlignment(Qt::AlignRight);
+ else t->setAlignment(Qt::AlignCenter);
+ tickLay->addWidget(t, 1);
+ }
+ lay->addWidget(tickHost, 1);
+ auto* dlbl = new QLabel(tr("Duration"));
+ dlbl->setFixedWidth(70);
+ dlbl->setAlignment(Qt::AlignRight);
+ dlbl->setStyleSheet(mutedTextCss());
+ lay->addWidget(dlbl);
+ waterfallLay_->addWidget(row);
+ }
+
+ for (const auto& s : seq) {
+ waterfallLay_->addWidget(new WaterfallRow(
+ s.glyph, s.label, s.startMs, s.durMs, maxMs, s.level));
+ }
+}
+
+void ExplainVisualizerWidget::renderRecs() {
+ clearLayout(recsLay_);
+ if (recs_.empty()) {
+ auto* hint = new QLabel(tr("No tuning suggestions — the planner looks healthy."));
+ hint->setStyleSheet(mutedTextCss());
+ recsLay_->addWidget(hint);
+ return;
+ }
+ for (const auto& r : recs_) {
+ auto* card = new RecCard(r);
+ connect(card, &RecCard::previewRequested, this, &ExplainVisualizerWidget::previewSqlRequested);
+ recsLay_->addWidget(card);
+ }
+}
+
+void ExplainVisualizerWidget::selectNode(const QString& id) {
+ selectedNodeId_ = id;
+ for (auto* r : treeRows_) r->setSelected(r->nodeId() == id);
+ renderFlyout();
+}
+
+}
diff --git a/linux/src/Presentation/Views/ExplainVisualizer/ExplainVisualizerWidget.h b/linux/src/Presentation/Views/ExplainVisualizer/ExplainVisualizerWidget.h
new file mode 100644
index 0000000..449c985
--- /dev/null
+++ b/linux/src/Presentation/Views/ExplainVisualizer/ExplainVisualizerWidget.h
@@ -0,0 +1,93 @@
+#pragma once
+// Native Qt Explain Plan Visualizer.
+//
+// Four states (Empty/Loading/Loaded/Error) cycled via QStackedWidget.
+// Host pushes a parsed PlanDocument via setPlan(); the widget owns
+// rendering of the metric cards, plan tree, flyout, waterfall, and
+// recommendation cards. User actions (Run, Copy plan, Preview SQL) are
+// emitted as signals so the host can decide what to do with them.
+
+#include "Presentation/Views/ExplainVisualizer/ExplainPlanTypes.h"
+#include "Presentation/Views/ExplainVisualizer/ExplainPlanHeuristics.h"
+
+#include <QWidget>
+#include <memory>
+#include <vector>
+
+class QFrame;
+class QLabel;
+class QPushButton;
+class QStackedWidget;
+class QCheckBox;
+class QVBoxLayout;
+
+namespace gridex::explain {
+
+class InfoBarLite;
+class PlanNodeRow;
+
+class ExplainVisualizerWidget : public QWidget {
+ Q_OBJECT
+public:
+ explicit ExplainVisualizerWidget(QWidget* parent = nullptr);
+
+ void setPlan(std::shared_ptr<::gridex::explainviz::PlanDocument> doc);
+ void showEmpty();
+ void showLoading(const QString& text = QString());
+ void showError(const QString& message);
+ void reset() { showEmpty(); }
+
+signals:
+ void runRequested();
+ void copyPlanRequested(const QString& rawJson);
+ void previewSqlRequested(const QString& sql);
+
+private:
+ void buildUi();
+ QWidget* buildEmptyState();
+ QWidget* buildLoadingState();
+ QWidget* buildErrorState();
+ QWidget* buildLoadedState();
+
+ void renderInfoBar();
+ void renderMetrics();
+ void renderPlanTree();
+ void renderFlyout();
+ void renderWaterfall();
+ void renderRecs();
+
+ void selectNode(const QString& id);
+ void clearLayout(QVBoxLayout* lay);
+
+ void buildNodeRowRecursive(
+ const std::shared_ptr<::gridex::explainviz::PlanNode>& node,
+ int depth);
+
+ // State.
+ QStackedWidget* stack_ = nullptr;
+ QLabel* loadingLbl_ = nullptr;
+ QLabel* errorLbl_ = nullptr;
+
+ // Loaded-state widgets.
+ QLabel* metaLbl_ = nullptr;
+ InfoBarLite* infoBar_ = nullptr;
+ QFrame* metricsCard_ = nullptr;
+ QVBoxLayout* metricsLay_ = nullptr;
+ QFrame* treeCard_ = nullptr;
+ QVBoxLayout* treeLay_ = nullptr;
+ QFrame* flyoutCard_ = nullptr;
+ QVBoxLayout* flyoutLay_ = nullptr;
+ QVBoxLayout* waterfallLay_ = nullptr;
+ QVBoxLayout* recsLay_ = nullptr;
+ QCheckBox* hotOnlyChk_ = nullptr;
+ QLabel* planCountLbl_ = nullptr;
+
+ // Doc + derived.
+ std::shared_ptr<::gridex::explainviz::PlanDocument> doc_;
+ std::vector<::gridex::explainviz::Issue> issues_;
+ std::vector<::gridex::explainviz::Recommendation> recs_;
+ QString selectedNodeId_;
+ std::vector<PlanNodeRow*> treeRows_;
+};
+
+}
diff --git a/linux/src/Presentation/Views/ExplainVisualizer/PlanNodeRow.cpp b/linux/src/Presentation/Views/ExplainVisualizer/PlanNodeRow.cpp
new file mode 100644
index 0000000..d131e4f
--- /dev/null
+++ b/linux/src/Presentation/Views/ExplainVisualizer/PlanNodeRow.cpp
@@ -0,0 +1,213 @@
+#include "Presentation/Views/ExplainVisualizer/PlanNodeRow.h"
+#include "Presentation/Views/ExplainVisualizer/ExplainColors.h"
+#include "Presentation/Views/ExplainVisualizer/ExplainFormat.h"
+
+#include <QEnterEvent>
+#include <QHBoxLayout>
+#include <QLabel>
+#include <QMouseEvent>
+#include <QPainter>
+#include <QPainterPath>
+#include <QVBoxLayout>
+
+namespace gridex::explain {
+
+// ── HeatBar ────────────────────────────────────────────────────────────
+HeatBar::HeatBar(::gridex::explainviz::NodeLevel level, double pctFill, QWidget* parent)
+ : QFrame(parent), level_(level), pct_(qBound(0.0, pctFill, 100.0))
+{
+ setFixedHeight(7);
+ setMinimumWidth(60);
+ setAttribute(Qt::WA_TransparentForMouseEvents);
+}
+
+void HeatBar::paintEvent(QPaintEvent*) {
+ QPainter p(this);
+ p.setRenderHint(QPainter::Antialiasing);
+ const QColor track = isDarkPalette() ? QColor(255, 255, 255, 30)
+ : QColor(0, 0, 0, 20);
+ QPainterPath tp;
+ tp.addRoundedRect(rect(), 2, 2);
+ p.fillPath(tp, track);
+ // Fill — minimum 2px so even ~0% nodes are visible.
+ const double w = std::max(2.0, width() * pct_ / 100.0);
+ QRectF fillRect(0, 0, w, height());
+ QPainterPath fp;
+ fp.addRoundedRect(fillRect, 2, 2);
+ p.fillPath(fp, heatColor(level_));
+}
+
+// ── PlanNodeRow ────────────────────────────────────────────────────────
+PlanNodeRow::PlanNodeRow(std::shared_ptr<::gridex::explainviz::PlanNode> node,
+ int depth,
+ QWidget* parent)
+ : QFrame(parent), level_(node ? node->level : ::gridex::explainviz::NodeLevel::Good)
+{
+ nodeId_ = toQ(node ? node->id : std::wstring());
+ setFrameShape(QFrame::NoFrame);
+ setCursor(Qt::PointingHandCursor);
+ applyStyle();
+
+ auto* outer = new QHBoxLayout(this);
+ outer->setContentsMargins(8 + depth * 18, 6, 8, 6);
+ outer->setSpacing(10);
+
+ // Glyph badge — 34×28 rounded, heat tint background, heat accent text.
+ auto* glyph = new QLabel(node ? kindGlyph(node->kind) : QStringLiteral("•"), this);
+ glyph->setFixedSize(34, 28);
+ glyph->setAlignment(Qt::AlignCenter);
+ {
+ auto gf = glyph->font();
+ gf.setPointSize(gf.pointSize() + 2);
+ gf.setBold(true);
+ glyph->setFont(gf);
+ }
+ glyph->setStyleSheet(QStringLiteral(
+ "background: %1; color: %2; border-radius: 5px;")
+ .arg(heatBgRgba(level_, 64), heatColor(level_).name()));
+ outer->addWidget(glyph, 0, Qt::AlignVCenter);
+
+ // Body column: head row (op + relation + pill) + detail (elided) + cost line.
+ auto* col = new QVBoxLayout();
+ col->setSpacing(2);
+ col->setContentsMargins(0, 0, 0, 0);
+
+ auto* headRow = new QHBoxLayout();
+ headRow->setSpacing(8);
+ headRow->setContentsMargins(0, 0, 0, 0);
+ auto* opLbl = new QLabel(node ? toQ(node->op) : QString(), this);
+ {
+ auto of = opLbl->font();
+ of.setBold(true);
+ of.setPointSize(of.pointSize() + 1);
+ opLbl->setFont(of);
+ }
+ headRow->addWidget(opLbl);
+ if (node && !node->relation.empty()) {
+ QString rel = toQ(node->relation);
+ if (!node->alias.empty() && node->alias != node->relation)
+ rel += QStringLiteral(" ") + toQ(node->alias);
+ auto* relLbl = new QLabel(rel, this);
+ relLbl->setFont(monospaceFont(opLbl->font().pointSize() - 1));
+ relLbl->setStyleSheet(mutedTextCss());
+ headRow->addWidget(relLbl);
+ }
+ using L = ::gridex::explainviz::NodeLevel;
+ if (node && (node->level == L::Bad || node->level == L::Warn)) {
+ const bool bad = node->level == L::Bad;
+ auto* pill = new QLabel(bad ? tr("hot path") : tr("watch"), this);
+ pill->setAlignment(Qt::AlignCenter);
+ pill->setContentsMargins(8, 1, 8, 1);
+ auto pf = pill->font();
+ pf.setPointSize(qMax(8, pf.pointSize() - 2));
+ pf.setBold(true);
+ pill->setFont(pf);
+ pill->setStyleSheet(QStringLiteral(
+ "background: %1; color: %2; border-radius: 8px;")
+ .arg(heatBgRgba(node->level, 90), heatColor(node->level).name()));
+ headRow->addWidget(pill);
+ }
+ headRow->addStretch(1);
+ col->addLayout(headRow);
+
+ if (node && !node->detail.empty()) {
+ auto* det = new QLabel(this);
+ det->setText(toQ(node->detail));
+ det->setStyleSheet(mutedTextCss());
+ auto df = det->font(); df.setPointSize(qMax(8, df.pointSize() - 1)); det->setFont(df);
+ // Match Windows: NoWrap + CharacterEllipsis at width.
+ det->setTextFormat(Qt::PlainText);
+ det->setWordWrap(false);
+ det->setMinimumWidth(100);
+ det->setMaximumWidth(600);
+ det->setTextInteractionFlags(Qt::NoTextInteraction);
+ // Qt doesn't have ellipsis on QLabel out-of-the-box; clip via
+ // size policy + style. Force shrink with sizeHint horizontal.
+ det->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);
+ col->addWidget(det);
+ }
+
+ // Cost line: monospace, gray.
+ if (node) {
+ QString cost;
+ cost += QStringLiteral("cost %1…%2 · rows %3 · width %4")
+ .arg(node->startupCost, 0, 'f', 2)
+ .arg(node->totalCost, 0, 'f', 2)
+ .arg(fmtNum(node->actualRows))
+ .arg(node->planWidth);
+ if (node->analyzed) {
+ cost += QStringLiteral(" · actual %1 ms").arg(fmtMs(node->actualTotal));
+ if (node->actualLoops > 1)
+ cost += QStringLiteral(" × %1 loops").arg(node->actualLoops);
+ }
+ auto* costLbl = new QLabel(cost, this);
+ costLbl->setFont(monospaceFont(opLbl->font().pointSize() - 2));
+ costLbl->setStyleSheet(mutedTextCss());
+ costLbl->setWordWrap(false);
+ costLbl->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);
+ col->addWidget(costLbl);
+ }
+
+ outer->addLayout(col, 1);
+
+ // Right column: %time number (bold, heat color) + heat bar (140px).
+ if (node && node->analyzed) {
+ auto* heatCol = new QVBoxLayout();
+ heatCol->setSpacing(4);
+ heatCol->setContentsMargins(0, 0, 0, 0);
+
+ auto* pct = new QLabel(QStringLiteral("%1%").arg(node->pctOfTotal, 0, 'f', 1), this);
+ pct->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ {
+ auto pf = pct->font();
+ pf.setBold(true);
+ pf.setPointSize(pf.pointSize() + 1);
+ pct->setFont(pf);
+ }
+ pct->setStyleSheet(QStringLiteral("color: %1;").arg(heatColor(level_).name()));
+ heatCol->addWidget(pct);
+
+ auto* bar = new HeatBar(level_, node->pctOfTotal, this);
+ bar->setFixedWidth(140);
+ heatCol->addWidget(bar);
+
+ auto* heatHost = new QWidget(this);
+ heatHost->setFixedWidth(140);
+ heatHost->setLayout(heatCol);
+ outer->addWidget(heatHost, 0, Qt::AlignVCenter);
+ }
+}
+
+void PlanNodeRow::applyStyle() {
+ QString bg;
+ if (selected_) {
+ bg = heatBgRgba(level_, 40);
+ } else if (hovered_) {
+ bg = isDarkPalette() ? QStringLiteral("rgba(255,255,255,0.06)")
+ : QStringLiteral("rgba(0,0,0,0.04)");
+ } else {
+ bg = QStringLiteral("transparent");
+ }
+ QString border = selected_
+ ? QStringLiteral("border: 1px solid %1;").arg(heatColor(level_).name())
+ : QStringLiteral("border: 1px solid transparent;");
+ setStyleSheet(QStringLiteral(
+ "PlanNodeRow { background: %1; %2 border-radius: 6px; }")
+ .arg(bg, border));
+}
+
+void PlanNodeRow::setSelected(bool on) {
+ if (selected_ == on) return;
+ selected_ = on;
+ applyStyle();
+}
+
+void PlanNodeRow::mousePressEvent(QMouseEvent* e) {
+ if (e->button() == Qt::LeftButton) emit clicked(nodeId_);
+ QFrame::mousePressEvent(e);
+}
+
+void PlanNodeRow::enterEvent(QEnterEvent*) { hovered_ = true; applyStyle(); }
+void PlanNodeRow::leaveEvent(QEvent*) { hovered_ = false; applyStyle(); }
+
+}
diff --git a/linux/src/Presentation/Views/ExplainVisualizer/PlanNodeRow.h b/linux/src/Presentation/Views/ExplainVisualizer/PlanNodeRow.h
new file mode 100644
index 0000000..d2a8d2f
--- /dev/null
+++ b/linux/src/Presentation/Views/ExplainVisualizer/PlanNodeRow.h
@@ -0,0 +1,51 @@
+#pragma once
+// A single row in the plan tree. Mirror of the Windows BuildNodeRow:
+// [glyph badge] [op + relation(mono) + pill | detail(elided) | cost(mono)] [%time + heat bar 140px]
+
+#include "Presentation/Views/ExplainVisualizer/ExplainPlanTypes.h"
+
+#include <QFrame>
+#include <memory>
+
+namespace gridex::explain {
+
+class HeatBar : public QFrame {
+ Q_OBJECT
+public:
+ HeatBar(::gridex::explainviz::NodeLevel level,
+ double pctFill,
+ QWidget* parent = nullptr);
+protected:
+ void paintEvent(QPaintEvent*) override;
+private:
+ ::gridex::explainviz::NodeLevel level_;
+ double pct_; // 0..100
+};
+
+class PlanNodeRow : public QFrame {
+ Q_OBJECT
+public:
+ PlanNodeRow(std::shared_ptr<::gridex::explainviz::PlanNode> node,
+ int depth,
+ QWidget* parent = nullptr);
+
+ const QString& nodeId() const { return nodeId_; }
+ void setSelected(bool on);
+
+signals:
+ void clicked(const QString& nodeId);
+
+protected:
+ void mousePressEvent(QMouseEvent* e) override;
+ void enterEvent(QEnterEvent* e) override;
+ void leaveEvent(QEvent* e) override;
+
+private:
+ QString nodeId_;
+ bool selected_ = false;
+ bool hovered_ = false;
+ void applyStyle();
+ ::gridex::explainviz::NodeLevel level_;
+};
+
+}
diff --git a/linux/src/main.cpp b/linux/src/main.cpp
index 56cd6cc..5b7cc09 100644
--- a/linux/src/main.cpp
+++ b/linux/src/main.cpp
@@ -12,6 +12,7 @@
#include "Data/Persistence/AppConnectionRepository.h"
#include "Data/Persistence/AppDatabase.h"
#include "Presentation/Theme/ThemeManager.h"
+#include "Presentation/Views/ExplainVisualizer/ExplainExtension.h"
#include "Presentation/Windows/Main/MainWindow.h"
#include "Services/MCP/MCPServer.h"
@@ -90,6 +91,8 @@ int main(int argc, char* argv[]) {
gridex::ThemeManager::instance().apply(&app);
+ gridex::explain::registerQueryEditorExtension();
+
gridex::MainWindow window;
window.show();
diff --git a/windows/Gridex/ExplainVisualizer/ExplainPlanHeuristics.cpp b/windows/Gridex/ExplainVisualizer/ExplainPlanHeuristics.cpp
new file mode 100644
index 0000000..b8d7730
--- /dev/null
+++ b/windows/Gridex/ExplainVisualizer/ExplainPlanHeuristics.cpp
@@ -0,0 +1,243 @@
+#include "pch.h"
+// pch.h pulls in <windows.h> which defines `max`/`min` as macros — they
+// hijack `std::max` / `std::min` calls below. NOMINMAX isn't set globally
+// for this project, so undo the macros locally.
+#ifdef max
+#undef max
+#endif
+#ifdef min
+#undef min
+#endif
+#include "ExplainPlanHeuristics.h"
+
+#include <algorithm>
+#include <cmath>
+#include <functional>
+#include <sstream>
+
+namespace Gridex::ExplainViz
+{
+ // Threshold knobs — kept here for easy review.
+ static constexpr double SEQ_SCAN_FILTER_RATIO = 0.5; // ≥50% rows discarded → suggest index
+ static constexpr int SEQ_SCAN_MIN_REMOVED = 5000; // small tables not worth indexing
+ static constexpr double EST_VS_ACTUAL_FACTOR = 5.0; // |est−actual|/min > 5× → ANALYZE
+ static constexpr double EST_MIN_ROWS_FOR_ALERT = 100; // ignore tiny dev datasets
+ static constexpr int HASH_BATCH_THRESHOLD = 1; // >1 batch = spill
+ static constexpr double NESTED_LOOP_ROW_FACTOR = 1000; // outer rows × loops above this is suspicious
+
+ namespace
+ {
+ // Walk depth-first; first arg pre-order index lets caller process
+ // parents before children (tree label tagging) but isn't required.
+ void walk(const std::shared_ptr<PlanNode>& n,
+ const std::function<void(PlanNode&)>& fn)
+ {
+ if (!n) return;
+ fn(*n);
+ for (auto& c : n->children) walk(c, fn);
+ }
+
+ // Format a row count compactly (1.2k / 4.3M).
+ std::wstring fmtRows(double r)
+ {
+ std::wstringstream ss;
+ if (r >= 1e6) ss << (r / 1e6) << L"M";
+ else if (r >= 1e3) ss << (r / 1e3) << L"k";
+ else ss << static_cast<int>(r);
+ return ss.str();
+ }
+ }
+
+ std::vector<Issue> ExplainPlanHeuristics::analyze(PlanDocument& doc)
+ {
+ std::vector<Issue> issues;
+ if (!doc.root) return issues;
+
+ walk(doc.root, [&](PlanNode& n) {
+ // ── Rule 1: Sequential scan with high filter rejection.
+ // Reading a big table end-to-end and discarding most rows
+ // is the textbook case for "add an index".
+ if (n.kind == NodeKind::SeqScan && n.rowsRemovedByFilter > 0) {
+ double scanned = n.actualRows + n.rowsRemovedByFilter;
+ double rejectRatio = scanned > 0 ? n.rowsRemovedByFilter / scanned : 0.0;
+ if (rejectRatio >= SEQ_SCAN_FILTER_RATIO &&
+ n.rowsRemovedByFilter >= SEQ_SCAN_MIN_REMOVED)
+ {
+ Issue i;
+ i.nodeId = n.id;
+ i.severity = IssueSeverity::Bad;
+ i.title = L"Sequential scan rejecting " + fmtRows(n.rowsRemovedByFilter)
+ + L" rows on " + (n.relation.empty() ? L"a table" : n.relation);
+ std::wstringstream d;
+ d << L"The planner is reading "
+ << (n.relation.empty() ? L"the table" : n.relation)
+ << L" end-to-end and filtering " << static_cast<int>(rejectRatio * 100)
+ << L"% of rows. An index covering the WHERE clause would likely make this query much faster.";
+ i.detail = d.str();
+ issues.push_back(i);
+ n.level = NodeLevel::Bad;
+ }
+ }
+
+ // ── Rule 2: External-merge sort (spilled to disk).
+ if (n.kind == NodeKind::Sort && n.sortSpaceType == L"Disk") {
+ Issue i;
+ i.nodeId = n.id;
+ i.severity = IssueSeverity::Warn;
+ i.title = L"Sort spilled to disk (" + n.sortSpaceUsed + L")";
+ i.detail = L"work_mem was too small for the sort. Raising it for the session "
+ L"will keep the sort in memory.";
+ issues.push_back(i);
+ if (n.level == NodeLevel::Good) n.level = NodeLevel::Warn;
+ }
+
+ // ── Rule 3: Hash join with multiple batches.
+ if (n.kind == NodeKind::HashJoin && n.hashBatches > HASH_BATCH_THRESHOLD) {
+ Issue i;
+ i.nodeId = n.id;
+ i.severity = IssueSeverity::Warn;
+ i.title = L"Hash join spilled across " + std::to_wstring(n.hashBatches) + L" batches";
+ i.detail = L"The hash table didn't fit in work_mem. Larger work_mem prevents the spill.";
+ issues.push_back(i);
+ if (n.level == NodeLevel::Good) n.level = NodeLevel::Warn;
+ }
+
+ // ── Rule 4: Estimated vs. actual row mismatch — stale ANALYZE.
+ if (n.analyzed && n.planRows >= EST_MIN_ROWS_FOR_ALERT &&
+ n.actualRows >= EST_MIN_ROWS_FOR_ALERT)
+ {
+ double est = n.planRows;
+ double act = n.actualRows;
+ double factor = std::max(est, act) / std::max(1.0, std::min(est, act));
+ if (factor >= EST_VS_ACTUAL_FACTOR && !n.relation.empty()) {
+ Issue i;
+ i.nodeId = n.id;
+ i.severity = IssueSeverity::Warn;
+ std::wstringstream t;
+ t << L"Planner row estimate off by " << static_cast<int>(factor)
+ << L"× on " << n.relation;
+ i.title = t.str();
+ i.detail = L"Run ANALYZE to refresh table statistics — costing decisions "
+ L"depend on accurate row counts.";
+ issues.push_back(i);
+ // Keep tree pill consistent with InfoBar callout.
+ if (n.level == NodeLevel::Good) n.level = NodeLevel::Warn;
+ }
+ }
+
+ // ── Rule 5: Nested Loop with very large outer scan.
+ if (n.kind == NodeKind::NestedLoop && n.children.size() >= 2) {
+ double outerRows = n.children[0]->actualRows;
+ if (outerRows * n.actualLoops > NESTED_LOOP_ROW_FACTOR && n.actualTotal > 100) {
+ Issue i;
+ i.nodeId = n.id;
+ i.severity = IssueSeverity::Warn;
+ i.title = L"Nested Loop driving " + fmtRows(outerRows) + L" outer rows";
+ i.detail = L"For high outer counts a Hash Join or Merge Join is usually faster. "
+ L"Check that join columns are indexed and stats are fresh.";
+ issues.push_back(i);
+ if (n.level == NodeLevel::Good) n.level = NodeLevel::Warn;
+ }
+ }
+ });
+
+ // Stable order: Bad → Warn → Info, then plan order (already DFS).
+ std::stable_sort(issues.begin(), issues.end(),
+ [](const Issue& a, const Issue& b) {
+ return static_cast<int>(a.severity) > static_cast<int>(b.severity);
+ });
+ return issues;
+ }
+
+ std::vector<Recommendation> ExplainPlanHeuristics::recommend(
+ const PlanDocument& doc, const std::vector<Issue>& issues)
+ {
+ std::vector<Recommendation> recs;
+ if (!doc.root) return recs;
+
+ // Track which seq-scan tables we've already recommended an index
+ // for so we don't duplicate when there are multiple offending
+ // filters on the same relation.
+ std::vector<std::wstring> indexSuggested;
+
+ // Walk to find seq scans flagged Bad → suggest index. We pull the
+ // filter expression as-is; user reviews + edits the SQL preview.
+ std::function<void(const std::shared_ptr<PlanNode>&)> walk =
+ [&](const std::shared_ptr<PlanNode>& n) {
+ if (!n) return;
+ if (n->kind == NodeKind::SeqScan && n->level == NodeLevel::Bad &&
+ !n->relation.empty() && !n->filter.empty())
+ {
+ if (std::find(indexSuggested.begin(), indexSuggested.end(),
+ n->relation) == indexSuggested.end())
+ {
+ Recommendation r;
+ r.severity = IssueSeverity::Bad;
+ r.title = L"Create index on " + n->relation;
+ r.rationale = L"Eliminates the Seq Scan that filters out "
+ + fmtRows(n->rowsRemovedByFilter) + L" rows.";
+ // Best-effort SQL — extract the leftmost identifier
+ // from the filter as the candidate column.
+ std::wstring col;
+ for (auto c : n->filter) {
+ if (iswalnum(c) || c == L'_' || c == L'.') col += c;
+ else if (!col.empty()) break;
+ }
+ if (col.empty()) col = L"<column>";
+ r.previewSql = L"CREATE INDEX ON " + n->relation + L" (" + col + L");";
+ recs.push_back(r);
+ indexSuggested.push_back(n->relation);
+ }
+ }
+ for (auto& c : n->children) walk(c);
+ };
+ walk(doc.root);
+
+ // Spilling sort → raise work_mem.
+ bool sortSpilled = false;
+ bool hashSpilled = false;
+ std::function<void(const std::shared_ptr<PlanNode>&)> walk2 =
+ [&](const std::shared_ptr<PlanNode>& n) {
+ if (!n) return;
+ if (n->kind == NodeKind::Sort && n->sortSpaceType == L"Disk") sortSpilled = true;
+ if (n->kind == NodeKind::HashJoin && n->hashBatches > 1) hashSpilled = true;
+ for (auto& c : n->children) walk2(c);
+ };
+ walk2(doc.root);
+ if (sortSpilled || hashSpilled) {
+ Recommendation r;
+ r.severity = IssueSeverity::Warn;
+ r.title = L"Raise work_mem for this session";
+ r.rationale = sortSpilled
+ ? L"The sort spilled to disk — bigger work_mem keeps it in memory."
+ : L"The hash join spilled across batches — bigger work_mem prevents the spill.";
+ r.previewSql = L"SET LOCAL work_mem = '64MB';";
+ recs.push_back(r);
+ }
+
+ // ANALYZE recommendation: collect distinct relations from estimate-mismatch issues.
+ std::vector<std::wstring> staleRels;
+ for (const auto& i : issues) {
+ if (i.title.find(L"Planner row estimate off") != std::wstring::npos) {
+ // Pull relation off the title's last word — ugly but cheap;
+ // we can wire a structured field through later if needed.
+ auto pos = i.title.rfind(L' ');
+ if (pos != std::wstring::npos) {
+ auto rel = i.title.substr(pos + 1);
+ if (std::find(staleRels.begin(), staleRels.end(), rel) == staleRels.end())
+ staleRels.push_back(rel);
+ }
+ }
+ }
+ for (const auto& rel : staleRels) {
+ Recommendation r;
+ r.severity = IssueSeverity::Info;
+ r.title = L"Run ANALYZE " + rel;
+ r.rationale = L"Planner stats are stale — refresh row estimates.";
+ r.previewSql = L"ANALYZE " + rel + L";";
+ recs.push_back(r);
+ }
+
+ return recs;
+ }
+}
diff --git a/windows/Gridex/ExplainVisualizer/ExplainPlanHeuristics.h b/windows/Gridex/ExplainVisualizer/ExplainPlanHeuristics.h
new file mode 100644
index 0000000..9e1dcc6
--- /dev/null
+++ b/windows/Gridex/ExplainVisualizer/ExplainPlanHeuristics.h
@@ -0,0 +1,50 @@
+#pragma once
+// Pure-function heuristics over a parsed PlanDocument. Two outputs:
+// • Warnings — short, single-issue callouts shown inline (the InfoBar)
+// and as `pill` badges on offending tree nodes.
+// • Recommendations — actionable suggestions surfaced in the bottom
+// "Recommendations" card (ANALYZE, raise work_mem, add index...).
+//
+// Rules are intentionally simple + transparent. We bias toward false
+// negatives (no nag) over false positives — every recommendation must
+// be a thing a senior DBA would also say after one glance at the plan.
+
+#include "ExplainPlanTypes.h"
+
+#include <string>
+#include <vector>
+
+namespace Gridex::ExplainViz
+{
+ enum class IssueSeverity { Info, Warn, Bad };
+
+ struct Issue
+ {
+ std::wstring nodeId; // PlanNode.id this issue points at
+ std::wstring title; // short summary (used in InfoBar header)
+ std::wstring detail; // longer body
+ IssueSeverity severity = IssueSeverity::Warn;
+ };
+
+ struct Recommendation
+ {
+ std::wstring title; // bold lead, e.g. "Create index on admissions(admit_date)"
+ std::wstring rationale; // single-sentence justification
+ std::wstring previewSql; // SQL to copy/preview when user clicks
+ IssueSeverity severity = IssueSeverity::Warn;
+ };
+
+ class ExplainPlanHeuristics
+ {
+ public:
+ // Walks the plan and returns the issues found. Sets level=Bad on
+ // any node tagged with a Bad-severity issue (mutates in place so
+ // the tree's heat coloring matches the InfoBar).
+ static std::vector<Issue> analyze(PlanDocument& doc);
+
+ // Build recommendation cards from the same pass. Caller can run
+ // this after analyze() so the same data is reused.
+ static std::vector<Recommendation> recommend(const PlanDocument& doc,
+ const std::vector<Issue>& issues);
+ };
+}
diff --git a/windows/Gridex/ExplainVisualizer/ExplainPlanParser.cpp b/windows/Gridex/ExplainVisualizer/ExplainPlanParser.cpp
new file mode 100644
index 0000000..318b485
--- /dev/null
+++ b/windows/Gridex/ExplainVisualizer/ExplainPlanParser.cpp
@@ -0,0 +1,441 @@
+#include "pch.h"
+// Undo windows.h max/min macros (see note in heuristics).
+#ifdef max
+#undef max
+#endif
+#ifdef min
+#undef min
+#endif
+#include "ExplainPlanParser.h"
+
+#include <cctype>
+#include <cwctype>
+#include <sstream>
+
+namespace Gridex::ExplainViz
+{
+ // ── Mini wstring JSON tokenizer ───────────────────────────────
+ // Tiny scanner over wide chars — only what we need to walk arrays
+ // and objects in PG's EXPLAIN output. Whitespace tolerant; assumes
+ // valid UTF-16 produced by Postgres.
+ namespace
+ {
+ struct Reader
+ {
+ const wchar_t* p;
+ const wchar_t* end;
+
+ void skipWs()
+ {
+ while (p < end && std::iswspace(*p)) ++p;
+ }
+ bool eof() const { return p >= end; }
+ wchar_t peek() { skipWs(); return p < end ? *p : 0; }
+
+ bool match(wchar_t c)
+ {
+ skipWs();
+ if (p < end && *p == c) { ++p; return true; }
+ return false;
+ }
+
+ bool parseString(std::wstring& out)
+ {
+ skipWs();
+ if (p >= end || *p != L'"') return false;
+ ++p;
+ out.clear();
+ while (p < end && *p != L'"') {
+ if (*p == L'\\' && p + 1 < end) {
+ wchar_t n = p[1];
+ switch (n) {
+ case L'n': out += L'\n'; break;
+ case L't': out += L'\t'; break;
+ case L'r': out += L'\r'; break;
+ case L'"': out += L'"'; break;
+ case L'\\': out += L'\\'; break;
+ case L'/': out += L'/'; break;
+ case L'b': out += L'\b'; break;
+ case L'f': out += L'\f'; break;
+ case L'u': {
+ // \uXXXX consumes 6 chars (\, u, 4 hex). Guard
+ // against truncated escapes so we don't loop.
+ if (p + 6 <= end) {
+ wchar_t hex[5] = { p[2], p[3], p[4], p[5], 0 };
+ out += static_cast<wchar_t>(std::wcstoul(hex, nullptr, 16));
+ p += 6;
+ } else {
+ p = end;
+ }
+ continue; // skip the unified `p += 2` below
+ }
+ default: out += n; break;
+ }
+ p += 2;
+ } else {
+ out += *p; ++p;
+ }
+ }
+ if (p < end && *p == L'"') ++p;
+ return true;
+ }
+
+ bool parseNumber(double& out)
+ {
+ skipWs();
+ if (p >= end) return false;
+ wchar_t* endPtr = nullptr;
+ out = std::wcstod(p, &endPtr);
+ if (endPtr == p) return false;
+ p = endPtr;
+ return true;
+ }
+
+ // Skip a value (object / array / string / number / bool / null)
+ // without parsing it — used for unknown keys.
+ bool skipValue()
+ {
+ skipWs();
+ if (p >= end) return false;
+ if (*p == L'"') { std::wstring tmp; return parseString(tmp); }
+ if (*p == L'{' || *p == L'[') {
+ wchar_t open = *p;
+ wchar_t close = (open == L'{') ? L'}' : L']';
+ int depth = 0; ++p;
+ bool inStr = false, esc = false;
+ while (p < end) {
+ wchar_t c = *p;
+ if (inStr) {
+ if (esc) esc = false;
+ else if (c == L'\\') esc = true;
+ else if (c == L'"') inStr = false;
+ } else {
+ if (c == L'"') inStr = true;
+ else if (c == open) ++depth;
+ else if (c == close) {
+ if (depth == 0) { ++p; return true; }
+ --depth;
+ }
+ }
+ ++p;
+ }
+ return false;
+ }
+ // bool / null / number — eat until comma or close.
+ while (p < end && *p != L',' && *p != L'}' && *p != L']') ++p;
+ return true;
+ }
+ };
+
+ // Forward decl
+ std::shared_ptr<PlanNode> parsePlanNode(Reader& r);
+
+ // Map the "Node Type" string from EXPLAIN to our enum.
+ NodeKind mapKind(const std::wstring& s)
+ {
+ if (s == L"Limit") return NodeKind::Limit;
+ if (s == L"Sort") return NodeKind::Sort;
+ if (s == L"Hash Join") return NodeKind::HashJoin;
+ if (s == L"Merge Join") return NodeKind::MergeJoin;
+ if (s == L"Nested Loop") return NodeKind::NestedLoop;
+ if (s == L"Seq Scan") return NodeKind::SeqScan;
+ if (s == L"Index Scan") return NodeKind::IndexScan;
+ if (s == L"Index Only Scan") return NodeKind::IndexOnlyScan;
+ if (s == L"Bitmap Heap Scan") return NodeKind::BitmapHeapScan;
+ if (s == L"Bitmap Index Scan") return NodeKind::BitmapIndexScan;
+ if (s == L"Hash") return NodeKind::Hash;
+ if (s == L"Aggregate") return NodeKind::Aggregate;
+ if (s == L"GroupAggregate") return NodeKind::GroupAggregate;
+ if (s == L"HashAggregate") return NodeKind::HashAggregate;
+ if (s == L"WindowAgg") return NodeKind::WindowAgg;
+ if (s == L"Materialize") return NodeKind::Materialize;
+ if (s == L"Gather") return NodeKind::Gather;
+ if (s == L"Gather Merge") return NodeKind::GatherMerge;
+ if (s == L"Append") return NodeKind::Append;
+ if (s == L"Result") return NodeKind::Result;
+ if (s == L"Subquery Scan") return NodeKind::SubqueryScan;
+ if (s == L"CTE Scan") return NodeKind::CteScan;
+ if (s == L"Unique") return NodeKind::Unique;
+ if (s == L"Memoize") return NodeKind::Memoize;
+ return NodeKind::Other;
+ }
+
+ // Build a one-liner detail string from a parsed node — what to show
+ // next to the op label in the tree. Mirrors the design's "detail"
+ // column without dumping every field.
+ std::wstring buildDetail(const PlanNode& n)
+ {
+ std::wstringstream ss;
+ bool first = true;
+ auto sep = [&]() { if (!first) ss << L" · "; first = false; };
+
+ if (!n.indexName.empty()) {
+ sep(); ss << L"using " << n.indexName;
+ }
+ if (!n.joinType.empty()) {
+ sep(); ss << n.joinType;
+ }
+ if (!n.strategy.empty()) {
+ sep(); ss << n.strategy;
+ }
+ if (!n.indexCond.empty()) {
+ sep(); ss << L"cond: " << n.indexCond;
+ }
+ if (!n.filter.empty()) {
+ sep(); ss << L"filter: " << n.filter;
+ }
+ if (!n.sortMethod.empty()) {
+ sep(); ss << n.sortMethod;
+ if (!n.sortSpaceUsed.empty())
+ ss << L" (" << n.sortSpaceUsed << L" " << n.sortSpaceType << L")";
+ }
+ if (n.hashBatches > 0 || !n.hashMemKb.empty()) {
+ sep();
+ if (n.hashBuckets > 0) ss << L"buckets " << n.hashBuckets;
+ if (n.hashBatches > 1) ss << L" batches " << n.hashBatches;
+ if (!n.hashMemKb.empty()) ss << L" mem " << n.hashMemKb << L" KB";
+ }
+ return ss.str();
+ }
+
+ // Walk a plan-object's keys filling our PlanNode. We skip unknown
+ // keys; PG occasionally adds new ones across versions and we don't
+ // want to fail because of them.
+ std::shared_ptr<PlanNode> parsePlanObject(Reader& r)
+ {
+ if (!r.match(L'{')) return nullptr;
+ auto node = std::make_shared<PlanNode>();
+ std::wstring schema, alias;
+
+ while (!r.eof()) {
+ r.skipWs();
+ if (r.match(L'}')) break;
+ std::wstring key;
+ if (!r.parseString(key)) return nullptr;
+ if (!r.match(L':')) return nullptr;
+ r.skipWs();
+
+ if (key == L"Node Type") {
+ r.parseString(node->op);
+ node->kind = mapKind(node->op);
+ }
+ else if (key == L"Relation Name") r.parseString(node->relation);
+ else if (key == L"Schema") r.parseString(schema);
+ else if (key == L"Alias") r.parseString(node->alias);
+ else if (key == L"Index Name") r.parseString(node->indexName);
+ else if (key == L"Index Cond") r.parseString(node->indexCond);
+ else if (key == L"Filter") r.parseString(node->filter);
+ else if (key == L"Sort Method") r.parseString(node->sortMethod);
+ else if (key == L"Sort Space Used") {
+ double v; if (r.parseNumber(v))
+ node->sortSpaceUsed = std::to_wstring(static_cast<int>(v)) + L" KB";
+ }
+ else if (key == L"Sort Space Type") r.parseString(node->sortSpaceType);
+ else if (key == L"Join Type") r.parseString(node->joinType);
+ else if (key == L"Strategy") r.parseString(node->strategy);
+ else if (key == L"Hash Buckets") {
+ double v; if (r.parseNumber(v)) node->hashBuckets = static_cast<int>(v);
+ }
+ else if (key == L"Hash Batches") {
+ double v; if (r.parseNumber(v)) node->hashBatches = static_cast<int>(v);
+ }
+ else if (key == L"Original Hash Batches") { double v; r.parseNumber(v); }
+ else if (key == L"Peak Memory Usage") {
+ double v; if (r.parseNumber(v)) node->hashMemKb = std::to_wstring(static_cast<int>(v));
+ }
+ else if (key == L"Startup Cost") r.parseNumber(node->startupCost);
+ else if (key == L"Total Cost") r.parseNumber(node->totalCost);
+ else if (key == L"Plan Rows") r.parseNumber(node->planRows);
+ else if (key == L"Plan Width") {
+ double v; if (r.parseNumber(v)) node->planWidth = static_cast<int>(v);
+ }
+ else if (key == L"Actual Startup Time") {
+ r.parseNumber(node->actualStartup);
+ node->analyzed = true;
+ }
+ else if (key == L"Actual Total Time") {
+ r.parseNumber(node->actualTotal);
+ node->analyzed = true;
+ }
+ else if (key == L"Actual Rows") r.parseNumber(node->actualRows);
+ else if (key == L"Actual Loops") {
+ double v; if (r.parseNumber(v)) node->actualLoops = static_cast<int>(v);
+ }
+ else if (key == L"Rows Removed by Filter") {
+ double v; if (r.parseNumber(v)) node->rowsRemovedByFilter = static_cast<int>(v);
+ }
+ else if (key == L"Rows Removed by Index Recheck") {
+ double v; if (r.parseNumber(v)) node->rowsRemovedByIndexRecheck = static_cast<int>(v);
+ }
+ else if (key == L"Shared Hit Blocks") {
+ double v; if (r.parseNumber(v)) node->sharedHit = static_cast<int64_t>(v);
+ }
+ else if (key == L"Shared Read Blocks") {
+ double v; if (r.parseNumber(v)) node->sharedRead = static_cast<int64_t>(v);
+ }
+ else if (key == L"Shared Dirtied Blocks") {
+ double v; if (r.parseNumber(v)) node->sharedDirtied = static_cast<int64_t>(v);
+ }
+ else if (key == L"Shared Written Blocks") {
+ double v; if (r.parseNumber(v)) node->sharedWritten = static_cast<int64_t>(v);
+ }
+ else if (key == L"Temp Read Blocks") {
+ double v; if (r.parseNumber(v)) node->tempRead = static_cast<int64_t>(v);
+ }
+ else if (key == L"Temp Written Blocks") {
+ double v; if (r.parseNumber(v)) node->tempWritten = static_cast<int64_t>(v);
+ }
+ else if (key == L"Output") {
+ // array of strings
+ if (r.match(L'[')) {
+ while (!r.eof()) {
+ r.skipWs();
+ if (r.match(L']')) break;
+ std::wstring col;
+ if (r.parseString(col)) node->outputCols.push_back(col);
+ r.skipWs(); r.match(L',');
+ }
+ } else {
+ r.skipValue();
+ }
+ }
+ else if (key == L"Plans") {
+ if (r.match(L'[')) {
+ while (!r.eof()) {
+ r.skipWs();
+ if (r.match(L']')) break;
+ auto child = parsePlanObject(r);
+ if (child) node->children.push_back(child);
+ r.skipWs(); r.match(L',');
+ }
+ } else {
+ r.skipValue();
+ }
+ }
+ else {
+ r.skipValue();
+ }
+
+ r.skipWs();
+ r.match(L',');
+ }
+
+ // Compose qualified relation name (schema.table).
+ if (!schema.empty() && !node->relation.empty()) {
+ node->relation = schema + L"." + node->relation;
+ }
+ // Detail composed last so all parts are available.
+ node->detail = buildDetail(*node);
+ return node;
+ }
+
+ std::shared_ptr<PlanNode> parsePlanNode(Reader& r)
+ {
+ return parsePlanObject(r);
+ }
+
+ // Generate ids by depth-first walk so siblings get distinct names.
+ void assignIds(PlanNode& n, int& counter)
+ {
+ n.id = L"n" + std::to_wstring(counter++);
+ for (auto& c : n.children) assignIds(*c, counter);
+ }
+
+ double sumSubtreeOwn(const PlanNode& n)
+ {
+ double total = (n.actualTotal * n.actualLoops);
+ // own = total - sum(children total). We compute own at parent
+ // level — nothing to do recursively here; classifyTimings does
+ // the second pass once we know the grand total.
+ return total;
+ }
+
+ void classifyTimings(PlanNode& n, double grandTotalMs)
+ {
+ double childrenTotal = 0.0;
+ for (auto& c : n.children) {
+ childrenTotal += c->actualTotal * c->actualLoops;
+ classifyTimings(*c, grandTotalMs);
+ }
+ n.ownMs = std::max(0.0, n.actualTotal * n.actualLoops - childrenTotal);
+ n.pctOfTotal = grandTotalMs > 0 ? (n.ownMs / grandTotalMs) * 100.0 : 0.0;
+
+ // Default heat classification — heuristics module may upgrade
+ // to Bad on issues even if the percentage is small.
+ if (n.pctOfTotal >= 25.0) n.level = NodeLevel::Bad;
+ else if (n.pctOfTotal >= 5.0) n.level = NodeLevel::Warn;
+ else n.level = NodeLevel::Good;
+
+ // Sort spilling to disk should always show as Warn at minimum.
+ if (n.sortSpaceType == L"Disk" && n.level == NodeLevel::Good)
+ n.level = NodeLevel::Warn;
+ }
+ } // anon namespace
+
+ void ExplainPlanParser::postProcess(PlanDocument& doc)
+ {
+ if (!doc.root) return;
+ int counter = 0;
+ assignIds(*doc.root, counter);
+ // Grand total = root's actualTotal*loops, fallback to summed if root
+ // wasn't analyzed (shouldn't happen with ANALYZE but defensive).
+ double total = doc.root->actualTotal * doc.root->actualLoops;
+ if (total <= 0.0) total = sumSubtreeOwn(*doc.root);
+ doc.executionMs = total;
+ classifyTimings(*doc.root, total);
+ }
+
+ bool ExplainPlanParser::parse(const std::wstring& json,
+ PlanDocument& out,
+ std::wstring& err)
+ {
+ if (json.empty()) { err = L"Empty plan JSON."; return false; }
+ out.rawJson = json;
+
+ Reader r{ json.c_str(), json.c_str() + json.size() };
+
+ // EXPLAIN FORMAT JSON returns a top-level array. Pop into the first
+ // element which is an object containing "Plan", "Planning Time" etc.
+ r.skipWs();
+ if (!r.match(L'[')) { err = L"Plan JSON must be an array."; return false; }
+ r.skipWs();
+ if (!r.match(L'{')) { err = L"Plan JSON missing root object."; return false; }
+
+ while (!r.eof()) {
+ r.skipWs();
+ if (r.match(L'}')) break;
+ std::wstring key;
+ if (!r.parseString(key)) { err = L"Bad key in plan."; return false; }
+ if (!r.match(L':')) { err = L"Missing ':' in plan."; return false; }
+ r.skipWs();
+ if (key == L"Plan") {
+ out.root = parsePlanObject(r);
+ }
+ else if (key == L"Planning Time") {
+ r.parseNumber(out.planningMs);
+ }
+ else if (key == L"Execution Time") {
+ r.parseNumber(out.executionMs);
+ }
+ else {
+ r.skipValue();
+ }
+ r.skipWs();
+ r.match(L',');
+ }
+
+ if (!out.root) { err = L"Plan JSON had no Plan object."; return false; }
+
+ out.analyzed = out.root->analyzed;
+ postProcess(out);
+
+ // executionMs from `Execution Time` (when present) takes priority
+ // — that's the wall-clock for the whole query, more accurate than
+ // root node totals on parallel plans.
+ // postProcess already used root total; if Execution Time is bigger
+ // (e.g., parallel workers), keep the root-derived sum for share %
+ // but expose Execution Time separately via planningMs/executionMs
+ // accessors. We accept the slight drift.
+ return true;
+ }
+}
diff --git a/windows/Gridex/ExplainVisualizer/ExplainPlanParser.h b/windows/Gridex/ExplainVisualizer/ExplainPlanParser.h
new file mode 100644
index 0000000..e5543b7
--- /dev/null
+++ b/windows/Gridex/ExplainVisualizer/ExplainPlanParser.h
@@ -0,0 +1,30 @@
+#pragma once
+// Parser for Postgres `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)` output.
+// We hand-roll a tiny JSON consumer (no nlohmann dependency to match the
+// rest of the application) — only the subset of PG's plan schema we
+// actually surface in the UI is read; unknown keys are skipped.
+
+#include "ExplainPlanTypes.h"
+
+#include <string>
+
+namespace Gridex::ExplainViz
+{
+ class ExplainPlanParser
+ {
+ public:
+ // Parses the JSON string returned in the single text cell of an
+ // `EXPLAIN (FORMAT JSON)` query. Returns true on success and fills
+ // `out`. On failure returns false and writes a human-readable
+ // explanation into `err`.
+ static bool parse(const std::wstring& json,
+ PlanDocument& out,
+ std::wstring& err);
+
+ // Convenience: re-walk the doc and recompute derived values
+ // (NodeLevel, pctOfTotal, ownMs, generated ids). Called automatically
+ // at the end of `parse`; exposed for tests and re-classification
+ // after heuristics tweak any node-level fields.
+ static void postProcess(PlanDocument& doc);
+ };
+}
diff --git a/windows/Gridex/ExplainVisualizer/ExplainPlanTypes.h b/windows/Gridex/ExplainVisualizer/ExplainPlanTypes.h
new file mode 100644
index 0000000..c98f0b3
--- /dev/null
+++ b/windows/Gridex/ExplainVisualizer/ExplainPlanTypes.h
@@ -0,0 +1,125 @@
+#pragma once
+// Pure-C++ value types for the Explain Plan Visualizer. Mirrors the shape
+// returned by `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)` on Postgres so a
+// JSON node maps 1:1 onto a PlanNode in our tree.
+
+#include <cstdint>
+#include <memory>
+#include <string>
+#include <vector>
+
+namespace Gridex::ExplainViz
+{
+ // Heuristic-derived severity used by the heat bar + node coloring.
+ enum class NodeLevel
+ {
+ Good, // <5% of total time, no warnings
+ Warn, // sort spill, partial spill, low-confidence stats
+ Bad // hot path: >25% of total time, or seq scan w/ heavy filter
+ };
+
+ // What kind of operation the node represents — drives the glyph and
+ // colored badge in the UI. Keep small + extend as needed.
+ enum class NodeKind
+ {
+ Other,
+ Limit,
+ Sort,
+ HashJoin,
+ MergeJoin,
+ NestedLoop,
+ SeqScan,
+ IndexScan,
+ IndexOnlyScan,
+ BitmapHeapScan,
+ BitmapIndexScan,
+ Hash,
+ Aggregate,
+ GroupAggregate,
+ HashAggregate,
+ WindowAgg,
+ Materialize,
+ Gather,
+ GatherMerge,
+ Append,
+ Result,
+ SubqueryScan,
+ CteScan,
+ Unique,
+ Memoize
+ };
+
+ struct PlanNode
+ {
+ std::wstring id; // generated, used for UI selection (e.g. "n0")
+ std::wstring op; // raw "Node Type" from EXPLAIN
+ NodeKind kind = NodeKind::Other;
+ std::wstring relation; // table name when applicable
+ std::wstring alias;
+ std::wstring detail; // human-readable extras (filter, sort key, join cond...)
+
+ // Cost numbers from the planner.
+ double startupCost = 0.0;
+ double totalCost = 0.0;
+ double planRows = 0.0;
+ int planWidth = 0;
+
+ // Actual measurements when ANALYZE was used.
+ bool analyzed = false;
+ double actualStartup = 0.0;
+ double actualTotal = 0.0; // ms per loop
+ double actualRows = 0.0;
+ int actualLoops = 1;
+ double pctOfTotal = 0.0; // own-time share of grand total ms
+ double ownMs = 0.0; // own-time = actualTotal*loops − Σ children own-time
+
+ // Buffer accounting (int64 — large plans can touch billions of blocks).
+ int64_t sharedHit = 0;
+ int64_t sharedRead = 0;
+ int64_t sharedDirtied = 0;
+ int64_t sharedWritten = 0;
+ int64_t tempRead = 0;
+ int64_t tempWritten = 0;
+
+ // Sort-specific
+ std::wstring sortMethod; // "external merge", "quicksort", ...
+ std::wstring sortSpaceUsed;
+ std::wstring sortSpaceType; // "Memory" or "Disk"
+
+ // Hash-specific
+ int hashBuckets = 0;
+ int hashBatches = 0;
+ std::wstring hashMemKb; // raw value, formatted later
+
+ // Index-specific
+ std::wstring indexName;
+ std::wstring indexCond;
+
+ // Filter accounting
+ std::wstring filter;
+ int rowsRemovedByFilter = 0;
+ int rowsRemovedByIndexRecheck = 0;
+ std::wstring joinType;
+ std::wstring strategy;
+
+ std::vector<std::wstring> outputCols;
+
+ NodeLevel level = NodeLevel::Good;
+
+ std::vector<std::shared_ptr<PlanNode>> children;
+ };
+
+ // Top-level container for one parsed EXPLAIN output.
+ struct PlanDocument
+ {
+ std::shared_ptr<PlanNode> root;
+ double planningMs = 0.0;
+ double executionMs = 0.0; // grand total ms (ANALYZE)
+ std::wstring rawJson; // kept so flyout / Copy plan works
+ std::wstring originalSql; // SQL that generated this plan
+ std::wstring databaseName;
+ std::wstring serverVersion;
+ bool analyzed = false;
+ bool buffers = false;
+ };
+}
diff --git a/windows/Gridex/ExplainVisualizer/ExplainPlanVisualizerControl.cpp b/windows/Gridex/ExplainVisualizer/ExplainPlanVisualizerControl.cpp
new file mode 100644
index 0000000..51f3986
--- /dev/null
+++ b/windows/Gridex/ExplainVisualizer/ExplainPlanVisualizerControl.cpp
@@ -0,0 +1,969 @@
+#include "pch.h"
+// Undo windows.h max/min macros — they collide with std::max/min/clamp
+// used heavily in the rendering math.
+#ifdef max
+#undef max
+#endif
+#ifdef min
+#undef min
+#endif
+#include "xaml-includes.h"
+#include "ExplainPlanVisualizerControl.h"
+#if __has_include("ExplainPlanVisualizerControl.g.cpp")
+#include "ExplainPlanVisualizerControl.g.cpp"
+#endif
+
+#include <winrt/Microsoft.UI.Xaml.Controls.h>
+#include <winrt/Microsoft.UI.Xaml.Media.h>
+#include <winrt/Microsoft.UI.Xaml.Shapes.h>
+#include <winrt/Microsoft.UI.Xaml.Input.h>
+#include <winrt/Windows.UI.h>
+#include <winrt/Windows.UI.Text.h>
+
+#include <algorithm>
+#include <functional>
+#include <iomanip>
+#include <sstream>
+
+namespace winrt::Gridex::implementation
+{
+ namespace EX = ::Gridex::ExplainViz;
+ namespace mux = winrt::Microsoft::UI::Xaml;
+ namespace muxc = winrt::Microsoft::UI::Xaml::Controls;
+ namespace muxm = winrt::Microsoft::UI::Xaml::Media;
+ namespace muxs = winrt::Microsoft::UI::Xaml::Shapes;
+ using winrt::Windows::UI::Color;
+ using winrt::Windows::Foundation::IInspectable;
+ // Thickness lives in Microsoft.UI.Xaml — not in Windows.Foundation
+ // (despite Padding/Margin signatures using the type by struct name).
+
+ // ── Small XAML helpers (mirror cell-builders elsewhere in the codebase) ──
+ static muxc::TextBlock TB(const std::wstring& text, double fontSize, double opacity = 1.0,
+ bool semibold = false)
+ {
+ muxc::TextBlock t;
+ t.Text(winrt::hstring(text));
+ t.FontSize(fontSize);
+ t.Opacity(opacity);
+ if (semibold) t.FontWeight(winrt::Windows::UI::Text::FontWeights::SemiBold());
+ t.IsTextSelectionEnabled(false);
+ return t;
+ }
+
+ static muxc::FontIcon FI(const std::wstring& glyph, double size)
+ {
+ muxc::FontIcon f;
+ f.Glyph(winrt::hstring(glyph));
+ f.FontSize(size);
+ return f;
+ }
+
+ static muxm::SolidColorBrush Brush(Color c)
+ {
+ return muxm::SolidColorBrush(c);
+ }
+
+ // Renamed from MakeColor() — wingdi.h #defines RGB as a macro that would
+ // mangle the function signature.
+ static Color MakeColor(uint8_t r, uint8_t g, uint8_t b)
+ {
+ return Color{ 255, r, g, b };
+ }
+
+ static muxc::Border CardBorder()
+ {
+ muxc::Border b;
+ b.CornerRadius(mux::CornerRadiusHelper::FromRadii(10, 10, 10, 10));
+ b.BorderThickness(mux::Thickness{ 1, 1, 1, 1 });
+ b.Padding(mux::Thickness{ 16, 14, 16, 14 });
+ try {
+ b.Background(unbox_value<muxm::Brush>(
+ mux::Application::Current().Resources().Lookup(
+ box_value(L"LayerFillColorDefaultBrush"))));
+ b.BorderBrush(unbox_value<muxm::Brush>(
+ mux::Application::Current().Resources().Lookup(
+ box_value(L"CardStrokeColorDefaultBrush"))));
+ } catch (...) {}
+ return b;
+ }
+
+ // ── Formatting helpers ──────────────────────────────
+ static std::wstring fmtMs(double ms)
+ {
+ std::wstringstream ss;
+ if (ms >= 10) ss << std::fixed << std::setprecision(0) << ms;
+ else ss << std::fixed << std::setprecision(2) << ms;
+ return ss.str();
+ }
+
+ static std::wstring fmtNum(double n)
+ {
+ // Locale-friendly thousand separator (commas).
+ std::wstringstream ss;
+ ss << static_cast<long long>(n);
+ std::wstring s = ss.str();
+ std::wstring out;
+ int c = 0;
+ for (auto it = s.rbegin(); it != s.rend(); ++it) {
+ if (c && c % 3 == 0 && *it != L'-') out += L',';
+ out += *it;
+ ++c;
+ }
+ std::reverse(out.begin(), out.end());
+ return out;
+ }
+
+ static std::wstring fmtBytes(uint64_t n)
+ {
+ std::wstringstream ss;
+ if (n < 1024) { ss << n << L" B"; }
+ else if (n < 1024*1024) { ss << std::fixed << std::setprecision(1) << (n/1024.0) << L" KB"; }
+ else if (n < 1024ULL*1024*1024) { ss << std::fixed << std::setprecision(2) << (n/(1024.0*1024)) << L" MB"; }
+ else { ss << std::fixed << std::setprecision(2) << (n/(1024.0*1024*1024)) << L" GB"; }
+ return ss.str();
+ }
+
+ ExplainPlanVisualizerControl::ExplainPlanVisualizerControl()
+ {
+ InitializeComponent();
+ }
+
+ // ── Public API ────────────────────────────────────
+ void ExplainPlanVisualizerControl::SetPlan(std::shared_ptr<EX::PlanDocument> doc)
+ {
+ doc_ = doc;
+ if (!doc_ || !doc_->root) {
+ ShowError(L"Plan was empty.");
+ return;
+ }
+ // Run heuristics — may upgrade NodeLevel on the tree.
+ issues_ = EX::ExplainPlanHeuristics::analyze(*doc_);
+ recs_ = EX::ExplainPlanHeuristics::recommend(*doc_, issues_);
+ // Default selection: hottest node (Bad with highest pct), else root.
+ selectedNodeId_.clear();
+ EX::PlanNode* hot = nullptr;
+ std::function<void(EX::PlanNode&)> walk = [&](EX::PlanNode& n) {
+ if (n.level == EX::NodeLevel::Bad &&
+ (!hot || n.pctOfTotal > hot->pctOfTotal)) hot = &n;
+ for (auto& c : n.children) walk(*c);
+ };
+ walk(*doc_->root);
+ selectedNodeId_ = hot ? hot->id : doc_->root->id;
+
+ SwitchState(State::Loaded);
+ RenderInfoBar();
+ RenderMetrics();
+ RenderPlanTree();
+ RenderFlyout();
+ RenderWaterfall();
+ RenderRecommendations();
+ }
+
+ void ExplainPlanVisualizerControl::ShowEmpty() { SwitchState(State::Empty); }
+ void ExplainPlanVisualizerControl::ShowLoading() { SwitchState(State::Loading); }
+ void ExplainPlanVisualizerControl::ShowError(const std::wstring& m)
+ {
+ ErrorText().Text(winrt::hstring(m));
+ SwitchState(State::Error);
+ }
+ void ExplainPlanVisualizerControl::Reset() { doc_.reset(); ShowEmpty(); }
+
+ void ExplainPlanVisualizerControl::SwitchState(State s)
+ {
+ EmptyState().Visibility(s == State::Empty ? mux::Visibility::Visible : mux::Visibility::Collapsed);
+ LoadingState().Visibility(s == State::Loading ? mux::Visibility::Visible : mux::Visibility::Collapsed);
+ ErrorState().Visibility(s == State::Error ? mux::Visibility::Visible : mux::Visibility::Collapsed);
+ LoadedState().Visibility(s == State::Loaded ? mux::Visibility::Visible : mux::Visibility::Collapsed);
+ }
+
+ // ── Click handlers ──────────────────────────────
+ void ExplainPlanVisualizerControl::OnRunClicked(IInspectable const&, mux::RoutedEventArgs const&)
+ {
+ if (OnRunRequested) OnRunRequested();
+ }
+ void ExplainPlanVisualizerControl::OnCopyPlanClicked(IInspectable const&, mux::RoutedEventArgs const&)
+ {
+ if (OnCopyPlanRequested && doc_) OnCopyPlanRequested(doc_->rawJson);
+ }
+ void ExplainPlanVisualizerControl::OnHotOnlyToggled(IInspectable const&, mux::RoutedEventArgs const&)
+ {
+ // IsChecked() can be null on indeterminate state; default false.
+ auto v = HotOnlyToggle().IsChecked();
+ hotOnly_ = v ? v.Value() : false;
+ RenderPlanTree();
+ }
+
+ // ── InfoBar ──────────────────────────────
+ void ExplainPlanVisualizerControl::RenderInfoBar()
+ {
+ if (issues_.empty()) {
+ WarnInfoBar().IsOpen(false);
+ return;
+ }
+ const auto& top = issues_.front();
+ WarnInfoBar().Severity(
+ top.severity == EX::IssueSeverity::Bad ? muxc::InfoBarSeverity::Error :
+ top.severity == EX::IssueSeverity::Warn ? muxc::InfoBarSeverity::Warning :
+ muxc::InfoBarSeverity::Informational);
+ WarnInfoBar().Title(winrt::hstring(top.title));
+ WarnInfoBar().Message(winrt::hstring(top.detail));
+ WarnInfoBar().IsOpen(true);
+ }
+
+ // ── Metrics ──────────────────────────────
+ void ExplainPlanVisualizerControl::RenderMetrics()
+ {
+ if (!doc_ || !doc_->root) return;
+ // Total time
+ double total = doc_->executionMs > 0 ? doc_->executionMs : 0.0;
+ double planning = doc_->planningMs;
+ std::wstring delta = planning > 0
+ ? L"planning " + fmtMs(planning) + L"ms · execution " + fmtMs(total) + L"ms"
+ : L"execution " + fmtMs(total) + L"ms";
+ CardTotalTime().Content(BuildMetricCard(
+ L"" /*clock*/, L"Total time", fmtMs(total), L"ms", delta,
+ std::min(100.0, total / 1000.0 * 50.0), // arbitrary bar 0..100%
+ total > 1000 ? L"bad" : total > 250 ? L"warn" : L"good"));
+
+ // Rows
+ double rowsActual = doc_->root->actualRows;
+ double rowsScanned = 0.0;
+ std::function<void(const EX::PlanNode&)> sumScan = [&](const EX::PlanNode& n) {
+ if (n.kind == EX::NodeKind::SeqScan ||
+ n.kind == EX::NodeKind::IndexScan ||
+ n.kind == EX::NodeKind::IndexOnlyScan ||
+ n.kind == EX::NodeKind::BitmapHeapScan)
+ rowsScanned += n.actualRows + n.rowsRemovedByFilter;
+ for (auto& c : n.children) sumScan(*c);
+ };
+ sumScan(*doc_->root);
+ std::wstring rowsDelta = rowsScanned > 0
+ ? L"selectivity " + fmtMs(rowsActual / rowsScanned * 100) + L"%"
+ : L"";
+ CardRows().Content(BuildMetricCard(
+ L"" /*list*/, L"Rows returned", fmtNum(rowsActual),
+ rowsScanned > 0 ? (L" / " + fmtNum(rowsScanned) + L" scanned") : L"",
+ rowsDelta,
+ rowsScanned > 0 ? std::min(100.0, rowsActual / rowsScanned * 100) : 0.0,
+ L""));
+
+ // Buffers
+ uint64_t totalHit = 0, totalRead = 0;
+ std::function<void(const EX::PlanNode&)> sumBuf = [&](const EX::PlanNode& n) {
+ totalHit += n.sharedHit;
+ totalRead += n.sharedRead;
+ for (auto& c : n.children) sumBuf(*c);
+ };
+ sumBuf(*doc_->root);
+ uint64_t bufBytes = (totalHit + totalRead) * 8ULL * 1024; // 8 KB pages
+ std::wstring bufDelta = std::to_wstring(totalHit) + L" hit · "
+ + std::to_wstring(totalRead) + L" read";
+ CardBuffers().Content(BuildMetricCard(
+ L"" /*memory*/, L"Buffers", fmtBytes(bufBytes), L"", bufDelta,
+ totalRead > 1000 ? 70.0 : 30.0,
+ totalRead > 1000 ? L"warn" : L""));
+
+ // Planner accuracy — biggest est/actual mismatch ratio in tree.
+ double worstFactor = 1.0;
+ std::function<void(const EX::PlanNode&)> walk = [&](const EX::PlanNode& n) {
+ if (n.planRows >= 100 && n.actualRows >= 100) {
+ double f = std::max(n.planRows, n.actualRows) /
+ std::max(1.0, std::min(n.planRows, n.actualRows));
+ if (f > worstFactor) worstFactor = f;
+ }
+ for (auto& c : n.children) walk(*c);
+ };
+ walk(*doc_->root);
+ std::wstringstream accDelta;
+ accDelta << std::fixed << std::setprecision(1) << worstFactor << L"× worst-case error";
+ CardAccuracy().Content(BuildMetricCard(
+ L"" /*target*/, L"Planner accuracy", fmtMs(worstFactor), L"×",
+ accDelta.str(),
+ std::min(100.0, (worstFactor - 1) * 20.0),
+ worstFactor >= 5 ? L"bad" : worstFactor >= 2 ? L"warn" : L"good"));
+
+ // Plan summary header text.
+ int nodeCount = 0;
+ std::function<void(const EX::PlanNode&)> countNodes = [&](const EX::PlanNode& n) {
+ ++nodeCount;
+ for (auto& c : n.children) countNodes(*c);
+ };
+ countNodes(*doc_->root);
+ PlanCountText().Text(winrt::hstring(
+ std::to_wstring(nodeCount) + L" nodes · planner cost "
+ + fmtMs(doc_->root->totalCost)));
+
+ MetaText().Text(winrt::hstring(
+ L"Postgres · execution " + fmtMs(total) + L"ms · planning " + fmtMs(planning) + L"ms"));
+ }
+
+ mux::UIElement ExplainPlanVisualizerControl::BuildMetricCard(
+ const std::wstring& glyph, const std::wstring& label,
+ const std::wstring& value, const std::wstring& unit,
+ const std::wstring& delta, double barPct, const std::wstring& tone)
+ {
+ auto outer = CardBorder();
+ muxc::StackPanel sp;
+ sp.Spacing(8);
+
+ // Header row: glyph + label
+ muxc::StackPanel head;
+ head.Orientation(muxc::Orientation::Horizontal);
+ head.Spacing(6);
+ head.Children().Append(FI(glyph, 14));
+ head.Children().Append(TB(label, 12, 0.7));
+ sp.Children().Append(head);
+
+ // Value + unit
+ muxc::StackPanel vrow;
+ vrow.Orientation(muxc::Orientation::Horizontal);
+ vrow.Spacing(4);
+ vrow.VerticalAlignment(mux::VerticalAlignment::Bottom);
+ auto val = TB(value, 28, 1.0, true);
+ vrow.Children().Append(val);
+ if (!unit.empty()) vrow.Children().Append(TB(unit, 12, 0.6));
+ sp.Children().Append(vrow);
+
+ // Delta line
+ if (!delta.empty()) {
+ auto d = TB(delta, 12, 0.7);
+ if (tone == L"bad") d.Foreground(Brush(MakeColor(196, 43, 28)));
+ else if (tone == L"warn") d.Foreground(Brush(MakeColor(224, 168, 0)));
+ else if (tone == L"good") d.Foreground(Brush(MakeColor(16, 124, 16)));
+ sp.Children().Append(d);
+ }
+
+ // Mini bar
+ muxc::Grid bar;
+ bar.Height(6);
+ bar.CornerRadius(mux::CornerRadiusHelper::FromUniformRadius(3));
+ try {
+ bar.Background(unbox_value<muxm::Brush>(
+ mux::Application::Current().Resources().Lookup(
+ box_value(L"ControlAltFillColorTertiaryBrush"))));
+ } catch (...) {}
+ muxc::Grid fill;
+ fill.HorizontalAlignment(mux::HorizontalAlignment::Left);
+ fill.CornerRadius(mux::CornerRadiusHelper::FromUniformRadius(2));
+ Color c = tone == L"bad" ? MakeColor(196, 43, 28)
+ : tone == L"warn" ? MakeColor(224, 168, 0)
+ : MakeColor(120, 96, 217); // accent
+ fill.Background(Brush(c));
+ // Setting width via percent on a Grid child is tricky — we wrap in
+ // a Border with explicit Width using the parent's actual size on
+ // first SizeChanged. For static design we approximate using a
+ // fixed-width container scaled by barPct% of card content width.
+ // Position the fill on initial layout AND on every resize so the
+ // bar is non-empty before the parent grid first measures it.
+ auto sizeFill = [fill, barPct](double w) {
+ fill.Width(std::max(2.0, w * std::clamp(barPct, 0.0, 100.0) / 100.0));
+ };
+ bar.SizeChanged([sizeFill](IInspectable const&, mux::SizeChangedEventArgs const& e) {
+ sizeFill(e.NewSize().Width);
+ });
+ bar.Loaded([bar, sizeFill](IInspectable const&, mux::RoutedEventArgs const&) {
+ sizeFill(bar.ActualWidth());
+ });
+ bar.Children().Append(fill);
+ sp.Children().Append(bar);
+
+ outer.Child(sp);
+ return outer;
+ }
+
+ // ── Plan tree ──────────────────────────────
+ std::shared_ptr<EX::PlanNode> ExplainPlanVisualizerControl::FindNode(
+ const std::shared_ptr<EX::PlanNode>& n, const std::wstring& id)
+ {
+ if (!n) return nullptr;
+ if (n->id == id) return n;
+ for (auto& c : n->children) {
+ if (auto r = FindNode(c, id)) return r;
+ }
+ return nullptr;
+ }
+
+ void ExplainPlanVisualizerControl::RenderPlanTree()
+ {
+ PlanTreeContainer().Children().Clear();
+ if (!doc_ || !doc_->root) return;
+ BuildNodeRow(doc_->root, 0);
+ }
+
+ void ExplainPlanVisualizerControl::BuildNodeRow(
+ const std::shared_ptr<EX::PlanNode>& node, int depth)
+ {
+ if (!node) return;
+ // Hot-only filter: skip nodes that aren't Bad/Warn unless they have
+ // a hot descendant (we still need to descend).
+ bool isHot = node->level != EX::NodeLevel::Good;
+ bool hasHotChild = false;
+ std::function<void(const EX::PlanNode&)> findHot = [&](const EX::PlanNode& n) {
+ if (n.level != EX::NodeLevel::Good) hasHotChild = true;
+ for (auto& c : n.children) findHot(*c);
+ };
+ findHot(*node);
+
+ bool include = (!hotOnly_) || isHot || hasHotChild;
+ if (!include) return;
+
+ // Row layout: indent | glyph | body | heat
+ muxc::Grid row;
+ row.Padding(mux::Thickness{ 8.0 + depth * 18.0, 6, 8, 6 });
+ row.HorizontalAlignment(mux::HorizontalAlignment::Stretch);
+ muxc::ColumnDefinition c0; c0.Width(mux::GridLengthHelper::Auto());
+ muxc::ColumnDefinition c1; c1.Width(mux::GridLengthHelper::FromValueAndType(1, mux::GridUnitType::Star));
+ muxc::ColumnDefinition c2; c2.Width(mux::GridLengthHelper::Auto());
+ row.ColumnDefinitions().Append(c0);
+ row.ColumnDefinitions().Append(c1);
+ row.ColumnDefinitions().Append(c2);
+
+ // Selection highlight
+ if (node->id == selectedNodeId_) {
+ try {
+ row.Background(unbox_value<muxm::Brush>(
+ mux::Application::Current().Resources().Lookup(
+ box_value(L"AccentFillColorTertiaryBrush"))));
+ } catch (...) {}
+ }
+ row.CornerRadius(mux::CornerRadiusHelper::FromUniformRadius(6));
+
+ // Glyph badge
+ muxc::Border g;
+ g.Width(34); g.Height(28);
+ g.CornerRadius(mux::CornerRadiusHelper::FromUniformRadius(5));
+ g.Padding(mux::Thickness{ 4, 2, 4, 2 });
+ g.Margin(mux::Thickness{ 0, 0, 10, 0 });
+ g.VerticalAlignment(mux::VerticalAlignment::Center);
+ g.Background(Brush(HeatBgColor(node->level)));
+ auto gtxt = TB(KindGlyph(node->kind), 13, 1.0, true);
+ gtxt.HorizontalAlignment(mux::HorizontalAlignment::Center);
+ gtxt.VerticalAlignment(mux::VerticalAlignment::Center);
+ gtxt.Foreground(Brush(HeatColor(node->level)));
+ g.Child(gtxt);
+ muxc::Grid::SetColumn(g, 0);
+ row.Children().Append(g);
+
+ // Body — op + relation + detail + cost line
+ muxc::StackPanel body;
+ body.Spacing(2);
+ muxc::StackPanel headRow;
+ headRow.Orientation(muxc::Orientation::Horizontal);
+ headRow.Spacing(8);
+ auto opTxt = TB(node->op, 14, 1.0, true);
+ headRow.Children().Append(opTxt);
+ if (!node->relation.empty()) {
+ std::wstring relText = node->relation;
+ if (!node->alias.empty()) relText += L" " + node->alias;
+ auto rel = TB(relText, 13, 0.85);
+ try {
+ rel.FontFamily(muxm::FontFamily(L"Cascadia Code, Consolas, monospace"));
+ } catch (...) {}
+ headRow.Children().Append(rel);
+ }
+ if (node->level == EX::NodeLevel::Bad) {
+ muxc::Border pill;
+ pill.CornerRadius(mux::CornerRadiusHelper::FromUniformRadius(8));
+ pill.Padding(mux::Thickness{ 6, 1, 6, 1 });
+ pill.Background(Brush(MakeColor(253, 231, 233)));
+ auto pt = TB(L"hot path", 10, 1.0);
+ pt.Foreground(Brush(MakeColor(196, 43, 28)));
+ pill.Child(pt);
+ headRow.Children().Append(pill);
+ } else if (node->level == EX::NodeLevel::Warn) {
+ muxc::Border pill;
+ pill.CornerRadius(mux::CornerRadiusHelper::FromUniformRadius(8));
+ pill.Padding(mux::Thickness{ 6, 1, 6, 1 });
+ pill.Background(Brush(MakeColor(255, 244, 206)));
+ auto pt = TB(L"watch", 10, 1.0);
+ pt.Foreground(Brush(MakeColor(138, 109, 0)));
+ pill.Child(pt);
+ headRow.Children().Append(pill);
+ }
+ body.Children().Append(headRow);
+
+ if (!node->detail.empty()) {
+ auto d = TB(node->detail, 12, 0.7);
+ d.TextWrapping(mux::TextWrapping::NoWrap);
+ d.TextTrimming(mux::TextTrimming::CharacterEllipsis);
+ body.Children().Append(d);
+ }
+
+ // Cost / rows / actual line
+ std::wstringstream cost;
+ cost << L"cost " << std::fixed << std::setprecision(2) << node->startupCost
+ << L"…" << std::fixed << std::setprecision(2) << node->totalCost
+ << L" · rows " << fmtNum(node->actualRows)
+ << L" · width " << node->planWidth;
+ if (node->analyzed) {
+ cost << L" · actual " << fmtMs(node->actualTotal) << L" ms";
+ if (node->actualLoops > 1) cost << L" × " << node->actualLoops << L" loops";
+ }
+ auto costTxt = TB(cost.str(), 12, 0.6);
+ try {
+ costTxt.FontFamily(muxm::FontFamily(L"Cascadia Code, Consolas, monospace"));
+ } catch (...) {}
+ body.Children().Append(costTxt);
+
+ muxc::Grid::SetColumn(body, 1);
+ row.Children().Append(body);
+
+ // Heat bar
+ muxc::StackPanel heat;
+ heat.Width(140);
+ heat.Spacing(4);
+ heat.VerticalAlignment(mux::VerticalAlignment::Center);
+ std::wstringstream pctTxt;
+ pctTxt << std::fixed << std::setprecision(1) << node->pctOfTotal << L"%";
+ auto pct = TB(pctTxt.str(), 13, 1.0, true);
+ pct.HorizontalAlignment(mux::HorizontalAlignment::Right);
+ pct.Foreground(Brush(HeatColor(node->level)));
+ heat.Children().Append(pct);
+ muxc::Grid hbar;
+ hbar.Height(7);
+ hbar.CornerRadius(mux::CornerRadiusHelper::FromUniformRadius(2));
+ try {
+ hbar.Background(unbox_value<muxm::Brush>(
+ mux::Application::Current().Resources().Lookup(
+ box_value(L"ControlAltFillColorTertiaryBrush"))));
+ } catch (...) {}
+ muxc::Grid hfill;
+ hfill.HorizontalAlignment(mux::HorizontalAlignment::Left);
+ hfill.CornerRadius(mux::CornerRadiusHelper::FromUniformRadius(2));
+ hfill.Background(Brush(HeatColor(node->level)));
+ double pctFill = std::max(2.0, std::min(100.0, node->pctOfTotal));
+ auto sizeHFill = [hfill, pctFill](double w) {
+ hfill.Width(std::max(2.0, w * pctFill / 100.0));
+ };
+ hbar.SizeChanged([sizeHFill](IInspectable const&, mux::SizeChangedEventArgs const& e) {
+ sizeHFill(e.NewSize().Width);
+ });
+ hbar.Loaded([hbar, sizeHFill](IInspectable const&, mux::RoutedEventArgs const&) {
+ sizeHFill(hbar.ActualWidth());
+ });
+ hbar.Children().Append(hfill);
+ heat.Children().Append(hbar);
+ muxc::Grid::SetColumn(heat, 2);
+ row.Children().Append(heat);
+
+ // Click → select
+ std::wstring nid = node->id;
+ row.PointerReleased([this, nid](IInspectable const&, auto const&) {
+ SelectNode(nid);
+ });
+ row.PointerEntered([row](IInspectable const&, auto const&) {
+ try {
+ row.Background(unbox_value<muxm::Brush>(
+ mux::Application::Current().Resources().Lookup(
+ box_value(L"ControlFillColorSecondaryBrush"))));
+ } catch (...) {}
+ });
+ PlanTreeContainer().Children().Append(row);
+
+ // Children — recurse.
+ for (auto& c : node->children) BuildNodeRow(c, depth + 1);
+ }
+
+ void ExplainPlanVisualizerControl::SelectNode(const std::wstring& id)
+ {
+ if (id == selectedNodeId_) return;
+ selectedNodeId_ = id;
+ RenderPlanTree();
+ RenderFlyout();
+ }
+
+ // ── Flyout ──────────────────────────────
+ void ExplainPlanVisualizerControl::RenderFlyout()
+ {
+ FlyoutContainer().Children().Clear();
+ if (!doc_) return;
+ auto node = FindNode(doc_->root, selectedNodeId_);
+ if (!node) node = doc_->root;
+
+ // Header
+ muxc::StackPanel head;
+ head.Orientation(muxc::Orientation::Horizontal);
+ head.Spacing(10);
+ muxc::Border g;
+ g.Width(42); g.Height(36);
+ g.CornerRadius(mux::CornerRadiusHelper::FromUniformRadius(7));
+ g.Background(Brush(HeatBgColor(node->level)));
+ auto gtxt = TB(KindGlyph(node->kind), 16, 1.0, true);
+ gtxt.HorizontalAlignment(mux::HorizontalAlignment::Center);
+ gtxt.VerticalAlignment(mux::VerticalAlignment::Center);
+ gtxt.Foreground(Brush(HeatColor(node->level)));
+ g.Child(gtxt);
+ head.Children().Append(g);
+
+ muxc::StackPanel ht;
+ std::wstring title = node->op;
+ if (!node->relation.empty()) title += L" · " + node->relation;
+ ht.Children().Append(TB(title, 16, 1.0, true));
+ if (!node->detail.empty()) {
+ auto d = TB(node->detail, 12, 0.7);
+ d.TextWrapping(mux::TextWrapping::Wrap);
+ ht.Children().Append(d);
+ }
+ head.Children().Append(ht);
+ FlyoutContainer().Children().Append(head);
+
+ // Section helper — title + key/value grid
+ auto section = [&](const std::wstring& title, std::vector<std::pair<std::wstring, std::wstring>> kv) {
+ muxc::StackPanel s; s.Spacing(4); s.Margin(mux::Thickness{ 0, 8, 0, 0 });
+ auto t = TB(title, 12, 0.55, true);
+ s.Children().Append(t);
+ for (auto& [k, v] : kv) {
+ muxc::Grid row; row.Padding(mux::Thickness{ 0, 3, 0, 3 });
+ muxc::ColumnDefinition c1; c1.Width(mux::GridLengthHelper::FromValueAndType(120, mux::GridUnitType::Pixel));
+ muxc::ColumnDefinition c2; c2.Width(mux::GridLengthHelper::FromValueAndType(1, mux::GridUnitType::Star));
+ row.ColumnDefinitions().Append(c1);
+ row.ColumnDefinitions().Append(c2);
+ auto kt = TB(k, 12, 0.55);
+ muxc::Grid::SetColumn(kt, 0);
+ row.Children().Append(kt);
+ auto vt = TB(v, 13, 0.95);
+ vt.TextWrapping(mux::TextWrapping::Wrap);
+ muxc::Grid::SetColumn(vt, 1);
+ row.Children().Append(vt);
+ s.Children().Append(row);
+ }
+ FlyoutContainer().Children().Append(s);
+ };
+
+ std::wstringstream pct; pct << std::fixed << std::setprecision(1) << node->pctOfTotal << L"%";
+ section(L"TIMING", {
+ { L"Startup cost", fmtMs(node->startupCost) },
+ { L"Total cost", fmtMs(node->totalCost) },
+ { L"Actual time", fmtMs(node->actualTotal) + L" ms" },
+ { L"Loops", std::to_wstring(node->actualLoops) },
+ { L"% of total", pct.str() },
+ });
+
+ std::wstring estErr = L"—";
+ if (node->planRows >= 1 && node->actualRows >= 1) {
+ double f = std::max(node->planRows, node->actualRows) /
+ std::max(1.0, std::min(node->planRows, node->actualRows));
+ std::wstringstream s;
+ s << std::fixed << std::setprecision(1) << f << L"× "
+ << (node->actualRows > node->planRows ? L"under" : L"over");
+ estErr = s.str();
+ }
+ section(L"ROWS", {
+ { L"Estimated", fmtNum(node->planRows) },
+ { L"Actual", fmtNum(node->actualRows) },
+ { L"Estimation error", estErr },
+ { L"Rows removed by filter", fmtNum(node->rowsRemovedByFilter) },
+ { L"Width", std::to_wstring(node->planWidth) + L" bytes" },
+ });
+
+ if (node->sharedHit > 0 || node->sharedRead > 0 || node->tempRead > 0 || node->tempWritten > 0) {
+ section(L"BUFFERS", {
+ { L"Shared hit", fmtNum(node->sharedHit) + L" blocks" },
+ { L"Shared read", fmtNum(node->sharedRead) + L" blocks" },
+ { L"Shared dirtied", fmtNum(node->sharedDirtied) },
+ { L"Temp read", fmtNum(node->tempRead) },
+ { L"Temp written", fmtNum(node->tempWritten) },
+ });
+ }
+
+ if (!node->outputCols.empty()) {
+ muxc::StackPanel s; s.Spacing(4); s.Margin(mux::Thickness{ 0, 8, 0, 0 });
+ s.Children().Append(TB(L"OUTPUT", 11, 0.55, true));
+ muxc::StackPanel chips;
+ chips.Orientation(muxc::Orientation::Horizontal);
+ chips.Spacing(4);
+ for (size_t i = 0; i < node->outputCols.size() && i < 12; ++i) {
+ muxc::Border chip;
+ chip.CornerRadius(mux::CornerRadiusHelper::FromUniformRadius(8));
+ chip.Padding(mux::Thickness{ 6, 2, 6, 2 });
+ try {
+ chip.Background(unbox_value<muxm::Brush>(
+ mux::Application::Current().Resources().Lookup(
+ box_value(L"ControlFillColorSecondaryBrush"))));
+ } catch (...) {}
+ chip.Child(TB(node->outputCols[i], 10, 0.85));
+ chips.Children().Append(chip);
+ }
+ s.Children().Append(chips);
+ FlyoutContainer().Children().Append(s);
+ }
+ }
+
+ // ── Waterfall ──────────────────────────────
+ void ExplainPlanVisualizerControl::RenderWaterfall()
+ {
+ WaterfallContainer().Children().Clear();
+ if (!doc_) return;
+
+ // Build a flat sequence of leaves + their parents, in execution
+ // order (post-order DFS = children before parents). Track cumulative
+ // start time per node by summing previous siblings' durations.
+ struct Step { std::wstring label, glyph; std::wstring cls;
+ double startMs, durMs; EX::NodeLevel level; };
+ std::vector<Step> seq;
+ double cursor = 0.0;
+
+ std::function<void(const EX::PlanNode&)> walk = [&](const EX::PlanNode& n) {
+ // Children execute first in PG plan model.
+ double childrenSum = 0.0;
+ for (auto& c : n.children) {
+ walk(*c);
+ childrenSum += c->actualTotal * c->actualLoops;
+ }
+ double dur = std::max(0.0, n.actualTotal * n.actualLoops - childrenSum);
+ std::wstring label = n.op + (n.relation.empty() ? L"" : L" · " + n.relation);
+ seq.push_back({ label, KindGlyph(n.kind), KindClass(n.kind),
+ cursor, dur, n.level });
+ cursor += dur;
+ };
+ walk(*doc_->root);
+
+ double maxMs = std::max(1.0, doc_->executionMs);
+
+ // Axis row
+ muxc::Grid axis;
+ axis.Padding(mux::Thickness{ 0, 0, 0, 4 });
+ muxc::ColumnDefinition a0; a0.Width(mux::GridLengthHelper::FromValueAndType(220, mux::GridUnitType::Pixel));
+ muxc::ColumnDefinition a1; a1.Width(mux::GridLengthHelper::FromValueAndType(1, mux::GridUnitType::Star));
+ muxc::ColumnDefinition a2; a2.Width(mux::GridLengthHelper::FromValueAndType(70, mux::GridUnitType::Pixel));
+ axis.ColumnDefinitions().Append(a0);
+ axis.ColumnDefinitions().Append(a1);
+ axis.ColumnDefinitions().Append(a2);
+ auto t1 = TB(L"Node", 10, 0.5);
+ muxc::Grid::SetColumn(t1, 0);
+ axis.Children().Append(t1);
+ // Tick row
+ muxc::Grid ticks;
+ for (int i = 0; i <= 4; ++i) {
+ auto tick = TB(fmtMs(maxMs * i / 4) + L" ms", 10, 0.5);
+ tick.HorizontalAlignment(i == 0 ? mux::HorizontalAlignment::Left
+ : i == 4 ? mux::HorizontalAlignment::Right
+ : mux::HorizontalAlignment::Center);
+ muxc::ColumnDefinition cd;
+ cd.Width(mux::GridLengthHelper::FromValueAndType(1, mux::GridUnitType::Star));
+ ticks.ColumnDefinitions().Append(cd);
+ muxc::Grid::SetColumn(tick, i);
+ ticks.Children().Append(tick);
+ }
+ muxc::Grid::SetColumn(ticks, 1);
+ axis.Children().Append(ticks);
+ auto t3 = TB(L"Duration", 10, 0.5);
+ t3.HorizontalAlignment(mux::HorizontalAlignment::Right);
+ muxc::Grid::SetColumn(t3, 2);
+ axis.Children().Append(t3);
+ WaterfallContainer().Children().Append(axis);
+
+ for (auto& s : seq) {
+ WaterfallContainer().Children().Append(BuildWaterfallRow(
+ s.label, s.glyph, s.cls, s.startMs, s.durMs, maxMs, s.level));
+ }
+ }
+
+ mux::UIElement ExplainPlanVisualizerControl::BuildWaterfallRow(
+ const std::wstring& label, const std::wstring& glyph, const std::wstring& glyphCls,
+ double startMs, double durMs, double maxMs, EX::NodeLevel level)
+ {
+ muxc::Grid row;
+ muxc::ColumnDefinition c0; c0.Width(mux::GridLengthHelper::FromValueAndType(220, mux::GridUnitType::Pixel));
+ muxc::ColumnDefinition c1; c1.Width(mux::GridLengthHelper::FromValueAndType(1, mux::GridUnitType::Star));
+ muxc::ColumnDefinition c2; c2.Width(mux::GridLengthHelper::FromValueAndType(70, mux::GridUnitType::Pixel));
+ row.ColumnDefinitions().Append(c0);
+ row.ColumnDefinitions().Append(c1);
+ row.ColumnDefinitions().Append(c2);
+ row.Padding(mux::Thickness{ 0, 3, 0, 3 });
+
+ // Name
+ muxc::StackPanel name;
+ name.Orientation(muxc::Orientation::Horizontal);
+ name.Spacing(6);
+ name.VerticalAlignment(mux::VerticalAlignment::Center);
+ muxc::Border g;
+ g.Width(24); g.Height(20);
+ g.CornerRadius(mux::CornerRadiusHelper::FromUniformRadius(4));
+ g.Background(Brush(HeatBgColor(level)));
+ auto gt = TB(glyph, 10, 1.0, true);
+ gt.HorizontalAlignment(mux::HorizontalAlignment::Center);
+ gt.VerticalAlignment(mux::VerticalAlignment::Center);
+ gt.Foreground(Brush(HeatColor(level)));
+ g.Child(gt);
+ name.Children().Append(g);
+ auto lt = TB(label, 11, 0.85);
+ lt.TextTrimming(mux::TextTrimming::CharacterEllipsis);
+ name.Children().Append(lt);
+ muxc::Grid::SetColumn(name, 0);
+ row.Children().Append(name);
+
+ // Track
+ muxc::Grid track;
+ track.Height(16);
+ track.CornerRadius(mux::CornerRadiusHelper::FromUniformRadius(3));
+ try {
+ track.Background(unbox_value<muxm::Brush>(
+ mux::Application::Current().Resources().Lookup(
+ box_value(L"ControlAltFillColorTertiaryBrush"))));
+ } catch (...) {}
+ track.VerticalAlignment(mux::VerticalAlignment::Center);
+ muxc::Grid::SetColumn(track, 1);
+
+ muxc::Grid bar;
+ bar.Height(10);
+ bar.HorizontalAlignment(mux::HorizontalAlignment::Left);
+ bar.VerticalAlignment(mux::VerticalAlignment::Center);
+ bar.CornerRadius(mux::CornerRadiusHelper::FromUniformRadius(2));
+ bar.Background(Brush(HeatColor(level)));
+ double startFrac = std::clamp(startMs / maxMs, 0.0, 1.0);
+ double durFrac = std::clamp(durMs / maxMs, 0.001, 1.0);
+ auto sizeBar = [bar, startFrac, durFrac](double w) {
+ bar.Margin(mux::Thickness{ w * startFrac, 0, 0, 0 });
+ bar.Width(std::max(2.0, w * durFrac));
+ };
+ track.SizeChanged([sizeBar](IInspectable const&, mux::SizeChangedEventArgs const& e) {
+ sizeBar(e.NewSize().Width);
+ });
+ track.Loaded([track, sizeBar](IInspectable const&, mux::RoutedEventArgs const&) {
+ sizeBar(track.ActualWidth());
+ });
+ track.Children().Append(bar);
+ row.Children().Append(track);
+
+ // Duration text
+ auto d = TB(fmtMs(durMs) + L" ms", 11, 0.85);
+ d.HorizontalAlignment(mux::HorizontalAlignment::Right);
+ d.VerticalAlignment(mux::VerticalAlignment::Center);
+ muxc::Grid::SetColumn(d, 2);
+ row.Children().Append(d);
+ return row;
+ }
+
+ // ── Recommendations ──────────────────────────────
+ void ExplainPlanVisualizerControl::RenderRecommendations()
+ {
+ RecsContainer().Children().Clear();
+ if (recs_.empty()) {
+ auto empty = TB(L"No tuning suggestions — the planner looks healthy.", 12, 0.55);
+ empty.Margin(mux::Thickness{ 4, 6, 0, 0 });
+ RecsContainer().Children().Append(empty);
+ return;
+ }
+ for (auto& r : recs_) {
+ RecsContainer().Children().Append(BuildRecCard(r));
+ }
+ }
+
+ mux::UIElement ExplainPlanVisualizerControl::BuildRecCard(const EX::Recommendation& r)
+ {
+ auto card = CardBorder();
+ // Severity tone — left-edge accent.
+ Color tone =
+ r.severity == EX::IssueSeverity::Bad ? MakeColor(196, 43, 28) :
+ r.severity == EX::IssueSeverity::Warn ? MakeColor(224, 168, 0) :
+ MakeColor(120, 96, 217);
+ card.BorderBrush(Brush(tone));
+ card.BorderThickness(mux::Thickness{ 4, 1, 1, 1 });
+
+ muxc::Grid grid;
+ muxc::ColumnDefinition c1; c1.Width(mux::GridLengthHelper::FromValueAndType(1, mux::GridUnitType::Star));
+ muxc::ColumnDefinition c2; c2.Width(mux::GridLengthHelper::Auto());
+ grid.ColumnDefinitions().Append(c1);
+ grid.ColumnDefinitions().Append(c2);
+
+ muxc::StackPanel left;
+ left.Spacing(3);
+ left.Children().Append(TB(r.title, 13, 1.0, true));
+ left.Children().Append(TB(r.rationale, 11, 0.65));
+ if (!r.previewSql.empty()) {
+ auto sql = TB(r.previewSql, 11, 0.85);
+ try {
+ sql.FontFamily(muxm::FontFamily(L"Cascadia Code, Consolas, monospace"));
+ } catch (...) {}
+ sql.Margin(mux::Thickness{ 0, 4, 0, 0 });
+ left.Children().Append(sql);
+ }
+ muxc::Grid::SetColumn(left, 0);
+ grid.Children().Append(left);
+
+ muxc::StackPanel actions;
+ actions.Orientation(muxc::Orientation::Horizontal);
+ actions.Spacing(6);
+ actions.VerticalAlignment(mux::VerticalAlignment::Center);
+ muxc::Button preview;
+ preview.Content(box_value(L"Preview SQL"));
+ std::wstring sqlCopy = r.previewSql;
+ preview.Click([this, sqlCopy](IInspectable const&, mux::RoutedEventArgs const&) {
+ if (OnPreviewSqlRequested) OnPreviewSqlRequested(sqlCopy);
+ });
+ actions.Children().Append(preview);
+ muxc::Grid::SetColumn(actions, 1);
+ grid.Children().Append(actions);
+
+ card.Child(grid);
+ return card;
+ }
+
+ // ── Glyph + color helpers ──────────────────────────────
+ Color ExplainPlanVisualizerControl::HeatColor(EX::NodeLevel l)
+ {
+ switch (l) {
+ case EX::NodeLevel::Bad: return MakeColor(196, 43, 28);
+ case EX::NodeLevel::Warn: return MakeColor(138, 109, 0);
+ default: return MakeColor(16, 124, 16);
+ }
+ }
+ Color ExplainPlanVisualizerControl::HeatBgColor(EX::NodeLevel l)
+ {
+ switch (l) {
+ case EX::NodeLevel::Bad: return MakeColor(253, 231, 233);
+ case EX::NodeLevel::Warn: return MakeColor(255, 244, 206);
+ default: return MakeColor(230, 244, 230);
+ }
+ }
+ std::wstring ExplainPlanVisualizerControl::KindGlyph(EX::NodeKind k)
+ {
+ switch (k) {
+ case EX::NodeKind::Limit: return L"L";
+ case EX::NodeKind::Sort: return L"↧"; // ↧
+ case EX::NodeKind::HashJoin: return L"⋈"; // ⋈
+ case EX::NodeKind::MergeJoin: return L"⋈";
+ case EX::NodeKind::NestedLoop: return L"NL";
+ case EX::NodeKind::SeqScan: return L"SS";
+ case EX::NodeKind::IndexScan: return L"IX";
+ case EX::NodeKind::IndexOnlyScan:return L"IO";
+ case EX::NodeKind::BitmapHeapScan:return L"BH";
+ case EX::NodeKind::BitmapIndexScan:return L"BI";
+ case EX::NodeKind::Hash: return L"#";
+ case EX::NodeKind::Aggregate: return L"Σ"; // Σ
+ case EX::NodeKind::GroupAggregate:return L"Σ";
+ case EX::NodeKind::HashAggregate:return L"Σ";
+ case EX::NodeKind::WindowAgg: return L"W";
+ case EX::NodeKind::Materialize: return L"M";
+ case EX::NodeKind::Gather: return L"G";
+ case EX::NodeKind::GatherMerge: return L"GM";
+ case EX::NodeKind::Append: return L"+";
+ case EX::NodeKind::Result: return L"R";
+ case EX::NodeKind::SubqueryScan: return L"SQ";
+ case EX::NodeKind::CteScan: return L"CT";
+ case EX::NodeKind::Unique: return L"U";
+ case EX::NodeKind::Memoize: return L"≡"; // ≡
+ default: return L"·";
+ }
+ }
+ std::wstring ExplainPlanVisualizerControl::KindClass(EX::NodeKind k)
+ {
+ switch (k) {
+ case EX::NodeKind::SeqScan: return L"seq";
+ case EX::NodeKind::IndexScan:
+ case EX::NodeKind::IndexOnlyScan:
+ case EX::NodeKind::BitmapHeapScan:
+ case EX::NodeKind::BitmapIndexScan: return L"idx";
+ case EX::NodeKind::HashJoin:
+ case EX::NodeKind::MergeJoin:
+ case EX::NodeKind::NestedLoop: return L"join";
+ case EX::NodeKind::Sort: return L"sort";
+ case EX::NodeKind::Hash:
+ case EX::NodeKind::Aggregate:
+ case EX::NodeKind::GroupAggregate:
+ case EX::NodeKind::HashAggregate:return L"agg";
+ default: return L"";
+ }
+ }
+}
diff --git a/windows/Gridex/ExplainVisualizer/ExplainPlanVisualizerControl.h b/windows/Gridex/ExplainVisualizer/ExplainPlanVisualizerControl.h
new file mode 100644
index 0000000..d86220c
--- /dev/null
+++ b/windows/Gridex/ExplainVisualizer/ExplainPlanVisualizerControl.h
@@ -0,0 +1,121 @@
+#pragma once
+// Native WinUI 3 visualizer for Postgres EXPLAIN ANALYZE plans. Lives
+// inside the QueryEditorView's results-panel "Visualize" tab. The
+// control owns its own state (empty / loading / loaded / error) and
+// expects the host to drive the EXPLAIN execution via the OnRunRequested
+// callback then push the resulting JSON via SetPlan / ShowError.
+
+#include "ExplainPlanVisualizerControl.g.h"
+#include "ExplainPlanTypes.h"
+#include "ExplainPlanHeuristics.h"
+
+#include <functional>
+#include <memory>
+#include <string>
+#include <vector>
+
+namespace winrt::Gridex::implementation
+{
+ struct ExplainPlanVisualizerControl : ExplainPlanVisualizerControlT<ExplainPlanVisualizerControl>
+ {
+ ExplainPlanVisualizerControl();
+
+ // Push a parsed plan and render. Switches to LoadedState.
+ void SetPlan(std::shared_ptr<::Gridex::ExplainViz::PlanDocument> doc);
+
+ // Show empty state (no plan run yet).
+ void ShowEmpty();
+
+ // Show progress while EXPLAIN runs.
+ void ShowLoading();
+
+ // Show error message.
+ void ShowError(const std::wstring& message);
+
+ // Reset to empty (used when query tab switches — last plan is stale).
+ // Cheap to call repeatedly; only re-renders when transitioning state.
+ void Reset();
+
+ // ── Host callbacks ──────────────────────────────
+ // Fired when the user clicks "Run with Explain Analyze" or "Re-run".
+ std::function<void()> OnRunRequested;
+ // User clicked "Preview SQL" on a recommendation — host opens it
+ // in a new query tab.
+ std::function<void(std::wstring sql)> OnPreviewSqlRequested;
+ // User clicked Copy plan — host writes raw JSON to clipboard
+ // (we send the cached doc.rawJson).
+ std::function<void(std::wstring rawJson)> OnCopyPlanRequested;
+
+ // ── XAML event handlers (bound from .xaml) ──────
+ void OnRunClicked(
+ winrt::Windows::Foundation::IInspectable const& sender,
+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);
+ void OnCopyPlanClicked(
+ winrt::Windows::Foundation::IInspectable const& sender,
+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);
+ void OnHotOnlyToggled(
+ winrt::Windows::Foundation::IInspectable const& sender,
+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);
+
+ private:
+ std::shared_ptr<::Gridex::ExplainViz::PlanDocument> doc_;
+ std::vector<::Gridex::ExplainViz::Issue> issues_;
+ std::vector<::Gridex::ExplainViz::Recommendation> recs_;
+ std::wstring selectedNodeId_;
+ bool hotOnly_ = false;
+
+ enum class State { Empty, Loading, Loaded, Error };
+ void SwitchState(State s);
+
+ // Render passes — invoked from SetPlan in order.
+ void RenderInfoBar();
+ void RenderMetrics();
+ void RenderPlanTree();
+ void RenderFlyout();
+ void RenderWaterfall();
+ void RenderRecommendations();
+
+ // Recursively build a node row for the plan tree. `depth` controls
+ // indentation; `parentExpanded` lets us pre-collapse via the toggle.
+ void BuildNodeRow(
+ const std::shared_ptr<::Gridex::ExplainViz::PlanNode>& node,
+ int depth);
+
+ // Helpers
+ winrt::Microsoft::UI::Xaml::UIElement BuildMetricCard(
+ const std::wstring& glyph,
+ const std::wstring& label,
+ const std::wstring& value,
+ const std::wstring& unit,
+ const std::wstring& delta,
+ double barPct,
+ const std::wstring& tone /* "good"|"warn"|"bad"|"" */);
+ winrt::Microsoft::UI::Xaml::UIElement BuildRecCard(
+ const ::Gridex::ExplainViz::Recommendation& r);
+ winrt::Microsoft::UI::Xaml::UIElement BuildWaterfallRow(
+ const std::wstring& label,
+ const std::wstring& glyph,
+ const std::wstring& glyphCls,
+ double startMs, double durMs, double maxMs,
+ ::Gridex::ExplainViz::NodeLevel level);
+
+ // Theme-aware accent colors for heat/glyph badges.
+ winrt::Windows::UI::Color HeatColor(::Gridex::ExplainViz::NodeLevel l);
+ winrt::Windows::UI::Color HeatBgColor(::Gridex::ExplainViz::NodeLevel l);
+ std::wstring KindGlyph(::Gridex::ExplainViz::NodeKind k);
+ std::wstring KindClass(::Gridex::ExplainViz::NodeKind k);
+
+ // Rebuilds + re-selects when user clicks a node.
+ void SelectNode(const std::wstring& id);
+
+ // Walk plan to find node by id.
+ std::shared_ptr<::Gridex::ExplainViz::PlanNode> FindNode(
+ const std::shared_ptr<::Gridex::ExplainViz::PlanNode>& n,
+ const std::wstring& id);
+ };
+}
+namespace winrt::Gridex::factory_implementation
+{
+ struct ExplainPlanVisualizerControl
+ : ExplainPlanVisualizerControlT<ExplainPlanVisualizerControl, implementation::ExplainPlanVisualizerControl> {};
+}
diff --git a/windows/Gridex/ExplainVisualizer/ExplainPlanVisualizerControl.idl b/windows/Gridex/ExplainVisualizer/ExplainPlanVisualizerControl.idl
new file mode 100644
index 0000000..11ae3d6
--- /dev/null
+++ b/windows/Gridex/ExplainVisualizer/ExplainPlanVisualizerControl.idl
@@ -0,0 +1,8 @@
+namespace Gridex
+{
+ [default_interface]
+ runtimeclass ExplainPlanVisualizerControl : Microsoft.UI.Xaml.Controls.UserControl
+ {
+ ExplainPlanVisualizerControl();
+ }
+}
diff --git a/windows/Gridex/ExplainVisualizer/ExplainPlanVisualizerControl.xaml b/windows/Gridex/ExplainVisualizer/ExplainPlanVisualizerControl.xaml
new file mode 100644
index 0000000..dd8d215
--- /dev/null
+++ b/windows/Gridex/ExplainVisualizer/ExplainPlanVisualizerControl.xaml
@@ -0,0 +1,206 @@
+<?xml version="1.0" encoding="utf-8"?>
+<UserControl
+ x:Class="Gridex.ExplainPlanVisualizerControl"
+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+ xmlns:controls="using:Microsoft.UI.Xaml.Controls">
+
+ <Grid>
+ <!-- ── Empty state: no plan loaded yet ─────────────────────── -->
+ <Grid x:Name="EmptyState"
+ Background="{ThemeResource LayerFillColorDefaultBrush}">
+ <StackPanel HorizontalAlignment="Center"
+ VerticalAlignment="Center"
+ MaxWidth="520" Spacing="12">
+ <FontIcon Glyph="&#xE9D9;" FontSize="36" Opacity="0.55"/>
+ <TextBlock Text="Visualize execution plan"
+ FontSize="18" FontWeight="SemiBold"
+ HorizontalAlignment="Center"/>
+ <TextBlock TextWrapping="Wrap"
+ Opacity="0.75" FontSize="13"
+ TextAlignment="Center"
+ Text="Run your query with EXPLAIN ANALYZE and we'll render the plan tree, hot paths, and tuning recommendations."/>
+ <Button x:Name="EmptyRunBtn" Click="OnRunClicked"
+ Style="{ThemeResource AccentButtonStyle}"
+ HorizontalAlignment="Center" Padding="14,8">
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <FontIcon Glyph="&#xE768;" FontSize="13"/>
+ <TextBlock Text="Run with Explain Analyze"/>
+ </StackPanel>
+ </Button>
+ <TextBlock x:Name="EmptyHint" Opacity="0.5" FontSize="11"
+ HorizontalAlignment="Center"
+ Text="Postgres only — MySQL coming soon."/>
+ </StackPanel>
+ </Grid>
+
+ <!-- ── Loading state ───────────────────────────────────────── -->
+ <Grid x:Name="LoadingState" Visibility="Collapsed"
+ Background="{ThemeResource LayerFillColorDefaultBrush}">
+ <StackPanel HorizontalAlignment="Center"
+ VerticalAlignment="Center"
+ Spacing="10">
+ <controls:ProgressRing IsActive="True" Width="36" Height="36"/>
+ <TextBlock x:Name="LoadingText"
+ Text="Running EXPLAIN ANALYZE..."
+ Opacity="0.75" FontSize="12"
+ HorizontalAlignment="Center"/>
+ </StackPanel>
+ </Grid>
+
+ <!-- ── Error state ─────────────────────────────────────────── -->
+ <Grid x:Name="ErrorState" Visibility="Collapsed"
+ Background="{ThemeResource LayerFillColorDefaultBrush}">
+ <StackPanel HorizontalAlignment="Center"
+ VerticalAlignment="Center"
+ MaxWidth="520" Spacing="10">
+ <FontIcon Glyph="&#xE783;" FontSize="28"
+ Foreground="{ThemeResource SystemFillColorCriticalBrush}"/>
+ <TextBlock Text="Couldn't run EXPLAIN ANALYZE"
+ FontSize="14" FontWeight="SemiBold"
+ HorizontalAlignment="Center"/>
+ <TextBlock x:Name="ErrorText"
+ TextWrapping="Wrap" TextAlignment="Center"
+ Opacity="0.75" FontSize="12"/>
+ <Button Click="OnRunClicked" HorizontalAlignment="Center"
+ Padding="12,6">
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <FontIcon Glyph="&#xE72C;" FontSize="12"/>
+ <TextBlock Text="Try again"/>
+ </StackPanel>
+ </Button>
+ </StackPanel>
+ </Grid>
+
+ <!-- ── Loaded state ────────────────────────────────────────── -->
+ <Grid x:Name="LoadedState" Visibility="Collapsed">
+ <Grid.ColumnDefinitions>
+ <ColumnDefinition Width="*" />
+ <ColumnDefinition Width="Auto" />
+ </Grid.ColumnDefinitions>
+
+ <ScrollViewer Grid.Column="0"
+ VerticalScrollBarVisibility="Auto"
+ HorizontalScrollBarVisibility="Disabled">
+ <StackPanel Padding="20,16,20,28" Spacing="18">
+
+ <!-- Run bar -->
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <Button Click="OnRunClicked" Padding="10,5">
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <FontIcon Glyph="&#xE72C;" FontSize="12"/>
+ <TextBlock Text="Re-run"/>
+ </StackPanel>
+ </Button>
+ <Button Click="OnCopyPlanClicked" Padding="10,5">
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <FontIcon Glyph="&#xE8C8;" FontSize="12"/>
+ <TextBlock Text="Copy plan"/>
+ </StackPanel>
+ </Button>
+ <Border Width="1" Background="{ThemeResource DividerStrokeColorDefaultBrush}"
+ Margin="4,0"/>
+ <TextBlock x:Name="MetaText" VerticalAlignment="Center"
+ FontSize="11" Opacity="0.6"
+ Text=""/>
+ </StackPanel>
+
+ <!-- InfoBar (warning callout) -->
+ <controls:InfoBar x:Name="WarnInfoBar"
+ Severity="Warning"
+ IsClosable="True"
+ IsOpen="False"
+ Title=""
+ Message=""/>
+
+ <!-- Summary metrics -->
+ <Grid x:Name="MetricsGrid">
+ <Grid.ColumnDefinitions>
+ <ColumnDefinition Width="*"/>
+ <ColumnDefinition Width="*"/>
+ <ColumnDefinition Width="*"/>
+ <ColumnDefinition Width="*"/>
+ </Grid.ColumnDefinitions>
+ <ContentControl x:Name="CardTotalTime" Grid.Column="0" Margin="0,0,8,0"/>
+ <ContentControl x:Name="CardRows" Grid.Column="1" Margin="4,0"/>
+ <ContentControl x:Name="CardBuffers" Grid.Column="2" Margin="4,0"/>
+ <ContentControl x:Name="CardAccuracy" Grid.Column="3" Margin="8,0,0,0"/>
+ </Grid>
+
+ <!-- Plan section header -->
+ <Grid Margin="0,4,0,0">
+ <Grid.ColumnDefinitions>
+ <ColumnDefinition Width="Auto"/>
+ <ColumnDefinition Width="*"/>
+ <ColumnDefinition Width="Auto"/>
+ </Grid.ColumnDefinitions>
+ <TextBlock Grid.Column="0" Text="Execution plan"
+ FontSize="16" FontWeight="SemiBold"
+ VerticalAlignment="Center"/>
+ <TextBlock x:Name="PlanCountText" Grid.Column="1"
+ Margin="12,0,0,0" VerticalAlignment="Center"
+ FontSize="12" Opacity="0.55"
+ Text=""/>
+ <ToggleButton x:Name="HotOnlyToggle" Grid.Column="2"
+ Padding="8,4" FontSize="11"
+ Click="OnHotOnlyToggled">
+ <StackPanel Orientation="Horizontal" Spacing="4">
+ <FontIcon Glyph="&#xE71C;" FontSize="11"/>
+ <TextBlock Text="Show only hot"/>
+ </StackPanel>
+ </ToggleButton>
+ </Grid>
+
+ <!-- Plan tree + Flyout (two-column layout) -->
+ <Grid>
+ <Grid.ColumnDefinitions>
+ <ColumnDefinition Width="*"/>
+ <ColumnDefinition Width="Auto"/>
+ </Grid.ColumnDefinitions>
+
+ <Border Grid.Column="0"
+ Background="{ThemeResource LayerFillColorDefaultBrush}"
+ BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}"
+ BorderThickness="1"
+ CornerRadius="8"
+ Padding="6,8">
+ <StackPanel x:Name="PlanTreeContainer" Spacing="2"/>
+ </Border>
+
+ <Border Grid.Column="1" x:Name="FlyoutBorder"
+ Width="340" Margin="12,0,0,0"
+ Background="{ThemeResource LayerFillColorAltBrush}"
+ BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}"
+ BorderThickness="1"
+ CornerRadius="8">
+ <StackPanel x:Name="FlyoutContainer" Padding="14,12" Spacing="10"/>
+ </Border>
+ </Grid>
+
+ <!-- Timing waterfall -->
+ <TextBlock Text="Timing waterfall"
+ FontSize="16" FontWeight="SemiBold"
+ Margin="0,12,0,0"/>
+ <TextBlock Opacity="0.55" FontSize="12"
+ Text="Actual time per node, in execution order."/>
+ <Border Background="{ThemeResource LayerFillColorDefaultBrush}"
+ BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}"
+ BorderThickness="1"
+ CornerRadius="8"
+ Padding="12">
+ <StackPanel x:Name="WaterfallContainer" Spacing="6"/>
+ </Border>
+
+ <!-- Recommendations -->
+ <TextBlock Text="Recommendations"
+ FontSize="16" FontWeight="SemiBold"
+ Margin="0,12,0,0"/>
+ <TextBlock Opacity="0.55" FontSize="12"
+ Text="Suggestions are derived from the plan above. Click Preview to copy the SQL into a new tab."/>
+ <StackPanel x:Name="RecsContainer" Spacing="8"/>
+
+ </StackPanel>
+ </ScrollViewer>
+ </Grid>
+ </Grid>
+</UserControl>
diff --git a/windows/Gridex/Gridex.items.props b/windows/Gridex/Gridex.items.props
index 2250531..27c524f 100644
--- a/windows/Gridex/Gridex.items.props
+++ b/windows/Gridex/Gridex.items.props
@@ -94,6 +94,13 @@
<ClInclude Include="$(MSBuildThisFileDirectory)Models\ERDiagramService.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)Models\ExportService.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)Models\ImportService.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)ExplainVisualizer\ExplainPlanTypes.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)ExplainVisualizer\ExplainPlanParser.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)ExplainVisualizer\ExplainPlanHeuristics.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)ExplainVisualizer\ExplainPlanVisualizerControl.h">
+ <DependentUpon>ExplainPlanVisualizerControl.xaml</DependentUpon>
+ <SubType>Code</SubType>
+ </ClInclude>
<ClInclude Include="$(MSBuildThisFileDirectory)xaml-includes.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)UpdateService.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)SettingsPage.h">
@@ -214,6 +221,9 @@
<Page Include="$(MSBuildThisFileDirectory)MCPPage.xaml">
<SubType>Designer</SubType>
</Page>
+ <Page Include="$(MSBuildThisFileDirectory)ExplainVisualizer\ExplainPlanVisualizerControl.xaml">
+ <SubType>Designer</SubType>
+ </Page>
</ItemGroup>
<ItemGroup>
<ClCompile Include="$(MSBuildThisFileDirectory)ConnectionCard.cpp">
@@ -450,6 +460,12 @@
<ClCompile Include="$(MSBuildThisFileDirectory)UpdateService.cpp">
<PrecompiledHeader>NotUsing</PrecompiledHeader>
</ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)ExplainVisualizer\ExplainPlanParser.cpp" />
+ <ClCompile Include="$(MSBuildThisFileDirectory)ExplainVisualizer\ExplainPlanHeuristics.cpp" />
+ <ClCompile Include="$(MSBuildThisFileDirectory)ExplainVisualizer\ExplainPlanVisualizerControl.cpp">
+ <DependentUpon>ExplainPlanVisualizerControl.xaml</DependentUpon>
+ <SubType>Code</SubType>
+ </ClCompile>
</ItemGroup>
<ItemGroup>
<Midl Include="$(MSBuildThisFileDirectory)MainWindow.idl">
@@ -516,5 +532,9 @@
<DependentUpon>MCPPage.xaml</DependentUpon>
<SubType>Code</SubType>
</Midl>
+ <Midl Include="$(MSBuildThisFileDirectory)ExplainVisualizer\ExplainPlanVisualizerControl.idl">
+ <DependentUpon>ExplainPlanVisualizerControl.xaml</DependentUpon>
+ <SubType>Code</SubType>
+ </Midl>
</ItemGroup>
</Project>
diff --git a/windows/Gridex/Gridex.vcxproj b/windows/Gridex/Gridex.vcxproj
index b2df240..d17fe27 100644
--- a/windows/Gridex/Gridex.vcxproj
+++ b/windows/Gridex/Gridex.vcxproj
@@ -96,8 +96,8 @@
<WarningLevel>Level4</WarningLevel>
<LanguageStandard Condition="'$(VisualStudioVersion)' &gt;= '18.0'">stdcpp20</LanguageStandard>
<LanguageStandard Condition="'$(VisualStudioVersion)' &lt; '18.0'">stdcpp17</LanguageStandard>
- <AdditionalOptions>%(AdditionalOptions) /bigobj /Zm500</AdditionalOptions>
- <AdditionalIncludeDirectories>$(ProjectDir);$(ProjectDir)..\vendor\velopack\include;C:\vcpkg\installed\x64-windows\include;C:\vcpkg\installed\x64-windows\include\mongocxx\v_noabi;C:\vcpkg\installed\x64-windows\include\bsoncxx\v_noabi;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalOptions>%(AdditionalOptions) /utf-8 /bigobj /Zm500</AdditionalOptions>
+ <AdditionalIncludeDirectories>$(ProjectDir);$(GeneratedFilesDir)ExplainVisualizer;$(ProjectDir)..\vendor\velopack\include;C:\vcpkg\installed\x64-windows\include;C:\vcpkg\installed\x64-windows\include\mongocxx\v_noabi;C:\vcpkg\installed\x64-windows\include\bsoncxx\v_noabi;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
@@ -114,7 +114,7 @@
</ClCompile>
<Link>
<AdditionalLibraryDirectories>C:\vcpkg\installed\x64-windows\debug\lib;$(ProjectDir)..\vendor\velopack\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
- <AdditionalDependencies>mongocxx-v_noabi-dhi-mdd.lib;bsoncxx-v_noabi-dhi-mdd.lib;hiredisd.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <AdditionalDependencies>mongocxx1-v1-dhi-mdd.lib;bsoncxx1-v1-dhi-mdd.lib;hiredisd.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<!-- Release: link against vcpkg release libs + mongocxx release variant -->
@@ -124,7 +124,7 @@
</ClCompile>
<Link>
<AdditionalLibraryDirectories>C:\vcpkg\installed\x64-windows\lib;$(ProjectDir)..\vendor\velopack\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
- <AdditionalDependencies>mongocxx-v_noabi-rhi-md.lib;bsoncxx-v_noabi-rhi-md.lib;hiredis.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <AdditionalDependencies>mongocxx1-v1-rhi-md.lib;bsoncxx1-v1-rhi-md.lib;hiredis.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
<Link>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
@@ -209,13 +209,13 @@
Mixing Debug exe with Release DLLs causes ABI mismatch →
strlen(NULL) crash inside mongoc_uri_parse. -->
<!-- Release DLLs -->
- <Content Include="C:\vcpkg\installed\x64-windows\bin\mongocxx-v_noabi-rhi-md.dll" Condition="'$(Configuration)'=='Release'">
- <Link>mongocxx-v_noabi-rhi-md.dll</Link>
+ <Content Include="C:\vcpkg\installed\x64-windows\bin\mongocxx1-v1-rhi-md.dll" Condition="'$(Configuration)'=='Release'">
+ <Link>mongocxx1-v1-rhi-md.dll</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<DeploymentContent>true</DeploymentContent>
</Content>
- <Content Include="C:\vcpkg\installed\x64-windows\bin\bsoncxx-v_noabi-rhi-md.dll" Condition="'$(Configuration)'=='Release'">
- <Link>bsoncxx-v_noabi-rhi-md.dll</Link>
+ <Content Include="C:\vcpkg\installed\x64-windows\bin\bsoncxx1-v1-rhi-md.dll" Condition="'$(Configuration)'=='Release'">
+ <Link>bsoncxx1-v1-rhi-md.dll</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<DeploymentContent>true</DeploymentContent>
</Content>
@@ -229,19 +229,19 @@
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<DeploymentContent>true</DeploymentContent>
</Content>
- <Content Include="C:\vcpkg\installed\x64-windows\bin\zlib1.dll" Condition="'$(Configuration)'=='Release'">
- <Link>zlib1.dll</Link>
+ <Content Include="C:\vcpkg\installed\x64-windows\bin\z.dll" Condition="'$(Configuration)'=='Release'">
+ <Link>z.dll</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<DeploymentContent>true</DeploymentContent>
</Content>
<!-- Debug DLLs -->
- <Content Include="C:\vcpkg\installed\x64-windows\debug\bin\mongocxx-v_noabi-dhi-mdd.dll" Condition="'$(Configuration)'=='Debug'">
- <Link>mongocxx-v_noabi-dhi-mdd.dll</Link>
+ <Content Include="C:\vcpkg\installed\x64-windows\debug\bin\mongocxx1-v1-dhi-mdd.dll" Condition="'$(Configuration)'=='Debug'">
+ <Link>mongocxx1-v1-dhi-mdd.dll</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<DeploymentContent>true</DeploymentContent>
</Content>
- <Content Include="C:\vcpkg\installed\x64-windows\debug\bin\bsoncxx-v_noabi-dhi-mdd.dll" Condition="'$(Configuration)'=='Debug'">
- <Link>bsoncxx-v_noabi-dhi-mdd.dll</Link>
+ <Content Include="C:\vcpkg\installed\x64-windows\debug\bin\bsoncxx1-v1-dhi-mdd.dll" Condition="'$(Configuration)'=='Debug'">
+ <Link>bsoncxx1-v1-dhi-mdd.dll</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<DeploymentContent>true</DeploymentContent>
</Content>
@@ -255,8 +255,8 @@
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<DeploymentContent>true</DeploymentContent>
</Content>
- <Content Include="C:\vcpkg\installed\x64-windows\debug\bin\zlibd1.dll" Condition="'$(Configuration)'=='Debug'">
- <Link>zlibd1.dll</Link>
+ <Content Include="C:\vcpkg\installed\x64-windows\debug\bin\zd.dll" Condition="'$(Configuration)'=='Debug'">
+ <Link>zd.dll</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<DeploymentContent>true</DeploymentContent>
</Content>
diff --git a/windows/Gridex/QueryEditorView.cpp b/windows/Gridex/QueryEditorView.cpp
index 680218c..48e7eab 100644
--- a/windows/Gridex/QueryEditorView.cpp
+++ b/windows/Gridex/QueryEditorView.cpp
@@ -6,6 +6,7 @@
#include <winrt/Microsoft.UI.Input.h>
#include <winrt/Microsoft.UI.Dispatching.h>
#include "QueryEditorView.h"
+#include <cwctype>
#if __has_include("QueryEditorView.g.cpp")
#include "QueryEditorView.g.cpp"
#endif
@@ -72,7 +73,6 @@ namespace winrt::Gridex::implementation
ClearEditorButton().Click(
[this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)
{ ClearEditor_Click({}, {}); });
-
// Create SQL editor TextBox
sqlEditor_ = muxc::TextBox();
sqlEditor_.AcceptsReturn(true);
@@ -600,6 +600,7 @@ namespace winrt::Gridex::implementation
}
else
pendingSql_ = sql;
+ if (OnSqlChanged) OnSqlChanged();
}
std::wstring QueryEditorView::GetSql() const
@@ -669,6 +670,56 @@ namespace winrt::Gridex::implementation
HideSuggestions();
}
+ void QueryEditorView::ResultsTab_Click(
+ winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)
+ {
+ ResultsTabBtn().IsChecked(true);
+ VisualizeTabBtn().IsChecked(false);
+ ResultsScroller().Visibility(mux::Visibility::Visible);
+ VisualizeHost().Visibility(mux::Visibility::Collapsed);
+ ResultsHeader().Visibility(
+ lastResult_.columnNames.empty() ? mux::Visibility::Collapsed : mux::Visibility::Visible);
+ EditorRowDef().Height(mux::GridLengthHelper::FromValueAndType(1, mux::GridUnitType::Star));
+ SplitterRowDef().Height(mux::GridLengthHelper::Auto());
+ EditorContainer().Visibility(mux::Visibility::Visible);
+ EditorSplitter().Visibility(mux::Visibility::Visible);
+ }
+
+ void QueryEditorView::VisualizeTab_Click(
+ winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)
+ {
+ ResultsTabBtn().IsChecked(false);
+ VisualizeTabBtn().IsChecked(true);
+ ResultsScroller().Visibility(mux::Visibility::Collapsed);
+ VisualizeHost().Visibility(mux::Visibility::Visible);
+ ResultsHeader().Visibility(mux::Visibility::Collapsed);
+ EditorContainer().Visibility(mux::Visibility::Collapsed);
+ EditorSplitter().Visibility(mux::Visibility::Collapsed);
+ EditorRowDef().Height(mux::GridLengthHelper::FromPixels(0));
+ SplitterRowDef().Height(mux::GridLengthHelper::FromPixels(0));
+ }
+
+ void QueryEditorView::SetVisualizeAvailable(bool available)
+ {
+ VisualizeTabBtn().Visibility(
+ available ? mux::Visibility::Visible : mux::Visibility::Collapsed);
+ auto checkedValue = VisualizeTabBtn().IsChecked();
+ if (!available && checkedValue && checkedValue.Value())
+ ResultsTab_Click({}, {});
+ }
+
+ void QueryEditorView::SetVisualizerControl(
+ winrt::Microsoft::UI::Xaml::UIElement const& control)
+ {
+ VisualizeHost().Content(control);
+ }
+
+ void QueryEditorView::TriggerVisualize()
+ {
+ if (VisualizeTabBtn().Visibility() == mux::Visibility::Visible)
+ VisualizeTab_Click({}, {});
+ }
+
// ── Results display ────────────────────────────────
void QueryEditorView::ShowResult(const DBModels::QueryResult& result)
diff --git a/windows/Gridex/QueryEditorView.h b/windows/Gridex/QueryEditorView.h
index 1b7b839..76d4a96 100644
--- a/windows/Gridex/QueryEditorView.h
+++ b/windows/Gridex/QueryEditorView.h
@@ -19,8 +19,20 @@ namespace winrt::Gridex::implementation
void ClearEditor_Click(
winrt::Windows::Foundation::IInspectable const& sender,
winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);
+ void ResultsTab_Click(
+ winrt::Windows::Foundation::IInspectable const& sender,
+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);
+ void VisualizeTab_Click(
+ winrt::Windows::Foundation::IInspectable const& sender,
+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);
+
+ void SetVisualizeAvailable(bool available);
+ void TriggerVisualize();
+ void SetVisualizerControl(
+ winrt::Microsoft::UI::Xaml::UIElement const& control);
std::function<DBModels::QueryResult(const std::wstring& sql)> OnExecuteQuery;
+ std::function<void()> OnSqlChanged;
void SetSql(const std::wstring& sql);
std::wstring GetSql() const;
diff --git a/windows/Gridex/QueryEditorView.xaml b/windows/Gridex/QueryEditorView.xaml
index 5d2685a..5d0a513 100644
--- a/windows/Gridex/QueryEditorView.xaml
+++ b/windows/Gridex/QueryEditorView.xaml
@@ -4,11 +4,11 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Gridex">
- <Grid>
+ <Grid x:Name="RootGrid">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
- <RowDefinition Height="*" />
- <RowDefinition Height="Auto" />
+ <RowDefinition x:Name="EditorRowDef" Height="*" />
+ <RowDefinition x:Name="SplitterRowDef" Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
@@ -62,7 +62,7 @@
</Grid>
<!-- Splitter -->
- <Grid Grid.Row="2" Height="6"
+ <Grid x:Name="EditorSplitter" Grid.Row="2" Height="6"
Background="{ThemeResource LayerFillColorDefaultBrush}"
BorderBrush="{ThemeResource DividerStrokeColorDefaultBrush}"
BorderThickness="0,1,0,1">
@@ -74,11 +74,42 @@
<!-- Results -->
<Grid Grid.Row="3">
<Grid.RowDefinitions>
+ <RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
- <Grid Grid.Row="0" Padding="8,4"
+ <Grid Grid.Row="0" Padding="8,4,8,0"
+ Background="{ThemeResource LayerFillColorDefaultBrush}"
+ BorderBrush="{ThemeResource DividerStrokeColorDefaultBrush}"
+ BorderThickness="0,0,0,1">
+ <StackPanel Orientation="Horizontal" Spacing="2">
+ <ToggleButton x:Name="ResultsTabBtn"
+ IsChecked="True"
+ Padding="10,4"
+ Background="Transparent"
+ BorderThickness="0"
+ Click="ResultsTab_Click">
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <FontIcon Glyph="&#xE71D;" FontSize="11"/>
+ <TextBlock Text="Results" FontSize="12"/>
+ </StackPanel>
+ </ToggleButton>
+ <ToggleButton x:Name="VisualizeTabBtn"
+ Padding="10,4"
+ Background="Transparent"
+ BorderThickness="0"
+ Visibility="Collapsed"
+ Click="VisualizeTab_Click">
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <FontIcon Glyph="&#xE9D9;" FontSize="11"/>
+ <TextBlock Text="Visualize" FontSize="12"/>
+ </StackPanel>
+ </ToggleButton>
+ </StackPanel>
+ </Grid>
+
+ <Grid Grid.Row="1" Padding="8,4"
Background="{ThemeResource LayerFillColorDefaultBrush}"
BorderBrush="{ThemeResource DividerStrokeColorDefaultBrush}"
BorderThickness="0,0,0,1"
@@ -87,11 +118,16 @@
Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
</Grid>
- <Grid Grid.Row="1">
- <ScrollViewer HorizontalScrollBarVisibility="Auto"
+ <Grid Grid.Row="2">
+ <ScrollViewer x:Name="ResultsScroller"
+ HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto">
<StackPanel x:Name="ResultsContainer" Spacing="0" />
</ScrollViewer>
+ <ContentControl x:Name="VisualizeHost"
+ Visibility="Collapsed"
+ HorizontalContentAlignment="Stretch"
+ VerticalContentAlignment="Stretch"/>
<!-- Loading overlay shown while a query is running. -->
<Grid x:Name="QueryLoadingOverlay"
diff --git a/windows/Gridex/WorkspacePage.cpp b/windows/Gridex/WorkspacePage.cpp
index eee3b86..6ae386d 100644
--- a/windows/Gridex/WorkspacePage.cpp
+++ b/windows/Gridex/WorkspacePage.cpp
@@ -8,6 +8,8 @@
#include "TabBarControl.h"
#include "DataGridView.h"
#include "QueryEditorView.h"
+#include "ExplainVisualizer/ExplainPlanVisualizerControl.h"
+#include "ExplainVisualizer/ExplainPlanParser.h"
#include "StructureView.h"
#include "StatusBarControl.h"
#include "DetailsPanel.h"
@@ -1410,6 +1412,60 @@ namespace winrt::Gridex::implementation
// (Redis gets Browse Keys / Flush DB; SQL gets Open / Export / Import)
Sidebar().as<SidebarPanel>()->SetDatabaseType(config.databaseType);
+ // Postgres Explain Visualizer lives in QueryEditor's results pane
+ // as a dedicated Results | Visualize view.
+ {
+ const bool isPostgres =
+ config.databaseType == DBModels::DatabaseType::PostgreSQL;
+ auto queryEditor = QueryEditor().as<QueryEditorView>();
+ queryEditor->SetVisualizeAvailable(isPostgres);
+
+ if (isPostgres)
+ {
+ auto visualizer = winrt::make<ExplainPlanVisualizerControl>();
+ auto visualizerImpl =
+ winrt::get_self<ExplainPlanVisualizerControl>(visualizer);
+ queryEditor->SetVisualizerControl(visualizer);
+ explainVizElement_ = visualizer;
+ visualizerImpl->ShowEmpty();
+
+ visualizerImpl->OnRunRequested = [this]()
+ {
+ RunExplainAnalyzeForVisualizer();
+ };
+ visualizerImpl->OnPreviewSqlRequested = [this](std::wstring sql)
+ {
+ OpenNewQueryTab();
+ try { QueryEditor().as<QueryEditorView>()->SetSql(sql); }
+ catch (...) {}
+ };
+ visualizerImpl->OnCopyPlanRequested = [](std::wstring rawJson)
+ {
+ try
+ {
+ winrt::Windows::ApplicationModel::DataTransfer::DataPackage package;
+ package.SetText(winrt::hstring(rawJson));
+ winrt::Windows::ApplicationModel::DataTransfer::Clipboard::SetContent(package);
+ }
+ catch (...) {}
+ };
+ }
+ else
+ {
+ queryEditor->SetVisualizerControl(nullptr);
+ explainVizElement_ = nullptr;
+ }
+
+ queryEditor->OnSqlChanged = [this]()
+ {
+ if (!explainVizElement_) return;
+ auto visualizer = explainVizElement_.try_as<
+ winrt::Gridex::ExplainPlanVisualizerControl>();
+ if (!visualizer) return;
+ winrt::get_self<ExplainPlanVisualizerControl>(visualizer)->Reset();
+ };
+ }
+
// Redis does not support SQL-style row updates -- inline edits
// would silently overwrite hash / list / set values via SET
// and corrupt the data. Flip the grid + details pane into
@@ -1592,6 +1648,91 @@ namespace winrt::Gridex::implementation
#endif // GRIDEX_ENTERPRISE
}
+ void WorkspacePage::RunExplainAnalyzeForVisualizer()
+ {
+ if (!connMgr_.isConnected() || !explainVizElement_) return;
+ auto adapter = connMgr_.getActiveAdapter();
+ if (!adapter) return;
+
+ auto visualizer = explainVizElement_.try_as<
+ winrt::Gridex::ExplainPlanVisualizerControl>();
+ if (!visualizer) return;
+ auto visualizerImpl = winrt::get_self<ExplainPlanVisualizerControl>(visualizer);
+
+ auto queryEditor = QueryEditor().as<QueryEditorView>();
+ std::wstring sql = queryEditor->GetSql();
+ while (!sql.empty() && (sql.back() == L'\n' || sql.back() == L'\r' ||
+ sql.back() == L' ' || sql.back() == L'\t' ||
+ sql.back() == L';'))
+ sql.pop_back();
+ if (sql.empty())
+ {
+ visualizerImpl->ShowError(L"Editor is empty. Type a query first.");
+ return;
+ }
+
+ visualizerImpl->ShowLoading();
+ bool rewritten = false;
+ std::wstring effectiveSql = AutoQuoteReservedIdentifiers(
+ sql, state_.connection.databaseType, rewritten);
+
+ DBModels::QueryResult result;
+ try
+ {
+ result = adapter->execute(
+ L"EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) " + effectiveSql);
+ }
+ catch (const std::exception& error)
+ {
+ const int byteCount = static_cast<int>(strlen(error.what()));
+ int size = MultiByteToWideChar(
+ CP_UTF8, 0, error.what(), byteCount, nullptr, 0);
+ std::wstring message(size > 0 ? size : 0, L'\0');
+ if (size > 0)
+ MultiByteToWideChar(
+ CP_UTF8, 0, error.what(), byteCount, message.data(), size);
+ visualizerImpl->ShowError(message.empty()
+ ? L"EXPLAIN ANALYZE failed." : message);
+ return;
+ }
+ catch (...)
+ {
+ visualizerImpl->ShowError(L"Unknown error running EXPLAIN ANALYZE.");
+ return;
+ }
+
+ if (!result.success)
+ {
+ visualizerImpl->ShowError(result.error.empty()
+ ? L"EXPLAIN ANALYZE returned no plan." : result.error);
+ return;
+ }
+ if (result.rows.empty() || result.columnNames.empty())
+ {
+ visualizerImpl->ShowError(L"EXPLAIN ANALYZE returned no rows.");
+ return;
+ }
+
+ const auto& firstRow = result.rows.front();
+ auto cell = firstRow.find(result.columnNames.front());
+ if (cell == firstRow.end() || cell->second.empty())
+ {
+ visualizerImpl->ShowError(L"EXPLAIN ANALYZE returned an empty cell.");
+ return;
+ }
+
+ auto document = std::make_shared<::Gridex::ExplainViz::PlanDocument>();
+ document->originalSql = effectiveSql;
+ std::wstring parseError;
+ if (!::Gridex::ExplainViz::ExplainPlanParser::parse(
+ cell->second, *document, parseError))
+ {
+ visualizerImpl->ShowError(L"Could not parse plan JSON: " + parseError);
+ return;
+ }
+ visualizerImpl->SetPlan(document);
+ }
+
// ── Sidebar Data Loading ────────────────────────────
void WorkspacePage::LoadSidebarFromDB()
diff --git a/windows/Gridex/WorkspacePage.h b/windows/Gridex/WorkspacePage.h
index c5e671b..9d6739c 100644
--- a/windows/Gridex/WorkspacePage.h
+++ b/windows/Gridex/WorkspacePage.h
@@ -67,6 +67,7 @@ namespace winrt::Gridex::implementation
static std::wstring sLastPassword_;
static bool sHasLastConnection_;
bool buttonsWired_ = false;
+ winrt::Microsoft::UI::Xaml::UIElement explainVizElement_{ nullptr };
bool sidebarVisible_ = true;
bool detailsVisible_ = true;
bool filterVisible_ = false;
@@ -112,6 +113,7 @@ namespace winrt::Gridex::implementation
void SwitchContentView();
void OnTableSelected(const std::wstring& tableName, const std::wstring& schema);
void OpenNewQueryTab();
+ void RunExplainAnalyzeForVisualizer();
// Opens a read-only query tab showing the function's source
// (CREATE FUNCTION DDL or body) fetched via
// DatabaseAdapter::getFunctionSource.