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++
feat(linux): Qt6 Linux port with full MCP server + UI (#31)
haidang1810be06347f374a
diff --git a/linux/.gitignore b/linux/.gitignorenew file mode 100644index 0000000..6fb94f6--- /dev/null+++ b/linux/.gitignore@@ -0,0 +1,22 @@+build/+build-*/+bin-tests/+cmake-build-*/+.cache/+compile_commands.json+*.o+*.obj+*.user+CMakeCache.txt+CMakeFiles/+CMakeScripts/+Makefile+cmake_install.cmake+install_manifest.txt+*.AppImage+AppDir/++# Ad-hoc screenshots / local artifacts+image.png+*.screenshot.png+dist/diff --git a/linux/CMakeLists.txt b/linux/CMakeLists.txtnew file mode 100644index 0000000..ae9b926--- /dev/null+++ b/linux/CMakeLists.txt@@ -0,0 +1,57 @@+cmake_minimum_required(VERSION 3.24)++project(gridex+ VERSION 0.1.0+ DESCRIPTION "Gridex — AI-Native Database IDE (Linux)"+ LANGUAGES CXX+)++set(CMAKE_CXX_STANDARD 20)+set(CMAKE_CXX_STANDARD_REQUIRED ON)+set(CMAKE_CXX_EXTENSIONS OFF)++set(CMAKE_AUTOMOC ON)+set(CMAKE_AUTORCC ON)+set(CMAKE_AUTOUIC ON)++if(NOT CMAKE_BUILD_TYPE)+ set(CMAKE_BUILD_TYPE Release CACHE STRING "" FORCE)+endif()++list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake")++find_package(Qt6 6.4 REQUIRED COMPONENTS Widgets Network Concurrent Svg)++qt_standard_project_setup()++option(GRIDEX_BUILD_TESTS "Build smoke tests" ON)++add_subdirectory(src/Core)+add_subdirectory(src/Data)+add_subdirectory(src/Services)+add_subdirectory(src/Domain)+add_subdirectory(src/App)+add_subdirectory(src/Presentation)++if(GRIDEX_BUILD_TESTS)+ add_subdirectory(tests)+endif()++qt_add_executable(gridex src/main.cpp resources/gridex.qrc)++target_link_libraries(gridex PRIVATE+ gridex-core+ gridex-data+ gridex-services+ gridex-domain+ gridex-app+ gridex-presentation+ Qt6::Widgets+)++set_target_properties(gridex PROPERTIES+ WIN32_EXECUTABLE OFF+ MACOSX_BUNDLE OFF+)++install(TARGETS gridex RUNTIME DESTINATION bin)diff --git a/linux/README.md b/linux/README.mdnew file mode 100644index 0000000..313c051--- /dev/null+++ b/linux/README.md@@ -0,0 +1,92 @@+# Gridex — Linux++AI-Native Database IDE for Linux. Qt 6 + C++20.++Part of the Gridex multi-platform project. See the top-level repo for macOS and Windows ports.++## Status++Phase 1 scaffolding. Empty `MainWindow` launches; layers + CI wired up. Subsequent phases add database adapters, services, and full UI per the plan.++## Build requirements++- **C++20** compiler: GCC ≥ 11 or Clang ≥ 14+- **CMake** ≥ 3.24+- **Ninja** (recommended generator)+- **Qt 6 LTS** (≥ 6.4): `Qt6::Widgets`+- Mesa/OpenGL dev headers++### Distro packages++**Ubuntu 22.04** (Qt 6.2 in main — use `jurplel/install-qt-action` or a 6.4 backport PPA)++**Ubuntu 24.04**++```bash+sudo apt install build-essential cmake ninja-build pkg-config \+ qt6-base-dev qt6-base-dev-tools libgl1-mesa-dev+```++**Debian 12**++```bash+sudo apt install build-essential cmake ninja-build pkg-config \+ qt6-base-dev qt6-base-dev-tools libgl1-mesa-dev+```++**Fedora 40**++```bash+sudo dnf install gcc-c++ cmake ninja-build pkgconf-pkg-config \+ qt6-qtbase-devel mesa-libGL-devel+```++## Configure & build++From the repository root:++```bash+cmake -S linux -B linux/build -G Ninja -DCMAKE_BUILD_TYPE=Release+cmake --build linux/build --parallel+./linux/build/gridex+```++## Directory layout++```+linux/+├── CMakeLists.txt # root build+├── cmake/ # FindXxx.cmake modules (populated in later phases)+├── src/+│ ├── main.cpp # app entry+│ ├── Core/ # protocols, models, enums, errors (no Qt)+│ ├── Domain/ # use cases, repository interfaces (no Qt) — later phase+│ ├── Data/ # adapters, persistence, credentials — later phase+│ ├── Services/ # query engine, MCP, AI, SSH — later phase+│ ├── Presentation/ # Qt Widgets views + view models+│ └── App/ # DI container, config, lifecycle+├── resources/ # .qrc, icons — later phase+├── tests/ # Qt Test — later phase+└── packaging/+ ├── appimage/ # AppImage build pipeline+ ├── debian/ # .deb — Phase 8+ └── rpm/ # .rpm — Phase 8+```++## AppImage++After a successful build and with `linuxdeploy` + `linuxdeploy-plugin-qt` in `PATH`:++```bash+./linux/packaging/appimage/build-appimage.sh+```++Output goes to `linux/dist/`.++## CI++`.github/workflows/linux-build.yml` runs builds on Ubuntu 22.04, Ubuntu 24.04, Debian 12, and Fedora 40.++## Roadmap++See `/home/danghuynh/.claude/plans/piped-hopping-newt.md` for the full 8-phase plan, or `plans/reports/brainstorm-260415-1008-linux-qt-port.md` for the architecture brainstorm.diff --git a/linux/packaging/appimage/AppRun b/linux/packaging/appimage/AppRunnew file mode 100755index 0000000..a914666--- /dev/null+++ b/linux/packaging/appimage/AppRun@@ -0,0 +1,6 @@+#!/bin/sh+HERE="$(dirname "$(readlink -f "${0}")")"+export LD_LIBRARY_PATH="${HERE}/usr/lib:${LD_LIBRARY_PATH}"+export QT_PLUGIN_PATH="${HERE}/usr/plugins:${QT_PLUGIN_PATH}"+export XDG_DATA_DIRS="${HERE}/usr/share:${XDG_DATA_DIRS}"+exec "${HERE}/usr/bin/gridex" "$@"diff --git a/linux/packaging/appimage/build-appimage.sh b/linux/packaging/appimage/build-appimage.shnew file mode 100755index 0000000..3f7ae22--- /dev/null+++ b/linux/packaging/appimage/build-appimage.sh@@ -0,0 +1,38 @@+#!/usr/bin/env bash+# Build AppImage for Gridex Linux.+# Requires: linuxdeploy + linuxdeploy-plugin-qt in PATH.++set -euo pipefail++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+LINUX_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)"+BUILD_DIR="${BUILD_DIR:-${LINUX_ROOT}/build}"+APPDIR="${APPDIR:-${LINUX_ROOT}/AppDir}"+OUT_DIR="${OUT_DIR:-${LINUX_ROOT}/dist}"++command -v linuxdeploy >/dev/null || { echo "linuxdeploy not found"; exit 1; }+command -v linuxdeploy-plugin-qt >/dev/null || { echo "linuxdeploy-plugin-qt not found"; exit 1; }++mkdir -p "${BUILD_DIR}" "${OUT_DIR}"+rm -rf "${APPDIR}"++cmake -S "${LINUX_ROOT}" -B "${BUILD_DIR}" -G Ninja -DCMAKE_BUILD_TYPE=Release+cmake --build "${BUILD_DIR}" --parallel+DESTDIR="${APPDIR}" cmake --install "${BUILD_DIR}" --prefix /usr++install -Dm644 "${SCRIPT_DIR}/gridex.desktop" "${APPDIR}/usr/share/applications/gridex.desktop"+install -Dm755 "${SCRIPT_DIR}/AppRun" "${APPDIR}/AppRun"++# Icon: use placeholder if bundled icon absent.+ICON_SRC="${SCRIPT_DIR}/gridex.png"+if [ ! -f "${ICON_SRC}" ]; then+ ICON_SRC="${LINUX_ROOT}/../logo.png"+fi+install -Dm644 "${ICON_SRC}" "${APPDIR}/usr/share/icons/hicolor/512x512/apps/gridex.png"++cd "${OUT_DIR}"+linuxdeploy --appdir "${APPDIR}" --plugin qt --output appimage \+ --desktop-file "${APPDIR}/usr/share/applications/gridex.desktop" \+ --icon-file "${APPDIR}/usr/share/icons/hicolor/512x512/apps/gridex.png"++echo "AppImage produced under: ${OUT_DIR}"diff --git a/linux/packaging/appimage/gridex.desktop b/linux/packaging/appimage/gridex.desktopnew file mode 100644index 0000000..b5b93c8--- /dev/null+++ b/linux/packaging/appimage/gridex.desktop@@ -0,0 +1,11 @@+[Desktop Entry]+Type=Application+Name=Gridex+GenericName=Database IDE+Comment=AI-Native Database IDE+Exec=gridex+Icon=gridex+Terminal=false+Categories=Development;Database;+Keywords=database;sql;postgres;mysql;sqlite;mongodb;redis;+StartupWMClass=gridexdiff --git a/linux/packaging/debian/changelog b/linux/packaging/debian/changelognew file mode 100644index 0000000..c3cd3b6--- /dev/null+++ b/linux/packaging/debian/changelog@@ -0,0 +1,5 @@+gridex (0.1.0-1) unstable; urgency=low++ * Initial release.++ -- Gridex Team <[email protected]> Tue, 15 Apr 2026 17:26:00 +0000diff --git a/linux/packaging/debian/compat b/linux/packaging/debian/compatnew file mode 100644index 0000000..b1bd38b--- /dev/null+++ b/linux/packaging/debian/compat@@ -0,0 +1 @@+13diff --git a/linux/packaging/debian/control b/linux/packaging/debian/controlnew file mode 100644index 0000000..0a84be3--- /dev/null+++ b/linux/packaging/debian/control@@ -0,0 +1,36 @@+Source: gridex+Section: devel+Priority: optional+Maintainer: Gridex Team <[email protected]>+Build-Depends: debhelper-compat (= 13),+ cmake (>= 3.20),+ ninja-build,+ qt6-base-dev,+ qt6-base-dev-tools,+ libgl1-mesa-dev,+ libpq-dev,+ libmariadb-dev,+ libssh-dev,+ libsecret-1-dev,+ libhiredis-dev,+ freetds-dev,+ unixodbc-dev+Standards-Version: 4.6.2+Homepage: https://github.com/vurakit/vura+Rules-Requires-Root: no++Package: gridex+Architecture: amd64+Depends: ${shlibs:Depends},+ ${misc:Depends},+ qt6-base (>= 6.4) | libqt6core6 (>= 6.4),+ libpq5,+ libmariadb3,+ libssh-4,+ libsecret-1-0,+ libhiredis0.14+Description: AI-Native Database IDE+ Gridex is an AI-native database IDE for Linux that provides a powerful+ GUI for managing multiple database backends including PostgreSQL, MySQL,+ SQLite, MongoDB, Redis, and SQL Server, combined with AI chat and an+ MCP server for external AI agent integration.diff --git a/linux/packaging/debian/copyright b/linux/packaging/debian/copyrightnew file mode 100644index 0000000..d64c359--- /dev/null+++ b/linux/packaging/debian/copyright@@ -0,0 +1,27 @@+Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/+Upstream-Name: gridex+Upstream-Contact: Gridex Team <[email protected]>+Source: https://github.com/vurakit/vura++Files: *+Copyright: 2024-2026 Gridex Team+License: MIT++License: MIT+ Permission is hereby granted, free of charge, to any person obtaining a+ copy of this software and associated documentation files (the "Software"),+ to deal in the Software without restriction, including without limitation+ the rights to use, copy, modify, merge, publish, distribute, sublicense,+ and/or sell copies of the Software, and to permit persons to whom the+ Software is furnished to do so, subject to the following conditions:+ .+ The above copyright notice and this permission notice shall be included in+ all copies or substantial portions of the Software.+ .+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER+ DEALINGS IN THE SOFTWARE.diff --git a/linux/packaging/debian/rules b/linux/packaging/debian/rulesnew file mode 100755index 0000000..3efdea5--- /dev/null+++ b/linux/packaging/debian/rules@@ -0,0 +1,20 @@+#!/usr/bin/make -f+# Gridex debian/rules — minimal debhelper + cmake build.++export DH_VERBOSE = 1+export DEB_BUILD_MAINT_OPTIONS = hardening=+all++%:+ dh $@ --buildsystem=cmake++override_dh_auto_configure:+ dh_auto_configure -- \+ -GNinja \+ -DCMAKE_BUILD_TYPE=Release \+ -DCMAKE_INSTALL_PREFIX=/usr++override_dh_auto_build:+ dh_auto_build -- --parallel++override_dh_auto_install:+ dh_auto_install --destdir=debian/gridexdiff --git a/linux/packaging/rpm/gridex.spec b/linux/packaging/rpm/gridex.specnew file mode 100644index 0000000..dfb0eb6--- /dev/null+++ b/linux/packaging/rpm/gridex.spec@@ -0,0 +1,56 @@+Name: gridex+Version: 0.1.0+Release: 1%{?dist}+Summary: AI-Native Database IDE+License: MIT+URL: https://github.com/vurakit/vura++BuildRequires: cmake >= 3.20+BuildRequires: ninja-build+BuildRequires: gcc-c+++BuildRequires: qt6-qtbase-devel+BuildRequires: libpq-devel+BuildRequires: mariadb-connector-c-devel+BuildRequires: libssh-devel+BuildRequires: libsecret-devel+BuildRequires: hiredis-devel+BuildRequires: freetds-devel+BuildRequires: unixODBC-devel+BuildRequires: pkgconf-pkg-config+BuildRequires: mesa-libGL-devel++Requires: qt6-qtbase+Requires: libpq+Requires: mariadb-connector-c+Requires: libssh+Requires: libsecret+Requires: hiredis++%description+Gridex is an AI-native database IDE for Linux that provides a powerful+GUI for managing multiple database backends including PostgreSQL, MySQL,+SQLite, MongoDB, Redis, and SQL Server, combined with AI chat and an+MCP server for external AI agent integration.++%prep+# Sources are checked out directly; no tarball extraction needed in CI.+# When building locally with rpmbuild, copy sources into+# %{_builddir}/%{name}-%{version}/ before invoking this spec.++%build+cmake -S . -B %{_builddir}/%{name}-%{version}/build \+ -G Ninja \+ -DCMAKE_BUILD_TYPE=Release \+ -DCMAKE_INSTALL_PREFIX=%{_prefix}+cmake --build %{_builddir}/%{name}-%{version}/build --parallel++%install+DESTDIR=%{buildroot} cmake --install %{_builddir}/%{name}-%{version}/build++%files+%license LICENSE+%{_bindir}/gridex++%changelog+* Tue Apr 15 2026 Gridex Team <[email protected]> - 0.1.0-1+- Initial releasediff --git a/linux/resources/gridex.qrc b/linux/resources/gridex.qrcnew file mode 100644index 0000000..94e37a2--- /dev/null+++ b/linux/resources/gridex.qrc@@ -0,0 +1,8 @@+<!DOCTYPE RCC>+<RCC version="1.0">+ <qresource prefix="/">+ <file>logo.png</file>+ <file>style-dark.qss</file>+ <file>style-light.qss</file>+ </qresource>+</RCC>diff --git a/linux/resources/logo.png b/linux/resources/logo.pngnew file mode 100644index 0000000..cc8608eBinary files /dev/null and b/linux/resources/logo.png differdiff --git a/linux/resources/style-dark.qss b/linux/resources/style-dark.qssnew file mode 100644index 0000000..5e4bc44--- /dev/null+++ b/linux/resources/style-dark.qss@@ -0,0 +1,703 @@+/* Gridex Modern Dark Theme (Catppuccin Mocha Inspired) */++/* ---------------------------------------------------------+ GLOBAL RESET & BASICS+--------------------------------------------------------- */+QWidget {+ background-color: #1e1e2e;+ color: #cdd6f4;+ font-family: "Inter", "Segoe UI", "Roboto", sans-serif;+ font-size: 13px;+ border: none;+}++QToolTip {+ background-color: #11111b;+ color: #cdd6f4;+ border: 1px solid #313244;+ border-radius: 6px;+ padding: 6px 10px;+ font-weight: 500;+}++/* ---------------------------------------------------------+ MAIN WINDOW & DIALOGS+--------------------------------------------------------- */+QMainWindow, QDialog {+ background-color: #1e1e2e;+}++/* Base frames and containers */+QFrame {+ border: none;+}+QFrame#MainContainer {+ background-color: #11111b; /* darker background for internal workspace */+ border-radius: 8px;+ margin: 8px;+}++/* SPLITTER (adjustable dividers) */+QSplitter::handle {+ background-color: #181825;+ margin: 2px;+ border-radius: 2px;+}+QSplitter::handle:hover {+ background-color: #89b4fa;+}+QSplitter::handle:horizontal {+ width: 4px;+}+QSplitter::handle:vertical {+ height: 4px;+}++/* ---------------------------------------------------------+ MENUS & TOOLBARS+--------------------------------------------------------- */+QMenuBar {+ background-color: #11111b;+ color: #bac2de;+ border-bottom: 1px solid #1e1e2e;+}+QMenuBar::item {+ padding: 8px 14px;+ background: transparent;+ border-radius: 6px;+ margin: 4px;+}+QMenuBar::item:selected {+ background-color: #313244;+ color: #cdd6f4;+}+QMenuBar::item:pressed {+ background-color: #45475a;+}++QMenu {+ background-color: #181825;+ color: #cdd6f4;+ border: 1px solid #313244;+ border-radius: 8px;+ padding: 6px;+ margin: 0px;+}+QMenu::item {+ padding: 8px 30px 8px 24px;+ border-radius: 6px;+ margin: 2px 4px;+}+QMenu::item:selected {+ background-color: #313244;+ color: #cdd6f4;+}+QMenu::separator {+ height: 1px;+ background-color: #313244;+ margin: 4px 10px;+}+QMenu::indicator {+ width: 16px;+ height: 16px;+ margin-left: 6px;+}++QToolBar {+ background-color: #11111b;+ border: none;+ border-bottom: 1px solid #181825;+ padding: 6px;+ spacing: 8px;+}+QToolBar::separator {+ background-color: #313244;+ width: 1px;+ margin: 4px 8px;+}+QToolButton {+ background-color: transparent;+ border: none;+ border-radius: 6px;+ padding: 8px;+ color: #bac2de;+}+QToolButton:hover {+ background-color: #313244;+ color: #cdd6f4;+}+QToolButton:pressed, QToolButton:checked {+ background-color: #89b4fa;+ color: #11111b;+}++/* ---------------------------------------------------------+ SCROLLBARS+--------------------------------------------------------- */+QScrollBar:vertical {+ background-color: transparent;+ width: 14px;+ margin: 0px;+}+QScrollBar::handle:vertical {+ background-color: #45475a;+ border-radius: 5px;+ min-height: 30px;+ margin: 2px;+}+QScrollBar::handle:vertical:hover {+ background-color: #585b70;+}+QScrollBar::handle:vertical:pressed {+ background-color: #89b4fa;+}+QScrollBar::sub-line:vertical, QScrollBar::add-line:vertical,+QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical {+ height: 0px; width: 0px; background: none; border: none;+}+QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {+ background: none;+}++QScrollBar:horizontal {+ background-color: transparent;+ height: 14px;+ margin: 0px;+}+QScrollBar::handle:horizontal {+ background-color: #45475a;+ border-radius: 5px;+ min-width: 30px;+ margin: 2px;+}+QScrollBar::handle:horizontal:hover {+ background-color: #585b70;+}+QScrollBar::handle:horizontal:pressed {+ background-color: #89b4fa;+}+QScrollBar::sub-line:horizontal, QScrollBar::add-line:horizontal,+QScrollBar::left-arrow:horizontal, QScrollBar::right-arrow:horizontal {+ width: 0px; height: 0px; background: none; border: none;+}+QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {+ background: none;+}++/* ---------------------------------------------------------+ BUTTONS+--------------------------------------------------------- */+QPushButton {+ background-color: #313244;+ color: #cdd6f4;+ border: 1px solid #45475a;+ border-radius: 6px;+ padding: 8px 16px;+ font-weight: 600;+}+QPushButton:hover {+ background-color: #45475a;+ border-color: #585b70;+ color: #ffffff;+}+QPushButton:pressed, QPushButton:checked {+ background-color: #89b4fa;+ border-color: #89b4fa;+ color: #11111b;+}+QPushButton:disabled {+ background-color: #181825;+ border-color: #313244;+ color: #6c7086;+}++/* Primary actions or danger buttons can be styled differently via dynamic properties or object name */+QPushButton#primaryButton, QPushButton#commitButton {+ background-color: #89b4fa;+ color: #11111b;+ border: none;+}+QPushButton#primaryButton:hover, QPushButton#commitButton:hover {+ background-color: #b4befe;+}+QPushButton#primaryButton:pressed, QPushButton#primaryButton:checked, QPushButton#commitButton:pressed, QPushButton#commitButton:checked {+ background-color: #74c7ec;+ color: #11111b;+}+QPushButton#dangerButton, QPushButton#discardButton {+ background-color: #f38ba8;+ color: #11111b;+ border: none;+}+QPushButton#dangerButton:hover, QPushButton#discardButton:hover {+ background-color: #f5e0dc;+}+QPushButton#dangerButton:pressed, QPushButton#discardButton:pressed {+ background-color: #eba0ac;+}++/* Compact density: set QWidget property compact="true" on a container and+ all descendant QPushButton / QSpinBox / QComboBox / QLineEdit shrink to+ toolbar-size instead of the default 8px/16px padding. */+QWidget[compact="true"] QPushButton {+ padding: 4px 10px;+ font-size: 12px;+ font-weight: 500;+ min-height: 0;+ border-radius: 5px;+}+QWidget[compact="true"] QSpinBox,+QWidget[compact="true"] QDoubleSpinBox,+QWidget[compact="true"] QLineEdit,+QWidget[compact="true"] QComboBox {+ padding: 3px 8px;+ font-size: 12px;+ min-height: 0;+ border-radius: 5px;+}+QWidget[compact="true"] QLabel {+ font-size: 12px;+ padding: 0 2px;+}++/* Toolbar icon buttons — flat, no chrome, hover highlight; checked state+ shows an accent (sidebar / details toggles). Opt-in via toolbarIcon. */+QPushButton[toolbarIcon="true"] {+ background-color: transparent;+ color: #bac2de;+ border: none;+ border-right: 1px solid #181825;+ border-radius: 0;+ padding: 0;+ font-size: 13px;+ min-height: 0;+}+QPushButton[toolbarIcon="true"]:hover {+ background-color: #181825;+ color: #cdd6f4;+}+QPushButton[toolbarIcon="true"]:checked {+ color: #89b4fa;+ background-color: #181825;+}+QPushButton[toolbarIcon="true"]:disabled {+ color: #45475a;+ background-color: transparent;+}++/* Connection status dot in the top toolbar: gray when disconnected,+ Catppuccin green when a live connection is open. */+QPushButton#connDot {+ background-color: transparent;+ color: #6c7086;+ border: none;+ border-right: 1px solid #181825;+ border-radius: 0;+ padding: 0;+ font-size: 10px;+ min-height: 0;+}+QPushButton#connDot[connected="true"] {+ color: #a6e3a1;+}++/* Workspace tab bar (top query tabs) */+QWidget#WorkspaceTabBar {+ background-color: #11111b;+ border-bottom: 1px solid #181825;+}+QPushButton#newTabButton {+ background-color: transparent;+ color: #bac2de;+ font-size: 16px;+ font-weight: 500;+ border: none;+ border-right: 1px solid #181825;+ border-radius: 0;+ padding: 0;+}+QPushButton#newTabButton:hover {+ background-color: #181825;+ color: #89b4fa;+}++QWidget[queryTab="true"] {+ background-color: transparent;+ border-right: 1px solid #181825;+}+QWidget[queryTab="true"][active="true"] {+ background-color: #1e1e2e;+ border-bottom: 2px solid #89b4fa;+}++QLabel#statusDot {+ background-color: #45475a;+ border-radius: 3px;+}+QLabel#statusDot[active="true"] {+ background-color: #f38ba8;+}++QPushButton[queryTabLabel="true"] {+ background-color: transparent;+ color: #bac2de;+ border: none;+ border-radius: 0;+ padding: 0 4px;+ font-size: 12px;+ font-weight: 500;+ min-height: 0;+}+QPushButton[queryTabLabel="true"][active="true"] {+ color: #cdd6f4;+ font-weight: 700;+}++QPushButton#queryTabClose {+ background-color: transparent;+ color: #6c7086;+ border: none;+ border-radius: 9px;+ padding: 0;+ font-size: 14px;+ font-weight: 500;+ min-height: 0;+}+QPushButton#queryTabClose:hover {+ background-color: #313244;+ color: #f38ba8;+}++/* Tab-style buttons: checkable QPushButton that should look like a tab+ (underline active indicator, no chrome). Opt-in via property "tab". */+QPushButton[tab="true"] {+ background-color: transparent;+ color: #6c7086;+ border: none;+ border-bottom: 2px solid transparent;+ border-radius: 0;+ padding: 6px 12px;+ font-weight: 600;+}+QPushButton[tab="true"]:hover {+ color: #bac2de;+ background-color: transparent;+}+QPushButton[tab="true"]:checked {+ color: #89b4fa;+ background-color: transparent;+ border-bottom: 2px solid #89b4fa;+}+QPushButton[tab="true"]:disabled {+ color: #45475a;+ background-color: transparent;+}++/* ---------------------------------------------------------+ INPUTS (LineEdit, TextEdit, SpinBox)+--------------------------------------------------------- */+QLineEdit, QTextEdit, QPlainTextEdit, QSpinBox, QDoubleSpinBox {+ background-color: #11111b;+ color: #cdd6f4;+ border: 1px solid #313244;+ border-radius: 6px;+ padding: 8px 12px;+ selection-background-color: #585b70;+}+QLineEdit:hover, QTextEdit:hover, QPlainTextEdit:hover, QSpinBox:hover, QDoubleSpinBox:hover {+ border: 1px solid #585b70;+ background-color: #181825;+}+QLineEdit:focus, QTextEdit:focus, QPlainTextEdit:focus, QSpinBox:focus, QDoubleSpinBox:focus {+ border: 1px solid #89b4fa;+ background-color: #1e1e2e;+}+QLineEdit:disabled, QTextEdit:disabled, QPlainTextEdit:disabled, QSpinBox:disabled {+ background-color: #181825;+ color: #6c7086;+ border-color: #1e1e2e;+}++/* Inline cell editors (spawned by QTableView / QTreeView when a cell is+ double-clicked). The global QLineEdit padding/radius is too big for a+ 22px row, so we tighten it for editors living inside an item view. */+QAbstractItemView QLineEdit,+QAbstractItemView QTextEdit,+QAbstractItemView QPlainTextEdit,+QAbstractItemView QSpinBox,+QAbstractItemView QDoubleSpinBox,+QAbstractItemView QComboBox {+ padding: 0 4px;+ margin: 0;+ border: 1px solid #89b4fa;+ border-radius: 2px;+ background-color: #181825;+ color: #cdd6f4;+ selection-background-color: #89b4fa;+ selection-color: #11111b;+ min-height: 0;+}++/* ---------------------------------------------------------+ COMBOBOX+--------------------------------------------------------- */+QComboBox {+ background-color: #11111b;+ color: #cdd6f4;+ border: 1px solid #313244;+ border-radius: 6px;+ padding: 6px 12px;+}+QComboBox:hover {+ border: 1px solid #585b70;+ background-color: #181825;+}+QComboBox:focus {+ border: 1px solid #89b4fa;+ background-color: #1e1e2e;+}+QComboBox::drop-down {+ subcontrol-origin: padding;+ subcontrol-position: top right;+ width: 24px;+ border-left: none;+}+QComboBox::down-arrow {+ image: none;+ border-left: 5px solid transparent;+ border-right: 5px solid transparent;+ border-top: 5px solid #a6adc8;+ margin-right: 8px;+}+QComboBox QAbstractItemView {+ background-color: #181825;+ border: 1px solid #313244;+ border-radius: 6px;+ outline: none;+ padding: 4px;+ selection-background-color: #313244;+ selection-color: #cdd6f4;+}+QComboBox QAbstractItemView::item {+ border-radius: 4px;+ padding: 6px;+}+QComboBox QAbstractItemView::item:selected {+ background-color: #313244;+}++/* ---------------------------------------------------------+ TAB WIDGETS & TAB BAR+--------------------------------------------------------- */+QTabWidget::pane {+ border: 1px solid #313244;+ border-radius: 8px;+ background-color: #1e1e2e;+ top: -1px;+}+QTabBar {+ qproperty-drawBase: 0;+}+QTabBar::tab {+ background-color: #11111b;+ color: #6c7086;+ padding: 10px 20px;+ border: 1px solid transparent;+ border-bottom: 2px solid transparent;+ border-top-left-radius: 8px;+ border-top-right-radius: 8px;+ margin-right: 4px;+ font-weight: 600;+}+QTabBar::tab:hover {+ background-color: #181825;+ color: #bac2de;+}+QTabBar::tab:selected {+ background-color: #1e1e2e;+ color: #89b4fa;+ border-bottom: 2px solid #89b4fa;+}++/* ---------------------------------------------------------+ TABLE & TREE VIEWS+--------------------------------------------------------- */+QTableView, QTreeView, QListView {+ background-color: #1e1e2e;+ alternate-background-color: #181825;+ color: #cdd6f4;+ border: 1px solid #181825;+ border-radius: 8px;+ gridline-color: #313244;+ outline: none;+ selection-background-color: transparent;+}+QTableView::item, QTreeView::item, QListView::item {+ padding: 2px 8px;+ border: none;+}+QTableView::item:hover, QTreeView::item:hover, QListView::item:hover {+ background-color: #313244;+ color: #ffffff;+}+QTableView::item:selected, QTreeView::item:selected, QListView::item:selected {+ background-color: rgba(137, 180, 250, 0.2);+ color: #89b4fa;+}+QTreeView {+ show-decoration-selected: 1;+}++/* Tree Branches */+QTreeView::branch:has-siblings:!adjoins-item { border-image: none; }+QTreeView::branch:has-siblings:adjoins-item { border-image: none; }+QTreeView::branch:!has-children:!has-siblings:adjoins-item { border-image: none; }+QTreeView::branch:has-children:closed { border-image: none; }+QTreeView::branch:open:has-children { border-image: none; }++/* ---------------------------------------------------------+ HEADER VIEWS (Table columns)+--------------------------------------------------------- */+QHeaderView {+ background-color: #1e1e2e;+ border: none;+ border-top-left-radius: 8px;+ border-top-right-radius: 8px;+}+QHeaderView::section {+ background-color: #181825;+ color: #a6adc8;+ padding: 8px 12px;+ border: none;+ border-right: 1px solid #313244;+ border-bottom: 2px solid #313244;+ font-weight: 600;+}+QHeaderView::section:hover {+ background-color: rgba(49, 50, 68, 0.5);+ color: #cdd6f4;+}+QHeaderView::section:checked {+ background-color: #313244;+ color: #89b4fa;+ border-bottom: 2px solid #89b4fa;+}++/* ---------------------------------------------------------+ STATUS BAR+--------------------------------------------------------- */+QStatusBar {+ background-color: #11111b;+ color: #bac2de;+ border-top: 1px solid #181825;+}+QStatusBar::item {+ border: none;+}+QStatusBar QLabel {+ padding: 2px 8px;+}++/* ---------------------------------------------------------+ GROUP BOX+--------------------------------------------------------- */+QGroupBox {+ background-color: #181825;+ border: 1px solid #313244;+ border-radius: 8px;+ margin-top: 14px;+ font-weight: 600;+ padding-top: 14px;+}+QGroupBox::title {+ subcontrol-origin: margin;+ subcontrol-position: top left;+ padding: 0 10px;+ color: #89b4fa;+ background-color: transparent;+}++/* ---------------------------------------------------------+ CHECKBOX & RADIOBUTTON+--------------------------------------------------------- */+QCheckBox, QRadioButton {+ spacing: 8px;+ color: #cdd6f4;+ padding: 4px;+}+QCheckBox:hover, QRadioButton:hover {+ color: #89b4fa;+}+QCheckBox::indicator, QRadioButton::indicator {+ width: 20px;+ height: 20px;+ border: 1px solid #45475a;+ background-color: #11111b;+ border-radius: 4px;+}+QRadioButton::indicator {+ border-radius: 10px;+}+QCheckBox::indicator:hover, QRadioButton::indicator:hover {+ border: 1px solid #89b4fa;+ background-color: #181825;+}+QCheckBox::indicator:checked {+ background-color: #89b4fa;+ border: 1px solid #89b4fa;+}+QRadioButton::indicator:checked {+ background-color: #11111b;+ border: 6px solid #89b4fa;+}++/* ---------------------------------------------------------+ PROGRESS BAR+--------------------------------------------------------- */+QProgressBar {+ background-color: #11111b;+ border: 1px solid #313244;+ border-radius: 8px;+ text-align: center;+ color: #cdd6f4;+ font-weight: bold;+}+QProgressBar::chunk {+ background-color: #89b4fa;+ border-radius: 7px;+}++/* ---------------------------------------------------------+ QUERY LOG PANEL+--------------------------------------------------------- */+QWidget#QueryLogHeader {+ background-color: #11111b;+}+QPushButton#QueryLogToggle, QPushButton#QueryLogClear {+ background-color: transparent;+ border: none;+ font-size: 11px;+ color: #a6adc8;+ padding: 2px 6px;+}+QPushButton#QueryLogToggle:hover, QPushButton#QueryLogClear:hover {+ color: #cdd6f4;+ background-color: #313244;+}+QLabel#QueryLogTitle {+ color: #a6adc8;+ font-size: 12px;+ font-weight: bold;+}+QPlainTextEdit#QueryLogEdit {+ background-color: #11111b;+ border: 1px solid #181825;+ border-top: none;+ border-radius: 0px;+ border-bottom-left-radius: 8px;+ border-bottom-right-radius: 8px;+ font-family: monospace;+ font-size: 12px;+ color: #a6adc8;+ padding: 6px 10px;+}diff --git a/linux/resources/style-light.qss b/linux/resources/style-light.qssnew file mode 100644index 0000000..462d011--- /dev/null+++ b/linux/resources/style-light.qss@@ -0,0 +1,689 @@+/* Gridex Light Theme (Catppuccin Latte) */++/* ---------------------------------------------------------+ GLOBAL RESET & BASICS+--------------------------------------------------------- */+QWidget {+ background-color: #eff1f5;+ color: #4c4f69;+ font-family: "Inter", "Segoe UI", "Roboto", sans-serif;+ font-size: 13px;+ border: none;+}++QToolTip {+ background-color: #e6e9ef;+ color: #4c4f69;+ border: 1px solid #ccd0da;+ border-radius: 6px;+ padding: 6px 10px;+ font-weight: 500;+}++/* ---------------------------------------------------------+ MAIN WINDOW & DIALOGS+--------------------------------------------------------- */+QMainWindow, QDialog {+ background-color: #eff1f5;+}++/* Base frames and containers */+QFrame {+ border: none;+}+QFrame#MainContainer {+ background-color: #e6e9ef;+ border-radius: 8px;+ margin: 8px;+}++/* SPLITTER (adjustable dividers) */+QSplitter::handle {+ background-color: #dce0e8;+ margin: 2px;+ border-radius: 2px;+}+QSplitter::handle:hover {+ background-color: #1e66f5;+}+QSplitter::handle:horizontal {+ width: 4px;+}+QSplitter::handle:vertical {+ height: 4px;+}++/* ---------------------------------------------------------+ MENUS & TOOLBARS+--------------------------------------------------------- */+QMenuBar {+ background-color: #e6e9ef;+ color: #5c5f77;+ border-bottom: 1px solid #eff1f5;+}+QMenuBar::item {+ padding: 8px 14px;+ background: transparent;+ border-radius: 6px;+ margin: 4px;+}+QMenuBar::item:selected {+ background-color: #ccd0da;+ color: #4c4f69;+}+QMenuBar::item:pressed {+ background-color: #bcc0cc;+}++QMenu {+ background-color: #dce0e8;+ color: #4c4f69;+ border: 1px solid #ccd0da;+ border-radius: 8px;+ padding: 6px;+ margin: 0px;+}+QMenu::item {+ padding: 8px 30px 8px 24px;+ border-radius: 6px;+ margin: 2px 4px;+}+QMenu::item:selected {+ background-color: #ccd0da;+ color: #4c4f69;+}+QMenu::separator {+ height: 1px;+ background-color: #ccd0da;+ margin: 4px 10px;+}+QMenu::indicator {+ width: 16px;+ height: 16px;+ margin-left: 6px;+}++QToolBar {+ background-color: #e6e9ef;+ border: none;+ border-bottom: 1px solid #dce0e8;+ padding: 6px;+ spacing: 8px;+}+QToolBar::separator {+ background-color: #ccd0da;+ width: 1px;+ margin: 4px 8px;+}+QToolButton {+ background-color: transparent;+ border: none;+ border-radius: 6px;+ padding: 8px;+ color: #5c5f77;+}+QToolButton:hover {+ background-color: #ccd0da;+ color: #4c4f69;+}+QToolButton:pressed, QToolButton:checked {+ background-color: #1e66f5;+ color: #eff1f5;+}++/* ---------------------------------------------------------+ SCROLLBARS+--------------------------------------------------------- */+QScrollBar:vertical {+ background-color: transparent;+ width: 14px;+ margin: 0px;+}+QScrollBar::handle:vertical {+ background-color: #bcc0cc;+ border-radius: 5px;+ min-height: 30px;+ margin: 2px;+}+QScrollBar::handle:vertical:hover {+ background-color: #acb0be;+}+QScrollBar::handle:vertical:pressed {+ background-color: #1e66f5;+}+QScrollBar::sub-line:vertical, QScrollBar::add-line:vertical,+QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical {+ height: 0px; width: 0px; background: none; border: none;+}+QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {+ background: none;+}++QScrollBar:horizontal {+ background-color: transparent;+ height: 14px;+ margin: 0px;+}+QScrollBar::handle:horizontal {+ background-color: #bcc0cc;+ border-radius: 5px;+ min-width: 30px;+ margin: 2px;+}+QScrollBar::handle:horizontal:hover {+ background-color: #acb0be;+}+QScrollBar::handle:horizontal:pressed {+ background-color: #1e66f5;+}+QScrollBar::sub-line:horizontal, QScrollBar::add-line:horizontal,+QScrollBar::left-arrow:horizontal, QScrollBar::right-arrow:horizontal {+ width: 0px; height: 0px; background: none; border: none;+}+QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {+ background: none;+}++/* ---------------------------------------------------------+ BUTTONS+--------------------------------------------------------- */+QPushButton {+ background-color: #ccd0da;+ color: #4c4f69;+ border: 1px solid #bcc0cc;+ border-radius: 6px;+ padding: 8px 16px;+ font-weight: 600;+}+QPushButton:hover {+ background-color: #bcc0cc;+ border-color: #acb0be;+ color: #4c4f69;+}+QPushButton:pressed, QPushButton:checked {+ background-color: #1e66f5;+ border-color: #1e66f5;+ color: #eff1f5;+}+QPushButton:disabled {+ background-color: #dce0e8;+ border-color: #ccd0da;+ color: #acb0be;+}++QPushButton#primaryButton, QPushButton#commitButton {+ background-color: #1e66f5;+ color: #eff1f5;+ border: none;+}+QPushButton#primaryButton:hover, QPushButton#commitButton:hover {+ background-color: #8839ef;+}+QPushButton#primaryButton:pressed, QPushButton#primaryButton:checked, QPushButton#commitButton:pressed, QPushButton#commitButton:checked {+ background-color: #179299;+ color: #eff1f5;+}+QPushButton#dangerButton, QPushButton#discardButton {+ background-color: #d20f39;+ color: #eff1f5;+ border: none;+}+QPushButton#dangerButton:hover, QPushButton#discardButton:hover {+ background-color: #e64553;+}+QPushButton#dangerButton:pressed, QPushButton#discardButton:pressed {+ background-color: #b5000e;+}++QWidget[compact="true"] QPushButton {+ padding: 4px 10px;+ font-size: 12px;+ font-weight: 500;+ min-height: 0;+ border-radius: 5px;+}+QWidget[compact="true"] QSpinBox,+QWidget[compact="true"] QDoubleSpinBox,+QWidget[compact="true"] QLineEdit,+QWidget[compact="true"] QComboBox {+ padding: 3px 8px;+ font-size: 12px;+ min-height: 0;+ border-radius: 5px;+}+QWidget[compact="true"] QLabel {+ font-size: 12px;+ padding: 0 2px;+}++QPushButton[toolbarIcon="true"] {+ background-color: transparent;+ color: #5c5f77;+ border: none;+ border-right: 1px solid #dce0e8;+ border-radius: 0;+ padding: 0;+ font-size: 13px;+ min-height: 0;+}+QPushButton[toolbarIcon="true"]:hover {+ background-color: #dce0e8;+ color: #4c4f69;+}+QPushButton[toolbarIcon="true"]:checked {+ color: #1e66f5;+ background-color: #dce0e8;+}+QPushButton[toolbarIcon="true"]:disabled {+ color: #bcc0cc;+ background-color: transparent;+}++QPushButton#connDot {+ background-color: transparent;+ color: #acb0be;+ border: none;+ border-right: 1px solid #dce0e8;+ border-radius: 0;+ padding: 0;+ font-size: 10px;+ min-height: 0;+}+QPushButton#connDot[connected="true"] {+ color: #40a02b;+}++QWidget#WorkspaceTabBar {+ background-color: #e6e9ef;+ border-bottom: 1px solid #dce0e8;+}+QPushButton#newTabButton {+ background-color: transparent;+ color: #5c5f77;+ font-size: 16px;+ font-weight: 500;+ border: none;+ border-right: 1px solid #dce0e8;+ border-radius: 0;+ padding: 0;+}+QPushButton#newTabButton:hover {+ background-color: #dce0e8;+ color: #1e66f5;+}++QWidget[queryTab="true"] {+ background-color: transparent;+ border-right: 1px solid #dce0e8;+}+QWidget[queryTab="true"][active="true"] {+ background-color: #eff1f5;+ border-bottom: 2px solid #1e66f5;+}++QLabel#statusDot {+ background-color: #bcc0cc;+ border-radius: 3px;+}+QLabel#statusDot[active="true"] {+ background-color: #d20f39;+}++QPushButton[queryTabLabel="true"] {+ background-color: transparent;+ color: #5c5f77;+ border: none;+ border-radius: 0;+ padding: 0 4px;+ font-size: 12px;+ font-weight: 500;+ min-height: 0;+}+QPushButton[queryTabLabel="true"][active="true"] {+ color: #4c4f69;+ font-weight: 700;+}++QPushButton#queryTabClose {+ background-color: transparent;+ color: #acb0be;+ border: none;+ border-radius: 9px;+ padding: 0;+ font-size: 14px;+ font-weight: 500;+ min-height: 0;+}+QPushButton#queryTabClose:hover {+ background-color: #ccd0da;+ color: #d20f39;+}++QPushButton[tab="true"] {+ background-color: transparent;+ color: #acb0be;+ border: none;+ border-bottom: 2px solid transparent;+ border-radius: 0;+ padding: 6px 12px;+ font-weight: 600;+}+QPushButton[tab="true"]:hover {+ color: #5c5f77;+ background-color: transparent;+}+QPushButton[tab="true"]:checked {+ color: #1e66f5;+ background-color: transparent;+ border-bottom: 2px solid #1e66f5;+}+QPushButton[tab="true"]:disabled {+ color: #bcc0cc;+ background-color: transparent;+}++/* ---------------------------------------------------------+ INPUTS (LineEdit, TextEdit, SpinBox)+--------------------------------------------------------- */+QLineEdit, QTextEdit, QPlainTextEdit, QSpinBox, QDoubleSpinBox {+ background-color: #e6e9ef;+ color: #4c4f69;+ border: 1px solid #ccd0da;+ border-radius: 6px;+ padding: 8px 12px;+ selection-background-color: #bcc0cc;+}+QLineEdit:hover, QTextEdit:hover, QPlainTextEdit:hover, QSpinBox:hover, QDoubleSpinBox:hover {+ border: 1px solid #acb0be;+ background-color: #dce0e8;+}+QLineEdit:focus, QTextEdit:focus, QPlainTextEdit:focus, QSpinBox:focus, QDoubleSpinBox:focus {+ border: 1px solid #1e66f5;+ background-color: #eff1f5;+}+QLineEdit:disabled, QTextEdit:disabled, QPlainTextEdit:disabled, QSpinBox:disabled {+ background-color: #dce0e8;+ color: #acb0be;+ border-color: #eff1f5;+}++QAbstractItemView QLineEdit,+QAbstractItemView QTextEdit,+QAbstractItemView QPlainTextEdit,+QAbstractItemView QSpinBox,+QAbstractItemView QDoubleSpinBox,+QAbstractItemView QComboBox {+ padding: 0 4px;+ margin: 0;+ border: 1px solid #1e66f5;+ border-radius: 2px;+ background-color: #dce0e8;+ color: #4c4f69;+ selection-background-color: #1e66f5;+ selection-color: #eff1f5;+ min-height: 0;+}++/* ---------------------------------------------------------+ COMBOBOX+--------------------------------------------------------- */+QComboBox {+ background-color: #e6e9ef;+ color: #4c4f69;+ border: 1px solid #ccd0da;+ border-radius: 6px;+ padding: 6px 12px;+}+QComboBox:hover {+ border: 1px solid #acb0be;+ background-color: #dce0e8;+}+QComboBox:focus {+ border: 1px solid #1e66f5;+ background-color: #eff1f5;+}+QComboBox::drop-down {+ subcontrol-origin: padding;+ subcontrol-position: top right;+ width: 24px;+ border-left: none;+}+QComboBox::down-arrow {+ image: none;+ border-left: 5px solid transparent;+ border-right: 5px solid transparent;+ border-top: 5px solid #6c6f85;+ margin-right: 8px;+}+QComboBox QAbstractItemView {+ background-color: #dce0e8;+ border: 1px solid #ccd0da;+ border-radius: 6px;+ outline: none;+ padding: 4px;+ selection-background-color: #ccd0da;+ selection-color: #4c4f69;+}+QComboBox QAbstractItemView::item {+ border-radius: 4px;+ padding: 6px;+}+QComboBox QAbstractItemView::item:selected {+ background-color: #ccd0da;+}++/* ---------------------------------------------------------+ TAB WIDGETS & TAB BAR+--------------------------------------------------------- */+QTabWidget::pane {+ border: 1px solid #ccd0da;+ border-radius: 8px;+ background-color: #eff1f5;+ top: -1px;+}+QTabBar {+ qproperty-drawBase: 0;+}+QTabBar::tab {+ background-color: #e6e9ef;+ color: #acb0be;+ padding: 10px 20px;+ border: 1px solid transparent;+ border-bottom: 2px solid transparent;+ border-top-left-radius: 8px;+ border-top-right-radius: 8px;+ margin-right: 4px;+ font-weight: 600;+}+QTabBar::tab:hover {+ background-color: #dce0e8;+ color: #5c5f77;+}+QTabBar::tab:selected {+ background-color: #eff1f5;+ color: #1e66f5;+ border-bottom: 2px solid #1e66f5;+}++/* ---------------------------------------------------------+ TABLE & TREE VIEWS+--------------------------------------------------------- */+QTableView, QTreeView, QListView {+ background-color: #eff1f5;+ alternate-background-color: #dce0e8;+ color: #4c4f69;+ border: 1px solid #dce0e8;+ border-radius: 8px;+ gridline-color: #ccd0da;+ outline: none;+ selection-background-color: transparent;+}+QTableView::item, QTreeView::item, QListView::item {+ padding: 2px 8px;+ border: none;+}+QTableView::item:hover, QTreeView::item:hover, QListView::item:hover {+ background-color: #ccd0da;+ color: #4c4f69;+}+QTableView::item:selected, QTreeView::item:selected, QListView::item:selected {+ background-color: rgba(30, 102, 245, 0.15);+ color: #1e66f5;+}+QTreeView {+ show-decoration-selected: 1;+}++/* Tree Branches */+QTreeView::branch:has-siblings:!adjoins-item { border-image: none; }+QTreeView::branch:has-siblings:adjoins-item { border-image: none; }+QTreeView::branch:!has-children:!has-siblings:adjoins-item { border-image: none; }+QTreeView::branch:has-children:closed { border-image: none; }+QTreeView::branch:open:has-children { border-image: none; }++/* ---------------------------------------------------------+ HEADER VIEWS (Table columns)+--------------------------------------------------------- */+QHeaderView {+ background-color: #eff1f5;+ border: none;+ border-top-left-radius: 8px;+ border-top-right-radius: 8px;+}+QHeaderView::section {+ background-color: #dce0e8;+ color: #6c6f85;+ padding: 8px 12px;+ border: none;+ border-right: 1px solid #ccd0da;+ border-bottom: 2px solid #ccd0da;+ font-weight: 600;+}+QHeaderView::section:hover {+ background-color: rgba(204, 208, 218, 0.5);+ color: #4c4f69;+}+QHeaderView::section:checked {+ background-color: #ccd0da;+ color: #1e66f5;+ border-bottom: 2px solid #1e66f5;+}++/* ---------------------------------------------------------+ STATUS BAR+--------------------------------------------------------- */+QStatusBar {+ background-color: #e6e9ef;+ color: #5c5f77;+ border-top: 1px solid #dce0e8;+}+QStatusBar::item {+ border: none;+}+QStatusBar QLabel {+ padding: 2px 8px;+}++/* ---------------------------------------------------------+ GROUP BOX+--------------------------------------------------------- */+QGroupBox {+ background-color: #dce0e8;+ border: 1px solid #ccd0da;+ border-radius: 8px;+ margin-top: 14px;+ font-weight: 600;+ padding-top: 14px;+}+QGroupBox::title {+ subcontrol-origin: margin;+ subcontrol-position: top left;+ padding: 0 10px;+ color: #1e66f5;+ background-color: transparent;+}++/* ---------------------------------------------------------+ CHECKBOX & RADIOBUTTON+--------------------------------------------------------- */+QCheckBox, QRadioButton {+ spacing: 8px;+ color: #4c4f69;+ padding: 4px;+}+QCheckBox:hover, QRadioButton:hover {+ color: #1e66f5;+}+QCheckBox::indicator, QRadioButton::indicator {+ width: 20px;+ height: 20px;+ border: 1px solid #bcc0cc;+ background-color: #e6e9ef;+ border-radius: 4px;+}+QRadioButton::indicator {+ border-radius: 10px;+}+QCheckBox::indicator:hover, QRadioButton::indicator:hover {+ border: 1px solid #1e66f5;+ background-color: #dce0e8;+}+QCheckBox::indicator:checked {+ background-color: #1e66f5;+ border: 1px solid #1e66f5;+}+QRadioButton::indicator:checked {+ background-color: #e6e9ef;+ border: 6px solid #1e66f5;+}++/* ---------------------------------------------------------+ PROGRESS BAR+--------------------------------------------------------- */+QProgressBar {+ background-color: #e6e9ef;+ border: 1px solid #ccd0da;+ border-radius: 8px;+ text-align: center;+ color: #4c4f69;+ font-weight: bold;+}+QProgressBar::chunk {+ background-color: #1e66f5;+ border-radius: 7px;+}++/* ---------------------------------------------------------+ QUERY LOG PANEL+--------------------------------------------------------- */+QWidget#QueryLogHeader {+ background-color: #e6e9ef;+}+QPushButton#QueryLogToggle, QPushButton#QueryLogClear {+ background-color: transparent;+ border: none;+ font-size: 11px;+ color: #6c6f85;+ padding: 2px 6px;+}+QPushButton#QueryLogToggle:hover, QPushButton#QueryLogClear:hover {+ color: #4c4f69;+ background-color: #ccd0da;+}+QLabel#QueryLogTitle {+ color: #6c6f85;+ font-size: 12px;+ font-weight: bold;+}+QPlainTextEdit#QueryLogEdit {+ background-color: #e6e9ef;+ border: 1px solid #dce0e8;+ border-top: none;+ border-radius: 0px;+ border-bottom-left-radius: 8px;+ border-bottom-right-radius: 8px;+ font-family: monospace;+ font-size: 12px;+ color: #6c6f85;+ padding: 6px 10px;+}diff --git a/linux/resources/style.qss b/linux/resources/style.qssnew file mode 100644index 0000000..5e4bc44--- /dev/null+++ b/linux/resources/style.qss@@ -0,0 +1,703 @@+/* Gridex Modern Dark Theme (Catppuccin Mocha Inspired) */++/* ---------------------------------------------------------+ GLOBAL RESET & BASICS+--------------------------------------------------------- */+QWidget {+ background-color: #1e1e2e;+ color: #cdd6f4;+ font-family: "Inter", "Segoe UI", "Roboto", sans-serif;+ font-size: 13px;+ border: none;+}++QToolTip {+ background-color: #11111b;+ color: #cdd6f4;+ border: 1px solid #313244;+ border-radius: 6px;+ padding: 6px 10px;+ font-weight: 500;+}++/* ---------------------------------------------------------+ MAIN WINDOW & DIALOGS+--------------------------------------------------------- */+QMainWindow, QDialog {+ background-color: #1e1e2e;+}++/* Base frames and containers */+QFrame {+ border: none;+}+QFrame#MainContainer {+ background-color: #11111b; /* darker background for internal workspace */+ border-radius: 8px;+ margin: 8px;+}++/* SPLITTER (adjustable dividers) */+QSplitter::handle {+ background-color: #181825;+ margin: 2px;+ border-radius: 2px;+}+QSplitter::handle:hover {+ background-color: #89b4fa;+}+QSplitter::handle:horizontal {+ width: 4px;+}+QSplitter::handle:vertical {+ height: 4px;+}++/* ---------------------------------------------------------+ MENUS & TOOLBARS+--------------------------------------------------------- */+QMenuBar {+ background-color: #11111b;+ color: #bac2de;+ border-bottom: 1px solid #1e1e2e;+}+QMenuBar::item {+ padding: 8px 14px;+ background: transparent;+ border-radius: 6px;+ margin: 4px;+}+QMenuBar::item:selected {+ background-color: #313244;+ color: #cdd6f4;+}+QMenuBar::item:pressed {+ background-color: #45475a;+}++QMenu {+ background-color: #181825;+ color: #cdd6f4;+ border: 1px solid #313244;+ border-radius: 8px;+ padding: 6px;+ margin: 0px;+}+QMenu::item {+ padding: 8px 30px 8px 24px;+ border-radius: 6px;+ margin: 2px 4px;+}+QMenu::item:selected {+ background-color: #313244;+ color: #cdd6f4;+}+QMenu::separator {+ height: 1px;+ background-color: #313244;+ margin: 4px 10px;+}+QMenu::indicator {+ width: 16px;+ height: 16px;+ margin-left: 6px;+}++QToolBar {+ background-color: #11111b;+ border: none;+ border-bottom: 1px solid #181825;+ padding: 6px;+ spacing: 8px;+}+QToolBar::separator {+ background-color: #313244;+ width: 1px;+ margin: 4px 8px;+}+QToolButton {+ background-color: transparent;+ border: none;+ border-radius: 6px;+ padding: 8px;+ color: #bac2de;+}+QToolButton:hover {+ background-color: #313244;+ color: #cdd6f4;+}+QToolButton:pressed, QToolButton:checked {+ background-color: #89b4fa;+ color: #11111b;+}++/* ---------------------------------------------------------+ SCROLLBARS+--------------------------------------------------------- */+QScrollBar:vertical {+ background-color: transparent;+ width: 14px;+ margin: 0px;+}+QScrollBar::handle:vertical {+ background-color: #45475a;+ border-radius: 5px;+ min-height: 30px;+ margin: 2px;+}+QScrollBar::handle:vertical:hover {+ background-color: #585b70;+}+QScrollBar::handle:vertical:pressed {+ background-color: #89b4fa;+}+QScrollBar::sub-line:vertical, QScrollBar::add-line:vertical,+QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical {+ height: 0px; width: 0px; background: none; border: none;+}+QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {+ background: none;+}++QScrollBar:horizontal {+ background-color: transparent;+ height: 14px;+ margin: 0px;+}+QScrollBar::handle:horizontal {+ background-color: #45475a;+ border-radius: 5px;+ min-width: 30px;+ margin: 2px;+}+QScrollBar::handle:horizontal:hover {+ background-color: #585b70;+}+QScrollBar::handle:horizontal:pressed {+ background-color: #89b4fa;+}+QScrollBar::sub-line:horizontal, QScrollBar::add-line:horizontal,+QScrollBar::left-arrow:horizontal, QScrollBar::right-arrow:horizontal {+ width: 0px; height: 0px; background: none; border: none;+}+QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {+ background: none;+}++/* ---------------------------------------------------------+ BUTTONS+--------------------------------------------------------- */+QPushButton {+ background-color: #313244;+ color: #cdd6f4;+ border: 1px solid #45475a;+ border-radius: 6px;+ padding: 8px 16px;+ font-weight: 600;+}+QPushButton:hover {+ background-color: #45475a;+ border-color: #585b70;+ color: #ffffff;+}+QPushButton:pressed, QPushButton:checked {+ background-color: #89b4fa;+ border-color: #89b4fa;+ color: #11111b;+}+QPushButton:disabled {+ background-color: #181825;+ border-color: #313244;+ color: #6c7086;+}++/* Primary actions or danger buttons can be styled differently via dynamic properties or object name */+QPushButton#primaryButton, QPushButton#commitButton {+ background-color: #89b4fa;+ color: #11111b;+ border: none;+}+QPushButton#primaryButton:hover, QPushButton#commitButton:hover {+ background-color: #b4befe;+}+QPushButton#primaryButton:pressed, QPushButton#primaryButton:checked, QPushButton#commitButton:pressed, QPushButton#commitButton:checked {+ background-color: #74c7ec;+ color: #11111b;+}+QPushButton#dangerButton, QPushButton#discardButton {+ background-color: #f38ba8;+ color: #11111b;+ border: none;+}+QPushButton#dangerButton:hover, QPushButton#discardButton:hover {+ background-color: #f5e0dc;+}+QPushButton#dangerButton:pressed, QPushButton#discardButton:pressed {+ background-color: #eba0ac;+}++/* Compact density: set QWidget property compact="true" on a container and+ all descendant QPushButton / QSpinBox / QComboBox / QLineEdit shrink to+ toolbar-size instead of the default 8px/16px padding. */+QWidget[compact="true"] QPushButton {+ padding: 4px 10px;+ font-size: 12px;+ font-weight: 500;+ min-height: 0;+ border-radius: 5px;+}+QWidget[compact="true"] QSpinBox,+QWidget[compact="true"] QDoubleSpinBox,+QWidget[compact="true"] QLineEdit,+QWidget[compact="true"] QComboBox {+ padding: 3px 8px;+ font-size: 12px;+ min-height: 0;+ border-radius: 5px;+}+QWidget[compact="true"] QLabel {+ font-size: 12px;+ padding: 0 2px;+}++/* Toolbar icon buttons — flat, no chrome, hover highlight; checked state+ shows an accent (sidebar / details toggles). Opt-in via toolbarIcon. */+QPushButton[toolbarIcon="true"] {+ background-color: transparent;+ color: #bac2de;+ border: none;+ border-right: 1px solid #181825;+ border-radius: 0;+ padding: 0;+ font-size: 13px;+ min-height: 0;+}+QPushButton[toolbarIcon="true"]:hover {+ background-color: #181825;+ color: #cdd6f4;+}+QPushButton[toolbarIcon="true"]:checked {+ color: #89b4fa;+ background-color: #181825;+}+QPushButton[toolbarIcon="true"]:disabled {+ color: #45475a;+ background-color: transparent;+}++/* Connection status dot in the top toolbar: gray when disconnected,+ Catppuccin green when a live connection is open. */+QPushButton#connDot {+ background-color: transparent;+ color: #6c7086;+ border: none;+ border-right: 1px solid #181825;+ border-radius: 0;+ padding: 0;+ font-size: 10px;+ min-height: 0;+}+QPushButton#connDot[connected="true"] {+ color: #a6e3a1;+}++/* Workspace tab bar (top query tabs) */+QWidget#WorkspaceTabBar {+ background-color: #11111b;+ border-bottom: 1px solid #181825;+}+QPushButton#newTabButton {+ background-color: transparent;+ color: #bac2de;+ font-size: 16px;+ font-weight: 500;+ border: none;+ border-right: 1px solid #181825;+ border-radius: 0;+ padding: 0;+}+QPushButton#newTabButton:hover {+ background-color: #181825;+ color: #89b4fa;+}++QWidget[queryTab="true"] {+ background-color: transparent;+ border-right: 1px solid #181825;+}+QWidget[queryTab="true"][active="true"] {+ background-color: #1e1e2e;+ border-bottom: 2px solid #89b4fa;+}++QLabel#statusDot {+ background-color: #45475a;+ border-radius: 3px;+}+QLabel#statusDot[active="true"] {+ background-color: #f38ba8;+}++QPushButton[queryTabLabel="true"] {+ background-color: transparent;+ color: #bac2de;+ border: none;+ border-radius: 0;+ padding: 0 4px;+ font-size: 12px;+ font-weight: 500;+ min-height: 0;+}+QPushButton[queryTabLabel="true"][active="true"] {+ color: #cdd6f4;+ font-weight: 700;+}++QPushButton#queryTabClose {+ background-color: transparent;+ color: #6c7086;+ border: none;+ border-radius: 9px;+ padding: 0;+ font-size: 14px;+ font-weight: 500;+ min-height: 0;+}+QPushButton#queryTabClose:hover {+ background-color: #313244;+ color: #f38ba8;+}++/* Tab-style buttons: checkable QPushButton that should look like a tab+ (underline active indicator, no chrome). Opt-in via property "tab". */+QPushButton[tab="true"] {+ background-color: transparent;+ color: #6c7086;+ border: none;+ border-bottom: 2px solid transparent;+ border-radius: 0;+ padding: 6px 12px;+ font-weight: 600;+}+QPushButton[tab="true"]:hover {+ color: #bac2de;+ background-color: transparent;+}+QPushButton[tab="true"]:checked {+ color: #89b4fa;+ background-color: transparent;+ border-bottom: 2px solid #89b4fa;+}+QPushButton[tab="true"]:disabled {+ color: #45475a;+ background-color: transparent;+}++/* ---------------------------------------------------------+ INPUTS (LineEdit, TextEdit, SpinBox)+--------------------------------------------------------- */+QLineEdit, QTextEdit, QPlainTextEdit, QSpinBox, QDoubleSpinBox {+ background-color: #11111b;+ color: #cdd6f4;+ border: 1px solid #313244;+ border-radius: 6px;+ padding: 8px 12px;+ selection-background-color: #585b70;+}+QLineEdit:hover, QTextEdit:hover, QPlainTextEdit:hover, QSpinBox:hover, QDoubleSpinBox:hover {+ border: 1px solid #585b70;+ background-color: #181825;+}+QLineEdit:focus, QTextEdit:focus, QPlainTextEdit:focus, QSpinBox:focus, QDoubleSpinBox:focus {+ border: 1px solid #89b4fa;+ background-color: #1e1e2e;+}+QLineEdit:disabled, QTextEdit:disabled, QPlainTextEdit:disabled, QSpinBox:disabled {+ background-color: #181825;+ color: #6c7086;+ border-color: #1e1e2e;+}++/* Inline cell editors (spawned by QTableView / QTreeView when a cell is+ double-clicked). The global QLineEdit padding/radius is too big for a+ 22px row, so we tighten it for editors living inside an item view. */+QAbstractItemView QLineEdit,+QAbstractItemView QTextEdit,+QAbstractItemView QPlainTextEdit,+QAbstractItemView QSpinBox,+QAbstractItemView QDoubleSpinBox,+QAbstractItemView QComboBox {+ padding: 0 4px;+ margin: 0;+ border: 1px solid #89b4fa;+ border-radius: 2px;+ background-color: #181825;+ color: #cdd6f4;+ selection-background-color: #89b4fa;+ selection-color: #11111b;+ min-height: 0;+}++/* ---------------------------------------------------------+ COMBOBOX+--------------------------------------------------------- */+QComboBox {+ background-color: #11111b;+ color: #cdd6f4;+ border: 1px solid #313244;+ border-radius: 6px;+ padding: 6px 12px;+}+QComboBox:hover {+ border: 1px solid #585b70;+ background-color: #181825;+}+QComboBox:focus {+ border: 1px solid #89b4fa;+ background-color: #1e1e2e;+}+QComboBox::drop-down {+ subcontrol-origin: padding;+ subcontrol-position: top right;+ width: 24px;+ border-left: none;+}+QComboBox::down-arrow {+ image: none;+ border-left: 5px solid transparent;+ border-right: 5px solid transparent;+ border-top: 5px solid #a6adc8;+ margin-right: 8px;+}+QComboBox QAbstractItemView {+ background-color: #181825;+ border: 1px solid #313244;+ border-radius: 6px;+ outline: none;+ padding: 4px;+ selection-background-color: #313244;+ selection-color: #cdd6f4;+}+QComboBox QAbstractItemView::item {+ border-radius: 4px;+ padding: 6px;+}+QComboBox QAbstractItemView::item:selected {+ background-color: #313244;+}++/* ---------------------------------------------------------+ TAB WIDGETS & TAB BAR+--------------------------------------------------------- */+QTabWidget::pane {+ border: 1px solid #313244;+ border-radius: 8px;+ background-color: #1e1e2e;+ top: -1px;+}+QTabBar {+ qproperty-drawBase: 0;+}+QTabBar::tab {+ background-color: #11111b;+ color: #6c7086;+ padding: 10px 20px;+ border: 1px solid transparent;+ border-bottom: 2px solid transparent;+ border-top-left-radius: 8px;+ border-top-right-radius: 8px;+ margin-right: 4px;+ font-weight: 600;+}+QTabBar::tab:hover {+ background-color: #181825;+ color: #bac2de;+}+QTabBar::tab:selected {+ background-color: #1e1e2e;+ color: #89b4fa;+ border-bottom: 2px solid #89b4fa;+}++/* ---------------------------------------------------------+ TABLE & TREE VIEWS+--------------------------------------------------------- */+QTableView, QTreeView, QListView {+ background-color: #1e1e2e;+ alternate-background-color: #181825;+ color: #cdd6f4;+ border: 1px solid #181825;+ border-radius: 8px;+ gridline-color: #313244;+ outline: none;+ selection-background-color: transparent;+}+QTableView::item, QTreeView::item, QListView::item {+ padding: 2px 8px;+ border: none;+}+QTableView::item:hover, QTreeView::item:hover, QListView::item:hover {+ background-color: #313244;+ color: #ffffff;+}+QTableView::item:selected, QTreeView::item:selected, QListView::item:selected {+ background-color: rgba(137, 180, 250, 0.2);+ color: #89b4fa;+}+QTreeView {+ show-decoration-selected: 1;+}++/* Tree Branches */+QTreeView::branch:has-siblings:!adjoins-item { border-image: none; }+QTreeView::branch:has-siblings:adjoins-item { border-image: none; }+QTreeView::branch:!has-children:!has-siblings:adjoins-item { border-image: none; }+QTreeView::branch:has-children:closed { border-image: none; }+QTreeView::branch:open:has-children { border-image: none; }++/* ---------------------------------------------------------+ HEADER VIEWS (Table columns)+--------------------------------------------------------- */+QHeaderView {+ background-color: #1e1e2e;+ border: none;+ border-top-left-radius: 8px;+ border-top-right-radius: 8px;+}+QHeaderView::section {+ background-color: #181825;+ color: #a6adc8;+ padding: 8px 12px;+ border: none;+ border-right: 1px solid #313244;+ border-bottom: 2px solid #313244;+ font-weight: 600;+}+QHeaderView::section:hover {+ background-color: rgba(49, 50, 68, 0.5);+ color: #cdd6f4;+}+QHeaderView::section:checked {+ background-color: #313244;+ color: #89b4fa;+ border-bottom: 2px solid #89b4fa;+}++/* ---------------------------------------------------------+ STATUS BAR+--------------------------------------------------------- */+QStatusBar {+ background-color: #11111b;+ color: #bac2de;+ border-top: 1px solid #181825;+}+QStatusBar::item {+ border: none;+}+QStatusBar QLabel {+ padding: 2px 8px;+}++/* ---------------------------------------------------------+ GROUP BOX+--------------------------------------------------------- */+QGroupBox {+ background-color: #181825;+ border: 1px solid #313244;+ border-radius: 8px;+ margin-top: 14px;+ font-weight: 600;+ padding-top: 14px;+}+QGroupBox::title {+ subcontrol-origin: margin;+ subcontrol-position: top left;+ padding: 0 10px;+ color: #89b4fa;+ background-color: transparent;+}++/* ---------------------------------------------------------+ CHECKBOX & RADIOBUTTON+--------------------------------------------------------- */+QCheckBox, QRadioButton {+ spacing: 8px;+ color: #cdd6f4;+ padding: 4px;+}+QCheckBox:hover, QRadioButton:hover {+ color: #89b4fa;+}+QCheckBox::indicator, QRadioButton::indicator {+ width: 20px;+ height: 20px;+ border: 1px solid #45475a;+ background-color: #11111b;+ border-radius: 4px;+}+QRadioButton::indicator {+ border-radius: 10px;+}+QCheckBox::indicator:hover, QRadioButton::indicator:hover {+ border: 1px solid #89b4fa;+ background-color: #181825;+}+QCheckBox::indicator:checked {+ background-color: #89b4fa;+ border: 1px solid #89b4fa;+}+QRadioButton::indicator:checked {+ background-color: #11111b;+ border: 6px solid #89b4fa;+}++/* ---------------------------------------------------------+ PROGRESS BAR+--------------------------------------------------------- */+QProgressBar {+ background-color: #11111b;+ border: 1px solid #313244;+ border-radius: 8px;+ text-align: center;+ color: #cdd6f4;+ font-weight: bold;+}+QProgressBar::chunk {+ background-color: #89b4fa;+ border-radius: 7px;+}++/* ---------------------------------------------------------+ QUERY LOG PANEL+--------------------------------------------------------- */+QWidget#QueryLogHeader {+ background-color: #11111b;+}+QPushButton#QueryLogToggle, QPushButton#QueryLogClear {+ background-color: transparent;+ border: none;+ font-size: 11px;+ color: #a6adc8;+ padding: 2px 6px;+}+QPushButton#QueryLogToggle:hover, QPushButton#QueryLogClear:hover {+ color: #cdd6f4;+ background-color: #313244;+}+QLabel#QueryLogTitle {+ color: #a6adc8;+ font-size: 12px;+ font-weight: bold;+}+QPlainTextEdit#QueryLogEdit {+ background-color: #11111b;+ border: 1px solid #181825;+ border-top: none;+ border-radius: 0px;+ border-bottom-left-radius: 8px;+ border-bottom-right-radius: 8px;+ font-family: monospace;+ font-size: 12px;+ color: #a6adc8;+ padding: 6px 10px;+}diff --git a/linux/src/App/CMakeLists.txt b/linux/src/App/CMakeLists.txtnew file mode 100644index 0000000..078fe4e--- /dev/null+++ b/linux/src/App/CMakeLists.txt@@ -0,0 +1,14 @@+add_library(gridex-app STATIC+ DependencyInjection/DIContainer.cpp+ MCP/MCPConnectionProvider.cpp+)++target_include_directories(gridex-app PUBLIC+ ${CMAKE_CURRENT_SOURCE_DIR}/..+)++target_link_libraries(gridex-app PUBLIC+ gridex-core+ gridex-data+ gridex-services+)diff --git a/linux/src/App/DependencyInjection/DIContainer.cpp b/linux/src/App/DependencyInjection/DIContainer.cppnew file mode 100644index 0000000..19f95eb--- /dev/null+++ b/linux/src/App/DependencyInjection/DIContainer.cpp@@ -0,0 +1 @@+#include "App/DependencyInjection/DIContainer.h"diff --git a/linux/src/App/DependencyInjection/DIContainer.h b/linux/src/App/DependencyInjection/DIContainer.hnew file mode 100644index 0000000..a9ea6a6--- /dev/null+++ b/linux/src/App/DependencyInjection/DIContainer.h@@ -0,0 +1,59 @@+#pragma once++#include <any>+#include <functional>+#include <memory>+#include <mutex>+#include <shared_mutex>+#include <string>+#include <typeindex>+#include <unordered_map>++#include "Core/Errors/GridexError.h"++namespace gridex {++class DIContainer {+public:+ DIContainer() = default;+ DIContainer(const DIContainer&) = delete;+ DIContainer& operator=(const DIContainer&) = delete;++ template <typename T>+ void registerSingleton(std::shared_ptr<T> instance) {+ std::unique_lock lock(mutex_);+ singletons_[std::type_index(typeid(T))] = std::move(instance);+ }++ template <typename T>+ void registerFactory(std::function<std::shared_ptr<T>()> factory) {+ std::unique_lock lock(mutex_);+ factories_[std::type_index(typeid(T))] = [f = std::move(factory)]() -> std::any {+ return f();+ };+ }++ template <typename T>+ std::shared_ptr<T> resolve() {+ std::shared_lock lock(mutex_);+ const auto key = std::type_index(typeid(T));++ if (auto it = singletons_.find(key); it != singletons_.end()) {+ return std::any_cast<std::shared_ptr<T>>(it->second);+ }++ if (auto it = factories_.find(key); it != factories_.end()) {+ auto produced = it->second();+ return std::any_cast<std::shared_ptr<T>>(produced);+ }++ throw InternalError(std::string("DIContainer: no binding for ") + typeid(T).name());+ }++private:+ mutable std::shared_mutex mutex_;+ std::unordered_map<std::type_index, std::any> singletons_;+ std::unordered_map<std::type_index, std::function<std::any()>> factories_;+};++}diff --git a/linux/src/App/MCP/MCPConnectionProvider.cpp b/linux/src/App/MCP/MCPConnectionProvider.cppnew file mode 100644index 0000000..a6f14ca--- /dev/null+++ b/linux/src/App/MCP/MCPConnectionProvider.cpp@@ -0,0 +1,57 @@+#include "App/MCP/MCPConnectionProvider.h"++#include "Data/Adapters/AdapterFactory.h"+#include "Data/Keychain/SecretStore.h"+#include "Domain/Repositories/IConnectionRepository.h"+#include "Services/MCP/Protocol.h"++namespace gridex {++MCPConnectionProvider::MCPConnectionProvider(IConnectionRepository* repo, SecretStore* secretStore)+ : repo_(repo), secretStore_(secretStore) {}++std::pair<std::shared_ptr<IDatabaseAdapter>, ConnectionConfig>+MCPConnectionProvider::openConnection(const std::string& connectionId) {+ if (!repo_) throw mcp::MCPToolError::connectionNotFound(connectionId);+ auto cfg = repo_->fetchById(connectionId);+ if (!cfg) throw mcp::MCPToolError::connectionNotFound(connectionId);++ // Fast path: reuse cached adapter.+ {+ std::lock_guard lk(mu_);+ if (auto it = cache_.find(connectionId); it != cache_.end() && it->second && it->second->isConnected()) {+ return {it->second, *cfg};+ }+ }++ std::unique_ptr<IDatabaseAdapter> u = createAdapter(cfg->databaseType);+ if (!u) throw mcp::MCPToolError::connectionNotFound(connectionId);++ std::optional<std::string> password;+ if (secretStore_) password = secretStore_->loadPassword(connectionId);++ try {+ u->connect(*cfg, password);+ } catch (const std::exception& e) {+ throw mcp::MCPToolError::connectionNotConnected(connectionId);+ }++ std::shared_ptr<IDatabaseAdapter> s(std::move(u));+ {+ std::lock_guard lk(mu_);+ cache_[connectionId] = s;+ }+ return {s, *cfg};+}++bool MCPConnectionProvider::hasConnection(const std::string& connectionId) {+ if (!repo_) return false;+ return repo_->fetchById(connectionId).has_value();+}++std::vector<ConnectionConfig> MCPConnectionProvider::listConnections() {+ if (!repo_) return {};+ return repo_->fetchAll();+}++} // namespace gridexdiff --git a/linux/src/App/MCP/MCPConnectionProvider.h b/linux/src/App/MCP/MCPConnectionProvider.hnew file mode 100644index 0000000..c892830--- /dev/null+++ b/linux/src/App/MCP/MCPConnectionProvider.h@@ -0,0 +1,37 @@+#pragma once++// Concrete IMCPConnectionProvider wired into the App layer. Lazily opens+// database adapters for any connection ID by looking up ConnectionConfig in+// the connection repository, reading the password from the system keychain,+// and calling IDatabaseAdapter::connect().++#include <memory>+#include <mutex>+#include <string>+#include <unordered_map>++#include "Services/MCP/Tools/MCPTool.h"++namespace gridex {++class IConnectionRepository;+class SecretStore;++class MCPConnectionProvider : public mcp::IMCPConnectionProvider {+public:+ MCPConnectionProvider(IConnectionRepository* repository, SecretStore* secretStore);++ std::pair<std::shared_ptr<IDatabaseAdapter>, ConnectionConfig>+ openConnection(const std::string& connectionId) override;++ bool hasConnection(const std::string& connectionId) override;+ std::vector<ConnectionConfig> listConnections() override;++private:+ IConnectionRepository* repo_;+ SecretStore* secretStore_;+ std::mutex mu_;+ std::unordered_map<std::string, std::shared_ptr<IDatabaseAdapter>> cache_;+};++} // namespace gridexdiff --git a/linux/src/Core/CMakeLists.txt b/linux/src/Core/CMakeLists.txtnew file mode 100644index 0000000..4d453f3--- /dev/null+++ b/linux/src/Core/CMakeLists.txt@@ -0,0 +1,7 @@+add_library(gridex-core INTERFACE)++target_include_directories(gridex-core INTERFACE+ ${CMAKE_CURRENT_SOURCE_DIR}/..+)++target_compile_features(gridex-core INTERFACE cxx_std_20)diff --git a/linux/src/Core/Enums/ColorTag.h b/linux/src/Core/Enums/ColorTag.hnew file mode 100644index 0000000..a7ec3b7--- /dev/null+++ b/linux/src/Core/Enums/ColorTag.h@@ -0,0 +1,76 @@+#pragma once++#include <array>+#include <cstdint>+#include <optional>+#include <string_view>++namespace gridex {++enum class ColorTag {+ Red,+ Orange,+ Green,+ Blue,+ Purple,+ Gray,+};++inline constexpr std::array<ColorTag, 6> kAllColorTags = {+ ColorTag::Red, ColorTag::Orange, ColorTag::Green,+ ColorTag::Blue, ColorTag::Purple, ColorTag::Gray,+};++struct RgbColor {+ std::uint8_t r = 0;+ std::uint8_t g = 0;+ std::uint8_t b = 0;+};++inline std::string_view rawValue(ColorTag c) {+ switch (c) {+ case ColorTag::Red: return "red";+ case ColorTag::Orange: return "orange";+ case ColorTag::Green: return "green";+ case ColorTag::Blue: return "blue";+ case ColorTag::Purple: return "purple";+ case ColorTag::Gray: return "gray";+ }+ return "";+}++inline std::optional<ColorTag> colorTagFromRaw(std::string_view raw) {+ if (raw == "red") return ColorTag::Red;+ if (raw == "orange") return ColorTag::Orange;+ if (raw == "green") return ColorTag::Green;+ if (raw == "blue") return ColorTag::Blue;+ if (raw == "purple") return ColorTag::Purple;+ if (raw == "gray") return ColorTag::Gray;+ return std::nullopt;+}++inline constexpr RgbColor rgbColor(ColorTag c) {+ switch (c) {+ case ColorTag::Red: return {226, 75, 74};+ case ColorTag::Orange: return {239, 159, 39};+ case ColorTag::Green: return { 99, 153, 34};+ case ColorTag::Blue: return { 55, 138, 221};+ case ColorTag::Purple: return { 83, 74, 183};+ case ColorTag::Gray: return {128, 128, 128};+ }+ return {};+}++inline std::string_view environmentHint(ColorTag c) {+ switch (c) {+ case ColorTag::Red: return "Production";+ case ColorTag::Orange: return "Staging";+ case ColorTag::Green: return "Development";+ case ColorTag::Blue: return "Local";+ case ColorTag::Purple: return "Custom";+ case ColorTag::Gray: return "Other";+ }+ return "";+}++}diff --git a/linux/src/Core/Enums/DatabaseType.h b/linux/src/Core/Enums/DatabaseType.hnew file mode 100644index 0000000..389069f--- /dev/null+++ b/linux/src/Core/Enums/DatabaseType.h@@ -0,0 +1,112 @@+#pragma once++#include <array>+#include <optional>+#include <string>+#include <string_view>++#include "Core/Enums/SQLDialect.h"++namespace gridex {++enum class DatabaseType {+ PostgreSQL,+ MySQL,+ SQLite,+ Redis,+ MongoDB,+ MSSQL,+};++inline constexpr std::array<DatabaseType, 6> kAllDatabaseTypes = {+ DatabaseType::PostgreSQL, DatabaseType::MySQL, DatabaseType::SQLite,+ DatabaseType::Redis, DatabaseType::MongoDB, DatabaseType::MSSQL,+};++inline std::string_view rawValue(DatabaseType t) {+ switch (t) {+ case DatabaseType::PostgreSQL: return "postgresql";+ case DatabaseType::MySQL: return "mysql";+ case DatabaseType::SQLite: return "sqlite";+ case DatabaseType::Redis: return "redis";+ case DatabaseType::MongoDB: return "mongodb";+ case DatabaseType::MSSQL: return "mssql";+ }+ return "";+}++inline std::optional<DatabaseType> databaseTypeFromRaw(std::string_view raw) {+ if (raw == "postgresql") return DatabaseType::PostgreSQL;+ if (raw == "mysql") return DatabaseType::MySQL;+ if (raw == "sqlite") return DatabaseType::SQLite;+ if (raw == "redis") return DatabaseType::Redis;+ if (raw == "mongodb") return DatabaseType::MongoDB;+ if (raw == "mssql") return DatabaseType::MSSQL;+ return std::nullopt;+}++inline std::string_view displayName(DatabaseType t) {+ switch (t) {+ case DatabaseType::PostgreSQL: return "PostgreSQL";+ case DatabaseType::MySQL: return "MySQL";+ case DatabaseType::SQLite: return "SQLite";+ case DatabaseType::Redis: return "Redis";+ case DatabaseType::MongoDB: return "MongoDB";+ case DatabaseType::MSSQL: return "SQL Server";+ }+ return "";+}++inline constexpr int defaultPort(DatabaseType t) {+ switch (t) {+ case DatabaseType::PostgreSQL: return 5432;+ case DatabaseType::MySQL: return 3306;+ case DatabaseType::SQLite: return 0;+ case DatabaseType::Redis: return 6379;+ case DatabaseType::MongoDB: return 27017;+ case DatabaseType::MSSQL: return 1433;+ }+ return 0;+}++inline SQLDialect sqlDialect(DatabaseType t) {+ switch (t) {+ case DatabaseType::PostgreSQL: return SQLDialect::PostgreSQL;+ case DatabaseType::MySQL: return SQLDialect::MySQL;+ case DatabaseType::SQLite: return SQLDialect::SQLite;+ case DatabaseType::Redis: return SQLDialect::Redis;+ case DatabaseType::MongoDB: return SQLDialect::MongoDB;+ case DatabaseType::MSSQL: return SQLDialect::MSSQL;+ }+ return SQLDialect::SQLite;+}++inline constexpr bool isSQL(DatabaseType t) {+ switch (t) {+ case DatabaseType::PostgreSQL:+ case DatabaseType::MySQL:+ case DatabaseType::SQLite:+ case DatabaseType::MSSQL:+ return true;+ case DatabaseType::Redis:+ case DatabaseType::MongoDB:+ return false;+ }+ return false;+}++inline constexpr bool supportsSchemas(DatabaseType t) {+ switch (t) {+ case DatabaseType::PostgreSQL:+ case DatabaseType::MSSQL:+ return true;+ case DatabaseType::MySQL:+ case DatabaseType::SQLite:+ case DatabaseType::Redis:+ case DatabaseType::MongoDB:+ return false;+ }+ return false;+}++}diff --git a/linux/src/Core/Enums/MCPConnectionMode.h b/linux/src/Core/Enums/MCPConnectionMode.hnew file mode 100644index 0000000..307f14d--- /dev/null+++ b/linux/src/Core/Enums/MCPConnectionMode.h@@ -0,0 +1,64 @@+#pragma once++#include <array>+#include <optional>+#include <string_view>++namespace gridex {++enum class MCPConnectionMode {+ Locked,+ ReadOnly,+ ReadWrite,+};++inline constexpr std::array<MCPConnectionMode, 3> kAllMCPConnectionModes = {+ MCPConnectionMode::Locked,+ MCPConnectionMode::ReadOnly,+ MCPConnectionMode::ReadWrite,+};++inline std::string_view rawValue(MCPConnectionMode m) {+ switch (m) {+ case MCPConnectionMode::Locked: return "locked";+ case MCPConnectionMode::ReadOnly: return "read_only";+ case MCPConnectionMode::ReadWrite: return "read_write";+ }+ return "";+}++inline std::optional<MCPConnectionMode> mcpConnectionModeFromRaw(std::string_view raw) {+ if (raw == "locked") return MCPConnectionMode::Locked;+ if (raw == "read_only") return MCPConnectionMode::ReadOnly;+ if (raw == "read_write") return MCPConnectionMode::ReadWrite;+ return std::nullopt;+}++inline std::string_view displayName(MCPConnectionMode m) {+ switch (m) {+ case MCPConnectionMode::Locked: return "Locked";+ case MCPConnectionMode::ReadOnly: return "Read-only";+ case MCPConnectionMode::ReadWrite: return "Read-write";+ }+ return "";+}++inline std::string_view description(MCPConnectionMode m) {+ switch (m) {+ case MCPConnectionMode::Locked:+ return "AI cannot access this connection";+ case MCPConnectionMode::ReadOnly:+ return "AI can query but not modify (recommended for production)";+ case MCPConnectionMode::ReadWrite:+ return "AI can modify with your approval (use for dev only)";+ }+ return "";+}++inline bool allowsTier1(MCPConnectionMode m) { return m != MCPConnectionMode::Locked; }+inline bool allowsTier2(MCPConnectionMode m) { return m != MCPConnectionMode::Locked; }+inline bool allowsTier3(MCPConnectionMode m) { return m == MCPConnectionMode::ReadWrite; }+inline bool allowsTier4(MCPConnectionMode m) { return m == MCPConnectionMode::ReadWrite; }+inline bool allowsTier5(MCPConnectionMode m) { return m != MCPConnectionMode::Locked; }++}diff --git a/linux/src/Core/Enums/MCPPermissionTier.h b/linux/src/Core/Enums/MCPPermissionTier.hnew file mode 100644index 0000000..fce9c3b--- /dev/null+++ b/linux/src/Core/Enums/MCPPermissionTier.h@@ -0,0 +1,45 @@+#pragma once++#include <string_view>++namespace gridex {++enum class MCPPermissionTier {+ Schema = 1,+ Read = 2,+ Write = 3,+ Ddl = 4,+ Advanced = 5,+};++inline int tierRawValue(MCPPermissionTier t) { return static_cast<int>(t); }++inline std::string_view displayName(MCPPermissionTier t) {+ switch (t) {+ case MCPPermissionTier::Schema: return "Schema";+ case MCPPermissionTier::Read: return "Read";+ case MCPPermissionTier::Write: return "Write";+ case MCPPermissionTier::Ddl: return "DDL";+ case MCPPermissionTier::Advanced: return "Advanced";+ }+ return "";+}++inline bool requiresApproval(MCPPermissionTier t) {+ switch (t) {+ case MCPPermissionTier::Schema:+ case MCPPermissionTier::Read:+ return false;+ case MCPPermissionTier::Write:+ case MCPPermissionTier::Ddl:+ case MCPPermissionTier::Advanced:+ return true;+ }+ return true;+}++inline bool isReadOnly(MCPPermissionTier t) {+ return t == MCPPermissionTier::Schema || t == MCPPermissionTier::Read;+}++}diff --git a/linux/src/Core/Enums/SQLDialect.h b/linux/src/Core/Enums/SQLDialect.hnew file mode 100644index 0000000..f4bdc18--- /dev/null+++ b/linux/src/Core/Enums/SQLDialect.h@@ -0,0 +1,72 @@+#pragma once++#include <string>+#include <string_view>++namespace gridex {++enum class SQLDialect {+ PostgreSQL,+ MySQL,+ SQLite,+ Redis,+ MongoDB,+ MSSQL,+};++inline std::string quoteIdentifier(SQLDialect dialect, std::string_view identifier) {+ std::string out;+ out.reserve(identifier.size() + 2);++ auto escapeWith = [&](char quote) {+ out.push_back(quote);+ for (char c : identifier) {+ if (c == quote) out.push_back(quote);+ out.push_back(c);+ }+ out.push_back(quote);+ };++ switch (dialect) {+ case SQLDialect::PostgreSQL:+ case SQLDialect::SQLite:+ escapeWith('"');+ return out;+ case SQLDialect::MySQL:+ escapeWith('`');+ return out;+ case SQLDialect::MSSQL: {+ out.push_back('[');+ for (char c : identifier) {+ if (c == ']') out.push_back(']');+ out.push_back(c);+ }+ out.push_back(']');+ return out;+ }+ case SQLDialect::Redis:+ case SQLDialect::MongoDB:+ return std::string(identifier);+ }+ return std::string(identifier);+}++inline std::string parameterPlaceholder(SQLDialect dialect, int index) {+ switch (dialect) {+ case SQLDialect::PostgreSQL:+ return "$" + std::to_string(index);+ case SQLDialect::MSSQL:+ return "@p" + std::to_string(index);+ case SQLDialect::MySQL:+ case SQLDialect::SQLite:+ case SQLDialect::Redis:+ case SQLDialect::MongoDB:+ return "?";+ }+ return "?";+}++inline constexpr std::string_view limitClause(SQLDialect) { return "LIMIT"; }+inline constexpr std::string_view offsetClause(SQLDialect) { return "OFFSET"; }++}diff --git a/linux/src/Core/Enums/SSHAuthMethod.h b/linux/src/Core/Enums/SSHAuthMethod.hnew file mode 100644index 0000000..8dee280--- /dev/null+++ b/linux/src/Core/Enums/SSHAuthMethod.h@@ -0,0 +1,30 @@+#pragma once++#include <optional>+#include <string_view>++namespace gridex {++enum class SSHAuthMethod {+ Password,+ PrivateKey,+ KeyWithPassphrase,+};++inline std::string_view rawValue(SSHAuthMethod m) {+ switch (m) {+ case SSHAuthMethod::Password: return "password";+ case SSHAuthMethod::PrivateKey: return "privateKey";+ case SSHAuthMethod::KeyWithPassphrase: return "keyWithPassphrase";+ }+ return "";+}++inline std::optional<SSHAuthMethod> sshAuthMethodFromRaw(std::string_view raw) {+ if (raw == "password") return SSHAuthMethod::Password;+ if (raw == "privateKey") return SSHAuthMethod::PrivateKey;+ if (raw == "keyWithPassphrase") return SSHAuthMethod::KeyWithPassphrase;+ return std::nullopt;+}++}diff --git a/linux/src/Core/Enums/SSLMode.h b/linux/src/Core/Enums/SSLMode.hnew file mode 100644index 0000000..f3d1827--- /dev/null+++ b/linux/src/Core/Enums/SSLMode.h@@ -0,0 +1,53 @@+#pragma once++#include <array>+#include <optional>+#include <string_view>++namespace gridex {++enum class SSLMode {+ Preferred,+ Disabled,+ Required,+ VerifyCA,+ VerifyIdentity,+};++inline constexpr std::array<SSLMode, 5> kAllSSLModes = {+ SSLMode::Preferred, SSLMode::Disabled, SSLMode::Required,+ SSLMode::VerifyCA, SSLMode::VerifyIdentity,+};++inline std::string_view rawValue(SSLMode m) {+ switch (m) {+ case SSLMode::Preferred: return "PREFERRED";+ case SSLMode::Disabled: return "DISABLED";+ case SSLMode::Required: return "REQUIRED";+ case SSLMode::VerifyCA: return "VERIFY_CA";+ case SSLMode::VerifyIdentity: return "VERIFY_IDENTITY";+ }+ return "";+}++inline std::optional<SSLMode> sslModeFromRaw(std::string_view raw) {+ if (raw == "PREFERRED") return SSLMode::Preferred;+ if (raw == "DISABLED") return SSLMode::Disabled;+ if (raw == "REQUIRED") return SSLMode::Required;+ if (raw == "VERIFY_CA") return SSLMode::VerifyCA;+ if (raw == "VERIFY_IDENTITY") return SSLMode::VerifyIdentity;+ return std::nullopt;+}++inline std::string_view displayName(SSLMode m) {+ switch (m) {+ case SSLMode::Preferred: return "PREFERRED";+ case SSLMode::Disabled: return "DISABLED";+ case SSLMode::Required: return "REQUIRED";+ case SSLMode::VerifyCA: return "VERIFY CA";+ case SSLMode::VerifyIdentity: return "VERIFY IDENTITY";+ }+ return "";+}++}diff --git a/linux/src/Core/Errors/GridexError.h b/linux/src/Core/Errors/GridexError.hnew file mode 100644index 0000000..47d805f--- /dev/null+++ b/linux/src/Core/Errors/GridexError.h@@ -0,0 +1,87 @@+#pragma once++#include <stdexcept>+#include <string>+#include <utility>++namespace gridex {++enum class ErrorCategory {+ Unknown,+ Connection,+ Query,+ Schema,+ Authentication,+ Permission,+ Configuration,+ Serialization,+ Network,+ Internal,+};++class GridexError : public std::runtime_error {+public:+ GridexError(ErrorCategory category, std::string message)+ : std::runtime_error(std::move(message)), category_(category) {}++ [[nodiscard]] ErrorCategory category() const noexcept { return category_; }++private:+ ErrorCategory category_;+};++class ConnectionError : public GridexError {+public:+ explicit ConnectionError(std::string message)+ : GridexError(ErrorCategory::Connection, std::move(message)) {}+};++class QueryError : public GridexError {+public:+ explicit QueryError(std::string message)+ : GridexError(ErrorCategory::Query, std::move(message)) {}+};++class SchemaError : public GridexError {+public:+ explicit SchemaError(std::string message)+ : GridexError(ErrorCategory::Schema, std::move(message)) {}+};++class AuthenticationError : public GridexError {+public:+ explicit AuthenticationError(std::string message)+ : GridexError(ErrorCategory::Authentication, std::move(message)) {}+};++class PermissionError : public GridexError {+public:+ explicit PermissionError(std::string message)+ : GridexError(ErrorCategory::Permission, std::move(message)) {}+};++class ConfigurationError : public GridexError {+public:+ explicit ConfigurationError(std::string message)+ : GridexError(ErrorCategory::Configuration, std::move(message)) {}+};++class SerializationError : public GridexError {+public:+ explicit SerializationError(std::string message)+ : GridexError(ErrorCategory::Serialization, std::move(message)) {}+};++class NetworkError : public GridexError {+public:+ explicit NetworkError(std::string message)+ : GridexError(ErrorCategory::Network, std::move(message)) {}+};++class InternalError : public GridexError {+public:+ explicit InternalError(std::string message)+ : GridexError(ErrorCategory::Internal, std::move(message)) {}+};++}diff --git a/linux/src/Core/Models/AI/AIModels.h b/linux/src/Core/Models/AI/AIModels.hnew file mode 100644index 0000000..55235f2--- /dev/null+++ b/linux/src/Core/Models/AI/AIModels.h@@ -0,0 +1,67 @@+#pragma once++#include <chrono>+#include <string>+#include <vector>++namespace gridex {++// ---- LLMMessage -------------------------------------------------------++struct LLMMessage {+ enum class Role { User, Assistant, System };++ Role role;+ std::string content;++ static std::string roleString(Role r) {+ switch (r) {+ case Role::User: return "user";+ case Role::Assistant: return "assistant";+ case Role::System: return "system";+ }+ return "user";+ }+};++// ---- LLMModel ---------------------------------------------------------++struct LLMModel {+ std::string id;+ std::string name;+ std::string provider;+ int contextWindow = 128000;+ bool supportsStreaming = true;+};++// ---- ChatMessage ------------------------------------------------------+// Represents a single turn in the UI chat history.++struct ChatMessage {+ std::string id; // UUID string+ LLMMessage::Role role;+ std::string content;+ std::chrono::system_clock::time_point timestamp;++ // Factory helpers+ static ChatMessage user(const std::string& text);+ static ChatMessage assistant(const std::string& text);+};++inline ChatMessage ChatMessage::user(const std::string& text) {+ ChatMessage m;+ m.role = LLMMessage::Role::User;+ m.content = text;+ m.timestamp = std::chrono::system_clock::now();+ return m;+}++inline ChatMessage ChatMessage::assistant(const std::string& text) {+ ChatMessage m;+ m.role = LLMMessage::Role::Assistant;+ m.content = text;+ m.timestamp = std::chrono::system_clock::now();+ return m;+}++} // namespace gridexdiff --git a/linux/src/Core/Models/Database/ConnectionConfig.h b/linux/src/Core/Models/Database/ConnectionConfig.hnew file mode 100644index 0000000..0c5ea24--- /dev/null+++ b/linux/src/Core/Models/Database/ConnectionConfig.h@@ -0,0 +1,53 @@+#pragma once++#include <optional>+#include <string>+#include <utility>++#include "Core/Enums/ColorTag.h"+#include "Core/Enums/DatabaseType.h"+#include "Core/Enums/SSHAuthMethod.h"++namespace gridex {++struct SSHTunnelConfig {+ std::string host;+ int port = 22;+ std::string username;+ SSHAuthMethod authMethod = SSHAuthMethod::Password;+ std::optional<std::string> keyPath;++ bool operator==(const SSHTunnelConfig&) const noexcept = default;+};++struct ConnectionConfig {+ std::string id; // UUID string+ std::string name;+ DatabaseType databaseType = DatabaseType::PostgreSQL;+ std::optional<std::string> host;+ std::optional<int> port;+ std::optional<std::string> database;+ std::optional<std::string> username;+ bool sslEnabled = false;+ std::optional<ColorTag> colorTag;+ std::optional<std::string> group;++ // SQLite-specific+ std::optional<std::string> filePath;++ // SSH tunnel+ std::optional<SSHTunnelConfig> sshConfig;++ bool operator==(const ConnectionConfig&) const noexcept = default;++ [[nodiscard]] std::string displayHost() const {+ if (databaseType == DatabaseType::SQLite) {+ return filePath.value_or("Unknown");+ }+ const auto h = host.value_or(std::string{"localhost"});+ const int p = port.value_or(defaultPort(databaseType));+ return h + ":" + std::to_string(p);+ }+};++}diff --git a/linux/src/Core/Models/Database/ConnectionConfigJson.h b/linux/src/Core/Models/Database/ConnectionConfigJson.hnew file mode 100644index 0000000..5ea2753--- /dev/null+++ b/linux/src/Core/Models/Database/ConnectionConfigJson.h@@ -0,0 +1,279 @@+#pragma once++// Minimal hand-rolled JSON serializer/deserializer for ConnectionConfig.+// Kept narrow on purpose — when nlohmann/json lands in Phase 2d+ we can swap+// this for a general-purpose library.++#include <cctype>+#include <cstdint>+#include <optional>+#include <stdexcept>+#include <string>+#include <string_view>++#include "Core/Enums/ColorTag.h"+#include "Core/Enums/DatabaseType.h"+#include "Core/Enums/SSHAuthMethod.h"+#include "Core/Errors/GridexError.h"+#include "Core/Models/Database/ConnectionConfig.h"++namespace gridex::json {++inline std::string escape(std::string_view s) {+ std::string out;+ out.reserve(s.size() + 2);+ out.push_back('"');+ for (char c : s) {+ switch (c) {+ case '"': out += "\\\""; break;+ case '\\': out += "\\\\"; break;+ case '\n': out += "\\n"; break;+ case '\r': out += "\\r"; break;+ case '\t': out += "\\t"; break;+ default:+ if (static_cast<unsigned char>(c) < 0x20) {+ char buf[8];+ std::snprintf(buf, sizeof(buf), "\\u%04x", static_cast<unsigned>(c));+ out += buf;+ } else {+ out.push_back(c);+ }+ }+ }+ out.push_back('"');+ return out;+}++inline std::string encodeSSHConfig(const SSHTunnelConfig& s) {+ std::string out = "{";+ out += "\"host\":" + escape(s.host) + ",";+ out += "\"port\":" + std::to_string(s.port) + ",";+ out += "\"username\":" + escape(s.username) + ",";+ out += "\"authMethod\":" + escape(rawValue(s.authMethod));+ if (s.keyPath) out += ",\"keyPath\":" + escape(*s.keyPath);+ out += "}";+ return out;+}++inline std::string encode(const ConnectionConfig& c) {+ std::string out = "{";+ out += "\"id\":" + escape(c.id) + ",";+ out += "\"name\":" + escape(c.name) + ",";+ out += "\"databaseType\":" + escape(rawValue(c.databaseType)) + ",";+ out += "\"sslEnabled\":";+ out += c.sslEnabled ? "true" : "false";+ if (c.host) out += ",\"host\":" + escape(*c.host);+ if (c.port) out += ",\"port\":" + std::to_string(*c.port);+ if (c.database) out += ",\"database\":" + escape(*c.database);+ if (c.username) out += ",\"username\":" + escape(*c.username);+ if (c.colorTag) out += ",\"colorTag\":" + escape(rawValue(*c.colorTag));+ if (c.group) out += ",\"group\":" + escape(*c.group);+ if (c.filePath) out += ",\"filePath\":" + escape(*c.filePath);+ if (c.sshConfig) out += ",\"sshConfig\":" + encodeSSHConfig(*c.sshConfig);+ out += "}";+ return out;+}++// ---- Minimal parser ----++class Parser {+public:+ explicit Parser(std::string_view s) : s_(s), i_(0) {}++ void skipWs() {+ while (i_ < s_.size() && std::isspace(static_cast<unsigned char>(s_[i_]))) ++i_;+ }++ void expect(char c) {+ skipWs();+ if (i_ >= s_.size() || s_[i_] != c) {+ throw SerializationError("JSON: expected '" + std::string(1, c) + "' at pos " + std::to_string(i_));+ }+ ++i_;+ }++ bool peek(char c) {+ skipWs();+ return i_ < s_.size() && s_[i_] == c;+ }++ std::string readString() {+ expect('"');+ std::string out;+ while (i_ < s_.size() && s_[i_] != '"') {+ char c = s_[i_++];+ if (c == '\\' && i_ < s_.size()) {+ char e = s_[i_++];+ switch (e) {+ case '"': out.push_back('"'); break;+ case '\\': out.push_back('\\'); break;+ case '/': out.push_back('/'); break;+ case 'n': out.push_back('\n'); break;+ case 'r': out.push_back('\r'); break;+ case 't': out.push_back('\t'); break;+ case 'b': out.push_back('\b'); break;+ case 'f': out.push_back('\f'); break;+ case 'u': {+ if (i_ + 4 > s_.size()) throw SerializationError("JSON: bad \\u");+ const auto hex = std::string(s_.substr(i_, 4));+ i_ += 4;+ const auto code = static_cast<int>(std::stoul(hex, nullptr, 16));+ if (code < 0x80) out.push_back(static_cast<char>(code));+ else if (code < 0x800) {+ out.push_back(static_cast<char>(0xC0 | (code >> 6)));+ out.push_back(static_cast<char>(0x80 | (code & 0x3F)));+ } else {+ out.push_back(static_cast<char>(0xE0 | (code >> 12)));+ out.push_back(static_cast<char>(0x80 | ((code >> 6) & 0x3F)));+ out.push_back(static_cast<char>(0x80 | (code & 0x3F)));+ }+ break;+ }+ default: throw SerializationError("JSON: bad escape");+ }+ } else {+ out.push_back(c);+ }+ }+ expect('"');+ return out;+ }++ bool readBool() {+ skipWs();+ if (s_.compare(i_, 4, "true") == 0) { i_ += 4; return true; }+ if (s_.compare(i_, 5, "false") == 0) { i_ += 5; return false; }+ throw SerializationError("JSON: expected bool at pos " + std::to_string(i_));+ }++ int readInt() {+ skipWs();+ std::size_t start = i_;+ if (i_ < s_.size() && (s_[i_] == '-' || s_[i_] == '+')) ++i_;+ while (i_ < s_.size() && std::isdigit(static_cast<unsigned char>(s_[i_]))) ++i_;+ if (start == i_) throw SerializationError("JSON: expected number at pos " + std::to_string(start));+ try {+ return std::stoi(std::string(s_.substr(start, i_ - start)));+ } catch (const std::exception&) {+ throw SerializationError("JSON: integer overflow at pos " + std::to_string(start));+ }+ }++ void skipValue() {+ skipWs();+ if (i_ >= s_.size()) return;+ char c = s_[i_];+ if (c == '"') { (void)readString(); return; }+ if (c == '{') { skipObject(); return; }+ if (c == '[') { skipArray(); return; }+ if (c == 't' || c == 'f') { (void)readBool(); return; }+ if (c == 'n') { if (s_.compare(i_, 4, "null") == 0) { i_ += 4; return; } }+ // number+ if (c == '-' || std::isdigit(static_cast<unsigned char>(c))) {+ while (i_ < s_.size() && (std::isdigit(static_cast<unsigned char>(s_[i_])) ||+ s_[i_] == '.' || s_[i_] == 'e' || s_[i_] == 'E' ||+ s_[i_] == '+' || s_[i_] == '-')) ++i_;+ return;+ }+ throw SerializationError("JSON: unknown value at pos " + std::to_string(i_));+ }++ void skipObject() {+ expect('{');+ skipWs();+ if (peek('}')) { ++i_; return; }+ while (true) {+ (void)readString();+ expect(':');+ skipValue();+ skipWs();+ if (peek(',')) { ++i_; continue; }+ break;+ }+ expect('}');+ }++ void skipArray() {+ expect('[');+ skipWs();+ if (peek(']')) { ++i_; return; }+ while (true) {+ skipValue();+ skipWs();+ if (peek(',')) { ++i_; continue; }+ break;+ }+ expect(']');+ }++ bool done() { skipWs(); return i_ >= s_.size(); }++private:+ std::string_view s_;+ std::size_t i_;+};++inline SSHTunnelConfig decodeSSHConfig(Parser& p) {+ SSHTunnelConfig s;+ p.expect('{');+ while (true) {+ p.skipWs();+ if (p.peek('}')) break;+ const auto key = p.readString();+ p.expect(':');+ if (key == "host") s.host = p.readString();+ else if (key == "port") s.port = p.readInt();+ else if (key == "username") s.username = p.readString();+ else if (key == "authMethod") {+ const auto raw = p.readString();+ s.authMethod = sshAuthMethodFromRaw(raw).value_or(SSHAuthMethod::Password);+ }+ else if (key == "keyPath") s.keyPath = p.readString();+ else p.skipValue();+ p.skipWs();+ if (p.peek(',')) { p.expect(','); continue; }+ break;+ }+ p.expect('}');+ return s;+}++inline ConnectionConfig decode(std::string_view s) {+ Parser p(s);+ ConnectionConfig c;+ p.expect('{');+ while (true) {+ p.skipWs();+ if (p.peek('}')) break;+ const auto key = p.readString();+ p.expect(':');+ if (key == "id") c.id = p.readString();+ else if (key == "name") c.name = p.readString();+ else if (key == "databaseType") {+ const auto raw = p.readString();+ const auto dt = databaseTypeFromRaw(raw);+ if (!dt) throw SerializationError("Unknown databaseType: " + raw);+ c.databaseType = *dt;+ }+ else if (key == "sslEnabled") c.sslEnabled = p.readBool();+ else if (key == "host") c.host = p.readString();+ else if (key == "port") c.port = p.readInt();+ else if (key == "database") c.database = p.readString();+ else if (key == "username") c.username = p.readString();+ else if (key == "colorTag") {+ const auto raw = p.readString();+ c.colorTag = colorTagFromRaw(raw);+ }+ else if (key == "group") c.group = p.readString();+ else if (key == "filePath") c.filePath = p.readString();+ else if (key == "sshConfig") c.sshConfig = decodeSSHConfig(p);+ else p.skipValue();+ p.skipWs();+ if (p.peek(',')) { p.expect(','); continue; }+ break;+ }+ p.expect('}');+ return c;+}++}diff --git a/linux/src/Core/Models/Database/RowValue.h b/linux/src/Core/Models/Database/RowValue.hnew file mode 100644index 0000000..ca242c3--- /dev/null+++ b/linux/src/Core/Models/Database/RowValue.h@@ -0,0 +1,258 @@+#pragma once++#include <chrono>+#include <cstdint>+#include <memory>+#include <optional>+#include <string>+#include <utility>+#include <variant>+#include <vector>++namespace gridex {++class RowValue;++struct JsonString {+ std::string value;+ bool operator==(const JsonString& other) const noexcept = default;+};++struct UuidString {+ std::string value;+ bool operator==(const UuidString& other) const noexcept = default;+};++using Bytes = std::vector<std::uint8_t>;+using Timestamp = std::chrono::system_clock::time_point;++namespace detail {+struct ArrayBox {+ std::vector<RowValue> items;+};+}++class RowValue {+public:+ using Storage = std::variant<+ std::monostate, // null+ std::string, // string+ std::int64_t, // integer+ double, // double+ bool, // boolean+ Timestamp, // date+ Bytes, // data+ JsonString, // json+ UuidString, // uuid+ std::shared_ptr<detail::ArrayBox> // array (boxed for recursion)+ >;++ RowValue() = default;++ // Factories (keep construction intent explicit)+ static RowValue makeNull() { return RowValue{}; }+ static RowValue makeString(std::string v) { return RowValue{Storage{std::move(v)}}; }+ static RowValue makeInteger(std::int64_t v) { return RowValue{Storage{v}}; }+ static RowValue makeDouble(double v) { return RowValue{Storage{v}}; }+ static RowValue makeBoolean(bool v) { return RowValue{Storage{v}}; }+ static RowValue makeDate(Timestamp v) { return RowValue{Storage{v}}; }+ static RowValue makeData(Bytes v) { return RowValue{Storage{std::move(v)}}; }+ static RowValue makeJson(std::string v) { return RowValue{Storage{JsonString{std::move(v)}}}; }+ static RowValue makeUuid(std::string v) { return RowValue{Storage{UuidString{std::move(v)}}}; }+ static RowValue makeArray(std::vector<RowValue> items) {+ auto box = std::make_shared<detail::ArrayBox>();+ box->items = std::move(items);+ return RowValue{Storage{std::move(box)}};+ }++ const Storage& storage() const noexcept { return storage_; }++ [[nodiscard]] bool isNull() const noexcept { return std::holds_alternative<std::monostate>(storage_); }+ [[nodiscard]] bool isString() const noexcept { return std::holds_alternative<std::string>(storage_); }+ [[nodiscard]] bool isInteger() const noexcept { return std::holds_alternative<std::int64_t>(storage_); }+ [[nodiscard]] bool isDouble() const noexcept { return std::holds_alternative<double>(storage_); }+ [[nodiscard]] bool isBoolean() const noexcept { return std::holds_alternative<bool>(storage_); }+ [[nodiscard]] bool isDate() const noexcept { return std::holds_alternative<Timestamp>(storage_); }+ [[nodiscard]] bool isData() const noexcept { return std::holds_alternative<Bytes>(storage_); }+ [[nodiscard]] bool isJson() const noexcept { return std::holds_alternative<JsonString>(storage_); }+ [[nodiscard]] bool isUuid() const noexcept { return std::holds_alternative<UuidString>(storage_); }+ [[nodiscard]] bool isArray() const noexcept { return std::holds_alternative<std::shared_ptr<detail::ArrayBox>>(storage_); }++ [[nodiscard]] bool isNumeric() const noexcept { return isInteger() || isDouble(); }++ // Typed accessors. Caller must check via is*() first or use try* below.+ [[nodiscard]] const std::string& asString() const { return std::get<std::string>(storage_); }+ [[nodiscard]] std::int64_t asInteger() const { return std::get<std::int64_t>(storage_); }+ [[nodiscard]] double asDouble() const { return std::get<double>(storage_); }+ [[nodiscard]] bool asBoolean() const { return std::get<bool>(storage_); }+ [[nodiscard]] Timestamp asDate() const { return std::get<Timestamp>(storage_); }+ [[nodiscard]] const Bytes& asData() const { return std::get<Bytes>(storage_); }+ [[nodiscard]] const std::string& asJson() const { return std::get<JsonString>(storage_).value; }+ [[nodiscard]] const std::string& asUuid() const { return std::get<UuidString>(storage_).value; }+ [[nodiscard]] const std::vector<RowValue>& asArray() const {+ return std::get<std::shared_ptr<detail::ArrayBox>>(storage_)->items;+ }++ [[nodiscard]] std::optional<std::string> tryStringValue() const;+ [[nodiscard]] std::optional<std::int64_t> tryIntValue() const;+ [[nodiscard]] std::optional<double> tryDoubleValue() const;++ [[nodiscard]] std::string description() const;+ [[nodiscard]] std::string displayString() const;++ bool operator==(const RowValue& other) const noexcept;+ bool operator!=(const RowValue& other) const noexcept { return !(*this == other); }++private:+ explicit RowValue(Storage s) : storage_(std::move(s)) {}++ Storage storage_;+};++inline std::string formatTimestampUtc(Timestamp ts) {+ using namespace std::chrono;+ const auto tt = system_clock::to_time_t(ts);+ std::tm tm{};+#if defined(_WIN32)+ gmtime_s(&tm, &tt);+#else+ gmtime_r(&tt, &tm);+#endif+ char buf[64];+ std::snprintf(buf, sizeof(buf), "%04d-%02d-%02d %02d:%02d:%02d",+ tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,+ tm.tm_hour, tm.tm_min, tm.tm_sec);+ return buf;+}++// Standard RFC 4648 base64 encoder — small, dep-free, matches Swift's Data.base64EncodedString().+inline std::string encodeBase64(const Bytes& bytes) {+ static constexpr char kTable[] =+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";+ std::string out;+ const auto n = bytes.size();+ out.reserve(((n + 2) / 3) * 4);+ std::size_t i = 0;+ while (i + 3 <= n) {+ const auto b0 = bytes[i++];+ const auto b1 = bytes[i++];+ const auto b2 = bytes[i++];+ out.push_back(kTable[(b0 >> 2) & 0x3F]);+ out.push_back(kTable[((b0 << 4) | (b1 >> 4)) & 0x3F]);+ out.push_back(kTable[((b1 << 2) | (b2 >> 6)) & 0x3F]);+ out.push_back(kTable[b2 & 0x3F]);+ }+ if (i < n) {+ const auto b0 = bytes[i++];+ const auto b1 = (i < n) ? bytes[i++] : static_cast<std::uint8_t>(0);+ out.push_back(kTable[(b0 >> 2) & 0x3F]);+ out.push_back(kTable[((b0 << 4) | (b1 >> 4)) & 0x3F]);+ if (i == n && bytes.size() % 3 == 2) {+ out.push_back(kTable[(b1 << 2) & 0x3F]);+ out.push_back('=');+ } else {+ out.push_back('=');+ out.push_back('=');+ }+ }+ return out;+}++inline std::optional<std::string> RowValue::tryStringValue() const {+ if (isNull()) return std::nullopt;+ if (isString()) return asString();+ if (isInteger()) return std::to_string(asInteger());+ if (isDouble()) return std::to_string(asDouble());+ if (isBoolean()) return asBoolean() ? std::string{"true"} : std::string{"false"};+ if (isDate()) return formatTimestampUtc(asDate());+ if (isJson()) return asJson();+ if (isUuid()) return asUuid();+ if (isData()) return encodeBase64(asData()); // Parity with Swift RowValue.stringValue+ if (isArray()) {+ std::string out;+ bool first = true;+ for (const auto& v : asArray()) {+ if (!first) out += ", ";+ out += v.description();+ first = false;+ }+ return out;+ }+ return std::nullopt;+}++inline std::optional<std::int64_t> RowValue::tryIntValue() const {+ if (isInteger()) return asInteger();+ if (isDouble()) return static_cast<std::int64_t>(asDouble());+ if (isBoolean()) return asBoolean() ? 1 : 0;+ if (isString()) {+ try { return static_cast<std::int64_t>(std::stoll(asString())); }+ catch (...) { return std::nullopt; }+ }+ return std::nullopt;+}++inline std::optional<double> RowValue::tryDoubleValue() const {+ if (isDouble()) return asDouble();+ if (isInteger()) return static_cast<double>(asInteger());+ if (isString()) {+ try { return std::stod(asString()); }+ catch (...) { return std::nullopt; }+ }+ return std::nullopt;+}++inline std::string RowValue::description() const {+ if (auto s = tryStringValue()) return *s;+ return "NULL";+}++inline std::string RowValue::displayString() const {+ if (isNull()) return "NULL";+ if (isData()) {+ const auto& d = asData();+ if (d.size() > 100) return "(BLOB " + std::to_string(d.size()) + " bytes)";+ return encodeBase64(d); // Parity with Swift displayString+ }+ if (isJson()) {+ const auto& v = asJson();+ if (v.size() > 300) return v.substr(0, 300) + "\xE2\x80\xA6";+ return v;+ }+ if (isString()) {+ const auto& v = asString();+ if (v.size() > 500) return v.substr(0, 500) + "\xE2\x80\xA6";+ return v;+ }+ if (isArray()) {+ const auto& a = asArray();+ std::string out;+ const std::size_t limit = 20;+ std::size_t i = 0;+ for (; i < a.size() && i < limit; ++i) {+ if (i > 0) out += ", ";+ out += a[i].description();+ }+ if (a.size() > limit) {+ out += "\xE2\x80\xA6 (" + std::to_string(a.size()) + " items)";+ }+ return out;+ }+ return description();+}++inline bool RowValue::operator==(const RowValue& other) const noexcept {+ if (storage_.index() != other.storage_.index()) return false;+ if (isArray()) {+ const auto& lhs = asArray();+ const auto& rhs = other.asArray();+ if (lhs.size() != rhs.size()) return false;+ for (std::size_t i = 0; i < lhs.size(); ++i) {+ if (!(lhs[i] == rhs[i])) return false;+ }+ return true;+ }+ return storage_ == other.storage_;+}++}diff --git a/linux/src/Core/Models/Query/FilterExpression.h b/linux/src/Core/Models/Query/FilterExpression.hnew file mode 100644index 0000000..e4095ef--- /dev/null+++ b/linux/src/Core/Models/Query/FilterExpression.h@@ -0,0 +1,156 @@+#pragma once++#include <array>+#include <optional>+#include <string>+#include <string_view>+#include <vector>++#include "Core/Enums/SQLDialect.h"+#include "Core/Models/Database/RowValue.h"++namespace gridex {++enum class FilterOperator {+ Equal,+ NotEqual,+ GreaterThan,+ LessThan,+ GreaterOrEqual,+ LessOrEqual,+ Like,+ NotLike,+ IsNull,+ IsNotNull,+ In,+};++inline constexpr std::array<FilterOperator, 11> kAllFilterOperators = {+ FilterOperator::Equal, FilterOperator::NotEqual,+ FilterOperator::GreaterThan, FilterOperator::LessThan,+ FilterOperator::GreaterOrEqual, FilterOperator::LessOrEqual,+ FilterOperator::Like, FilterOperator::NotLike,+ FilterOperator::IsNull, FilterOperator::IsNotNull,+ FilterOperator::In,+};++inline std::string_view rawValue(FilterOperator op) {+ switch (op) {+ case FilterOperator::Equal: return "=";+ case FilterOperator::NotEqual: return "!=";+ case FilterOperator::GreaterThan: return ">";+ case FilterOperator::LessThan: return "<";+ case FilterOperator::GreaterOrEqual: return ">=";+ case FilterOperator::LessOrEqual: return "<=";+ case FilterOperator::Like: return "LIKE";+ case FilterOperator::NotLike: return "NOT LIKE";+ case FilterOperator::IsNull: return "IS NULL";+ case FilterOperator::IsNotNull: return "IS NOT NULL";+ case FilterOperator::In: return "IN";+ }+ return "";+}++enum class FilterCombinator {+ And,+ Or,+};++inline std::string_view rawValue(FilterCombinator c) {+ switch (c) {+ case FilterCombinator::And: return "AND";+ case FilterCombinator::Or: return "OR";+ }+ return "";+}++namespace detail {++inline std::string escapeFilterValue(const RowValue& value, SQLDialect dialect) {+ if (value.isNull()) return "NULL";++ auto escapeSingle = [](std::string_view v) {+ std::string out;+ out.reserve(v.size() + 2);+ out.push_back('\'');+ for (char c : v) {+ if (c == '\'') out.push_back('\'');+ out.push_back(c);+ }+ out.push_back('\'');+ return out;+ };++ if (value.isString()) {+ const auto& s = value.asString();+ // Pass numeric-looking strings through unquoted for compatibility with macOS behavior.+ try {+ std::size_t pos = 0;+ (void)std::stoll(s, &pos);+ if (pos == s.size()) return s;+ } catch (...) {}+ try {+ std::size_t pos = 0;+ (void)std::stod(s, &pos);+ if (pos == s.size()) return s;+ } catch (...) {}+ return escapeSingle(s);+ }+ if (value.isInteger()) return std::to_string(value.asInteger());+ if (value.isDouble()) return std::to_string(value.asDouble());+ if (value.isBoolean()) return value.asBoolean() ? "TRUE" : "FALSE";+ if (value.isDate()) return "'" + formatTimestampUtc(value.asDate()) + "'";+ if (value.isUuid()) return "'" + value.asUuid() + "'";+ if (value.isJson()) {+ const auto quoted = escapeSingle(value.asJson());+ // H11: PG requires ::jsonb cast for json comparisons+ return dialect == SQLDialect::PostgreSQL ? quoted + "::jsonb" : quoted;+ }+ // data, array → NULL (matches Swift behavior)+ return "NULL";+}++}++struct FilterCondition {+ std::string column;+ FilterOperator op = FilterOperator::Equal;+ RowValue value;++ [[nodiscard]] std::string toSQL(SQLDialect dialect) const {+ const std::string qc = quoteIdentifier(dialect, column);+ const std::string val = detail::escapeFilterValue(value, dialect);+ switch (op) {+ case FilterOperator::Equal: return qc + " = " + val;+ case FilterOperator::NotEqual: return qc + " != " + val;+ case FilterOperator::GreaterThan: return qc + " > " + val;+ case FilterOperator::LessThan: return qc + " < " + val;+ case FilterOperator::GreaterOrEqual: return qc + " >= " + val;+ case FilterOperator::LessOrEqual: return qc + " <= " + val;+ case FilterOperator::Like: return qc + " LIKE " + val;+ case FilterOperator::NotLike: return qc + " NOT LIKE " + val;+ case FilterOperator::IsNull: return qc + " IS NULL";+ case FilterOperator::IsNotNull: return qc + " IS NOT NULL";+ case FilterOperator::In: return qc + " IN (" + val + ")";+ }+ return qc;+ }+};++struct FilterExpression {+ std::vector<FilterCondition> conditions;+ FilterCombinator combinator = FilterCombinator::And;++ [[nodiscard]] std::string toSQL(SQLDialect dialect) const {+ if (conditions.empty()) return {};+ const std::string sep = combinator == FilterCombinator::And ? " AND " : " OR ";+ std::string out;+ for (std::size_t i = 0; i < conditions.size(); ++i) {+ if (i > 0) out += sep;+ out += conditions[i].toSQL(dialect);+ }+ return out;+ }+};++}diff --git a/linux/src/Core/Models/Query/QueryParameter.h b/linux/src/Core/Models/Query/QueryParameter.hnew file mode 100644index 0000000..08db40a--- /dev/null+++ b/linux/src/Core/Models/Query/QueryParameter.h@@ -0,0 +1,20 @@+#pragma once++#include <optional>+#include <string>+#include <utility>++#include "Core/Models/Database/RowValue.h"++namespace gridex {++struct QueryParameter {+ RowValue value;+ std::optional<std::string> type;++ QueryParameter() = default;+ explicit QueryParameter(RowValue v, std::optional<std::string> t = std::nullopt)+ : value(std::move(v)), type(std::move(t)) {}+};++}diff --git a/linux/src/Core/Models/Query/QueryResult.h b/linux/src/Core/Models/Query/QueryResult.hnew file mode 100644index 0000000..0ecdd0c--- /dev/null+++ b/linux/src/Core/Models/Query/QueryResult.h@@ -0,0 +1,54 @@+#pragma once++#include <chrono>+#include <optional>+#include <string>+#include <string_view>+#include <vector>++#include "Core/Models/Database/RowValue.h"++namespace gridex {++enum class QueryType {+ Select,+ Insert,+ Update,+ Delete,+ DDL,+ Other,+};++inline std::string_view rawValue(QueryType t) {+ switch (t) {+ case QueryType::Select: return "select";+ case QueryType::Insert: return "insert";+ case QueryType::Update: return "update";+ case QueryType::Delete: return "delete";+ case QueryType::DDL: return "ddl";+ case QueryType::Other: return "other";+ }+ return "";+}++struct ColumnHeader {+ std::string name;+ std::string dataType{"unknown"};+ bool isNullable = true;+ std::optional<std::string> tableName;++ bool operator==(const ColumnHeader&) const noexcept = default;+};++struct QueryResult {+ std::vector<ColumnHeader> columns;+ std::vector<std::vector<RowValue>> rows;+ int rowsAffected = 0;+ std::chrono::duration<double> executionTime{};+ QueryType queryType = QueryType::Other;++ [[nodiscard]] std::size_t rowCount() const noexcept { return rows.size(); }+ [[nodiscard]] bool isEmpty() const noexcept { return rows.empty(); }+};++}diff --git a/linux/src/Core/Models/Query/SortDescriptor.h b/linux/src/Core/Models/Query/SortDescriptor.hnew file mode 100644index 0000000..df2c363--- /dev/null+++ b/linux/src/Core/Models/Query/SortDescriptor.h@@ -0,0 +1,41 @@+#pragma once++#include <string>+#include <string_view>++#include "Core/Enums/SQLDialect.h"++namespace gridex {++enum class SortDirection {+ Ascending,+ Descending,+};++inline std::string_view rawValue(SortDirection d) {+ switch (d) {+ case SortDirection::Ascending: return "ASC";+ case SortDirection::Descending: return "DESC";+ }+ return "";+}++inline void toggle(SortDirection& d) noexcept {+ d = d == SortDirection::Ascending ? SortDirection::Descending : SortDirection::Ascending;+}++struct QuerySortDescriptor {+ std::string column;+ SortDirection direction = SortDirection::Ascending;++ [[nodiscard]] std::string toSQL(SQLDialect dialect) const {+ std::string out = quoteIdentifier(dialect, column);+ out.push_back(' ');+ out.append(rawValue(direction));+ return out;+ }++ bool operator==(const QuerySortDescriptor&) const noexcept = default;+};++}diff --git a/linux/src/Core/Models/Schema/SchemaSnapshot.h b/linux/src/Core/Models/Schema/SchemaSnapshot.hnew file mode 100644index 0000000..fb33ea4--- /dev/null+++ b/linux/src/Core/Models/Schema/SchemaSnapshot.h@@ -0,0 +1,241 @@+#pragma once++#include <chrono>+#include <optional>+#include <string>+#include <string_view>+#include <vector>++#include "Core/Enums/DatabaseType.h"+#include "Core/Enums/SQLDialect.h"++namespace gridex {++enum class TableKind {+ Table,+ View,+ MaterializedView,+ ForeignTable,+};++inline std::string_view rawValue(TableKind k) {+ switch (k) {+ case TableKind::Table: return "table";+ case TableKind::View: return "view";+ case TableKind::MaterializedView: return "materializedView";+ case TableKind::ForeignTable: return "foreignTable";+ }+ return "";+}++enum class ForeignKeyAction {+ Cascade,+ SetNull,+ SetDefault,+ Restrict,+ NoAction,+};++inline std::string_view rawValue(ForeignKeyAction a) {+ switch (a) {+ case ForeignKeyAction::Cascade: return "CASCADE";+ case ForeignKeyAction::SetNull: return "SET NULL";+ case ForeignKeyAction::SetDefault: return "SET DEFAULT";+ case ForeignKeyAction::Restrict: return "RESTRICT";+ case ForeignKeyAction::NoAction: return "NO ACTION";+ }+ return "";+}++enum class ConstraintType {+ PrimaryKey,+ Unique,+ Check,+ Exclusion,+};++inline std::string_view rawValue(ConstraintType t) {+ switch (t) {+ case ConstraintType::PrimaryKey: return "PRIMARY KEY";+ case ConstraintType::Unique: return "UNIQUE";+ case ConstraintType::Check: return "CHECK";+ case ConstraintType::Exclusion: return "EXCLUSION";+ }+ return "";+}++struct ColumnInfo {+ std::string name;+ std::string dataType;+ bool isNullable = true;+ std::optional<std::string> defaultValue;+ bool isPrimaryKey = false;+ bool isAutoIncrement = false;+ std::optional<std::string> comment;+ int ordinalPosition = 0;+ std::optional<int> characterMaxLength;+ std::optional<std::string> checkConstraint;++ bool operator==(const ColumnInfo&) const noexcept = default;+};++struct IndexInfo {+ std::string name;+ std::vector<std::string> columns;+ bool isUnique = false;+ std::optional<std::string> type;+ std::optional<std::string> tableName;+ std::optional<std::string> condition;+ std::optional<std::string> include;+ std::optional<std::string> comment;++ bool operator==(const IndexInfo&) const noexcept = default;+};++struct ForeignKeyInfo {+ std::optional<std::string> name;+ std::vector<std::string> columns;+ std::string referencedTable;+ std::vector<std::string> referencedColumns;+ ForeignKeyAction onDelete = ForeignKeyAction::NoAction;+ ForeignKeyAction onUpdate = ForeignKeyAction::NoAction;++ [[nodiscard]] std::string column() const {+ std::string out;+ for (std::size_t i = 0; i < columns.size(); ++i) {+ if (i > 0) out += ", ";+ out += columns[i];+ }+ return out;+ }++ [[nodiscard]] std::string referencedColumn() const {+ std::string out;+ for (std::size_t i = 0; i < referencedColumns.size(); ++i) {+ if (i > 0) out += ", ";+ out += referencedColumns[i];+ }+ return out;+ }++ bool operator==(const ForeignKeyInfo&) const noexcept = default;+};++struct ConstraintInfo {+ std::string name;+ ConstraintType type = ConstraintType::Check;+ std::vector<std::string> columns;+ std::optional<std::string> definition;++ bool operator==(const ConstraintInfo&) const noexcept = default;+};++struct TableDescription {+ std::string name;+ std::optional<std::string> schema;+ std::vector<ColumnInfo> columns;+ std::vector<IndexInfo> indexes;+ std::vector<ForeignKeyInfo> foreignKeys;+ std::vector<ConstraintInfo> constraints;+ std::optional<std::string> comment;+ std::optional<int> estimatedRowCount;++ [[nodiscard]] std::vector<ColumnInfo> primaryKeyColumns() const {+ std::vector<ColumnInfo> out;+ for (const auto& c : columns) if (c.isPrimaryKey) out.push_back(c);+ return out;+ }++ [[nodiscard]] std::string toDDL(SQLDialect dialect) const {+ std::string ddl = "CREATE TABLE " + quoteIdentifier(dialect, name) + " (\n";+ for (std::size_t i = 0; i < columns.size(); ++i) {+ const auto& c = columns[i];+ ddl += " " + c.name + " " + c.dataType;+ if (!c.isNullable) ddl += " NOT NULL";+ if (c.defaultValue) ddl += " DEFAULT " + *c.defaultValue;+ if (i + 1 < columns.size()) ddl += ",";+ ddl += "\n";+ }+ ddl += ");";+ return ddl;+ }++ bool operator==(const TableDescription&) const noexcept = default;+};++struct TableInfo {+ std::string name;+ std::optional<std::string> schema;+ TableKind type = TableKind::Table;+ std::optional<int> estimatedRowCount;+};++struct ViewInfo {+ std::string name;+ std::optional<std::string> schema;+ std::optional<std::string> definition;+ bool isMaterialized = false;+};++struct FunctionInfo {+ std::string name;+ std::optional<std::string> schema;+ std::string returnType;+ std::optional<std::string> parameters;+ std::optional<std::string> language;+};++struct EnumInfo {+ std::string name;+ std::optional<std::string> schema;+ std::vector<std::string> values;+};++struct SchemaInfo {+ std::string name;+ std::vector<TableDescription> tables;+ std::vector<ViewInfo> views;+ std::vector<FunctionInfo> functions;+ std::vector<EnumInfo> enums;+};++struct SchemaSnapshot {+ std::string databaseName;+ DatabaseType databaseType = DatabaseType::PostgreSQL;+ std::vector<SchemaInfo> schemas;+ std::chrono::system_clock::time_point capturedAt;++ [[nodiscard]] std::vector<TableDescription> allTables() const {+ std::vector<TableDescription> out;+ for (const auto& s : schemas) {+ for (const auto& t : s.tables) out.push_back(t);+ }+ return out;+ }++ [[nodiscard]] std::size_t totalTableCount() const noexcept {+ std::size_t n = 0;+ for (const auto& s : schemas) n += s.tables.size();+ return n;+ }+};++struct ColumnStatistics {+ std::string columnName;+ std::optional<int> distinctCount;+ std::optional<double> nullRatio;+ std::optional<std::vector<std::string>> topValues;+ std::optional<std::string> minValue;+ std::optional<std::string> maxValue;+};++struct QueryStatisticsEntry {+ std::string query;+ int callCount = 0;+ std::chrono::duration<double> totalTime{};+ std::chrono::duration<double> meanTime{};+ std::chrono::duration<double> minTime{};+ std::chrono::duration<double> maxTime{};+};++}diff --git a/linux/src/Core/Protocols/AI/ILLMService.h b/linux/src/Core/Protocols/AI/ILLMService.hnew file mode 100644index 0000000..d509d91--- /dev/null+++ b/linux/src/Core/Protocols/AI/ILLMService.h@@ -0,0 +1,39 @@+#pragma once++#include <string>+#include <vector>++#include "Core/Models/AI/AIModels.h"++namespace gridex {++// Pure-virtual interface for LLM providers.+// Mirrors macos/Core/Protocols/AI/LLMService.swift.+// Phase 5 uses synchronous (blocking) HTTP calls; streaming via QThread+// is deferred to a later phase.+class ILLMService {+public:+ virtual ~ILLMService() = default;++ // Human-readable provider label ("Anthropic", "OpenAI", etc.)+ [[nodiscard]] virtual std::string providerName() const = 0;++ // Send a conversation and return the full assistant response.+ // Throws gridex::NetworkError on transport failure.+ // Throws gridex::GridexError on API error (bad key, rate limit, etc.).+ [[nodiscard]] virtual std::string sendMessage(+ const std::vector<LLMMessage>& messages,+ const std::string& systemPrompt,+ const std::string& model,+ int maxTokens = 4096,+ double temperature = 0.7) = 0;++ // Return hardcoded or fetched model list for this provider.+ [[nodiscard]] virtual std::vector<LLMModel> availableModels() = 0;++ // Light validation — returns true when key looks usable.+ // Implementations may make a cheap test request; Ollama checks reachability.+ [[nodiscard]] virtual bool validateAPIKey() = 0;+};++} // namespace gridexdiff --git a/linux/src/Core/Protocols/Database/IDatabaseAdapter.h b/linux/src/Core/Protocols/Database/IDatabaseAdapter.hnew file mode 100644index 0000000..573bb4f--- /dev/null+++ b/linux/src/Core/Protocols/Database/IDatabaseAdapter.h@@ -0,0 +1,211 @@+#pragma once++#include <optional>+#include <string>+#include <unordered_map>+#include <vector>++#include "Core/Enums/DatabaseType.h"+#include "Core/Models/Database/ConnectionConfig.h"+#include "Core/Models/Database/RowValue.h"+#include "Core/Models/Query/FilterExpression.h"+#include "Core/Models/Query/QueryParameter.h"+#include "Core/Models/Query/QueryResult.h"+#include "Core/Models/Query/SortDescriptor.h"+#include "Core/Models/Schema/SchemaSnapshot.h"++namespace gridex {++// Interface mirrors macos/Core/Protocols/Database/DatabaseAdapter.swift.+// Adapters are synchronous; higher layers (QueryEngine) wrap calls onto threads.+// Methods throw gridex::GridexError subclasses on failure.+class IDatabaseAdapter {+public:+ virtual ~IDatabaseAdapter() = default;++ // Identity+ [[nodiscard]] virtual DatabaseType databaseType() const noexcept = 0;+ [[nodiscard]] virtual bool isConnected() const noexcept = 0;++ // Connection lifecycle+ virtual void connect(const ConnectionConfig& config,+ const std::optional<std::string>& password) = 0;+ virtual void disconnect() = 0;+ virtual bool testConnection(const ConnectionConfig& config,+ const std::optional<std::string>& password) = 0;++ // Query execution+ virtual QueryResult execute(const std::string& query,+ const std::vector<QueryParameter>& parameters) = 0;+ virtual QueryResult executeRaw(const std::string& sql) = 0;++ // Parameterized execution with RowValue. Default inlines values into SQL when+ // not overridden; adapters should override using native driver bindings.+ virtual QueryResult executeWithRowValues(const std::string& sql,+ const std::vector<RowValue>& parameters);++ // Schema inspection+ virtual std::vector<std::string> listDatabases() = 0;+ virtual std::vector<std::string> listSchemas(const std::optional<std::string>& database) = 0;+ virtual std::vector<TableInfo> listTables(const std::optional<std::string>& schema) = 0;+ virtual std::vector<ViewInfo> listViews(const std::optional<std::string>& schema) = 0;+ virtual TableDescription describeTable(const std::string& name,+ const std::optional<std::string>& schema) = 0;+ virtual std::vector<IndexInfo> listIndexes(const std::string& table,+ const std::optional<std::string>& schema) = 0;+ virtual std::vector<ForeignKeyInfo> listForeignKeys(const std::string& table,+ const std::optional<std::string>& schema) = 0;+ virtual std::vector<std::string> listFunctions(const std::optional<std::string>& schema) = 0;+ virtual std::string getFunctionSource(const std::string& name,+ const std::optional<std::string>& schema) = 0;++ // Stored procedures — default no-op (only MSSQL overrides in practice).+ virtual std::vector<std::string> listProcedures(const std::optional<std::string>& /*schema*/) { return {}; }+ virtual std::string getProcedureSource(const std::string& /*name*/,+ const std::optional<std::string>& /*schema*/) { return {}; }+ virtual std::vector<std::string> listProcedureParameters(const std::string& /*name*/,+ const std::optional<std::string>& /*schema*/) { return {}; }++ // Data manipulation+ virtual QueryResult insertRow(const std::string& table,+ const std::optional<std::string>& schema,+ const std::unordered_map<std::string, RowValue>& values) = 0;+ virtual QueryResult updateRow(const std::string& table,+ const std::optional<std::string>& schema,+ const std::unordered_map<std::string, RowValue>& set,+ const std::unordered_map<std::string, RowValue>& where) = 0;+ virtual QueryResult deleteRow(const std::string& table,+ const std::optional<std::string>& schema,+ const std::unordered_map<std::string, RowValue>& where) = 0;++ // Transactions+ virtual void beginTransaction() = 0;+ virtual void commitTransaction() = 0;+ virtual void rollbackTransaction() = 0;++ // Pagination+ virtual QueryResult fetchRows(const std::string& table,+ const std::optional<std::string>& schema,+ const std::optional<std::vector<std::string>>& columns,+ const std::optional<FilterExpression>& where,+ const std::optional<std::vector<QuerySortDescriptor>>& orderBy,+ int limit,+ int offset) = 0;++ // Database management — default implementations use DDL via executeRaw.+ virtual void createDatabase(const std::string& name);+ virtual void dropDatabase(const std::string& name);++ // Server info+ virtual std::string serverVersion() = 0;+ virtual std::optional<std::string> currentDatabase() = 0;+};++// Inline default implementations mirroring Swift protocol extensions.++inline QueryResult IDatabaseAdapter::executeWithRowValues(const std::string& sql,+ const std::vector<RowValue>& parameters) {+ // WARNING: default impl inlines values into SQL using naive single-quote-doubling.+ // Safe for PostgreSQL + SQLite which don't interpret backslash by default.+ // MySQL adapters MUST override with mysql_real_escape_string-based inlining.+ auto inlineValue = [](const RowValue& v) -> std::string {+ if (v.isNull()) return "NULL";+ auto quote = [](std::string_view src) {+ std::string out;+ out.reserve(src.size() + 2);+ out.push_back('\'');+ for (char c : src) {+ if (c == '\'') out.push_back('\'');+ out.push_back(c);+ }+ out.push_back('\'');+ return out;+ };+ if (v.isString()) return quote(v.asString());+ if (v.isInteger()) return std::to_string(v.asInteger());+ if (v.isDouble()) return std::to_string(v.asDouble());+ if (v.isBoolean()) return v.asBoolean() ? "1" : "0";+ if (v.isDate()) return "'" + formatTimestampUtc(v.asDate()) + "'";+ if (v.isUuid()) return "'" + v.asUuid() + "'";+ if (v.isJson()) return quote(v.asJson());+ return "NULL"; // data, array+ };++ // Single-pass tokenizer: walks SQL, skips over string/identifier literals and comments,+ // and substitutes $N or ? placeholders with inlined values.+ std::string out;+ out.reserve(sql.size() + 64);+ std::size_t i = 0;+ std::size_t qIndex = 0; // counts `?` placeholders already consumed+ const std::size_t n = sql.size();+ while (i < n) {+ const char c = sql[i];+ // Skip string / quoted identifier literals verbatim.+ if (c == '\'' || c == '"' || c == '`') {+ const char quote = c;+ out.push_back(c); ++i;+ while (i < n) {+ if (sql[i] == '\\' && i + 1 < n) { out.push_back(sql[i]); out.push_back(sql[i + 1]); i += 2; continue; }+ if (sql[i] == quote) {+ // Handle doubled quote as escape: '' "" ``+ if (i + 1 < n && sql[i + 1] == quote) { out.push_back(quote); out.push_back(quote); i += 2; continue; }+ out.push_back(quote); ++i; break;+ }+ out.push_back(sql[i]); ++i;+ }+ continue;+ }+ // Skip line + block comments verbatim.+ if (c == '-' && i + 1 < n && sql[i + 1] == '-') {+ while (i < n && sql[i] != '\n') { out.push_back(sql[i++]); }+ continue;+ }+ if (c == '/' && i + 1 < n && sql[i + 1] == '*') {+ out.push_back(sql[i++]); out.push_back(sql[i++]);+ while (i + 1 < n && !(sql[i] == '*' && sql[i + 1] == '/')) { out.push_back(sql[i++]); }+ if (i + 1 < n) { out.push_back(sql[i++]); out.push_back(sql[i++]); }+ continue;+ }+ // `?` placeholder (MySQL/SQLite).+ if (c == '?') {+ if (qIndex < parameters.size()) {+ out += inlineValue(parameters[qIndex++]);+ } else {+ out.push_back(c);+ }+ ++i;+ continue;+ }+ // `$N` placeholder (PostgreSQL). Read digits and substitute when N <= params.+ if (c == '$' && i + 1 < n && std::isdigit(static_cast<unsigned char>(sql[i + 1]))) {+ std::size_t j = i + 1;+ std::size_t idx = 0;+ while (j < n && std::isdigit(static_cast<unsigned char>(sql[j]))) {+ idx = idx * 10 + static_cast<std::size_t>(sql[j] - '0');+ ++j;+ }+ if (idx >= 1 && idx <= parameters.size()) {+ out += inlineValue(parameters[idx - 1]);+ i = j;+ continue;+ }+ // Out-of-range or literal $0 — leave as-is.+ out.push_back(c); ++i;+ continue;+ }+ out.push_back(c); ++i;+ }+ return executeRaw(out);+}++inline void IDatabaseAdapter::createDatabase(const std::string& name) {+ const auto quoted = quoteIdentifier(sqlDialect(databaseType()), name);+ (void)executeRaw("CREATE DATABASE " + quoted);+}++inline void IDatabaseAdapter::dropDatabase(const std::string& name) {+ const auto quoted = quoteIdentifier(sqlDialect(databaseType()), name);+ (void)executeRaw("DROP DATABASE " + quoted);+}++}diff --git a/linux/src/Core/Protocols/Database/ISchemaInspectable.h b/linux/src/Core/Protocols/Database/ISchemaInspectable.hnew file mode 100644index 0000000..6af5087--- /dev/null+++ b/linux/src/Core/Protocols/Database/ISchemaInspectable.h@@ -0,0 +1,31 @@+#pragma once++#include <cstdint>+#include <optional>+#include <string>+#include <vector>++#include "Core/Models/Schema/SchemaSnapshot.h"++namespace gridex {++// Mirrors macos/Core/Protocols/Database/SchemaInspectable.swift.+// Implemented by adapters to feed AI context and schema browser views.+class ISchemaInspectable {+public:+ virtual ~ISchemaInspectable() = default;++ virtual SchemaSnapshot fullSchemaSnapshot(const std::optional<std::string>& database) = 0;+ virtual std::vector<ColumnStatistics> columnStatistics(const std::string& table,+ const std::optional<std::string>& schema,+ int sampleSize) = 0;+ virtual int tableRowCount(const std::string& table,+ const std::optional<std::string>& schema) = 0;+ virtual std::optional<std::int64_t> tableSizeBytes(const std::string& table,+ const std::optional<std::string>& schema) = 0;+ virtual std::vector<QueryStatisticsEntry> queryStatistics() = 0;+ virtual std::vector<std::string> primaryKeyColumns(const std::string& table,+ const std::optional<std::string>& schema) = 0;+};++}diff --git a/linux/src/Core/Utils/SqlStatementSplitter.h b/linux/src/Core/Utils/SqlStatementSplitter.hnew file mode 100644index 0000000..acf5e8c--- /dev/null+++ b/linux/src/Core/Utils/SqlStatementSplitter.h@@ -0,0 +1,79 @@+#pragma once++#include <string>+#include <vector>++namespace gridex {++// Splits a SQL buffer into individual statements on ";" while respecting+// single-quoted strings and -- / /* */ comments. Returns non-empty trimmed+// statements. Dollar-quoting ($$ ... $$) and DELIMITER rewriting are not+// supported; use native backup/restore for complex dumps.+inline std::vector<std::string> splitSqlStatements(const std::string& buf) {+ std::vector<std::string> out;+ std::string cur;+ cur.reserve(256);+ bool inSingle = false, inLineComment = false, inBlockComment = false;++ for (std::size_t i = 0; i < buf.size(); ++i) {+ const char c = buf[i];+ const char next = (i + 1 < buf.size()) ? buf[i + 1] : '\0';++ if (inLineComment) {+ cur.push_back(c);+ if (c == '\n') inLineComment = false;+ continue;+ }+ if (inBlockComment) {+ cur.push_back(c);+ if (c == '*' && next == '/') { cur.push_back(next); ++i; inBlockComment = false; }+ continue;+ }+ if (inSingle) {+ cur.push_back(c);+ if (c == '\'') {+ if (next == '\'') { cur.push_back(next); ++i; }+ else inSingle = false;+ }+ continue;+ }++ if (c == '-' && next == '-') { cur.push_back(c); cur.push_back(next); ++i; inLineComment = true; continue; }+ if (c == '/' && next == '*') { cur.push_back(c); cur.push_back(next); ++i; inBlockComment = true; continue; }+ if (c == '\'') { cur.push_back(c); inSingle = true; continue; }++ if (c == ';') {+ auto ws = [](char ch) { return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n'; };+ while (!cur.empty() && ws(cur.front())) cur.erase(cur.begin());+ while (!cur.empty() && ws(cur.back())) cur.pop_back();+ if (!cur.empty()) out.push_back(std::move(cur));+ cur.clear();+ continue;+ }+ cur.push_back(c);+ }++ auto ws = [](char ch) { return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n'; };+ while (!cur.empty() && ws(cur.front())) cur.erase(cur.begin());+ while (!cur.empty() && ws(cur.back())) cur.pop_back();+ if (!cur.empty()) out.push_back(std::move(cur));++ return out;+}++// Heuristic dialect hint shown read-only in the import wizard.+inline std::string detectSqlDialectHint(const std::string& buf) {+ const std::size_t probe = std::min(buf.size(), std::size_t{4096});+ const std::string sample(buf.data(), probe);++ bool hasBacktick = sample.find('`') != std::string::npos;+ bool hasDollarQuot = sample.find("$$") != std::string::npos;+ bool hasAutoIncr = sample.find("AUTO_INCREMENT") != std::string::npos ||+ sample.find("auto_increment") != std::string::npos;++ if (hasBacktick || hasAutoIncr) return "MySQL / MariaDB";+ if (hasDollarQuot) return "PostgreSQL";+ return "Generic SQL";+}++} // namespace gridexdiff --git a/linux/src/Data/Adapters/AdapterFactory.cpp b/linux/src/Data/Adapters/AdapterFactory.cppnew file mode 100644index 0000000..4329676--- /dev/null+++ b/linux/src/Data/Adapters/AdapterFactory.cpp@@ -0,0 +1,33 @@+#include "Data/Adapters/AdapterFactory.h"++#include <string>++#include "Core/Errors/GridexError.h"+#include "Data/Adapters/MSSQL/MssqlAdapter.h"+#include "Data/Adapters/MongoDB/MongodbAdapter.h"+#include "Data/Adapters/MySQL/MysqlAdapter.h"+#include "Data/Adapters/PostgreSQL/PostgresAdapter.h"+#include "Data/Adapters/Redis/RedisAdapter.h"+#include "Data/Adapters/SQLite/SqliteAdapter.h"++namespace gridex {++std::unique_ptr<IDatabaseAdapter> createAdapter(DatabaseType type) {+ switch (type) {+ case DatabaseType::SQLite:+ return std::make_unique<SqliteAdapter>();+ case DatabaseType::PostgreSQL:+ return std::make_unique<PostgresAdapter>();+ case DatabaseType::MySQL:+ return std::make_unique<MysqlAdapter>();+ case DatabaseType::MSSQL:+ return std::make_unique<MssqlAdapter>();+ case DatabaseType::Redis:+ return std::make_unique<RedisAdapter>();+ case DatabaseType::MongoDB:+ return std::make_unique<MongodbAdapter>();+ }+ throw ConfigurationError("Unknown DatabaseType");+}++}diff --git a/linux/src/Data/Adapters/AdapterFactory.h b/linux/src/Data/Adapters/AdapterFactory.hnew file mode 100644index 0000000..9d5c997--- /dev/null+++ b/linux/src/Data/Adapters/AdapterFactory.h@@ -0,0 +1,15 @@+#pragma once++#include <memory>++#include "Core/Enums/DatabaseType.h"+#include "Core/Protocols/Database/IDatabaseAdapter.h"++namespace gridex {++// Creates a concrete IDatabaseAdapter for the given database type.+// Unimplemented adapters (PostgreSQL/MySQL/MSSQL/MongoDB/Redis) throw+// gridex::ConfigurationError until Phase 2d/4 lands.+std::unique_ptr<IDatabaseAdapter> createAdapter(DatabaseType type);++}diff --git a/linux/src/Data/Adapters/MSSQL/MssqlAdapter.cpp b/linux/src/Data/Adapters/MSSQL/MssqlAdapter.cppnew file mode 100644index 0000000..b20ca8d--- /dev/null+++ b/linux/src/Data/Adapters/MSSQL/MssqlAdapter.cpp@@ -0,0 +1,733 @@+#include "Data/Adapters/MSSQL/MssqlAdapter.h"++#include <chrono>+#include <cstring>+#include <mutex>+#include <sstream>+#include <sybdb.h>++#include "Core/Errors/GridexError.h"++// Convenience: the header stores dbproc_ as void* to avoid leaking sybdb.h+// into translation units that include the header. Cast once here.+#define DBPROC() (static_cast<DBPROCESS*>(dbproc_))++namespace gridex {++namespace {++// dbinit() must be called exactly once before any db-lib usage.+void ensureLibraryInit() {+ static std::once_flag once;+ std::call_once(once, [] {+ if (dbinit() == FAIL)+ throw InternalError("FreeTDS dbinit() failed");+ // Suppress default error/message handlers (they print to stderr).+ dberrhandle([](DBPROCESS*, int, int, int, char*, char*) -> int {+ return INT_CANCEL;+ });+ dbmsghandle([](DBPROCESS*, DBINT, int, int, char*, char*, char*, int) -> int {+ return 0;+ });+ });+}++// Quote a T-SQL identifier with square brackets.+std::string msQuote(std::string_view ident) {+ std::string out;+ out.reserve(ident.size() + 2);+ out.push_back('[');+ for (char c : ident) {+ if (c == ']') out.push_back(']'); // escape ]+ out.push_back(c);+ }+ out.push_back(']');+ return out;+}++// Quote a string literal — double any single quotes.+std::string msLiteral(const std::string& s) {+ std::string out;+ out.reserve(s.size() + 2);+ out.push_back('\'');+ for (char c : s) {+ if (c == '\'') out.push_back('\'');+ out.push_back(c);+ }+ out.push_back('\'');+ return out;+}++QueryType detectQueryType(const std::string& sql) {+ auto start = sql.find_first_not_of(" \t\n\r");+ if (start == std::string::npos) return QueryType::Other;+ std::string head;+ for (auto i = start; i < sql.size() && i - start < 10; ++i)+ head.push_back(static_cast<char>(std::toupper(static_cast<unsigned char>(sql[i]))));+ auto starts = [&](const char* p) { return head.rfind(p, 0) == 0; };+ if (starts("SELECT") || starts("WITH") || starts("EXPLAIN") || starts("SHOW")) return QueryType::Select;+ if (starts("INSERT")) return QueryType::Insert;+ if (starts("UPDATE")) return QueryType::Update;+ if (starts("DELETE")) return QueryType::Delete;+ if (starts("CREATE") || starts("ALTER") || starts("DROP") || starts("TRUNCATE")) return QueryType::DDL;+ return QueryType::Other;+}++// Convert a RowValue to a T-SQL literal string for inline parameter expansion.+std::string rowValueToLiteral(const RowValue& v) {+ if (v.isNull()) return "NULL";+ if (v.isInteger()) return std::to_string(v.asInteger());+ if (v.isDouble()) return std::to_string(v.asDouble());+ if (v.isBoolean()) return v.asBoolean() ? "1" : "0";+ if (v.isString()) return msLiteral(v.asString());+ if (v.isDate()) return "'" + formatTimestampUtc(v.asDate()) + "'";+ if (v.isJson()) return msLiteral(v.asJson());+ if (v.isUuid()) return "'" + v.asUuid() + "'";+ return "NULL";+}++// Read a single cell from the current row in dbproc.+RowValue readCell(DBPROCESS* dbproc, int col) {+ const BYTE* data = dbdata(dbproc, col);+ const DBINT len = dbdatlen(dbproc, col);+ if (!data || len <= 0) return RowValue::makeNull();++ const int colType = dbcoltype(dbproc, col);+ switch (colType) {+ case SYBBIT:+ case SYBBITN: {+ const std::uint8_t b = *reinterpret_cast<const std::uint8_t*>(data);+ return RowValue::makeBoolean(b != 0);+ }+ case SYBINT1: {+ const std::uint8_t v = *reinterpret_cast<const std::uint8_t*>(data);+ return RowValue::makeInteger(static_cast<std::int64_t>(v));+ }+ case SYBINT2: {+ std::int16_t v{};+ std::memcpy(&v, data, sizeof(v));+ return RowValue::makeInteger(static_cast<std::int64_t>(v));+ }+ case SYBINT4: {+ std::int32_t v{};+ std::memcpy(&v, data, sizeof(v));+ return RowValue::makeInteger(static_cast<std::int64_t>(v));+ }+ case SYBINT8: {+ std::int64_t v{};+ std::memcpy(&v, data, sizeof(v));+ return RowValue::makeInteger(v);+ }+ case SYBINTN: {+ switch (len) {+ case 1: { std::uint8_t v{}; std::memcpy(&v, data, 1); return RowValue::makeInteger(v); }+ case 2: { std::int16_t v{}; std::memcpy(&v, data, 2); return RowValue::makeInteger(v); }+ case 4: { std::int32_t v{}; std::memcpy(&v, data, 4); return RowValue::makeInteger(v); }+ case 8: { std::int64_t v{}; std::memcpy(&v, data, 8); return RowValue::makeInteger(v); }+ default: break;+ }+ break;+ }+ case SYBFLT8: {+ double v{};+ std::memcpy(&v, data, sizeof(v));+ return RowValue::makeDouble(v);+ }+ case SYBFLTN: {+ if (len == 4) { float v{}; std::memcpy(&v, data, 4); return RowValue::makeDouble(static_cast<double>(v)); }+ if (len == 8) { double v{}; std::memcpy(&v, data, 8); return RowValue::makeDouble(v); }+ break;+ }+ default:+ break;+ }+ // Default: treat as string (char/nchar/varchar/nvarchar/text/datetime/numeric/money/…)+ return RowValue::makeString(std::string(reinterpret_cast<const char*>(data),+ static_cast<std::size_t>(len)));+}++} // anonymous namespace++// ---- Lifecycle ----++MssqlAdapter::MssqlAdapter() {+ ensureLibraryInit();+}++MssqlAdapter::~MssqlAdapter() {+ std::lock_guard lock(mutex_);+ if (dbproc_) { dbclose(DBPROC()); dbproc_ = nullptr; }+ connected_.store(false, std::memory_order_release);+}++void MssqlAdapter::connect(const ConnectionConfig& config,+ const std::optional<std::string>& password) {+ std::lock_guard lock(mutex_);+ if (dbproc_) { dbclose(DBPROC()); dbproc_ = nullptr; }++ const std::string host = config.host.value_or("localhost");+ const int port = config.port.value_or(1433);+ const std::string user = config.username.value_or("sa");+ const std::string database = config.database.value_or("master");+ const std::string pwd = password.value_or("");++ // FreeTDS accepts "host:port" as the server string.+ const std::string server = host + ":" + std::to_string(port);++ LOGINREC* login = dblogin();+ if (!login) throw ConnectionError("MSSQL: dblogin() returned null");++ DBSETLUSER(login, user.c_str());+ DBSETLPWD(login, pwd.c_str());+ DBSETLAPP(login, "gridex");+ DBSETLCHARSET(login, "UTF-8");+ DBSETLDBNAME(login, database.c_str());++ DBPROCESS* proc = dbopen(login, server.c_str());+ dbloginfree(login);++ if (!proc) { // dbopen returns NULL on failure (FAIL == 0)+ throw ConnectionError("MSSQL: dbopen failed — server=" + server ++ " user=" + user);+ }++ dbproc_ = static_cast<void*>(proc);+ connected_.store(true, std::memory_order_release);+ databaseName_ = database;+}++void MssqlAdapter::disconnect() {+ std::lock_guard lock(mutex_);+ if (dbproc_) { dbclose(DBPROC()); dbproc_ = nullptr; }+ connected_.store(false, std::memory_order_release);+ databaseName_.reset();+}++bool MssqlAdapter::testConnection(const ConnectionConfig& config,+ const std::optional<std::string>& password) {+ MssqlAdapter probe;+ probe.connect(config, password);+ probe.disconnect();+ return true;+}++void MssqlAdapter::ensureConnected() const {+ if (!connected_.load(std::memory_order_acquire) || !dbproc_)+ throw QueryError("Not connected to MSSQL");+}++// ---- Core query execution ----++QueryResult MssqlAdapter::executeInternal(const std::string& sql) {+ ensureConnected();+ const auto start = std::chrono::steady_clock::now();++ std::lock_guard lock(mutex_);++ // Clear any pending results from a previous query.+ dbcancel(DBPROC());++ if (dbcmd(DBPROC(), sql.c_str()) == FAIL)+ throw QueryError("MSSQL: dbcmd failed");++ if (dbsqlexec(DBPROC()) == FAIL)+ throw QueryError("MSSQL: dbsqlexec failed");++ QueryResult result;+ result.queryType = detectQueryType(sql);++ // Consume result sets — collect only the first SELECT result set.+ bool gotColumns = false;+ RETCODE rc = dbresults(DBPROC());+ while (rc != NO_MORE_RESULTS && rc != FAIL) {+ const int ncols = dbnumcols(DBPROC());+ if (ncols > 0 && !gotColumns) {+ // Build column headers+ result.columns.reserve(static_cast<std::size_t>(ncols));+ for (int c = 1; c <= ncols; ++c) {+ ColumnHeader h;+ const char* name = dbcolname(DBPROC(), c);+ h.name = name ? name : ("col" + std::to_string(c));+ h.dataType = std::to_string(dbcoltype(DBPROC(), c));+ result.columns.push_back(std::move(h));+ }+ gotColumns = true;++ // Fetch rows+ STATUS rowStatus;+ while ((rowStatus = dbnextrow(DBPROC())) != NO_MORE_ROWS) {+ if (rowStatus == FAIL) {+ throw QueryError("MSSQL: dbnextrow failed");+ }+ if (rowStatus != REG_ROW) continue; // skip compute rows+ std::vector<RowValue> row;+ row.reserve(static_cast<std::size_t>(ncols));+ for (int c = 1; c <= ncols; ++c)+ row.push_back(readCell(DBPROC(), c));+ result.rows.push_back(std::move(row));+ }+ result.rowsAffected = static_cast<int>(result.rows.size());+ } else {+ // Drain remaining result sets (e.g. row-count from INSERT/UPDATE/DELETE)+ STATUS rowStatus;+ while ((rowStatus = dbnextrow(DBPROC())) != NO_MORE_ROWS) {+ if (rowStatus == FAIL) break;+ }+ // DBCOUNT gives rows affected for DML+ const DBINT affected = dbcount(DBPROC());+ if (affected >= 0 && result.rowsAffected == 0)+ result.rowsAffected = static_cast<int>(affected);+ }+ rc = dbresults(DBPROC());+ }++ if (rc == FAIL)+ throw QueryError("MSSQL: dbresults failed");++ result.executionTime = std::chrono::steady_clock::now() - start;+ return result;+}++QueryResult MssqlAdapter::execute(const std::string& query,+ const std::vector<QueryParameter>& parameters) {+ // db-lib has no native parameterized queries — inline values.+ if (parameters.empty()) return executeInternal(query);++ std::string sql;+ sql.reserve(query.size() + parameters.size() * 8);+ std::size_t i = 0;+ std::size_t paramIdx = 0;+ const std::size_t n = query.size();+ while (i < n) {+ // Respect string literals+ if (query[i] == '\'' ) {+ sql.push_back(query[i++]);+ while (i < n) {+ if (query[i] == '\'' && i + 1 < n && query[i+1] == '\'') {+ sql.push_back('\''); sql.push_back('\''); i += 2; continue;+ }+ if (query[i] == '\'') { sql.push_back(query[i++]); break; }+ sql.push_back(query[i++]);+ }+ continue;+ }+ // ? placeholder+ if (query[i] == '?' && paramIdx < parameters.size()) {+ sql += rowValueToLiteral(parameters[paramIdx++].value);+ ++i; continue;+ }+ // @N placeholder (MSSQL style)+ if (query[i] == '@' && i + 1 < n && std::isdigit(static_cast<unsigned char>(query[i+1]))) {+ std::size_t j = i + 1;+ std::size_t idx = 0;+ while (j < n && std::isdigit(static_cast<unsigned char>(query[j])))+ idx = idx * 10 + static_cast<std::size_t>(query[j++] - '0');+ if (idx >= 1 && idx <= parameters.size()) {+ sql += rowValueToLiteral(parameters[idx - 1].value);+ i = j; continue;+ }+ }+ sql.push_back(query[i++]);+ }+ return executeInternal(sql);+}++QueryResult MssqlAdapter::executeRaw(const std::string& sql) {+ return executeInternal(sql);+}++std::string MssqlAdapter::qualified(const std::string& table,+ const std::optional<std::string>& schema) const {+ if (schema) return msQuote(*schema) + "." + msQuote(table);+ return msQuote(table);+}++// ---- Schema inspection ----++std::vector<std::string> MssqlAdapter::listDatabases() {+ const auto r = executeInternal(+ "SELECT name FROM sys.databases WHERE state_desc = 'ONLINE' ORDER BY name");+ std::vector<std::string> out;+ out.reserve(r.rows.size());+ for (const auto& row : r.rows)+ if (!row.empty() && row[0].isString()) out.push_back(row[0].asString());+ return out;+}++std::vector<std::string> MssqlAdapter::listSchemas(const std::optional<std::string>& /*database*/) {+ const auto r = executeInternal(+ "SELECT schema_name FROM information_schema.schemata ORDER BY schema_name");+ std::vector<std::string> out;+ for (const auto& row : r.rows)+ if (!row.empty() && row[0].isString()) out.push_back(row[0].asString());+ return out;+}++std::vector<TableInfo> MssqlAdapter::listTables(const std::optional<std::string>& schema) {+ const std::string s = schema.value_or("dbo");+ const auto r = executeInternal(+ "SELECT table_name FROM information_schema.tables "+ "WHERE table_schema = " + msLiteral(s) ++ " AND table_type = 'BASE TABLE' ORDER BY table_name");+ std::vector<TableInfo> out;+ out.reserve(r.rows.size());+ for (const auto& row : r.rows) {+ if (row.empty() || !row[0].isString()) continue;+ TableInfo t;+ t.name = row[0].asString();+ t.schema = s;+ t.type = TableKind::Table;+ out.push_back(std::move(t));+ }+ return out;+}++std::vector<ViewInfo> MssqlAdapter::listViews(const std::optional<std::string>& schema) {+ const std::string s = schema.value_or("dbo");+ const auto r = executeInternal(+ "SELECT table_name, view_definition FROM information_schema.views "+ "WHERE table_schema = " + msLiteral(s) + " ORDER BY table_name");+ std::vector<ViewInfo> out;+ for (const auto& row : r.rows) {+ if (row.empty() || !row[0].isString()) continue;+ ViewInfo v;+ v.name = row[0].asString();+ v.schema = s;+ if (row.size() > 1) v.definition = row[1].tryStringValue();+ out.push_back(std::move(v));+ }+ return out;+}++TableDescription MssqlAdapter::describeTable(const std::string& name,+ const std::optional<std::string>& schema) {+ TableDescription desc;+ desc.name = name;+ desc.schema = schema;++ const std::string s = schema.value_or("dbo");+ const auto r = executeInternal(+ "SELECT column_name, data_type, is_nullable, column_default, ordinal_position "+ "FROM information_schema.columns "+ "WHERE table_schema = " + msLiteral(s) ++ " AND table_name = " + msLiteral(name) ++ " ORDER BY ordinal_position");++ const auto pks = primaryKeyColumns(name, schema);+ for (const auto& row : r.rows) {+ if (row.size() < 5) continue;+ ColumnInfo c;+ c.name = row[0].tryStringValue().value_or("");+ c.dataType = row[1].tryStringValue().value_or("");+ c.isNullable = row[2].tryStringValue().value_or("YES") == "YES";+ if (!row[3].isNull()) c.defaultValue = row[3].tryStringValue();+ c.ordinalPosition = static_cast<int>(row[4].tryIntValue().value_or(0));+ for (const auto& pk : pks) if (pk == c.name) c.isPrimaryKey = true;+ desc.columns.push_back(std::move(c));+ }++ try { desc.foreignKeys = listForeignKeys(name, schema); } catch (...) {}+ try { desc.indexes = listIndexes(name, schema); } catch (...) {}+ try { desc.estimatedRowCount = tableRowCount(name, schema); } catch (...) {}+ return desc;+}++std::vector<IndexInfo> MssqlAdapter::listIndexes(const std::string& table,+ const std::optional<std::string>& schema) {+ const std::string s = schema.value_or("dbo");+ const auto r = executeInternal(+ "SELECT i.name, i.is_unique "+ "FROM sys.indexes i "+ "JOIN sys.objects o ON o.object_id = i.object_id "+ "JOIN sys.schemas sc ON sc.schema_id = o.schema_id "+ "WHERE o.name = " + msLiteral(table) ++ " AND sc.name = " + msLiteral(s) ++ " AND i.name IS NOT NULL ORDER BY i.name");+ std::vector<IndexInfo> out;+ for (const auto& row : r.rows) {+ if (row.size() < 2) continue;+ IndexInfo idx;+ idx.name = row[0].tryStringValue().value_or("");+ // is_unique is a bit column — may come as integer or "1"/"0"+ idx.isUnique = row[1].tryIntValue().value_or(0) != 0 ||+ row[1].tryStringValue().value_or("") == "1";+ idx.tableName = table;+ out.push_back(std::move(idx));+ }+ return out;+}++std::vector<ForeignKeyInfo> MssqlAdapter::listForeignKeys(const std::string& table,+ const std::optional<std::string>& schema) {+ const std::string s = schema.value_or("dbo");+ const auto r = executeInternal(+ "SELECT fk.name, kcu.column_name, ccu.table_name, ccu.column_name "+ "FROM information_schema.table_constraints fk "+ "JOIN information_schema.key_column_usage kcu "+ " ON fk.constraint_name = kcu.constraint_name "+ "JOIN information_schema.constraint_column_usage ccu "+ " ON fk.constraint_name = ccu.constraint_name "+ "WHERE fk.table_schema = " + msLiteral(s) ++ " AND fk.table_name = " + msLiteral(table) ++ " AND fk.constraint_type = 'FOREIGN KEY'");+ std::vector<ForeignKeyInfo> out;+ for (const auto& row : r.rows) {+ if (row.size() < 4) continue;+ ForeignKeyInfo fk;+ fk.name = row[0].tryStringValue();+ fk.columns.push_back(row[1].tryStringValue().value_or(""));+ fk.referencedTable = row[2].tryStringValue().value_or("");+ fk.referencedColumns.push_back(row[3].tryStringValue().value_or(""));+ out.push_back(std::move(fk));+ }+ return out;+}++std::vector<std::string> MssqlAdapter::listFunctions(const std::optional<std::string>& schema) {+ const std::string s = schema.value_or("dbo");+ const auto r = executeInternal(+ "SELECT routine_name FROM information_schema.routines "+ "WHERE specific_schema = " + msLiteral(s) ++ " AND routine_type = 'FUNCTION' ORDER BY routine_name");+ std::vector<std::string> out;+ for (const auto& row : r.rows)+ if (!row.empty() && row[0].isString()) out.push_back(row[0].asString());+ return out;+}++std::string MssqlAdapter::getFunctionSource(const std::string& name,+ const std::optional<std::string>& schema) {+ const std::string s = schema.value_or("dbo");+ const auto r = executeInternal(+ "SELECT OBJECT_DEFINITION(OBJECT_ID(" + msLiteral(s + "." + name) + "))");+ if (r.rows.empty() || r.rows[0].empty()) return {};+ return r.rows[0][0].tryStringValue().value_or("");+}++// ---- Stored procedures ----++std::vector<std::string> MssqlAdapter::listProcedures(const std::optional<std::string>& schema) {+ const std::string s = schema.value_or("dbo");+ const auto r = executeInternal(+ "SELECT p.name FROM sys.procedures p "+ "JOIN sys.schemas sc ON sc.schema_id = p.schema_id "+ "WHERE sc.name = " + msLiteral(s) + " ORDER BY p.name");+ std::vector<std::string> out;+ for (const auto& row : r.rows)+ if (!row.empty() && row[0].isString()) out.push_back(row[0].asString());+ return out;+}++std::string MssqlAdapter::getProcedureSource(const std::string& name,+ const std::optional<std::string>& schema) {+ const std::string s = schema.value_or("dbo");+ const auto r = executeInternal(+ "SELECT OBJECT_DEFINITION(OBJECT_ID(" + msLiteral(s + "." + name) + "))");+ if (r.rows.empty() || r.rows[0].empty()) return {};+ return r.rows[0][0].tryStringValue().value_or("");+}++std::vector<std::string> MssqlAdapter::listProcedureParameters(+ const std::string& name, const std::optional<std::string>& schema) {+ const std::string s = schema.value_or("dbo");+ const auto r = executeInternal(+ "SELECT p.name + ' ' + t.name "+ "FROM sys.parameters p "+ "JOIN sys.objects o ON o.object_id = p.object_id "+ "JOIN sys.schemas sc ON sc.schema_id = o.schema_id "+ "JOIN sys.types t ON t.user_type_id = p.user_type_id "+ "WHERE o.name = " + msLiteral(name) ++ " AND sc.name = " + msLiteral(s) ++ " ORDER BY p.parameter_id");+ std::vector<std::string> out;+ for (const auto& row : r.rows)+ if (!row.empty() && row[0].isString()) out.push_back(row[0].asString());+ return out;+}++// ---- DML ----++QueryResult MssqlAdapter::insertRow(const std::string& table,+ const std::optional<std::string>& schema,+ const std::unordered_map<std::string, RowValue>& values) {+ if (values.empty()) throw QueryError("insertRow: empty values");+ std::string cols, vals;+ int i = 0;+ for (const auto& [k, v] : values) {+ if (i > 0) { cols += ", "; vals += ", "; }+ cols += msQuote(k);+ vals += rowValueToLiteral(v);+ ++i;+ }+ return executeInternal("INSERT INTO " + qualified(table, schema) ++ " (" + cols + ") VALUES (" + vals + ")");+}++QueryResult MssqlAdapter::updateRow(const std::string& table,+ const std::optional<std::string>& schema,+ const std::unordered_map<std::string, RowValue>& set,+ const std::unordered_map<std::string, RowValue>& where) {+ if (set.empty() || where.empty()) throw QueryError("updateRow: empty set/where");+ std::string setClause, whereClause;+ {+ int i = 0;+ for (const auto& [k, v] : set) {+ if (i > 0) setClause += ", ";+ setClause += msQuote(k) + " = " + rowValueToLiteral(v);+ ++i;+ }+ }+ {+ bool first = true;+ for (const auto& [k, v] : where) {+ if (!first) whereClause += " AND ";+ whereClause += msQuote(k) + " = " + rowValueToLiteral(v);+ first = false;+ }+ }+ return executeInternal("UPDATE " + qualified(table, schema) ++ " SET " + setClause + " WHERE " + whereClause);+}++QueryResult MssqlAdapter::deleteRow(const std::string& table,+ const std::optional<std::string>& schema,+ const std::unordered_map<std::string, RowValue>& where) {+ if (where.empty()) throw QueryError("deleteRow: empty where");+ std::string whereClause;+ bool first = true;+ for (const auto& [k, v] : where) {+ if (!first) whereClause += " AND ";+ whereClause += msQuote(k) + " = " + rowValueToLiteral(v);+ first = false;+ }+ return executeInternal("DELETE FROM " + qualified(table, schema) ++ " WHERE " + whereClause);+}++// ---- Transactions ----++void MssqlAdapter::beginTransaction() { (void)executeInternal("BEGIN TRANSACTION"); }+void MssqlAdapter::commitTransaction() { (void)executeInternal("COMMIT TRANSACTION"); }+void MssqlAdapter::rollbackTransaction() { (void)executeInternal("ROLLBACK TRANSACTION"); }++// ---- Pagination ----++QueryResult MssqlAdapter::fetchRows(const std::string& table,+ const std::optional<std::string>& schema,+ const std::optional<std::vector<std::string>>& columns,+ const std::optional<FilterExpression>& where,+ const std::optional<std::vector<QuerySortDescriptor>>& orderBy,+ int limit, int offset) {+ std::string colList = "*";+ if (columns && !columns->empty()) {+ colList.clear();+ for (std::size_t i = 0; i < columns->size(); ++i) {+ if (i > 0) colList += ", ";+ colList += msQuote((*columns)[i]);+ }+ }++ // MSSQL 2012+ OFFSET/FETCH syntax requires an ORDER BY clause.+ std::string orderClause;+ if (orderBy && !orderBy->empty()) {+ for (std::size_t i = 0; i < orderBy->size(); ++i) {+ if (i > 0) orderClause += ", ";+ orderClause += (*orderBy)[i].toSQL(SQLDialect::MSSQL);+ }+ } else {+ // Provide a deterministic default so OFFSET/FETCH is valid.+ orderClause = "(SELECT NULL)";+ }++ std::string sql = "SELECT " + colList + " FROM " + qualified(table, schema);+ if (where && !where->conditions.empty())+ sql += " WHERE " + where->toSQL(SQLDialect::MSSQL);+ sql += " ORDER BY " + orderClause;+ sql += " OFFSET " + std::to_string(offset) + " ROWS";+ sql += " FETCH NEXT " + std::to_string(limit) + " ROWS ONLY";+ return executeInternal(sql);+}++// ---- Server info ----++std::string MssqlAdapter::serverVersion() {+ const auto r = executeInternal("SELECT @@VERSION");+ if (r.rows.empty() || r.rows[0].empty()) return "MSSQL";+ return r.rows[0][0].tryStringValue().value_or("MSSQL");+}++std::optional<std::string> MssqlAdapter::currentDatabase() {+ if (databaseName_) return databaseName_;+ const auto r = executeInternal("SELECT DB_NAME()");+ if (r.rows.empty() || r.rows[0].empty()) return std::nullopt;+ return r.rows[0][0].tryStringValue();+}++// ---- ISchemaInspectable ----++SchemaSnapshot MssqlAdapter::fullSchemaSnapshot(const std::optional<std::string>& /*database*/) {+ SchemaSnapshot snap;+ snap.databaseName = currentDatabase().value_or("");+ snap.databaseType = DatabaseType::MSSQL;+ snap.capturedAt = std::chrono::system_clock::now();+ for (const auto& s : listSchemas(std::nullopt)) {+ SchemaInfo si;+ si.name = s;+ for (const auto& t : listTables(s))+ si.tables.push_back(describeTable(t.name, s));+ si.views = listViews(s);+ snap.schemas.push_back(std::move(si));+ }+ return snap;+}++std::vector<ColumnStatistics> MssqlAdapter::columnStatistics(const std::string& /*table*/,+ const std::optional<std::string>& /*schema*/,+ int /*sampleSize*/) {+ return {}; // deferred to Phase 7+}++int MssqlAdapter::tableRowCount(const std::string& table,+ const std::optional<std::string>& schema) {+ const auto r = executeInternal("SELECT COUNT(*) FROM " + qualified(table, schema));+ if (r.rows.empty() || r.rows[0].empty()) return 0;+ return static_cast<int>(r.rows[0][0].tryIntValue().value_or(0));+}++std::optional<std::int64_t> MssqlAdapter::tableSizeBytes(const std::string& table,+ const std::optional<std::string>& schema) {+ const std::string s = schema.value_or("dbo");+ const auto r = executeInternal(+ "SELECT SUM(a.total_pages) * 8192 "+ "FROM sys.tables t "+ "JOIN sys.schemas sc ON sc.schema_id = t.schema_id "+ "JOIN sys.indexes i ON i.object_id = t.object_id "+ "JOIN sys.partitions p ON p.object_id = t.object_id AND p.index_id = i.index_id "+ "JOIN sys.allocation_units a ON a.container_id = p.partition_id "+ "WHERE t.name = " + msLiteral(table) ++ " AND sc.name = " + msLiteral(s));+ if (r.rows.empty() || r.rows[0].empty() || r.rows[0][0].isNull()) return std::nullopt;+ return r.rows[0][0].tryIntValue();+}++std::vector<QueryStatisticsEntry> MssqlAdapter::queryStatistics() { return {}; }++std::vector<std::string> MssqlAdapter::primaryKeyColumns(const std::string& table,+ const std::optional<std::string>& schema) {+ const std::string s = schema.value_or("dbo");+ const auto r = executeInternal(+ "SELECT kcu.column_name "+ "FROM information_schema.table_constraints tc "+ "JOIN information_schema.key_column_usage kcu "+ " ON tc.constraint_name = kcu.constraint_name "+ "WHERE tc.table_schema = " + msLiteral(s) ++ " AND tc.table_name = " + msLiteral(table) ++ " AND tc.constraint_type = 'PRIMARY KEY' "+ "ORDER BY kcu.ordinal_position");+ std::vector<std::string> out;+ for (const auto& row : r.rows)+ if (!row.empty() && row[0].isString()) out.push_back(row[0].asString());+ return out;+}++} // namespace gridexdiff --git a/linux/src/Data/Adapters/MSSQL/MssqlAdapter.h b/linux/src/Data/Adapters/MSSQL/MssqlAdapter.hnew file mode 100644index 0000000..7cf0cd8--- /dev/null+++ b/linux/src/Data/Adapters/MSSQL/MssqlAdapter.h@@ -0,0 +1,104 @@+#pragma once++#include <atomic>+#include <mutex>+#include <optional>+#include <string>++#include "Core/Protocols/Database/IDatabaseAdapter.h"+#include "Core/Protocols/Database/ISchemaInspectable.h"++namespace gridex {++// Microsoft SQL Server adapter using FreeTDS db-lib (libsybdb).+// Mirrors the PostgresAdapter pattern: synchronous, mutex-protected,+// std::atomic<bool> connected_ for race-free isConnected().+//+// Schema inspection uses information_schema / sys catalog queries+// identical to the macOS CosmoMSSQL adapter.+class MssqlAdapter final : public IDatabaseAdapter, public ISchemaInspectable {+public:+ MssqlAdapter();+ ~MssqlAdapter() override;++ MssqlAdapter(const MssqlAdapter&) = delete;+ MssqlAdapter& operator=(const MssqlAdapter&) = delete;++ [[nodiscard]] DatabaseType databaseType() const noexcept override { return DatabaseType::MSSQL; }+ [[nodiscard]] bool isConnected() const noexcept override { return connected_.load(std::memory_order_acquire); }++ void connect(const ConnectionConfig& config, const std::optional<std::string>& password) override;+ void disconnect() override;+ bool testConnection(const ConnectionConfig& config, const std::optional<std::string>& password) override;++ QueryResult execute(const std::string& query, const std::vector<QueryParameter>& parameters) override;+ QueryResult executeRaw(const std::string& sql) override;++ std::vector<std::string> listDatabases() override;+ std::vector<std::string> listSchemas(const std::optional<std::string>& database) override;+ std::vector<TableInfo> listTables(const std::optional<std::string>& schema) override;+ std::vector<ViewInfo> listViews(const std::optional<std::string>& schema) override;+ TableDescription describeTable(const std::string& name,+ const std::optional<std::string>& schema) override;+ std::vector<IndexInfo> listIndexes(const std::string& table,+ const std::optional<std::string>& schema) override;+ std::vector<ForeignKeyInfo> listForeignKeys(const std::string& table,+ const std::optional<std::string>& schema) override;+ std::vector<std::string> listFunctions(const std::optional<std::string>& schema) override;+ std::string getFunctionSource(const std::string& name,+ const std::optional<std::string>& schema) override;++ // Stored procedures — MSSQL implements these.+ std::vector<std::string> listProcedures(const std::optional<std::string>& schema) override;+ std::string getProcedureSource(const std::string& name,+ const std::optional<std::string>& schema) override;+ std::vector<std::string> listProcedureParameters(const std::string& name,+ const std::optional<std::string>& schema) override;++ QueryResult insertRow(const std::string& table, const std::optional<std::string>& schema,+ const std::unordered_map<std::string, RowValue>& values) override;+ QueryResult updateRow(const std::string& table, const std::optional<std::string>& schema,+ const std::unordered_map<std::string, RowValue>& set,+ const std::unordered_map<std::string, RowValue>& where) override;+ QueryResult deleteRow(const std::string& table, const std::optional<std::string>& schema,+ const std::unordered_map<std::string, RowValue>& where) override;++ void beginTransaction() override;+ void commitTransaction() override;+ void rollbackTransaction() override;++ QueryResult fetchRows(const std::string& table,+ const std::optional<std::string>& schema,+ const std::optional<std::vector<std::string>>& columns,+ const std::optional<FilterExpression>& where,+ const std::optional<std::vector<QuerySortDescriptor>>& orderBy,+ int limit, int offset) override;++ std::string serverVersion() override;+ std::optional<std::string> currentDatabase() override;++ // ISchemaInspectable+ SchemaSnapshot fullSchemaSnapshot(const std::optional<std::string>& database) override;+ std::vector<ColumnStatistics> columnStatistics(const std::string& table,+ const std::optional<std::string>& schema,+ int sampleSize) override;+ int tableRowCount(const std::string& table,+ const std::optional<std::string>& schema) override;+ std::optional<std::int64_t> tableSizeBytes(const std::string& table,+ const std::optional<std::string>& schema) override;+ std::vector<QueryStatisticsEntry> queryStatistics() override;+ std::vector<std::string> primaryKeyColumns(const std::string& table,+ const std::optional<std::string>& schema) override;++private:+ QueryResult executeInternal(const std::string& sql);+ void ensureConnected() const;+ std::string qualified(const std::string& table, const std::optional<std::string>& schema) const;++ void* dbproc_ = nullptr; // actually DBPROCESS*; sybdb.h only included in .cpp+ std::optional<std::string> databaseName_;+ std::atomic<bool> connected_{false};+ mutable std::mutex mutex_;+};++}diff --git a/linux/src/Data/Adapters/MongoDB/MongodbAdapter.cpp b/linux/src/Data/Adapters/MongoDB/MongodbAdapter.cppnew file mode 100644index 0000000..b918747--- /dev/null+++ b/linux/src/Data/Adapters/MongoDB/MongodbAdapter.cpp@@ -0,0 +1,741 @@+#include "Data/Adapters/MongoDB/MongodbAdapter.h"++#include <chrono>+#include <mutex>+#include <sstream>++#include <bsoncxx/builder/basic/document.hpp>+#include <bsoncxx/builder/basic/kvp.hpp>+#include <bsoncxx/json.hpp>+#include <bsoncxx/types.hpp>+#include <mongocxx/client.hpp>+#include <mongocxx/database.hpp>+#include <mongocxx/exception/exception.hpp>+#include <mongocxx/instance.hpp>+#include <mongocxx/uri.hpp>++#include "Core/Errors/GridexError.h"++namespace gridex {++// ---------------------------------------------------------------------------+// Internal helpers+// ---------------------------------------------------------------------------++namespace {++// Convert a bsoncxx element value to a RowValue.+RowValue bsonElementToRowValue(const bsoncxx::document::element& elem) {+ using bsoncxx::type;+ switch (elem.type()) {+ case type::k_string:+ return RowValue::makeString(std::string(elem.get_string().value));+ case type::k_int32:+ return RowValue::makeInteger(static_cast<std::int64_t>(elem.get_int32().value));+ case type::k_int64:+ return RowValue::makeInteger(elem.get_int64().value);+ case type::k_double:+ return RowValue::makeDouble(elem.get_double().value);+ case type::k_bool:+ return RowValue::makeBoolean(elem.get_bool().value);+ case type::k_null:+ return RowValue::makeNull();+ case type::k_oid:+ return RowValue::makeString(elem.get_oid().value.to_string());+ case type::k_date:+ // Milliseconds since epoch → human-readable string+ return RowValue::makeString(std::to_string(+ elem.get_date().value.count()) + "ms");+ case type::k_document:+ return RowValue::makeJson(bsoncxx::to_json(elem.get_document().value));+ case type::k_array:+ return RowValue::makeJson(bsoncxx::to_json(elem.get_array().value));+ case type::k_undefined:+ case type::k_binary:+ case type::k_regex:+ case type::k_dbpointer:+ case type::k_code:+ case type::k_symbol:+ case type::k_codewscope:+ case type::k_timestamp:+ case type::k_decimal128:+ case type::k_maxkey:+ case type::k_minkey:+ default:+ // Serialize complex/unknown types as JSON string+ return RowValue::makeString(bsoncxx::to_json(+ bsoncxx::builder::basic::make_document(+ bsoncxx::builder::basic::kvp("v", elem.get_value()))));+ }+}++// Determine the BSON type name as a string for column metadata.+std::string bsonTypeName(bsoncxx::type t) {+ using bsoncxx::type;+ switch (t) {+ case type::k_string: return "string";+ case type::k_int32: return "int32";+ case type::k_int64: return "int64";+ case type::k_double: return "double";+ case type::k_bool: return "boolean";+ case type::k_null: return "null";+ case type::k_oid: return "objectId";+ case type::k_date: return "date";+ case type::k_document: return "document";+ case type::k_array: return "array";+ case type::k_binary: return "binary";+ case type::k_regex: return "regex";+ case type::k_timestamp: return "timestamp";+ case type::k_decimal128:return "decimal128";+ default: return "unknown";+ }+}++// Convert a RowValue to a BSON value appended into a builder document.+void appendRowValueToBson(bsoncxx::builder::basic::document& doc,+ const std::string& key,+ const RowValue& v) {+ using namespace bsoncxx::builder::basic;+ if (v.isNull()) {+ doc.append(kvp(key, bsoncxx::types::b_null{}));+ } else if (v.isString()) {+ doc.append(kvp(key, v.asString()));+ } else if (v.isInteger()) {+ doc.append(kvp(key, v.asInteger()));+ } else if (v.isDouble()) {+ doc.append(kvp(key, v.asDouble()));+ } else if (v.isBoolean()) {+ doc.append(kvp(key, v.asBoolean()));+ } else if (v.isJson()) {+ // Parse JSON string back to BSON document+ try {+ auto bson = bsoncxx::from_json(v.asJson());+ doc.append(kvp(key, bsoncxx::types::b_document{bson.view()}));+ } catch (...) {+ doc.append(kvp(key, v.asJson()));+ }+ } else {+ // Fallback: store as string representation+ doc.append(kvp(key, v.description()));+ }+}++} // anonymous namespace++// ---------------------------------------------------------------------------+// Pimpl struct holding mongocxx objects+// ---------------------------------------------------------------------------++struct MongodbAdapter::Impl {+ std::unique_ptr<mongocxx::client> client;++ mongocxx::database getDb(const std::string& dbName) {+ if (!client) throw ConnectionError("MongoDB client is not initialized");+ return (*client)[dbName];+ }+};++// ---------------------------------------------------------------------------+// mongocxx::instance singleton guard+// ---------------------------------------------------------------------------++namespace {++void ensureMongocxxInstance() {+ static std::once_flag flag;+ std::call_once(flag, []() {+ // mongocxx::instance must be created exactly once per process.+ // Storing in a static local ensures lifetime until program exit.+ static mongocxx::instance inst{};+ (void)inst;+ });+}++} // anonymous namespace++// ---------------------------------------------------------------------------+// Constructor / Destructor+// ---------------------------------------------------------------------------++MongodbAdapter::MongodbAdapter()+ : impl_(std::make_unique<Impl>()) {+ ensureMongocxxInstance();+}++MongodbAdapter::~MongodbAdapter() {+ std::lock_guard lock(mutex_);+ impl_->client.reset();+ connected_.store(false, std::memory_order_release);+}++// ---------------------------------------------------------------------------+// Connection lifecycle+// ---------------------------------------------------------------------------++void MongodbAdapter::connect(const ConnectionConfig& config,+ const std::optional<std::string>& password) {+ std::lock_guard lock(mutex_);++ const std::string host = config.host.value_or("localhost");+ const int port = config.port.value_or(27017);++ // Build URI: mongodb://[username:password@]host:port[/database]+ std::string uri = "mongodb://";+ if (config.username && !config.username->empty()) {+ uri += *config.username;+ if (password && !password->empty()) uri += ":" + *password;+ uri += "@";+ }+ uri += host + ":" + std::to_string(port);++ const std::string dbName = config.database.value_or("admin");+ if (!dbName.empty()) uri += "/" + dbName;++ // Add server-selection timeout (5 s) so connect() fails fast+ uri += "?serverSelectionTimeoutMS=5000&connectTimeoutMS=5000";++ try {+ mongocxx::uri mongoUri(uri);+ impl_->client = std::make_unique<mongocxx::client>(mongoUri);++ // Force an actual connection attempt by pinging the server+ auto db = (*impl_->client)[dbName];+ using namespace bsoncxx::builder::basic;+ auto pingCmd = make_document(kvp("ping", 1));+ db.run_command(pingCmd.view());++ currentDb_ = dbName;+ connected_.store(true, std::memory_order_release);+ } catch (const mongocxx::exception& ex) {+ impl_->client.reset();+ throw ConnectionError(std::string("MongoDB connect failed: ") + ex.what());+ }+}++void MongodbAdapter::disconnect() {+ std::lock_guard lock(mutex_);+ impl_->client.reset();+ connected_.store(false, std::memory_order_release);+ currentDb_.clear();+}++bool MongodbAdapter::testConnection(const ConnectionConfig& config,+ const std::optional<std::string>& password) {+ MongodbAdapter probe;+ probe.connect(config, password);+ probe.disconnect();+ return true;+}++void MongodbAdapter::ensureConnected() const {+ if (!connected_.load(std::memory_order_acquire) || !impl_->client)+ throw QueryError("Not connected to MongoDB");+}++// ---------------------------------------------------------------------------+// Query execution — treat query/sql as a JSON command document+// ---------------------------------------------------------------------------++QueryResult MongodbAdapter::execute(const std::string& query,+ const std::vector<QueryParameter>& /*parameters*/) {+ return executeRaw(query);+}++QueryResult MongodbAdapter::executeRaw(const std::string& sql) {+ ensureConnected();+ const auto start = std::chrono::steady_clock::now();++ std::lock_guard lock(mutex_);+ try {+ auto db = impl_->getDb(currentDb_);+ auto cmdDoc = bsoncxx::from_json(sql);+ auto result = db.run_command(cmdDoc.view());++ QueryResult qr;+ qr.queryType = QueryType::Other;+ qr.executionTime = std::chrono::steady_clock::now() - start;++ // Present the command result as a single row with one "result" column+ ColumnHeader h;+ h.name = "result";+ h.dataType = "document";+ qr.columns.push_back(std::move(h));++ std::vector<RowValue> row;+ row.push_back(RowValue::makeJson(bsoncxx::to_json(result.view())));+ qr.rows.push_back(std::move(row));+ qr.rowsAffected = 1;+ return qr;+ } catch (const mongocxx::exception& ex) {+ throw QueryError(std::string("MongoDB command failed: ") + ex.what());+ } catch (const std::exception& ex) {+ // bsoncxx::from_json throws bsoncxx::exception (a std::system_error);+ // catch via std::exception base to avoid potential macro-expansion issues.+ throw QueryError(std::string("MongoDB BSON parse error: ") + ex.what());+ }+}++// ---------------------------------------------------------------------------+// Schema inspection+// ---------------------------------------------------------------------------++std::vector<std::string> MongodbAdapter::listDatabases() {+ ensureConnected();+ std::lock_guard lock(mutex_);+ try {+ return impl_->client->list_database_names();+ } catch (const mongocxx::exception& ex) {+ throw QueryError(std::string("MongoDB listDatabases failed: ") + ex.what());+ }+}++std::vector<std::string> MongodbAdapter::listSchemas(const std::optional<std::string>& /*database*/) {+ // MongoDB has no schema concept; return a single "default" namespace+ return {"default"};+}++std::vector<TableInfo> MongodbAdapter::listTables(const std::optional<std::string>& /*schema*/) {+ ensureConnected();+ std::lock_guard lock(mutex_);+ try {+ auto db = impl_->getDb(currentDb_);+ auto names = db.list_collection_names();+ std::vector<TableInfo> out;+ out.reserve(names.size());+ for (const auto& name : names) {+ TableInfo t;+ t.name = name;+ t.schema = "default";+ t.type = TableKind::Table;+ out.push_back(std::move(t));+ }+ return out;+ } catch (const mongocxx::exception& ex) {+ throw QueryError(std::string("MongoDB listTables failed: ") + ex.what());+ }+}++std::vector<ViewInfo> MongodbAdapter::listViews(const std::optional<std::string>& /*schema*/) {+ // MongoDB views exist but require a separate listCollections filter; not+ // implemented — return empty to avoid unnecessary complexity (YAGNI).+ return {};+}++TableDescription MongodbAdapter::describeTable(const std::string& name,+ const std::optional<std::string>& schema) {+ ensureConnected();+ std::lock_guard lock(mutex_);++ TableDescription desc;+ desc.name = name;+ desc.schema = schema;++ try {+ auto db = impl_->getDb(currentDb_);+ auto coll = db[name];++ // Sample the first document to infer the schema+ auto cursor = coll.find({}, mongocxx::options::find{}.limit(1));+ int pos = 1;+ for (const auto& doc : cursor) {+ for (const auto& elem : doc) {+ ColumnInfo col;+ col.name = std::string(elem.key());+ col.dataType = bsonTypeName(elem.type());+ col.isNullable = true;+ col.ordinalPosition = pos++;+ if (col.name == "_id") {+ col.isPrimaryKey = true;+ col.isNullable = false;+ }+ desc.columns.push_back(std::move(col));+ }+ break; // only the first document+ }+ // If collection is empty or no fields found, add a placeholder _id column+ if (desc.columns.empty()) {+ ColumnInfo idCol;+ idCol.name = "_id";+ idCol.dataType = "objectId";+ idCol.isNullable = false;+ idCol.isPrimaryKey = true;+ idCol.ordinalPosition = 1;+ desc.columns.push_back(std::move(idCol));+ }+ } catch (const mongocxx::exception& ex) {+ throw QueryError(std::string("MongoDB describeTable failed: ") + ex.what());+ }+ return desc;+}++std::vector<IndexInfo> MongodbAdapter::listIndexes(const std::string& table,+ const std::optional<std::string>& /*schema*/) {+ ensureConnected();+ std::lock_guard lock(mutex_);+ std::vector<IndexInfo> out;+ try {+ auto db = impl_->getDb(currentDb_);+ auto coll = db[table];+ auto cursor = coll.list_indexes();+ for (const auto& idxDoc : cursor) {+ IndexInfo idx;+ // name field+ if (idxDoc["name"] && idxDoc["name"].type() == bsoncxx::type::k_string)+ idx.name = std::string(idxDoc["name"].get_string().value);+ // unique field+ if (idxDoc["unique"] && idxDoc["unique"].type() == bsoncxx::type::k_bool)+ idx.isUnique = idxDoc["unique"].get_bool().value;+ // key field → column names+ if (idxDoc["key"] && idxDoc["key"].type() == bsoncxx::type::k_document) {+ for (const auto& kv : idxDoc["key"].get_document().value)+ idx.columns.push_back(std::string(kv.key()));+ }+ idx.tableName = table;+ out.push_back(std::move(idx));+ }+ } catch (const mongocxx::exception& ex) {+ throw QueryError(std::string("MongoDB listIndexes failed: ") + ex.what());+ }+ return out;+}++std::vector<ForeignKeyInfo> MongodbAdapter::listForeignKeys(+ const std::string& /*table*/,+ const std::optional<std::string>& /*schema*/) {+ // MongoDB has no foreign keys+ return {};+}++std::vector<std::string> MongodbAdapter::listFunctions(const std::optional<std::string>& /*schema*/) {+ return {};+}++std::string MongodbAdapter::getFunctionSource(const std::string& /*name*/,+ const std::optional<std::string>& /*schema*/) {+ return {};+}++// ---------------------------------------------------------------------------+// Data manipulation+// ---------------------------------------------------------------------------++QueryResult MongodbAdapter::insertRow(const std::string& table,+ const std::optional<std::string>& /*schema*/,+ const std::unordered_map<std::string, RowValue>& values) {+ ensureConnected();+ const auto start = std::chrono::steady_clock::now();+ std::lock_guard lock(mutex_);++ try {+ auto db = impl_->getDb(currentDb_);+ auto coll = db[table];++ bsoncxx::builder::basic::document docBuilder;+ for (const auto& [key, val] : values)+ appendRowValueToBson(docBuilder, key, val);++ auto result = coll.insert_one(docBuilder.view());++ QueryResult qr;+ qr.queryType = QueryType::Insert;+ qr.rowsAffected = result ? 1 : 0;+ qr.executionTime = std::chrono::steady_clock::now() - start;++ ColumnHeader h;+ h.name = "insertedId";+ h.dataType = "objectId";+ qr.columns.push_back(std::move(h));+ if (result && result->inserted_id().type() == bsoncxx::type::k_oid) {+ std::vector<RowValue> row;+ row.push_back(RowValue::makeString(result->inserted_id().get_oid().value.to_string()));+ qr.rows.push_back(std::move(row));+ }+ return qr;+ } catch (const mongocxx::exception& ex) {+ throw QueryError(std::string("MongoDB insertRow failed: ") + ex.what());+ }+}++QueryResult MongodbAdapter::updateRow(const std::string& table,+ const std::optional<std::string>& /*schema*/,+ const std::unordered_map<std::string, RowValue>& set,+ const std::unordered_map<std::string, RowValue>& where) {+ ensureConnected();+ const auto start = std::chrono::steady_clock::now();+ std::lock_guard lock(mutex_);++ try {+ auto db = impl_->getDb(currentDb_);+ auto coll = db[table];++ bsoncxx::builder::basic::document filterDoc;+ for (const auto& [key, val] : where)+ appendRowValueToBson(filterDoc, key, val);++ bsoncxx::builder::basic::document setDoc;+ bsoncxx::builder::basic::document updateDoc;+ for (const auto& [key, val] : set)+ appendRowValueToBson(setDoc, key, val);+ updateDoc.append(bsoncxx::builder::basic::kvp("$set", setDoc.view()));++ auto result = coll.update_one(filterDoc.view(), updateDoc.view());++ QueryResult qr;+ qr.queryType = QueryType::Update;+ qr.rowsAffected = result ? static_cast<int>(result->modified_count()) : 0;+ qr.executionTime = std::chrono::steady_clock::now() - start;+ return qr;+ } catch (const mongocxx::exception& ex) {+ throw QueryError(std::string("MongoDB updateRow failed: ") + ex.what());+ }+}++QueryResult MongodbAdapter::deleteRow(const std::string& table,+ const std::optional<std::string>& /*schema*/,+ const std::unordered_map<std::string, RowValue>& where) {+ ensureConnected();+ const auto start = std::chrono::steady_clock::now();+ std::lock_guard lock(mutex_);++ try {+ auto db = impl_->getDb(currentDb_);+ auto coll = db[table];++ bsoncxx::builder::basic::document filterDoc;+ for (const auto& [key, val] : where)+ appendRowValueToBson(filterDoc, key, val);++ auto result = coll.delete_one(filterDoc.view());++ QueryResult qr;+ qr.queryType = QueryType::Delete;+ qr.rowsAffected = result ? static_cast<int>(result->deleted_count()) : 0;+ qr.executionTime = std::chrono::steady_clock::now() - start;+ return qr;+ } catch (const mongocxx::exception& ex) {+ throw QueryError(std::string("MongoDB deleteRow failed: ") + ex.what());+ }+}++// ---------------------------------------------------------------------------+// Transactions (MongoDB 4.0+ replica-set sessions)+// ---------------------------------------------------------------------------++void MongodbAdapter::beginTransaction() {+ // Transactions require a client session and replica set; throw a clear+ // error rather than silently ignoring — callers need to know.+ throw QueryError("MongoDB transactions require a replica-set session; "+ "use executeRaw with a JSON command to manage sessions manually");+}++void MongodbAdapter::commitTransaction() {+ throw QueryError("MongoDB transactions require a replica-set session");+}++void MongodbAdapter::rollbackTransaction() {+ throw QueryError("MongoDB transactions require a replica-set session");+}++// ---------------------------------------------------------------------------+// Pagination+// ---------------------------------------------------------------------------++QueryResult MongodbAdapter::fetchRows(const std::string& table,+ const std::optional<std::string>& /*schema*/,+ const std::optional<std::vector<std::string>>& columns,+ const std::optional<FilterExpression>& /*where*/,+ const std::optional<std::vector<QuerySortDescriptor>>& /*orderBy*/,+ int limit, int offset) {+ ensureConnected();+ const auto start = std::chrono::steady_clock::now();+ std::lock_guard lock(mutex_);++ QueryResult qr;+ qr.queryType = QueryType::Select;++ try {+ auto db = impl_->getDb(currentDb_);+ auto coll = db[table];++ // Build optional projection from requested columns+ mongocxx::options::find opts;+ if (columns && !columns->empty()) {+ bsoncxx::builder::basic::document projDoc;+ for (const auto& col : *columns)+ projDoc.append(bsoncxx::builder::basic::kvp(col, 1));+ opts.projection(projDoc.view());+ }+ opts.skip(static_cast<std::int64_t>(offset));+ opts.limit(static_cast<std::int64_t>(limit));++ auto cursor = coll.find({}, opts);++ bool headerBuilt = false;+ for (const auto& doc : cursor) {+ // Build column headers from the first document+ if (!headerBuilt) {+ for (const auto& elem : doc) {+ ColumnHeader h;+ h.name = std::string(elem.key());+ h.dataType = bsonTypeName(elem.type());+ qr.columns.push_back(std::move(h));+ }+ headerBuilt = true;+ }++ // Build row aligned to the header column order+ std::vector<RowValue> row;+ row.reserve(qr.columns.size());+ for (const auto& col : qr.columns) {+ const auto elem = doc[col.name];+ if (elem) {+ row.push_back(bsonElementToRowValue(elem));+ } else {+ row.push_back(RowValue::makeNull());+ }+ }+ qr.rows.push_back(std::move(row));+ }++ // If collection was empty, add a minimal _id column so the caller+ // gets a valid (but empty) result rather than a headerless table.+ if (!headerBuilt) {+ ColumnHeader h;+ h.name = "_id";+ h.dataType = "objectId";+ qr.columns.push_back(std::move(h));+ }+ } catch (const mongocxx::exception& ex) {+ throw QueryError(std::string("MongoDB fetchRows failed: ") + ex.what());+ }++ qr.rowsAffected = static_cast<int>(qr.rows.size());+ qr.executionTime = std::chrono::steady_clock::now() - start;+ return qr;+}++// ---------------------------------------------------------------------------+// Server info+// ---------------------------------------------------------------------------++std::string MongodbAdapter::serverVersion() {+ ensureConnected();+ std::lock_guard lock(mutex_);+ try {+ auto db = impl_->getDb(currentDb_);+ using namespace bsoncxx::builder::basic;+ auto cmd = make_document(kvp("buildInfo", 1));+ auto result = db.run_command(cmd.view());++ const auto versionElem = result.view()["version"];+ if (versionElem && versionElem.type() == bsoncxx::type::k_string)+ return "MongoDB " + std::string(versionElem.get_string().value);+ return "MongoDB";+ } catch (const mongocxx::exception& ex) {+ throw QueryError(std::string("MongoDB serverVersion failed: ") + ex.what());+ }+}++std::optional<std::string> MongodbAdapter::currentDatabase() {+ if (currentDb_.empty()) return std::nullopt;+ return currentDb_;+}++// ---------------------------------------------------------------------------+// Document-level operations for MongoCollectionView+// ---------------------------------------------------------------------------++std::vector<std::string> MongodbAdapter::findDocuments(+ const std::string& collection,+ const std::string& filterJson,+ int limit, int skip) {+ ensureConnected();+ std::lock_guard lock(mutex_);+ try {+ auto db = impl_->getDb(currentDb_);+ auto coll = db[collection];++ bsoncxx::document::value filterDoc = filterJson.empty()+ ? bsoncxx::from_json("{}")+ : bsoncxx::from_json(filterJson);++ mongocxx::options::find opts;+ opts.skip(static_cast<std::int64_t>(skip));+ opts.limit(static_cast<std::int64_t>(limit));++ auto cursor = coll.find(filterDoc.view(), opts);+ std::vector<std::string> out;+ for (const auto& doc : cursor)+ out.push_back(bsoncxx::to_json(doc));+ return out;+ } catch (const std::exception& ex) {+ throw QueryError(std::string("MongoDB findDocuments failed: ") + ex.what());+ }+}++std::string MongodbAdapter::insertDocument(const std::string& collection,+ const std::string& json) {+ ensureConnected();+ std::lock_guard lock(mutex_);+ try {+ auto db = impl_->getDb(currentDb_);+ auto coll = db[collection];+ auto docVal = bsoncxx::from_json(json);+ auto result = coll.insert_one(docVal.view());+ if (result && result->inserted_id().type() == bsoncxx::type::k_oid)+ return result->inserted_id().get_oid().value.to_string();+ return {};+ } catch (const std::exception& ex) {+ throw QueryError(std::string("MongoDB insertDocument failed: ") + ex.what());+ }+}++void MongodbAdapter::updateDocument(const std::string& collection,+ const std::string& idJson,+ const std::string& json) {+ ensureConnected();+ std::lock_guard lock(mutex_);+ try {+ auto db = impl_->getDb(currentDb_);+ auto coll = db[collection];+ auto filterDoc = bsoncxx::from_json(idJson);+ auto newDoc = bsoncxx::from_json(json);+ using namespace bsoncxx::builder::basic;+ auto updateDoc = make_document(kvp("$set", newDoc.view()));+ coll.update_one(filterDoc.view(), updateDoc.view());+ } catch (const std::exception& ex) {+ throw QueryError(std::string("MongoDB updateDocument failed: ") + ex.what());+ }+}++void MongodbAdapter::deleteDocument(const std::string& collection,+ const std::string& idJson) {+ ensureConnected();+ std::lock_guard lock(mutex_);+ try {+ auto db = impl_->getDb(currentDb_);+ auto coll = db[collection];+ auto filterDoc = bsoncxx::from_json(idJson);+ coll.delete_one(filterDoc.view());+ } catch (const std::exception& ex) {+ throw QueryError(std::string("MongoDB deleteDocument failed: ") + ex.what());+ }+}++long MongodbAdapter::countDocuments(const std::string& collection,+ const std::string& filterJson) {+ ensureConnected();+ std::lock_guard lock(mutex_);+ try {+ auto db = impl_->getDb(currentDb_);+ auto coll = db[collection];+ bsoncxx::document::value filterDoc = filterJson.empty()+ ? bsoncxx::from_json("{}")+ : bsoncxx::from_json(filterJson);+ return static_cast<long>(coll.count_documents(filterDoc.view()));+ } catch (const std::exception& ex) {+ throw QueryError(std::string("MongoDB countDocuments failed: ") + ex.what());+ }+}++} // namespace gridexdiff --git a/linux/src/Data/Adapters/MongoDB/MongodbAdapter.h b/linux/src/Data/Adapters/MongoDB/MongodbAdapter.hnew file mode 100644index 0000000..7a61015--- /dev/null+++ b/linux/src/Data/Adapters/MongoDB/MongodbAdapter.h@@ -0,0 +1,119 @@+#pragma once++#include <atomic>+#include <memory>+#include <mutex>+#include <optional>+#include <string>++#include "Core/Protocols/Database/IDatabaseAdapter.h"++// Forward-declare mongocxx types to avoid including mongocxx headers in every+// translation unit that includes this header.+namespace mongocxx {+inline namespace v_noabi {+class client;+class database;+}+}++namespace gridex {++// MongoDB adapter using the official mongo-cxx-driver (mongocxx).+// IDatabaseAdapter method mapping for the document-oriented model:+// listDatabases() → client.list_database_names()+// listSchemas() → ["default"] (MongoDB has no schema concept)+// listTables() → db.list_collection_names() (collections = "tables")+// describeTable() → sample first document, infer field names as columns+// execute() → db.run_command() with JSON command string+// executeRaw() → same+// fetchRows() → collection.find({}).skip(offset).limit(limit)+// insertRow() → collection.insert_one()+// updateRow() → collection.update_one()+// deleteRow() → collection.delete_one()+// serverVersion() → db.run_command({"buildInfo": 1}) → version field+// transactions → client session with start/commit/abort+//+// mongocxx::instance must be created exactly once per process — enforced+// via std::call_once in the constructor.+class MongodbAdapter final : public IDatabaseAdapter {+public:+ MongodbAdapter();+ ~MongodbAdapter() override;++ MongodbAdapter(const MongodbAdapter&) = delete;+ MongodbAdapter& operator=(const MongodbAdapter&) = delete;++ [[nodiscard]] DatabaseType databaseType() const noexcept override { return DatabaseType::MongoDB; }+ [[nodiscard]] bool isConnected() const noexcept override { return connected_.load(std::memory_order_acquire); }++ void connect(const ConnectionConfig& config, const std::optional<std::string>& password) override;+ void disconnect() override;+ bool testConnection(const ConnectionConfig& config, const std::optional<std::string>& password) override;++ QueryResult execute(const std::string& query, const std::vector<QueryParameter>& parameters) override;+ QueryResult executeRaw(const std::string& sql) override;++ std::vector<std::string> listDatabases() override;+ std::vector<std::string> listSchemas(const std::optional<std::string>& database) override;+ std::vector<TableInfo> listTables(const std::optional<std::string>& schema) override;+ std::vector<ViewInfo> listViews(const std::optional<std::string>& schema) override;+ TableDescription describeTable(const std::string& name,+ const std::optional<std::string>& schema) override;+ std::vector<IndexInfo> listIndexes(const std::string& table,+ const std::optional<std::string>& schema) override;+ std::vector<ForeignKeyInfo> listForeignKeys(const std::string& table,+ const std::optional<std::string>& schema) override;+ std::vector<std::string> listFunctions(const std::optional<std::string>& schema) override;+ std::string getFunctionSource(const std::string& name,+ const std::optional<std::string>& schema) override;++ QueryResult insertRow(const std::string& table, const std::optional<std::string>& schema,+ const std::unordered_map<std::string, RowValue>& values) override;+ QueryResult updateRow(const std::string& table, const std::optional<std::string>& schema,+ const std::unordered_map<std::string, RowValue>& set,+ const std::unordered_map<std::string, RowValue>& where) override;+ QueryResult deleteRow(const std::string& table, const std::optional<std::string>& schema,+ const std::unordered_map<std::string, RowValue>& where) override;++ void beginTransaction() override;+ void commitTransaction() override;+ void rollbackTransaction() override;++ QueryResult fetchRows(const std::string& table,+ const std::optional<std::string>& schema,+ const std::optional<std::vector<std::string>>& columns,+ const std::optional<FilterExpression>& where,+ const std::optional<std::vector<QuerySortDescriptor>>& orderBy,+ int limit, int offset) override;++ std::string serverVersion() override;+ std::optional<std::string> currentDatabase() override;++ // Document-level operations for MongoCollectionView+ std::vector<std::string> findDocuments(const std::string& collection,+ const std::string& filterJson,+ int limit, int skip);+ std::string insertDocument(const std::string& collection,+ const std::string& json);+ void updateDocument(const std::string& collection,+ const std::string& idJson,+ const std::string& json);+ void deleteDocument(const std::string& collection,+ const std::string& idJson);+ long countDocuments(const std::string& collection,+ const std::string& filterJson);++private:+ void ensureConnected() const;++ // Pimpl for mongocxx types — keeps mongocxx headers out of this header.+ struct Impl;+ std::unique_ptr<Impl> impl_;++ std::string currentDb_;+ std::atomic<bool> connected_{false};+ mutable std::mutex mutex_;+};++} // namespace gridexdiff --git a/linux/src/Data/Adapters/MySQL/MysqlAdapter.cpp b/linux/src/Data/Adapters/MySQL/MysqlAdapter.cppnew file mode 100644index 0000000..9115f8d--- /dev/null+++ b/linux/src/Data/Adapters/MySQL/MysqlAdapter.cpp@@ -0,0 +1,580 @@+#include "Data/Adapters/MySQL/MysqlAdapter.h"++#include <cassert>+#include <chrono>+#include <cstdio>+#include <cstring>+#include <mutex>+#include <mysql.h>+#include <sstream>+#include <stdexcept>++#include "Core/Errors/GridexError.h"++namespace gridex {++namespace {++// libmariadb / libmysqlclient requires mysql_library_init once before any thread touches it.+void ensureLibraryInit() {+ static std::once_flag once;+ std::call_once(once, []{ mysql_library_init(0, nullptr, nullptr); });+}++std::string myQuote(std::string_view ident) {+ std::string out;+ out.reserve(ident.size() + 2);+ out.push_back('`');+ for (char c : ident) {+ if (c == '`') out.push_back('`');+ out.push_back(c);+ }+ out.push_back('`');+ return out;+}++QueryType detectQueryType(const std::string& sql) {+ auto start = sql.find_first_not_of(" \t\n\r");+ if (start == std::string::npos) return QueryType::Other;+ std::string head;+ for (auto i = start; i < sql.size() && i - start < 10; ++i) {+ head.push_back(static_cast<char>(std::toupper(static_cast<unsigned char>(sql[i]))));+ }+ auto starts = [&](const char* p) { return head.rfind(p, 0) == 0; };+ if (starts("SELECT") || starts("SHOW") || starts("EXPLAIN") || starts("WITH") || starts("DESCRIBE")) return QueryType::Select;+ if (starts("INSERT")) return QueryType::Insert;+ if (starts("UPDATE")) return QueryType::Update;+ if (starts("DELETE")) return QueryType::Delete;+ if (starts("CREATE") || starts("ALTER") || starts("DROP") || starts("TRUNCATE")) return QueryType::DDL;+ return QueryType::Other;+}++std::string escapeAsSqlLiteral(MYSQL* c, const RowValue& v) {+ assert(c != nullptr && "escapeAsSqlLiteral requires a live MYSQL*");+ if (v.isNull()) return "NULL";+ if (v.isInteger()) return std::to_string(v.asInteger());+ if (v.isDouble()) return std::to_string(v.asDouble());+ if (v.isBoolean()) return v.asBoolean() ? "1" : "0";++ std::string src;+ if (v.isString()) src = v.asString();+ else if (v.isDate()) src = formatTimestampUtc(v.asDate());+ else if (v.isJson()) src = v.asJson();+ else if (v.isUuid()) src = v.asUuid();+ else src = v.description();++ std::string buf;+ buf.resize(src.size() * 2 + 1);+ const unsigned long n = mysql_real_escape_string(c, buf.data(), src.c_str(),+ static_cast<unsigned long>(src.size()));+ buf.resize(n);+ return "'" + buf + "'";+}++RowValue readCell(const char* raw, MYSQL_FIELD* field, unsigned long length) {+ if (!raw) return RowValue::makeNull();+ const std::string s(raw, length);+ switch (field->type) {+ case MYSQL_TYPE_TINY:+ case MYSQL_TYPE_SHORT:+ case MYSQL_TYPE_LONG:+ case MYSQL_TYPE_LONGLONG:+ case MYSQL_TYPE_INT24:+ try { return RowValue::makeInteger(std::stoll(s)); } catch (...) { return RowValue::makeString(s); }+ case MYSQL_TYPE_FLOAT:+ case MYSQL_TYPE_DOUBLE:+ case MYSQL_TYPE_DECIMAL:+ case MYSQL_TYPE_NEWDECIMAL:+ try { return RowValue::makeDouble(std::stod(s)); } catch (...) { return RowValue::makeString(s); }+ case MYSQL_TYPE_JSON:+ return RowValue::makeJson(s);+ default:+ return RowValue::makeString(s);+ }+}++std::string currentMyError(MYSQL* c) {+ if (!c) return "Unknown MySQL error";+ const char* m = mysql_error(c);+ return m && *m ? std::string(m) : std::string("Unknown MySQL error");+}++}++MysqlAdapter::MysqlAdapter() {+ ensureLibraryInit();+ conn_ = mysql_init(nullptr);+ if (!conn_) throw ConnectionError("mysql_init failed");+}++MysqlAdapter::~MysqlAdapter() {+ std::lock_guard lock(mutex_);+ if (conn_) { mysql_close(conn_); conn_ = nullptr; }+ connected_.store(false, std::memory_order_release);+ databaseName_.reset();+}++void MysqlAdapter::connect(const ConnectionConfig& config, const std::optional<std::string>& password) {+ std::lock_guard lock(mutex_);+ ensureLibraryInit();+ if (!conn_) conn_ = mysql_init(nullptr);+ if (!conn_) throw ConnectionError("mysql_init failed");++ const std::string host = config.host.value_or("localhost");+ const unsigned port = static_cast<unsigned>(config.port.value_or(3306));+ const std::string user = config.username.value_or("root");+ const std::string database = config.database.value_or("");+ const char* pw = password ? password->c_str() : nullptr;+ const char* dbName = database.empty() ? nullptr : database.c_str();++ // CLIENT_LONG_FLAG + CLIENT_REMEMBER_OPTIONS improve compatibility; CLIENT_INTERACTIVE+ // bumps server idle timeout. CLIENT_MULTI_STATEMENTS stays off to keep the surface safe.+ const unsigned long flags = CLIENT_LONG_FLAG | CLIENT_REMEMBER_OPTIONS | CLIENT_INTERACTIVE;+ if (!mysql_real_connect(conn_, host.c_str(), user.c_str(), pw, dbName, port, nullptr, flags)) {+ std::string msg = currentMyError(conn_);+ mysql_close(conn_);+ conn_ = mysql_init(nullptr);+ throw ConnectionError("MySQL connect failed: " + msg);+ }+ if (mysql_set_character_set(conn_, "utf8mb4") != 0) {+ // Not fatal: some older servers may lack utf8mb4. Keep connection but warn via stderr+ // so the user can see the fallback; writes of 4-byte UTF-8 may fail.+ std::fprintf(stderr, "[MysqlAdapter] utf8mb4 not available, falling back (%s)\n",+ currentMyError(conn_).c_str());+ }+ connected_.store(true, std::memory_order_release);+ if (!database.empty()) databaseName_ = database;+}++void MysqlAdapter::disconnect() {+ std::lock_guard lock(mutex_);+ if (conn_) { mysql_close(conn_); conn_ = nullptr; }+ connected_.store(false, std::memory_order_release);+ databaseName_.reset(); // H1+}++bool MysqlAdapter::testConnection(const ConnectionConfig& config, const std::optional<std::string>& password) {+ try {+ MysqlAdapter probe;+ probe.connect(config, password);+ probe.disconnect();+ return true;+ } catch (const GridexError&) {+ throw; // re-throw so caller sees typed error+ } catch (const std::exception& e) {+ throw ConnectionError(std::string("MySQL test: ") + e.what());+ }+}++void MysqlAdapter::ensureConnected() const {+ if (!connected_.load(std::memory_order_acquire) || !conn_)+ throw QueryError("Not connected to MySQL");+}++QueryResult MysqlAdapter::executeInternal(std::string sql, const std::vector<RowValue>& values) {+ ensureConnected();+ const auto start = std::chrono::steady_clock::now();++ std::lock_guard lock(mutex_);++ // Client-side parameter substitution for `?` placeholders.+ if (!values.empty()) {+ std::string out;+ out.reserve(sql.size());+ std::size_t i = 0;+ std::size_t pi = 0;+ while (i < sql.size()) {+ const char c = sql[i];+ if (c == '\'' || c == '"' || c == '`') {+ out.push_back(c);+ ++i;+ while (i < sql.size() && sql[i] != c) {+ out.push_back(sql[i]);+ if (sql[i] == '\\' && i + 1 < sql.size()) { out.push_back(sql[++i]); }+ ++i;+ }+ if (i < sql.size()) { out.push_back(sql[i]); ++i; }+ continue;+ }+ if (c == '?' && pi < values.size()) {+ out += escapeAsSqlLiteral(conn_, values[pi++]);+ ++i;+ continue;+ }+ out.push_back(c);+ ++i;+ }+ sql = std::move(out);+ }++ if (mysql_real_query(conn_, sql.c_str(), static_cast<unsigned long>(sql.size())) != 0) {+ throw QueryError("MySQL query failed: " + currentMyError(conn_));+ }++ QueryResult result;+ result.queryType = detectQueryType(sql);++ MYSQL_RES* res = mysql_store_result(conn_);+ if (res) {+ const unsigned fieldCount = mysql_num_fields(res);+ MYSQL_FIELD* fields = mysql_fetch_fields(res);+ result.columns.reserve(fieldCount);+ for (unsigned i = 0; i < fieldCount; ++i) {+ ColumnHeader h;+ h.name = fields[i].name ? fields[i].name : "";+ h.dataType = std::to_string(static_cast<int>(fields[i].type));+ h.isNullable = !(fields[i].flags & NOT_NULL_FLAG);+ if (fields[i].table) h.tableName = std::string(fields[i].table);+ result.columns.push_back(std::move(h));+ }+ while (true) {+ MYSQL_ROW r = mysql_fetch_row(res);+ if (!r) break;+ unsigned long* lens = mysql_fetch_lengths(res);+ std::vector<RowValue> row;+ row.reserve(fieldCount);+ for (unsigned c = 0; c < fieldCount; ++c) {+ if (!r[c]) { row.push_back(RowValue::makeNull()); continue; }+ row.push_back(readCell(r[c], &fields[c], lens ? lens[c] : 0));+ }+ result.rows.push_back(std::move(row));+ }+ mysql_free_result(res);+ result.rowsAffected = static_cast<int>(result.rows.size());+ } else if (mysql_field_count(conn_) == 0) {+ result.rowsAffected = static_cast<int>(mysql_affected_rows(conn_));+ } else {+ throw QueryError("MySQL mysql_store_result failed: " + currentMyError(conn_));+ }++ result.executionTime = std::chrono::steady_clock::now() - start;+ return result;+}++QueryResult MysqlAdapter::execute(const std::string& query, const std::vector<QueryParameter>& parameters) {+ std::vector<RowValue> vals;+ vals.reserve(parameters.size());+ for (const auto& p : parameters) vals.push_back(p.value);+ return executeInternal(query, vals);+}++QueryResult MysqlAdapter::executeRaw(const std::string& sql) { return executeInternal(sql, {}); }++// ---- Schema ----++std::vector<std::string> MysqlAdapter::listDatabases() {+ const auto r = executeRaw("SHOW DATABASES");+ std::vector<std::string> out;+ for (const auto& row : r.rows) if (!row.empty() && row[0].isString()) out.push_back(row[0].asString());+ return out;+}++std::vector<std::string> MysqlAdapter::listSchemas(const std::optional<std::string>& /*database*/) {+ // MySQL doesn't have schemas distinct from databases; return [currentDatabase].+ const auto cur = currentDatabase();+ if (cur) return {*cur};+ return {};+}++std::vector<TableInfo> MysqlAdapter::listTables(const std::optional<std::string>& schema) {+ const auto dbName = schema.value_or(currentDatabase().value_or(""));+ if (dbName.empty()) return {};+ std::vector<QueryParameter> params;+ params.emplace_back(RowValue::makeString(dbName));+ const auto r = execute(+ "SELECT table_name FROM information_schema.tables "+ "WHERE table_schema = ? AND table_type = 'BASE TABLE' ORDER BY table_name", params);+ std::vector<TableInfo> out;+ for (const auto& row : r.rows) {+ if (row.empty() || !row[0].isString()) continue;+ TableInfo t;+ t.name = row[0].asString();+ t.schema = dbName;+ t.type = TableKind::Table;+ out.push_back(std::move(t));+ }+ return out;+}++std::vector<ViewInfo> MysqlAdapter::listViews(const std::optional<std::string>& schema) {+ const auto dbName = schema.value_or(currentDatabase().value_or(""));+ if (dbName.empty()) return {};+ std::vector<QueryParameter> params;+ params.emplace_back(RowValue::makeString(dbName));+ const auto r = execute(+ "SELECT table_name, view_definition FROM information_schema.views "+ "WHERE table_schema = ? ORDER BY table_name", params);+ std::vector<ViewInfo> out;+ for (const auto& row : r.rows) {+ if (row.empty() || !row[0].isString()) continue;+ ViewInfo v;+ v.name = row[0].asString();+ v.schema = dbName;+ if (row.size() > 1) v.definition = row[1].tryStringValue();+ out.push_back(std::move(v));+ }+ return out;+}++TableDescription MysqlAdapter::describeTable(const std::string& name, const std::optional<std::string>& schema) {+ TableDescription desc;+ desc.name = name;+ desc.schema = schema;+ const auto dbName = schema.value_or(currentDatabase().value_or(""));++ std::vector<QueryParameter> params;+ params.emplace_back(RowValue::makeString(dbName));+ params.emplace_back(RowValue::makeString(name));+ const auto r = execute(+ "SELECT column_name, column_type, is_nullable, column_default, ordinal_position, column_key, extra "+ "FROM information_schema.columns WHERE table_schema = ? AND table_name = ? ORDER BY ordinal_position",+ params);+ for (const auto& row : r.rows) {+ if (row.size() < 7) continue;+ ColumnInfo c;+ c.name = row[0].tryStringValue().value_or("");+ c.dataType = row[1].tryStringValue().value_or("");+ c.isNullable = row[2].tryStringValue().value_or("YES") == "YES";+ if (!row[3].isNull()) c.defaultValue = row[3].tryStringValue();+ c.ordinalPosition = static_cast<int>(row[4].tryIntValue().value_or(0));+ c.isPrimaryKey = row[5].tryStringValue().value_or("") == "PRI";+ c.isAutoIncrement = row[6].tryStringValue().value_or("").find("auto_increment") != std::string::npos;+ desc.columns.push_back(std::move(c));+ }++ try { desc.foreignKeys = listForeignKeys(name, schema); } catch (...) {}+ try { desc.estimatedRowCount = tableRowCount(name, schema); } catch (...) {}+ return desc;+}++std::vector<IndexInfo> MysqlAdapter::listIndexes(const std::string& table, const std::optional<std::string>& schema) {+ const auto dbName = schema.value_or(currentDatabase().value_or(""));+ std::vector<QueryParameter> params;+ params.emplace_back(RowValue::makeString(dbName));+ params.emplace_back(RowValue::makeString(table));+ const auto r = execute(+ "SELECT index_name, non_unique, GROUP_CONCAT(column_name ORDER BY seq_in_index) "+ "FROM information_schema.statistics "+ "WHERE table_schema = ? AND table_name = ? "+ "GROUP BY index_name, non_unique ORDER BY index_name", params);+ std::vector<IndexInfo> out;+ for (const auto& row : r.rows) {+ if (row.size() < 3) continue;+ IndexInfo idx;+ idx.name = row[0].tryStringValue().value_or("");+ idx.isUnique = row[1].tryStringValue().value_or("1") == "0";+ const auto colsJoined = row[2].tryStringValue().value_or("");+ std::string cur;+ for (char c : colsJoined) {+ if (c == ',') { if (!cur.empty()) { idx.columns.push_back(std::move(cur)); cur.clear(); } }+ else cur.push_back(c);+ }+ if (!cur.empty()) idx.columns.push_back(std::move(cur));+ idx.tableName = table;+ out.push_back(std::move(idx));+ }+ return out;+}++std::vector<ForeignKeyInfo> MysqlAdapter::listForeignKeys(const std::string& table, const std::optional<std::string>& schema) {+ const auto dbName = schema.value_or(currentDatabase().value_or(""));+ std::vector<QueryParameter> params;+ params.emplace_back(RowValue::makeString(dbName));+ params.emplace_back(RowValue::makeString(table));+ const auto r = execute(+ "SELECT constraint_name, column_name, referenced_table_name, referenced_column_name "+ "FROM information_schema.key_column_usage "+ "WHERE table_schema = ? AND table_name = ? AND referenced_table_name IS NOT NULL", params);+ std::vector<ForeignKeyInfo> out;+ for (const auto& row : r.rows) {+ if (row.size() < 4) continue;+ ForeignKeyInfo fk;+ fk.name = row[0].tryStringValue();+ fk.columns.push_back(row[1].tryStringValue().value_or(""));+ fk.referencedTable = row[2].tryStringValue().value_or("");+ fk.referencedColumns.push_back(row[3].tryStringValue().value_or(""));+ out.push_back(std::move(fk));+ }+ return out;+}++std::vector<std::string> MysqlAdapter::listFunctions(const std::optional<std::string>& schema) {+ const auto dbName = schema.value_or(currentDatabase().value_or(""));+ std::vector<QueryParameter> params;+ params.emplace_back(RowValue::makeString(dbName));+ const auto r = execute(+ "SELECT routine_name FROM information_schema.routines "+ "WHERE routine_schema = ? AND routine_type = 'FUNCTION' ORDER BY routine_name", params);+ std::vector<std::string> out;+ for (const auto& row : r.rows) if (!row.empty() && row[0].isString()) out.push_back(row[0].asString());+ return out;+}++std::string MysqlAdapter::getFunctionSource(const std::string& name, const std::optional<std::string>& schema) {+ const auto dbName = schema.value_or(currentDatabase().value_or(""));+ std::vector<QueryParameter> params;+ params.emplace_back(RowValue::makeString(dbName));+ params.emplace_back(RowValue::makeString(name));+ const auto r = execute(+ "SELECT routine_definition FROM information_schema.routines "+ "WHERE routine_schema = ? AND routine_name = ? LIMIT 1", params);+ if (r.rows.empty() || r.rows[0].empty()) return {};+ return r.rows[0][0].tryStringValue().value_or("");+}++// ---- DML ----++QueryResult MysqlAdapter::insertRow(const std::string& table, const std::optional<std::string>& /*schema*/,+ const std::unordered_map<std::string, RowValue>& values) {+ if (values.empty()) throw QueryError("insertRow: empty values");+ std::string cols, placeholders;+ std::vector<QueryParameter> params;+ bool first = true;+ for (const auto& [k, v] : values) {+ if (!first) { cols += ", "; placeholders += ", "; }+ cols += myQuote(k);+ placeholders += "?";+ params.emplace_back(v);+ first = false;+ }+ return execute("INSERT INTO " + myQuote(table) + " (" + cols + ") VALUES (" + placeholders + ")", params);+}++QueryResult MysqlAdapter::updateRow(const std::string& table, const std::optional<std::string>& /*schema*/,+ const std::unordered_map<std::string, RowValue>& set,+ const std::unordered_map<std::string, RowValue>& where) {+ if (set.empty() || where.empty()) throw QueryError("updateRow: empty set/where");+ std::string setClause, whereClause;+ std::vector<QueryParameter> params;+ bool first = true;+ for (const auto& [k, v] : set) {+ if (!first) setClause += ", ";+ setClause += myQuote(k) + " = ?";+ params.emplace_back(v);+ first = false;+ }+ first = true;+ for (const auto& [k, v] : where) {+ if (!first) whereClause += " AND ";+ whereClause += myQuote(k) + " = ?";+ params.emplace_back(v);+ first = false;+ }+ return execute("UPDATE " + myQuote(table) + " SET " + setClause + " WHERE " + whereClause, params);+}++QueryResult MysqlAdapter::deleteRow(const std::string& table, const std::optional<std::string>& /*schema*/,+ const std::unordered_map<std::string, RowValue>& where) {+ if (where.empty()) throw QueryError("deleteRow: empty where");+ std::string whereClause;+ std::vector<QueryParameter> params;+ bool first = true;+ for (const auto& [k, v] : where) {+ if (!first) whereClause += " AND ";+ whereClause += myQuote(k) + " = ?";+ params.emplace_back(v);+ first = false;+ }+ return execute("DELETE FROM " + myQuote(table) + " WHERE " + whereClause, params);+}++void MysqlAdapter::beginTransaction() { (void)executeRaw("START TRANSACTION"); }+void MysqlAdapter::commitTransaction() { (void)executeRaw("COMMIT"); }+void MysqlAdapter::rollbackTransaction() { (void)executeRaw("ROLLBACK"); }++QueryResult MysqlAdapter::fetchRows(const std::string& table,+ const std::optional<std::string>& /*schema*/,+ const std::optional<std::vector<std::string>>& columns,+ const std::optional<FilterExpression>& where,+ const std::optional<std::vector<QuerySortDescriptor>>& orderBy,+ int limit, int offset) {+ std::string colList = "*";+ if (columns && !columns->empty()) {+ colList.clear();+ for (std::size_t i = 0; i < columns->size(); ++i) {+ if (i > 0) colList += ", ";+ colList += myQuote((*columns)[i]);+ }+ }+ std::string sql = "SELECT " + colList + " FROM " + myQuote(table);+ if (where && !where->conditions.empty()) sql += " WHERE " + where->toSQL(SQLDialect::MySQL);+ if (orderBy && !orderBy->empty()) {+ sql += " ORDER BY ";+ for (std::size_t i = 0; i < orderBy->size(); ++i) {+ if (i > 0) sql += ", ";+ sql += (*orderBy)[i].toSQL(SQLDialect::MySQL);+ }+ }+ sql += " LIMIT " + std::to_string(limit) + " OFFSET " + std::to_string(offset);+ return executeRaw(sql);+}++std::string MysqlAdapter::serverVersion() {+ const auto r = executeRaw("SELECT VERSION()");+ if (r.rows.empty() || r.rows[0].empty()) return "MySQL";+ return "MySQL " + r.rows[0][0].tryStringValue().value_or("");+}++std::optional<std::string> MysqlAdapter::currentDatabase() {+ if (databaseName_) return databaseName_;+ const auto r = executeRaw("SELECT DATABASE()");+ if (r.rows.empty() || r.rows[0].empty() || r.rows[0][0].isNull()) return std::nullopt;+ return r.rows[0][0].tryStringValue();+}++// ---- ISchemaInspectable ----++SchemaSnapshot MysqlAdapter::fullSchemaSnapshot(const std::optional<std::string>& /*database*/) {+ SchemaSnapshot snap;+ snap.databaseName = currentDatabase().value_or("");+ snap.databaseType = DatabaseType::MySQL;+ snap.capturedAt = std::chrono::system_clock::now();+ SchemaInfo si;+ si.name = snap.databaseName;+ for (const auto& t : listTables(snap.databaseName)) {+ si.tables.push_back(describeTable(t.name, snap.databaseName));+ }+ si.views = listViews(snap.databaseName);+ snap.schemas.push_back(std::move(si));+ return snap;+}++std::vector<ColumnStatistics> MysqlAdapter::columnStatistics(const std::string&,+ const std::optional<std::string>&,+ int) { return {}; }++int MysqlAdapter::tableRowCount(const std::string& table, const std::optional<std::string>& /*schema*/) {+ const auto r = executeRaw("SELECT COUNT(*) FROM " + myQuote(table));+ if (r.rows.empty() || r.rows[0].empty()) return 0;+ return static_cast<int>(r.rows[0][0].tryIntValue().value_or(0));+}++std::optional<std::int64_t> MysqlAdapter::tableSizeBytes(const std::string& table, const std::optional<std::string>& schema) {+ const auto dbName = schema.value_or(currentDatabase().value_or(""));+ std::vector<QueryParameter> params;+ params.emplace_back(RowValue::makeString(dbName));+ params.emplace_back(RowValue::makeString(table));+ const auto r = execute(+ "SELECT data_length + index_length FROM information_schema.tables "+ "WHERE table_schema = ? AND table_name = ? LIMIT 1", params);+ if (r.rows.empty() || r.rows[0].empty()) return std::nullopt;+ return r.rows[0][0].tryIntValue();+}++std::vector<QueryStatisticsEntry> MysqlAdapter::queryStatistics() { return {}; }++std::vector<std::string> MysqlAdapter::primaryKeyColumns(const std::string& table, const std::optional<std::string>& schema) {+ const auto dbName = schema.value_or(currentDatabase().value_or(""));+ std::vector<QueryParameter> params;+ params.emplace_back(RowValue::makeString(dbName));+ params.emplace_back(RowValue::makeString(table));+ const auto r = execute(+ "SELECT column_name FROM information_schema.key_column_usage "+ "WHERE table_schema = ? AND table_name = ? AND constraint_name = 'PRIMARY' "+ "ORDER BY ordinal_position", params);+ std::vector<std::string> out;+ for (const auto& row : r.rows) if (!row.empty() && row[0].isString()) out.push_back(row[0].asString());+ return out;+}++}diff --git a/linux/src/Data/Adapters/MySQL/MysqlAdapter.h b/linux/src/Data/Adapters/MySQL/MysqlAdapter.hnew file mode 100644index 0000000..3dc6a4c--- /dev/null+++ b/linux/src/Data/Adapters/MySQL/MysqlAdapter.h@@ -0,0 +1,94 @@+#pragma once++#include <atomic>+#include <mutex>+#include <optional>+#include <string>++#include "Core/Protocols/Database/IDatabaseAdapter.h"+#include "Core/Protocols/Database/ISchemaInspectable.h"++// Opaque MYSQL handle; include <mysql.h> in the .cpp only.+typedef struct st_mysql MYSQL;++namespace gridex {++// MySQL adapter using libmariadb (MariaDB Connector/C, protocol-compatible with MySQL 5.7/8.x).+class MysqlAdapter final : public IDatabaseAdapter, public ISchemaInspectable {+public:+ MysqlAdapter();+ ~MysqlAdapter() override;++ MysqlAdapter(const MysqlAdapter&) = delete;+ MysqlAdapter& operator=(const MysqlAdapter&) = delete;++ [[nodiscard]] DatabaseType databaseType() const noexcept override { return DatabaseType::MySQL; }+ [[nodiscard]] bool isConnected() const noexcept override { return connected_.load(std::memory_order_acquire); }++ void connect(const ConnectionConfig& config, const std::optional<std::string>& password) override;+ void disconnect() override;+ bool testConnection(const ConnectionConfig& config, const std::optional<std::string>& password) override;++ QueryResult execute(const std::string& query, const std::vector<QueryParameter>& parameters) override;+ QueryResult executeRaw(const std::string& sql) override;++ std::vector<std::string> listDatabases() override;+ std::vector<std::string> listSchemas(const std::optional<std::string>& database) override;+ std::vector<TableInfo> listTables(const std::optional<std::string>& schema) override;+ std::vector<ViewInfo> listViews(const std::optional<std::string>& schema) override;+ TableDescription describeTable(const std::string& name,+ const std::optional<std::string>& schema) override;+ std::vector<IndexInfo> listIndexes(const std::string& table,+ const std::optional<std::string>& schema) override;+ std::vector<ForeignKeyInfo> listForeignKeys(const std::string& table,+ const std::optional<std::string>& schema) override;+ std::vector<std::string> listFunctions(const std::optional<std::string>& schema) override;+ std::string getFunctionSource(const std::string& name,+ const std::optional<std::string>& schema) override;++ QueryResult insertRow(const std::string& table, const std::optional<std::string>& schema,+ const std::unordered_map<std::string, RowValue>& values) override;+ QueryResult updateRow(const std::string& table, const std::optional<std::string>& schema,+ const std::unordered_map<std::string, RowValue>& set,+ const std::unordered_map<std::string, RowValue>& where) override;+ QueryResult deleteRow(const std::string& table, const std::optional<std::string>& schema,+ const std::unordered_map<std::string, RowValue>& where) override;++ void beginTransaction() override;+ void commitTransaction() override;+ void rollbackTransaction() override;++ QueryResult fetchRows(const std::string& table,+ const std::optional<std::string>& schema,+ const std::optional<std::vector<std::string>>& columns,+ const std::optional<FilterExpression>& where,+ const std::optional<std::vector<QuerySortDescriptor>>& orderBy,+ int limit, int offset) override;++ std::string serverVersion() override;+ std::optional<std::string> currentDatabase() override;++ // ISchemaInspectable+ SchemaSnapshot fullSchemaSnapshot(const std::optional<std::string>& database) override;+ std::vector<ColumnStatistics> columnStatistics(const std::string& table,+ const std::optional<std::string>& schema,+ int sampleSize) override;+ int tableRowCount(const std::string& table,+ const std::optional<std::string>& schema) override;+ std::optional<std::int64_t> tableSizeBytes(const std::string& table,+ const std::optional<std::string>& schema) override;+ std::vector<QueryStatisticsEntry> queryStatistics() override;+ std::vector<std::string> primaryKeyColumns(const std::string& table,+ const std::optional<std::string>& schema) override;++private:+ QueryResult executeInternal(std::string sql, const std::vector<RowValue>& values);+ void ensureConnected() const;++ MYSQL* conn_ = nullptr;+ std::atomic<bool> connected_{false};+ std::optional<std::string> databaseName_;+ mutable std::mutex mutex_;+};++}diff --git a/linux/src/Data/Adapters/PostgreSQL/PostgresAdapter.cpp b/linux/src/Data/Adapters/PostgreSQL/PostgresAdapter.cppnew file mode 100644index 0000000..f493eb5--- /dev/null+++ b/linux/src/Data/Adapters/PostgreSQL/PostgresAdapter.cpp@@ -0,0 +1,601 @@+#include "Data/Adapters/PostgreSQL/PostgresAdapter.h"++#include <chrono>+#include <cstdlib>+#include <cstring>+#include <libpq-fe.h>+#include <sstream>+#include <stdexcept>++#include "Core/Errors/GridexError.h"++namespace gridex {++namespace {++std::string pgQuote(std::string_view ident) {+ std::string out;+ out.reserve(ident.size() + 2);+ out.push_back('"');+ for (char c : ident) {+ if (c == '"') out.push_back('"');+ out.push_back(c);+ }+ out.push_back('"');+ return out;+}++QueryType detectQueryType(const std::string& sql) {+ auto start = sql.find_first_not_of(" \t\n\r");+ if (start == std::string::npos) return QueryType::Other;+ std::string head;+ for (auto i = start; i < sql.size() && i - start < 10; ++i) {+ head.push_back(static_cast<char>(std::toupper(static_cast<unsigned char>(sql[i]))));+ }+ auto starts = [&](const char* p) { return head.rfind(p, 0) == 0; };+ if (starts("SELECT") || starts("WITH") || starts("EXPLAIN") || starts("SHOW")) return QueryType::Select;+ if (starts("INSERT")) return QueryType::Insert;+ if (starts("UPDATE")) return QueryType::Update;+ if (starts("DELETE")) return QueryType::Delete;+ if (starts("CREATE") || starts("ALTER") || starts("DROP") || starts("TRUNCATE")) return QueryType::DDL;+ return QueryType::Other;+}++std::string serializeForParam(const RowValue& v) {+ if (v.isString()) return v.asString();+ if (v.isInteger()) return std::to_string(v.asInteger());+ if (v.isDouble()) return std::to_string(v.asDouble());+ if (v.isBoolean()) return v.asBoolean() ? "t" : "f";+ if (v.isDate()) return formatTimestampUtc(v.asDate());+ if (v.isJson()) return v.asJson();+ if (v.isUuid()) return v.asUuid();+ return v.description();+}++std::string currentPgError(PGconn* c) {+ const char* m = c ? PQerrorMessage(c) : nullptr;+ if (!m || !*m) return "Unknown libpq error";+ // Strip trailing newline commonly present in PQerrorMessage+ std::string out(m);+ while (!out.empty() && (out.back() == '\n' || out.back() == '\r')) out.pop_back();+ return out;+}++Bytes decodePgByteaHex(std::string_view s) {+ Bytes out;+ // libpq text format: bytea values are returned as \x<hex> or the escape form.+ if (s.size() >= 2 && s[0] == '\\' && (s[1] == 'x' || s[1] == 'X')) {+ const auto hex = s.substr(2);+ out.reserve(hex.size() / 2);+ auto hexVal = [](char c) -> int {+ if (c >= '0' && c <= '9') return c - '0';+ if (c >= 'a' && c <= 'f') return c - 'a' + 10;+ if (c >= 'A' && c <= 'F') return c - 'A' + 10;+ return -1;+ };+ for (std::size_t i = 0; i + 1 < hex.size(); i += 2) {+ const int hi = hexVal(hex[i]);+ const int lo = hexVal(hex[i + 1]);+ if (hi < 0 || lo < 0) { out.clear(); return out; }+ out.push_back(static_cast<std::uint8_t>((hi << 4) | lo));+ }+ return out;+ }+ // Escape format fallback: treat as raw bytes.+ out.assign(reinterpret_cast<const std::uint8_t*>(s.data()),+ reinterpret_cast<const std::uint8_t*>(s.data()) + s.size());+ return out;+}++RowValue readCell(PGresult* r, int row, int col) {+ if (PQgetisnull(r, row, col)) return RowValue::makeNull();+ const Oid oid = PQftype(r, col);+ const char* raw = PQgetvalue(r, row, col);+ const int len = PQgetlength(r, row, col);+ // Build a length-aware string so embedded NULs survive.+ std::string s(raw, static_cast<std::size_t>(len > 0 ? len : 0));+ switch (oid) {+ case 16: // bool+ return RowValue::makeBoolean(s == "t" || s == "true" || s == "1");+ case 20: // int8+ case 21: // int2+ case 23: // int4+ try { return RowValue::makeInteger(std::stoll(s)); }+ catch (...) { return RowValue::makeString(s); }+ case 700: // float4+ case 701: // float8+ case 1700: // numeric (lossy via stod — acceptable for Phase 2; Phase 4+ may add decimal type)+ case 790: // money — stored as formatted string; try double+ try { return RowValue::makeDouble(std::stod(s)); }+ catch (...) { return RowValue::makeString(s); }+ case 17: // bytea+ return RowValue::makeData(decodePgByteaHex(s));+ case 114: // json+ case 3802: // jsonb+ return RowValue::makeJson(s);+ case 2950: // uuid+ return RowValue::makeUuid(s);+ case 1082: // date+ case 1114: // timestamp without tz+ case 1184: // timestamp with tz+ // Keep as string for now; the format differs per column and needs+ // dialect-aware parsing. Phase 4+ introduces proper date parsing.+ return RowValue::makeString(s);+ default:+ return RowValue::makeString(s);+ }+}++}++PostgresAdapter::PostgresAdapter() = default;++PostgresAdapter::~PostgresAdapter() {+ std::lock_guard lock(mutex_);+ if (conn_) { PQfinish(conn_); conn_ = nullptr; }+ connected_.store(false, std::memory_order_release);+ databaseName_.reset();+}++void PostgresAdapter::connect(const ConnectionConfig& config, const std::optional<std::string>& password) {+ std::lock_guard lock(mutex_);+ if (conn_) { PQfinish(conn_); conn_ = nullptr; }++ const std::string host = config.host.value_or("localhost");+ const int port = config.port.value_or(5432);+ const std::string user = config.username.value_or("postgres");+ const std::string database = config.database.value_or(user);++ std::vector<const char*> keys{"host", "port", "user", "dbname", "application_name", "sslmode"};+ const std::string portStr = std::to_string(port);+ const std::string sslmode = config.sslEnabled ? "prefer" : "disable";+ std::vector<std::string> buf{host, portStr, user, database, "gridex", sslmode};+ if (password) {+ keys.push_back("password");+ buf.push_back(*password);+ }+ keys.push_back(nullptr);++ std::vector<const char*> vals;+ vals.reserve(buf.size() + 1);+ for (const auto& s : buf) vals.push_back(s.c_str());+ vals.push_back(nullptr);++ conn_ = PQconnectdbParams(keys.data(), vals.data(), /*expand_dbname=*/0);+ if (!conn_ || PQstatus(conn_) != CONNECTION_OK) {+ std::string msg = currentPgError(conn_);+ if (conn_) { PQfinish(conn_); conn_ = nullptr; }+ throw ConnectionError("Postgres connect failed: " + msg);+ }++ connected_.store(true, std::memory_order_release);+ databaseName_ = database;+}++void PostgresAdapter::disconnect() {+ std::lock_guard lock(mutex_);+ if (conn_) { PQfinish(conn_); conn_ = nullptr; }+ connected_.store(false, std::memory_order_release);+ databaseName_.reset(); // H1: avoid stale identity after reconnect to a different DB+}++bool PostgresAdapter::testConnection(const ConnectionConfig& config, const std::optional<std::string>& password) {+ PostgresAdapter probe;+ probe.connect(config, password);+ probe.disconnect();+ return true;+}++void PostgresAdapter::ensureConnected() const {+ if (!connected_.load(std::memory_order_acquire) || !conn_)+ throw QueryError("Not connected to PostgreSQL");+}++QueryResult PostgresAdapter::executeInternal(const std::string& sql, const std::vector<RowValue>& values) {+ ensureConnected();+ const auto start = std::chrono::steady_clock::now();++ std::lock_guard lock(mutex_);++ // Pre-serialize param values to keep c_str() pointers alive across PQexecParams.+ std::vector<std::string> buf;+ buf.reserve(values.size());+ std::vector<const char*> ptrs;+ ptrs.reserve(values.size());+ for (const auto& v : values) {+ if (v.isNull()) { buf.emplace_back(); ptrs.push_back(nullptr); }+ else { buf.push_back(serializeForParam(v)); ptrs.push_back(buf.back().c_str()); }+ }++ const char* const* paramValues = values.empty() ? nullptr : ptrs.data();+ PGresult* res = PQexecParams(conn_, sql.c_str(),+ static_cast<int>(values.size()),+ /*paramTypes*/ nullptr,+ paramValues,+ /*paramLengths*/ nullptr,+ /*paramFormats*/ nullptr,+ /*resultFormat text*/ 0);++ // RAII: guarantee PQclear even if subsequent code throws.+ struct PgResultGuard {+ PGresult* p;+ ~PgResultGuard() { if (p) PQclear(p); }+ } guard{res};++ const auto status = res ? PQresultStatus(res) : PGRES_FATAL_ERROR;+ if (status == PGRES_BAD_RESPONSE || status == PGRES_FATAL_ERROR) {+ throw QueryError("Postgres query failed: " + currentPgError(conn_));+ }++ QueryResult result;+ result.queryType = detectQueryType(sql);++ if (status == PGRES_TUPLES_OK) {+ const int rows = PQntuples(res);+ const int cols = PQnfields(res);+ result.columns.reserve(static_cast<std::size_t>(cols));+ for (int c = 0; c < cols; ++c) {+ ColumnHeader h;+ h.name = PQfname(res, c);+ h.dataType = std::to_string(PQftype(res, c));+ result.columns.push_back(std::move(h));+ }+ result.rows.reserve(static_cast<std::size_t>(rows));+ for (int r = 0; r < rows; ++r) {+ std::vector<RowValue> row;+ row.reserve(static_cast<std::size_t>(cols));+ for (int c = 0; c < cols; ++c) row.push_back(readCell(res, r, c));+ result.rows.push_back(std::move(row));+ }+ result.rowsAffected = rows;+ } else if (status == PGRES_COMMAND_OK) {+ const char* tag = PQcmdTuples(res);+ result.rowsAffected = tag && *tag ? std::atoi(tag) : 0;+ }++ result.executionTime = std::chrono::steady_clock::now() - start;+ return result;+}++QueryResult PostgresAdapter::execute(const std::string& query, const std::vector<QueryParameter>& parameters) {+ std::vector<RowValue> vals;+ vals.reserve(parameters.size());+ for (const auto& p : parameters) vals.push_back(p.value);+ return executeInternal(query, vals);+}++QueryResult PostgresAdapter::executeRaw(const std::string& sql) {+ return executeInternal(sql, {});+}++std::string PostgresAdapter::qualified(const std::string& table, const std::optional<std::string>& schema) const {+ if (schema) return pgQuote(*schema) + "." + pgQuote(table);+ return pgQuote(table);+}++// ---- Schema inspection ----++std::vector<std::string> PostgresAdapter::listDatabases() {+ const auto r = executeRaw("SELECT datname FROM pg_database WHERE datistemplate = false ORDER BY datname");+ std::vector<std::string> out;+ out.reserve(r.rows.size());+ for (const auto& row : r.rows) {+ if (!row.empty() && row[0].isString()) out.push_back(row[0].asString());+ }+ return out;+}++std::vector<std::string> PostgresAdapter::listSchemas(const std::optional<std::string>& /*database*/) {+ const auto r = executeRaw(+ "SELECT schema_name FROM information_schema.schemata "+ "WHERE schema_name NOT IN ('pg_catalog','information_schema','pg_toast') "+ "AND schema_name NOT LIKE 'pg_temp_%' ORDER BY schema_name");+ std::vector<std::string> out;+ out.reserve(r.rows.size());+ for (const auto& row : r.rows) if (!row.empty() && row[0].isString()) out.push_back(row[0].asString());+ return out;+}++std::vector<TableInfo> PostgresAdapter::listTables(const std::optional<std::string>& schema) {+ const std::string s = schema.value_or("public");+ std::vector<QueryParameter> params;+ params.emplace_back(RowValue::makeString(s));+ const auto r = execute(+ "SELECT table_name FROM information_schema.tables "+ "WHERE table_schema = $1 AND table_type = 'BASE TABLE' "+ "ORDER BY table_name", params);+ std::vector<TableInfo> out;+ out.reserve(r.rows.size());+ for (const auto& row : r.rows) {+ if (row.empty() || !row[0].isString()) continue;+ TableInfo t;+ t.name = row[0].asString();+ t.schema = s;+ t.type = TableKind::Table;+ out.push_back(std::move(t));+ }+ return out;+}++std::vector<ViewInfo> PostgresAdapter::listViews(const std::optional<std::string>& schema) {+ const std::string s = schema.value_or("public");+ std::vector<QueryParameter> params;+ params.emplace_back(RowValue::makeString(s));+ const auto r = execute(+ "SELECT table_name, view_definition FROM information_schema.views "+ "WHERE table_schema = $1 ORDER BY table_name", params);+ std::vector<ViewInfo> out;+ for (const auto& row : r.rows) {+ if (row.empty() || !row[0].isString()) continue;+ ViewInfo v;+ v.name = row[0].asString();+ v.schema = s;+ if (row.size() > 1) v.definition = row[1].tryStringValue();+ out.push_back(std::move(v));+ }+ return out;+}++TableDescription PostgresAdapter::describeTable(const std::string& name, const std::optional<std::string>& schema) {+ TableDescription desc;+ desc.name = name;+ desc.schema = schema;++ std::vector<QueryParameter> params;+ params.emplace_back(RowValue::makeString(schema.value_or("public")));+ params.emplace_back(RowValue::makeString(name));+ const auto r = execute(+ "SELECT column_name, data_type, is_nullable, column_default, ordinal_position "+ "FROM information_schema.columns "+ "WHERE table_schema = $1 AND table_name = $2 "+ "ORDER BY ordinal_position", params);++ const auto pks = primaryKeyColumns(name, schema);+ for (const auto& row : r.rows) {+ if (row.size() < 5) continue;+ ColumnInfo c;+ c.name = row[0].tryStringValue().value_or("");+ c.dataType = row[1].tryStringValue().value_or("");+ c.isNullable = row[2].tryStringValue().value_or("YES") == "YES";+ if (!row[3].isNull()) c.defaultValue = row[3].tryStringValue();+ c.ordinalPosition = static_cast<int>(row[4].tryIntValue().value_or(0));+ for (const auto& pk : pks) if (pk == c.name) c.isPrimaryKey = true;+ desc.columns.push_back(std::move(c));+ }++ try { desc.foreignKeys = listForeignKeys(name, schema); } catch (...) {}+ try { desc.indexes = listIndexes(name, schema); } catch (...) {}+ try { desc.estimatedRowCount = tableRowCount(name, schema); } catch (...) {}+ return desc;+}++std::vector<IndexInfo> PostgresAdapter::listIndexes(const std::string& table, const std::optional<std::string>& schema) {+ std::vector<QueryParameter> params;+ params.emplace_back(RowValue::makeString(schema.value_or("public")));+ params.emplace_back(RowValue::makeString(table));+ const auto r = execute(+ "SELECT i.relname AS idx_name, ix.indisunique, "+ "pg_catalog.pg_get_indexdef(ix.indexrelid) "+ "FROM pg_index ix "+ "JOIN pg_class i ON i.oid = ix.indexrelid "+ "JOIN pg_class t ON t.oid = ix.indrelid "+ "JOIN pg_namespace n ON n.oid = t.relnamespace "+ "WHERE n.nspname = $1 AND t.relname = $2 ORDER BY i.relname", params);+ std::vector<IndexInfo> out;+ for (const auto& row : r.rows) {+ if (row.size() < 3) continue;+ IndexInfo idx;+ idx.name = row[0].tryStringValue().value_or("");+ idx.isUnique = row[1].tryStringValue().value_or("f") == "t";+ idx.tableName = table;+ out.push_back(std::move(idx));+ }+ return out;+}++std::vector<ForeignKeyInfo> PostgresAdapter::listForeignKeys(const std::string& table, const std::optional<std::string>& schema) {+ std::vector<QueryParameter> params;+ params.emplace_back(RowValue::makeString(schema.value_or("public")));+ params.emplace_back(RowValue::makeString(table));+ const auto r = execute(+ "SELECT kcu.constraint_name, kcu.column_name, ccu.table_name, ccu.column_name "+ "FROM information_schema.table_constraints tc "+ "JOIN information_schema.key_column_usage kcu ON tc.constraint_name = kcu.constraint_name "+ "JOIN information_schema.constraint_column_usage ccu ON tc.constraint_name = ccu.constraint_name "+ "WHERE tc.table_schema = $1 AND tc.table_name = $2 AND tc.constraint_type = 'FOREIGN KEY'", params);+ std::vector<ForeignKeyInfo> out;+ for (const auto& row : r.rows) {+ if (row.size() < 4) continue;+ ForeignKeyInfo fk;+ fk.name = row[0].tryStringValue();+ fk.columns.push_back(row[1].tryStringValue().value_or(""));+ fk.referencedTable = row[2].tryStringValue().value_or("");+ fk.referencedColumns.push_back(row[3].tryStringValue().value_or(""));+ out.push_back(std::move(fk));+ }+ return out;+}++std::vector<std::string> PostgresAdapter::listFunctions(const std::optional<std::string>& schema) {+ std::vector<QueryParameter> params;+ params.emplace_back(RowValue::makeString(schema.value_or("public")));+ const auto r = execute(+ "SELECT routine_name FROM information_schema.routines "+ "WHERE specific_schema = $1 AND routine_type = 'FUNCTION' "+ "ORDER BY routine_name", params);+ std::vector<std::string> out;+ for (const auto& row : r.rows) if (!row.empty() && row[0].isString()) out.push_back(row[0].asString());+ return out;+}++std::string PostgresAdapter::getFunctionSource(const std::string& name, const std::optional<std::string>& schema) {+ std::vector<QueryParameter> params;+ params.emplace_back(RowValue::makeString(schema.value_or("public")));+ params.emplace_back(RowValue::makeString(name));+ const auto r = execute(+ "SELECT pg_get_functiondef(p.oid) "+ "FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace "+ "WHERE n.nspname = $1 AND p.proname = $2 LIMIT 1", params);+ if (r.rows.empty() || r.rows[0].empty()) return {};+ return r.rows[0][0].tryStringValue().value_or("");+}++// ---- DML ----++QueryResult PostgresAdapter::insertRow(const std::string& table, const std::optional<std::string>& schema,+ const std::unordered_map<std::string, RowValue>& values) {+ if (values.empty()) throw QueryError("insertRow: empty values");+ std::string cols, placeholders;+ std::vector<QueryParameter> params;+ int i = 0;+ for (const auto& [k, v] : values) {+ if (i > 0) { cols += ", "; placeholders += ", "; }+ cols += pgQuote(k);+ placeholders += "$" + std::to_string(++i);+ params.emplace_back(v);+ }+ return execute("INSERT INTO " + qualified(table, schema) + " (" + cols + ") VALUES (" + placeholders + ")", params);+}++QueryResult PostgresAdapter::updateRow(const std::string& table, const std::optional<std::string>& schema,+ const std::unordered_map<std::string, RowValue>& set,+ const std::unordered_map<std::string, RowValue>& where) {+ if (set.empty() || where.empty()) throw QueryError("updateRow: empty set/where");+ std::string setClause, whereClause;+ std::vector<QueryParameter> params;+ int i = 0;+ for (const auto& [k, v] : set) {+ if (i > 0) setClause += ", ";+ setClause += pgQuote(k) + " = $" + std::to_string(++i);+ params.emplace_back(v);+ }+ bool first = true;+ for (const auto& [k, v] : where) {+ if (!first) whereClause += " AND ";+ whereClause += pgQuote(k) + " = $" + std::to_string(++i);+ params.emplace_back(v);+ first = false;+ }+ return execute("UPDATE " + qualified(table, schema) + " SET " + setClause + " WHERE " + whereClause, params);+}++QueryResult PostgresAdapter::deleteRow(const std::string& table, const std::optional<std::string>& schema,+ const std::unordered_map<std::string, RowValue>& where) {+ if (where.empty()) throw QueryError("deleteRow: empty where");+ std::string whereClause;+ std::vector<QueryParameter> params;+ int i = 0;+ bool first = true;+ for (const auto& [k, v] : where) {+ if (!first) whereClause += " AND ";+ whereClause += pgQuote(k) + " = $" + std::to_string(++i);+ params.emplace_back(v);+ first = false;+ }+ return execute("DELETE FROM " + qualified(table, schema) + " WHERE " + whereClause, params);+}++void PostgresAdapter::beginTransaction() { (void)executeRaw("BEGIN"); }+void PostgresAdapter::commitTransaction() { (void)executeRaw("COMMIT"); }+void PostgresAdapter::rollbackTransaction() { (void)executeRaw("ROLLBACK"); }++QueryResult PostgresAdapter::fetchRows(const std::string& table,+ const std::optional<std::string>& schema,+ const std::optional<std::vector<std::string>>& columns,+ const std::optional<FilterExpression>& where,+ const std::optional<std::vector<QuerySortDescriptor>>& orderBy,+ int limit, int offset) {+ std::string colList = "*";+ if (columns && !columns->empty()) {+ colList.clear();+ for (std::size_t i = 0; i < columns->size(); ++i) {+ if (i > 0) colList += ", ";+ colList += pgQuote((*columns)[i]);+ }+ }+ std::string sql = "SELECT " + colList + " FROM " + qualified(table, schema);+ if (where && !where->conditions.empty()) sql += " WHERE " + where->toSQL(SQLDialect::PostgreSQL);+ if (orderBy && !orderBy->empty()) {+ sql += " ORDER BY ";+ for (std::size_t i = 0; i < orderBy->size(); ++i) {+ if (i > 0) sql += ", ";+ sql += (*orderBy)[i].toSQL(SQLDialect::PostgreSQL);+ }+ }+ sql += " LIMIT " + std::to_string(limit) + " OFFSET " + std::to_string(offset);+ return executeRaw(sql);+}++std::string PostgresAdapter::serverVersion() {+ const auto r = executeRaw("SHOW server_version");+ if (r.rows.empty() || r.rows[0].empty()) return "PostgreSQL";+ return "PostgreSQL " + r.rows[0][0].tryStringValue().value_or("");+}++std::optional<std::string> PostgresAdapter::currentDatabase() {+ if (databaseName_) return databaseName_;+ const auto r = executeRaw("SELECT current_database()");+ if (r.rows.empty() || r.rows[0].empty()) return std::nullopt;+ return r.rows[0][0].tryStringValue();+}++// ---- ISchemaInspectable ----++SchemaSnapshot PostgresAdapter::fullSchemaSnapshot(const std::optional<std::string>& /*database*/) {+ SchemaSnapshot snap;+ snap.databaseName = currentDatabase().value_or("");+ snap.databaseType = DatabaseType::PostgreSQL;+ snap.capturedAt = std::chrono::system_clock::now();+ for (const auto& s : listSchemas(std::nullopt)) {+ SchemaInfo si;+ si.name = s;+ for (const auto& t : listTables(s)) {+ si.tables.push_back(describeTable(t.name, s));+ }+ si.views = listViews(s);+ snap.schemas.push_back(std::move(si));+ }+ return snap;+}++std::vector<ColumnStatistics> PostgresAdapter::columnStatistics(const std::string& /*table*/,+ const std::optional<std::string>& /*schema*/,+ int /*sampleSize*/) {+ return {}; // deferred to Phase 7+}++int PostgresAdapter::tableRowCount(const std::string& table, const std::optional<std::string>& schema) {+ const auto r = executeRaw("SELECT COUNT(*) FROM " + qualified(table, schema));+ if (r.rows.empty() || r.rows[0].empty()) return 0;+ return static_cast<int>(r.rows[0][0].tryIntValue().value_or(0));+}++std::optional<std::int64_t> PostgresAdapter::tableSizeBytes(const std::string& table, const std::optional<std::string>& schema) {+ // Use format('%I.%I', ...)::regclass so the server does identifier quoting.+ std::vector<QueryParameter> params;+ params.emplace_back(RowValue::makeString(schema.value_or("public")));+ params.emplace_back(RowValue::makeString(table));+ const auto r = execute(+ "SELECT pg_total_relation_size(format('%I.%I', $1::text, $2::text)::regclass)", params);+ if (r.rows.empty() || r.rows[0].empty()) return std::nullopt;+ return r.rows[0][0].tryIntValue();+}++std::vector<QueryStatisticsEntry> PostgresAdapter::queryStatistics() { return {}; }++std::vector<std::string> PostgresAdapter::primaryKeyColumns(const std::string& table, const std::optional<std::string>& schema) {+ std::vector<QueryParameter> params;+ params.emplace_back(RowValue::makeString(schema.value_or("public")));+ params.emplace_back(RowValue::makeString(table));+ const auto r = execute(+ "SELECT kcu.column_name "+ "FROM information_schema.table_constraints tc "+ "JOIN information_schema.key_column_usage kcu ON tc.constraint_name = kcu.constraint_name "+ "WHERE tc.table_schema = $1 AND tc.table_name = $2 AND tc.constraint_type = 'PRIMARY KEY' "+ "ORDER BY kcu.ordinal_position", params);+ std::vector<std::string> out;+ for (const auto& row : r.rows) if (!row.empty() && row[0].isString()) out.push_back(row[0].asString());+ return out;+}++}diff --git a/linux/src/Data/Adapters/PostgreSQL/PostgresAdapter.h b/linux/src/Data/Adapters/PostgreSQL/PostgresAdapter.hnew file mode 100644index 0000000..dee47d9--- /dev/null+++ b/linux/src/Data/Adapters/PostgreSQL/PostgresAdapter.h@@ -0,0 +1,100 @@+#pragma once++#include <atomic>+#include <mutex>+#include <optional>+#include <string>++#include "Core/Protocols/Database/IDatabaseAdapter.h"+#include "Core/Protocols/Database/ISchemaInspectable.h"++// Opaque libpq connection type. Include <libpq-fe.h> in the .cpp only.+struct pg_conn;+typedef struct pg_conn PGconn;++namespace gridex {++// PostgreSQL adapter using libpq (sync API).+// Phase 2d scope: connection lifecycle, parameterized queries, transactions,+// basic schema inspection (databases/schemas/tables/columns/PKs/FKs, version).+// Advanced inspection methods (functions, procedures, detailed constraints)+// stay stub until Phase 4.+class PostgresAdapter final : public IDatabaseAdapter, public ISchemaInspectable {+public:+ PostgresAdapter();+ ~PostgresAdapter() override;++ PostgresAdapter(const PostgresAdapter&) = delete;+ PostgresAdapter& operator=(const PostgresAdapter&) = delete;++ [[nodiscard]] DatabaseType databaseType() const noexcept override { return DatabaseType::PostgreSQL; }+ [[nodiscard]] bool isConnected() const noexcept override { return connected_.load(std::memory_order_acquire); }++ void connect(const ConnectionConfig& config, const std::optional<std::string>& password) override;+ void disconnect() override;+ bool testConnection(const ConnectionConfig& config, const std::optional<std::string>& password) override;++ QueryResult execute(const std::string& query, const std::vector<QueryParameter>& parameters) override;+ QueryResult executeRaw(const std::string& sql) override;++ std::vector<std::string> listDatabases() override;+ std::vector<std::string> listSchemas(const std::optional<std::string>& database) override;+ std::vector<TableInfo> listTables(const std::optional<std::string>& schema) override;+ std::vector<ViewInfo> listViews(const std::optional<std::string>& schema) override;+ TableDescription describeTable(const std::string& name,+ const std::optional<std::string>& schema) override;+ std::vector<IndexInfo> listIndexes(const std::string& table,+ const std::optional<std::string>& schema) override;+ std::vector<ForeignKeyInfo> listForeignKeys(const std::string& table,+ const std::optional<std::string>& schema) override;+ std::vector<std::string> listFunctions(const std::optional<std::string>& schema) override;+ std::string getFunctionSource(const std::string& name,+ const std::optional<std::string>& schema) override;++ QueryResult insertRow(const std::string& table, const std::optional<std::string>& schema,+ const std::unordered_map<std::string, RowValue>& values) override;+ QueryResult updateRow(const std::string& table, const std::optional<std::string>& schema,+ const std::unordered_map<std::string, RowValue>& set,+ const std::unordered_map<std::string, RowValue>& where) override;+ QueryResult deleteRow(const std::string& table, const std::optional<std::string>& schema,+ const std::unordered_map<std::string, RowValue>& where) override;++ void beginTransaction() override;+ void commitTransaction() override;+ void rollbackTransaction() override;++ QueryResult fetchRows(const std::string& table,+ const std::optional<std::string>& schema,+ const std::optional<std::vector<std::string>>& columns,+ const std::optional<FilterExpression>& where,+ const std::optional<std::vector<QuerySortDescriptor>>& orderBy,+ int limit, int offset) override;++ std::string serverVersion() override;+ std::optional<std::string> currentDatabase() override;++ // ISchemaInspectable+ SchemaSnapshot fullSchemaSnapshot(const std::optional<std::string>& database) override;+ std::vector<ColumnStatistics> columnStatistics(const std::string& table,+ const std::optional<std::string>& schema,+ int sampleSize) override;+ int tableRowCount(const std::string& table,+ const std::optional<std::string>& schema) override;+ std::optional<std::int64_t> tableSizeBytes(const std::string& table,+ const std::optional<std::string>& schema) override;+ std::vector<QueryStatisticsEntry> queryStatistics() override;+ std::vector<std::string> primaryKeyColumns(const std::string& table,+ const std::optional<std::string>& schema) override;++private:+ QueryResult executeInternal(const std::string& sql, const std::vector<RowValue>& values);+ void ensureConnected() const;+ std::string qualified(const std::string& table, const std::optional<std::string>& schema) const;++ PGconn* conn_ = nullptr;+ std::atomic<bool> connected_{false};+ std::optional<std::string> databaseName_;+ mutable std::mutex mutex_;+};++}diff --git a/linux/src/Data/Adapters/Redis/RedisAdapter.cpp b/linux/src/Data/Adapters/Redis/RedisAdapter.cppnew file mode 100644index 0000000..23001fb--- /dev/null+++ b/linux/src/Data/Adapters/Redis/RedisAdapter.cpp@@ -0,0 +1,805 @@+#include "Data/Adapters/Redis/RedisAdapter.h"++#include <chrono>+#include <hiredis/hiredis.h>+#include <sstream>+#include <stdexcept>++#include "Core/Errors/GridexError.h"++namespace gridex {++namespace {++// Split a command string on whitespace, respecting double-quoted tokens.+// e.g. "SET mykey \"hello world\"" → ["SET", "mykey", "hello world"]+std::vector<std::string> tokenize(const std::string& cmd) {+ std::vector<std::string> out;+ std::size_t i = 0;+ const std::size_t n = cmd.size();+ while (i < n) {+ // skip whitespace+ while (i < n && std::isspace(static_cast<unsigned char>(cmd[i]))) ++i;+ if (i >= n) break;+ if (cmd[i] == '"') {+ // quoted token+ ++i;+ std::string tok;+ while (i < n && cmd[i] != '"') {+ if (cmd[i] == '\\' && i + 1 < n) { tok.push_back(cmd[++i]); ++i; continue; }+ tok.push_back(cmd[i++]);+ }+ if (i < n) ++i; // consume closing "+ out.push_back(std::move(tok));+ } else {+ std::string tok;+ while (i < n && !std::isspace(static_cast<unsigned char>(cmd[i]))) tok.push_back(cmd[i++]);+ out.push_back(std::move(tok));+ }+ }+ return out;+}++// Classify the first token of a Redis command for QueryType mapping.+QueryType detectQueryType(const std::vector<std::string>& args) {+ if (args.empty()) return QueryType::Other;+ std::string verb;+ for (char c : args[0]) verb.push_back(static_cast<char>(std::toupper(static_cast<unsigned char>(c))));+ if (verb == "GET" || verb == "MGET" || verb == "KEYS" ||+ verb == "SCAN" || verb == "HSCAN" || verb == "SSCAN" ||+ verb == "ZSCAN" || verb == "HGET" || verb == "HGETALL" ||+ verb == "LRANGE" || verb == "SMEMBERS" || verb == "ZRANGE" ||+ verb == "TYPE" || verb == "TTL" || verb == "PTTL" ||+ verb == "EXISTS" || verb == "INFO" || verb == "DBSIZE" ||+ verb == "STRLEN" || verb == "LLEN" || verb == "SCARD" ||+ verb == "ZCARD" || verb == "HLEN" || verb == "GETRANGE")+ return QueryType::Select;+ if (verb == "SET" || verb == "MSET" || verb == "HSET" ||+ verb == "LPUSH" || verb == "RPUSH" || verb == "SADD" || verb == "ZADD")+ return QueryType::Insert;+ if (verb == "SETEX" || verb == "PSETEX" || verb == "GETSET" ||+ verb == "INCR" || verb == "DECR" || verb == "INCRBY" ||+ verb == "DECRBY"|| verb == "APPEND" || verb == "EXPIRE" ||+ verb == "RENAME"|| verb == "HMSET")+ return QueryType::Update;+ if (verb == "DEL" || verb == "UNLINK" || verb == "HDEL" ||+ verb == "LREM" || verb == "SREM" || verb == "ZREM")+ return QueryType::Delete;+ return QueryType::Other;+}++// Convert a redisReply into a flat string for display.+std::string replyToString(redisReply* reply) {+ if (!reply) return "(nil)";+ switch (reply->type) {+ case REDIS_REPLY_STRING:+ case REDIS_REPLY_STATUS:+ return std::string(reply->str, static_cast<std::size_t>(reply->len));+ case REDIS_REPLY_INTEGER:+ return std::to_string(reply->integer);+ case REDIS_REPLY_NIL:+ return "(nil)";+ case REDIS_REPLY_ERROR:+ return std::string("(error) ") + (reply->str ? reply->str : "");+ case REDIS_REPLY_ARRAY: {+ std::string out;+ for (std::size_t i = 0; i < static_cast<std::size_t>(reply->elements); ++i) {+ if (i > 0) out += '\n';+ out += std::to_string(i + 1) + ") " + replyToString(reply->element[i]);+ }+ return out;+ }+ default:+ return "(unknown)";+ }+}++// Build a QueryResult from a single-value reply (status/integer/string/nil).+QueryResult scalarResult(redisReply* reply, QueryType qt,+ std::chrono::duration<double> elapsed) {+ QueryResult r;+ r.queryType = qt;+ r.executionTime = elapsed;++ ColumnHeader h;+ h.name = "result";+ h.dataType = "string";+ r.columns.push_back(std::move(h));++ std::vector<RowValue> row;+ if (reply->type == REDIS_REPLY_NIL) {+ row.push_back(RowValue::makeNull());+ } else if (reply->type == REDIS_REPLY_INTEGER) {+ row.push_back(RowValue::makeInteger(static_cast<std::int64_t>(reply->integer)));+ } else {+ row.push_back(RowValue::makeString(replyToString(reply)));+ }+ r.rows.push_back(std::move(row));+ r.rowsAffected = 1;+ return r;+}++} // anonymous namespace++// ---- Lifecycle ----++RedisAdapter::RedisAdapter() = default;++RedisAdapter::~RedisAdapter() {+ std::lock_guard lock(mutex_);+ if (ctx_) { redisFree(ctx_); ctx_ = nullptr; }+ connected_.store(false, std::memory_order_release);+}++void RedisAdapter::connect(const ConnectionConfig& config,+ const std::optional<std::string>& password) {+ std::lock_guard lock(mutex_);+ if (ctx_) { redisFree(ctx_); ctx_ = nullptr; }++ const std::string host = config.host.value_or("localhost");+ const int port = config.port.value_or(6379);++ struct timeval tv{5, 0}; // 5-second connect timeout+ ctx_ = redisConnectWithTimeout(host.c_str(), port, tv);+ if (!ctx_ || ctx_->err) {+ std::string msg = ctx_ ? ctx_->errstr : "out of memory";+ if (ctx_) { redisFree(ctx_); ctx_ = nullptr; }+ throw ConnectionError("Redis connect failed: " + msg);+ }++ // Optional AUTH+ if (password && !password->empty()) {+ redisReply* r = static_cast<redisReply*>(+ redisCommand(ctx_, "AUTH %s", password->c_str()));+ if (!r || r->type == REDIS_REPLY_ERROR) {+ std::string err = r ? std::string(r->str, static_cast<std::size_t>(r->len))+ : "no reply";+ if (r) freeReplyObject(r);+ redisFree(ctx_); ctx_ = nullptr;+ throw AuthenticationError("Redis AUTH failed: " + err);+ }+ freeReplyObject(r);+ }++ // SELECT database index if specified (default 0)+ int dbIndex = 0;+ if (config.database) {+ try { dbIndex = std::stoi(*config.database); } catch (...) { dbIndex = 0; }+ }+ if (dbIndex != 0) {+ redisReply* r = static_cast<redisReply*>(+ redisCommand(ctx_, "SELECT %d", dbIndex));+ if (!r || r->type == REDIS_REPLY_ERROR) {+ std::string err = r ? std::string(r->str, static_cast<std::size_t>(r->len))+ : "no reply";+ if (r) freeReplyObject(r);+ redisFree(ctx_); ctx_ = nullptr;+ throw ConnectionError("Redis SELECT " + std::to_string(dbIndex) + " failed: " + err);+ }+ freeReplyObject(r);+ currentDb_ = dbIndex;+ }++ connected_.store(true, std::memory_order_release);+}++void RedisAdapter::disconnect() {+ std::lock_guard lock(mutex_);+ if (ctx_) { redisFree(ctx_); ctx_ = nullptr; }+ connected_.store(false, std::memory_order_release);+ currentDb_ = 0;+}++bool RedisAdapter::testConnection(const ConnectionConfig& config,+ const std::optional<std::string>& password) {+ RedisAdapter probe;+ probe.connect(config, password);+ probe.disconnect();+ return true;+}++void RedisAdapter::ensureConnected() const {+ if (!connected_.load(std::memory_order_acquire) || !ctx_)+ throw QueryError("Not connected to Redis");+}++// ---- Command execution ----++QueryResult RedisAdapter::runCommand(const std::vector<std::string>& args) {+ ensureConnected();+ if (args.empty()) throw QueryError("Empty Redis command");++ const auto start = std::chrono::steady_clock::now();+ const QueryType qt = detectQueryType(args);++ std::lock_guard lock(mutex_);++ // Build argv/argvlen arrays for redisCommandArgv+ std::vector<const char*> argv;+ std::vector<std::size_t> argvlen;+ argv.reserve(args.size());+ argvlen.reserve(args.size());+ for (const auto& a : args) {+ argv.push_back(a.c_str());+ argvlen.push_back(a.size());+ }++ redisReply* reply = static_cast<redisReply*>(+ redisCommandArgv(ctx_, static_cast<int>(args.size()),+ argv.data(), argvlen.data()));++ const auto elapsed = std::chrono::steady_clock::now() - start;++ if (!reply) {+ const std::string err = ctx_->err ? ctx_->errstr : "connection lost";+ throw QueryError("Redis command failed: " + err);+ }++ // RAII guard+ struct Guard { redisReply* p; ~Guard() { if (p) freeReplyObject(p); } } guard{reply};++ if (reply->type == REDIS_REPLY_ERROR) {+ throw QueryError("Redis error: " + std::string(reply->str,+ static_cast<std::size_t>(reply->len)));+ }++ QueryResult result;+ result.queryType = qt;+ result.executionTime = elapsed;++ if (reply->type == REDIS_REPLY_ARRAY) {+ // Multi-bulk reply: present as single column "value" with one row per element+ ColumnHeader h;+ h.name = "value";+ h.dataType = "string";+ result.columns.push_back(std::move(h));+ result.rows.reserve(static_cast<std::size_t>(reply->elements));+ for (std::size_t i = 0; i < static_cast<std::size_t>(reply->elements); ++i) {+ redisReply* elem = reply->element[i];+ std::vector<RowValue> row;+ if (!elem || elem->type == REDIS_REPLY_NIL) {+ row.push_back(RowValue::makeNull());+ } else if (elem->type == REDIS_REPLY_INTEGER) {+ row.push_back(RowValue::makeInteger(static_cast<std::int64_t>(elem->integer)));+ } else {+ row.push_back(RowValue::makeString(+ std::string(elem->str, static_cast<std::size_t>(elem->len))));+ }+ result.rows.push_back(std::move(row));+ }+ result.rowsAffected = static_cast<int>(reply->elements);+ } else {+ // Scalar+ result = scalarResult(reply, qt, elapsed);+ }++ return result;+}++QueryResult RedisAdapter::execute(const std::string& query,+ const std::vector<QueryParameter>& /*parameters*/) {+ return executeRaw(query);+}++QueryResult RedisAdapter::executeRaw(const std::string& sql) {+ return runCommand(tokenize(sql));+}++// ---- Schema inspection ----++std::vector<std::string> RedisAdapter::listDatabases() {+ // Redis has 16 logical DBs (0-15) by default+ std::vector<std::string> dbs;+ dbs.reserve(16);+ for (int i = 0; i < 16; ++i) dbs.push_back(std::to_string(i));+ return dbs;+}++std::vector<std::string> RedisAdapter::listSchemas(const std::optional<std::string>& /*database*/) {+ return {"default"};+}++std::vector<TableInfo> RedisAdapter::listTables(const std::optional<std::string>& /*schema*/) {+ // Treat each key as a "table"+ auto r = runCommand({"KEYS", "*"});+ std::vector<TableInfo> out;+ out.reserve(r.rows.size());+ for (const auto& row : r.rows) {+ if (row.empty()) continue;+ TableInfo t;+ t.name = row[0].tryStringValue().value_or("");+ t.schema = "default";+ t.type = TableKind::Table;+ out.push_back(std::move(t));+ }+ return out;+}++std::vector<ViewInfo> RedisAdapter::listViews(const std::optional<std::string>& /*schema*/) {+ return {}; // Redis has no views+}++TableDescription RedisAdapter::describeTable(const std::string& name,+ const std::optional<std::string>& schema) {+ TableDescription desc;+ desc.name = name;+ desc.schema = schema;++ // Get key type+ auto typeReply = runCommand({"TYPE", name});+ std::string keyType = "none";+ if (!typeReply.rows.empty() && !typeReply.rows[0].empty())+ keyType = typeReply.rows[0][0].tryStringValue().value_or("none");++ // Get TTL+ auto ttlReply = runCommand({"TTL", name});+ std::int64_t ttlVal = -1;+ if (!ttlReply.rows.empty() && !ttlReply.rows[0].empty())+ ttlVal = ttlReply.rows[0][0].tryIntValue().value_or(-1);++ // Represent as two virtual columns: "value" (type=keyType) and "ttl"+ ColumnInfo cKey;+ cKey.name = "value";+ cKey.dataType = keyType;+ cKey.isNullable = true;+ cKey.ordinalPosition = 1;+ desc.columns.push_back(std::move(cKey));++ ColumnInfo cTtl;+ cTtl.name = "ttl";+ cTtl.dataType = "integer";+ cTtl.isNullable = false;+ cTtl.defaultValue = std::to_string(ttlVal);+ cTtl.ordinalPosition = 2;+ desc.columns.push_back(std::move(cTtl));++ return desc;+}++std::vector<IndexInfo> RedisAdapter::listIndexes(const std::string& /*table*/,+ const std::optional<std::string>& /*schema*/) {+ return {}; // Redis has no indexes+}++std::vector<ForeignKeyInfo> RedisAdapter::listForeignKeys(const std::string& /*table*/,+ const std::optional<std::string>& /*schema*/) {+ return {}; // Redis has no foreign keys+}++std::vector<std::string> RedisAdapter::listFunctions(const std::optional<std::string>& /*schema*/) {+ return {};+}++std::string RedisAdapter::getFunctionSource(const std::string& /*name*/,+ const std::optional<std::string>& /*schema*/) {+ return {};+}++// ---- DML (key-value mapping) ----++QueryResult RedisAdapter::insertRow(const std::string& table,+ const std::optional<std::string>& /*schema*/,+ const std::unordered_map<std::string, RowValue>& values) {+ // table = key name; values["value"] = value to SET+ auto it = values.find("value");+ if (it == values.end()) {+ // Fallback: use the first value, key = table name+ if (values.empty()) throw QueryError("insertRow: no values provided");+ const auto& [k, v] = *values.begin();+ return runCommand({"SET", table + ":" + k, v.description()});+ }+ return runCommand({"SET", table, it->second.description()});+}++QueryResult RedisAdapter::updateRow(const std::string& table,+ const std::optional<std::string>& /*schema*/,+ const std::unordered_map<std::string, RowValue>& set,+ const std::unordered_map<std::string, RowValue>& /*where*/) {+ // SET key value (overwrite)+ auto it = set.find("value");+ if (it == set.end()) {+ if (set.empty()) throw QueryError("updateRow: no set values provided");+ const auto& [k, v] = *set.begin();+ return runCommand({"SET", table + ":" + k, v.description()});+ }+ return runCommand({"SET", table, it->second.description()});+}++QueryResult RedisAdapter::deleteRow(const std::string& table,+ const std::optional<std::string>& /*schema*/,+ const std::unordered_map<std::string, RowValue>& where) {+ // where["key"] overrides; otherwise delete the key named by `table`+ auto it = where.find("key");+ const std::string key = (it != where.end())+ ? it->second.tryStringValue().value_or(table)+ : table;+ return runCommand({"DEL", key});+}++// ---- Transactions ----++void RedisAdapter::beginTransaction() { (void)runCommand({"MULTI"}); }+void RedisAdapter::commitTransaction() { (void)runCommand({"EXEC"}); }+void RedisAdapter::rollbackTransaction() { (void)runCommand({"DISCARD"}); }++// ---- Pagination (SCAN-based) ----++QueryResult RedisAdapter::fetchRows(const std::string& /*table*/,+ const std::optional<std::string>& /*schema*/,+ const std::optional<std::vector<std::string>>& /*columns*/,+ const std::optional<FilterExpression>& /*where*/,+ const std::optional<std::vector<QuerySortDescriptor>>& /*orderBy*/,+ int limit, int offset) {+ ensureConnected();+ const auto start = std::chrono::steady_clock::now();++ // Column layout: key | type | value | ttl+ QueryResult result;+ result.queryType = QueryType::Select;+ for (const char* name : {"key", "type", "value", "ttl"}) {+ ColumnHeader h;+ h.name = name;+ h.dataType = "string";+ result.columns.push_back(std::move(h));+ }++ // SCAN to collect up to (offset + limit) keys, then skip `offset`+ std::string cursor = "0";+ int collected = 0;+ int target = offset + limit;+ std::vector<std::string> keys;+ keys.reserve(static_cast<std::size_t>(target));++ do {+ auto r = runCommand({"SCAN", cursor, "COUNT", "100"});+ // SCAN returns array[2]: [next_cursor, [key0, key1, ...]]+ if (r.rows.size() < 2) break;+ cursor = r.rows[0][0].tryStringValue().value_or("0");++ // The elements from index 1 onward are keys in a nested array format.+ // runCommand flattens the outer array; SCAN specifically returns+ // element[0]=cursor, element[1..N]=keys from the inner array.+ // We need to re-issue with ARGV so we get the raw structure.+ // Instead, re-run SCAN and parse the array reply manually.+ break; // sentinel — handled below via direct hiredis call+ } while (false);++ // Direct SCAN loop using hiredis to access nested reply structure+ {+ std::lock_guard lock(mutex_);+ cursor = "0";+ do {+ const std::string countStr = "100";+ const char* scanArgv[] = {"SCAN", cursor.c_str(), "COUNT", countStr.c_str()};+ const std::size_t scanArgvLen[] = {4, cursor.size(), 5, countStr.size()};+ redisReply* reply = static_cast<redisReply*>(+ redisCommandArgv(ctx_, 4, scanArgv, scanArgvLen));+ if (!reply) throw QueryError("Redis SCAN failed: connection lost");+ struct Guard { redisReply* p; ~Guard() { if (p) freeReplyObject(p); } } guard{reply};++ if (reply->type != REDIS_REPLY_ARRAY || reply->elements < 2) break;+ cursor = std::string(reply->element[0]->str,+ static_cast<std::size_t>(reply->element[0]->len));+ redisReply* keyArray = reply->element[1];+ if (keyArray->type == REDIS_REPLY_ARRAY) {+ for (std::size_t i = 0; i < static_cast<std::size_t>(keyArray->elements); ++i) {+ redisReply* ke = keyArray->element[i];+ if (!ke || ke->type != REDIS_REPLY_STRING) continue;+ keys.emplace_back(ke->str, static_cast<std::size_t>(ke->len));+ ++collected;+ if (collected >= target) { cursor = "0"; break; }+ }+ }+ } while (cursor != "0");+ }++ // Apply offset/limit+ int start_idx = offset;+ int end_idx = std::min(static_cast<int>(keys.size()), offset + limit);+ result.rows.reserve(static_cast<std::size_t>(std::max(0, end_idx - start_idx)));++ for (int i = start_idx; i < end_idx; ++i) {+ const std::string& key = keys[static_cast<std::size_t>(i)];++ // Get type+ std::string keyType = "string";+ {+ std::lock_guard lock(mutex_);+ redisReply* tr = static_cast<redisReply*>(+ redisCommand(ctx_, "TYPE %s", key.c_str()));+ if (tr) {+ if (tr->type == REDIS_REPLY_STATUS)+ keyType = std::string(tr->str, static_cast<std::size_t>(tr->len));+ freeReplyObject(tr);+ }+ }++ // Get value (string type only; others show type name)+ std::string value;+ if (keyType == "string") {+ std::lock_guard lock(mutex_);+ redisReply* vr = static_cast<redisReply*>(+ redisCommand(ctx_, "GET %s", key.c_str()));+ if (vr) {+ if (vr->type == REDIS_REPLY_STRING)+ value = std::string(vr->str, static_cast<std::size_t>(vr->len));+ freeReplyObject(vr);+ }+ } else {+ value = "(" + keyType + ")";+ }++ // Get TTL+ std::int64_t ttl = -1;+ {+ std::lock_guard lock(mutex_);+ redisReply* tr = static_cast<redisReply*>(+ redisCommand(ctx_, "TTL %s", key.c_str()));+ if (tr) {+ if (tr->type == REDIS_REPLY_INTEGER)+ ttl = static_cast<std::int64_t>(tr->integer);+ freeReplyObject(tr);+ }+ }++ std::vector<RowValue> row;+ row.push_back(RowValue::makeString(key));+ row.push_back(RowValue::makeString(keyType));+ row.push_back(value.empty() ? RowValue::makeNull() : RowValue::makeString(value));+ row.push_back(RowValue::makeInteger(ttl));+ result.rows.push_back(std::move(row));+ }++ result.rowsAffected = static_cast<int>(result.rows.size());+ result.executionTime = std::chrono::steady_clock::now() - start;+ return result;+}++// ---- Server info ----++std::string RedisAdapter::serverVersion() {+ ensureConnected();+ std::lock_guard lock(mutex_);+ redisReply* r = static_cast<redisReply*>(redisCommand(ctx_, "INFO server"));+ if (!r) throw QueryError("Redis INFO failed");+ struct Guard { redisReply* p; ~Guard() { if (p) freeReplyObject(p); } } guard{r};++ std::string info(r->str, static_cast<std::size_t>(r->len));+ // Find "redis_version:X.Y.Z"+ const std::string marker = "redis_version:";+ auto pos = info.find(marker);+ if (pos == std::string::npos) return "Redis";+ pos += marker.size();+ auto end = info.find('\r', pos);+ if (end == std::string::npos) end = info.find('\n', pos);+ const std::string ver = end != std::string::npos+ ? info.substr(pos, end - pos)+ : info.substr(pos);+ return "Redis " + ver;+}++std::optional<std::string> RedisAdapter::currentDatabase() {+ return std::to_string(currentDb_);+}++// ---- Redis key-detail helpers ----++RedisAdapter::KeyDetail RedisAdapter::keyDetail(const std::string& key) {+ KeyDetail d;+ {+ std::lock_guard lock(mutex_);+ ensureConnected();+ redisReply* tr = static_cast<redisReply*>(redisCommand(ctx_, "TYPE %s", key.c_str()));+ if (tr) {+ d.type = (tr->type == REDIS_REPLY_STATUS)+ ? std::string(tr->str, static_cast<std::size_t>(tr->len)) : "none";+ freeReplyObject(tr);+ }+ redisReply* ttlr = static_cast<redisReply*>(redisCommand(ctx_, "TTL %s", key.c_str()));+ if (ttlr) {+ d.ttl = (ttlr->type == REDIS_REPLY_INTEGER)+ ? static_cast<std::int64_t>(ttlr->integer) : -1;+ freeReplyObject(ttlr);+ }+ }+ return d;+}++void RedisAdapter::expireKey(const std::string& key, int seconds) {+ runCommand({"EXPIRE", key, std::to_string(seconds)});+}++void RedisAdapter::persistKey(const std::string& key) {+ runCommand({"PERSIST", key});+}++void RedisAdapter::deleteKey(const std::string& key) {+ runCommand({"DEL", key});+}++std::string RedisAdapter::getString(const std::string& key) {+ std::lock_guard lock(mutex_);+ ensureConnected();+ redisReply* r = static_cast<redisReply*>(redisCommand(ctx_, "GET %s", key.c_str()));+ if (!r) throw QueryError("GET failed");+ struct Guard { redisReply* p; ~Guard() { if (p) freeReplyObject(p); } } g{r};+ if (r->type == REDIS_REPLY_NIL) return {};+ if (r->type == REDIS_REPLY_ERROR)+ throw QueryError(std::string(r->str, static_cast<std::size_t>(r->len)));+ return std::string(r->str, static_cast<std::size_t>(r->len));+}++void RedisAdapter::setString(const std::string& key, const std::string& value) {+ runCommand({"SET", key, value});+}++std::vector<std::string> RedisAdapter::lrange(const std::string& key) {+ std::lock_guard lock(mutex_);+ ensureConnected();+ redisReply* r = static_cast<redisReply*>(+ redisCommand(ctx_, "LRANGE %s 0 -1", key.c_str()));+ if (!r) throw QueryError("LRANGE failed");+ struct Guard { redisReply* p; ~Guard() { if (p) freeReplyObject(p); } } g{r};+ if (r->type == REDIS_REPLY_ERROR)+ throw QueryError(std::string(r->str, static_cast<std::size_t>(r->len)));+ std::vector<std::string> out;+ if (r->type == REDIS_REPLY_ARRAY) {+ out.reserve(static_cast<std::size_t>(r->elements));+ for (std::size_t i = 0; i < static_cast<std::size_t>(r->elements); ++i) {+ redisReply* e = r->element[i];+ out.push_back(e && e->type == REDIS_REPLY_STRING+ ? std::string(e->str, static_cast<std::size_t>(e->len)) : "");+ }+ }+ return out;+}++void RedisAdapter::lpush(const std::string& key, const std::string& value) {+ runCommand({"LPUSH", key, value});+}++void RedisAdapter::rpush(const std::string& key, const std::string& value) {+ runCommand({"RPUSH", key, value});+}++void RedisAdapter::lpop(const std::string& key) { runCommand({"LPOP", key}); }+void RedisAdapter::rpop(const std::string& key) { runCommand({"RPOP", key}); }++void RedisAdapter::lrem(const std::string& key, const std::string& value) {+ runCommand({"LREM", key, "0", value});+}++std::vector<std::pair<std::string,std::string>> RedisAdapter::hgetall(const std::string& key) {+ std::lock_guard lock(mutex_);+ ensureConnected();+ redisReply* r = static_cast<redisReply*>(+ redisCommand(ctx_, "HGETALL %s", key.c_str()));+ if (!r) throw QueryError("HGETALL failed");+ struct Guard { redisReply* p; ~Guard() { if (p) freeReplyObject(p); } } g{r};+ if (r->type == REDIS_REPLY_ERROR)+ throw QueryError(std::string(r->str, static_cast<std::size_t>(r->len)));+ std::vector<std::pair<std::string,std::string>> out;+ if (r->type == REDIS_REPLY_ARRAY && r->elements % 2 == 0) {+ out.reserve(static_cast<std::size_t>(r->elements / 2));+ for (std::size_t i = 0; i + 1 < static_cast<std::size_t>(r->elements); i += 2) {+ auto* fk = r->element[i];+ auto* fv = r->element[i+1];+ std::string field = fk && fk->type == REDIS_REPLY_STRING+ ? std::string(fk->str, static_cast<std::size_t>(fk->len)) : "";+ std::string val = fv && fv->type == REDIS_REPLY_STRING+ ? std::string(fv->str, static_cast<std::size_t>(fv->len)) : "";+ out.push_back({field, val});+ }+ }+ return out;+}++void RedisAdapter::hset(const std::string& key, const std::string& field, const std::string& value) {+ runCommand({"HSET", key, field, value});+}++void RedisAdapter::hdel(const std::string& key, const std::string& field) {+ runCommand({"HDEL", key, field});+}++std::vector<std::string> RedisAdapter::smembers(const std::string& key) {+ std::lock_guard lock(mutex_);+ ensureConnected();+ redisReply* r = static_cast<redisReply*>(+ redisCommand(ctx_, "SMEMBERS %s", key.c_str()));+ if (!r) throw QueryError("SMEMBERS failed");+ struct Guard { redisReply* p; ~Guard() { if (p) freeReplyObject(p); } } g{r};+ if (r->type == REDIS_REPLY_ERROR)+ throw QueryError(std::string(r->str, static_cast<std::size_t>(r->len)));+ std::vector<std::string> out;+ if (r->type == REDIS_REPLY_ARRAY) {+ out.reserve(static_cast<std::size_t>(r->elements));+ for (std::size_t i = 0; i < static_cast<std::size_t>(r->elements); ++i) {+ redisReply* e = r->element[i];+ out.push_back(e && e->type == REDIS_REPLY_STRING+ ? std::string(e->str, static_cast<std::size_t>(e->len)) : "");+ }+ }+ return out;+}++void RedisAdapter::sadd(const std::string& key, const std::string& member) {+ runCommand({"SADD", key, member});+}++void RedisAdapter::srem(const std::string& key, const std::string& member) {+ runCommand({"SREM", key, member});+}++std::vector<std::pair<std::string,double>> RedisAdapter::zrangeWithScores(const std::string& key) {+ std::lock_guard lock(mutex_);+ ensureConnected();+ redisReply* r = static_cast<redisReply*>(+ redisCommand(ctx_, "ZRANGE %s 0 -1 WITHSCORES", key.c_str()));+ if (!r) throw QueryError("ZRANGE failed");+ struct Guard { redisReply* p; ~Guard() { if (p) freeReplyObject(p); } } g{r};+ if (r->type == REDIS_REPLY_ERROR)+ throw QueryError(std::string(r->str, static_cast<std::size_t>(r->len)));+ std::vector<std::pair<std::string,double>> out;+ if (r->type == REDIS_REPLY_ARRAY && r->elements % 2 == 0) {+ out.reserve(static_cast<std::size_t>(r->elements / 2));+ for (std::size_t i = 0; i + 1 < static_cast<std::size_t>(r->elements); i += 2) {+ auto* me = r->element[i];+ auto* se = r->element[i+1];+ std::string member = me && me->type == REDIS_REPLY_STRING+ ? std::string(me->str, static_cast<std::size_t>(me->len)) : "";+ double score = 0.0;+ if (se && se->type == REDIS_REPLY_STRING)+ score = std::stod(std::string(se->str, static_cast<std::size_t>(se->len)));+ out.push_back({member, score});+ }+ }+ return out;+}++void RedisAdapter::zadd(const std::string& key, double score, const std::string& member) {+ runCommand({"ZADD", key, std::to_string(score), member});+}++void RedisAdapter::zrem(const std::string& key, const std::string& member) {+ runCommand({"ZREM", key, member});+}++std::vector<RedisAdapter::StreamEntry> RedisAdapter::xrevrange(const std::string& key, int count) {+ std::lock_guard lock(mutex_);+ ensureConnected();+ const std::string countStr = std::to_string(count);+ redisReply* r = static_cast<redisReply*>(+ redisCommand(ctx_, "XREVRANGE %s + - COUNT %s", key.c_str(), countStr.c_str()));+ if (!r) throw QueryError("XREVRANGE failed");+ struct Guard { redisReply* p; ~Guard() { if (p) freeReplyObject(p); } } g{r};+ if (r->type == REDIS_REPLY_ERROR)+ throw QueryError(std::string(r->str, static_cast<std::size_t>(r->len)));+ std::vector<StreamEntry> out;+ if (r->type != REDIS_REPLY_ARRAY) return out;+ out.reserve(static_cast<std::size_t>(r->elements));+ for (std::size_t i = 0; i < static_cast<std::size_t>(r->elements); ++i) {+ redisReply* entry = r->element[i];+ if (!entry || entry->type != REDIS_REPLY_ARRAY || entry->elements < 2) continue;+ StreamEntry se;+ auto* idElem = entry->element[0];+ se.id = idElem && idElem->type == REDIS_REPLY_STRING+ ? std::string(idElem->str, static_cast<std::size_t>(idElem->len)) : "";+ auto* fields = entry->element[1];+ if (fields && fields->type == REDIS_REPLY_ARRAY && fields->elements % 2 == 0) {+ for (std::size_t j = 0; j + 1 < static_cast<std::size_t>(fields->elements); j += 2) {+ auto* fk = fields->element[j];+ auto* fv = fields->element[j+1];+ std::string fkStr = fk && fk->type == REDIS_REPLY_STRING+ ? std::string(fk->str, static_cast<std::size_t>(fk->len)) : "";+ std::string fvStr = fv && fv->type == REDIS_REPLY_STRING+ ? std::string(fv->str, static_cast<std::size_t>(fv->len)) : "";+ se.fields.push_back({fkStr, fvStr});+ }+ }+ out.push_back(std::move(se));+ }+ return out;+}++} // namespace gridexdiff --git a/linux/src/Data/Adapters/Redis/RedisAdapter.h b/linux/src/Data/Adapters/Redis/RedisAdapter.hnew file mode 100644index 0000000..a8c27d2--- /dev/null+++ b/linux/src/Data/Adapters/Redis/RedisAdapter.h@@ -0,0 +1,133 @@+#pragma once++#include <atomic>+#include <mutex>+#include <optional>+#include <string>++#include "Core/Protocols/Database/IDatabaseAdapter.h"++// Opaque hiredis context; include <hiredis/hiredis.h> in the .cpp only.+struct redisContext;++namespace gridex {++// Redis adapter using hiredis sync API.+// Since Redis is a key-value store, IDatabaseAdapter methods are mapped as:+// listDatabases() → ["0".."15"]+// listTables() → KEYS * results (key names treated as "tables")+// listSchemas() → ["default"]+// describeTable() → TYPE + TTL for the given key+// execute()/executeRaw() → raw Redis command string (space-separated tokens)+// fetchRows() → SCAN cursor-based iteration, returns key+type+value rows+// insertRow() → SET key value+// deleteRow() → DEL key+// transactions → MULTI / EXEC / DISCARD+class RedisAdapter final : public IDatabaseAdapter {+public:+ RedisAdapter();+ ~RedisAdapter() override;++ RedisAdapter(const RedisAdapter&) = delete;+ RedisAdapter& operator=(const RedisAdapter&) = delete;++ [[nodiscard]] DatabaseType databaseType() const noexcept override { return DatabaseType::Redis; }+ [[nodiscard]] bool isConnected() const noexcept override { return connected_.load(std::memory_order_acquire); }++ void connect(const ConnectionConfig& config, const std::optional<std::string>& password) override;+ void disconnect() override;+ bool testConnection(const ConnectionConfig& config, const std::optional<std::string>& password) override;++ // Raw Redis command: treat `query`/`sql` as a space-separated Redis command.+ QueryResult execute(const std::string& query, const std::vector<QueryParameter>& parameters) override;+ QueryResult executeRaw(const std::string& sql) override;++ std::vector<std::string> listDatabases() override;+ std::vector<std::string> listSchemas(const std::optional<std::string>& database) override;+ std::vector<TableInfo> listTables(const std::optional<std::string>& schema) override;+ std::vector<ViewInfo> listViews(const std::optional<std::string>& schema) override;+ TableDescription describeTable(const std::string& name,+ const std::optional<std::string>& schema) override;+ std::vector<IndexInfo> listIndexes(const std::string& table,+ const std::optional<std::string>& schema) override;+ std::vector<ForeignKeyInfo> listForeignKeys(const std::string& table,+ const std::optional<std::string>& schema) override;+ std::vector<std::string> listFunctions(const std::optional<std::string>& schema) override;+ std::string getFunctionSource(const std::string& name,+ const std::optional<std::string>& schema) override;++ QueryResult insertRow(const std::string& table, const std::optional<std::string>& schema,+ const std::unordered_map<std::string, RowValue>& values) override;+ QueryResult updateRow(const std::string& table, const std::optional<std::string>& schema,+ const std::unordered_map<std::string, RowValue>& set,+ const std::unordered_map<std::string, RowValue>& where) override;+ QueryResult deleteRow(const std::string& table, const std::optional<std::string>& schema,+ const std::unordered_map<std::string, RowValue>& where) override;++ void beginTransaction() override;+ void commitTransaction() override;+ void rollbackTransaction() override;++ QueryResult fetchRows(const std::string& table,+ const std::optional<std::string>& schema,+ const std::optional<std::vector<std::string>>& columns,+ const std::optional<FilterExpression>& where,+ const std::optional<std::vector<QuerySortDescriptor>>& orderBy,+ int limit, int offset) override;++ std::string serverVersion() override;+ std::optional<std::string> currentDatabase() override;++ // Redis key-detail helpers (used by RedisKeyDetailView)+ struct KeyDetail {+ std::string type; // string|list|hash|set|zset|stream+ std::int64_t ttl; // -1=persist, -2=missing+ };+ KeyDetail keyDetail(const std::string& key);+ void expireKey(const std::string& key, int seconds);+ void persistKey(const std::string& key);+ void deleteKey(const std::string& key);++ // String+ std::string getString(const std::string& key);+ void setString(const std::string& key, const std::string& value);++ // List+ std::vector<std::string> lrange(const std::string& key);+ void lpush(const std::string& key, const std::string& value);+ void rpush(const std::string& key, const std::string& value);+ void lpop(const std::string& key);+ void rpop(const std::string& key);+ void lrem(const std::string& key, const std::string& value);++ // Hash+ std::vector<std::pair<std::string,std::string>> hgetall(const std::string& key);+ void hset(const std::string& key, const std::string& field, const std::string& value);+ void hdel(const std::string& key, const std::string& field);++ // Set+ std::vector<std::string> smembers(const std::string& key);+ void sadd(const std::string& key, const std::string& member);+ void srem(const std::string& key, const std::string& member);++ // ZSet+ std::vector<std::pair<std::string,double>> zrangeWithScores(const std::string& key);+ void zadd(const std::string& key, double score, const std::string& member);+ void zrem(const std::string& key, const std::string& member);++ // Stream (read-only)+ struct StreamEntry { std::string id; std::vector<std::pair<std::string,std::string>> fields; };+ std::vector<StreamEntry> xrevrange(const std::string& key, int count = 50);++private:+ // Execute a pre-tokenized Redis command via the hiredis API.+ QueryResult runCommand(const std::vector<std::string>& args);+ void ensureConnected() const;++ redisContext* ctx_ = nullptr;+ int currentDb_{0};+ std::atomic<bool> connected_{false};+ mutable std::mutex mutex_;+};++}diff --git a/linux/src/Data/Adapters/SQLite/SqliteAdapter.cpp b/linux/src/Data/Adapters/SQLite/SqliteAdapter.cppnew file mode 100644index 0000000..2e54161--- /dev/null+++ b/linux/src/Data/Adapters/SQLite/SqliteAdapter.cpp@@ -0,0 +1,585 @@+#include "Data/Adapters/SQLite/SqliteAdapter.h"++#include <algorithm>+#include <chrono>+#include <cstring>+#include <filesystem>+#include <sqlite3.h>+#include <stdexcept>+#include <utility>++#include "Core/Errors/GridexError.h"++namespace gridex {++namespace {++// Use SQLITE_TRANSIENT directly — it is a macro that cannot be a constexpr value.++std::string toUpperTrim(std::string_view s) {+ const auto firstNonWs = s.find_first_not_of(" \t\n\r");+ if (firstNonWs == std::string_view::npos) return {};+ const auto lastNonWs = s.find_last_not_of(" \t\n\r");+ std::string out(s.substr(firstNonWs, lastNonWs - firstNonWs + 1));+ std::transform(out.begin(), out.end(), out.begin(),+ [](unsigned char c) { return std::toupper(c); });+ return out;+}++QueryType detectQueryType(std::string_view sql) {+ const auto u = toUpperTrim(sql);+ auto starts = [&](std::string_view p) { return u.rfind(p, 0) == 0; };+ if (starts("SELECT") || starts("PRAGMA") || starts("EXPLAIN")) return QueryType::Select;+ if (starts("INSERT")) return QueryType::Insert;+ if (starts("UPDATE")) return QueryType::Update;+ if (starts("DELETE")) return QueryType::Delete;+ if (starts("CREATE") || starts("ALTER") || starts("DROP")) return QueryType::DDL;+ return QueryType::Other;+}++std::string quoteIdent(std::string_view name) {+ std::string out;+ out.reserve(name.size() + 2);+ out.push_back('"');+ for (char c : name) {+ if (c == '"') out.push_back('"');+ out.push_back(c);+ }+ out.push_back('"');+ return out;+}++void bindRowValue(sqlite3_stmt* stmt, int idx, const RowValue& v) {+ if (v.isNull()) { sqlite3_bind_null(stmt, idx); return; }+ if (v.isString()) { sqlite3_bind_text(stmt, idx, v.asString().c_str(), -1, SQLITE_TRANSIENT); return; }+ if (v.isInteger()) { sqlite3_bind_int64(stmt, idx, v.asInteger()); return; }+ if (v.isDouble()) { sqlite3_bind_double(stmt, idx, v.asDouble()); return; }+ if (v.isBoolean()) { sqlite3_bind_int(stmt, idx, v.asBoolean() ? 1 : 0); return; }+ if (v.isDate()) {+ const auto s = formatTimestampUtc(v.asDate());+ sqlite3_bind_text(stmt, idx, s.c_str(), -1, SQLITE_TRANSIENT);+ return;+ }+ if (v.isData()) {+ const auto& b = v.asData();+ sqlite3_bind_blob(stmt, idx, b.data(), static_cast<int>(b.size()), SQLITE_TRANSIENT);+ return;+ }+ if (v.isJson()) { sqlite3_bind_text(stmt, idx, v.asJson().c_str(), -1, SQLITE_TRANSIENT); return; }+ if (v.isUuid()) { sqlite3_bind_text(stmt, idx, v.asUuid().c_str(), -1, SQLITE_TRANSIENT); return; }+ // array / fallback: serialize via description+ const auto s = v.description();+ sqlite3_bind_text(stmt, idx, s.c_str(), -1, SQLITE_TRANSIENT);+}++RowValue readColumn(sqlite3_stmt* stmt, int idx) {+ switch (sqlite3_column_type(stmt, idx)) {+ case SQLITE_NULL: return RowValue::makeNull();+ case SQLITE_INTEGER: return RowValue::makeInteger(sqlite3_column_int64(stmt, idx));+ case SQLITE_FLOAT: return RowValue::makeDouble(sqlite3_column_double(stmt, idx));+ case SQLITE_TEXT: {+ const auto* txt = reinterpret_cast<const char*>(sqlite3_column_text(stmt, idx));+ const int n = sqlite3_column_bytes(stmt, idx);+ return RowValue::makeString(txt ? std::string(txt, static_cast<std::size_t>(n)) : std::string{});+ }+ case SQLITE_BLOB: {+ const int n = sqlite3_column_bytes(stmt, idx);+ const void* ptr = sqlite3_column_blob(stmt, idx);+ if (!ptr || n <= 0) return RowValue::makeNull();+ const auto* bytes = static_cast<const std::uint8_t*>(ptr);+ return RowValue::makeData(Bytes(bytes, bytes + n));+ }+ default: return RowValue::makeNull();+ }+}++std::string errorMessage(sqlite3* db) {+ if (!db) return "Unknown SQLite error";+ const auto* msg = sqlite3_errmsg(db);+ return msg ? std::string(msg) : std::string{};+}++}++SqliteAdapter::SqliteAdapter() = default;++SqliteAdapter::~SqliteAdapter() {+ std::lock_guard lock(mutex_);+ if (db_) {+ sqlite3_close_v2(db_);+ db_ = nullptr;+ }+ connected_.store(false, std::memory_order_release);+}++void SqliteAdapter::connect(const ConnectionConfig& config, const std::optional<std::string>& /*password*/) {+ if (!config.filePath || config.filePath->empty()) {+ throw ConnectionError("SQLite: no file path");+ }++ std::lock_guard lock(mutex_);+ if (db_) {+ sqlite3_close_v2(db_);+ db_ = nullptr;+ }++ const int flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;+ sqlite3* handle = nullptr;+ const int rc = sqlite3_open_v2(config.filePath->c_str(), &handle, flags, nullptr);+ if (rc != SQLITE_OK) {+ std::string msg = handle ? errorMessage(handle) : sqlite3_errstr(rc);+ sqlite3_close_v2(handle);+ throw ConnectionError("SQLite open failed: " + msg);+ }++ sqlite3_exec(handle, "PRAGMA journal_mode=WAL", nullptr, nullptr, nullptr);+ sqlite3_exec(handle, "PRAGMA foreign_keys=ON", nullptr, nullptr, nullptr);++ db_ = handle;+ filePath_ = *config.filePath;+ connected_.store(true, std::memory_order_release);+}++void SqliteAdapter::disconnect() {+ std::lock_guard lock(mutex_);+ if (db_) {+ sqlite3_close_v2(db_);+ db_ = nullptr;+ }+ filePath_.clear();+ connected_.store(false, std::memory_order_release);+}++bool SqliteAdapter::testConnection(const ConnectionConfig& config, const std::optional<std::string>& /*password*/) {+ if (!config.filePath || config.filePath->empty()) {+ throw ConnectionError("SQLite: no file path");+ }+ sqlite3* test = nullptr;+ const int rc = sqlite3_open_v2(config.filePath->c_str(), &test, SQLITE_OPEN_READONLY, nullptr);+ const bool ok = rc == SQLITE_OK;+ if (!ok) {+ std::string msg = test ? errorMessage(test) : sqlite3_errstr(rc);+ sqlite3_close_v2(test);+ throw ConnectionError("SQLite test failed: " + msg);+ }+ sqlite3_close_v2(test);+ return true;+}++void SqliteAdapter::ensureConnected() const {+ // connected_ is atomic; db_ is stable once connected_ is true under our mutex discipline.+ if (!connected_.load(std::memory_order_acquire) || !db_) {+ throw QueryError("Not connected to SQLite database");+ }+}++QueryResult SqliteAdapter::executeInternal(const std::string& sql, const std::vector<RowValue>& values) {+ ensureConnected();+ const auto start = std::chrono::steady_clock::now();++ std::lock_guard lock(mutex_);+ sqlite3_stmt* stmt = nullptr;+ if (sqlite3_prepare_v2(db_, sql.c_str(), -1, &stmt, nullptr) != SQLITE_OK || !stmt) {+ const auto msg = errorMessage(db_);+ if (stmt) sqlite3_finalize(stmt);+ throw QueryError("Prepare failed: " + msg);+ }++ struct Finalizer {+ sqlite3_stmt* s;+ ~Finalizer() { if (s) sqlite3_finalize(s); }+ } fin{stmt};++ for (std::size_t i = 0; i < values.size(); ++i) {+ bindRowValue(stmt, static_cast<int>(i + 1), values[i]);+ }++ const auto qt = detectQueryType(sql);++ QueryResult result;+ result.queryType = qt;++ if (qt == QueryType::Select) {+ const int colCount = sqlite3_column_count(stmt);+ result.columns.reserve(static_cast<std::size_t>(colCount));+ for (int i = 0; i < colCount; ++i) {+ ColumnHeader h;+ const auto* name = sqlite3_column_name(stmt, i);+ const auto* decl = sqlite3_column_decltype(stmt, i);+ h.name = name ? std::string(name) : std::string{};+ h.dataType = decl ? std::string(decl) : std::string{"TEXT"};+ result.columns.push_back(std::move(h));+ }++ while (true) {+ const int rc = sqlite3_step(stmt);+ if (rc == SQLITE_ROW) {+ std::vector<RowValue> row;+ row.reserve(static_cast<std::size_t>(colCount));+ for (int i = 0; i < colCount; ++i) row.push_back(readColumn(stmt, i));+ result.rows.push_back(std::move(row));+ continue;+ }+ if (rc == SQLITE_DONE) break;+ throw QueryError("Step failed: " + errorMessage(db_));+ }+ result.rowsAffected = static_cast<int>(result.rows.size());+ } else {+ const int rc = sqlite3_step(stmt);+ if (rc != SQLITE_DONE && rc != SQLITE_ROW) {+ throw QueryError("Execute failed: " + errorMessage(db_));+ }+ result.rowsAffected = sqlite3_changes(db_);+ }++ result.executionTime = std::chrono::steady_clock::now() - start;+ return result;+}++QueryResult SqliteAdapter::execute(const std::string& query, const std::vector<QueryParameter>& parameters) {+ std::vector<RowValue> values;+ values.reserve(parameters.size());+ for (const auto& p : parameters) values.push_back(p.value);+ return executeInternal(query, values);+}++QueryResult SqliteAdapter::executeRaw(const std::string& sql) {+ return executeInternal(sql, {});+}++std::string SqliteAdapter::lastBasename() const {+ if (filePath_.empty()) return "main";+ try {+ return std::filesystem::path(filePath_).filename().string();+ } catch (...) {+ return "main";+ }+}++std::vector<std::string> SqliteAdapter::listDatabases() {+ return {lastBasename()};+}++std::vector<std::string> SqliteAdapter::listSchemas(const std::optional<std::string>& /*database*/) {+ return {"main"};+}++std::vector<TableInfo> SqliteAdapter::listTables(const std::optional<std::string>& /*schema*/) {+ const auto r = executeRaw(+ "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name");+ std::vector<TableInfo> tables;+ tables.reserve(r.rows.size());+ for (const auto& row : r.rows) {+ if (row.empty() || !row[0].isString()) continue;+ TableInfo info;+ info.name = row[0].asString();+ info.type = TableKind::Table;+ try { info.estimatedRowCount = tableRowCount(info.name, std::nullopt); } catch (...) {}+ tables.push_back(std::move(info));+ }+ return tables;+}++std::vector<ViewInfo> SqliteAdapter::listViews(const std::optional<std::string>& /*schema*/) {+ const auto r = executeRaw("SELECT name, sql FROM sqlite_master WHERE type='view' ORDER BY name");+ std::vector<ViewInfo> views;+ views.reserve(r.rows.size());+ for (const auto& row : r.rows) {+ if (row.empty() || !row[0].isString()) continue;+ ViewInfo v;+ v.name = row[0].asString();+ if (row.size() > 1) {+ auto s = row[1].tryStringValue();+ if (s) v.definition = std::move(*s);+ }+ views.push_back(std::move(v));+ }+ return views;+}++std::vector<ColumnInfo> SqliteAdapter::describeColumns(const std::string& table) {+ const auto r = executeRaw("PRAGMA table_info(" + quoteIdent(table) + ")");+ std::vector<ColumnInfo> cols;+ cols.reserve(r.rows.size());+ for (std::size_t idx = 0; idx < r.rows.size(); ++idx) {+ const auto& row = r.rows[idx];+ ColumnInfo c;+ if (row.size() < 6) continue;+ c.name = row[1].tryStringValue().value_or(std::string{});+ c.dataType = row[2].tryStringValue().value_or(std::string{"TEXT"});+ c.isNullable = row[3].tryIntValue().value_or(0) == 0;+ if (!row[4].isNull()) c.defaultValue = row[4].tryStringValue();+ const bool pk = row[5].tryIntValue().value_or(0) != 0;+ c.isPrimaryKey = pk;+ std::string typeUpper = c.dataType;+ std::transform(typeUpper.begin(), typeUpper.end(), typeUpper.begin(),+ [](unsigned char ch){ return std::toupper(ch); });+ c.isAutoIncrement = pk && typeUpper == "INTEGER";+ c.ordinalPosition = static_cast<int>(row[0].tryIntValue().value_or(static_cast<std::int64_t>(idx)));+ cols.push_back(std::move(c));+ }+ return cols;+}++TableDescription SqliteAdapter::describeTable(const std::string& name,+ const std::optional<std::string>& /*schema*/) {+ TableDescription desc;+ desc.name = name;+ desc.columns = describeColumns(name);+ desc.indexes = listIndexes(name, std::nullopt);+ desc.foreignKeys = listForeignKeys(name, std::nullopt);+ try { desc.estimatedRowCount = tableRowCount(name, std::nullopt); } catch (...) {}+ return desc;+}++std::vector<IndexInfo> SqliteAdapter::listIndexes(const std::string& table,+ const std::optional<std::string>& /*schema*/) {+ std::string escaped;+ escaped.reserve(table.size());+ for (char c : table) {+ if (c == '\'') escaped.push_back('\'');+ escaped.push_back(c);+ }+ const std::string sql =+ "SELECT il.name, il.\"unique\", GROUP_CONCAT(ii.name) "+ "FROM pragma_index_list('" + escaped + "') il "+ "JOIN pragma_index_info(il.name) ii "+ "GROUP BY il.name, il.\"unique\" ORDER BY il.name, ii.seqno";+ const auto r = executeRaw(sql);+ std::vector<IndexInfo> out;+ out.reserve(r.rows.size());+ for (const auto& row : r.rows) {+ if (row.size() < 3) continue;+ IndexInfo idx;+ idx.name = row[0].tryStringValue().value_or(std::string{});+ idx.isUnique = row[1].tryStringValue().value_or("0") == "1";+ const auto cols = row[2].tryStringValue().value_or(std::string{});+ std::string cur;+ for (char c : cols) {+ if (c == ',') { if (!cur.empty()) idx.columns.push_back(std::move(cur)); cur.clear(); }+ else cur.push_back(c);+ }+ if (!cur.empty()) idx.columns.push_back(std::move(cur));+ idx.type = std::string{"btree"};+ idx.tableName = table;+ out.push_back(std::move(idx));+ }+ return out;+}++std::vector<ForeignKeyInfo> SqliteAdapter::listForeignKeys(const std::string& table,+ const std::optional<std::string>& /*schema*/) {+ const auto r = executeRaw("PRAGMA foreign_key_list(" + quoteIdent(table) + ")");+ std::vector<ForeignKeyInfo> out;+ out.reserve(r.rows.size());++ auto parseAction = [](std::string_view s) {+ if (s == "CASCADE") return ForeignKeyAction::Cascade;+ if (s == "SET NULL") return ForeignKeyAction::SetNull;+ if (s == "SET DEFAULT") return ForeignKeyAction::SetDefault;+ if (s == "RESTRICT") return ForeignKeyAction::Restrict;+ return ForeignKeyAction::NoAction;+ };++ for (const auto& row : r.rows) {+ if (row.size() < 7) continue;+ ForeignKeyInfo fk;+ fk.columns.push_back(row[3].tryStringValue().value_or(std::string{}));+ fk.referencedTable = row[2].tryStringValue().value_or(std::string{});+ fk.referencedColumns.push_back(row[4].tryStringValue().value_or(std::string{}));+ fk.onUpdate = parseAction(row[5].tryStringValue().value_or("NO ACTION"));+ fk.onDelete = parseAction(row[6].tryStringValue().value_or("NO ACTION"));+ out.push_back(std::move(fk));+ }+ return out;+}++std::vector<std::string> SqliteAdapter::listFunctions(const std::optional<std::string>& /*schema*/) {+ return {};+}++std::string SqliteAdapter::getFunctionSource(const std::string& /*name*/,+ const std::optional<std::string>& /*schema*/) {+ throw QueryError("SQLite does not support stored functions");+}++QueryResult SqliteAdapter::insertRow(const std::string& table,+ const std::optional<std::string>& /*schema*/,+ const std::unordered_map<std::string, RowValue>& values) {+ if (values.empty()) throw QueryError("insertRow: values map is empty");+ std::string cols, placeholders;+ std::vector<QueryParameter> params;+ params.reserve(values.size());+ bool first = true;+ for (const auto& [k, v] : values) {+ if (!first) { cols += ", "; placeholders += ", "; }+ cols += quoteIdent(k);+ placeholders += "?";+ params.emplace_back(v);+ first = false;+ }+ return execute("INSERT INTO " + quoteIdent(table) + " (" + cols + ") VALUES (" + placeholders + ")",+ params);+}++QueryResult SqliteAdapter::updateRow(const std::string& table,+ const std::optional<std::string>& /*schema*/,+ const std::unordered_map<std::string, RowValue>& set,+ const std::unordered_map<std::string, RowValue>& where) {+ if (set.empty() || where.empty()) throw QueryError("updateRow: set or where is empty");+ std::string setClause, whereClause;+ std::vector<QueryParameter> params;+ params.reserve(set.size() + where.size());++ bool first = true;+ for (const auto& [k, v] : set) {+ if (!first) setClause += ", ";+ setClause += quoteIdent(k) + " = ?";+ params.emplace_back(v);+ first = false;+ }+ first = true;+ for (const auto& [k, v] : where) {+ if (!first) whereClause += " AND ";+ whereClause += quoteIdent(k) + " = ?";+ params.emplace_back(v);+ first = false;+ }+ return execute("UPDATE " + quoteIdent(table) + " SET " + setClause + " WHERE " + whereClause, params);+}++QueryResult SqliteAdapter::deleteRow(const std::string& table,+ const std::optional<std::string>& /*schema*/,+ const std::unordered_map<std::string, RowValue>& where) {+ if (where.empty()) throw QueryError("deleteRow: where is empty");+ std::string whereClause;+ std::vector<QueryParameter> params;+ params.reserve(where.size());+ bool first = true;+ for (const auto& [k, v] : where) {+ if (!first) whereClause += " AND ";+ whereClause += quoteIdent(k) + " = ?";+ params.emplace_back(v);+ first = false;+ }+ return execute("DELETE FROM " + quoteIdent(table) + " WHERE " + whereClause, params);+}++void SqliteAdapter::beginTransaction() { (void)executeRaw("BEGIN TRANSACTION"); }+void SqliteAdapter::commitTransaction() { (void)executeRaw("COMMIT"); }+void SqliteAdapter::rollbackTransaction() { (void)executeRaw("ROLLBACK"); }++QueryResult SqliteAdapter::fetchRows(const std::string& table,+ const std::optional<std::string>& /*schema*/,+ const std::optional<std::vector<std::string>>& columns,+ const std::optional<FilterExpression>& where,+ const std::optional<std::vector<QuerySortDescriptor>>& orderBy,+ int limit, int offset) {+ std::string colList = "*";+ if (columns && !columns->empty()) {+ colList.clear();+ for (std::size_t i = 0; i < columns->size(); ++i) {+ if (i > 0) colList += ", ";+ colList += quoteIdent((*columns)[i]);+ }+ }+ std::string sql = "SELECT " + colList + " FROM " + quoteIdent(table);+ if (where && !where->conditions.empty()) {+ sql += " WHERE " + where->toSQL(SQLDialect::SQLite);+ }+ if (orderBy && !orderBy->empty()) {+ sql += " ORDER BY ";+ for (std::size_t i = 0; i < orderBy->size(); ++i) {+ if (i > 0) sql += ", ";+ sql += (*orderBy)[i].toSQL(SQLDialect::SQLite);+ }+ }+ sql += " LIMIT " + std::to_string(limit) + " OFFSET " + std::to_string(offset);+ return executeRaw(sql);+}++std::string SqliteAdapter::serverVersion() {+ const auto r = executeRaw("SELECT sqlite_version()");+ if (r.rows.empty() || r.rows[0].empty()) return "SQLite";+ const auto v = r.rows[0][0].tryStringValue().value_or(std::string{});+ return "SQLite " + v;+}++std::optional<std::string> SqliteAdapter::currentDatabase() {+ if (filePath_.empty()) return std::nullopt;+ return filePath_;+}++SchemaSnapshot SqliteAdapter::fullSchemaSnapshot(const std::optional<std::string>& /*database*/) {+ SchemaSnapshot snap;+ snap.databaseName = lastBasename();+ snap.databaseType = DatabaseType::SQLite;+ snap.capturedAt = std::chrono::system_clock::now();++ const auto tables = listTables(std::nullopt);+ SchemaInfo main;+ main.name = "main";+ main.tables.reserve(tables.size());+ for (const auto& t : tables) {+ main.tables.push_back(describeTable(t.name, std::nullopt));+ }+ main.views = listViews(std::nullopt);+ snap.schemas.push_back(std::move(main));+ return snap;+}++std::vector<ColumnStatistics> SqliteAdapter::columnStatistics(const std::string& table,+ const std::optional<std::string>& /*schema*/,+ int /*sampleSize*/) {+ const auto cols = describeColumns(table);+ std::vector<ColumnStatistics> stats;+ stats.reserve(cols.size());+ for (const auto& c : cols) {+ const auto qc = quoteIdent(c.name);+ const auto sql =+ "SELECT COUNT(DISTINCT " + qc + "), "+ "CAST(SUM(CASE WHEN " + qc + " IS NULL THEN 1 ELSE 0 END) AS REAL) / NULLIF(COUNT(*), 0), "+ "MIN(" + qc + "), MAX(" + qc + ") FROM " + quoteIdent(table);+ const auto r = executeRaw(sql);+ if (r.rows.empty()) continue;+ const auto& row = r.rows[0];+ if (row.size() < 4) continue;+ ColumnStatistics cs;+ cs.columnName = c.name;+ if (auto n = row[0].tryIntValue()) cs.distinctCount = static_cast<int>(*n);+ if (auto d = row[1].tryDoubleValue()) cs.nullRatio = *d;+ cs.minValue = row[2].tryStringValue();+ cs.maxValue = row[3].tryStringValue();+ stats.push_back(std::move(cs));+ }+ return stats;+}++int SqliteAdapter::tableRowCount(const std::string& table, const std::optional<std::string>& /*schema*/) {+ const auto r = executeRaw("SELECT COUNT(*) FROM " + quoteIdent(table));+ if (r.rows.empty() || r.rows[0].empty()) return 0;+ return static_cast<int>(r.rows[0][0].tryIntValue().value_or(0));+}++std::optional<std::int64_t> SqliteAdapter::tableSizeBytes(const std::string& /*table*/,+ const std::optional<std::string>& /*schema*/) {+ return std::nullopt;+}++std::vector<QueryStatisticsEntry> SqliteAdapter::queryStatistics() { return {}; }++std::vector<std::string> SqliteAdapter::primaryKeyColumns(const std::string& table,+ const std::optional<std::string>& /*schema*/) {+ const auto r = executeRaw("PRAGMA table_info(" + quoteIdent(table) + ")");+ std::vector<std::string> cols;+ for (const auto& row : r.rows) {+ if (row.size() < 6) continue;+ const auto pk = row[5].tryIntValue().value_or(0);+ if (pk > 0) {+ if (auto n = row[1].tryStringValue()) cols.push_back(std::move(*n));+ }+ }+ return cols;+}++}diff --git a/linux/src/Data/Adapters/SQLite/SqliteAdapter.h b/linux/src/Data/Adapters/SQLite/SqliteAdapter.hnew file mode 100644index 0000000..8147d8a--- /dev/null+++ b/linux/src/Data/Adapters/SQLite/SqliteAdapter.h@@ -0,0 +1,99 @@+#pragma once++#include <atomic>+#include <memory>+#include <mutex>+#include <optional>+#include <string>++#include "Core/Protocols/Database/IDatabaseAdapter.h"+#include "Core/Protocols/Database/ISchemaInspectable.h"++struct sqlite3;++namespace gridex {++// SQLite adapter using the sqlite3 C API.+// Thread-safe: opens with SQLITE_OPEN_FULLMUTEX so concurrent calls are serialized inside the lib.+// A separate std::mutex protects adapter-owned state (db pointer, connection flag).+class SqliteAdapter final : public IDatabaseAdapter, public ISchemaInspectable {+public:+ SqliteAdapter();+ ~SqliteAdapter() override;++ SqliteAdapter(const SqliteAdapter&) = delete;+ SqliteAdapter& operator=(const SqliteAdapter&) = delete;++ // IDatabaseAdapter+ [[nodiscard]] DatabaseType databaseType() const noexcept override { return DatabaseType::SQLite; }+ [[nodiscard]] bool isConnected() const noexcept override { return connected_; }++ void connect(const ConnectionConfig& config, const std::optional<std::string>& password) override;+ void disconnect() override;+ bool testConnection(const ConnectionConfig& config, const std::optional<std::string>& password) override;++ QueryResult execute(const std::string& query, const std::vector<QueryParameter>& parameters) override;+ QueryResult executeRaw(const std::string& sql) override;++ std::vector<std::string> listDatabases() override;+ std::vector<std::string> listSchemas(const std::optional<std::string>& database) override;+ std::vector<TableInfo> listTables(const std::optional<std::string>& schema) override;+ std::vector<ViewInfo> listViews(const std::optional<std::string>& schema) override;+ TableDescription describeTable(const std::string& name,+ const std::optional<std::string>& schema) override;+ std::vector<IndexInfo> listIndexes(const std::string& table,+ const std::optional<std::string>& schema) override;+ std::vector<ForeignKeyInfo> listForeignKeys(const std::string& table,+ const std::optional<std::string>& schema) override;+ std::vector<std::string> listFunctions(const std::optional<std::string>& schema) override;+ std::string getFunctionSource(const std::string& name,+ const std::optional<std::string>& schema) override;++ QueryResult insertRow(const std::string& table, const std::optional<std::string>& schema,+ const std::unordered_map<std::string, RowValue>& values) override;+ QueryResult updateRow(const std::string& table, const std::optional<std::string>& schema,+ const std::unordered_map<std::string, RowValue>& set,+ const std::unordered_map<std::string, RowValue>& where) override;+ QueryResult deleteRow(const std::string& table, const std::optional<std::string>& schema,+ const std::unordered_map<std::string, RowValue>& where) override;++ void beginTransaction() override;+ void commitTransaction() override;+ void rollbackTransaction() override;++ QueryResult fetchRows(const std::string& table,+ const std::optional<std::string>& schema,+ const std::optional<std::vector<std::string>>& columns,+ const std::optional<FilterExpression>& where,+ const std::optional<std::vector<QuerySortDescriptor>>& orderBy,+ int limit, int offset) override;++ std::string serverVersion() override;+ std::optional<std::string> currentDatabase() override;++ // ISchemaInspectable+ SchemaSnapshot fullSchemaSnapshot(const std::optional<std::string>& database) override;+ std::vector<ColumnStatistics> columnStatistics(const std::string& table,+ const std::optional<std::string>& schema,+ int sampleSize) override;+ int tableRowCount(const std::string& table,+ const std::optional<std::string>& schema) override;+ std::optional<std::int64_t> tableSizeBytes(const std::string& table,+ const std::optional<std::string>& schema) override;+ std::vector<QueryStatisticsEntry> queryStatistics() override;+ std::vector<std::string> primaryKeyColumns(const std::string& table,+ const std::optional<std::string>& schema) override;++private:+ QueryResult executeInternal(const std::string& sql, const std::vector<RowValue>& values);+ std::vector<ColumnInfo> describeColumns(const std::string& table);+ void ensureConnected() const;+ std::string lastBasename() const;++ sqlite3* db_ = nullptr;+ std::string filePath_; // empty when disconnected+ std::atomic<bool> connected_{false}; // race-free read in isConnected/ensureConnected+ mutable std::mutex mutex_;+};++}diff --git a/linux/src/Data/CMakeLists.txt b/linux/src/Data/CMakeLists.txtnew file mode 100644index 0000000..a799338--- /dev/null+++ b/linux/src/Data/CMakeLists.txt@@ -0,0 +1,65 @@+find_package(PkgConfig REQUIRED)+pkg_check_modules(SQLITE3 REQUIRED IMPORTED_TARGET sqlite3)+pkg_check_modules(LIBSECRET REQUIRED IMPORTED_TARGET libsecret-1)+pkg_check_modules(LIBPQ REQUIRED IMPORTED_TARGET libpq)+pkg_check_modules(LIBMARIADB REQUIRED IMPORTED_TARGET libmariadb)+pkg_check_modules(HIREDIS REQUIRED IMPORTED_TARGET hiredis)++# ---------------------------------------------------------------------------+# mongo-c-driver (libmongoc + libbson) — required by mongo-cxx-driver+# ---------------------------------------------------------------------------+include(FetchContent)++FetchContent_Declare(mongo-c-driver+ GIT_REPOSITORY https://github.com/mongodb/mongo-c-driver.git+ GIT_TAG 1.27.1+ GIT_SHALLOW TRUE+)+set(ENABLE_TESTS OFF CACHE BOOL "" FORCE)+set(ENABLE_EXAMPLES OFF CACHE BOOL "" FORCE)+set(ENABLE_AUTOMATIC_INIT_AND_CLEANUP OFF CACHE BOOL "" FORCE)+FetchContent_MakeAvailable(mongo-c-driver)++# ---------------------------------------------------------------------------+# mongo-cxx-driver (mongocxx / bsoncxx)+# ---------------------------------------------------------------------------+FetchContent_Declare(mongo-cxx-driver+ GIT_REPOSITORY https://github.com/mongodb/mongo-cxx-driver.git+ GIT_TAG r3.10.1+ GIT_SHALLOW TRUE+)+set(BUILD_TESTING OFF CACHE BOOL "" FORCE)+FetchContent_MakeAvailable(mongo-cxx-driver)++add_library(gridex-data STATIC+ Adapters/AdapterFactory.cpp+ Adapters/MSSQL/MssqlAdapter.cpp+ Adapters/MySQL/MysqlAdapter.cpp+ Adapters/MongoDB/MongodbAdapter.cpp+ Adapters/PostgreSQL/PostgresAdapter.cpp+ Adapters/Redis/RedisAdapter.cpp+ Adapters/SQLite/SqliteAdapter.cpp+ Keychain/SecretStore.cpp+ Persistence/AppConnectionRepository.cpp+ Persistence/AppDatabase.cpp+ Persistence/SavedQueryRepository.cpp+)++target_include_directories(gridex-data PUBLIC+ ${CMAKE_CURRENT_SOURCE_DIR}/..+)++target_link_libraries(gridex-data+ PUBLIC gridex-core+ PRIVATE+ PkgConfig::SQLITE3+ PkgConfig::LIBSECRET+ PkgConfig::LIBPQ+ PkgConfig::LIBMARIADB+ PkgConfig::HIREDIS+ sybdb+ # When consumed via FetchContent the targets live in the build scope without+ # the "mongo::" namespace prefix (that prefix is only created after install).+ # Use a generator expression to prefer static when available.+ $<IF:$<TARGET_EXISTS:mongocxx_static>,mongocxx_static,mongocxx_shared>+)diff --git a/linux/src/Data/Keychain/SecretStore.cpp b/linux/src/Data/Keychain/SecretStore.cppnew file mode 100644index 0000000..0b1cedb--- /dev/null+++ b/linux/src/Data/Keychain/SecretStore.cpp@@ -0,0 +1,110 @@+#include "Data/Keychain/SecretStore.h"++#include <libsecret/secret.h>+#include <stdexcept>+#include <string>+#include <utility>++#include "Core/Errors/GridexError.h"++namespace gridex {++namespace {++// Schema used for all Gridex credentials. Stored attributes are:+// "service" = logical service name (e.g. com.gridex.credentials)+// "account" = key name (e.g. db.password.<connection-id>)+const SecretSchema* gridexSchema() {+ static const SecretSchema schema = {+ "com.gridex.Secret",+ SECRET_SCHEMA_NONE,+ {+ { "service", SECRET_SCHEMA_ATTRIBUTE_STRING },+ { "account", SECRET_SCHEMA_ATTRIBUTE_STRING },+ { nullptr, SECRET_SCHEMA_ATTRIBUTE_STRING },+ },+ 0, 0, 0, 0, 0, 0, 0, 0+ };+ return &schema;+}++[[noreturn]] void throwFromGError(const std::string& ctx, GError* err) {+ std::string msg = ctx;+ if (err) {+ msg += ": ";+ msg += err->message ? err->message : "unknown libsecret error";+ g_error_free(err);+ } else {+ msg += ": operation returned failure with no detail (is the Secret Service daemon running?)";+ }+ throw InternalError(msg);+}++}++SecretStore::SecretStore() : serviceName_("com.gridex.credentials") {}++SecretStore::SecretStore(std::string serviceName) : serviceName_(std::move(serviceName)) {}++bool SecretStore::isAvailable() {+ // Probe by doing a harmless lookup on a reserved key. We don't cache across+ // process restarts; a single in-process static would mask a user switching+ // keyring daemons, which is rare but possible.+ GError* err = nullptr;+ gchar* value = secret_password_lookup_sync(+ gridexSchema(), nullptr, &err,+ "service", serviceName_.c_str(),+ "account", "__gridex_probe__",+ nullptr);+ if (err) { g_error_free(err); return false; }+ if (value) g_free(value);+ return true;+}++void SecretStore::save(std::string_view key, std::string_view value) {+ const std::string account(key);+ const std::string password(value);+ const std::string label = "Gridex: " + account;++ GError* err = nullptr;+ const gboolean ok = secret_password_store_sync(+ gridexSchema(),+ SECRET_COLLECTION_DEFAULT,+ label.c_str(),+ password.c_str(),+ nullptr,+ &err,+ "service", serviceName_.c_str(),+ "account", account.c_str(),+ nullptr);+ if (!ok || err) throwFromGError("SecretStore::save", err);+}++std::optional<std::string> SecretStore::load(std::string_view key) {+ const std::string account(key);+ GError* err = nullptr;+ gchar* raw = secret_password_lookup_sync(+ gridexSchema(), nullptr, &err,+ "service", serviceName_.c_str(),+ "account", account.c_str(),+ nullptr);+ if (err) throwFromGError("SecretStore::load", err);+ if (!raw) return std::nullopt;++ std::string out(raw);+ secret_password_free(raw);+ return out;+}++void SecretStore::remove(std::string_view key) {+ const std::string account(key);+ GError* err = nullptr;+ secret_password_clear_sync(+ gridexSchema(), nullptr, &err,+ "service", serviceName_.c_str(),+ "account", account.c_str(),+ nullptr);+ if (err) throwFromGError("SecretStore::remove", err);+}++}diff --git a/linux/src/Data/Keychain/SecretStore.h b/linux/src/Data/Keychain/SecretStore.hnew file mode 100644index 0000000..9ba89ef--- /dev/null+++ b/linux/src/Data/Keychain/SecretStore.h@@ -0,0 +1,60 @@+#pragma once++#include <optional>+#include <string>+#include <string_view>++namespace gridex {++// libsecret-backed credential store. Mirrors macos KeychainService semantics.+// Keys are scoped by service name "com.gridex.credentials". The store delegates+// to the Secret Service daemon (GNOME Keyring / KWallet). If no daemon is+// available (e.g. headless/WSL) operations throw gridex::GridexError.+class SecretStore {+public:+ SecretStore();+ explicit SecretStore(std::string serviceName);++ // Store / update a password under the given account key.+ void save(std::string_view key, std::string_view value);++ // Returns std::nullopt when the key is absent.+ [[nodiscard]] std::optional<std::string> load(std::string_view key);++ // No-op if the key is absent.+ void remove(std::string_view key);++ // Probes availability once per process. Returns false if Secret Service is+ // missing (headless/WSL). Callers can decide to degrade gracefully.+ [[nodiscard]] bool isAvailable();++ // Convenience keys matching macOS layout.+ void savePassword(std::string_view connectionId, std::string_view password) {+ save("db.password." + std::string(connectionId), password);+ }+ std::optional<std::string> loadPassword(std::string_view connectionId) {+ return load("db.password." + std::string(connectionId));+ }+ void removePassword(std::string_view connectionId) {+ remove("db.password." + std::string(connectionId));+ }++ void saveSSHPassword(std::string_view connectionId, std::string_view password) {+ save("ssh.password." + std::string(connectionId), password);+ }+ std::optional<std::string> loadSSHPassword(std::string_view connectionId) {+ return load("ssh.password." + std::string(connectionId));+ }++ void saveAPIKey(std::string_view provider, std::string_view key) {+ save("ai.apikey." + std::string(provider), key);+ }+ std::optional<std::string> loadAPIKey(std::string_view provider) {+ return load("ai.apikey." + std::string(provider));+ }++private:+ std::string serviceName_;+};++}diff --git a/linux/src/Data/Persistence/AppConnectionRepository.cpp b/linux/src/Data/Persistence/AppConnectionRepository.cppnew file mode 100644index 0000000..076ac26--- /dev/null+++ b/linux/src/Data/Persistence/AppConnectionRepository.cpp@@ -0,0 +1,56 @@+#include "Data/Persistence/AppConnectionRepository.h"++#include <chrono>+#include <utility>++#include "Core/Errors/GridexError.h"+#include "Core/Models/Database/ConnectionConfigJson.h"++namespace gridex {++AppConnectionRepository::AppConnectionRepository(std::shared_ptr<AppDatabase> db)+ : db_(std::move(db)) {+ if (!db_) throw InternalError("AppConnectionRepository: null AppDatabase");+}++std::vector<ConnectionConfig> AppConnectionRepository::fetchAll() {+ const auto records = db_->listConnections();+ std::vector<ConnectionConfig> out;+ out.reserve(records.size());+ for (const auto& r : records) {+ try { out.push_back(json::decode(r.configJson)); }+ catch (const GridexError&) { /* skip malformed row */ }+ }+ return out;+}++std::optional<ConnectionConfig> AppConnectionRepository::fetchById(const std::string& id) {+ const auto rec = db_->getConnection(id);+ if (!rec) return std::nullopt;+ return json::decode(rec->configJson);+}++std::vector<ConnectionConfig> AppConnectionRepository::fetchByGroup(const std::string& group) {+ auto all = fetchAll();+ std::vector<ConnectionConfig> out;+ for (auto& c : all) {+ if (c.group && *c.group == group) out.push_back(std::move(c));+ }+ return out;+}++void AppConnectionRepository::save(const ConnectionConfig& config) {+ AppDatabase::ConnectionRecord rec;+ rec.id = config.id;+ rec.name = config.name;+ rec.databaseType = std::string(rawValue(config.databaseType));+ rec.configJson = json::encode(config);+ rec.updatedAt = std::chrono::system_clock::now();+ db_->upsertConnection(rec);+}++void AppConnectionRepository::remove(const std::string& id) {+ db_->deleteConnection(id);+}++}diff --git a/linux/src/Data/Persistence/AppConnectionRepository.h b/linux/src/Data/Persistence/AppConnectionRepository.hnew file mode 100644index 0000000..dce44ca--- /dev/null+++ b/linux/src/Data/Persistence/AppConnectionRepository.h@@ -0,0 +1,26 @@+#pragma once++#include <memory>++#include "Data/Persistence/AppDatabase.h"+#include "Domain/Repositories/IConnectionRepository.h"++namespace gridex {++// IConnectionRepository backed by AppDatabase + hand-rolled JSON serializer.+// Secrets are NOT stored here — use SecretStore keyed by ConnectionConfig::id.+class AppConnectionRepository final : public IConnectionRepository {+public:+ explicit AppConnectionRepository(std::shared_ptr<AppDatabase> db);++ std::vector<ConnectionConfig> fetchAll() override;+ std::optional<ConnectionConfig> fetchById(const std::string& id) override;+ std::vector<ConnectionConfig> fetchByGroup(const std::string& group) override;+ void save(const ConnectionConfig& config) override;+ void remove(const std::string& id) override;++private:+ std::shared_ptr<AppDatabase> db_;+};++}diff --git a/linux/src/Data/Persistence/AppDatabase.cpp b/linux/src/Data/Persistence/AppDatabase.cppnew file mode 100644index 0000000..e472b6e--- /dev/null+++ b/linux/src/Data/Persistence/AppDatabase.cpp@@ -0,0 +1,472 @@+#include "Data/Persistence/AppDatabase.h"++#include <cstdlib>+#include <filesystem>+#include <sqlite3.h>+#include <stdexcept>++#include "Core/Errors/GridexError.h"++namespace gridex {++namespace {++std::int64_t timePointToUnix(std::chrono::system_clock::time_point tp) {+ return std::chrono::duration_cast<std::chrono::seconds>(tp.time_since_epoch()).count();+}++std::chrono::system_clock::time_point unixToTimePoint(std::int64_t secs) {+ return std::chrono::system_clock::time_point{std::chrono::seconds{secs}};+}++std::string errmsg(sqlite3* db) {+ const auto* m = db ? sqlite3_errmsg(db) : nullptr;+ return m ? std::string(m) : std::string{"unknown"};+}++void exec(sqlite3* db, const char* sql) {+ char* err = nullptr;+ if (sqlite3_exec(db, sql, nullptr, nullptr, &err) != SQLITE_OK) {+ std::string msg = err ? std::string(err) : errmsg(db);+ if (err) sqlite3_free(err);+ throw InternalError("AppDatabase exec failed: " + msg);+ }+}++// Null-safe text column read. Returns "" when the column is SQL NULL — avoids+// UB from std::string(nullptr) if a future migration adds a nullable TEXT col.+std::string safeText(sqlite3_stmt* stmt, int col) {+ const auto* v = sqlite3_column_text(stmt, col);+ return v ? std::string(reinterpret_cast<const char*>(v)) : std::string{};+}++}++std::string AppDatabase::defaultPath() {+ const char* xdg = std::getenv("XDG_DATA_HOME");+ const char* home = std::getenv("HOME");+ std::filesystem::path base;+ if (xdg && *xdg) base = xdg;+ else if (home && *home) base = std::filesystem::path(home) / ".local" / "share";+ else base = std::filesystem::current_path();+ base /= "gridex";+ std::error_code ec;+ std::filesystem::create_directories(base, ec);+ return (base / "app.sqlite").string();+}++AppDatabase::AppDatabase() = default;++AppDatabase::~AppDatabase() {+ close();+}++void AppDatabase::open(const std::string& path) {+ std::lock_guard lock(mutex_);+ if (db_) {+ sqlite3_close_v2(db_);+ db_ = nullptr;+ }++ path_ = path.empty() ? defaultPath() : path;+ const int flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;+ if (sqlite3_open_v2(path_.c_str(), &db_, flags, nullptr) != SQLITE_OK) {+ const std::string msg = errmsg(db_);+ sqlite3_close_v2(db_);+ db_ = nullptr;+ throw InternalError("AppDatabase open failed: " + msg);+ }++ exec(db_, "PRAGMA journal_mode=WAL");+ exec(db_, "PRAGMA foreign_keys=ON");+ applyMigrations();+}++void AppDatabase::close() {+ std::lock_guard lock(mutex_);+ if (db_) {+ sqlite3_close_v2(db_);+ db_ = nullptr;+ }+}++void AppDatabase::applyMigrations() {+ // schema_version table tracks forward migrations so future versions know+ // what is already applied. Always created first; each migration adds a row.+ exec(db_,+ "CREATE TABLE IF NOT EXISTS schema_version ("+ " version INTEGER PRIMARY KEY,"+ " applied_at INTEGER NOT NULL"+ ")");+ exec(db_,+ "CREATE TABLE IF NOT EXISTS connections ("+ " id TEXT PRIMARY KEY,"+ " name TEXT NOT NULL,"+ " database_type TEXT NOT NULL,"+ " config_json TEXT NOT NULL,"+ " updated_at INTEGER NOT NULL"+ ")");+ exec(db_,+ "CREATE TABLE IF NOT EXISTS history ("+ " id INTEGER PRIMARY KEY AUTOINCREMENT,"+ " connection_id TEXT NOT NULL,"+ " sql TEXT NOT NULL,"+ " executed_at INTEGER NOT NULL,"+ " duration_ms INTEGER NOT NULL DEFAULT 0,"+ " succeeded INTEGER NOT NULL DEFAULT 1"+ ")");+ exec(db_,+ "CREATE INDEX IF NOT EXISTS idx_history_conn_time "+ "ON history(connection_id, executed_at DESC)");+ exec(db_,+ "CREATE TABLE IF NOT EXISTS settings ("+ " key TEXT PRIMARY KEY,"+ " value TEXT NOT NULL"+ ")");++ const auto now = std::to_string(+ std::chrono::duration_cast<std::chrono::seconds>(+ std::chrono::system_clock::now().time_since_epoch()).count());++ // Mark v1 as applied (idempotent).+ exec(db_, ("INSERT OR IGNORE INTO schema_version(version, applied_at) VALUES(1, " + now + ")").c_str());++ // v2: add row_count to history, saved_queries table, group_name to connections+ sqlite3_stmt* verStmt = nullptr;+ bool v2Applied = false;+ if (sqlite3_prepare_v2(db_, "SELECT 1 FROM schema_version WHERE version=2", -1, &verStmt, nullptr) == SQLITE_OK) {+ v2Applied = sqlite3_step(verStmt) == SQLITE_ROW;+ sqlite3_finalize(verStmt);+ }+ if (!v2Applied) {+ // Add row_count column to history (ignore if already exists)+ sqlite3_exec(db_, "ALTER TABLE history ADD COLUMN row_count INTEGER NOT NULL DEFAULT 0", nullptr, nullptr, nullptr);+ // Add group_name column to connections+ sqlite3_exec(db_, "ALTER TABLE connections ADD COLUMN group_name TEXT", nullptr, nullptr, nullptr);+ exec(db_,+ "CREATE TABLE IF NOT EXISTS saved_queries ("+ " id TEXT PRIMARY KEY,"+ " connection_id TEXT,"+ " group_name TEXT NOT NULL DEFAULT '',"+ " name TEXT NOT NULL,"+ " sql TEXT NOT NULL,"+ " created_at INTEGER NOT NULL,"+ " updated_at INTEGER NOT NULL"+ ")");+ exec(db_, ("INSERT OR IGNORE INTO schema_version(version, applied_at) VALUES(2, " + now + ")").c_str());+ }+}++void AppDatabase::upsertConnection(const ConnectionRecord& rec) {+ std::lock_guard lock(mutex_);+ if (!db_) throw InternalError("AppDatabase not open");++ const char* sql =+ "INSERT INTO connections(id, name, database_type, config_json, updated_at) "+ "VALUES(?1, ?2, ?3, ?4, ?5) "+ "ON CONFLICT(id) DO UPDATE SET "+ " name=excluded.name,"+ " database_type=excluded.database_type,"+ " config_json=excluded.config_json,"+ " updated_at=excluded.updated_at";+ sqlite3_stmt* stmt = nullptr;+ if (sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr) != SQLITE_OK) {+ throw InternalError("upsertConnection prepare: " + errmsg(db_));+ }+ sqlite3_bind_text(stmt, 1, rec.id.c_str(), -1, SQLITE_TRANSIENT);+ sqlite3_bind_text(stmt, 2, rec.name.c_str(), -1, SQLITE_TRANSIENT);+ sqlite3_bind_text(stmt, 3, rec.databaseType.c_str(), -1, SQLITE_TRANSIENT);+ sqlite3_bind_text(stmt, 4, rec.configJson.c_str(), -1, SQLITE_TRANSIENT);+ sqlite3_bind_int64(stmt, 5, timePointToUnix(rec.updatedAt));+ const int rc = sqlite3_step(stmt);+ sqlite3_finalize(stmt);+ if (rc != SQLITE_DONE) {+ throw InternalError("upsertConnection step: " + errmsg(db_));+ }+}++std::vector<AppDatabase::ConnectionRecord> AppDatabase::listConnections() {+ std::lock_guard lock(mutex_);+ if (!db_) throw InternalError("AppDatabase not open");++ const char* sql =+ "SELECT id, name, database_type, config_json, updated_at FROM connections ORDER BY name";+ sqlite3_stmt* stmt = nullptr;+ if (sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr) != SQLITE_OK) {+ throw InternalError("listConnections prepare: " + errmsg(db_));+ }+ std::vector<ConnectionRecord> out;+ while (sqlite3_step(stmt) == SQLITE_ROW) {+ ConnectionRecord r;+ r.id = safeText(stmt, 0);+ r.name = safeText(stmt, 1);+ r.databaseType = safeText(stmt, 2);+ r.configJson = safeText(stmt, 3);+ r.updatedAt = unixToTimePoint(sqlite3_column_int64(stmt, 4));+ out.push_back(std::move(r));+ }+ sqlite3_finalize(stmt);+ return out;+}++std::optional<AppDatabase::ConnectionRecord> AppDatabase::getConnection(const std::string& id) {+ std::lock_guard lock(mutex_);+ if (!db_) throw InternalError("AppDatabase not open");++ const char* sql =+ "SELECT id, name, database_type, config_json, updated_at FROM connections WHERE id = ?1";+ sqlite3_stmt* stmt = nullptr;+ if (sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr) != SQLITE_OK) {+ throw InternalError("getConnection prepare: " + errmsg(db_));+ }+ sqlite3_bind_text(stmt, 1, id.c_str(), -1, SQLITE_TRANSIENT);+ std::optional<ConnectionRecord> out;+ if (sqlite3_step(stmt) == SQLITE_ROW) {+ ConnectionRecord r;+ r.id = safeText(stmt, 0);+ r.name = safeText(stmt, 1);+ r.databaseType = safeText(stmt, 2);+ r.configJson = safeText(stmt, 3);+ r.updatedAt = unixToTimePoint(sqlite3_column_int64(stmt, 4));+ out = std::move(r);+ }+ sqlite3_finalize(stmt);+ return out;+}++void AppDatabase::deleteConnection(const std::string& id) {+ std::lock_guard lock(mutex_);+ if (!db_) throw InternalError("AppDatabase not open");++ sqlite3_stmt* stmt = nullptr;+ if (sqlite3_prepare_v2(db_, "DELETE FROM connections WHERE id = ?1", -1, &stmt, nullptr) != SQLITE_OK) {+ throw InternalError("deleteConnection prepare: " + errmsg(db_));+ }+ sqlite3_bind_text(stmt, 1, id.c_str(), -1, SQLITE_TRANSIENT);+ const int rc = sqlite3_step(stmt);+ sqlite3_finalize(stmt);+ if (rc != SQLITE_DONE) throw InternalError("deleteConnection step: " + errmsg(db_));+}++void AppDatabase::appendHistory(const HistoryEntry& entry) {+ std::lock_guard lock(mutex_);+ if (!db_) throw InternalError("AppDatabase not open");++ const char* sql =+ "INSERT INTO history(connection_id, sql, executed_at, duration_ms, row_count, succeeded) "+ "VALUES(?1, ?2, ?3, ?4, ?5, ?6)";+ sqlite3_stmt* stmt = nullptr;+ if (sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr) != SQLITE_OK) {+ throw InternalError("appendHistory prepare: " + errmsg(db_));+ }+ sqlite3_bind_text(stmt, 1, entry.connectionId.c_str(), -1, SQLITE_TRANSIENT);+ sqlite3_bind_text(stmt, 2, entry.sql.c_str(), -1, SQLITE_TRANSIENT);+ sqlite3_bind_int64(stmt, 3, timePointToUnix(entry.executedAt));+ sqlite3_bind_int(stmt, 4, entry.durationMs);+ sqlite3_bind_int(stmt, 5, entry.rowCount);+ sqlite3_bind_int(stmt, 6, entry.succeeded ? 1 : 0);+ const int rc = sqlite3_step(stmt);+ sqlite3_finalize(stmt);+ if (rc != SQLITE_DONE) throw InternalError("appendHistory step: " + errmsg(db_));+}++std::vector<AppDatabase::HistoryEntry> AppDatabase::listHistory(const std::string& connectionId, int limit) {+ std::lock_guard lock(mutex_);+ if (!db_) throw InternalError("AppDatabase not open");++ const char* sql =+ "SELECT id, connection_id, sql, executed_at, duration_ms, row_count, succeeded "+ "FROM history WHERE connection_id = ?1 ORDER BY executed_at DESC LIMIT ?2";+ sqlite3_stmt* stmt = nullptr;+ if (sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr) != SQLITE_OK) {+ throw InternalError("listHistory prepare: " + errmsg(db_));+ }+ sqlite3_bind_text(stmt, 1, connectionId.c_str(), -1, SQLITE_TRANSIENT);+ sqlite3_bind_int(stmt, 2, limit);+ std::vector<HistoryEntry> out;+ while (sqlite3_step(stmt) == SQLITE_ROW) {+ HistoryEntry h;+ h.id = sqlite3_column_int64(stmt, 0);+ h.connectionId = safeText(stmt, 1);+ h.sql = safeText(stmt, 2);+ h.executedAt = unixToTimePoint(sqlite3_column_int64(stmt, 3));+ h.durationMs = sqlite3_column_int(stmt, 4);+ h.rowCount = sqlite3_column_int(stmt, 5);+ h.succeeded = sqlite3_column_int(stmt, 6) != 0;+ out.push_back(std::move(h));+ }+ sqlite3_finalize(stmt);+ return out;+}++std::vector<AppDatabase::HistoryEntry> AppDatabase::listAllHistory(int limit) {+ std::lock_guard lock(mutex_);+ if (!db_) throw InternalError("AppDatabase not open");++ const char* sql =+ "SELECT id, connection_id, sql, executed_at, duration_ms, row_count, succeeded "+ "FROM history ORDER BY executed_at DESC LIMIT ?1";+ sqlite3_stmt* stmt = nullptr;+ if (sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr) != SQLITE_OK) {+ throw InternalError("listAllHistory prepare: " + errmsg(db_));+ }+ sqlite3_bind_int(stmt, 1, limit);+ std::vector<HistoryEntry> out;+ while (sqlite3_step(stmt) == SQLITE_ROW) {+ HistoryEntry h;+ h.id = sqlite3_column_int64(stmt, 0);+ h.connectionId = safeText(stmt, 1);+ h.sql = safeText(stmt, 2);+ h.executedAt = unixToTimePoint(sqlite3_column_int64(stmt, 3));+ h.durationMs = sqlite3_column_int(stmt, 4);+ h.rowCount = sqlite3_column_int(stmt, 5);+ h.succeeded = sqlite3_column_int(stmt, 6) != 0;+ out.push_back(std::move(h));+ }+ sqlite3_finalize(stmt);+ return out;+}++void AppDatabase::clearAllHistory() {+ std::lock_guard lock(mutex_);+ if (!db_) throw InternalError("AppDatabase not open");+ exec(db_, "DELETE FROM history");+}++void AppDatabase::upsertSavedQuery(const SavedQueryRecord& rec) {+ std::lock_guard lock(mutex_);+ if (!db_) throw InternalError("AppDatabase not open");++ const char* sql =+ "INSERT INTO saved_queries(id, connection_id, group_name, name, sql, created_at, updated_at) "+ "VALUES(?1,?2,?3,?4,?5,?6,?7) "+ "ON CONFLICT(id) DO UPDATE SET "+ " connection_id=excluded.connection_id,"+ " group_name=excluded.group_name,"+ " name=excluded.name,"+ " sql=excluded.sql,"+ " updated_at=excluded.updated_at";+ sqlite3_stmt* stmt = nullptr;+ if (sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr) != SQLITE_OK) {+ throw InternalError("upsertSavedQuery prepare: " + errmsg(db_));+ }+ sqlite3_bind_text(stmt, 1, rec.id.c_str(), -1, SQLITE_TRANSIENT);+ sqlite3_bind_text(stmt, 2, rec.connectionId.c_str(), -1, SQLITE_TRANSIENT);+ sqlite3_bind_text(stmt, 3, rec.groupName.c_str(), -1, SQLITE_TRANSIENT);+ sqlite3_bind_text(stmt, 4, rec.name.c_str(), -1, SQLITE_TRANSIENT);+ sqlite3_bind_text(stmt, 5, rec.sql.c_str(), -1, SQLITE_TRANSIENT);+ sqlite3_bind_int64(stmt, 6, timePointToUnix(rec.createdAt));+ sqlite3_bind_int64(stmt, 7, timePointToUnix(rec.updatedAt));+ const int rc = sqlite3_step(stmt);+ sqlite3_finalize(stmt);+ if (rc != SQLITE_DONE) throw InternalError("upsertSavedQuery step: " + errmsg(db_));+}++std::vector<AppDatabase::SavedQueryRecord> AppDatabase::listSavedQueries() {+ std::lock_guard lock(mutex_);+ if (!db_) throw InternalError("AppDatabase not open");++ const char* sql =+ "SELECT id, connection_id, group_name, name, sql, created_at, updated_at "+ "FROM saved_queries ORDER BY group_name, name";+ sqlite3_stmt* stmt = nullptr;+ if (sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr) != SQLITE_OK) {+ throw InternalError("listSavedQueries prepare: " + errmsg(db_));+ }+ std::vector<SavedQueryRecord> out;+ while (sqlite3_step(stmt) == SQLITE_ROW) {+ SavedQueryRecord r;+ r.id = safeText(stmt, 0);+ r.connectionId = safeText(stmt, 1);+ r.groupName = safeText(stmt, 2);+ r.name = safeText(stmt, 3);+ r.sql = safeText(stmt, 4);+ r.createdAt = unixToTimePoint(sqlite3_column_int64(stmt, 5));+ r.updatedAt = unixToTimePoint(sqlite3_column_int64(stmt, 6));+ out.push_back(std::move(r));+ }+ sqlite3_finalize(stmt);+ return out;+}++void AppDatabase::deleteSavedQuery(const std::string& id) {+ std::lock_guard lock(mutex_);+ if (!db_) throw InternalError("AppDatabase not open");++ sqlite3_stmt* stmt = nullptr;+ if (sqlite3_prepare_v2(db_, "DELETE FROM saved_queries WHERE id=?1", -1, &stmt, nullptr) != SQLITE_OK) {+ throw InternalError("deleteSavedQuery prepare: " + errmsg(db_));+ }+ sqlite3_bind_text(stmt, 1, id.c_str(), -1, SQLITE_TRANSIENT);+ const int rc = sqlite3_step(stmt);+ sqlite3_finalize(stmt);+ if (rc != SQLITE_DONE) throw InternalError("deleteSavedQuery step: " + errmsg(db_));+}++void AppDatabase::setConnectionGroup(const std::string& connectionId, const std::string& group) {+ std::lock_guard lock(mutex_);+ if (!db_) throw InternalError("AppDatabase not open");++ sqlite3_stmt* stmt = nullptr;+ if (sqlite3_prepare_v2(db_, "UPDATE connections SET group_name=?1 WHERE id=?2", -1, &stmt, nullptr) != SQLITE_OK) {+ throw InternalError("setConnectionGroup prepare: " + errmsg(db_));+ }+ if (group.empty()) sqlite3_bind_null(stmt, 1);+ else sqlite3_bind_text(stmt, 1, group.c_str(), -1, SQLITE_TRANSIENT);+ sqlite3_bind_text(stmt, 2, connectionId.c_str(), -1, SQLITE_TRANSIENT);+ const int rc = sqlite3_step(stmt);+ sqlite3_finalize(stmt);+ if (rc != SQLITE_DONE) throw InternalError("setConnectionGroup step: " + errmsg(db_));+}++std::string AppDatabase::getConnectionGroup(const std::string& connectionId) {+ std::lock_guard lock(mutex_);+ if (!db_) throw InternalError("AppDatabase not open");++ sqlite3_stmt* stmt = nullptr;+ if (sqlite3_prepare_v2(db_, "SELECT group_name FROM connections WHERE id=?1", -1, &stmt, nullptr) != SQLITE_OK) {+ throw InternalError("getConnectionGroup prepare: " + errmsg(db_));+ }+ sqlite3_bind_text(stmt, 1, connectionId.c_str(), -1, SQLITE_TRANSIENT);+ std::string out;+ if (sqlite3_step(stmt) == SQLITE_ROW) out = safeText(stmt, 0);+ sqlite3_finalize(stmt);+ return out;+}++void AppDatabase::setSetting(const std::string& key, const std::string& value) {+ std::lock_guard lock(mutex_);+ if (!db_) throw InternalError("AppDatabase not open");++ const char* sql =+ "INSERT INTO settings(key, value) VALUES(?1, ?2) "+ "ON CONFLICT(key) DO UPDATE SET value=excluded.value";+ sqlite3_stmt* stmt = nullptr;+ if (sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr) != SQLITE_OK) {+ throw InternalError("setSetting prepare: " + errmsg(db_));+ }+ sqlite3_bind_text(stmt, 1, key.c_str(), -1, SQLITE_TRANSIENT);+ sqlite3_bind_text(stmt, 2, value.c_str(), -1, SQLITE_TRANSIENT);+ const int rc = sqlite3_step(stmt);+ sqlite3_finalize(stmt);+ if (rc != SQLITE_DONE) throw InternalError("setSetting step: " + errmsg(db_));+}++std::optional<std::string> AppDatabase::getSetting(const std::string& key) {+ std::lock_guard lock(mutex_);+ if (!db_) throw InternalError("AppDatabase not open");++ sqlite3_stmt* stmt = nullptr;+ if (sqlite3_prepare_v2(db_, "SELECT value FROM settings WHERE key = ?1", -1, &stmt, nullptr) != SQLITE_OK) {+ throw InternalError("getSetting prepare: " + errmsg(db_));+ }+ sqlite3_bind_text(stmt, 1, key.c_str(), -1, SQLITE_TRANSIENT);+ std::optional<std::string> out;+ if (sqlite3_step(stmt) == SQLITE_ROW) {+ out = safeText(stmt, 0);+ }+ sqlite3_finalize(stmt);+ return out;+}++}diff --git a/linux/src/Data/Persistence/AppDatabase.h b/linux/src/Data/Persistence/AppDatabase.hnew file mode 100644index 0000000..7a08c9b--- /dev/null+++ b/linux/src/Data/Persistence/AppDatabase.h@@ -0,0 +1,93 @@+#pragma once++#include <chrono>+#include <cstdint>+#include <memory>+#include <mutex>+#include <optional>+#include <string>+#include <vector>++struct sqlite3;++namespace gridex {++// SQLite-backed app persistence: connection list, query history, settings.+// Stored under XDG_DATA_HOME/gridex or ~/.local/share/gridex.+class AppDatabase {+public:+ struct ConnectionRecord {+ std::string id; // UUID+ std::string name;+ std::string databaseType; // rawValue of DatabaseType+ std::string configJson; // serialized ConnectionConfig (no secrets)+ std::chrono::system_clock::time_point updatedAt;+ };++ struct HistoryEntry {+ std::int64_t id = 0;+ std::string connectionId;+ std::string sql;+ std::chrono::system_clock::time_point executedAt;+ int durationMs = 0;+ int rowCount = 0;+ bool succeeded = true;+ };++ struct SavedQueryRecord {+ std::string id;+ std::string connectionId;+ std::string groupName;+ std::string name;+ std::string sql;+ std::chrono::system_clock::time_point createdAt;+ std::chrono::system_clock::time_point updatedAt;+ };++ AppDatabase();+ ~AppDatabase();++ AppDatabase(const AppDatabase&) = delete;+ AppDatabase& operator=(const AppDatabase&) = delete;++ // Opens the DB at the given path (or default path if empty) and applies migrations.+ void open(const std::string& path = {});+ void close();++ // Connection CRUD+ void upsertConnection(const ConnectionRecord& rec);+ std::vector<ConnectionRecord> listConnections();+ std::optional<ConnectionRecord> getConnection(const std::string& id);+ void deleteConnection(const std::string& id);++ // History+ void appendHistory(const HistoryEntry& entry);+ std::vector<HistoryEntry> listHistory(const std::string& connectionId, int limit = 100);+ std::vector<HistoryEntry> listAllHistory(int limit = 200);+ void clearAllHistory();++ // Saved queries+ void upsertSavedQuery(const SavedQueryRecord& rec);+ std::vector<SavedQueryRecord> listSavedQueries();+ void deleteSavedQuery(const std::string& id);++ // Connection group support+ void setConnectionGroup(const std::string& connectionId, const std::string& group);+ std::string getConnectionGroup(const std::string& connectionId);++ // Settings (string KV)+ void setSetting(const std::string& key, const std::string& value);+ std::optional<std::string> getSetting(const std::string& key);++ [[nodiscard]] std::string path() const { return path_; }++private:+ void applyMigrations();+ static std::string defaultPath();++ sqlite3* db_ = nullptr;+ std::string path_;+ mutable std::mutex mutex_;+};++}diff --git a/linux/src/Data/Persistence/SavedQueryRepository.cpp b/linux/src/Data/Persistence/SavedQueryRepository.cppnew file mode 100644index 0000000..f152522--- /dev/null+++ b/linux/src/Data/Persistence/SavedQueryRepository.cpp@@ -0,0 +1,26 @@+#include "Data/Persistence/SavedQueryRepository.h"++#include <utility>++#include "Core/Errors/GridexError.h"++namespace gridex {++SavedQueryRepository::SavedQueryRepository(std::shared_ptr<AppDatabase> db)+ : db_(std::move(db)) {+ if (!db_) throw InternalError("SavedQueryRepository: null AppDatabase");+}++std::vector<AppDatabase::SavedQueryRecord> SavedQueryRepository::fetchAll() {+ return db_->listSavedQueries();+}++void SavedQueryRepository::save(const AppDatabase::SavedQueryRecord& rec) {+ db_->upsertSavedQuery(rec);+}++void SavedQueryRepository::remove(const std::string& id) {+ db_->deleteSavedQuery(id);+}++}diff --git a/linux/src/Data/Persistence/SavedQueryRepository.h b/linux/src/Data/Persistence/SavedQueryRepository.hnew file mode 100644index 0000000..474287f--- /dev/null+++ b/linux/src/Data/Persistence/SavedQueryRepository.h@@ -0,0 +1,23 @@+#pragma once++#include <memory>+#include <string>+#include <vector>++#include "Data/Persistence/AppDatabase.h"++namespace gridex {++class SavedQueryRepository {+public:+ explicit SavedQueryRepository(std::shared_ptr<AppDatabase> db);++ std::vector<AppDatabase::SavedQueryRecord> fetchAll();+ void save(const AppDatabase::SavedQueryRecord& rec);+ void remove(const std::string& id);++private:+ std::shared_ptr<AppDatabase> db_;+};++}diff --git a/linux/src/Domain/CMakeLists.txt b/linux/src/Domain/CMakeLists.txtnew file mode 100644index 0000000..af7ce9d--- /dev/null+++ b/linux/src/Domain/CMakeLists.txt@@ -0,0 +1,14 @@+add_library(gridex-domain STATIC+ UseCases/Connection/TestConnection.cpp+ UseCases/Connection/ConnectDatabase.cpp+ UseCases/Connection/DeleteConnection.cpp+)++target_include_directories(gridex-domain PUBLIC+ ${CMAKE_CURRENT_SOURCE_DIR}/..+)++target_link_libraries(gridex-domain+ PUBLIC gridex-core+ PRIVATE gridex-data+)diff --git a/linux/src/Domain/Repositories/IConnectionRepository.h b/linux/src/Domain/Repositories/IConnectionRepository.hnew file mode 100644index 0000000..4d04323--- /dev/null+++ b/linux/src/Domain/Repositories/IConnectionRepository.h@@ -0,0 +1,24 @@+#pragma once++#include <optional>+#include <string>+#include <vector>++#include "Core/Models/Database/ConnectionConfig.h"++namespace gridex {++// Mirrors macos ConnectionRepository protocol. Persists ConnectionConfig records+// (sans secrets — those live in SecretStore).+class IConnectionRepository {+public:+ virtual ~IConnectionRepository() = default;++ virtual std::vector<ConnectionConfig> fetchAll() = 0;+ virtual std::optional<ConnectionConfig> fetchById(const std::string& id) = 0;+ virtual std::vector<ConnectionConfig> fetchByGroup(const std::string& group) = 0;+ virtual void save(const ConnectionConfig& config) = 0;+ virtual void remove(const std::string& id) = 0;+};++}diff --git a/linux/src/Domain/UseCases/Connection/ConnectDatabase.cpp b/linux/src/Domain/UseCases/Connection/ConnectDatabase.cppnew file mode 100644index 0000000..ef04e50--- /dev/null+++ b/linux/src/Domain/UseCases/Connection/ConnectDatabase.cpp@@ -0,0 +1,49 @@+#include "Domain/UseCases/Connection/ConnectDatabase.h"++#include <utility>++#include <cstdio>++#include "Core/Errors/GridexError.h"+#include "Core/Protocols/Database/ISchemaInspectable.h"+#include "Data/Adapters/AdapterFactory.h"+#include "Data/Keychain/SecretStore.h"++namespace gridex {++ActiveConnection ConnectDatabaseUseCase::execute(const ConnectionConfig& config,+ const std::optional<std::string>& password,+ bool loadInitialSchema) {+ std::optional<std::string> pw = password;+ std::optional<std::string> degradedReason;+ if (!pw && secretStore_) {+ try {+ pw = secretStore_->loadPassword(config.id);+ } catch (const std::exception& e) {+ degradedReason = std::string("SecretStore lookup failed: ") + e.what();+ std::fprintf(stderr, "[ConnectDatabase] %s\n", degradedReason->c_str());+ }+ }++ auto adapter = createAdapter(config.databaseType);+ adapter->connect(config, pw);++ ActiveConnection conn;+ conn.id = config.id;+ conn.config = config;+ conn.connectedAt = std::chrono::system_clock::now();+ conn.degradedReason = std::move(degradedReason);++ if (loadInitialSchema) {+ // Only SQLite currently implements ISchemaInspectable; for others skip.+ if (auto* inspectable = dynamic_cast<ISchemaInspectable*>(adapter.get())) {+ try { conn.initialSchema = inspectable->fullSchemaSnapshot(std::nullopt); }+ catch (const GridexError&) { /* schema load best-effort */ }+ }+ }++ conn.adapter = std::move(adapter);+ return conn;+}++}diff --git a/linux/src/Domain/UseCases/Connection/ConnectDatabase.h b/linux/src/Domain/UseCases/Connection/ConnectDatabase.hnew file mode 100644index 0000000..768ddea--- /dev/null+++ b/linux/src/Domain/UseCases/Connection/ConnectDatabase.h@@ -0,0 +1,43 @@+#pragma once++#include <chrono>+#include <memory>+#include <optional>+#include <string>++#include "Core/Models/Database/ConnectionConfig.h"+#include "Core/Models/Schema/SchemaSnapshot.h"+#include "Core/Protocols/Database/IDatabaseAdapter.h"++namespace gridex {++class SecretStore;++struct ActiveConnection {+ std::string id;+ ConnectionConfig config;+ std::unique_ptr<IDatabaseAdapter> adapter;+ std::optional<SchemaSnapshot> initialSchema;+ std::chrono::system_clock::time_point connectedAt;+ // Populated when the SecretStore lookup degrades (daemon unavailable, auth race, etc.).+ // Empty when credentials were either provided directly or fetched cleanly.+ std::optional<std::string> degradedReason;+};++// Orchestrates: retrieve password from SecretStore (if needed) → create adapter+// → connect → optionally snapshot schema. Mirrors macos ConnectDatabaseUseCase.+class ConnectDatabaseUseCase {+public:+ explicit ConnectDatabaseUseCase(SecretStore* secretStore = nullptr)+ : secretStore_(secretStore) {}++ // password overrides the one stored in SecretStore when non-empty.+ ActiveConnection execute(const ConnectionConfig& config,+ const std::optional<std::string>& password = std::nullopt,+ bool loadInitialSchema = false);++private:+ SecretStore* secretStore_;+};++}diff --git a/linux/src/Domain/UseCases/Connection/DeleteConnection.cpp b/linux/src/Domain/UseCases/Connection/DeleteConnection.cppnew file mode 100644index 0000000..8eade94--- /dev/null+++ b/linux/src/Domain/UseCases/Connection/DeleteConnection.cpp@@ -0,0 +1,19 @@+#include "Domain/UseCases/Connection/DeleteConnection.h"++#include "Core/Errors/GridexError.h"+#include "Data/Keychain/SecretStore.h"+#include "Domain/Repositories/IConnectionRepository.h"++namespace gridex {++void DeleteConnectionUseCase::execute(const std::string& id) {+ if (!repo_) throw InternalError("DeleteConnectionUseCase: null repository");+ repo_->remove(id);+ if (secrets_) {+ // Best-effort: ignore failures so a vanished keyring doesn't block delete.+ try { secrets_->removePassword(id); } catch (...) {}+ try { secrets_->remove("ssh.password." + id); } catch (...) {}+ }+}++}diff --git a/linux/src/Domain/UseCases/Connection/DeleteConnection.h b/linux/src/Domain/UseCases/Connection/DeleteConnection.hnew file mode 100644index 0000000..c47d63c--- /dev/null+++ b/linux/src/Domain/UseCases/Connection/DeleteConnection.h@@ -0,0 +1,24 @@+#pragma once++#include <memory>+#include <string>++namespace gridex {++class IConnectionRepository;+class SecretStore;++// Deletes connection record from repository + scrubs credentials from SecretStore.+class DeleteConnectionUseCase {+public:+ DeleteConnectionUseCase(IConnectionRepository* repo, SecretStore* secrets)+ : repo_(repo), secrets_(secrets) {}++ void execute(const std::string& id);++private:+ IConnectionRepository* repo_;+ SecretStore* secrets_;+};++}diff --git a/linux/src/Domain/UseCases/Connection/TestConnection.cpp b/linux/src/Domain/UseCases/Connection/TestConnection.cppnew file mode 100644index 0000000..da406e4--- /dev/null+++ b/linux/src/Domain/UseCases/Connection/TestConnection.cpp@@ -0,0 +1,30 @@+#include "Domain/UseCases/Connection/TestConnection.h"++#include <chrono>++#include "Core/Errors/GridexError.h"+#include "Data/Adapters/AdapterFactory.h"++namespace gridex {++ConnectionTestResult TestConnectionUseCase::execute(const ConnectionConfig& config,+ const std::optional<std::string>& password) {+ // Single connect/probe/disconnect to avoid 3× round-trip cost the older impl paid.+ ConnectionTestResult result;+ const auto start = std::chrono::steady_clock::now();+ try {+ auto adapter = createAdapter(config.databaseType);+ adapter->connect(config, password);+ result.success = true;+ try { result.serverVersion = adapter->serverVersion(); }+ catch (const GridexError&) { /* version probe is best-effort */ }+ adapter->disconnect();+ } catch (const GridexError& e) {+ result.success = false;+ result.errorMessage = e.what();+ }+ result.latency = std::chrono::steady_clock::now() - start;+ return result;+}++}diff --git a/linux/src/Domain/UseCases/Connection/TestConnection.h b/linux/src/Domain/UseCases/Connection/TestConnection.hnew file mode 100644index 0000000..3b9da3d--- /dev/null+++ b/linux/src/Domain/UseCases/Connection/TestConnection.h@@ -0,0 +1,26 @@+#pragma once++#include <chrono>+#include <optional>+#include <string>++#include "Core/Models/Database/ConnectionConfig.h"++namespace gridex {++struct ConnectionTestResult {+ bool success = false;+ std::optional<std::string> serverVersion;+ std::chrono::duration<double> latency{};+ std::optional<std::string> errorMessage;+};++// Orchestrates a non-destructive connection probe: creates an adapter, calls+// testConnection+serverVersion, returns latency. Throws on unexpected errors.+class TestConnectionUseCase {+public:+ ConnectionTestResult execute(const ConnectionConfig& config,+ const std::optional<std::string>& password);+};++}diff --git a/linux/src/Presentation/CMakeLists.txt b/linux/src/Presentation/CMakeLists.txtnew file mode 100644index 0000000..3214a94--- /dev/null+++ b/linux/src/Presentation/CMakeLists.txt@@ -0,0 +1,71 @@+find_package(Qt6 6.4 REQUIRED COMPONENTS Widgets Concurrent Svg)++qt_add_library(gridex-presentation STATIC+ Theme/ThemeManager.cpp+ ViewModels/AIChatViewModel.cpp+ ViewModels/ConnectionListViewModel.cpp+ ViewModels/WorkspaceState.cpp+ Views/AIChat/AIChatView.cpp+ Views/Backup/BackupProgressDialog.cpp+ Views/ConnectionForm/ConnectionFormDialog.cpp+ Views/CreateTable/CreateTableDialog.cpp+ Views/DataGrid/DataGridView.cpp+ Views/DatabaseSwitcher/DatabaseSwitcherDialog.cpp+ Views/ERDiagram/ERDiagramView.cpp+ Views/ERDiagram/ERDiagramExporter.cpp+ Views/DataGrid/QueryResultModel.cpp+ Views/Details/DetailsPanel.cpp+ Views/FilterBar/FilterBarView.cpp+ Views/FunctionDetail/FunctionDetailView.cpp+ Views/QueryLog/QueryLogPanel.cpp+ Views/Redis/RedisKeyDetailView.cpp+ Views/MongoDB/MongoCollectionView.cpp+ Views/TableStructure/TableStructureView.cpp+ Views/Home/HomeBrandingPanel.cpp+ Views/Main/WorkspaceView.cpp+ Views/QueryEditor/QueryEditorView.cpp+ Views/QueryEditor/SqlHighlighter.cpp+ Views/Settings/SettingsDialog.cpp+ Views/QueryEditor/Autocomplete/AutocompleteProvider.cpp+ Views/QueryEditor/Autocomplete/CompletionPopup.cpp+ Views/QueryEditor/Autocomplete/SqlContextParser.cpp+ Views/Sidebar/ConnectionRowWidget.cpp+ Views/Sidebar/ConnectionSidebar.cpp+ Views/ImportSQL/SqlImportWizard.cpp+ Views/Sidebar/WorkspaceSidebar.cpp+ Views/TableList/TableGridView.cpp+ Views/StatusBar/StatusBarView.cpp+ Views/TabBar/WorkspaceTabBar.cpp+ Windows/Main/MainWindow.cpp+ Views/MCP/MCPWindowState.cpp+ Views/MCP/MCPWindow.cpp+ Views/MCP/MCPOverviewView.cpp+ Views/MCP/MCPConnectionsView.cpp+ Views/MCP/MCPActivityView.cpp+ Views/MCP/MCPSetupView.cpp+ Views/MCP/MCPAdvancedView.cpp+)++qt_add_resources(gridex-presentation "assets"+ PREFIX "/"+ BASE ${CMAKE_SOURCE_DIR}/resources+ FILES+ ${CMAKE_SOURCE_DIR}/resources/logo.png+ ${CMAKE_SOURCE_DIR}/resources/style-dark.qss+ ${CMAKE_SOURCE_DIR}/resources/style-light.qss+)++target_include_directories(gridex-presentation PUBLIC+ ${CMAKE_CURRENT_SOURCE_DIR}/..+)++target_link_libraries(gridex-presentation PUBLIC+ gridex-core+ gridex-data+ gridex-services+ gridex-domain+ gridex-app+ Qt6::Widgets+ Qt6::Concurrent+ Qt6::Svg+)diff --git a/linux/src/Presentation/Theme/ThemeManager.cpp b/linux/src/Presentation/Theme/ThemeManager.cppnew file mode 100644index 0000000..c678836--- /dev/null+++ b/linux/src/Presentation/Theme/ThemeManager.cpp@@ -0,0 +1,77 @@+#include "Presentation/Theme/ThemeManager.h"++#include <QApplication>+#include <QFile>+#include <QGuiApplication>+#include <QSettings>+#include <QStyleHints>++namespace gridex {++ThemeManager& ThemeManager::instance() {+ static ThemeManager inst;+ return inst;+}++ThemeManager::ThemeManager(QObject* parent) : QObject(parent) {+ QSettings s;+ const QString saved = s.value(QStringLiteral("ui/theme"), QStringLiteral("Auto")).toString();+ if (saved == QLatin1String("Light")) mode_ = Mode::Light;+ else if (saved == QLatin1String("Dark")) mode_ = Mode::Dark;+ else mode_ = Mode::Auto;+}++void ThemeManager::apply(QApplication* app) {+ app_ = app;++ if (mode_ == Mode::Auto) {+ applyForCurrentSystem(app);+ connect(QGuiApplication::styleHints(), &QStyleHints::colorSchemeChanged,+ this, [this](Qt::ColorScheme) {+ if (mode_ == Mode::Auto && app_) {+ applyForCurrentSystem(app_);+ emit themeChanged();+ }+ }, Qt::UniqueConnection);+ } else {+ applyQss(app, mode_ == Mode::Light+ ? QStringLiteral(":/style-light.qss")+ : QStringLiteral(":/style-dark.qss"));+ }+}++void ThemeManager::setMode(Mode mode, QApplication* app) {+ app_ = app;+ mode_ = mode;++ const QString key = (mode == Mode::Light) ? QStringLiteral("Light")+ : (mode == Mode::Dark) ? QStringLiteral("Dark")+ : QStringLiteral("Auto");+ QSettings s;+ s.setValue(QStringLiteral("ui/theme"), key);++ apply(app);+ emit themeChanged();+}++ThemeManager::Mode ThemeManager::mode() const {+ return mode_;+}++void ThemeManager::applyQss(QApplication* app, const QString& path) {+ QFile f(path);+ if (f.open(QFile::ReadOnly | QFile::Text)) {+ app->setStyleSheet(QString::fromUtf8(f.readAll()));+ f.close();+ }+}++void ThemeManager::applyForCurrentSystem(QApplication* app) {+ const Qt::ColorScheme scheme = QGuiApplication::styleHints()->colorScheme();+ const bool dark = (scheme == Qt::ColorScheme::Dark)+ || (scheme == Qt::ColorScheme::Unknown);+ applyQss(app, dark ? QStringLiteral(":/style-dark.qss")+ : QStringLiteral(":/style-light.qss"));+}++} // namespace gridexdiff --git a/linux/src/Presentation/Theme/ThemeManager.h b/linux/src/Presentation/Theme/ThemeManager.hnew file mode 100644index 0000000..066006b--- /dev/null+++ b/linux/src/Presentation/Theme/ThemeManager.h@@ -0,0 +1,36 @@+#pragma once++#include <QObject>+#include <QString>++class QApplication;++namespace gridex {++class ThemeManager : public QObject {+ Q_OBJECT+public:+ enum class Mode { Light, Dark, Auto };++ static ThemeManager& instance();++ void apply(QApplication* app);+ void setMode(Mode mode, QApplication* app);+ Mode mode() const;++signals:+ void themeChanged();++private:+ explicit ThemeManager(QObject* parent = nullptr);+ ThemeManager(const ThemeManager&) = delete;+ ThemeManager& operator=(const ThemeManager&) = delete;++ void applyQss(QApplication* app, const QString& path);+ void applyForCurrentSystem(QApplication* app);++ Mode mode_ = Mode::Auto;+ QApplication* app_ = nullptr;+};++} // namespace gridexdiff --git a/linux/src/Presentation/ViewModels/AIChatViewModel.cpp b/linux/src/Presentation/ViewModels/AIChatViewModel.cppnew file mode 100644index 0000000..00e5f24--- /dev/null+++ b/linux/src/Presentation/ViewModels/AIChatViewModel.cpp@@ -0,0 +1,174 @@+#include "Presentation/ViewModels/AIChatViewModel.h"++#include <QRegularExpression>+#include <QSettings>+#include <QThread>+#include <QtConcurrent/QtConcurrent>+#include <QFutureWatcher>++#include "Core/Errors/GridexError.h"+#include "Data/Keychain/SecretStore.h"+#include "Services/AI/AIServiceFactory.h"++namespace gridex {++AIChatViewModel::AIChatViewModel(SecretStore* secretStore, QObject* parent)+ : QObject(parent), secretStore_(secretStore) {+ // Read persisted default provider/model from the Settings dialog.+ QSettings s;+ const QString savedProvider = s.value("ai/provider").toString();+ if (!savedProvider.isEmpty()) selectedProvider_ = savedProvider;++ const QString savedModel = s.value("ai/model").toString();+ if (!savedModel.isEmpty()) {+ selectedModel_ = savedModel;+ if (savedModel.contains(' ') || savedModel.contains(QRegularExpression("[A-Z]"))) {+ QString normalized = savedModel.toLower();+ normalized.replace(' ', '-');+ selectedModel_ = normalized;+ }+ }+}++// ---- Static helpers ---------------------------------------------------++std::vector<LLMModel> AIChatViewModel::modelsForProvider(const QString& provider) {+ const std::string key = provider.toStdString();+ // Use factory's providers to get their static model lists without an API key.+ try {+ auto svc = AIServiceFactory::createAIService(key, "");+ return svc->availableModels();+ } catch (...) {+ return {};+ }+}++// ---- Mutators ---------------------------------------------------------++void AIChatViewModel::setProvider(const QString& provider) {+ if (provider == selectedProvider_) return;+ selectedProvider_ = provider;+ const auto models = modelsForProvider(provider);+ selectedModel_ = models.empty()+ ? QString{}+ : QString::fromStdString(models.front().id);+}++void AIChatViewModel::setModel(const QString& model) {+ selectedModel_ = model;+}++void AIChatViewModel::saveAPIKey(const QString& key) {+ if (!secretStore_) return;+ try {+ secretStore_->saveAPIKey(selectedProvider_.toStdString(), key.toStdString());+ } catch (const GridexError& e) {+ emit errorOccurred(QString::fromUtf8(e.what()));+ }+}++QString AIChatViewModel::loadAPIKey() const {+ if (!secretStore_) return {};+ try {+ const auto val = secretStore_->loadAPIKey(selectedProvider_.toStdString());+ return val ? QString::fromStdString(*val) : QString{};+ } catch (...) {+ return {};+ }+}++void AIChatViewModel::setDatabaseContext(const QString& dbType, const QString& schema) {+ dbType_ = dbType;+ dbSchema_ = schema;+}++void AIChatViewModel::clearHistory() {+ messages_.clear();+ emit messagesChanged();+}++// ---- Core send logic --------------------------------------------------++void AIChatViewModel::sendMessage(const QString& userText) {+ if (userText.trimmed().isEmpty() || isLoading_) return;++ const ChatMessage userMsg = ChatMessage::user(userText.toStdString());+ appendMessage(userMsg);+ setLoading(true);++ // Snapshot state for the background thread — avoid capturing this.+ const std::string provider = selectedProvider_.toStdString();+ const std::string model = selectedModel_.toStdString();+ const std::string apiKey = loadAPIKey().toStdString();+ const std::string sysPrompt = buildSystemPrompt();+ QSettings qs;+ const std::string baseUrl = qs.value(+ QStringLiteral("ai/endpoint/") + selectedProvider_).toString().toStdString();++ // Build LLMMessage history from current messages_ (excluding the one we+ // just appended — it's included below).+ std::vector<LLMMessage> history;+ history.reserve(messages_.size());+ for (const auto& m : messages_) {+ history.push_back({m.role, m.content});+ }++ struct AIResult { std::string text; std::string error; };+ auto* watcher = new QFutureWatcher<AIResult>(this);++ connect(watcher, &QFutureWatcher<AIResult>::finished, this,+ [this, watcher]() {+ setLoading(false);+ const AIResult r = watcher->result();+ if (!r.error.empty()) {+ emit errorOccurred(QString::fromStdString(r.error));+ } else {+ appendMessage(ChatMessage::assistant(r.text));+ }+ watcher->deleteLater();+ });++ const QFuture<AIResult> future = QtConcurrent::run(+ [provider, model, apiKey, baseUrl, sysPrompt, history]() -> AIResult {+ try {+ auto svc = AIServiceFactory::createAIService(provider, apiKey, baseUrl);+ if (!svc) return {"", "Unknown provider: " + provider};+ return {svc->sendMessage(history, sysPrompt, model), ""};+ } catch (const std::exception& e) {+ return {"", std::string(e.what())};+ } catch (...) {+ return {"", "Unknown error contacting AI provider."};+ }+ });++ watcher->setFuture(future);+}++// ---- Private helpers --------------------------------------------------++void AIChatViewModel::appendMessage(const ChatMessage& msg) {+ messages_.push_back(msg);+ emit messagesChanged();+}++void AIChatViewModel::setLoading(bool v) {+ if (isLoading_ == v) return;+ isLoading_ = v;+ emit isLoadingChanged(v);+}++std::string AIChatViewModel::buildSystemPrompt() const {+ std::string prompt =+ "You are a database assistant for Gridex, an AI-native database IDE.";+ if (!dbType_.isEmpty()) {+ prompt += " The connected database type is " + dbType_.toStdString() + ".";+ }+ if (!dbSchema_.isEmpty()) {+ prompt += " Current schema context:\n" + dbSchema_.toStdString();+ }+ prompt += "\nHelp the user write SQL queries. "+ "When suggesting SQL, wrap it in ```sql code blocks.";+ return prompt;+}++} // namespace gridexdiff --git a/linux/src/Presentation/ViewModels/AIChatViewModel.h b/linux/src/Presentation/ViewModels/AIChatViewModel.hnew file mode 100644index 0000000..879db6f--- /dev/null+++ b/linux/src/Presentation/ViewModels/AIChatViewModel.h@@ -0,0 +1,73 @@+#pragma once++#include <QObject>+#include <QString>+#include <memory>+#include <vector>++#include "Core/Models/AI/AIModels.h"+#include "Core/Protocols/AI/ILLMService.h"++namespace gridex {++class SecretStore;++// ViewModel for the AI chat panel.+// Owns the conversation history and dispatches sendMessage() calls onto a+// worker QThread to keep the UI responsive (sync HTTP calls block ~1-30s).+class AIChatViewModel : public QObject {+ Q_OBJECT++public:+ explicit AIChatViewModel(SecretStore* secretStore, QObject* parent = nullptr);++ // ---- Accessors ----+ [[nodiscard]] const std::vector<ChatMessage>& messages() const { return messages_; }+ [[nodiscard]] QString selectedProvider() const { return selectedProvider_; }+ [[nodiscard]] QString selectedModel() const { return selectedModel_; }+ [[nodiscard]] bool isLoading() const { return isLoading_; }++ // Return hardcoded model list for the given provider (no API round-trip).+ [[nodiscard]] static std::vector<LLMModel> modelsForProvider(const QString& provider);++ // Called from view when user changes provider combo.+ void setProvider(const QString& provider);+ void setModel(const QString& model);++ // Persist / retrieve API key for the current provider via SecretStore.+ void saveAPIKey(const QString& key);+ QString loadAPIKey() const;++ // Database context injected by WorkspaceView so the system prompt is useful.+ void setDatabaseContext(const QString& dbType, const QString& schema);++ // Clear conversation history.+ void clearHistory();++public slots:+ // Send a user message; runs provider call on background thread.+ void sendMessage(const QString& userText);++signals:+ void messagesChanged();+ void isLoadingChanged(bool loading);+ void errorOccurred(const QString& message);++private:+ void appendMessage(const ChatMessage& msg);+ void setLoading(bool v);+ [[nodiscard]] std::string buildSystemPrompt() const;++ SecretStore* secretStore_ = nullptr;++ std::vector<ChatMessage> messages_;+ QString selectedProvider_ = QStringLiteral("Anthropic");+ QString selectedModel_;+ bool isLoading_ = false;++ // Database context for system prompt.+ QString dbType_;+ QString dbSchema_;+};++} // namespace gridexdiff --git a/linux/src/Presentation/ViewModels/ConnectionListViewModel.cpp b/linux/src/Presentation/ViewModels/ConnectionListViewModel.cppnew file mode 100644index 0000000..69fcc1b--- /dev/null+++ b/linux/src/Presentation/ViewModels/ConnectionListViewModel.cpp@@ -0,0 +1,50 @@+#include "Presentation/ViewModels/ConnectionListViewModel.h"++#include <QString>++#include "Core/Errors/GridexError.h"+#include "Domain/Repositories/IConnectionRepository.h"++namespace gridex {++ConnectionListViewModel::ConnectionListViewModel(IConnectionRepository* repo, QObject* parent)+ : QObject(parent), repo_(repo) {}++std::optional<ConnectionConfig> ConnectionListViewModel::find(const std::string& id) const {+ for (const auto& c : connections_) {+ if (c.id == id) return c;+ }+ return std::nullopt;+}++void ConnectionListViewModel::reload() {+ if (!repo_) return;+ try {+ connections_ = repo_->fetchAll();+ emit connectionsChanged();+ } catch (const GridexError& e) {+ emit errorOccurred(QString::fromUtf8(e.what()));+ }+}++void ConnectionListViewModel::upsert(const ConnectionConfig& config) {+ if (!repo_) return;+ try {+ repo_->save(config);+ reload();+ } catch (const GridexError& e) {+ emit errorOccurred(QString::fromUtf8(e.what()));+ }+}++void ConnectionListViewModel::remove(const std::string& id) {+ if (!repo_) return;+ try {+ repo_->remove(id);+ reload();+ } catch (const GridexError& e) {+ emit errorOccurred(QString::fromUtf8(e.what()));+ }+}++}diff --git a/linux/src/Presentation/ViewModels/ConnectionListViewModel.h b/linux/src/Presentation/ViewModels/ConnectionListViewModel.hnew file mode 100644index 0000000..14b210e--- /dev/null+++ b/linux/src/Presentation/ViewModels/ConnectionListViewModel.h@@ -0,0 +1,44 @@+#pragma once++#include <QObject>+#include <memory>+#include <optional>+#include <string>+#include <vector>++#include "Core/Models/Database/ConnectionConfig.h"++namespace gridex {++class IConnectionRepository;++// QObject holding the list of saved connections. Pure read/write facade over+// IConnectionRepository — UI observers listen to signals and refresh.+class ConnectionListViewModel : public QObject {+ Q_OBJECT++public:+ explicit ConnectionListViewModel(IConnectionRepository* repo, QObject* parent = nullptr);++ [[nodiscard]] const std::vector<ConnectionConfig>& connections() const noexcept { return connections_; }+ [[nodiscard]] std::optional<ConnectionConfig> find(const std::string& id) const;++ // Fetches from repository and emits connectionsChanged.+ void reload();++ // Upsert: saves to repo then emits connectionsChanged.+ void upsert(const ConnectionConfig& config);++ // Removes and emits connectionsChanged.+ void remove(const std::string& id);++signals:+ void connectionsChanged();+ void errorOccurred(const QString& message);++private:+ IConnectionRepository* repo_;+ std::vector<ConnectionConfig> connections_;+};++}diff --git a/linux/src/Presentation/ViewModels/WorkspaceState.cpp b/linux/src/Presentation/ViewModels/WorkspaceState.cppnew file mode 100644index 0000000..d3ea74b--- /dev/null+++ b/linux/src/Presentation/ViewModels/WorkspaceState.cpp@@ -0,0 +1,129 @@+#include "Presentation/ViewModels/WorkspaceState.h"++#include <chrono>+#include <thread>+#include <utility>++#include "Core/Errors/GridexError.h"+#include "Data/Adapters/AdapterFactory.h"+#include "Data/Keychain/SecretStore.h"+#include "Services/SSH/SSHTunnelManager.h"++namespace gridex {++WorkspaceState::WorkspaceState(QObject* parent)+ : QObject(parent), tunnelMgr_(std::make_unique<SSHTunnelManager>()) {}++WorkspaceState::~WorkspaceState() { close(); }++void WorkspaceState::open(const ConnectionConfig& config,+ const std::optional<std::string>& password,+ SecretStore* secretStore) {+ if (adapter_) close();++ std::optional<std::string> pw = password;+ if (!pw && secretStore) {+ try { pw = secretStore->loadPassword(config.id); }+ catch (...) { /* SecretStore daemon absent — degrade */ }+ }++ // Load SSH password separately if needed.+ std::optional<std::string> sshPw;+ if (config.sshConfig && secretStore) {+ try { sshPw = secretStore->loadSSHPassword(config.id); }+ catch (...) {}+ }++ try {+ ConnectionConfig effective = config;++ // If SSH tunnel configured, establish tunnel first and rewrite host/port.+ if (config.sshConfig) {+ const auto& ssh = *config.sshConfig;+ const auto remoteHost = config.host.value_or("localhost");+ const int remotePort = config.port.value_or(defaultPort(config.databaseType));++ const auto localPort = tunnelMgr_->establish(+ config.id, ssh, remoteHost, remotePort, sshPw);++ effective.host = "127.0.0.1";+ effective.port = static_cast<int>(localPort);++ // Allow relay thread to reach accept() before the adapter connects.+ std::this_thread::sleep_for(std::chrono::milliseconds(200));+ }++ auto adapter = createAdapter(config.databaseType);+ adapter->connect(effective, pw);+ adapter_ = std::move(adapter);+ config_ = config; // store original config (with ssh info), not effective+ emit connectionOpened();+ } catch (const GridexError& e) {+ tunnelMgr_->disconnect(config.id);+ emit connectionFailed(QString::fromUtf8(e.what()));+ throw;+ }+}++void WorkspaceState::switchDatabase(const std::string& dbName, SecretStore* secretStore) {+ if (!adapter_) return;++ // Build modified config with new database name.+ auto cfg = config_;+ cfg.database = dbName;++ // Disconnect current adapter silently (no signals).+ try { adapter_->disconnect(); } catch (...) {}+ adapter_.reset();+ // NOTE: keep tunnel alive — same SSH tunnel, just different DB.++ // Load password.+ std::optional<std::string> pw;+ if (secretStore) {+ try { pw = secretStore->loadPassword(cfg.id); } catch (...) {}+ }++ // Reconnect with new database.+ ConnectionConfig effective = cfg;+ if (cfg.sshConfig && tunnelMgr_) {+ // Tunnel already running — reuse its local port.+ auto st = tunnelMgr_->status(cfg.id);+ if (st == SSHTunnelManager::Status::Connected ||+ st == SSHTunnelManager::Status::Connecting) {+ // Tunnel still alive; adapter needs to reconnect to same local port.+ // Re-establish tunnel to get the port (idempotent — establish() disconnects old first).+ std::optional<std::string> sshPw;+ if (secretStore) {+ try { sshPw = secretStore->loadSSHPassword(cfg.id); } catch (...) {}+ }+ try {+ const auto localPort = tunnelMgr_->establish(+ cfg.id, *cfg.sshConfig,+ cfg.host.value_or("localhost"),+ cfg.port.value_or(defaultPort(cfg.databaseType)),+ sshPw);+ effective.host = "127.0.0.1";+ effective.port = static_cast<int>(localPort);+ std::this_thread::sleep_for(std::chrono::milliseconds(200));+ } catch (...) {+ // Tunnel re-establish failed; try direct connect.+ }+ }+ }++ auto adapter = createAdapter(cfg.databaseType);+ adapter->connect(effective, pw);+ adapter_ = std::move(adapter);+ config_ = cfg;+ // Emit databaseSwitched — NOT connectionOpened (avoids HomeView flip).+}++void WorkspaceState::close() {+ if (!adapter_) return;+ try { adapter_->disconnect(); } catch (...) {}+ adapter_.reset();+ tunnelMgr_->disconnectAll();+ emit connectionClosed();+}++}diff --git a/linux/src/Presentation/ViewModels/WorkspaceState.h b/linux/src/Presentation/ViewModels/WorkspaceState.hnew file mode 100644index 0000000..83aecf5--- /dev/null+++ b/linux/src/Presentation/ViewModels/WorkspaceState.h@@ -0,0 +1,52 @@+#pragma once++#include <QObject>+#include <memory>+#include <optional>+#include <string>++#include "Core/Models/Database/ConnectionConfig.h"+#include "Core/Protocols/Database/IDatabaseAdapter.h"++namespace gridex {++class SecretStore;+class SSHTunnelManager;++// Holds the currently-active database connection. Mirrors the macOS+// AppState.activeAdapter + activeConnection pair. UI listens to signals to+// switch between HomeView and WorkspaceView.+// When sshConfig is present, an SSH tunnel is established first and the adapter+// connects via localhost:<tunnelPort>.+class WorkspaceState : public QObject {+ Q_OBJECT++public:+ explicit WorkspaceState(QObject* parent = nullptr);+ ~WorkspaceState() override;++ void open(const ConnectionConfig& config,+ const std::optional<std::string>& password = std::nullopt,+ SecretStore* secretStore = nullptr);++ // Switch database without emitting connectionClosed/Opened (stays in workspace).+ void switchDatabase(const std::string& dbName, SecretStore* secretStore = nullptr);++ void close();++ [[nodiscard]] bool isOpen() const noexcept { return adapter_ != nullptr; }+ [[nodiscard]] IDatabaseAdapter* adapter() const noexcept { return adapter_.get(); }+ [[nodiscard]] const ConnectionConfig& config() const noexcept { return config_; }++signals:+ void connectionOpened();+ void connectionClosed();+ void connectionFailed(const QString& message);++private:+ std::unique_ptr<IDatabaseAdapter> adapter_;+ std::unique_ptr<SSHTunnelManager> tunnelMgr_;+ ConnectionConfig config_;+};++}diff --git a/linux/src/Presentation/Views/AIChat/AIChatView.cpp b/linux/src/Presentation/Views/AIChat/AIChatView.cppnew file mode 100644index 0000000..275e2b7--- /dev/null+++ b/linux/src/Presentation/Views/AIChat/AIChatView.cpp@@ -0,0 +1,813 @@+#include "Presentation/Views/AIChat/AIChatView.h"++#include <QApplication>+#include <QClipboard>+#include <QEvent>+#include <QFrame>+#include <QHBoxLayout>+#include <QKeyEvent>+#include <QLabel>+#include <QLayoutItem>+#include <QLinearGradient>+#include <QMenu>+#include <QMessageBox>+#include <QPainter>+#include <QPainterPath>+#include <QPixmap>+#include <QPushButton>+#include <QScrollArea>+#include <QScrollBar>+#include <QStackedWidget>+#include <QTextEdit>+#include <QTimer>+#include <QToolButton>+#include <QVBoxLayout>+#include <QVariantAnimation>++#include "Core/Enums/DatabaseType.h"+#include "Core/Enums/SQLDialect.h"+#include "Core/Errors/GridexError.h"+#include "Core/Models/AI/AIModels.h"+#include "Core/Models/Schema/SchemaSnapshot.h"+#include "Core/Protocols/Database/IDatabaseAdapter.h"+#include "Data/Keychain/SecretStore.h"+#include "Presentation/ViewModels/AIChatViewModel.h"+#include "Presentation/ViewModels/WorkspaceState.h"++namespace gridex {++namespace {++// Catppuccin accent gradient (mauve → blue) matching macOS purple→blue.+constexpr const char* kGrad1 = "#cba6f7";+constexpr const char* kGrad2 = "#89b4fa";++// Paint a gradient square with an emoji glyph centred — used for brand icons+// and user/assistant avatars. Returns a QPixmap at 2x for HiDPI.+QPixmap makeGradientGlyphPixmap(int size, const QString& glyph,+ const QColor& c1, const QColor& c2,+ bool circle = false, int radius = 8) {+ const qreal dpr = 2.0;+ QPixmap pm(int(size * dpr), int(size * dpr));+ pm.setDevicePixelRatio(dpr);+ pm.fill(Qt::transparent);+ QPainter p(&pm);+ p.setRenderHint(QPainter::Antialiasing);+ QLinearGradient grad(0, 0, size, size);+ grad.setColorAt(0, c1);+ grad.setColorAt(1, c2);+ p.setBrush(grad);+ p.setPen(Qt::NoPen);+ if (circle) p.drawEllipse(0, 0, size, size);+ else p.drawRoundedRect(0, 0, size, size, radius, radius);++ QFont f = p.font();+ f.setPixelSize(int(size * 0.55));+ f.setBold(true);+ p.setFont(f);+ p.setPen(Qt::white);+ p.drawText(QRect(0, 0, size, size), Qt::AlignCenter, glyph);+ return pm;+}++// Parse `text` into alternating segments: plain text or fenced code block.+// Detects ```lang\n...\n``` and ```\n...\n``` markdown fences.+struct Segment {+ bool isCode = false;+ QString language;+ QString body;+};+std::vector<Segment> parseSegments(const QString& text) {+ std::vector<Segment> out;+ const QStringList lines = text.split('\n');+ QStringList buf;+ auto flushText = [&]() {+ if (buf.isEmpty()) return;+ const QString joined = buf.join('\n').trimmed();+ if (!joined.isEmpty()) out.push_back({false, {}, joined});+ buf.clear();+ };+ int i = 0;+ while (i < lines.size()) {+ const QString trimmed = lines[i].trimmed();+ if (trimmed.startsWith(QStringLiteral("```"))) {+ flushText();+ const QString lang = trimmed.mid(3).trimmed();+ QStringList code;+ ++i;+ while (i < lines.size()+ && lines[i].trimmed() != QStringLiteral("```")) {+ code << lines[i];+ ++i;+ }+ out.push_back({true, lang.isEmpty() ? QStringLiteral("plain") : lang,+ code.join('\n')});+ ++i;+ continue;+ }+ buf << lines[i];+ ++i;+ }+ flushText();+ return out;+}++// Code block widget: header (lang label + Copy button) + monospace body.+QWidget* makeCodeBlock(const QString& language, const QString& code,+ QWidget* parent) {+ auto* w = new QFrame(parent);+ w->setObjectName(QStringLiteral("codeBlock"));+ w->setStyleSheet(QStringLiteral(+ "QFrame#codeBlock { background-color: #11111b;"+ " border: 1px solid #313244; border-radius: 8px; }"));++ auto* v = new QVBoxLayout(w);+ v->setContentsMargins(0, 0, 0, 0);+ v->setSpacing(0);++ // Header+ auto* header = new QWidget(w);+ header->setStyleSheet(QStringLiteral(+ "QWidget { background-color: #181825;"+ " border-top-left-radius: 7px; border-top-right-radius: 7px; }"));+ auto* hh = new QHBoxLayout(header);+ hh->setContentsMargins(10, 4, 10, 4);+ hh->setSpacing(6);+ auto* lang = new QLabel(language.toUpper(), header);+ {+ QFont f = lang->font();+ f.setFamily(QStringLiteral("monospace"));+ f.setPointSize(9);+ f.setWeight(QFont::DemiBold);+ lang->setFont(f);+ }+ lang->setForegroundRole(QPalette::PlaceholderText);+ hh->addWidget(lang);+ hh->addStretch();++ auto* copy = new QToolButton(header);+ copy->setText(QStringLiteral("📋 Copy"));+ copy->setCursor(Qt::PointingHandCursor);+ copy->setStyleSheet(QStringLiteral(+ "QToolButton { background: transparent; border: none;"+ " color: #a6adc8; font-size: 11px; padding: 0 4px; }"+ "QToolButton:hover { color: #cdd6f4; }"));+ QObject::connect(copy, &QToolButton::clicked, copy, [copy, code]() {+ QApplication::clipboard()->setText(code);+ copy->setText(QStringLiteral("✓ Copied"));+ QTimer::singleShot(1500, copy, [copy]() {+ copy->setText(QStringLiteral("📋 Copy"));+ });+ });+ hh->addWidget(copy);+ v->addWidget(header);++ // Body — QLabel with monospace font, wraps horizontal scroll instead+ // of wrapping (code shouldn't be re-flowed).+ auto* body = new QLabel(code, w);+ body->setTextInteractionFlags(Qt::TextSelectableByMouse);+ body->setContentsMargins(12, 8, 12, 10);+ {+ QFont f(QStringLiteral("monospace"));+ f.setStyleHint(QFont::Monospace);+ f.setPointSize(11);+ body->setFont(f);+ }+ body->setStyleSheet(QStringLiteral("color: #cdd6f4;"));+ v->addWidget(body);+ return w;+}++// Animated typing indicator — 3 dots pulsing phase-shifted.+class TypingIndicator : public QWidget {+public:+ explicit TypingIndicator(QWidget* parent = nullptr) : QWidget(parent) {+ setFixedSize(48, 28);+ auto* anim = new QVariantAnimation(this);+ anim->setStartValue(0.0);+ anim->setEndValue(1.0);+ anim->setDuration(900);+ anim->setLoopCount(-1);+ connect(anim, &QVariantAnimation::valueChanged, this, [this](const QVariant& v) {+ phase_ = v.toDouble();+ update();+ });+ anim->start();+ }+protected:+ void paintEvent(QPaintEvent*) override {+ QPainter p(this);+ p.setRenderHint(QPainter::Antialiasing);+ p.setPen(Qt::NoPen);+ const int y = height() / 2;+ for (int i = 0; i < 3; ++i) {+ const double off = i * 0.2;+ const double prog = std::fmod(phase_ + off, 1.0);+ const double scale = 0.7 + 0.5 * std::sin(prog * 3.14159);+ const int r = int(4 * scale);+ const int x = 10 + i * 10;+ const int alpha = int(120 + 135 * std::sin(prog * 3.14159));+ p.setBrush(QColor(186, 194, 222, alpha));+ p.drawEllipse(QPoint(x, y), r, r);+ }+ }+private:+ double phase_ = 0.0;+};++} // namespace++// ---- Construction -----------------------------------------------------++AIChatView::AIChatView(SecretStore* secretStore, WorkspaceState* state, QWidget* parent)+ : QWidget(parent), state_(state) {+ vm_ = new AIChatViewModel(secretStore, this);++ if (state) {+ connect(state, &WorkspaceState::connectionOpened, this, [this, state]() {+ const auto dbTypeStr = QString::fromUtf8(+ std::string(displayName(state->config().databaseType)).c_str());+ vm_->setDatabaseContext(dbTypeStr, QString{});+ });+ if (state->isOpen()) {+ const auto dbTypeStr = QString::fromUtf8(+ std::string(displayName(state->config().databaseType)).c_str());+ vm_->setDatabaseContext(dbTypeStr, QString{});+ }+ }++ buildUi();++ connect(vm_, &AIChatViewModel::messagesChanged, this, &AIChatView::onMessagesChanged);+ connect(vm_, &AIChatViewModel::isLoadingChanged, this, &AIChatView::onLoadingChanged);+ connect(vm_, &AIChatViewModel::errorOccurred, this, &AIChatView::onErrorOccurred);+}++// ---- UI construction --------------------------------------------------++void AIChatView::buildUi() {+ auto* root = new QVBoxLayout(this);+ root->setContentsMargins(0, 0, 0, 0);+ root->setSpacing(0);++ buildHeader(root);++ // Body stack: welcome (empty chat) vs messages list.+ bodyStack_ = new QStackedWidget(this);+ buildWelcomePage();+ buildMessagesPage();+ bodyStack_->addWidget(welcomePage_);+ bodyStack_->addWidget(scrollArea_);+ bodyStack_->setCurrentWidget(welcomePage_);+ root->addWidget(bodyStack_, 1);++ // Chip row — shown when attachedTables_ non-empty.+ chipRow_ = new QWidget(this);+ chipLayout_ = new QHBoxLayout(chipRow_);+ chipLayout_->setContentsMargins(12, 6, 12, 4);+ chipLayout_->setSpacing(6);+ chipLayout_->addStretch();+ chipRow_->setVisible(false);+ root->addWidget(chipRow_);++ buildInputBar(root);++ refreshHeader();+}++void AIChatView::buildHeader(QVBoxLayout* root) {+ auto* header = new QWidget(this);+ header->setFixedHeight(48);+ header->setAutoFillBackground(true);+ header->setBackgroundRole(QPalette::Window);++ auto* h = new QHBoxLayout(header);+ h->setContentsMargins(12, 8, 12, 8);+ h->setSpacing(10);++ // Brand icon: gradient rounded square with ✨.+ brandIcon_ = new QLabel(header);+ brandIcon_->setFixedSize(28, 28);+ brandIcon_->setPixmap(makeGradientGlyphPixmap(+ 28, QStringLiteral("✨"),+ QColor(kGrad1), QColor(kGrad2), /*circle=*/false, /*radius=*/7));+ h->addWidget(brandIcon_);++ // Title + model line+ auto* titleCol = new QVBoxLayout();+ titleCol->setContentsMargins(0, 0, 0, 0);+ titleCol->setSpacing(1);+ brandTitle_ = new QLabel(tr("AI Assistant"), header);+ {+ QFont f = brandTitle_->font();+ f.setWeight(QFont::DemiBold);+ brandTitle_->setFont(f);+ }+ titleCol->addWidget(brandTitle_);++ auto* subRow = new QHBoxLayout();+ subRow->setContentsMargins(0, 0, 0, 0);+ subRow->setSpacing(5);+ statusDot_ = new QLabel(header);+ statusDot_->setFixedSize(8, 8);+ statusDot_->setStyleSheet(QStringLiteral(+ "QLabel { background-color: #f9e2af; border-radius: 4px; }"));+ subRow->addWidget(statusDot_);+ modelStatus_ = new QLabel(header);+ modelStatus_->setForegroundRole(QPalette::PlaceholderText);+ {+ QFont f = modelStatus_->font();+ f.setPointSize(f.pointSize() - 1);+ modelStatus_->setFont(f);+ }+ subRow->addWidget(modelStatus_, 1);+ titleCol->addLayout(subRow);++ h->addLayout(titleCol, 1);++ // New-chat button (circle icon-only).+ newChatBtn_ = new QToolButton(header);+ newChatBtn_->setText(QStringLiteral("↻"));+ newChatBtn_->setFixedSize(28, 28);+ newChatBtn_->setCursor(Qt::PointingHandCursor);+ newChatBtn_->setToolTip(tr("New chat"));+ newChatBtn_->setStyleSheet(QStringLiteral(+ "QToolButton { background-color: #313244; color: #cdd6f4;"+ " border: none; border-radius: 14px; font-size: 14px; }"+ "QToolButton:hover { background-color: #45475a; }"));+ connect(newChatBtn_, &QToolButton::clicked, this, [this]() {+ vm_->clearHistory();+ });+ h->addWidget(newChatBtn_);++ root->addWidget(header);++ auto* div = new QFrame(this);+ div->setFrameShape(QFrame::HLine);+ root->addWidget(div);+}++void AIChatView::buildWelcomePage() {+ welcomePage_ = new QWidget(this);+ auto* v = new QVBoxLayout(welcomePage_);+ v->setContentsMargins(30, 40, 30, 40);+ v->setSpacing(16);+ v->addStretch();++ // Big brand icon (circle)+ auto* bigIcon = new QLabel(welcomePage_);+ bigIcon->setFixedSize(64, 64);+ bigIcon->setAlignment(Qt::AlignCenter);+ bigIcon->setPixmap(makeGradientGlyphPixmap(+ 64, QStringLiteral("✨"),+ QColor(kGrad1), QColor(kGrad2), /*circle=*/true));+ auto* iconRow = new QHBoxLayout();+ iconRow->addStretch();+ iconRow->addWidget(bigIcon);+ iconRow->addStretch();+ v->addLayout(iconRow);++ auto* title = new QLabel(tr("How can I help you?"), welcomePage_);+ title->setAlignment(Qt::AlignCenter);+ {+ QFont f = title->font();+ f.setPointSize(14);+ f.setWeight(QFont::DemiBold);+ title->setFont(f);+ }+ v->addWidget(title);++ auto* subtitle = new QLabel(tr("Ask me anything about your database"), welcomePage_);+ subtitle->setAlignment(Qt::AlignCenter);+ subtitle->setForegroundRole(QPalette::PlaceholderText);+ v->addWidget(subtitle);++ v->addSpacing(12);++ // Suggested prompts+ const QList<QPair<QString, QString>> prompts = {+ {QStringLiteral("🔍"), tr("Show me the schema of all tables")},+ {QStringLiteral("📊"), tr("Find the top 10 records by date")},+ {QStringLiteral("📝"), tr("Generate a SQL query to count rows")},+ {QStringLiteral("💡"), tr("Explain the relationships between tables")},+ };+ for (const auto& [icon, text] : prompts) {+ auto* btn = new QToolButton(welcomePage_);+ btn->setText(QStringLiteral(" %1 %2").arg(icon, text));+ btn->setCursor(Qt::PointingHandCursor);+ btn->setToolButtonStyle(Qt::ToolButtonTextOnly);+ btn->setMinimumHeight(36);+ btn->setStyleSheet(QStringLiteral(+ "QToolButton { background-color: #313244; color: #cdd6f4;"+ " border: 1px solid #45475a; border-radius: 10px;"+ " padding: 8px 12px; text-align: left; font-size: 12px; }"+ "QToolButton:hover { background-color: #45475a; border-color: #585b70; }"));+ connect(btn, &QToolButton::clicked, this, [this, text]() {+ onSuggestedPromptClicked(text);+ });+ v->addWidget(btn);+ }++ v->addStretch();+}++void AIChatView::buildMessagesPage() {+ scrollArea_ = new QScrollArea(this);+ scrollArea_->setWidgetResizable(true);+ scrollArea_->setFrameShape(QFrame::NoFrame);+ scrollArea_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);++ messagesWidget_ = new QWidget(scrollArea_);+ messagesLayout_ = new QVBoxLayout(messagesWidget_);+ messagesLayout_->setContentsMargins(14, 16, 14, 16);+ messagesLayout_->setSpacing(14);+ messagesLayout_->addStretch();++ scrollArea_->setWidget(messagesWidget_);+}++void AIChatView::buildInputBar(QVBoxLayout* root) {+ auto* bar = new QWidget(this);+ auto* outer = new QVBoxLayout(bar);+ outer->setContentsMargins(12, 10, 12, 12);+ outer->setSpacing(0);++ // Capsule: [+] [text edit] [send]+ auto* capsule = new QFrame(bar);+ capsule->setObjectName(QStringLiteral("chatCapsule"));+ capsule->setStyleSheet(QStringLiteral(+ "QFrame#chatCapsule { background-color: #313244;"+ " border: 1px solid #45475a; border-radius: 18px; }"));++ auto* h = new QHBoxLayout(capsule);+ h->setContentsMargins(6, 4, 6, 4);+ h->setSpacing(4);++ attachBtn_ = new QToolButton(capsule);+ attachBtn_->setText(QStringLiteral("+"));+ attachBtn_->setFixedSize(28, 28);+ attachBtn_->setCursor(Qt::PointingHandCursor);+ attachBtn_->setToolTip(tr("Attach tables — their schema is sent as context"));+ attachBtn_->setStyleSheet(QStringLiteral(+ "QToolButton { background-color: #45475a; color: #bac2de;"+ " border: none; border-radius: 14px; font-size: 16px; font-weight: 600; }"+ "QToolButton:hover { background-color: #585b70; color: #cdd6f4; }"+ "QToolButton::menu-indicator { image: none; width: 0; }"));+ connect(attachBtn_, &QToolButton::clicked, this, &AIChatView::onAttachTablesClicked);+ h->addWidget(attachBtn_);++ inputEdit_ = new QTextEdit(capsule);+ inputEdit_->setPlaceholderText(tr("Ask anything..."));+ inputEdit_->setFrameShape(QFrame::NoFrame);+ inputEdit_->setStyleSheet(QStringLiteral(+ "QTextEdit { background: transparent; color: #cdd6f4;"+ " padding: 4px 6px; font-size: 13px; }"));+ inputEdit_->setFixedHeight(36);+ inputEdit_->installEventFilter(this);+ connect(inputEdit_, &QTextEdit::textChanged,+ this, &AIChatView::onInputTextChanged);+ h->addWidget(inputEdit_, 1);++ sendBtn_ = new QToolButton(capsule);+ sendBtn_->setText(QStringLiteral("↑"));+ sendBtn_->setFixedSize(28, 28);+ sendBtn_->setCursor(Qt::PointingHandCursor);+ sendBtn_->setToolTip(tr("Send"));+ sendBtn_->setStyleSheet(QString(+ "QToolButton { background-color: %1; color: white;"+ " border: none; border-radius: 14px; font-size: 15px; font-weight: 700; }"+ "QToolButton:hover { background-color: %2; }"+ "QToolButton:disabled { background-color: #45475a; color: #6c7086; }")+ .arg(kGrad2, kGrad1));+ sendBtn_->setEnabled(false);+ connect(sendBtn_, &QToolButton::clicked, this, &AIChatView::onSendClicked);+ h->addWidget(sendBtn_);++ outer->addWidget(capsule);+ root->addWidget(bar);+}++// ---- Slots ------------------------------------------------------------++void AIChatView::onSendClicked() {+ const QString text = inputEdit_->toPlainText().trimmed();+ if (text.isEmpty()) return;+ inputEdit_->clear();++ const std::string ctx = buildSchemaContext();+ QString full = text;+ if (!ctx.empty()) full = QString::fromStdString(ctx) + "\n\n" + text;+ vm_->sendMessage(full);++ showMessagesIfHidden();+}++void AIChatView::onSuggestedPromptClicked(const QString& prompt) {+ inputEdit_->setPlainText(prompt);+ inputEdit_->setFocus();+ updateSendButton();+}++void AIChatView::onInputTextChanged() {+ updateSendButton();+}++void AIChatView::updateSendButton() {+ const bool canSend = !inputEdit_->toPlainText().trimmed().isEmpty();+ sendBtn_->setEnabled(canSend);+}++void AIChatView::showMessagesIfHidden() {+ if (bodyStack_ && bodyStack_->currentWidget() != scrollArea_) {+ bodyStack_->setCurrentWidget(scrollArea_);+ }+}++void AIChatView::onAttachTablesClicked() {+ if (!state_ || !state_->adapter()) {+ QMessageBox::information(this, tr("Attach Tables"),+ tr("Open a connection first."));+ return;+ }++ std::vector<std::string> names;+ try {+ for (const auto& info : state_->adapter()->listTables(std::nullopt)) {+ if (info.type == TableKind::Table) names.push_back(info.name);+ }+ } catch (const GridexError& e) {+ QMessageBox::warning(this, tr("Attach Tables"), QString::fromUtf8(e.what()));+ return;+ }+ std::sort(names.begin(), names.end());++ QMenu menu(this);+ if (names.empty()) {+ menu.addAction(tr("(no tables)"))->setEnabled(false);+ } else {+ for (const auto& n : names) {+ const QString qn = QString::fromStdString(n);+ auto* act = menu.addAction(qn);+ act->setCheckable(true);+ act->setChecked(attachedTables_.contains(qn));+ connect(act, &QAction::toggled, this, [this, qn](bool on) {+ if (on) attachedTables_.insert(qn);+ else attachedTables_.remove(qn);+ rebuildAttachedChips();+ });+ }+ }+ menu.exec(attachBtn_->mapToGlobal(QPoint(0, attachBtn_->height())));+}++void AIChatView::rebuildAttachedChips() {+ while (chipLayout_->count() > 1) {+ auto* item = chipLayout_->takeAt(0);+ if (item->widget()) item->widget()->deleteLater();+ delete item;+ }++ QStringList sorted(attachedTables_.begin(), attachedTables_.end());+ sorted.sort();++ for (const QString& name : sorted) {+ auto* chip = new QWidget(chipRow_);+ auto* h = new QHBoxLayout(chip);+ h->setContentsMargins(10, 3, 4, 3);+ h->setSpacing(4);+ chip->setStyleSheet(QStringLiteral(+ "QWidget { background-color: rgba(203, 166, 247, 0.18); border-radius: 10px; }"));++ auto* lbl = new QLabel(QStringLiteral("📊 %1").arg(name), chip);+ lbl->setStyleSheet(QStringLiteral("color: #cba6f7; font-weight: 500;"));+ h->addWidget(lbl);++ auto* close = new QToolButton(chip);+ close->setText(QStringLiteral("×"));+ close->setCursor(Qt::PointingHandCursor);+ close->setStyleSheet(QStringLiteral(+ "QToolButton { background: transparent; border: none;"+ " color: #bac2de; font-size: 13px; padding: 0 4px; }"+ "QToolButton:hover { color: #f38ba8; }"));+ connect(close, &QToolButton::clicked, this, [this, name]() {+ attachedTables_.remove(name);+ rebuildAttachedChips();+ });+ h->addWidget(close);++ chipLayout_->insertWidget(chipLayout_->count() - 1, chip);+ }+ chipRow_->setVisible(!attachedTables_.isEmpty());+}++std::string AIChatView::buildSchemaContext() {+ if (attachedTables_.isEmpty() || !state_ || !state_->adapter()) return {};++ auto* adapter = state_->adapter();+ std::string out = "--- Schema Context ---\n";+ QStringList sorted(attachedTables_.begin(), attachedTables_.end());+ sorted.sort();+ for (const QString& name : sorted) {+ try {+ const auto desc = adapter->describeTable(name.toStdString(), std::nullopt);+ out += desc.toDDL(sqlDialect(adapter->databaseType()));+ out += "\n";+ } catch (...) {+ out += "-- (failed to describe " + name.toStdString() + ")\n";+ }+ }+ return out;+}++void AIChatView::onMessagesChanged() {+ rebuildMessages();+ if (!vm_->messages().empty()) showMessagesIfHidden();+ else if (bodyStack_) bodyStack_->setCurrentWidget(welcomePage_);+}++void AIChatView::onLoadingChanged(bool loading) {+ sendBtn_->setEnabled(!loading && !inputEdit_->toPlainText().trimmed().isEmpty());+ inputEdit_->setEnabled(!loading);++ // Remove any existing typing indicator first.+ if (typingWidget_) {+ typingWidget_->deleteLater();+ typingWidget_ = nullptr;+ }+ if (loading) {+ // Insert typing indicator row before the trailing stretch.+ auto* row = new QWidget(messagesWidget_);+ auto* rowH = new QHBoxLayout(row);+ rowH->setContentsMargins(0, 0, 0, 0);+ rowH->setSpacing(10);+ auto* avatar = new QLabel(row);+ avatar->setFixedSize(28, 28);+ avatar->setPixmap(makeGradientGlyphPixmap(+ 28, QStringLiteral("✨"),+ QColor(kGrad1), QColor(kGrad2), true));+ rowH->addWidget(avatar, 0, Qt::AlignTop);+ rowH->addWidget(new TypingIndicator(row));+ rowH->addStretch();+ const int stretchIdx = messagesLayout_->count() - 1;+ messagesLayout_->insertWidget(stretchIdx, row);+ typingWidget_ = row;++ QTimer::singleShot(50, this, [this]() {+ if (scrollArea_) {+ QScrollBar* sb = scrollArea_->verticalScrollBar();+ sb->setValue(sb->maximum());+ }+ });+ }+}++void AIChatView::onErrorOccurred(const QString& message) {+ QMessageBox::warning(this, tr("AI Error"), message);+}++void AIChatView::refreshHeader() {+ if (!modelStatus_ || !vm_) return;+ const QString prov = vm_->selectedProvider();+ const QString model = vm_->selectedModel();+ modelStatus_->setText(model.isEmpty()+ ? tr("Not configured")+ : QStringLiteral("%1 · %2").arg(prov, model));++ // Status dot: green when model is set (assume key present via Settings),+ // yellow/warn when nothing.+ const bool configured = !model.isEmpty();+ statusDot_->setStyleSheet(QString(+ "QLabel { background-color: %1; border-radius: 4px; }")+ .arg(configured ? QStringLiteral("#a6e3a1") : QStringLiteral("#f9e2af")));+}++// ---- Message rendering ------------------------------------------------++namespace {++// Build the bubble content for a single message — list of widgets+// (text bubble and/or code blocks) stacked vertically.+QWidget* makeBubbleColumn(const ChatMessage& msg, QWidget* parent) {+ const bool isUser = (msg.role == LLMMessage::Role::User);+ auto* col = new QWidget(parent);+ auto* v = new QVBoxLayout(col);+ v->setContentsMargins(0, 0, 0, 0);+ v->setSpacing(6);++ // Sender label above the bubble.+ auto* sender = new QLabel(isUser ? QObject::tr("You") : QObject::tr("Assistant"), col);+ sender->setStyleSheet(QStringLiteral("color: #7f849c; font-size: 10px; font-weight: 600;"));+ sender->setAlignment(isUser ? Qt::AlignRight : Qt::AlignLeft);+ v->addWidget(sender);++ // Parse markdown segments.+ const QString text = QString::fromStdString(msg.content);+ const auto segments = parseSegments(text);++ if (segments.empty()) {+ auto* lbl = new QLabel(text.isEmpty() ? QStringLiteral(" ") : text, col);+ lbl->setWordWrap(true);+ lbl->setTextInteractionFlags(Qt::TextSelectableByMouse);+ lbl->setContentsMargins(12, 9, 12, 9);+ lbl->setStyleSheet(isUser+ ? QString("QLabel { background-color: %1; color: white;"+ " border-top-left-radius: 14px; border-top-right-radius: 14px;"+ " border-bottom-left-radius: 14px; border-bottom-right-radius: 4px;"+ " font-size: 13px; }").arg(kGrad2)+ : QStringLiteral("QLabel { background-color: #313244; color: #cdd6f4;"+ " border-top-left-radius: 14px; border-top-right-radius: 14px;"+ " border-bottom-left-radius: 4px; border-bottom-right-radius: 14px;"+ " font-size: 13px; }"));+ v->addWidget(lbl);+ } else {+ for (const auto& seg : segments) {+ if (seg.isCode) {+ v->addWidget(makeCodeBlock(seg.language, seg.body, col));+ } else {+ auto* lbl = new QLabel(seg.body, col);+ lbl->setWordWrap(true);+ lbl->setTextInteractionFlags(Qt::TextSelectableByMouse);+ lbl->setContentsMargins(12, 9, 12, 9);+ lbl->setStyleSheet(isUser+ ? QString("QLabel { background-color: %1; color: white;"+ " border-top-left-radius: 14px; border-top-right-radius: 14px;"+ " border-bottom-left-radius: 14px; border-bottom-right-radius: 4px;"+ " font-size: 13px; }").arg(kGrad2)+ : QStringLiteral("QLabel { background-color: #313244; color: #cdd6f4;"+ " border-top-left-radius: 14px; border-top-right-radius: 14px;"+ " border-bottom-left-radius: 4px; border-bottom-right-radius: 14px;"+ " font-size: 13px; }"));+ v->addWidget(lbl);+ }+ }+ }+ return col;+}++} // namespace++void AIChatView::rebuildMessages() {+ // Clear everything except trailing stretch.+ while (messagesLayout_->count() > 1) {+ auto* item = messagesLayout_->takeAt(0);+ if (item->widget()) item->widget()->deleteLater();+ delete item;+ }+ typingWidget_ = nullptr; // cleared above++ const auto& msgs = vm_->messages();+ for (const auto& msg : msgs) {+ const bool isUser = (msg.role == LLMMessage::Role::User);++ auto* row = new QWidget(messagesWidget_);+ auto* rowH = new QHBoxLayout(row);+ rowH->setContentsMargins(0, 0, 0, 0);+ rowH->setSpacing(10);++ auto addAvatar = [&]() {+ auto* avatar = new QLabel(row);+ avatar->setFixedSize(28, 28);+ avatar->setPixmap(makeGradientGlyphPixmap(+ 28,+ isUser ? QStringLiteral("🧑") : QStringLiteral("✨"),+ isUser ? QColor("#585b70") : QColor(kGrad1),+ isUser ? QColor("#45475a") : QColor(kGrad2),+ /*circle=*/true));+ rowH->addWidget(avatar, 0, Qt::AlignTop);+ };++ if (!isUser) addAvatar();+ else rowH->addSpacing(40);++ rowH->addWidget(makeBubbleColumn(msg, row), 1,+ isUser ? Qt::AlignRight : Qt::AlignLeft);++ if (isUser) addAvatar();+ else rowH->addSpacing(40);++ const int stretchIdx = messagesLayout_->count() - 1;+ messagesLayout_->insertWidget(stretchIdx, row);+ }++ // Auto-scroll to bottom.+ QTimer::singleShot(0, this, [this]() {+ if (scrollArea_) {+ QScrollBar* sb = scrollArea_->verticalScrollBar();+ sb->setValue(sb->maximum());+ }+ });+}++bool AIChatView::eventFilter(QObject* obj, QEvent* event) {+ if (obj == inputEdit_ && event->type() == QEvent::KeyPress) {+ auto* ke = static_cast<QKeyEvent*>(event);+ if ((ke->key() == Qt::Key_Return || ke->key() == Qt::Key_Enter)+ && !(ke->modifiers() & Qt::ShiftModifier)) {+ onSendClicked();+ return true;+ }+ }+ return QWidget::eventFilter(obj, event);+}++} // namespace gridexdiff --git a/linux/src/Presentation/Views/AIChat/AIChatView.h b/linux/src/Presentation/Views/AIChat/AIChatView.hnew file mode 100644index 0000000..f3ccaf5--- /dev/null+++ b/linux/src/Presentation/Views/AIChat/AIChatView.h@@ -0,0 +1,92 @@+#pragma once++#include <QPointer>+#include <QSet>+#include <QString>+#include <QWidget>++class QHBoxLayout;+class QLabel;+class QPushButton;+class QScrollArea;+class QStackedWidget;+class QTextEdit;+class QToolButton;+class QVBoxLayout;++namespace gridex {++class AIChatViewModel;+class SecretStore;+class WorkspaceState;++// AI chat panel. Provider/model/API-key configuration lives in the+// Preferences dialog (File → Preferences); this tab is just the chat.+// Visual design mirrors the macOS SwiftUI implementation: brand header,+// welcome screen with suggested prompts, avatar bubbles with asymmetric+// rounded corners, gradient user messages, typing indicator, code blocks.+class AIChatView : public QWidget {+ Q_OBJECT++public:+ explicit AIChatView(SecretStore* secretStore,+ WorkspaceState* state = nullptr,+ QWidget* parent = nullptr);++private slots:+ void onSendClicked();+ void onMessagesChanged();+ void onLoadingChanged(bool loading);+ void onErrorOccurred(const QString& message);+ void onAttachTablesClicked();+ void onSuggestedPromptClicked(const QString& prompt);+ void onInputTextChanged();++private:+ void buildUi();+ void buildHeader(QVBoxLayout* root);+ void buildWelcomePage();+ void buildMessagesPage();+ void buildInputBar(QVBoxLayout* root);+ void rebuildMessages();+ void rebuildAttachedChips();+ void refreshHeader();+ void updateSendButton();+ void showMessagesIfHidden();+ std::string buildSchemaContext();+ bool eventFilter(QObject* obj, QEvent* event) override;++ AIChatViewModel* vm_ = nullptr;+ QPointer<WorkspaceState> state_;++ // Header+ QLabel* brandTitle_ = nullptr;+ QLabel* brandIcon_ = nullptr; // gradient sparkle+ QLabel* modelStatus_ = nullptr; // "gemini-2.5-flash" / "Not configured"+ QLabel* statusDot_ = nullptr; // green dot when key present+ QToolButton* newChatBtn_ = nullptr;++ // Body stack: welcome / messages+ QStackedWidget* bodyStack_ = nullptr;++ // Welcome page+ QWidget* welcomePage_ = nullptr;++ // Messages page+ QScrollArea* scrollArea_ = nullptr;+ QWidget* messagesWidget_ = nullptr;+ QVBoxLayout* messagesLayout_ = nullptr;+ QWidget* typingWidget_ = nullptr; // transient indicator++ // Attached-tables chip row+ QWidget* chipRow_ = nullptr;+ QHBoxLayout* chipLayout_ = nullptr;+ QSet<QString> attachedTables_;++ // Input capsule+ QToolButton* attachBtn_ = nullptr;+ QTextEdit* inputEdit_ = nullptr;+ QToolButton* sendBtn_ = nullptr;+};++} // namespace gridexdiff --git a/linux/src/Presentation/Views/Backup/BackupProgressDialog.cpp b/linux/src/Presentation/Views/Backup/BackupProgressDialog.cppnew file mode 100644index 0000000..3341a77--- /dev/null+++ b/linux/src/Presentation/Views/Backup/BackupProgressDialog.cpp@@ -0,0 +1,270 @@+#include "Presentation/Views/Backup/BackupProgressDialog.h"++#include <QDialogButtonBox>+#include <QHBoxLayout>+#include <QLabel>+#include <QPlainTextEdit>+#include <QProcess>+#include <QProcessEnvironment>+#include <QProgressBar>+#include <QPushButton>+#include <QTimer>+#include <QVBoxLayout>++#include "Core/Enums/DatabaseType.h"++namespace gridex {++namespace {++struct DumpSpec {+ QString program;+ QStringList args;+ bool stdoutToFile = false;+ bool stdinFromFile = false;+};++std::optional<DumpSpec> makeBackupSpec(const ConnectionConfig& c, const QString& outPath) {+ DumpSpec s;+ switch (c.databaseType) {+ case DatabaseType::PostgreSQL:+ s.program = QStringLiteral("pg_dump");+ s.args << QStringLiteral("-h") << QString::fromStdString(c.host.value_or("localhost"))+ << QStringLiteral("-p") << QString::number(c.port.value_or(5432))+ << QStringLiteral("-U") << QString::fromStdString(c.username.value_or(""))+ << QStringLiteral("-f") << outPath+ << QString::fromStdString(c.database.value_or(""));+ return s;+ case DatabaseType::MySQL:+ s.program = QStringLiteral("mysqldump");+ s.args << QStringLiteral("-h") << QString::fromStdString(c.host.value_or("localhost"))+ << QStringLiteral("-P") << QString::number(c.port.value_or(3306))+ << QStringLiteral("-u") << QString::fromStdString(c.username.value_or(""))+ << (QStringLiteral("--result-file=") + outPath)+ << QString::fromStdString(c.database.value_or(""));+ return s;+ case DatabaseType::SQLite:+ s.program = QStringLiteral("sqlite3");+ s.args << QString::fromStdString(c.filePath.value_or("")) << QStringLiteral(".dump");+ s.stdoutToFile = true;+ return s;+ default:+ return std::nullopt;+ }+}++std::optional<DumpSpec> makeRestoreSpec(const ConnectionConfig& c, const QString& inPath) {+ DumpSpec s;+ switch (c.databaseType) {+ case DatabaseType::PostgreSQL:+ s.program = QStringLiteral("psql");+ s.args << QStringLiteral("-h") << QString::fromStdString(c.host.value_or("localhost"))+ << QStringLiteral("-p") << QString::number(c.port.value_or(5432))+ << QStringLiteral("-U") << QString::fromStdString(c.username.value_or(""))+ << QStringLiteral("-d") << QString::fromStdString(c.database.value_or(""))+ << QStringLiteral("-f") << inPath;+ return s;+ case DatabaseType::MySQL:+ s.program = QStringLiteral("mysql");+ s.args << QStringLiteral("-h") << QString::fromStdString(c.host.value_or("localhost"))+ << QStringLiteral("-P") << QString::number(c.port.value_or(3306))+ << QStringLiteral("-u") << QString::fromStdString(c.username.value_or(""))+ << QString::fromStdString(c.database.value_or(""));+ s.stdinFromFile = true;+ return s;+ case DatabaseType::SQLite:+ s.program = QStringLiteral("sqlite3");+ s.args << QString::fromStdString(c.filePath.value_or(""));+ s.stdinFromFile = true;+ return s;+ default:+ return std::nullopt;+ }+}++} // namespace++BackupProgressDialog::BackupProgressDialog(Mode mode,+ const ConnectionConfig& cfg,+ const std::optional<std::string>& password,+ const QString& filePath,+ QWidget* parent)+ : QDialog(parent)+ , mode_(mode)+ , cfg_(cfg)+ , password_(password)+ , filePath_(filePath)+{+ const QString dbName = QString::fromStdString(cfg_.database.value_or(cfg_.name));+ buildUi(dbName);+ setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);+ resize(560, 360);+}++BackupProgressDialog::~BackupProgressDialog() {+ if (process_ && process_->state() != QProcess::NotRunning) {+ process_->terminate();+ process_->waitForFinished(500);+ if (process_->state() != QProcess::NotRunning)+ process_->kill();+ }+}++void BackupProgressDialog::buildUi(const QString& dbName) {+ const bool isBackup = (mode_ == Mode::Backup);+ setWindowTitle(isBackup ? tr("Backup Database") : tr("Restore Database"));++ auto* root = new QVBoxLayout(this);+ root->setSpacing(10);+ root->setContentsMargins(16, 14, 16, 14);++ headerLabel_ = new QLabel(+ isBackup ? tr("Backing up %1...").arg(dbName)+ : tr("Restoring %1...").arg(dbName),+ this);+ QFont f = headerLabel_->font();+ f.setPointSize(f.pointSize() + 1);+ f.setBold(true);+ headerLabel_->setFont(f);+ root->addWidget(headerLabel_);++ progressBar_ = new QProgressBar(this);+ progressBar_->setRange(0, 0); // indeterminate+ progressBar_->setTextVisible(false);+ progressBar_->setFixedHeight(6);+ root->addWidget(progressBar_);++ logView_ = new QPlainTextEdit(this);+ logView_->setReadOnly(true);+ logView_->setMaximumBlockCount(500);+ QFont mono = logView_->font();+ mono.setFamily(QStringLiteral("Monospace"));+ mono.setPointSize(mono.pointSize() - 1);+ logView_->setFont(mono);+ logView_->setMinimumHeight(180);+ root->addWidget(logView_, 1);++ auto* btnRow = new QHBoxLayout;+ btnRow->setSpacing(8);+ btnRow->addStretch();++ cancelBtn_ = new QPushButton(tr("Cancel"), this);+ connect(cancelBtn_, &QPushButton::clicked, this, &BackupProgressDialog::onCancel);+ btnRow->addWidget(cancelBtn_);++ closeBtn_ = new QPushButton(tr("Close"), this);+ closeBtn_->setEnabled(false);+ connect(closeBtn_, &QPushButton::clicked, this, &QDialog::accept);+ btnRow->addWidget(closeBtn_);++ root->addLayout(btnRow);+}++void BackupProgressDialog::start() {+ const auto spec = (mode_ == Mode::Backup)+ ? makeBackupSpec(cfg_, filePath_)+ : makeRestoreSpec(cfg_, filePath_);++ if (!spec) {+ appendLog(tr("Error: database type not supported for dump operations."));+ markDone(false);+ return;+ }++ process_ = new QProcess(this);++ QProcessEnvironment env = QProcessEnvironment::systemEnvironment();+ if (password_ && !password_->empty()) {+ if (cfg_.databaseType == DatabaseType::PostgreSQL)+ env.insert(QStringLiteral("PGPASSWORD"), QString::fromStdString(*password_));+ else if (cfg_.databaseType == DatabaseType::MySQL)+ env.insert(QStringLiteral("MYSQL_PWD"), QString::fromStdString(*password_));+ }+ process_->setProcessEnvironment(env);++ if (spec->stdoutToFile)+ process_->setStandardOutputFile(filePath_, QIODevice::Truncate);+ if (spec->stdinFromFile)+ process_->setStandardInputFile(filePath_);++ connect(process_, &QProcess::readyReadStandardOutput,+ this, &BackupProgressDialog::onReadyRead);+ connect(process_, &QProcess::readyReadStandardError,+ this, &BackupProgressDialog::onReadyRead);+ connect(process_, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),+ this, [this](int code, QProcess::ExitStatus) { onFinished(code, 0); });++ appendLog(tr("Starting %1...").arg(spec->program));+ process_->start(spec->program, spec->args);++ if (!process_->waitForStarted(5000)) {+ appendLog(tr("Failed to start '%1'. Ensure it is installed and on PATH.").arg(spec->program));+ markDone(false);+ }+}++void BackupProgressDialog::onReadyRead() {+ if (!process_) return;+ const auto outData = process_->readAllStandardOutput();+ const auto errData = process_->readAllStandardError();+ if (!outData.isEmpty())+ appendLog(QString::fromUtf8(outData).trimmed());+ if (!errData.isEmpty())+ appendLog(QString::fromUtf8(errData).trimmed());+}++void BackupProgressDialog::onFinished(int exitCode, int /*exitStatus*/) {+ // Drain any remaining output+ if (process_) {+ const auto out = process_->readAllStandardOutput();+ const auto err = process_->readAllStandardError();+ if (!out.isEmpty()) appendLog(QString::fromUtf8(out).trimmed());+ if (!err.isEmpty()) appendLog(QString::fromUtf8(err).trimmed());+ }+ markDone(exitCode == 0,+ exitCode != 0 ? tr("Process exited with code %1").arg(exitCode) : QString{});+}++void BackupProgressDialog::onCancel() {+ if (!process_ || process_->state() == QProcess::NotRunning) {+ reject();+ return;+ }+ cancelBtn_->setEnabled(false);+ appendLog(tr("Cancelling..."));+ process_->terminate();+ QTimer::singleShot(2000, this, [this] {+ if (process_ && process_->state() != QProcess::NotRunning)+ process_->kill();+ });+}++void BackupProgressDialog::appendLog(const QString& line) {+ if (line.trimmed().isEmpty()) return;+ logView_->appendPlainText(line);+}++void BackupProgressDialog::markDone(bool ok, const QString& extra) {+ succeeded_ = ok;+ progressBar_->setRange(0, 1);+ progressBar_->setValue(1);++ const bool isBackup = (mode_ == Mode::Backup);+ if (ok) {+ setWindowTitle(isBackup ? tr("Backup Complete") : tr("Restore Complete"));+ headerLabel_->setText(isBackup ? tr("Backup finished successfully.")+ : tr("Restore finished successfully."));+ } else {+ setWindowTitle(isBackup ? tr("Backup Failed") : tr("Restore Failed"));+ headerLabel_->setText(isBackup ? tr("Backup failed.")+ : tr("Restore failed."));+ if (!extra.isEmpty()) appendLog(extra);+ }++ cancelBtn_->setEnabled(false);+ closeBtn_->setEnabled(true);+ closeBtn_->setDefault(true);+ closeBtn_->setFocus();+}++} // namespace gridexdiff --git a/linux/src/Presentation/Views/Backup/BackupProgressDialog.h b/linux/src/Presentation/Views/Backup/BackupProgressDialog.hnew file mode 100644index 0000000..941bcdc--- /dev/null+++ b/linux/src/Presentation/Views/Backup/BackupProgressDialog.h@@ -0,0 +1,64 @@+#pragma once++#include <optional>+#include <string>++#include <QDialog>+#include <QString>++#include "Core/Models/Database/ConnectionConfig.h"++class QLabel;+class QPlainTextEdit;+class QProgressBar;+class QPushButton;+class QProcess;++namespace gridex {++// Modal dialog that runs pg_dump / mysqldump / sqlite3 (or their restore+// counterparts) asynchronously and streams stderr into a log area.+class BackupProgressDialog : public QDialog {+ Q_OBJECT++public:+ enum class Mode { Backup, Restore };++ explicit BackupProgressDialog(Mode mode,+ const ConnectionConfig& cfg,+ const std::optional<std::string>& password,+ const QString& filePath,+ QWidget* parent = nullptr);+ ~BackupProgressDialog();++ // Start the process. Call once after showing the dialog.+ void start();++ bool succeeded() const { return succeeded_; }++private slots:+ void onReadyRead();+ void onFinished(int exitCode, int exitStatus);+ void onCancel();++private:+ void buildUi(const QString& dbName);+ void appendLog(const QString& line);+ void markDone(bool ok, const QString& extra = {});++ Mode mode_;+ ConnectionConfig cfg_;+ std::optional<std::string> password_;+ QString filePath_;+ bool succeeded_ = false;++ QLabel* headerLabel_ = nullptr;+ QProgressBar* progressBar_ = nullptr;+ QPlainTextEdit* logView_ = nullptr;+ QPushButton* cancelBtn_ = nullptr;+ QPushButton* closeBtn_ = nullptr;++ QProcess* process_ = nullptr;+};++} // namespace gridexdiff --git a/linux/src/Presentation/Views/ConnectionForm/ConnectionFormDialog.cpp b/linux/src/Presentation/Views/ConnectionForm/ConnectionFormDialog.cppnew file mode 100644index 0000000..97785af--- /dev/null+++ b/linux/src/Presentation/Views/ConnectionForm/ConnectionFormDialog.cpp@@ -0,0 +1,624 @@+#include "Presentation/Views/ConnectionForm/ConnectionFormDialog.h"++#include <QCheckBox>+#include <QComboBox>+#include <QFileDialog>+#include <QFrame>+#include <QGraphicsDropShadowEffect>+#include <QHBoxLayout>+#include <QLabel>+#include <QLineEdit>+#include <QPushButton>+#include <QSpinBox>+#include <QString>+#include <QUuid>+#include <QVBoxLayout>+#include <QWidget>++#include "Core/Enums/SSLMode.h"++namespace gridex {++namespace {++QString qs(const std::string& s) { return QString::fromUtf8(s.c_str(), static_cast<int>(s.size())); }+std::string st(const QString& s) { return s.toStdString(); }++constexpr int kLabelWidth = 110;+constexpr int kRowSpacing = 10;++// One labeled form row: fixed-width label on the left, content on the right.+QWidget* makeRow(const QString& label, QWidget* content, QWidget* parent) {+ auto* row = new QWidget(parent);+ auto* h = new QHBoxLayout(row);+ h->setContentsMargins(0, 0, 0, 0);+ h->setSpacing(8);+ auto* lbl = new QLabel(label, row);+ lbl->setMinimumWidth(kLabelWidth);+ lbl->setMaximumWidth(kLabelWidth);+ lbl->setAlignment(Qt::AlignRight | Qt::AlignVCenter);+ h->addWidget(lbl);+ h->addWidget(content, 1);+ return row;+}++}++ConnectionFormDialog::ConnectionFormDialog(QWidget* parent) : QDialog(parent) {+ setWindowTitle(tr("Connection"));+ setMinimumWidth(580);++ // Give the dialog a clearly-separated body: a bordered inner frame sitting on+ // an outer transparent margin. This reads as a distinct "sheet" even when+ // the WM doesn't paint a strong shadow (Wayland + minimal themes).+ setModal(true);+ setWindowModality(Qt::ApplicationModal);+ setAttribute(Qt::WA_TranslucentBackground, false);++ buildUi();+ applyLayoutForType(DatabaseType::PostgreSQL);+ updateButtonStates();+}++void ConnectionFormDialog::buildUi() {+ // Wrap content in a bordered card with drop shadow so the dialog reads as+ // a distinct sheet even when the window manager (e.g. Wayland + Fusion)+ // doesn't render a strong shadow around the OS window decoration.+ auto* outer = new QVBoxLayout(this);+ outer->setContentsMargins(14, 14, 14, 14);+ outer->setSpacing(0);++ auto* card = new QFrame(this);+ card->setObjectName(QStringLiteral("ConnectionFormCard"));+ auto* shadow = new QGraphicsDropShadowEffect(card);+ shadow->setBlurRadius(28);+ shadow->setOffset(0, 4);+ shadow->setColor(QColor(0, 0, 0, 120));+ card->setGraphicsEffect(shadow);+ outer->addWidget(card);++ auto* root = new QVBoxLayout(card);+ root->setContentsMargins(24, 20, 24, 12);+ root->setSpacing(kRowSpacing);++ // Title bar inside the card for visual anchor (matches macOS sheet header).+ auto* header = new QLabel(tr("Connection"), card);+ root->addWidget(header);+ auto* headerDiv = new QFrame(card);+ headerDiv->setFrameShape(QFrame::HLine);+ root->addWidget(headerDiv);+ root->addSpacing(4);++ // --- Row: Name ---+ nameEdit_ = new QLineEdit(this);+ nameEdit_->setPlaceholderText(tr("Connection name"));+ connect(nameEdit_, &QLineEdit::textChanged, this, &ConnectionFormDialog::onFieldChanged);+ root->addWidget(makeRow(tr("Name"), nameEdit_, this));++ // --- Row: Type (Linux-only helper — macOS chooses via DatabaseTypePicker before opening the form) ---+ typeCombo_ = new QComboBox(this);+ for (auto t : kAllDatabaseTypes) {+ typeCombo_->addItem(QString::fromUtf8(std::string(displayName(t)).c_str()),+ QString::fromUtf8(std::string(rawValue(t)).c_str()));+ }+ connect(typeCombo_, QOverload<int>::of(&QComboBox::currentIndexChanged),+ this, &ConnectionFormDialog::onDatabaseTypeChanged);+ root->addWidget(makeRow(tr("Type"), typeCombo_, this));++ // --- Row: Status color (6 dots + Tag dropdown) ---+ auto* colorRow = new QWidget(this);+ auto* colorH = new QHBoxLayout(colorRow);+ colorH->setContentsMargins(0, 0, 0, 0);+ colorH->setSpacing(6);+ const std::array<ColorTag, 6> tags = {+ ColorTag::Red, ColorTag::Orange, ColorTag::Green,+ ColorTag::Blue, ColorTag::Purple, ColorTag::Gray,+ };+ for (int i = 0; i < 6; ++i) {+ auto* dot = new QPushButton(colorRow);+ dot->setFixedSize(28, 20);+ dot->setCheckable(true);+ const auto rgb = rgbColor(tags[i]);+ dot->setStyleSheet(QString("QPushButton { background-color: rgb(%1,%2,%3); border-radius: 3px; border: 0px solid white; }"+ "QPushButton:checked { border: 2px solid palette(highlight); }")+ .arg(rgb.r).arg(rgb.g).arg(rgb.b));+ connect(dot, &QPushButton::clicked, this, [this, i] { onColorDotClicked(i); });+ colorDots_[i] = dot;+ colorH->addWidget(dot);+ }+ colorH->addStretch();+ auto* tagLbl = new QLabel(tr("Tag"), colorRow);+ colorH->addWidget(tagLbl);+ colorCombo_ = new QComboBox(colorRow);+ colorCombo_->setMinimumWidth(120);+ for (auto t : kAllColorTags) {+ colorCombo_->addItem(QString::fromUtf8(std::string(environmentHint(t)).c_str()),+ QString::fromUtf8(std::string(rawValue(t)).c_str()));+ }+ connect(colorCombo_, QOverload<int>::of(&QComboBox::currentIndexChanged),+ this, [this](int idx) {+ const auto raw = st(colorCombo_->itemData(idx).toString());+ colorTag_ = colorTagFromRaw(raw).value_or(ColorTag::Blue);+ refreshColorDotBorders();+ });+ colorH->addWidget(colorCombo_);+ root->addWidget(makeRow(tr("Status color"), colorRow, this));++ // --- SQLite file page ---+ filePage_ = new QWidget(this);+ {+ auto* h = new QHBoxLayout(filePage_);+ h->setContentsMargins(0, 0, 0, 0);+ h->setSpacing(8);+ filePathEdit_ = new QLineEdit(filePage_);+ filePathEdit_->setPlaceholderText(tr("path/to/database.db"));+ connect(filePathEdit_, &QLineEdit::textChanged, this, &ConnectionFormDialog::onFieldChanged);+ filePickBtn_ = new QPushButton(tr("Browse..."), filePage_);+ connect(filePickBtn_, &QPushButton::clicked, this, &ConnectionFormDialog::onBrowseFile);+ h->addWidget(filePathEdit_, 1);+ h->addWidget(filePickBtn_);+ }+ root->addWidget(makeRow(tr("File"), filePage_, this));++ // --- Host-based page (contains all PG/MySQL/MSSQL/Mongo/Redis rows) ---+ hostPage_ = new QWidget(this);+ auto* hostV = new QVBoxLayout(hostPage_);+ hostV->setContentsMargins(0, 0, 0, 0);+ hostV->setSpacing(kRowSpacing);++ // Host + Port (same row, aligned to form via makeRow semantics on the child)+ {+ auto* hp = new QWidget(hostPage_);+ auto* h = new QHBoxLayout(hp);+ h->setContentsMargins(0, 0, 0, 0);+ h->setSpacing(8);+ hostEdit_ = new QLineEdit(hp);+ hostEdit_->setPlaceholderText(QStringLiteral("127.0.0.1"));+ connect(hostEdit_, &QLineEdit::textChanged, this, &ConnectionFormDialog::onFieldChanged);+ h->addWidget(hostEdit_, 1);+ auto* portLbl = new QLabel(tr("Port"), hp);+ h->addWidget(portLbl);+ portSpin_ = new QSpinBox(hp);+ portSpin_->setRange(0, 65535);+ portSpin_->setFixedWidth(80);+ h->addWidget(portSpin_);+ hostV->addWidget(makeRow(tr("Host/Socket"), hp, hostPage_));+ }++ // User + Other options+ {+ auto* up = new QWidget(hostPage_);+ auto* h = new QHBoxLayout(up);+ h->setContentsMargins(0, 0, 0, 0);+ h->setSpacing(12);+ userEdit_ = new QLineEdit(up);+ userEdit_->setPlaceholderText(tr("user name"));+ h->addWidget(userEdit_, 1);+ otherOptsBtn_ = new QPushButton(tr("Other options"), up);+ otherOptsBtn_->setFixedWidth(130);+ otherOptsBtn_->setEnabled(false); // Placeholder — advanced options in later phase+ h->addWidget(otherOptsBtn_);+ hostV->addWidget(makeRow(tr("User"), up, hostPage_));+ }++ // Password + Store dropdown+ {+ auto* pp = new QWidget(hostPage_);+ auto* h = new QHBoxLayout(pp);+ h->setContentsMargins(0, 0, 0, 0);+ h->setSpacing(12);+ passwordEdit_ = new QLineEdit(pp);+ passwordEdit_->setPlaceholderText(tr("password"));+ passwordEdit_->setEchoMode(QLineEdit::Password);+ h->addWidget(passwordEdit_, 1);+ storeCombo_ = new QComboBox(pp);+ storeCombo_->addItem(tr("Store in keychain"), true);+ storeCombo_->addItem(tr("Don't store"), false);+ storeCombo_->setFixedWidth(170);+ h->addWidget(storeCombo_);+ hostV->addWidget(makeRow(tr("Password"), pp, hostPage_));+ }++ // Database + SSL mode+ {+ auto* dp = new QWidget(hostPage_);+ auto* h = new QHBoxLayout(dp);+ h->setContentsMargins(0, 0, 0, 0);+ h->setSpacing(12);+ databaseEdit_ = new QLineEdit(dp);+ databaseEdit_->setPlaceholderText(tr("database name"));+ h->addWidget(databaseEdit_, 1);+ auto* sslLbl = new QLabel(tr("SSL mode"), dp);+ h->addWidget(sslLbl);+ sslModeCombo_ = new QComboBox(dp);+ sslModeCombo_->setFixedWidth(140);+ for (auto m : kAllSSLModes) {+ sslModeCombo_->addItem(QString::fromUtf8(std::string(displayName(m)).c_str()),+ QString::fromUtf8(std::string(rawValue(m)).c_str()));+ }+ h->addWidget(sslModeCombo_);+ hostV->addWidget(makeRow(tr("Database"), dp, hostPage_));+ }++ // SSL keys+ {+ auto* sp = new QWidget(hostPage_);+ auto* h = new QHBoxLayout(sp);+ h->setContentsMargins(0, 0, 0, 0);+ h->setSpacing(6);++ auto makeSslField = [this, sp](QLineEdit*& edit, const QString& title, int slot) {+ edit = new QLineEdit(sp);+ edit->setPlaceholderText(title);+ edit->setReadOnly(true);+ auto* btn = new QPushButton(title, sp);+ btn->setFixedWidth(90);+ connect(btn, &QPushButton::clicked, this, [this, slot] { onBrowseSSLKey(slot); });+ auto* w = new QWidget(sp);+ auto* wh = new QHBoxLayout(w);+ wh->setContentsMargins(0, 0, 0, 0);+ wh->setSpacing(4);+ wh->addWidget(btn);+ wh->addWidget(edit, 1);+ return w;+ };++ h->addWidget(makeSslField(sslKeyPathEdit_, tr("Key..."), 0), 1);+ h->addWidget(makeSslField(sslCertPathEdit_, tr("Cert..."), 1), 1);+ h->addWidget(makeSslField(sslCAPathEdit_, tr("CA Cert..."), 2), 1);+ auto* clearBtn = new QPushButton(QStringLiteral("−"), sp);+ clearBtn->setFixedSize(28, 24);+ clearBtn->setToolTip(tr("Clear SSL keys"));+ connect(clearBtn, &QPushButton::clicked, this, &ConnectionFormDialog::onClearSSLKeys);+ h->addWidget(clearBtn);+ hostV->addWidget(makeRow(tr("SSL keys"), sp, hostPage_));+ }++ // SSH section (hidden until toggled)+ sshSection_ = new QWidget(hostPage_);+ {+ auto* sv = new QVBoxLayout(sshSection_);+ sv->setContentsMargins(0, 0, 0, 0);+ sv->setSpacing(kRowSpacing);++ auto* div = new QFrame(sshSection_);+ div->setFrameShape(QFrame::HLine);+ sv->addWidget(div);++ // SSH Host + Port+ auto* hp = new QWidget(sshSection_);+ auto* hh = new QHBoxLayout(hp);+ hh->setContentsMargins(0, 0, 0, 0);+ hh->setSpacing(8);+ sshHostEdit_ = new QLineEdit(hp);+ sshHostEdit_->setPlaceholderText(tr("ssh.example.com"));+ hh->addWidget(sshHostEdit_, 1);+ auto* pLbl = new QLabel(tr("Port"), hp);+ hh->addWidget(pLbl);+ sshPortSpin_ = new QSpinBox(hp);+ sshPortSpin_->setRange(1, 65535);+ sshPortSpin_->setValue(22);+ sshPortSpin_->setFixedWidth(80);+ hh->addWidget(sshPortSpin_);+ sv->addWidget(makeRow(tr("SSH Host"), hp, sshSection_));++ // SSH User + Auth method+ auto* up = new QWidget(sshSection_);+ auto* uh = new QHBoxLayout(up);+ uh->setContentsMargins(0, 0, 0, 0);+ uh->setSpacing(12);+ sshUserEdit_ = new QLineEdit(up);+ sshUserEdit_->setPlaceholderText(tr("username"));+ uh->addWidget(sshUserEdit_, 1);+ sshAuthCombo_ = new QComboBox(up);+ sshAuthCombo_->addItem(tr("Password"), int(SSHAuthMethod::Password));+ sshAuthCombo_->addItem(tr("Private Key"), int(SSHAuthMethod::PrivateKey));+ sshAuthCombo_->addItem(tr("Key + Passphrase"), int(SSHAuthMethod::KeyWithPassphrase));+ sshAuthCombo_->setFixedWidth(160);+ connect(sshAuthCombo_, QOverload<int>::of(&QComboBox::currentIndexChanged),+ this, &ConnectionFormDialog::onSSHAuthChanged);+ uh->addWidget(sshAuthCombo_);+ sv->addWidget(makeRow(tr("SSH User"), up, sshSection_));++ // SSH Password row+ sshPasswordEdit_ = new QLineEdit(sshSection_);+ sshPasswordEdit_->setPlaceholderText(tr("password"));+ sshPasswordEdit_->setEchoMode(QLineEdit::Password);+ sshPasswordRow_ = makeRow(tr("SSH Password"), sshPasswordEdit_, sshSection_);+ sv->addWidget(sshPasswordRow_);++ // SSH Key path + Browse+ auto* kp = new QWidget(sshSection_);+ auto* kh = new QHBoxLayout(kp);+ kh->setContentsMargins(0, 0, 0, 0);+ kh->setSpacing(8);+ sshKeyPathEdit_ = new QLineEdit(kp);+ sshKeyPathEdit_->setPlaceholderText(QStringLiteral("~/.ssh/id_rsa"));+ kh->addWidget(sshKeyPathEdit_, 1);+ auto* kbtn = new QPushButton(tr("Browse..."), kp);+ connect(kbtn, &QPushButton::clicked, this, &ConnectionFormDialog::onBrowseSSHKey);+ kh->addWidget(kbtn);+ sshKeyRow_ = makeRow(tr("SSH Key"), kp, sshSection_);+ sv->addWidget(sshKeyRow_);+ }+ sshSection_->setVisible(false);+ hostV->addWidget(sshSection_);++ root->addWidget(hostPage_);++ // --- Test result label ---+ testResult_ = new QLabel(this);+ testResult_->setVisible(false);+ testResult_->setWordWrap(true);+ root->addWidget(testResult_);++ // --- Divider ---+ auto* divider = new QFrame(this);+ divider->setFrameShape(QFrame::HLine);+ root->addWidget(divider);++ // --- Bottom bar: [Over SSH] [Save] [Test] [Connect] ---+ auto* bottom = new QHBoxLayout();+ bottom->setContentsMargins(0, 0, 0, 0);+ bottom->setSpacing(8);+ overSshBtn_ = new QPushButton(tr("Over SSH"), this);+ connect(overSshBtn_, &QPushButton::clicked, this, &ConnectionFormDialog::onToggleSSH);+ bottom->addWidget(overSshBtn_);+ bottom->addStretch();+ saveBtn_ = new QPushButton(tr("Save"), this);+ connect(saveBtn_, &QPushButton::clicked, this, &ConnectionFormDialog::onSaveClicked);+ bottom->addWidget(saveBtn_);+ testBtn_ = new QPushButton(tr("Test"), this);+ connect(testBtn_, &QPushButton::clicked, this, &ConnectionFormDialog::onTestClicked);+ bottom->addWidget(testBtn_);+ connectBtn_ = new QPushButton(tr("Connect"), this);+ connectBtn_->setDefault(true);+ connect(connectBtn_, &QPushButton::clicked, this, &ConnectionFormDialog::onConnectClicked);+ bottom->addWidget(connectBtn_);+ root->addLayout(bottom);++ // Initial color selection+ colorDots_[3]->setChecked(true); // Blue is index 3+}++void ConnectionFormDialog::applyLayoutForType(DatabaseType type) {+ const bool isSqlite = type == DatabaseType::SQLite;+ filePage_->setVisible(isSqlite);+ hostPage_->setVisible(!isSqlite);+ overSshBtn_->setVisible(!isSqlite);+ if (!isSqlite) portSpin_->setValue(defaultPort(type));+}++void ConnectionFormDialog::onDatabaseTypeChanged(int index) {+ const auto raw = st(typeCombo_->itemData(index).toString());+ const auto t = databaseTypeFromRaw(raw);+ if (!t) return;+ applyLayoutForType(*t);+ updateButtonStates();+}++void ConnectionFormDialog::onBrowseFile() {+ const auto file = QFileDialog::getOpenFileName(+ this, tr("Choose SQLite file"), QString{},+ tr("SQLite (*.sqlite *.db *.sqlite3);;All files (*)"));+ if (!file.isEmpty()) filePathEdit_->setText(file);+}++void ConnectionFormDialog::onColorDotClicked(int index) {+ const std::array<ColorTag, 6> tags = {+ ColorTag::Red, ColorTag::Orange, ColorTag::Green,+ ColorTag::Blue, ColorTag::Purple, ColorTag::Gray,+ };+ colorTag_ = tags[index];+ refreshColorDotBorders();+ const auto raw = QString::fromUtf8(std::string(rawValue(colorTag_)).c_str());+ const int comboIdx = colorCombo_->findData(raw);+ if (comboIdx >= 0) {+ QSignalBlocker block(colorCombo_);+ colorCombo_->setCurrentIndex(comboIdx);+ }+}++void ConnectionFormDialog::refreshColorDotBorders() {+ const std::array<ColorTag, 6> tags = {+ ColorTag::Red, ColorTag::Orange, ColorTag::Green,+ ColorTag::Blue, ColorTag::Purple, ColorTag::Gray,+ };+ for (int i = 0; i < 6; ++i) {+ colorDots_[i]->setChecked(tags[i] == colorTag_);+ }+}++void ConnectionFormDialog::onToggleSSH() {+ sshEnabled_ = !sshEnabled_;+ sshSection_->setVisible(sshEnabled_);+ overSshBtn_->setText(sshEnabled_ ? tr("Close SSH") : tr("Over SSH"));+ rebuildSSHRows();+ adjustSize();+}++void ConnectionFormDialog::rebuildSSHRows() {+ if (!sshEnabled_) return;+ const auto auth = static_cast<SSHAuthMethod>(sshAuthCombo_->currentData().toInt());+ const bool needsPassword = auth == SSHAuthMethod::Password || auth == SSHAuthMethod::KeyWithPassphrase;+ const bool needsKey = auth == SSHAuthMethod::PrivateKey || auth == SSHAuthMethod::KeyWithPassphrase;+ sshPasswordRow_->setVisible(needsPassword);+ sshKeyRow_->setVisible(needsKey);+}++void ConnectionFormDialog::onSSHAuthChanged(int /*index*/) { rebuildSSHRows(); }++void ConnectionFormDialog::onBrowseSSHKey() {+ const auto file = QFileDialog::getOpenFileName(this, tr("Choose SSH private key"));+ if (!file.isEmpty()) sshKeyPathEdit_->setText(file);+}++void ConnectionFormDialog::onBrowseSSLKey(int slot) {+ QLineEdit* target = slot == 0 ? sslKeyPathEdit_ : (slot == 1 ? sslCertPathEdit_ : sslCAPathEdit_);+ const auto file = QFileDialog::getOpenFileName(this, tr("Choose SSL file"));+ if (!file.isEmpty()) target->setText(file);+}++void ConnectionFormDialog::onClearSSLKeys() {+ sslKeyPathEdit_->clear();+ sslCertPathEdit_->clear();+ sslCAPathEdit_->clear();+}++void ConnectionFormDialog::onFieldChanged() {+ updateButtonStates();+}++void ConnectionFormDialog::updateButtonStates() {+ const bool nameOk = !nameEdit_->text().trimmed().isEmpty();+ const auto t = databaseTypeFromRaw(st(typeCombo_->currentData().toString()))+ .value_or(DatabaseType::PostgreSQL);+ const bool targetOk = (t == DatabaseType::SQLite)+ ? !filePathEdit_->text().trimmed().isEmpty()+ : !hostEdit_->text().trimmed().isEmpty();++ saveBtn_->setEnabled(nameOk && targetOk);+ testBtn_->setEnabled(targetOk);+ connectBtn_->setEnabled(nameOk && targetOk);++ saveBtn_->setToolTip(saveBtn_->isEnabled() ? QString{}+ : tr("Enter a name and the target (host or file) to save."));+ connectBtn_->setToolTip(connectBtn_->isEnabled() ? QString{}+ : tr("Enter a name and the target (host or file) to connect."));+}++void ConnectionFormDialog::showTestResult(bool success, const QString& detail) {+ testResult_->setVisible(true);+ testResult_->setStyleSheet(success+ ? "color: #2a9d3e; font-size: 12px;"+ : "color: #b94b4b; font-size: 12px;");+ testResult_->setText((success ? tr("✓ ") : tr("✗ ")) + detail);+}++void ConnectionFormDialog::onSaveClicked() {+ if (!saveBtn_->isEnabled()) return;+ done(Saved);+}++void ConnectionFormDialog::onTestClicked() {+ if (!testBtn_->isEnabled()) return;+ emit testRequested(config(), password());+}++void ConnectionFormDialog::onConnectClicked() {+ if (!connectBtn_->isEnabled()) return;+ done(Connect);+}++void ConnectionFormDialog::setConfig(const ConnectionConfig& config) {+ editingId_ = config.id;+ setWindowTitle(tr("Edit Connection"));+ nameEdit_->setText(qs(config.name));++ const auto raw = std::string(rawValue(config.databaseType));+ const int idx = typeCombo_->findData(QString::fromUtf8(raw.c_str()));+ if (idx >= 0) typeCombo_->setCurrentIndex(idx);+ applyLayoutForType(config.databaseType);++ colorTag_ = config.colorTag.value_or(ColorTag::Blue);+ refreshColorDotBorders();+ const int tagIdx = colorCombo_->findData(+ QString::fromUtf8(std::string(rawValue(colorTag_)).c_str()));+ if (tagIdx >= 0) colorCombo_->setCurrentIndex(tagIdx);++ if (config.databaseType == DatabaseType::SQLite) {+ filePathEdit_->setText(qs(config.filePath.value_or("")));+ } else {+ hostEdit_->setText(qs(config.host.value_or("")));+ portSpin_->setValue(config.port.value_or(defaultPort(config.databaseType)));+ databaseEdit_->setText(qs(config.database.value_or("")));+ userEdit_->setText(qs(config.username.value_or("")));+ const int sslIdx = sslModeCombo_->findData(+ config.sslEnabled ? QStringLiteral("REQUIRED") : QStringLiteral("DISABLED"));+ if (sslIdx >= 0) sslModeCombo_->setCurrentIndex(sslIdx);++ if (config.sshConfig) {+ sshEnabled_ = true;+ sshSection_->setVisible(true);+ overSshBtn_->setText(tr("Close SSH"));+ sshHostEdit_->setText(qs(config.sshConfig->host));+ sshPortSpin_->setValue(config.sshConfig->port);+ sshUserEdit_->setText(qs(config.sshConfig->username));+ const int authIdx = sshAuthCombo_->findData(int(config.sshConfig->authMethod));+ if (authIdx >= 0) sshAuthCombo_->setCurrentIndex(authIdx);+ if (config.sshConfig->keyPath) sshKeyPathEdit_->setText(qs(*config.sshConfig->keyPath));+ rebuildSSHRows();+ }+ }+ updateButtonStates();+}++void ConnectionFormDialog::setPassword(const std::string& password) {+ passwordEdit_->setText(qs(password));+}++bool ConnectionFormDialog::storeInKeychain() const {+ return storeCombo_ && storeCombo_->currentData().toBool();+}++ConnectionConfig ConnectionFormDialog::config() const {+ ConnectionConfig c;+ c.id = editingId_.empty()+ ? QUuid::createUuid().toString(QUuid::WithoutBraces).toStdString()+ : editingId_;+ c.name = st(nameEdit_->text().trimmed());+ const auto raw = st(typeCombo_->currentData().toString());+ c.databaseType = databaseTypeFromRaw(raw).value_or(DatabaseType::PostgreSQL);+ c.colorTag = colorTag_;++ if (c.databaseType == DatabaseType::SQLite) {+ const auto p = st(filePathEdit_->text().trimmed());+ if (!p.empty()) c.filePath = p;+ } else {+ const auto h = st(hostEdit_->text().trimmed());+ if (!h.empty()) c.host = h;+ c.port = portSpin_->value();+ const auto db = st(databaseEdit_->text().trimmed());+ if (!db.empty()) c.database = db;+ const auto u = st(userEdit_->text().trimmed());+ if (!u.empty()) c.username = u;+ const auto sslRaw = st(sslModeCombo_->currentData().toString());+ c.sslEnabled = !(sslRaw == "DISABLED");++ if (sshEnabled_) {+ SSHTunnelConfig s;+ s.host = st(sshHostEdit_->text().trimmed());+ s.port = sshPortSpin_->value();+ s.username = st(sshUserEdit_->text().trimmed());+ s.authMethod = static_cast<SSHAuthMethod>(sshAuthCombo_->currentData().toInt());+ const auto kp = st(sshKeyPathEdit_->text().trimmed());+ if (!kp.empty()) s.keyPath = kp;+ if (!s.host.empty()) c.sshConfig = s;+ }+ }+ return c;+}++std::optional<std::string> ConnectionFormDialog::password() const {+ const auto pw = passwordEdit_->text();+ if (pw.isEmpty()) return std::nullopt;+ return st(pw);+}++std::optional<std::string> ConnectionFormDialog::sshPassword() const {+ if (!sshPasswordEdit_) return std::nullopt;+ const auto pw = sshPasswordEdit_->text();+ if (pw.isEmpty()) return std::nullopt;+ return st(pw);+}++void ConnectionFormDialog::setSshPassword(const std::string& password) {+ if (sshPasswordEdit_) sshPasswordEdit_->setText(qs(password));+}++void ConnectionFormDialog::hideAllSSHRows() {+ sshPasswordRow_->setVisible(false);+ sshKeyRow_->setVisible(false);+}++}diff --git a/linux/src/Presentation/Views/ConnectionForm/ConnectionFormDialog.h b/linux/src/Presentation/Views/ConnectionForm/ConnectionFormDialog.hnew file mode 100644index 0000000..3f0f8e0--- /dev/null+++ b/linux/src/Presentation/Views/ConnectionForm/ConnectionFormDialog.h@@ -0,0 +1,135 @@+#pragma once++#include <QDialog>+#include <array>+#include <optional>+#include <string>++#include "Core/Models/Database/ConnectionConfig.h"++class QCheckBox;+class QComboBox;+class QFrame;+class QHBoxLayout;+class QLabel;+class QLineEdit;+class QPushButton;+class QSpinBox;+class QWidget;++namespace gridex {++// Matches macOS ConnectionFormView layout:+// Name+// Status color (6 color dots + Tag dropdown)+// SQLite: File + Browse+// Others:+// Host/Socket + Port (same row)+// User + Other options+// Password + Store in keychain+// Database + SSL mode+// SSL keys (Key/Cert/CA Cert + clear)+// Optional SSH section: SSH Host+Port, SSH User+Auth, SSH Password/Key+// Divider+// Bottom bar: [Over SSH] [Save] [Test] [Connect]+class ConnectionFormDialog : public QDialog {+ Q_OBJECT++public:+ // Result codes returned by exec().+ enum Result {+ Cancelled = QDialog::Rejected,+ Saved = QDialog::Accepted,+ Connect = 2, // save + connect+ };++ explicit ConnectionFormDialog(QWidget* parent = nullptr);++ void setConfig(const ConnectionConfig& config);+ void setPassword(const std::string& password);++ [[nodiscard]] ConnectionConfig config() const;+ [[nodiscard]] std::optional<std::string> password() const;+ [[nodiscard]] std::optional<std::string> sshPassword() const;+ [[nodiscard]] bool storeInKeychain() const;++ void setSshPassword(const std::string& password);++signals:+ void testRequested(const ConnectionConfig& config,+ const std::optional<std::string>& password);++public slots:+ void showTestResult(bool success, const QString& detail);++private slots:+ void onDatabaseTypeChanged(int index);+ void onBrowseFile();+ void onColorDotClicked(int index);+ void onToggleSSH();+ void onSSHAuthChanged(int index);+ void onFieldChanged();+ void onBrowseSSHKey();+ void onBrowseSSLKey(int slot);+ void onClearSSLKeys();+ void onSaveClicked();+ void onTestClicked();+ void onConnectClicked();++private:+ void buildUi();+ void applyLayoutForType(DatabaseType type);+ void updateButtonStates();+ void refreshColorDotBorders();+ void hideAllSSHRows();+ void rebuildSSHRows();++ // Top-of-dialog fields+ QLineEdit* nameEdit_ = nullptr;+ QComboBox* typeCombo_ = nullptr;+ QComboBox* colorCombo_ = nullptr;+ std::array<QPushButton*, 6> colorDots_{};++ // SQLite page+ QWidget* filePage_ = nullptr;+ QLineEdit* filePathEdit_ = nullptr;+ QPushButton* filePickBtn_ = nullptr;++ // Host-based page+ QWidget* hostPage_ = nullptr;+ QLineEdit* hostEdit_ = nullptr;+ QSpinBox* portSpin_ = nullptr;+ QLineEdit* userEdit_ = nullptr;+ QPushButton* otherOptsBtn_ = nullptr;+ QLineEdit* passwordEdit_ = nullptr;+ QComboBox* storeCombo_ = nullptr;+ QLineEdit* databaseEdit_ = nullptr;+ QComboBox* sslModeCombo_ = nullptr;+ QLineEdit* sslKeyPathEdit_ = nullptr;+ QLineEdit* sslCertPathEdit_ = nullptr;+ QLineEdit* sslCAPathEdit_ = nullptr;++ // SSH section (inside host page)+ QWidget* sshSection_ = nullptr;+ QLineEdit* sshHostEdit_ = nullptr;+ QSpinBox* sshPortSpin_ = nullptr;+ QLineEdit* sshUserEdit_ = nullptr;+ QComboBox* sshAuthCombo_ = nullptr;+ QLineEdit* sshPasswordEdit_ = nullptr;+ QLineEdit* sshKeyPathEdit_ = nullptr;+ QWidget* sshPasswordRow_ = nullptr;+ QWidget* sshKeyRow_ = nullptr;++ // Bottom bar+ QPushButton* overSshBtn_ = nullptr;+ QPushButton* saveBtn_ = nullptr;+ QPushButton* testBtn_ = nullptr;+ QPushButton* connectBtn_ = nullptr;+ QLabel* testResult_ = nullptr;++ ColorTag colorTag_ = ColorTag::Blue;+ bool sshEnabled_ = false;+ std::string editingId_;+};++}diff --git a/linux/src/Presentation/Views/CreateTable/CreateTableDialog.cpp b/linux/src/Presentation/Views/CreateTable/CreateTableDialog.cppnew file mode 100644index 0000000..858c229--- /dev/null+++ b/linux/src/Presentation/Views/CreateTable/CreateTableDialog.cpp@@ -0,0 +1,329 @@+#include "Presentation/Views/CreateTable/CreateTableDialog.h"++#include <QCheckBox>+#include <QComboBox>+#include <QFrame>+#include <QHBoxLayout>+#include <QHeaderView>+#include <QLabel>+#include <QLineEdit>+#include <QMessageBox>+#include <QPushButton>+#include <QTableWidget>+#include <QVBoxLayout>++#include "Core/Enums/DatabaseType.h"+#include "Core/Enums/SQLDialect.h"+#include "Core/Errors/GridexError.h"+#include "Core/Protocols/Database/IDatabaseAdapter.h"++namespace gridex {++namespace {++QStringList sqlTypesForAdapter(IDatabaseAdapter* adapter) {+ if (!adapter) {+ return {"INTEGER", "TEXT", "REAL", "BLOB"};+ }+ switch (adapter->databaseType()) {+ case DatabaseType::PostgreSQL:+ return {"INTEGER", "BIGINT", "SMALLINT", "SERIAL", "BIGSERIAL",+ "TEXT", "VARCHAR(255)", "CHAR(1)",+ "BOOLEAN",+ "FLOAT", "DOUBLE PRECISION", "DECIMAL", "NUMERIC",+ "TIMESTAMP", "TIMESTAMPTZ", "DATE", "TIME",+ "UUID", "JSON", "JSONB", "BYTEA"};+ case DatabaseType::MySQL:+ return {"INT", "BIGINT", "SMALLINT", "TINYINT",+ "TEXT", "VARCHAR(255)", "CHAR(1)", "LONGTEXT",+ "BOOLEAN", "TINYINT(1)",+ "FLOAT", "DOUBLE", "DECIMAL",+ "DATETIME", "TIMESTAMP", "DATE", "TIME",+ "JSON", "BLOB", "LONGBLOB"};+ case DatabaseType::SQLite:+ return {"INTEGER", "TEXT", "REAL", "NUMERIC", "BLOB"};+ case DatabaseType::MSSQL:+ return {"INT", "BIGINT", "SMALLINT", "TINYINT",+ "NVARCHAR(255)", "VARCHAR(255)", "NTEXT", "TEXT",+ "BIT",+ "FLOAT", "REAL", "DECIMAL", "NUMERIC",+ "DATETIME", "DATETIME2", "DATE", "TIME",+ "UNIQUEIDENTIFIER", "XML", "JSON", "VARBINARY(MAX)"};+ default:+ return {"INTEGER", "TEXT", "REAL", "BLOB"};+ }+}++} // namespace++CreateTableDialog::CreateTableDialog(IDatabaseAdapter* adapter,+ const QString& schema,+ QWidget* parent)+ : QDialog(parent)+ , adapter_(adapter)+ , schema_(schema)+{+ buildUi();+}++void CreateTableDialog::buildUi() {+ setWindowTitle(tr("Create Table"));+ setMinimumWidth(640);+ setMinimumHeight(420);++ auto* root = new QVBoxLayout(this);+ root->setSpacing(8);+ root->setContentsMargins(16, 16, 16, 12);++ // Table name row+ auto* nameRow = new QWidget(this);+ auto* nameH = new QHBoxLayout(nameRow);+ nameH->setContentsMargins(0, 0, 0, 0);+ nameH->setSpacing(8);+ auto* nameLabel = new QLabel(tr("Table name:"), nameRow);+ tableNameEdit_ = new QLineEdit(nameRow);+ tableNameEdit_->setPlaceholderText(tr("new_table"));+ tableNameEdit_->setText(QStringLiteral("new_table"));+ connect(tableNameEdit_, &QLineEdit::textChanged, this,+ [this](const QString& t) { createBtn_->setEnabled(!t.trimmed().isEmpty()); });+ nameH->addWidget(nameLabel);+ nameH->addWidget(tableNameEdit_, 1);+ if (!schema_.isEmpty()) {+ auto* schemaLabel = new QLabel(tr("Schema: %1").arg(schema_), nameRow);+ nameH->addWidget(schemaLabel);+ }+ root->addWidget(nameRow);++ // Column header label+ auto* colHeader = new QLabel(tr("Columns"), this);+ root->addWidget(colHeader);++ // Columns table+ columnsTable_ = new QTableWidget(0, 5, this);+ columnsTable_->setHorizontalHeaderLabels(+ {tr("Name"), tr("Type"), tr("Nullable"), tr("Default"), tr("Primary Key")});+ columnsTable_->horizontalHeader()->setSectionResizeMode(kColName, QHeaderView::Stretch);+ columnsTable_->horizontalHeader()->setSectionResizeMode(kColType, QHeaderView::ResizeToContents);+ columnsTable_->horizontalHeader()->setSectionResizeMode(kColNullable, QHeaderView::ResizeToContents);+ columnsTable_->horizontalHeader()->setSectionResizeMode(kColDefault, QHeaderView::Stretch);+ columnsTable_->horizontalHeader()->setSectionResizeMode(kColPrimaryKey, QHeaderView::ResizeToContents);+ columnsTable_->setSelectionBehavior(QAbstractItemView::SelectRows);+ columnsTable_->setAlternatingRowColors(true);+ root->addWidget(columnsTable_, 1);++ // Add a default "id" primary key column+ onAddColumn();+ // Set it up as PK with type appropriate for the adapter+ if (columnsTable_->rowCount() > 0) {+ auto* nameItem = columnsTable_->item(0, kColName);+ if (nameItem) nameItem->setText(QStringLiteral("id"));+ auto* typeCombo = qobject_cast<QComboBox*>(columnsTable_->cellWidget(0, kColType));+ if (typeCombo) {+ const DatabaseType dt = adapter_ ? adapter_->databaseType() : DatabaseType::SQLite;+ QString idType;+ switch (dt) {+ case DatabaseType::PostgreSQL: idType = QStringLiteral("SERIAL"); break;+ case DatabaseType::MySQL: idType = QStringLiteral("INT"); break;+ case DatabaseType::MSSQL: idType = QStringLiteral("INT"); break;+ default: idType = QStringLiteral("INTEGER"); break;+ }+ const int idx = typeCombo->findText(idType);+ if (idx >= 0) typeCombo->setCurrentIndex(idx);+ }+ auto* nullableCheck = qobject_cast<QCheckBox*>(columnsTable_->cellWidget(0, kColNullable));+ if (nullableCheck) nullableCheck->setChecked(false);+ auto* pkCheck = qobject_cast<QCheckBox*>(columnsTable_->cellWidget(0, kColPrimaryKey));+ if (pkCheck) pkCheck->setChecked(true);+ }++ // [+ Column] / [- Column] buttons+ auto* colBtnRow = new QWidget(this);+ auto* colBtnH = new QHBoxLayout(colBtnRow);+ colBtnH->setContentsMargins(0, 0, 0, 0);+ colBtnH->setSpacing(6);++ addColBtn_ = new QPushButton(tr("+ Column"), colBtnRow);+ connect(addColBtn_, &QPushButton::clicked, this, &CreateTableDialog::onAddColumn);++ removeColBtn_ = new QPushButton(tr("- Column"), colBtnRow);+ connect(removeColBtn_, &QPushButton::clicked, this, &CreateTableDialog::onRemoveColumn);++ colBtnH->addWidget(addColBtn_);+ colBtnH->addWidget(removeColBtn_);+ colBtnH->addStretch();+ root->addWidget(colBtnRow);++ // Divider+ auto* div = new QFrame(this);+ div->setFrameShape(QFrame::HLine);+ root->addWidget(div);++ // OK / Cancel row+ auto* btnRow = new QWidget(this);+ auto* btnH = new QHBoxLayout(btnRow);+ btnH->setContentsMargins(0, 0, 0, 0);++ cancelBtn_ = new QPushButton(tr("Cancel"), btnRow);+ connect(cancelBtn_, &QPushButton::clicked, this, &QDialog::reject);++ createBtn_ = new QPushButton(tr("Create"), btnRow);+ createBtn_->setDefault(true);+ connect(createBtn_, &QPushButton::clicked, this, &CreateTableDialog::onCreate);++ btnH->addWidget(cancelBtn_);+ btnH->addStretch();+ btnH->addWidget(createBtn_);+ root->addWidget(btnRow);+}++void CreateTableDialog::onAddColumn() {+ const int row = columnsTable_->rowCount();+ columnsTable_->insertRow(row);++ // Name cell+ const QString defaultName = QStringLiteral("column_%1").arg(row + 1);+ columnsTable_->setItem(row, kColName, new QTableWidgetItem(defaultName));++ // Type combo+ auto* typeCombo = new QComboBox(columnsTable_);+ typeCombo->addItems(sqlTypesForAdapter(adapter_));+ columnsTable_->setCellWidget(row, kColType, typeCombo);++ // Nullable checkbox (centred)+ auto* nullableCheck = new QCheckBox(columnsTable_);+ nullableCheck->setChecked(true);+ auto* nullableWrapper = new QWidget(columnsTable_);+ auto* nullableLayout = new QHBoxLayout(nullableWrapper);+ nullableLayout->setContentsMargins(0, 0, 0, 0);+ nullableLayout->setAlignment(Qt::AlignCenter);+ nullableLayout->addWidget(nullableCheck);+ columnsTable_->setCellWidget(row, kColNullable, nullableWrapper);++ // Default cell+ columnsTable_->setItem(row, kColDefault, new QTableWidgetItem(QString{}));++ // PK checkbox (centred)+ auto* pkCheck = new QCheckBox(columnsTable_);+ pkCheck->setChecked(false);+ auto* pkWrapper = new QWidget(columnsTable_);+ auto* pkLayout = new QHBoxLayout(pkWrapper);+ pkLayout->setContentsMargins(0, 0, 0, 0);+ pkLayout->setAlignment(Qt::AlignCenter);+ pkLayout->addWidget(pkCheck);+ columnsTable_->setCellWidget(row, kColPrimaryKey, pkWrapper);++ columnsTable_->selectRow(row);+}++void CreateTableDialog::onRemoveColumn() {+ const int row = columnsTable_->currentRow();+ if (row >= 0) columnsTable_->removeRow(row);+}++QString CreateTableDialog::buildCreateSql() const {+ const QString tableName = tableNameEdit_->text().trimmed();+ if (tableName.isEmpty()) return {};++ const SQLDialect dialect = adapter_+ ? sqlDialect(adapter_->databaseType())+ : SQLDialect::SQLite;++ // Qualified table name+ QString qualifiedTable;+ if (!schema_.isEmpty() &&+ adapter_ &&+ adapter_->databaseType() != DatabaseType::SQLite &&+ adapter_->databaseType() != DatabaseType::MySQL)+ {+ qualifiedTable = QString::fromStdString(quoteIdentifier(dialect, schema_.toStdString()))+ + QStringLiteral(".")+ + QString::fromStdString(quoteIdentifier(dialect, tableName.toStdString()));+ } else {+ qualifiedTable = QString::fromStdString(quoteIdentifier(dialect, tableName.toStdString()));+ }++ QStringList colDefs;+ QStringList pkCols;++ for (int row = 0; row < columnsTable_->rowCount(); ++row) {+ auto* nameItem = columnsTable_->item(row, kColName);+ auto* typeCombo = qobject_cast<QComboBox*>(columnsTable_->cellWidget(row, kColType));+ auto* defaultItem = columnsTable_->item(row, kColDefault);++ const QString colName = nameItem ? nameItem->text().trimmed() : QString{};+ const QString colType = typeCombo ? typeCombo->currentText() : QStringLiteral("TEXT");++ // Nullable: find QCheckBox inside wrapper widget+ bool isNullable = true;+ if (auto* wrapper = columnsTable_->cellWidget(row, kColNullable)) {+ if (auto* cb = wrapper->findChild<QCheckBox*>()) {+ isNullable = cb->isChecked();+ }+ }++ // PK+ bool isPK = false;+ if (auto* wrapper = columnsTable_->cellWidget(row, kColPrimaryKey)) {+ if (auto* cb = wrapper->findChild<QCheckBox*>()) {+ isPK = cb->isChecked();+ }+ }++ if (colName.isEmpty()) continue;++ QString def = QString::fromStdString(quoteIdentifier(dialect, colName.toStdString()))+ + QStringLiteral(" ") + colType;+ if (!isNullable) def += QStringLiteral(" NOT NULL");++ const QString defaultVal = defaultItem ? defaultItem->text().trimmed() : QString{};+ if (!defaultVal.isEmpty()) {+ def += QStringLiteral(" DEFAULT ") + defaultVal;+ }++ colDefs << def;+ if (isPK) {+ pkCols << QString::fromStdString(quoteIdentifier(dialect, colName.toStdString()));+ }+ }++ if (colDefs.isEmpty()) return {};++ if (!pkCols.isEmpty()) {+ colDefs << QStringLiteral("PRIMARY KEY (%1)").arg(pkCols.join(QStringLiteral(", ")));+ }++ return QStringLiteral("CREATE TABLE %1 (\n %2\n)")+ .arg(qualifiedTable, colDefs.join(QStringLiteral(",\n ")));+}++void CreateTableDialog::onCreate() {+ const QString sql = buildCreateSql();+ if (sql.isEmpty()) {+ QMessageBox::warning(this, tr("Create Table"),+ tr("Please provide a table name and at least one column."));+ return;+ }++ if (!adapter_) {+ QMessageBox::critical(this, tr("Create Table"), tr("No database connection."));+ return;+ }++ try {+ adapter_->executeRaw(sql.toStdString());+ } catch (const GridexError& e) {+ QMessageBox::critical(this, tr("Create Table Failed"),+ QString::fromUtf8(e.what()));+ return;+ } catch (const std::exception& e) {+ QMessageBox::critical(this, tr("Create Table Failed"),+ QString::fromUtf8(e.what()));+ return;+ }++ const QString name = tableNameEdit_->text().trimmed();+ emit tableCreated(name);+ accept();+}++} // namespace gridexdiff --git a/linux/src/Presentation/Views/CreateTable/CreateTableDialog.h b/linux/src/Presentation/Views/CreateTable/CreateTableDialog.hnew file mode 100644index 0000000..cb51632--- /dev/null+++ b/linux/src/Presentation/Views/CreateTable/CreateTableDialog.h@@ -0,0 +1,56 @@+#pragma once++#include <QDialog>++class QComboBox;+class QLineEdit;+class QPushButton;+class QTableWidget;++namespace gridex {++class IDatabaseAdapter;++// Dialog for creating a new database table.+// Mirrors macOS CreateTableView: table name + columns editor with+// Name, Type, Nullable, Default, Primary Key columns.+// Emits tableCreated(tableName) on success.+class CreateTableDialog : public QDialog {+ Q_OBJECT++public:+ explicit CreateTableDialog(IDatabaseAdapter* adapter,+ const QString& schema,+ QWidget* parent = nullptr);++signals:+ void tableCreated(const QString& tableName);++private slots:+ void onAddColumn();+ void onRemoveColumn();+ void onCreate();++private:+ void buildUi();+ QString buildCreateSql() const;++ IDatabaseAdapter* adapter_;+ QString schema_;++ QLineEdit* tableNameEdit_ = nullptr;+ QTableWidget* columnsTable_ = nullptr;+ QPushButton* addColBtn_ = nullptr;+ QPushButton* removeColBtn_ = nullptr;+ QPushButton* createBtn_ = nullptr;+ QPushButton* cancelBtn_ = nullptr;++ // Column table columns indices+ static constexpr int kColName = 0;+ static constexpr int kColType = 1;+ static constexpr int kColNullable = 2;+ static constexpr int kColDefault = 3;+ static constexpr int kColPrimaryKey = 4;+};++} // namespace gridexdiff --git a/linux/src/Presentation/Views/DataGrid/DataGridView.cpp b/linux/src/Presentation/Views/DataGrid/DataGridView.cppnew file mode 100644index 0000000..e1bf635--- /dev/null+++ b/linux/src/Presentation/Views/DataGrid/DataGridView.cpp@@ -0,0 +1,1036 @@+#include "Presentation/Views/DataGrid/DataGridView.h"++#include <QApplication>+#include <QClipboard>+#include <QDialog>+#include <QDialogButtonBox>+#include <QElapsedTimer>+#include <QFileDialog>+#include <QFrame>+#include <QHBoxLayout>+#include <QHeaderView>+#include <QItemSelectionModel>+#include <QLabel>+#include <QMenu>+#include <QMessageBox>+#include <QPlainTextEdit>+#include <QPushButton>+#include <QResizeEvent>+#include <QScrollBar>+#include <QShortcut>+#include <QWheelEvent>+#include <QSpinBox>+#include <QSplitter>+#include <QStackedWidget>+#include <QTableView>+#include <QTimer>+#include <QVBoxLayout>++#include "Core/Enums/DatabaseType.h"+#include "Core/Enums/SQLDialect.h"+#include "Core/Errors/GridexError.h"+#include "Core/Protocols/Database/IDatabaseAdapter.h"+#include "Presentation/Views/DataGrid/QueryResultModel.h"+#include "Presentation/Views/FilterBar/FilterBarView.h"+#include "Presentation/Views/QueryLog/QueryLogPanel.h"+#include "Presentation/Views/TableStructure/TableStructureView.h"+#include "Services/Export/ExportService.h"++namespace gridex {++namespace {++// Button styling lives in resources/style.qss — tag buttons with objectName+// (primaryButton / commitButton / discardButton) instead of inline sheets.++} // namespace++DataGridView::DataGridView(QWidget* parent) : QWidget(parent) {+ buildUi();+}++void DataGridView::buildUi() {+ auto* root = new QVBoxLayout(this);+ root->setContentsMargins(0, 0, 0, 0);+ root->setSpacing(0);++ // ===================== Top 28px DataGridToolbar =====================+ auto* topBar = new QWidget(this);+ topBar->setFixedHeight(28);+ topBar->setAutoFillBackground(true);+ topBar->setProperty("compact", true); // shrinks descendant buttons/inputs+ auto* topH = new QHBoxLayout(topBar);+ topH->setContentsMargins(12, 0, 12, 0);+ topH->setSpacing(8);++ pendingStub_ = new QLabel(QString{}, topBar);+ pendingStub_->setStyleSheet(QStringLiteral("color: #f9e2af;")); // warn (catppuccin yellow)+ pendingStub_->hide();+ topH->addWidget(pendingStub_);++ discardBtn_ = new QPushButton(tr("Discard"), topBar);+ discardBtn_->setToolTip(tr("Discard all pending changes"));+ discardBtn_->setObjectName(QStringLiteral("discardButton"));+ discardBtn_->setFixedHeight(22);+ discardBtn_->hide();+ connect(discardBtn_, &QPushButton::clicked, this, &DataGridView::onDiscard);+ topH->addWidget(discardBtn_);++ commitBtn_ = new QPushButton(tr("Commit"), topBar);+ commitBtn_->setToolTip(tr("Commit pending changes to database (Ctrl+S)"));+ commitBtn_->setObjectName(QStringLiteral("commitButton"));+ commitBtn_->setFixedHeight(22);+ commitBtn_->hide();+ connect(commitBtn_, &QPushButton::clicked, this, &DataGridView::onCommit);+ topH->addWidget(commitBtn_);++ // Ctrl+S — commit pending changes whenever this view has focus.+ auto* commitShortcut = new QShortcut(QKeySequence::Save, this);+ commitShortcut->setContext(Qt::WidgetWithChildrenShortcut);+ connect(commitShortcut, &QShortcut::activated, this, &DataGridView::onCommit);++ topH->addStretch();++ reloadBtn_ = new QPushButton(QStringLiteral("⟳"), topBar);+ reloadBtn_->setToolTip(tr("Reload"));+ reloadBtn_->setFixedSize(24, 22);+ connect(reloadBtn_, &QPushButton::clicked, this, &DataGridView::reload);+ topH->addWidget(reloadBtn_);++ root->addWidget(topBar);++ auto* topDiv = new QFrame(this);+ topDiv->setFrameShape(QFrame::HLine);+ root->addWidget(topDiv);++ // ===================== Filter bar (hidden until toggled) =====================+ filterBar_ = new FilterBarView(this);+ filterBar_->setVisible(false);+ filterBar_->setAutoFillBackground(true);++ connect(filterBar_, &FilterBarView::filterApplied, this,+ [this](const FilterExpression& expr) {+ activeFilter_ = expr;+ offset_ = 0;+ totalRowCount_ = -1;+ fetchAndRender();+ });+ connect(filterBar_, &FilterBarView::filterCleared, this,+ [this] {+ activeFilter_ = std::nullopt;+ filterBar_->reset();+ offset_ = 0;+ totalRowCount_ = -1;+ fetchAndRender();+ });++ filterBarDiv_ = new QFrame(this);+ filterBarDiv_->setFrameShape(QFrame::HLine);+ filterBarDiv_->setVisible(false);++ root->addWidget(filterBar_);+ root->addWidget(filterBarDiv_);++ // ===================== Center: QStackedWidget (data | structure) =====================+ centerStack_ = new QStackedWidget(this);++ // Page 0 — data table+ tableView_ = new QTableView(this);+ tableView_->setFrameShape(QFrame::NoFrame);+ tableView_->setAlternatingRowColors(true);+ tableView_->setShowGrid(true);+ tableView_->setSelectionBehavior(QAbstractItemView::SelectRows);+ tableView_->setSelectionMode(QAbstractItemView::ExtendedSelection);+ // Task 6: enable cell editing via double-click or F2+ tableView_->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::EditKeyPressed);+ tableView_->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);+ tableView_->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);+ tableView_->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);+ tableView_->horizontalHeader()->setStretchLastSection(true);+ tableView_->horizontalHeader()->setSortIndicatorShown(true);+ tableView_->setSortingEnabled(true);+ tableView_->verticalHeader()->setDefaultSectionSize(30);++ // Task 3/5: right-click context menu+ tableView_->setContextMenuPolicy(Qt::CustomContextMenu);+ connect(tableView_, &QTableView::customContextMenuRequested,+ this, &DataGridView::onTableContextMenu);++ // Delete key — mark selected row(s) for deletion (same as context menu).+ auto* deleteShortcut = new QShortcut(QKeySequence(Qt::Key_Delete), tableView_);+ deleteShortcut->setContext(Qt::WidgetShortcut);+ connect(deleteShortcut, &QShortcut::activated, this, &DataGridView::onDeleteRows);++ model_ = new QueryResultModel(this);+ tableView_->setModel(model_);+ // Shift+scroll → horizontal scroll.+ tableView_->viewport()->installEventFilter(this);+ connect(tableView_->selectionModel(), &QItemSelectionModel::currentRowChanged,+ this, &DataGridView::onRowSelectionChanged);+ connect(model_, &QueryResultModel::pendingChangesChanged,+ this, &DataGridView::onPendingChangesChanged);++ centerStack_->addWidget(tableView_); // index 0++ // Page 1 — structure view+ structureView_ = new TableStructureView(this);+ centerStack_->addWidget(structureView_); // index 1++ centerStack_->setCurrentIndex(0);++ // Vertical splitter: [table/structure] over [query log] — user can drag+ // the handle to grow the log panel.+ logPanel_ = new QueryLogPanel(this);+ auto* vSplit = new QSplitter(Qt::Vertical, this);+ vSplit->setChildrenCollapsible(false);+ vSplit->setHandleWidth(4);+ vSplit->addWidget(centerStack_);+ vSplit->addWidget(logPanel_);+ vSplit->setStretchFactor(0, 1);+ vSplit->setStretchFactor(1, 0);+ vSplit->setSizes({700, 140});+ root->addWidget(vSplit, 1);++ // ===================== Bottom 34px BottomTabBar =====================+ auto* botDiv = new QFrame(this);+ botDiv->setFrameShape(QFrame::HLine);+ root->addWidget(botDiv);++ auto* bot = new QWidget(this);+ bot->setFixedHeight(34);+ bot->setAutoFillBackground(true);+ bot->setProperty("compact", true); // shrinks descendant buttons/inputs+ auto* botH = new QHBoxLayout(bot);+ botH->setContentsMargins(10, 5, 10, 5);+ botH->setSpacing(8);++ // Data / Structure pill group+ auto* pillGroup = new QWidget(bot);+ auto* pillH = new QHBoxLayout(pillGroup);+ pillH->setContentsMargins(0, 0, 0, 0);+ pillH->setSpacing(0);++ dataTabBtn_ = new QPushButton(tr("Data"), pillGroup);+ dataTabBtn_->setCheckable(true);+ dataTabBtn_->setChecked(true);+ dataTabBtn_->setAutoExclusive(true);+ dataTabBtn_->setProperty("tab", true);+ connect(dataTabBtn_, &QPushButton::clicked, this, [this] { onModeClicked(0); });+ pillH->addWidget(dataTabBtn_);++ structTabBtn_ = new QPushButton(tr("Structure"), pillGroup);+ structTabBtn_->setCheckable(true);+ structTabBtn_->setAutoExclusive(true);+ structTabBtn_->setProperty("tab", true);+ connect(structTabBtn_, &QPushButton::clicked, this, [this] { onModeClicked(1); });+ pillH->addWidget(structTabBtn_);++ botH->addWidget(pillGroup);+ botH->addSpacing(8);++ // Task 2: [+ Row] button — enabled+ addRowBtn_ = new QPushButton(QStringLiteral("+ Row"), bot);+ addRowBtn_->setToolTip(tr("Insert a new empty row"));+ addRowBtn_->setEnabled(true);+ connect(addRowBtn_, &QPushButton::clicked, this, &DataGridView::onAddRow);+ botH->addWidget(addRowBtn_);++ botH->addSpacing(16);++ // Row count label+ pageLabel_ = new QLabel(tr("No rows"), bot);+ botH->addWidget(pageLabel_);++ botH->addStretch();++ // Filters button — now functional+ filtersBtn_ = new QPushButton(QStringLiteral("⚟ Filters"), bot);+ filtersBtn_->setCheckable(true);+ filtersBtn_->setToolTip(tr("Toggle filter bar"));+ connect(filtersBtn_, &QPushButton::clicked, this, &DataGridView::onFiltersToggled);+ botH->addWidget(filtersBtn_);++ // Export button with drop-down menu+ exportMenu_ = new QMenu(this);+ exportMenu_->addAction(tr("CSV…"), this, &DataGridView::onExportCsv);+ exportMenu_->addAction(tr("JSON…"), this, &DataGridView::onExportJson);+ exportMenu_->addAction(tr("SQL…"), this, &DataGridView::onExportSql);++ exportBtn_ = new QPushButton(QStringLiteral("Export ▾"), bot);+ exportBtn_->setToolTip(tr("Export current data"));+ exportBtn_->setMenu(exportMenu_);+ botH->addWidget(exportBtn_);++ // Pagination+ prevBtn_ = new QPushButton(QStringLiteral("‹"), bot);+ prevBtn_->setFixedSize(28, 22);+ prevBtn_->setToolTip(tr("Previous page"));+ connect(prevBtn_, &QPushButton::clicked, this, &DataGridView::onPrevPage);+ botH->addWidget(prevBtn_);++ nextBtn_ = new QPushButton(QStringLiteral("›"), bot);+ nextBtn_->setFixedSize(28, 22);+ nextBtn_->setToolTip(tr("Next page"));+ connect(nextBtn_, &QPushButton::clicked, this, &DataGridView::onNextPage);+ botH->addWidget(nextBtn_);++ // Rows-per-page spin+ auto* rowsLbl = new QLabel(tr("Rows"), bot);+ botH->addWidget(rowsLbl);+ limitSpin_ = new QSpinBox(bot);+ limitSpin_->setRange(100, 100000);+ limitSpin_->setSingleStep(100);+ limitSpin_->setValue(1000);+ limitSpin_->setFixedWidth(80);+ botH->addWidget(limitSpin_);++ root->addWidget(bot);++ // Initial disabled nav state+ prevBtn_->setEnabled(false);+ nextBtn_->setEnabled(false);++ // Build context menu (populated lazily in onTableContextMenu)+ tableContextMenu_ = new QMenu(this);+}++// ===================== Adapter & Table loading =====================++void DataGridView::setAdapter(IDatabaseAdapter* adapter) {+ adapter_ = adapter;+ pkColumns_.clear();+ if (!adapter_) {+ model_->clear();+ pageLabel_->setText(tr("No rows"));+ updatePendingLabel();+ }+}++void DataGridView::loadTable(const QString& schema, const QString& table) {+ currentSchema_ = schema.isEmpty() ? std::optional<std::string>{}+ : std::optional<std::string>(schema.toStdString());+ currentTable_ = table.toStdString();+ offset_ = 0;+ totalRowCount_ = -1;+ activeFilter_ = std::nullopt;++ // Reset to Data tab whenever a new table is selected.+ dataTabBtn_->setChecked(true);+ structTabBtn_->setChecked(false);+ centerStack_->setCurrentIndex(0);+ structureView_->clear();++ // Reset filter bar column list when table changes.+ if (filterBar_) {+ filterBar_->reset();+ }++ // Cache PK columns for the new table+ cachePrimaryKeys();++ fetchAndRender();+}++void DataGridView::cachePrimaryKeys() {+ pkColumns_.clear();+ if (!adapter_ || currentTable_.empty()) return;+ try {+ const auto desc = adapter_->describeTable(currentTable_, currentSchema_);+ for (const auto& col : desc.columns) {+ if (col.isPrimaryKey) pkColumns_.push_back(col.name);+ }+ } catch (...) {+ // Non-fatal: commit will fall back to full-row match or fail gracefully.+ }+}++void DataGridView::reload() {+ if (currentTable_.empty()) return;+ offset_ = 0;+ totalRowCount_ = -1;+ fetchAndRender();+}++// ===================== Pending changes UI =====================++void DataGridView::onPendingChangesChanged() {+ updatePendingLabel();+}++void DataGridView::updatePendingLabel() {+ const bool hasChanges = model_ && model_->hasPendingChanges();+ pendingStub_->setVisible(hasChanges);+ discardBtn_->setVisible(hasChanges);+ commitBtn_->setVisible(hasChanges);+ if (!hasChanges) {+ pendingStub_->setText(QString{});+ return;+ }+ const int edits = static_cast<int>(model_->pendingEdits().size());+ const int inserts = static_cast<int>(model_->insertedRows().size());+ const int deletes = static_cast<int>(model_->deletedRows().size());+ QStringList parts;+ if (edits > 0) parts << tr("%1 edit(s)").arg(edits);+ if (inserts > 0) parts << tr("%1 new").arg(inserts);+ if (deletes > 0) parts << tr("%1 delete(s)").arg(deletes);+ pendingStub_->setText(parts.join(QStringLiteral(", ")) + tr(" pending"));+ discardBtn_->setEnabled(true);+ commitBtn_->setEnabled(true);+}++// ===================== Add Row (Task 2) =====================++void DataGridView::onAddRow() {+ if (!model_ || currentTable_.empty()) return;+ model_->addEmptyRow();+ // Scroll to and select the new row+ const int newRow = model_->rowCount() - 1;+ const auto newIdx = model_->index(newRow, 0);+ tableView_->scrollTo(newIdx);+ tableView_->setCurrentIndex(newIdx);+ tableView_->edit(newIdx);+}++// ===================== Pending SQL preview helper =====================++QStringList DataGridView::buildPendingStatements() const {+ if (!model_ || currentTable_.empty()) return {};++ const SQLDialect dialect = adapter_ ? sqlDialect(adapter_->databaseType()) : SQLDialect::PostgreSQL;++ const std::string qualifiedTable = [&] {+ if (currentSchema_) {+ return quoteIdentifier(dialect, *currentSchema_) + "." ++ quoteIdentifier(dialect, currentTable_);+ }+ return quoteIdentifier(dialect, currentTable_);+ }();++ const auto& result = model_->result();+ const auto& cols = result.columns;+ const int colCount = static_cast<int>(cols.size());++ auto quoteLiteral = [](const RowValue& v) -> std::string {+ if (v.isNull()) return "NULL";+ if (v.isNumeric()) return v.displayString();+ std::string s = v.displayString();+ std::string out;+ out.reserve(s.size() + 2);+ out.push_back('\'');+ for (char c : s) {+ if (c == '\'') out.push_back('\'');+ out.push_back(c);+ }+ out.push_back('\'');+ return out;+ };++ auto buildWhereClause = [&](int row) -> std::string {+ std::string clause;+ auto append = [&](const std::string& col, const RowValue& val) {+ if (!clause.empty()) clause += " AND ";+ clause += quoteIdentifier(dialect, col) + " = " + quoteLiteral(val);+ };+ if (pkColumns_.empty()) {+ for (int c = 0; c < colCount; ++c) {+ append(cols[c].name, model_->effectiveCellValue(row, c));+ }+ } else {+ for (const auto& pk : pkColumns_) {+ for (int c = 0; c < colCount; ++c) {+ if (cols[c].name == pk) {+ const RowValue origVal = (row < static_cast<int>(result.rows.size()) &&+ c < static_cast<int>(result.rows[row].size()))+ ? result.rows[row][c]+ : RowValue::makeNull();+ append(pk, origVal);+ break;+ }+ }+ }+ }+ return clause;+ };++ QStringList stmts;++ // Updates+ std::map<int, std::unordered_map<std::string, RowValue>> editsByRow;+ for (const auto& [key, val] : model_->pendingEdits()) {+ const int c = key.second;+ if (c < colCount) editsByRow[key.first][cols[c].name] = val;+ }+ for (const auto& [row, setMap] : editsByRow) {+ if (model_->isRowDeleted(row)) continue;+ std::string setPart;+ for (const auto& [col, val] : setMap) {+ if (!setPart.empty()) setPart += ", ";+ setPart += quoteIdentifier(dialect, col) + " = " + quoteLiteral(val);+ }+ const std::string where = buildWhereClause(row);+ stmts << QString::fromStdString(+ "UPDATE " + qualifiedTable + " SET " + setPart ++ (where.empty() ? "" : " WHERE " + where) + ";");+ }++ // Inserts+ for (const auto& insertedRow : model_->insertedRows()) {+ std::string colPart, valPart;+ for (int c = 0; c < colCount && c < static_cast<int>(insertedRow.size()); ++c) {+ if (insertedRow[c].isNull()) continue;+ if (!colPart.empty()) { colPart += ", "; valPart += ", "; }+ colPart += quoteIdentifier(dialect, cols[c].name);+ valPart += quoteLiteral(insertedRow[c]);+ }+ if (!colPart.empty()) {+ stmts << QString::fromStdString(+ "INSERT INTO " + qualifiedTable + " (" + colPart + ") VALUES (" + valPart + ");");+ }+ }++ // Deletes+ std::vector<int> toDelete(model_->deletedRows().rbegin(), model_->deletedRows().rend());+ for (const int row : toDelete) {+ const std::string where = buildWhereClause(row);+ stmts << QString::fromStdString(+ "DELETE FROM " + qualifiedTable ++ (where.empty() ? "" : " WHERE " + where) + ";");+ }++ return stmts;+}++// ===================== Commit (Task 4) =====================++void DataGridView::onCommit() {+ if (!adapter_ || !model_ || currentTable_.empty()) return;+ if (!model_->hasPendingChanges()) return;++ // Pre-flight dry-run: show SQL preview and require explicit Apply.+ {+ const QStringList stmts = buildPendingStatements();+ const int updates = static_cast<int>(+ std::count_if(stmts.begin(), stmts.end(),+ [](const QString& s){ return s.startsWith(QLatin1String("UPDATE")); }));+ const int inserts = static_cast<int>(+ std::count_if(stmts.begin(), stmts.end(),+ [](const QString& s){ return s.startsWith(QLatin1String("INSERT")); }));+ const int deletes = static_cast<int>(+ std::count_if(stmts.begin(), stmts.end(),+ [](const QString& s){ return s.startsWith(QLatin1String("DELETE")); }));++ QStringList summaryParts;+ if (updates > 0) summaryParts << tr("%1 UPDATE").arg(updates);+ if (inserts > 0) summaryParts << tr("%1 INSERT").arg(inserts);+ if (deletes > 0) summaryParts << tr("%1 DELETE").arg(deletes);++ QString preview;+ preview.reserve(stmts.size() * 80);+ for (int i = 0; i < stmts.size(); ++i) {+ preview += QString::number(i + 1) + QLatin1String(". ") + stmts[i] + QLatin1Char('\n');+ }+ preview += QLatin1Char('\n') + tr("— %1 —").arg(summaryParts.join(QStringLiteral(" · ")));++ auto* dlg = new QDialog(this);+ dlg->setWindowTitle(tr("Preview Changes"));+ dlg->resize(640, 400);+ auto* vlay = new QVBoxLayout(dlg);+ auto* edit = new QPlainTextEdit(dlg);+ edit->setReadOnly(true);+ edit->setPlainText(preview);+ edit->setFont(QFont(QStringLiteral("Monospace"), 10));+ vlay->addWidget(edit);+ auto* btns = new QDialogButtonBox(dlg);+ auto* applyBtn = btns->addButton(tr("Apply"), QDialogButtonBox::AcceptRole);+ auto* cancelBtn = btns->addButton(tr("Cancel"), QDialogButtonBox::RejectRole);+ Q_UNUSED(applyBtn); Q_UNUSED(cancelBtn);+ connect(btns, &QDialogButtonBox::accepted, dlg, &QDialog::accept);+ connect(btns, &QDialogButtonBox::rejected, dlg, &QDialog::reject);+ vlay->addWidget(btns);++ if (dlg->exec() != QDialog::Accepted) {+ dlg->deleteLater();+ return;+ }+ dlg->deleteLater();+ }++ const auto& result = model_->result();+ const auto& cols = result.columns;+ const int colCount = static_cast<int>(cols.size());++ // Helper: build WHERE clause from PK columns for a given original row.+ auto buildPkWhere = [&](int row) -> std::unordered_map<std::string, RowValue> {+ std::unordered_map<std::string, RowValue> where;+ if (pkColumns_.empty()) {+ // No PK info — use all columns as identity (best-effort).+ for (int c = 0; c < colCount; ++c) {+ where[cols[c].name] = model_->effectiveCellValue(row, c);+ }+ } else {+ for (const auto& pk : pkColumns_) {+ for (int c = 0; c < colCount; ++c) {+ if (cols[c].name == pk) {+ // Use the ORIGINAL value from result_ for the WHERE clause.+ const RowValue origVal = (row < static_cast<int>(result.rows.size()) &&+ c < static_cast<int>(result.rows[row].size()))+ ? result.rows[row][c]+ : RowValue::makeNull();+ where[pk] = origVal;+ break;+ }+ }+ }+ }+ return where;+ };++ QStringList errors;++ try {+ adapter_->beginTransaction();++ // 1. Apply edits to original rows (grouped by row).+ std::map<int, std::unordered_map<std::string, RowValue>> editsByRow;+ for (const auto& [key, val] : model_->pendingEdits()) {+ const int r = key.first;+ const int c = key.second;+ if (c < colCount) {+ editsByRow[r][cols[c].name] = val;+ }+ }+ for (const auto& [row, setMap] : editsByRow) {+ if (model_->isRowDeleted(row)) continue; // will be handled by delete pass+ try {+ adapter_->updateRow(currentTable_, currentSchema_, setMap, buildPkWhere(row));+ } catch (const GridexError& e) {+ errors << tr("Update row %1: %2").arg(row + 1).arg(QString::fromUtf8(e.what()));+ }+ }++ // 2. Insert new rows.+ for (const auto& insertedRow : model_->insertedRows()) {+ std::unordered_map<std::string, RowValue> values;+ for (int c = 0; c < colCount && c < static_cast<int>(insertedRow.size()); ++c) {+ if (!insertedRow[c].isNull()) {+ values[cols[c].name] = insertedRow[c];+ }+ }+ if (values.empty()) continue; // skip fully-null rows+ try {+ adapter_->insertRow(currentTable_, currentSchema_, values);+ } catch (const GridexError& e) {+ errors << tr("Insert row: %1").arg(QString::fromUtf8(e.what()));+ }+ }++ // 3. Delete marked rows (process in reverse order to keep indices stable).+ std::vector<int> toDelete(model_->deletedRows().rbegin(), model_->deletedRows().rend());+ for (const int row : toDelete) {+ try {+ adapter_->deleteRow(currentTable_, currentSchema_, buildPkWhere(row));+ } catch (const GridexError& e) {+ errors << tr("Delete row %1: %2").arg(row + 1).arg(QString::fromUtf8(e.what()));+ }+ }++ if (errors.isEmpty()) {+ adapter_->commitTransaction();+ } else {+ adapter_->rollbackTransaction();+ QMessageBox::critical(this, tr("Commit Failed"),+ tr("Some operations failed — changes rolled back:\n\n") ++ errors.join(QStringLiteral("\n")));+ return;+ }+ } catch (const GridexError& e) {+ try { adapter_->rollbackTransaction(); } catch (...) {}+ QMessageBox::critical(this, tr("Commit Failed"), QString::fromUtf8(e.what()));+ return;+ }++ // Commit summary for the user (transient — auto-hides).+ const int edits = static_cast<int>(model_->pendingEdits().size());+ const int inserts = static_cast<int>(model_->insertedRows().size());+ const int deletes = static_cast<int>(model_->deletedRows().size());+ QStringList parts;+ if (edits > 0) parts << tr("%1 updated").arg(edits);+ if (inserts > 0) parts << tr("%1 inserted").arg(inserts);+ if (deletes > 0) parts << tr("%1 deleted").arg(deletes);++ // Reload to reflect committed state.+ model_->clearPendingChanges();+ fetchAndRender();++ // Show transient ✓ confirmation in the top toolbar for 3 seconds.+ pendingStub_->setStyleSheet(QStringLiteral("color: #a6e3a1;")); // success green+ pendingStub_->setText(tr("✓ Committed — %1").arg(parts.join(QStringLiteral(", "))));+ pendingStub_->setVisible(true);+ QTimer::singleShot(3000, this, [this] {+ pendingStub_->setText(QString{});+ pendingStub_->setVisible(false);+ pendingStub_->setStyleSheet(QStringLiteral("color: #f9e2af;")); // reset to warn+ });+}++// ===================== Discard (Task 4) =====================++void DataGridView::onDiscard() {+ if (!model_) return;+ model_->clearPendingChanges();+ fetchAndRender();+}++// ===================== Context menu (Tasks 3 & 5) =====================++void DataGridView::onTableContextMenu(const QPoint& pos) {+ const QModelIndex idx = tableView_->indexAt(pos);++ tableContextMenu_->clear();++ // Refresh — reload current table from adapter. Always enabled when a+ // table is loaded; works even on blank area (no cell under cursor).+ auto* refreshAction = tableContextMenu_->addAction(+ tr("Refresh"), this, &DataGridView::reload);+ refreshAction->setShortcut(QKeySequence::Refresh);+ refreshAction->setEnabled(!currentTable_.empty());++ tableContextMenu_->addSeparator();++ // Copy actions (Task 5)+ auto* copyCellAction = tableContextMenu_->addAction(tr("Copy Cell"), this, &DataGridView::onCopyCell);+ auto* copyRowAction = tableContextMenu_->addAction(tr("Copy Row"), this, &DataGridView::onCopyRow);+ auto* copyInsertAction = tableContextMenu_->addAction(tr("Copy as INSERT"), this, &DataGridView::onCopyAsInsert);++ copyCellAction->setEnabled(idx.isValid());+ copyRowAction->setEnabled(idx.isValid());+ copyInsertAction->setEnabled(idx.isValid() && !currentTable_.empty());++ tableContextMenu_->addSeparator();++ // Delete action (Task 3)+ const auto selected = tableView_->selectionModel()->selectedRows();+ auto* deleteAction = tableContextMenu_->addAction(tr("Delete Row(s)\tDel"), this, &DataGridView::onDeleteRows);+ deleteAction->setEnabled(!selected.isEmpty());++ tableContextMenu_->exec(tableView_->viewport()->mapToGlobal(pos));+}++void DataGridView::onCopyCell() {+ const QModelIndex idx = tableView_->currentIndex();+ if (!idx.isValid() || !model_) return;+ const RowValue cell = model_->effectiveCellValue(idx.row(), idx.column());+ const QString text = QString::fromUtf8(cell.displayString().c_str());+ QApplication::clipboard()->setText(text);+}++void DataGridView::onCopyRow() {+ const QModelIndex idx = tableView_->currentIndex();+ if (!idx.isValid() || !model_) return;+ const int row = idx.row();+ const int cols = model_->columnCount();+ QStringList parts;+ parts.reserve(cols);+ for (int c = 0; c < cols; ++c) {+ parts << QString::fromUtf8(model_->effectiveCellValue(row, c).displayString().c_str());+ }+ QApplication::clipboard()->setText(parts.join(QLatin1Char('\t')));+}++void DataGridView::onCopyAsInsert() {+ const QModelIndex idx = tableView_->currentIndex();+ if (!idx.isValid() || !model_ || currentTable_.empty()) return;+ const int row = idx.row();+ const int cols = model_->columnCount();+ const auto& columns = model_->result().columns;++ QStringList colNames, values;+ colNames.reserve(cols);+ values.reserve(cols);++ for (int c = 0; c < cols; ++c) {+ const RowValue cell = model_->effectiveCellValue(row, c);+ colNames << QString::fromUtf8(columns[c].name.c_str());+ if (cell.isNull()) {+ values << QStringLiteral("NULL");+ } else {+ // Quote as string literal; numeric types inline without quotes+ if (cell.isNumeric()) {+ values << QString::fromUtf8(cell.displayString().c_str());+ } else {+ QString escaped = QString::fromUtf8(cell.displayString().c_str());+ escaped.replace(QLatin1Char('\''), QStringLiteral("''"));+ values << (QLatin1Char('\'') + escaped + QLatin1Char('\''));+ }+ }+ }++ const QString sql = QStringLiteral("INSERT INTO %1 (%2) VALUES (%3);")+ .arg(QString::fromStdString(currentTable_))+ .arg(colNames.join(QStringLiteral(", ")))+ .arg(values.join(QStringLiteral(", ")));+ QApplication::clipboard()->setText(sql);+}++void DataGridView::onDeleteRows() {+ if (!model_) return;+ const auto selected = tableView_->selectionModel()->selectedRows();+ for (const auto& idx : selected) {+ model_->markRowDeleted(idx.row());+ }+}++// ===================== Navigation & paging =====================++void DataGridView::onPrevPage() {+ if (currentTable_.empty()) return;+ offset_ = std::max(0, offset_ - limitSpin_->value());+ fetchAndRender();+}++void DataGridView::onNextPage() {+ if (currentTable_.empty()) return;+ offset_ += limitSpin_->value();+ fetchAndRender();+}++void DataGridView::onFiltersToggled() {+ const bool show = filtersBtn_->isChecked();+ filterBar_->setVisible(show);+ filterBarDiv_->setVisible(show);+ if (!show) {+ if (activeFilter_.has_value()) {+ activeFilter_ = std::nullopt;+ filterBar_->reset();+ offset_ = 0;+ totalRowCount_ = -1;+ fetchAndRender();+ }+ }+}++void DataGridView::onModeClicked(int mode) {+ dataTabBtn_->setChecked(mode == 0);+ structTabBtn_->setChecked(mode == 1);++ if (mode == 1) {+ centerStack_->setCurrentIndex(1);+ loadStructure();+ } else {+ centerStack_->setCurrentIndex(0);+ }+}++void DataGridView::loadStructure() {+ if (!adapter_ || currentTable_.empty()) {+ structureView_->clear();+ return;+ }+ try {+ const auto desc = adapter_->describeTable(currentTable_, currentSchema_);+ structureView_->loadStructure(desc);+ } catch (const GridexError& e) {+ structureView_->clear();+ emit loadFailed(QString::fromUtf8(e.what()));+ }+}++void DataGridView::fetchAndRender() {+ if (!adapter_ || currentTable_.empty()) return;+ QElapsedTimer timer; timer.start();+ try {+ auto result = adapter_->fetchRows(currentTable_,+ currentSchema_,+ std::nullopt,+ activeFilter_,+ std::nullopt,+ limitSpin_->value(),+ offset_);+ const int n = static_cast<int>(result.rows.size());+ const int ms = static_cast<int>(timer.elapsed());++ // Fetch total row count using COUNT(*) so the label can show "X-Y of Z".+ // Only re-fetch when offset_ == 0 (table/filter just changed) or unknown.+ if (offset_ == 0 || totalRowCount_ < 0) {+ try {+ const SQLDialect dialect = sqlDialect(adapter_->databaseType());+ std::string qualTable = currentSchema_+ ? quoteIdentifier(dialect, *currentSchema_) + "." + quoteIdentifier(dialect, currentTable_)+ : quoteIdentifier(dialect, currentTable_);+ std::string countSql = "SELECT COUNT(*) FROM " + qualTable;+ if (activeFilter_.has_value() && !activeFilter_->conditions.empty()) {+ countSql += " WHERE " + activeFilter_->toSQL(dialect);+ }+ const auto countResult = adapter_->executeRaw(countSql);+ if (!countResult.rows.empty() && !countResult.rows[0].empty()) {+ const auto& cell = countResult.rows[0][0];+ totalRowCount_ = static_cast<int>(cell.tryIntValue().value_or(0));+ }+ } catch (...) {+ totalRowCount_ = -1;+ }+ }++ // Capture column list before moving result into model.+ std::vector<std::string> colNames;+ colNames.reserve(result.columns.size());+ for (const auto& h : result.columns) colNames.push_back(h.name);++ model_->setResult(std::move(result));+ // Update filter bar column list after data loads.+ if (filterBar_ && !colNames.empty()) {+ filterBar_->setColumns(colNames);+ }+ tableView_->resizeColumnsToContents();+ fitColumnsToViewport();++ const int limit = limitSpin_->value();+ setPagingLabel(n, ms);+ prevBtn_->setEnabled(offset_ > 0);+ nextBtn_->setEnabled(totalRowCount_ < 0+ ? n >= limit+ : offset_ + n < totalRowCount_);+ emit rowCountChanged(n, ms);++ // Log the query to the SQL log panel.+ if (logPanel_) {+ const QString schema = currentSchema_+ ? QString::fromStdString(*currentSchema_) : QString{};+ const QString table = QString::fromStdString(currentTable_);+ const QString qualified = schema.isEmpty() ? table : (schema + QStringLiteral(".") + table);+ QString logSql = QStringLiteral("SELECT * FROM %1").arg(qualified);+ if (activeFilter_.has_value() && !activeFilter_->conditions.empty()) {+ logSql += QStringLiteral(" WHERE [filter]");+ }+ logSql += QStringLiteral(" LIMIT %1 OFFSET %2").arg(limitSpin_->value()).arg(offset_);+ logPanel_->appendQuery(logSql, ms);+ }+ } catch (const GridexError& e) {+ model_->clear();+ pageLabel_->setText(QString::fromUtf8(e.what()));+ emit loadFailed(QString::fromUtf8(e.what()));+ }+ // Reset pending UI after a fresh load+ updatePendingLabel();+}++void DataGridView::fitColumnsToViewport() {+ if (!tableView_ || !model_) return;+ auto* h = tableView_->horizontalHeader();+ const int cols = model_->columnCount();+ if (!h || cols == 0) return;+ int used = 0;+ for (int i = 0; i < cols - 1; ++i) used += h->sectionSize(i);+ const int avail = tableView_->viewport()->width() - used;+ if (avail > h->sectionSize(cols - 1)) {+ h->resizeSection(cols - 1, avail);+ }+}++bool DataGridView::eventFilter(QObject* obj, QEvent* event) {+ // Shift+wheel → horizontal scroll on the table viewport.+ if (obj == tableView_->viewport() && event->type() == QEvent::Wheel) {+ auto* we = static_cast<QWheelEvent*>(event);+ if (we->modifiers() & Qt::ShiftModifier) {+ // Forward as horizontal scroll.+ auto* hBar = tableView_->horizontalScrollBar();+ if (hBar) {+ const int delta = we->angleDelta().y(); // vertical wheel value+ hBar->setValue(hBar->value() - delta);+ we->accept();+ return true;+ }+ }+ }+ return QWidget::eventFilter(obj, event);+}++void DataGridView::resizeEvent(QResizeEvent* event) {+ QWidget::resizeEvent(event);+ QTimer::singleShot(0, this, [this] { fitColumnsToViewport(); });+}++void DataGridView::onRowSelectionChanged() {+ const auto idx = tableView_->currentIndex();+ if (!idx.isValid() || !model_) return;+ const int row = idx.row();+ const auto& result = model_->result();+ if (row < 0 || row >= static_cast<int>(result.rows.size())) return;++ std::vector<std::pair<std::string, std::string>> fields;+ fields.reserve(result.columns.size());+ for (std::size_t c = 0; c < result.columns.size(); ++c) {+ const auto& col = result.columns[c].name;+ const auto& val = (c < result.rows[row].size())+ ? result.rows[row][c].displayString()+ : std::string{"NULL"};+ fields.emplace_back(col, val);+ }+ emit rowSelected(fields);+}++void DataGridView::setPagingLabel(int rowsShown, int /*durationMs*/) {+ if (rowsShown == 0) {+ pageLabel_->setText(tr("No rows"));+ return;+ }+ const int start = offset_ + 1;+ const int end = offset_ + rowsShown;+ if (totalRowCount_ >= 0) {+ pageLabel_->setText(tr("Showing %1–%2 of %3")+ .arg(start)+ .arg(end)+ .arg(QLocale().toString(totalRowCount_)));+ } else {+ pageLabel_->setText(tr("%1–%2").arg(start).arg(end));+ }+}++// ===================== Export =====================++void DataGridView::onExportCsv() {+ if (!model_ || model_->result().isEmpty()) return;+ const QString path = QFileDialog::getSaveFileName(+ this, tr("Export as CSV"),+ currentTable_.empty() ? QStringLiteral("export.csv")+ : QString::fromStdString(currentTable_) + QStringLiteral(".csv"),+ tr("CSV files (*.csv);;All files (*)"));+ if (path.isEmpty()) return;+ try {+ ExportService::exportToCsv(model_->result(), path.toStdString());+ } catch (const std::exception& e) {+ QMessageBox::critical(this, tr("Export Failed"), QString::fromUtf8(e.what()));+ }+}++void DataGridView::onExportJson() {+ if (!model_ || model_->result().isEmpty()) return;+ const QString path = QFileDialog::getSaveFileName(+ this, tr("Export as JSON"),+ currentTable_.empty() ? QStringLiteral("export.json")+ : QString::fromStdString(currentTable_) + QStringLiteral(".json"),+ tr("JSON files (*.json);;All files (*)"));+ if (path.isEmpty()) return;+ try {+ ExportService::exportToJson(model_->result(), path.toStdString());+ } catch (const std::exception& e) {+ QMessageBox::critical(this, tr("Export Failed"), QString::fromUtf8(e.what()));+ }+}++void DataGridView::onExportSql() {+ if (!model_ || model_->result().isEmpty()) return;+ const QString path = QFileDialog::getSaveFileName(+ this, tr("Export as SQL"),+ currentTable_.empty() ? QStringLiteral("export.sql")+ : QString::fromStdString(currentTable_) + QStringLiteral(".sql"),+ tr("SQL files (*.sql);;All files (*)"));+ if (path.isEmpty()) return;+ try {+ ExportService::exportToSql(model_->result(), currentTable_, path.toStdString());+ } catch (const std::exception& e) {+ QMessageBox::critical(this, tr("Export Failed"), QString::fromUtf8(e.what()));+ }+}++} // namespace gridexdiff --git a/linux/src/Presentation/Views/DataGrid/DataGridView.h b/linux/src/Presentation/Views/DataGrid/DataGridView.hnew file mode 100644index 0000000..2bdb815--- /dev/null+++ b/linux/src/Presentation/Views/DataGrid/DataGridView.h@@ -0,0 +1,141 @@+#pragma once++#include <QStringList>+#include <QWidget>+#include <optional>+#include <set>+#include <string>+#include <utility>+#include <vector>++#include "Core/Models/Query/FilterExpression.h"+#include "Core/Models/Schema/SchemaSnapshot.h"++class QFrame;+class QLabel;+class QMenu;+class QPushButton;+class QSpinBox;+class QStackedWidget;+class QTableView;++namespace gridex {++class FilterBarView;+class IDatabaseAdapter;+class QueryLogPanel;+class QueryResultModel;+class TableStructureView;++// Editable table data viewer:+// Top 28px DataGridToolbar: [pending label] [Discard] [Commit] .... [Reload]+// FilterBar (hidden by default, toggled by Filters button)+// Center: QStackedWidget — page 0: QTableView (data), page 1: TableStructureView+// QueryLogPanel (collapsible, logs executed queries with timestamps)+// Bottom 34px BottomTabBar: [Data|Structure] [+Row] [X-Y of Z rows] [Filters] [<][>] [Rows spin]+class DataGridView : public QWidget {+ Q_OBJECT++public:+ explicit DataGridView(QWidget* parent = nullptr);++ void setAdapter(IDatabaseAdapter* adapter);++public slots:+ void loadTable(const QString& schema, const QString& table);+ void reload();++protected:+ void resizeEvent(QResizeEvent* event) override;+ bool eventFilter(QObject* obj, QEvent* event) override;++signals:+ void loadFailed(const QString& message);+ void rowCountChanged(int rowsShown, int durationMs);+ void rowSelected(const std::vector<std::pair<std::string, std::string>>& fields);++private slots:+ void onRowSelectionChanged();+ void onPrevPage();+ void onNextPage();+ void onFiltersToggled();+ void onModeClicked(int mode); // 0 = Data, 1 = Structure+ void onExportCsv();+ void onExportJson();+ void onExportSql();++ // Editing actions+ void onAddRow();+ void onCommit();+ void onDiscard();+ void onTableContextMenu(const QPoint& pos);+ void onCopyCell();+ void onCopyRow();+ void onCopyAsInsert();+ void onDeleteRows();+ void onPendingChangesChanged();++private:+ void buildUi();+ void fetchAndRender();+ void loadStructure();+ void setPagingLabel(int rowsShown, int durationMs);+ void fitColumnsToViewport();+ void updatePendingLabel();++ // PK detection: called once per loadTable, cached in pkColumns_+ void cachePrimaryKeys();++ // Returns SQL statements for all pending changes without executing them.+ QStringList buildPendingStatements() const;++ IDatabaseAdapter* adapter_ = nullptr;++ // Current table state+ std::optional<std::string> currentSchema_;+ std::string currentTable_;+ int offset_ = 0;+ int totalRowCount_ = -1; // -1 = unknown++ // Cached primary key column names for the current table+ std::vector<std::string> pkColumns_;++ // UI — top toolbar+ QLabel* pendingStub_ = nullptr;+ QPushButton* discardBtn_ = nullptr;+ QPushButton* commitBtn_ = nullptr;+ QPushButton* reloadBtn_ = nullptr;++ // Filter bar (hidden until Filters toggled)+ FilterBarView* filterBar_ = nullptr;+ QFrame* filterBarDiv_ = nullptr; // separator below filterBar_++ // Active filter (nullopt = no filter applied)+ std::optional<FilterExpression> activeFilter_;++ // Center: stacked pages — index 0 = data, index 1 = structure+ QStackedWidget* centerStack_ = nullptr;+ QTableView* tableView_ = nullptr;+ QueryResultModel* model_ = nullptr;+ TableStructureView* structureView_ = nullptr;++ // SQL log panel (collapsible, below center stack)+ QueryLogPanel* logPanel_ = nullptr;++ // Bottom bar+ QPushButton* dataTabBtn_ = nullptr;+ QPushButton* structTabBtn_ = nullptr;+ QPushButton* addRowBtn_ = nullptr;+ QLabel* pageLabel_ = nullptr;+ QPushButton* filtersBtn_ = nullptr;+ QPushButton* exportBtn_ = nullptr;+ QMenu* exportMenu_ = nullptr;+ QPushButton* prevBtn_ = nullptr;+ QPushButton* nextBtn_ = nullptr;+ QSpinBox* limitSpin_ = nullptr;++ // Context menu for tableView_+ QMenu* tableContextMenu_ = nullptr;+};++}diff --git a/linux/src/Presentation/Views/DataGrid/QueryResultModel.cpp b/linux/src/Presentation/Views/DataGrid/QueryResultModel.cppnew file mode 100644index 0000000..fc7c133--- /dev/null+++ b/linux/src/Presentation/Views/DataGrid/QueryResultModel.cpp@@ -0,0 +1,220 @@+#include "Presentation/Views/DataGrid/QueryResultModel.h"++#include <QColor>+#include <QFont>++namespace gridex {++// ---- helpers ----++RowValue QueryResultModel::effectiveCellValue(int row, int col) const {+ auto it = pendingEdits_.find({row, col});+ if (it != pendingEdits_.end()) return it->second;++ if (isInsertedRow(row)) {+ const int insertedIdx = row - static_cast<int>(result_.rows.size());+ if (insertedIdx < static_cast<int>(insertedRows_.size()) &&+ col < static_cast<int>(insertedRows_[insertedIdx].size())) {+ return insertedRows_[insertedIdx][col];+ }+ return RowValue::makeNull();+ }++ if (row < static_cast<int>(result_.rows.size()) &&+ col < static_cast<int>(result_.rows[row].size())) {+ return result_.rows[row][col];+ }+ return RowValue::makeNull();+}++void QueryResultModel::addEmptyRow() {+ const int cols = columnCount();+ std::vector<RowValue> emptyRow(cols, RowValue::makeNull());+ const int newRowIdx = rowCount();+ beginInsertRows({}, newRowIdx, newRowIdx);+ insertedRows_.push_back(std::move(emptyRow));+ endInsertRows();+ emit pendingChangesChanged();+}++void QueryResultModel::markRowDeleted(int row) {+ if (row < 0 || row >= rowCount()) return;+ if (isInsertedRow(row)) {+ // Cancelling an inserted row: remove it directly.+ const int insertedIdx = row - static_cast<int>(result_.rows.size());+ beginRemoveRows({}, row, row);+ insertedRows_.erase(insertedRows_.begin() + insertedIdx);+ endRemoveRows();+ // Remove any pending edits for that inserted row and shift higher-row keys.+ std::map<CellKey, RowValue> adjusted;+ for (auto& [k, v] : pendingEdits_) {+ if (k.first < row) {+ adjusted[k] = v;+ } else if (k.first > row) {+ adjusted[{k.first - 1, k.second}] = v;+ }+ // k.first == row: drop it+ }+ pendingEdits_ = std::move(adjusted);+ } else {+ if (deletedRows_.count(row)) {+ // Toggle: undelete+ deletedRows_.erase(row);+ } else {+ deletedRows_.insert(row);+ }+ // Repaint the row+ if (columnCount() > 0) {+ emit dataChanged(index(row, 0), index(row, columnCount() - 1));+ }+ }+ emit pendingChangesChanged();+}++// ---- QAbstractTableModel overrides ----++Qt::ItemFlags QueryResultModel::flags(const QModelIndex& index) const {+ if (!index.isValid()) return Qt::NoItemFlags;+ // Deleted rows remain selectable but not editable+ if (isRowDeleted(index.row())) {+ return Qt::ItemIsSelectable | Qt::ItemIsEnabled;+ }+ return Qt::ItemIsEditable | Qt::ItemIsSelectable | Qt::ItemIsEnabled;+}++QVariant QueryResultModel::data(const QModelIndex& index, int role) const {+ if (!index.isValid()) return {};+ const int r = index.row();+ const int c = index.column();+ if (r < 0 || r >= rowCount() || c < 0 || c >= columnCount()) return {};++ const bool hasPendingEdit = pendingEdits_.count({r, c}) > 0;+ const bool isDeleted = isRowDeleted(r);+ const bool isNew = isInsertedRow(r);+ const RowValue cell = effectiveCellValue(r, c);++ switch (role) {+ case Qt::DisplayRole:+ case Qt::EditRole:+ return QString::fromUtf8(cell.displayString().c_str());++ case Qt::ToolTipRole: {+ const auto full = cell.tryStringValue().value_or("NULL");+ if (full.size() > 500) return QString::fromUtf8(full.substr(0, 500).c_str()) + QStringLiteral("…");+ return QString::fromUtf8(full.c_str());+ }++ case Qt::BackgroundRole:+ if (isDeleted) return QColor(255, 200, 200); // red tint for deletions+ if (isNew) return QColor(200, 255, 200); // green tint for new rows+ if (hasPendingEdit) return QColor(255, 255, 200); // yellow for modified cells+ return {};++ case Qt::ForegroundRole:+ if (isDeleted) return QColor(150, 50, 50);+ if (cell.isNull()) return QColor(150, 150, 150);+ return {};++ case Qt::FontRole: {+ QFont f;+ if (isDeleted) {+ f.setStrikeOut(true);+ return f;+ }+ if (cell.isNull() && !hasPendingEdit) {+ f.setItalic(true);+ return f;+ }+ return {};+ }++ case Qt::TextAlignmentRole:+ if (cell.isNumeric()) return int(Qt::AlignVCenter | Qt::AlignRight);+ return int(Qt::AlignVCenter | Qt::AlignLeft);++ default:+ return {};+ }+}++bool QueryResultModel::setData(const QModelIndex& index, const QVariant& value, int role) {+ if (role != Qt::EditRole) return false;+ if (!index.isValid()) return false;+ const int r = index.row();+ const int c = index.column();+ if (r < 0 || r >= rowCount() || c < 0 || c >= columnCount()) return false;+ if (isRowDeleted(r)) return false;++ const QString str = value.toString();+ RowValue newVal = str.isEmpty() ? RowValue::makeNull()+ : RowValue::makeString(str.toStdString());++ if (isInsertedRow(r)) {+ // Write directly into the inserted row buffer.+ const int insertedIdx = r - static_cast<int>(result_.rows.size());+ if (insertedIdx < static_cast<int>(insertedRows_.size()) &&+ c < static_cast<int>(insertedRows_[insertedIdx].size())) {+ insertedRows_[insertedIdx][c] = std::move(newVal);+ emit dataChanged(index, index, {Qt::DisplayRole, Qt::EditRole, Qt::BackgroundRole});+ emit pendingChangesChanged();+ return true;+ }+ return false;+ }++ pendingEdits_[{r, c}] = std::move(newVal);+ emit dataChanged(index, index, {Qt::DisplayRole, Qt::EditRole, Qt::BackgroundRole, Qt::ForegroundRole, Qt::FontRole});+ emit pendingChangesChanged();+ return true;+}++QVariant QueryResultModel::headerData(int section, Qt::Orientation orientation, int role) const {+ if (role == Qt::DisplayRole) {+ if (orientation == Qt::Horizontal) {+ if (section < 0 || section >= columnCount()) return {};+ return QString::fromUtf8(result_.columns[section].name.c_str());+ }+ if (orientation == Qt::Vertical) {+ return section + 1;+ }+ }+ if (role == Qt::ToolTipRole && orientation == Qt::Horizontal) {+ if (section < 0 || section >= columnCount()) return {};+ const auto& h = result_.columns[section];+ return QString::fromUtf8((h.name + " : " + h.dataType).c_str());+ }+ return {};+}++void QueryResultModel::sort(int column, Qt::SortOrder order) {+ if (column < 0 || column >= columnCount()) return;+ if (result_.rows.empty()) return;+ // Don't sort if there are pending changes — too complex to remap indices.+ if (hasPendingChanges()) return;++ const auto col = static_cast<std::size_t>(column);+ beginResetModel();+ std::stable_sort(result_.rows.begin(), result_.rows.end(),+ [col, order](const std::vector<RowValue>& a, const std::vector<RowValue>& b) {+ if (col >= a.size() || col >= b.size()) return false;+ const auto& va = a[col];+ const auto& vb = b[col];+ // NULLs always sort last.+ if (va.isNull() && vb.isNull()) return false;+ if (va.isNull()) return order == Qt::DescendingOrder;+ if (vb.isNull()) return order == Qt::AscendingOrder;+ // Numeric comparison when both are numeric.+ if (va.isNumeric() && vb.isNumeric()) {+ const double da = va.tryDoubleValue().value_or(0);+ const double db = vb.tryDoubleValue().value_or(0);+ return order == Qt::AscendingOrder ? da < db : da > db;+ }+ // Fall back to string comparison.+ const auto sa = va.displayString();+ const auto sb = vb.displayString();+ return order == Qt::AscendingOrder ? sa < sb : sa > sb;+ });+ endResetModel();+}++}diff --git a/linux/src/Presentation/Views/DataGrid/QueryResultModel.h b/linux/src/Presentation/Views/DataGrid/QueryResultModel.hnew file mode 100644index 0000000..e5b272c--- /dev/null+++ b/linux/src/Presentation/Views/DataGrid/QueryResultModel.h@@ -0,0 +1,109 @@+#pragma once++#include <QAbstractTableModel>+#include <map>+#include <set>+#include <utility>+#include <vector>++#include "Core/Models/Database/RowValue.h"+#include "Core/Models/Query/QueryResult.h"++namespace gridex {++// Editable table model wrapping a QueryResult. Rows are materialized up-front+// (bounded by adapter fetchRows limit). Cell text comes from RowValue::displayString.+//+// Pending changes:+// pendingEdits_ — {row, col} → new RowValue for modified cells+// insertedRows_ — new rows appended via addEmptyRow(); row index = result_.rows.size() + i+// deletedRows_ — set of row indices (original rows) marked for deletion+class QueryResultModel : public QAbstractTableModel {+ Q_OBJECT++public:+ explicit QueryResultModel(QObject* parent = nullptr) : QAbstractTableModel(parent) {}++ void setResult(QueryResult result) {+ beginResetModel();+ result_ = std::move(result);+ pendingEdits_.clear();+ insertedRows_.clear();+ deletedRows_.clear();+ endResetModel();+ }++ void clear() {+ beginResetModel();+ result_ = {};+ pendingEdits_.clear();+ insertedRows_.clear();+ deletedRows_.clear();+ endResetModel();+ }++ [[nodiscard]] const QueryResult& result() const noexcept { return result_; }++ // ---- Pending changes interface ----+ [[nodiscard]] bool hasPendingChanges() const noexcept {+ return !pendingEdits_.empty() || !insertedRows_.empty() || !deletedRows_.empty();+ }++ using CellKey = std::pair<int, int>;+ [[nodiscard]] const std::map<CellKey, RowValue>& pendingEdits() const noexcept { return pendingEdits_; }+ [[nodiscard]] const std::vector<std::vector<RowValue>>& insertedRows() const noexcept { return insertedRows_; }+ [[nodiscard]] const std::set<int>& deletedRows() const noexcept { return deletedRows_; }++ void clearPendingChanges() {+ pendingEdits_.clear();+ insertedRows_.clear();+ deletedRows_.clear();+ // Repaint entire view+ if (rowCount() > 0 && columnCount() > 0) {+ emit dataChanged(index(0, 0), index(rowCount() - 1, columnCount() - 1));+ }+ }++ // Returns the effective RowValue for a cell (pending edit or original).+ [[nodiscard]] RowValue effectiveCellValue(int row, int col) const;++ // Adds an empty row (all NULLs) at the bottom of the model.+ void addEmptyRow();++ // Marks a row as pending deletion.+ void markRowDeleted(int row);+ [[nodiscard]] bool isRowDeleted(int row) const noexcept { return deletedRows_.count(row) > 0; }++ // Returns true if row is an inserted (not yet committed) row.+ [[nodiscard]] bool isInsertedRow(int row) const noexcept {+ return row >= static_cast<int>(result_.rows.size());+ }++ // ---- QAbstractTableModel overrides ----+ int rowCount(const QModelIndex& parent = {}) const override {+ if (parent.isValid()) return 0;+ return static_cast<int>(result_.rows.size()) + static_cast<int>(insertedRows_.size());+ }++ int columnCount(const QModelIndex& parent = {}) const override {+ if (parent.isValid()) return 0;+ return static_cast<int>(result_.columns.size());+ }++ Qt::ItemFlags flags(const QModelIndex& index) const override;+ QVariant data(const QModelIndex& index, int role) const override;+ bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole) override;+ QVariant headerData(int section, Qt::Orientation orientation, int role) const override;+ void sort(int column, Qt::SortOrder order = Qt::AscendingOrder) override;++signals:+ void pendingChangesChanged();++private:+ QueryResult result_;+ std::map<CellKey, RowValue> pendingEdits_;+ std::vector<std::vector<RowValue>> insertedRows_;+ std::set<int> deletedRows_;+};++}diff --git a/linux/src/Presentation/Views/DatabaseSwitcher/DatabaseSwitcherDialog.cpp b/linux/src/Presentation/Views/DatabaseSwitcher/DatabaseSwitcherDialog.cppnew file mode 100644index 0000000..f11482d--- /dev/null+++ b/linux/src/Presentation/Views/DatabaseSwitcher/DatabaseSwitcherDialog.cpp@@ -0,0 +1,180 @@+#include "Presentation/Views/DatabaseSwitcher/DatabaseSwitcherDialog.h"++#include <QDialogButtonBox>+#include <QHBoxLayout>+#include <QInputDialog>+#include <QLabel>+#include <QLineEdit>+#include <QListWidget>+#include <QMessageBox>+#include <QPushButton>+#include <QVBoxLayout>++#include "Core/Errors/GridexError.h"+#include "Core/Protocols/Database/IDatabaseAdapter.h"++namespace gridex {++DatabaseSwitcherDialog::DatabaseSwitcherDialog(IDatabaseAdapter* adapter,+ const QString& currentDatabase,+ QWidget* parent)+ : QDialog(parent)+ , adapter_(adapter)+ , currentDatabase_(currentDatabase)+{+ buildUi();+ populate();+}++void DatabaseSwitcherDialog::buildUi() {+ setWindowTitle(tr("Open Database"));+ setMinimumWidth(360);++ auto* root = new QVBoxLayout(this);+ root->setSpacing(8);+ root->setContentsMargins(16, 16, 16, 12);++ // Title+ auto* title = new QLabel(tr("Open database"), this);+ title->setAlignment(Qt::AlignCenter);+ root->addWidget(title);++ // Search field+ searchEdit_ = new QLineEdit(this);+ searchEdit_->setPlaceholderText(tr("Search for database..."));+ searchEdit_->setClearButtonEnabled(true);+ connect(searchEdit_, &QLineEdit::textChanged,+ this, &DatabaseSwitcherDialog::onSearchChanged);+ root->addWidget(searchEdit_);++ // Database list+ listWidget_ = new QListWidget(this);+ listWidget_->setFrameShape(QFrame::NoFrame);+ listWidget_->setMinimumHeight(200);+ connect(listWidget_, &QListWidget::itemDoubleClicked,+ this, &DatabaseSwitcherDialog::onItemDoubleClicked);+ connect(listWidget_, &QListWidget::currentItemChanged, this,+ [this](QListWidgetItem* item) {+ openBtn_->setEnabled(item != nullptr);+ });+ root->addWidget(listWidget_);++ // Horizontal divider+ auto* div = new QFrame(this);+ div->setFrameShape(QFrame::HLine);+ root->addWidget(div);++ // Buttons row+ auto* btnRow = new QWidget(this);+ auto* btnH = new QHBoxLayout(btnRow);+ btnH->setContentsMargins(0, 0, 0, 0);++ auto* cancelBtn = new QPushButton(tr("Cancel"), btnRow);+ connect(cancelBtn, &QPushButton::clicked, this, &QDialog::reject);++ auto* newBtn = new QPushButton(tr("+ New..."), btnRow);+ newBtn->setToolTip(tr("Create a new database on this server"));+ connect(newBtn, &QPushButton::clicked, this, &DatabaseSwitcherDialog::onCreateClicked);++ openBtn_ = new QPushButton(tr("Open"), btnRow);+ openBtn_->setObjectName(QStringLiteral("primaryButton"));+ openBtn_->setEnabled(false);+ openBtn_->setDefault(true);+ connect(openBtn_, &QPushButton::clicked,+ this, &DatabaseSwitcherDialog::onAccepted);++ btnH->addWidget(cancelBtn);+ btnH->addStretch();+ btnH->addWidget(newBtn);+ btnH->addWidget(openBtn_);+ root->addWidget(btnRow);+}++void DatabaseSwitcherDialog::onCreateClicked() {+ if (!adapter_) return;++ bool ok = false;+ const QString name = QInputDialog::getText(+ this, tr("New Database"),+ tr("Name for the new database:"),+ QLineEdit::Normal, QString{}, &ok).trimmed();+ if (!ok || name.isEmpty()) return;++ try {+ adapter_->createDatabase(name.toStdString());+ } catch (const GridexError& e) {+ QMessageBox::critical(this, tr("Create Database Failed"),+ QString::fromUtf8(e.what()));+ return;+ } catch (const std::exception& e) {+ QMessageBox::critical(this, tr("Create Database Failed"),+ QString::fromUtf8(e.what()));+ return;+ }++ // Refresh the list and select the new entry.+ populate();+ const auto matches = listWidget_->findItems(name, Qt::MatchExactly);+ if (!matches.isEmpty()) {+ listWidget_->setCurrentItem(matches.first());+ }+ QMessageBox::information(this, tr("New Database"),+ tr("Database \"%1\" created. Select it and press Open to switch.").arg(name));+}++void DatabaseSwitcherDialog::populate() {+ if (!adapter_) return;++ listWidget_->clear();+ try {+ const auto databases = adapter_->listDatabases();+ for (const auto& db : databases) {+ const QString name = QString::fromUtf8(db.c_str());+ auto* item = new QListWidgetItem(name, listWidget_);+ if (name == currentDatabase_) {+ item->setForeground(Qt::blue);+ // Pre-select current database+ listWidget_->setCurrentItem(item);+ }+ }+ } catch (const GridexError&) {+ auto* item = new QListWidgetItem(tr("(failed to list databases)"), listWidget_);+ item->setFlags(item->flags() & ~Qt::ItemIsEnabled);+ }++ if (listWidget_->currentItem()) {+ openBtn_->setEnabled(true);+ }+}++void DatabaseSwitcherDialog::onSearchChanged(const QString& text) {+ const auto lower = text.trimmed().toLower();+ for (int i = 0; i < listWidget_->count(); ++i) {+ auto* item = listWidget_->item(i);+ item->setHidden(!lower.isEmpty() && !item->text().toLower().contains(lower));+ }+ // Select first visible item when filtering+ if (!lower.isEmpty()) {+ for (int i = 0; i < listWidget_->count(); ++i) {+ auto* item = listWidget_->item(i);+ if (!item->isHidden()) {+ listWidget_->setCurrentItem(item);+ break;+ }+ }+ }+}++void DatabaseSwitcherDialog::onAccepted() {+ auto* item = listWidget_->currentItem();+ if (!item || item->isHidden()) return;+ const QString name = item->text();+ emit databaseSelected(name);+ accept();+}++void DatabaseSwitcherDialog::onItemDoubleClicked() {+ onAccepted();+}++} // namespace gridexdiff --git a/linux/src/Presentation/Views/DatabaseSwitcher/DatabaseSwitcherDialog.h b/linux/src/Presentation/Views/DatabaseSwitcher/DatabaseSwitcherDialog.hnew file mode 100644index 0000000..a1af147--- /dev/null+++ b/linux/src/Presentation/Views/DatabaseSwitcher/DatabaseSwitcherDialog.h@@ -0,0 +1,45 @@+#pragma once++#include <QDialog>++class QLineEdit;+class QListWidget;+class QPushButton;++namespace gridex {++class IDatabaseAdapter;++// Dialog to list and switch databases on the current connection.+// Mirrors macOS DatabaseSwitcherDialog.+// Emits databaseSelected(dbName) when the user confirms a choice.+class DatabaseSwitcherDialog : public QDialog {+ Q_OBJECT++public:+ explicit DatabaseSwitcherDialog(IDatabaseAdapter* adapter,+ const QString& currentDatabase,+ QWidget* parent = nullptr);++signals:+ void databaseSelected(const QString& dbName);++private slots:+ void onSearchChanged(const QString& text);+ void onAccepted();+ void onItemDoubleClicked();+ void onCreateClicked();++private:+ void buildUi();+ void populate();++ IDatabaseAdapter* adapter_;+ QString currentDatabase_;++ QLineEdit* searchEdit_ = nullptr;+ QListWidget* listWidget_ = nullptr;+ QPushButton* openBtn_ = nullptr;+};++} // namespace gridexdiff --git a/linux/src/Presentation/Views/Details/DetailsPanel.cpp b/linux/src/Presentation/Views/Details/DetailsPanel.cppnew file mode 100644index 0000000..c54a9ce--- /dev/null+++ b/linux/src/Presentation/Views/Details/DetailsPanel.cpp@@ -0,0 +1,188 @@+#include "Presentation/Views/Details/DetailsPanel.h"++#include <QFrame>+#include <QHBoxLayout>+#include <QLabel>+#include <QLineEdit>+#include <QPushButton>+#include <QScrollArea>+#include <QStackedWidget>+#include <QVBoxLayout>++#include "Presentation/Views/AIChat/AIChatView.h"++namespace gridex {++DetailsPanel::DetailsPanel(SecretStore* secretStore, WorkspaceState* state, QWidget* parent)+ : QWidget(parent) {+ buildUi();+ chatView_ = new AIChatView(secretStore, state, stack_);+ stack_->addWidget(chatView_);+}++void DetailsPanel::buildUi() {+ auto* root = new QVBoxLayout(this);+ root->setContentsMargins(0, 0, 0, 0);+ root->setSpacing(0);++ // ---- Tab bar: [Details | Assistant] ----+ auto* tabBar = new QWidget(this);+ auto* tabH = new QHBoxLayout(tabBar);+ tabH->setContentsMargins(0, 0, 0, 0);+ tabH->setSpacing(0);++ auto makeTab = [this, tabBar](const QString& title, int index) {+ auto* btn = new QPushButton(title, tabBar);+ btn->setFlat(true);+ btn->setCheckable(true);+ btn->setAutoExclusive(true);+ btn->setProperty("tab", true); // styled by style.qss+ btn->setCursor(Qt::PointingHandCursor);+ btn->setMinimumHeight(32);+ connect(btn, &QPushButton::clicked, this, [this, index] { onTabClicked(index); });+ return btn;+ };++ detailsTabBtn_ = makeTab(tr("Details"), 0);+ assistantTabBtn_ = makeTab(tr("Assistant"), 1);+ tabH->addWidget(detailsTabBtn_, 1);+ tabH->addWidget(assistantTabBtn_, 1);+ root->addWidget(tabBar);++ auto* tabDiv = new QFrame(this);+ tabDiv->setFrameShape(QFrame::HLine);+ root->addWidget(tabDiv);++ // ---- Stacked content ----+ stack_ = new QStackedWidget(this);++ // Page 0: Details (row field list)+ detailsPage_ = new QWidget(stack_);+ auto* dv = new QVBoxLayout(detailsPage_);+ dv->setContentsMargins(0, 0, 0, 0);+ dv->setSpacing(0);++ // Search+ auto* searchRow = new QWidget(detailsPage_);+ auto* sh = new QHBoxLayout(searchRow);+ sh->setContentsMargins(8, 6, 8, 6);+ searchEdit_ = new QLineEdit(searchRow);+ searchEdit_->setPlaceholderText(tr("Search for field..."));+ searchEdit_->setClearButtonEnabled(true);+ connect(searchEdit_, &QLineEdit::textChanged, this, &DetailsPanel::onSearchChanged);+ sh->addWidget(searchEdit_);+ dv->addWidget(searchRow);++ auto* searchDiv = new QFrame(detailsPage_);+ searchDiv->setFrameShape(QFrame::HLine);+ dv->addWidget(searchDiv);++ // Scroll area for field rows+ scrollArea_ = new QScrollArea(detailsPage_);+ scrollArea_->setWidgetResizable(true);+ scrollArea_->setFrameShape(QFrame::NoFrame);+ fieldsHost_ = new QWidget(scrollArea_);+ fieldsLayout_ = new QVBoxLayout(fieldsHost_);+ fieldsLayout_->setContentsMargins(0, 0, 0, 0);+ fieldsLayout_->setSpacing(0);+ fieldsLayout_->addStretch();+ scrollArea_->setWidget(fieldsHost_);+ dv->addWidget(scrollArea_, 1);++ // Empty state+ emptyLabel_ = new QLabel(tr("No row selected"), detailsPage_);+ emptyLabel_->setAlignment(Qt::AlignCenter);+ dv->addWidget(emptyLabel_, 1);+ scrollArea_->setVisible(false);++ stack_->addWidget(detailsPage_);+ // Page 1 (AIChatView) added in constructor after buildUi().++ root->addWidget(stack_, 1);++ // Initial tab state+ onTabClicked(0);+}++void DetailsPanel::onTabClicked(int index) {+ activeTab_ = index;+ stack_->setCurrentIndex(index);++ // Checked state is styled globally by style.qss (QPushButton:checked).+ detailsTabBtn_->setChecked(index == 0);+ assistantTabBtn_->setChecked(index == 1);+}++void DetailsPanel::setSelectedRow(const std::vector<FieldEntry>& fields) {+ currentFields_ = fields;+ emptyLabel_->setVisible(false);+ scrollArea_->setVisible(true);+ rebuildDetailsList();+}++void DetailsPanel::clearSelectedRow() {+ currentFields_.clear();+ emptyLabel_->setVisible(true);+ scrollArea_->setVisible(false);+ // Clear existing field widgets.+ while (fieldsLayout_->count() > 1) { // keep stretch at end+ auto* item = fieldsLayout_->takeAt(0);+ if (item->widget()) item->widget()->deleteLater();+ delete item;+ }+}++void DetailsPanel::onSearchChanged(const QString&) {+ rebuildDetailsList();+}++void DetailsPanel::rebuildDetailsList() {+ // Clear existing (keep the trailing stretch).+ while (fieldsLayout_->count() > 1) {+ auto* item = fieldsLayout_->takeAt(0);+ if (item->widget()) item->widget()->deleteLater();+ delete item;+ }++ const auto filter = searchEdit_->text().trimmed().toLower();++ for (std::size_t fi = 0; fi < currentFields_.size(); ++fi) {+ const auto& f = currentFields_[fi];+ const auto col = QString::fromUtf8(f.column.c_str());+ const auto val = QString::fromUtf8(f.value.c_str());++ if (!filter.isEmpty() &&+ !col.toLower().contains(filter) &&+ !val.toLower().contains(filter)) {+ continue;+ }++ auto* row = new QWidget(fieldsHost_);+ auto* rv = new QVBoxLayout(row);+ rv->setContentsMargins(10, 6, 10, 6);+ rv->setSpacing(2);++ auto* colLabel = new QLabel(col, row);+ rv->addWidget(colLabel);++ // Editable field — QLineEdit replaces QLabel.+ auto* valEdit = new QLineEdit(val, row);+ const int colIdx = static_cast<int>(fi);+ connect(valEdit, &QLineEdit::editingFinished, this,+ [this, valEdit, colIdx, val] {+ const auto newVal = valEdit->text();+ if (newVal != val) {+ emit fieldEdited(colIdx, newVal);+ }+ });+ rv->addWidget(valEdit);++ fieldsLayout_->insertWidget(fieldsLayout_->count() - 1, row);++ auto* div = new QFrame(fieldsHost_);+ div->setFrameShape(QFrame::HLine);+ fieldsLayout_->insertWidget(fieldsLayout_->count() - 1, div);+ }+}++}diff --git a/linux/src/Presentation/Views/Details/DetailsPanel.h b/linux/src/Presentation/Views/Details/DetailsPanel.hnew file mode 100644index 0000000..419386a--- /dev/null+++ b/linux/src/Presentation/Views/Details/DetailsPanel.h@@ -0,0 +1,77 @@+#pragma once++#include <QPushButton>+#include <QStackedWidget>+#include <QWidget>+#include <string>+#include <vector>++class QLabel;+class QLineEdit;+class QScrollArea;+class QVBoxLayout;++namespace gridex {++class AIChatView;+class SecretStore;+class WorkspaceState;++// Right sidebar panel matching macOS DetailsPanel:+// [Details | Assistant] tab bar+// Details tab: search + selected row field list (column: value pairs)+// Assistant tab: AIChatView+class DetailsPanel : public QWidget {+ Q_OBJECT++public:+ explicit DetailsPanel(SecretStore* secretStore,+ WorkspaceState* state,+ QWidget* parent = nullptr);++ struct FieldEntry {+ std::string column;+ std::string value;+ };++public slots:+ void setSelectedRow(const std::vector<FieldEntry>& fields);+ void clearSelectedRow();++signals:+ // Emitted when user edits a field value in the Details tab.+ // columnIndex is the position in the current fields array.+ void fieldEdited(int columnIndex, const QString& newValue);++private slots:+ void onTabClicked(int index);+ void onSearchChanged(const QString& text);++private:+ void buildUi();+ void rebuildDetailsList();++ int activeTab_ = 0;++ // Tab bar+ QPushButton* detailsTabBtn_ = nullptr;+ QPushButton* assistantTabBtn_ = nullptr;++ // Stacked content+ QStackedWidget* stack_ = nullptr;++ // Details tab+ QWidget* detailsPage_ = nullptr;+ QLineEdit* searchEdit_ = nullptr;+ QScrollArea* scrollArea_ = nullptr;+ QWidget* fieldsHost_ = nullptr;+ QVBoxLayout* fieldsLayout_ = nullptr;+ QLabel* emptyLabel_ = nullptr;++ // Assistant tab+ AIChatView* chatView_ = nullptr;++ std::vector<FieldEntry> currentFields_;+};++}diff --git a/linux/src/Presentation/Views/ERDiagram/ERDiagramExporter.cpp b/linux/src/Presentation/Views/ERDiagram/ERDiagramExporter.cppnew file mode 100644index 0000000..c2400e0--- /dev/null+++ b/linux/src/Presentation/Views/ERDiagram/ERDiagramExporter.cpp@@ -0,0 +1,252 @@+#include "Presentation/Views/ERDiagram/ERDiagramExporter.h"++#include <QFile>+#include <QFileDialog>+#include <QGraphicsScene>+#include <QMessageBox>+#include <QPainter>+#include <QPdfWriter>+#include <QStandardPaths>+#include <QSvgGenerator>+#include <QTextStream>++namespace gridex {++namespace {++QString toUpperName(const std::string& name) {+ return QString::fromStdString(name).toUpper();+}++}++void ERDiagramExporter::exportAsSvg(QGraphicsScene* scene, QWidget* parent) {+ if (!scene || scene->items().isEmpty()) {+ QMessageBox::information(parent, QObject::tr("Export ER Diagram"),+ QObject::tr("No diagram to export."));+ return;+ }++ const QString defaultDir =+ QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);+ const QString path = QFileDialog::getSaveFileName(+ parent, QObject::tr("Export ER Diagram as SVG"),+ defaultDir + QStringLiteral("/er-diagram.svg"),+ QObject::tr("SVG Image (*.svg)"));+ if (path.isEmpty()) return;++ const QString outPath = path.endsWith(QStringLiteral(".svg"), Qt::CaseInsensitive)+ ? path : path + QStringLiteral(".svg");++ const QRectF source = scene->itemsBoundingRect().adjusted(-40, -40, 40, 40);++ QSvgGenerator generator;+ generator.setFileName(outPath);+ generator.setSize(source.size().toSize());+ generator.setViewBox(source);+ generator.setTitle(QStringLiteral("ER Diagram"));++ QPainter painter;+ if (!painter.begin(&generator)) {+ QMessageBox::warning(parent, QObject::tr("Export ER Diagram"),+ QObject::tr("Failed to write SVG to:\n%1").arg(outPath));+ return;+ }+ painter.setRenderHint(QPainter::Antialiasing);+ scene->render(&painter, QRectF(), source);+ painter.end();+}++void ERDiagramExporter::exportAsPdf(QGraphicsScene* scene, QWidget* parent) {+ if (!scene || scene->items().isEmpty()) {+ QMessageBox::information(parent, QObject::tr("Export ER Diagram"),+ QObject::tr("No diagram to export."));+ return;+ }++ const QString defaultDir =+ QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);+ const QString path = QFileDialog::getSaveFileName(+ parent, QObject::tr("Export ER Diagram as PDF"),+ defaultDir + QStringLiteral("/er-diagram.pdf"),+ QObject::tr("PDF Document (*.pdf)"));+ if (path.isEmpty()) return;++ const QString outPath = path.endsWith(QStringLiteral(".pdf"), Qt::CaseInsensitive)+ ? path : path + QStringLiteral(".pdf");++ const QRectF source = scene->itemsBoundingRect().adjusted(-40, -40, 40, 40);++ QPdfWriter writer(outPath);+ writer.setPageSize(QPageSize(source.size(), QPageSize::Point));+ writer.setPageMargins(QMarginsF(0, 0, 0, 0));++ QPainter painter;+ if (!painter.begin(&writer)) {+ QMessageBox::warning(parent, QObject::tr("Export ER Diagram"),+ QObject::tr("Failed to write PDF to:\n%1").arg(outPath));+ return;+ }+ painter.setRenderHint(QPainter::Antialiasing);+ scene->render(&painter, QRectF(), source);+ painter.end();+}++void ERDiagramExporter::exportAsDbml(const std::vector<TableDescription>& tables,+ QWidget* parent) {+ if (tables.empty()) {+ QMessageBox::information(parent, QObject::tr("Export ER Diagram"),+ QObject::tr("No schema to export."));+ return;+ }++ const QString defaultDir =+ QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);+ const QString path = QFileDialog::getSaveFileName(+ parent, QObject::tr("Export Schema as DBML"),+ defaultDir + QStringLiteral("/schema.dbml"),+ QObject::tr("DBML File (*.dbml)"));+ if (path.isEmpty()) return;++ const QString outPath = path.endsWith(QStringLiteral(".dbml"), Qt::CaseInsensitive)+ ? path : path + QStringLiteral(".dbml");++ QFile file(outPath);+ if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {+ QMessageBox::warning(parent, QObject::tr("Export ER Diagram"),+ QObject::tr("Failed to write DBML to:\n%1").arg(outPath));+ return;+ }+ QTextStream out(&file);+ out << dbmlFor(tables);+}++void ERDiagramExporter::exportAsMermaid(const std::vector<TableDescription>& tables,+ QWidget* parent) {+ if (tables.empty()) {+ QMessageBox::information(parent, QObject::tr("Export ER Diagram"),+ QObject::tr("No schema to export."));+ return;+ }++ const QString defaultDir =+ QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);+ const QString path = QFileDialog::getSaveFileName(+ parent, QObject::tr("Export Schema as Mermaid"),+ defaultDir + QStringLiteral("/er-diagram.md"),+ QObject::tr("Markdown File (*.md)"));+ if (path.isEmpty()) return;++ const QString outPath = path.endsWith(QStringLiteral(".md"), Qt::CaseInsensitive)+ ? path : path + QStringLiteral(".md");++ QFile file(outPath);+ if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {+ QMessageBox::warning(parent, QObject::tr("Export ER Diagram"),+ QObject::tr("Failed to write Mermaid to:\n%1").arg(outPath));+ return;+ }+ QTextStream out(&file);+ out << mermaidFor(tables);+}++QString ERDiagramExporter::dbmlType(const std::string& sqlType) {+ const QString t = QString::fromStdString(sqlType).toLower();+ if (t.startsWith(QStringLiteral("character varying")) ||+ t.startsWith(QStringLiteral("varchar"))) return QStringLiteral("varchar");+ if (t.startsWith(QStringLiteral("timestamp"))) return QStringLiteral("timestamp");+ if (t == QStringLiteral("integer") ||+ t == QStringLiteral("int4") ||+ t == QStringLiteral("int")) return QStringLiteral("int");+ if (t == QStringLiteral("bigint") ||+ t == QStringLiteral("int8")) return QStringLiteral("bigint");+ if (t == QStringLiteral("smallint") ||+ t == QStringLiteral("int2")) return QStringLiteral("smallint");+ if (t == QStringLiteral("boolean") ||+ t == QStringLiteral("bool")) return QStringLiteral("boolean");+ if (t == QStringLiteral("text")) return QStringLiteral("text");+ if (t == QStringLiteral("uuid")) return QStringLiteral("uuid");+ if (t.startsWith(QStringLiteral("numeric")) ||+ t.startsWith(QStringLiteral("decimal"))) return QStringLiteral("decimal");+ if (t.startsWith(QStringLiteral("double")) ||+ t == QStringLiteral("float8")) return QStringLiteral("float");+ if (t == QStringLiteral("real") ||+ t == QStringLiteral("float4")) return QStringLiteral("float");+ if (t == QStringLiteral("jsonb") ||+ t == QStringLiteral("json")) return QStringLiteral("json");+ if (t == QStringLiteral("date")) return QStringLiteral("date");+ if (t == QStringLiteral("time") ||+ t.startsWith(QStringLiteral("time "))) return QStringLiteral("time");+ return QString::fromStdString(sqlType).left(32);+}++QString ERDiagramExporter::dbmlFor(const std::vector<TableDescription>& tables) {+ QString out;+ QTextStream s(&out);++ for (const auto& td : tables) {+ s << "Table " << QString::fromStdString(td.name) << " {\n";+ for (const auto& col : td.columns) {+ s << " " << QString::fromStdString(col.name)+ << " " << dbmlType(col.dataType);+ QStringList notes;+ if (col.isPrimaryKey) notes << QStringLiteral("pk");+ if (!col.isNullable) notes << QStringLiteral("not null");+ if (col.isAutoIncrement) notes << QStringLiteral("increment");+ if (!notes.isEmpty())+ s << " [" << notes.join(QStringLiteral(", ")) << "]";+ s << "\n";+ }+ s << "}\n\n";+ }++ for (const auto& td : tables) {+ for (const auto& fk : td.foreignKeys) {+ if (fk.columns.empty() || fk.referencedColumns.empty()) continue;+ s << "Ref: "+ << QString::fromStdString(td.name) << "."+ << QString::fromStdString(fk.columns[0])+ << " > "+ << QString::fromStdString(fk.referencedTable) << "."+ << QString::fromStdString(fk.referencedColumns[0])+ << "\n";+ }+ }++ return out;+}++QString ERDiagramExporter::mermaidFor(const std::vector<TableDescription>& tables) {+ QString out;+ QTextStream s(&out);++ s << "erDiagram\n";++ for (const auto& td : tables) {+ for (const auto& fk : td.foreignKeys) {+ s << " " << toUpperName(td.name)+ << " ||--o{ "+ << toUpperName(fk.referencedTable)+ << " : \"\"\n";+ }+ }++ s << "\n";++ for (const auto& td : tables) {+ s << " " << toUpperName(td.name) << " {\n";+ for (const auto& col : td.columns) {+ const QString typePart = dbmlType(col.dataType).replace(+ QStringLiteral(" "), QStringLiteral("_"));+ s << " " << typePart+ << " " << QString::fromStdString(col.name);+ if (col.isPrimaryKey) s << " PK";+ s << "\n";+ }+ s << " }\n";+ }++ return out;+}++} // namespace gridexdiff --git a/linux/src/Presentation/Views/ERDiagram/ERDiagramExporter.h b/linux/src/Presentation/Views/ERDiagram/ERDiagramExporter.hnew file mode 100644index 0000000..6393405--- /dev/null+++ b/linux/src/Presentation/Views/ERDiagram/ERDiagramExporter.h@@ -0,0 +1,26 @@+#pragma once++#include <QString>+#include <vector>++#include "Core/Models/Schema/SchemaSnapshot.h"++class QGraphicsScene;+class QWidget;++namespace gridex {++class ERDiagramExporter {+public:+ static void exportAsSvg(QGraphicsScene* scene, QWidget* parent);+ static void exportAsPdf(QGraphicsScene* scene, QWidget* parent);+ static void exportAsDbml(const std::vector<TableDescription>& tables, QWidget* parent);+ static void exportAsMermaid(const std::vector<TableDescription>& tables, QWidget* parent);++private:+ static QString dbmlFor(const std::vector<TableDescription>& tables);+ static QString mermaidFor(const std::vector<TableDescription>& tables);+ static QString dbmlType(const std::string& sqlType);+};++}diff --git a/linux/src/Presentation/Views/ERDiagram/ERDiagramView.cpp b/linux/src/Presentation/Views/ERDiagram/ERDiagramView.cppnew file mode 100644index 0000000..1e73242--- /dev/null+++ b/linux/src/Presentation/Views/ERDiagram/ERDiagramView.cpp@@ -0,0 +1,519 @@+#include "Presentation/Views/ERDiagram/ERDiagramView.h"+#include "Presentation/Views/ERDiagram/ERDiagramExporter.h"++#include <cmath>++#include <QAction>+#include <QFileDialog>+#include <QFont>+#include <QGraphicsEllipseItem>+#include <QGraphicsLineItem>+#include <QGraphicsPathItem>+#include <QGraphicsRectItem>+#include <QGraphicsScene>+#include <QGraphicsTextItem>+#include <QImage>+#include <QMenu>+#include <QMessageBox>+#include <QPainter>+#include <QPainterPath>+#include <QPushButton>+#include <QResizeEvent>+#include <QStandardPaths>+#include <QStyleOptionGraphicsItem>+#include <QVBoxLayout>+#include <QWheelEvent>++#include "Core/Errors/GridexError.h"+#include "Core/Models/Schema/SchemaSnapshot.h"+#include "Core/Protocols/Database/IDatabaseAdapter.h"++namespace gridex {++namespace {++// Card geometry constants (matches macOS ERDiagramCanvas proportions)+constexpr qreal kCardWidth = 220.0;+constexpr qreal kHeaderHeight = 32.0;+constexpr qreal kRowHeight = 22.0;+constexpr qreal kCornerRadius = 8.0;+constexpr qreal kGridCols = 4.0; // columns in grid layout+constexpr qreal kHGap = 80.0;+constexpr qreal kVGap = 60.0;+constexpr qreal kPadding = 60.0;++inline qreal cardHeight(int columnCount) {+ return kHeaderHeight + columnCount * kRowHeight + 4.0;+}++// Abbreviate SQL type to short display form.+QString abbreviateType(const std::string& type) {+ const QString t = QString::fromStdString(type).toLower();+ if (t.startsWith(QStringLiteral("character varying")) ||+ t.startsWith(QStringLiteral("varchar"))) {+ const int p1 = t.indexOf(QLatin1Char('('));+ const int p2 = t.indexOf(QLatin1Char(')'));+ if (p1 != -1 && p2 > p1)+ return QStringLiteral("varchar") + t.mid(p1, p2 - p1 + 1);+ return QStringLiteral("varchar");+ }+ if (t.startsWith(QStringLiteral("timestamp"))) return QStringLiteral("timestamp");+ if (t.startsWith(QStringLiteral("double"))) return QStringLiteral("double");+ if (t == QStringLiteral("integer")) return QStringLiteral("int");+ if (t == QStringLiteral("boolean")) return QStringLiteral("bool");+ if (t == QStringLiteral("bigint")) return QStringLiteral("bigint");+ if (t == QStringLiteral("smallint")) return QStringLiteral("smallint");+ if (t == QStringLiteral("text")) return QStringLiteral("text");+ if (t == QStringLiteral("uuid")) return QStringLiteral("uuid");+ if (t == QStringLiteral("jsonb")) return QStringLiteral("jsonb");+ if (t == QStringLiteral("json")) return QStringLiteral("json");+ return QString::fromStdString(type).left(14);+}++// Build a table card QGraphicsItem group (returns the root rect item).+// The item is added to the scene inside this function; position is (0,0) —+// caller translates via QGraphicsItem::setPos.+QGraphicsRectItem* buildTableCard(QGraphicsScene* scene,+ const TableDescription& td) {+ const int cols = static_cast<int>(td.columns.size());+ const qreal cw = kCardWidth;+ const qreal ch = cardHeight(cols);++ // --- outer card rect (movable) ---+ auto* card = new QGraphicsRectItem(0, 0, cw, ch);+ card->setFlag(QGraphicsItem::ItemIsMovable, true);+ card->setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);+ card->setZValue(1.0);++ QPen borderPen(QColor(0x55, 0x55, 0x55, 180));+ borderPen.setWidthF(1.0);+ card->setPen(borderPen);+ card->setBrush(QBrush(QColor(0x2a, 0x2a, 0x2a)));++ // Drop shadow via a slightly-offset duplicate behind the card.+ auto* shadow = new QGraphicsRectItem(2, 3, cw, ch, card);+ shadow->setPen(Qt::NoPen);+ shadow->setBrush(QColor(0, 0, 0, 60));+ shadow->setZValue(-0.1);++ // --- header background ---+ auto* header = new QGraphicsRectItem(0, 0, cw, kHeaderHeight, card);+ header->setPen(Qt::NoPen);+ header->setBrush(QColor(0x1a, 0x6a, 0xc8, 50)); // accent blue tint++ // Header separator line+ auto* hSep = new QGraphicsLineItem(0, kHeaderHeight, cw, kHeaderHeight, card);+ hSep->setPen(QPen(QColor(0x55, 0x55, 0x55, 120), 0.5));++ // --- table name ---+ auto* nameItem = new QGraphicsTextItem(card);+ nameItem->setPos(10, 6);+ QFont nameFont;+ nameFont.setPointSize(9);+ nameFont.setBold(true);+ nameItem->setFont(nameFont);+ nameItem->setDefaultTextColor(QColor(0xec, 0xec, 0xec));+ nameItem->setPlainText(QString::fromStdString(td.name));+ nameItem->setTextWidth(cw - 20);++ // Column count badge (top-right of header)+ const QString countText = QString::number(cols);+ auto* countItem = new QGraphicsTextItem(card);+ QFont countFont;+ countFont.setPointSize(7);+ countItem->setFont(countFont);+ countItem->setDefaultTextColor(QColor(0x88, 0x88, 0x88));+ countItem->setPlainText(countText);+ const qreal cw2 = countItem->boundingRect().width();+ countItem->setPos(cw - cw2 - 8, 9);++ // --- column rows ---+ for (int i = 0; i < cols; ++i) {+ const auto& col = td.columns[static_cast<std::size_t>(i)];+ const qreal rowY = kHeaderHeight + 2 + i * kRowHeight;++ // Alternating row background+ if (i % 2 == 1) {+ auto* rowBg = new QGraphicsRectItem(0, rowY, cw, kRowHeight, card);+ rowBg->setPen(Qt::NoPen);+ rowBg->setBrush(QColor(0xff, 0xff, 0xff, 6));+ }++ // PK / FK badge+ if (col.isPrimaryKey) {+ auto* badge = new QGraphicsTextItem(card);+ QFont bf; bf.setPointSize(7); bf.setBold(true);+ badge->setFont(bf);+ badge->setDefaultTextColor(QColor(0xd4, 0xa0, 0x17)); // gold+ badge->setPlainText(QStringLiteral("PK"));+ badge->setPos(8, rowY + 3);+ } else {+ // Check if this column is a FK column+ bool isFk = false;+ for (const auto& fk : td.foreignKeys) {+ for (const auto& fcol : fk.columns) {+ if (fcol == col.name) { isFk = true; break; }+ }+ if (isFk) break;+ }+ if (isFk) {+ auto* badge = new QGraphicsTextItem(card);+ QFont bf; bf.setPointSize(7); bf.setBold(true);+ badge->setFont(bf);+ badge->setDefaultTextColor(QColor(0x5b, 0x9b, 0xd5)); // blue+ badge->setPlainText(QStringLiteral("FK"));+ badge->setPos(8, rowY + 3);+ }+ }++ // Column name+ auto* colName = new QGraphicsTextItem(card);+ QFont cf; cf.setPointSize(9);+ if (col.isPrimaryKey) cf.setBold(true);+ colName->setFont(cf);+ colName->setDefaultTextColor(QColor(0xd8, 0xd8, 0xd8));+ colName->setPlainText(QString::fromStdString(col.name));+ colName->setTextWidth(kCardWidth - 70);+ colName->setPos(28, rowY + 2);++ // Data type (right-aligned)+ auto* typeItem = new QGraphicsTextItem(card);+ QFont tf; tf.setPointSize(8); tf.setFamily(QStringLiteral("monospace"));+ typeItem->setFont(tf);+ typeItem->setDefaultTextColor(QColor(0x77, 0x99, 0x77));+ const QString shortType = abbreviateType(col.dataType);+ typeItem->setPlainText(shortType);+ const qreal tw = typeItem->boundingRect().width();+ typeItem->setPos(cw - tw - 6, rowY + 3);+ }++ scene->addItem(card);+ return card;+}++// Dynamic FK edge that recalculates its path every paint based on current+// positions of the source and target card items. Follows nodes when dragged.+class FKEdgeItem : public QGraphicsItem {+public:+ FKEdgeItem(QGraphicsRectItem* srcCard, int srcRowIdx,+ QGraphicsRectItem* tgtCard, int tgtRowIdx)+ : srcCard_(srcCard), tgtCard_(tgtCard),+ srcRowIdx_(srcRowIdx), tgtRowIdx_(tgtRowIdx) {+ setZValue(0.0);+ }++ QRectF boundingRect() const override {+ const auto s = srcPoint();+ const auto t = tgtPoint();+ return QRectF(std::min(s.x(), t.x()) - 20,+ std::min(s.y(), t.y()) - 20,+ std::abs(t.x() - s.x()) + 40,+ std::abs(t.y() - s.y()) + 40);+ }++ void paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*) override {+ const auto src = srcPoint();+ const auto tgt = tgtPoint();+ const qreal midX = (src.x() + tgt.x()) / 2.0;++ QPainterPath path;+ path.moveTo(src);+ path.cubicTo(QPointF(midX, src.y()), QPointF(midX, tgt.y()), tgt);++ QPen p(QColor(0x5b, 0x9b, 0xd5, 160));+ p.setWidthF(1.5);+ painter->setPen(p);+ painter->setBrush(Qt::NoBrush);+ painter->drawPath(path);++ // Arrowhead+ const double angle = std::atan2(tgt.y() - src.y(), tgt.x() - src.x());+ const double aLen = 8.0, aAng = M_PI / 6.0;+ QPolygonF arrow;+ arrow << tgt+ << QPointF(tgt.x() - aLen * std::cos(angle - aAng),+ tgt.y() - aLen * std::sin(angle - aAng))+ << QPointF(tgt.x() - aLen * std::cos(angle + aAng),+ tgt.y() - aLen * std::sin(angle + aAng));+ painter->setPen(Qt::NoPen);+ painter->setBrush(QColor(0x5b, 0x9b, 0xd5, 160));+ painter->drawPolygon(arrow);+ }++private:+ QPointF srcPoint() const {+ const auto pos = srcCard_->pos();+ const bool leftOfTarget = pos.x() < tgtCard_->pos().x();+ const qreal y = pos.y() + kHeaderHeight + (srcRowIdx_ + 0.5) * kRowHeight;+ return QPointF(leftOfTarget ? pos.x() + kCardWidth : pos.x(), y);+ }+ QPointF tgtPoint() const {+ const auto pos = tgtCard_->pos();+ const bool leftOfSource = pos.x() < srcCard_->pos().x();+ const qreal y = pos.y() + kHeaderHeight + (tgtRowIdx_ + 0.5) * kRowHeight;+ return QPointF(leftOfSource ? pos.x() + kCardWidth : pos.x(), y);+ }++ QGraphicsRectItem* srcCard_;+ QGraphicsRectItem* tgtCard_;+ int srcRowIdx_;+ int tgtRowIdx_;+};++} // namespace++// ---------------------------------------------------------------------------++ERDiagramView::ERDiagramView(QWidget* parent)+ : QGraphicsView(parent) {+ scene_ = new QGraphicsScene(this);+ setScene(scene_);++ setRenderHint(QPainter::Antialiasing);+ // Update the scene whenever items move so FKEdgeItem repaints.+ setViewportUpdateMode(QGraphicsView::FullViewportUpdate);+ setDragMode(QGraphicsView::ScrollHandDrag);+ setTransformationAnchor(QGraphicsView::AnchorUnderMouse);+ setResizeAnchor(QGraphicsView::AnchorUnderMouse);+ setBackgroundBrush(QColor(0x18, 0x18, 0x18));+ setFrameShape(QFrame::NoFrame);++ // Hide the dropdown arrow only — colors come from the global style.qss.+ const QString hideMenuArrow =+ QStringLiteral("QPushButton::menu-indicator { image: none; width: 0; }");++ // Fit-all button (top-right corner)+ fitBtn_ = new QPushButton(QStringLiteral("⤢ Fit"), this);+ fitBtn_->setFixedSize(60, 26);+ fitBtn_->setToolTip(tr("Fit all tables in view"));+ connect(fitBtn_, &QPushButton::clicked, this, &ERDiagramView::fitAll);+ fitBtn_->raise();++ // Export button with dropdown menu (placed left of Fit).+ exportMenu_ = new QMenu(this);+ auto* exportPngAct = exportMenu_->addAction(tr("Export as PNG..."));+ connect(exportPngAct, &QAction::triggered, this, &ERDiagramView::exportAsPng);+ auto* exportSvgAct = exportMenu_->addAction(tr("Export as SVG..."));+ connect(exportSvgAct, &QAction::triggered, this, &ERDiagramView::exportAsSvg);+ auto* exportPdfAct = exportMenu_->addAction(tr("Export as PDF..."));+ connect(exportPdfAct, &QAction::triggered, this, &ERDiagramView::exportAsPdf);+ exportMenu_->addSeparator();+ auto* exportDbmlAct = exportMenu_->addAction(tr("Export as DBML..."));+ connect(exportDbmlAct, &QAction::triggered, this, &ERDiagramView::exportAsDbml);+ auto* exportMermaidAct = exportMenu_->addAction(tr("Export as Mermaid (.md)..."));+ connect(exportMermaidAct, &QAction::triggered, this, &ERDiagramView::exportAsMermaid);++ exportBtn_ = new QPushButton(QStringLiteral("⇩ Export ▾"), this);+ exportBtn_->setFixedSize(84, 26);+ exportBtn_->setToolTip(tr("Export ER diagram"));+ exportBtn_->setStyleSheet(hideMenuArrow);+ exportBtn_->setMenu(exportMenu_);+ exportBtn_->raise();++ // Initial placement. resizeEvent repositions on every resize.+ fitBtn_->move(width() - fitBtn_->width() - 12, 8);+ exportBtn_->move(width() - fitBtn_->width() - exportBtn_->width() - 20, 8);+}++void ERDiagramView::resizeEvent(QResizeEvent* event) {+ QGraphicsView::resizeEvent(event);+ fitBtn_->move(width() - fitBtn_->width() - 12, 8);+ exportBtn_->move(width() - fitBtn_->width() - exportBtn_->width() - 20, 8);+}++void ERDiagramView::wheelEvent(QWheelEvent* event) {+ const qreal factor = (event->angleDelta().y() > 0) ? 1.15 : (1.0 / 1.15);+ scale(factor, factor);+ event->accept();+}++void ERDiagramView::fitAll() {+ if (scene_->items().isEmpty()) return;+ fitInView(scene_->itemsBoundingRect().adjusted(-40, -40, 40, 40),+ Qt::KeepAspectRatio);+}++void ERDiagramView::clear() {+ scene_->clear();+ nodePositions_.clear();+ nodeColumnCounts_.clear();+ tables_.clear();+}++void ERDiagramView::exportAsPng() {+ if (scene_->items().isEmpty()) {+ QMessageBox::information(this, tr("Export ER Diagram"),+ tr("No diagram to export."));+ return;+ }++ const QString defaultDir =+ QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);+ const QString defaultPath = defaultDir + QStringLiteral("/er-diagram.png");++ const QString path = QFileDialog::getSaveFileName(+ this, tr("Export ER Diagram as PNG"), defaultPath,+ tr("PNG Image (*.png)"));+ if (path.isEmpty()) return;++ // Render full scene bounding rect (not viewport) so offscreen tables+ // are included. 2x scale keeps text sharp on high-DPI displays.+ const QRectF source = scene_->itemsBoundingRect().adjusted(-40, -40, 40, 40);+ constexpr qreal scaleFactor = 2.0;+ const QSize imageSize(+ static_cast<int>(std::ceil(source.width() * scaleFactor)),+ static_cast<int>(std::ceil(source.height() * scaleFactor)));++ QImage image(imageSize, QImage::Format_ARGB32_Premultiplied);+ image.fill(backgroundBrush().color());++ QPainter painter(&image);+ painter.setRenderHint(QPainter::Antialiasing);+ painter.setRenderHint(QPainter::TextAntialiasing);+ painter.setRenderHint(QPainter::SmoothPixmapTransform);+ scene_->render(&painter, QRectF(QPointF(0, 0), imageSize), source);+ painter.end();++ const QString outPath = path.endsWith(QStringLiteral(".png"), Qt::CaseInsensitive)+ ? path+ : path + QStringLiteral(".png");++ if (!image.save(outPath, "PNG")) {+ QMessageBox::warning(this, tr("Export ER Diagram"),+ tr("Failed to write PNG to:\n%1").arg(outPath));+ }+}++void ERDiagramView::exportAsSvg() {+ ERDiagramExporter::exportAsSvg(scene_, this);+}++void ERDiagramView::exportAsPdf() {+ ERDiagramExporter::exportAsPdf(scene_, this);+}++void ERDiagramView::exportAsDbml() {+ ERDiagramExporter::exportAsDbml(tables_, this);+}++void ERDiagramView::exportAsMermaid() {+ ERDiagramExporter::exportAsMermaid(tables_, this);+}++void ERDiagramView::loadSchema(IDatabaseAdapter* adapter,+ const std::optional<std::string>& schema) {+ clear();+ if (!adapter) return;++ std::vector<TableDescription> tables;+ try {+ const auto tableInfos = adapter->listTables(schema);+ for (const auto& info : tableInfos) {+ if (info.type != TableKind::Table) continue;+ try {+ tables.push_back(adapter->describeTable(info.name, schema));+ } catch (...) {+ // Skip tables that fail to describe+ }+ }+ } catch (const GridexError&) {+ return;+ }++ buildScene(tables);+}++void ERDiagramView::buildScene(const std::vector<TableDescription>& tables) {+ if (tables.empty()) return;+ tables_ = tables;++ // Build layout nodes+ std::vector<TableNode> nodes;+ nodes.reserve(tables.size());+ for (const auto& td : tables) {+ TableNode n;+ n.name = td.name;+ n.columns = td.columns;+ nodes.push_back(std::move(n));+ }+ layoutGrid(nodes);++ // Place table cards in scene and record card pointers.+ std::unordered_map<std::string, QGraphicsRectItem*> cardMap;+ for (std::size_t i = 0; i < tables.size(); ++i) {+ const auto& td = tables[i];+ const auto& node = nodes[i];++ auto* card = buildTableCard(scene_, td);+ card->setPos(node.x, node.y);+ // ItemSendsGeometryChanges already set in buildTableCard.+ // Trigger scene update when card moves so edges repaint.+ card->setFlag(QGraphicsItem::ItemSendsScenePositionChanges, true);++ cardMap[td.name] = card;+ nodePositions_[td.name] = QPointF(node.x, node.y);+ nodeColumnCounts_[td.name] = static_cast<int>(td.columns.size());+ }++ // Draw FK edges as dynamic FKEdgeItem (follows nodes on drag).+ for (const auto& td : tables) {+ auto srcCardIt = cardMap.find(td.name);+ if (srcCardIt == cardMap.end()) continue;++ for (const auto& fk : td.foreignKeys) {+ auto tgtCardIt = cardMap.find(fk.referencedTable);+ if (tgtCardIt == cardMap.end()) continue;++ // Find FK column row index in source table.+ int srcRowIdx = 0;+ for (std::size_t c = 0; c < td.columns.size(); ++c) {+ if (!fk.columns.empty() && td.columns[c].name == fk.columns[0]) {+ srcRowIdx = static_cast<int>(c);+ break;+ }+ }++ auto* edge = new FKEdgeItem(srcCardIt->second, srcRowIdx,+ tgtCardIt->second, /*tgtRowIdx*/ 0);+ scene_->addItem(edge);+ }+ }++ fitAll();+}++void ERDiagramView::layoutGrid(std::vector<TableNode>& nodes) {+ const int cols = static_cast<int>(kGridCols);+ for (std::size_t i = 0; i < nodes.size(); ++i) {+ const int row = static_cast<int>(i) / cols;+ const int col = static_cast<int>(i) % cols;++ // Compute max height of this row to stack cleanly+ qreal rowH = 0;+ const int rowStart = row * cols;+ const int rowEnd = std::min(rowStart + cols, static_cast<int>(nodes.size()));+ for (int j = rowStart; j < rowEnd; ++j) {+ rowH = std::max(rowH,+ cardHeight(static_cast<int>(nodes[static_cast<std::size_t>(j)].columns.size())));+ }++ // X: sum of all card widths + gaps up to this column+ nodes[i].x = kPadding + col * (kCardWidth + kHGap);++ // Y: sum of max-heights of previous rows + gaps+ qreal y = kPadding;+ for (int r = 0; r < row; ++r) {+ const int rs = r * cols;+ const int re = std::min(rs + cols, static_cast<int>(nodes.size()));+ qreal maxH = 0;+ for (int j = rs; j < re; ++j) {+ maxH = std::max(maxH,+ cardHeight(static_cast<int>(nodes[static_cast<std::size_t>(j)].columns.size())));+ }+ y += maxH + kVGap;+ }+ nodes[i].y = y;+ }+}++} // namespace gridexdiff --git a/linux/src/Presentation/Views/ERDiagram/ERDiagramView.h b/linux/src/Presentation/Views/ERDiagram/ERDiagramView.hnew file mode 100644index 0000000..a624f9a--- /dev/null+++ b/linux/src/Presentation/Views/ERDiagram/ERDiagramView.h@@ -0,0 +1,68 @@+#pragma once++#include <QGraphicsView>+#include <optional>+#include <string>+#include <unordered_map>+#include <vector>++#include "Core/Models/Schema/SchemaSnapshot.h"++class QGraphicsScene;+class QMenu;+class QPushButton;+class QResizeEvent;+class QWheelEvent;++namespace gridex {++class IDatabaseAdapter;++// ER Diagram viewer using QGraphicsView + QGraphicsScene.+// Table cards are draggable nodes; FK edges drawn as bezier arrows.+class ERDiagramView : public QGraphicsView {+ Q_OBJECT++public:+ explicit ERDiagramView(QWidget* parent = nullptr);++ // Loads schema: calls listTables + describeTable, builds nodes + edges.+ void loadSchema(IDatabaseAdapter* adapter,+ const std::optional<std::string>& schema);++ void clear();++protected:+ void wheelEvent(QWheelEvent* event) override;+ void resizeEvent(QResizeEvent* event) override;++private slots:+ void fitAll();+ void exportAsPng();+ void exportAsSvg();+ void exportAsPdf();+ void exportAsDbml();+ void exportAsMermaid();++private:+ struct TableNode {+ std::string name;+ std::vector<ColumnInfo> columns;+ qreal x = 0;+ qreal y = 0;+ };++ void buildScene(const std::vector<TableDescription>& tables);+ void layoutGrid(std::vector<TableNode>& nodes);++ QGraphicsScene* scene_ = nullptr;+ QPushButton* fitBtn_ = nullptr;+ QPushButton* exportBtn_ = nullptr;+ QMenu* exportMenu_ = nullptr;++ std::unordered_map<std::string, QPointF> nodePositions_;+ std::unordered_map<std::string, int> nodeColumnCounts_;+ std::vector<TableDescription> tables_;+};++}diff --git a/linux/src/Presentation/Views/FilterBar/FilterBarView.cpp b/linux/src/Presentation/Views/FilterBar/FilterBarView.cppnew file mode 100644index 0000000..bee6837--- /dev/null+++ b/linux/src/Presentation/Views/FilterBar/FilterBarView.cpp@@ -0,0 +1,136 @@+#include "Presentation/Views/FilterBar/FilterBarView.h"++#include <QComboBox>+#include <QHBoxLayout>+#include <QLineEdit>+#include <QPushButton>++#include "Core/Models/Database/RowValue.h"++namespace gridex {++namespace {++// Ordered operator labels and matching FilterOperator values.+struct OpEntry { const char* label; FilterOperator op; };+constexpr OpEntry kOps[] = {+ { "=", FilterOperator::Equal },+ { "!=", FilterOperator::NotEqual },+ { ">", FilterOperator::GreaterThan },+ { "<", FilterOperator::LessThan },+ { ">=", FilterOperator::GreaterOrEqual },+ { "<=", FilterOperator::LessOrEqual },+ { "LIKE", FilterOperator::Like },+ { "IS NULL", FilterOperator::IsNull },+ { "IS NOT NULL", FilterOperator::IsNotNull },+};+constexpr int kOpsCount = static_cast<int>(sizeof(kOps) / sizeof(kOps[0]));++// Operators that don't need a value input.+bool needsValue(FilterOperator op) {+ return op != FilterOperator::IsNull && op != FilterOperator::IsNotNull;+}++}++FilterBarView::FilterBarView(QWidget* parent) : QWidget(parent) {+ buildUi();+}++void FilterBarView::buildUi() {+ setProperty("compact", true); // shrinks descendant buttons/inputs+ auto* h = new QHBoxLayout(this);+ h->setContentsMargins(10, 4, 10, 4);+ h->setSpacing(6);++ columnCombo_ = new QComboBox(this);+ columnCombo_->setMinimumWidth(130);+ columnCombo_->setSizeAdjustPolicy(QComboBox::AdjustToContents);+ columnCombo_->addItem(tr("Any column"));+ h->addWidget(columnCombo_);++ operatorCombo_ = new QComboBox(this);+ operatorCombo_->setFixedWidth(110);+ for (int i = 0; i < kOpsCount; ++i) {+ operatorCombo_->addItem(QString::fromUtf8(kOps[i].label));+ }+ connect(operatorCombo_, QOverload<int>::of(&QComboBox::currentIndexChanged),+ this, &FilterBarView::onOperatorChanged);+ h->addWidget(operatorCombo_);++ valueEdit_ = new QLineEdit(this);+ valueEdit_->setPlaceholderText(tr("value"));+ valueEdit_->setMinimumWidth(160);+ connect(valueEdit_, &QLineEdit::returnPressed, this, &FilterBarView::onApply);+ h->addWidget(valueEdit_, 1);++ applyBtn_ = new QPushButton(tr("Apply"), this);+ applyBtn_->setCursor(Qt::PointingHandCursor);+ connect(applyBtn_, &QPushButton::clicked, this, &FilterBarView::onApply);+ h->addWidget(applyBtn_);++ clearBtn_ = new QPushButton(tr("Clear"), this);+ clearBtn_->setCursor(Qt::PointingHandCursor);+ connect(clearBtn_, &QPushButton::clicked, this, &FilterBarView::onClear);+ h->addWidget(clearBtn_);+}++void FilterBarView::setColumns(const std::vector<std::string>& columns) {+ const QString current = columnCombo_->currentText();+ columnCombo_->clear();+ columnCombo_->addItem(tr("Any column"));+ for (const auto& c : columns) {+ columnCombo_->addItem(QString::fromUtf8(c.c_str()));+ }+ // Restore previous selection if still present.+ const int idx = columnCombo_->findText(current);+ if (idx >= 0) columnCombo_->setCurrentIndex(idx);+}++void FilterBarView::reset() {+ columnCombo_->setCurrentIndex(0);+ operatorCombo_->setCurrentIndex(0);+ valueEdit_->clear();+ valueEdit_->setEnabled(true);+}++void FilterBarView::onOperatorChanged(int index) {+ if (index < 0 || index >= kOpsCount) return;+ const bool needs = needsValue(kOps[index].op);+ valueEdit_->setEnabled(needs);+ if (!needs) valueEdit_->clear();+}++void FilterBarView::onApply() {+ const int opIdx = operatorCombo_->currentIndex();+ if (opIdx < 0 || opIdx >= kOpsCount) return;++ const FilterOperator op = kOps[opIdx].op;+ const QString colText = columnCombo_->currentIndex() <= 0+ ? QString{}+ : columnCombo_->currentText();++ // Build expression: if no column chosen we emit filterCleared instead.+ if (colText.isEmpty()) {+ emit filterCleared();+ return;+ }++ FilterCondition cond;+ cond.column = colText.toStdString();+ cond.op = op;+ if (needsValue(op)) {+ cond.value = RowValue::makeString(valueEdit_->text().toStdString());+ }++ FilterExpression expr;+ expr.conditions.push_back(std::move(cond));+ emit filterApplied(expr);+}++void FilterBarView::onClear() {+ reset();+ emit filterCleared();+}++}diff --git a/linux/src/Presentation/Views/FilterBar/FilterBarView.h b/linux/src/Presentation/Views/FilterBar/FilterBarView.hnew file mode 100644index 0000000..c3a5ab7--- /dev/null+++ b/linux/src/Presentation/Views/FilterBar/FilterBarView.h@@ -0,0 +1,50 @@+#pragma once++#include <QWidget>+#include <vector>+#include <string>++#include "Core/Models/Query/FilterExpression.h"++class QComboBox;+class QLineEdit;+class QPushButton;++namespace gridex {++// Filter bar matching macOS layout:+// [Any column ▾] [= ▾] [value input] [Apply] [Clear]+// Emits filterApplied(FilterExpression) or filterCleared().+// Column list is updated via setColumns() when a table loads.+class FilterBarView : public QWidget {+ Q_OBJECT++public:+ explicit FilterBarView(QWidget* parent = nullptr);++ // Populate column combo from query result headers.+ void setColumns(const std::vector<std::string>& columns);++ // Reset inputs to defaults.+ void reset();++signals:+ void filterApplied(const gridex::FilterExpression& expr);+ void filterCleared();++private slots:+ void onApply();+ void onClear();+ void onOperatorChanged(int index);++private:+ void buildUi();++ QComboBox* columnCombo_ = nullptr;+ QComboBox* operatorCombo_ = nullptr;+ QLineEdit* valueEdit_ = nullptr;+ QPushButton* applyBtn_ = nullptr;+ QPushButton* clearBtn_ = nullptr;+};++}diff --git a/linux/src/Presentation/Views/FunctionDetail/FunctionDetailView.cpp b/linux/src/Presentation/Views/FunctionDetail/FunctionDetailView.cppnew file mode 100644index 0000000..b6bc579--- /dev/null+++ b/linux/src/Presentation/Views/FunctionDetail/FunctionDetailView.cpp@@ -0,0 +1,120 @@+#include "Presentation/Views/FunctionDetail/FunctionDetailView.h"++#include <QApplication>+#include <QClipboard>+#include <QFont>+#include <QFrame>+#include <QHBoxLayout>+#include <QLabel>+#include <QMessageBox>+#include <QPlainTextEdit>+#include <QPushButton>+#include <QVBoxLayout>++#include "Core/Protocols/Database/IDatabaseAdapter.h"+#include "Core/Errors/GridexError.h"+#include "Presentation/Views/QueryEditor/SqlHighlighter.h"++namespace gridex {++FunctionDetailView::FunctionDetailView(IDatabaseAdapter* adapter,+ const QString& schema,+ const QString& name,+ bool isProcedure,+ QWidget* parent)+ : QWidget(parent)+ , adapter_(adapter)+ , schema_(schema)+ , name_(name)+ , isProcedure_(isProcedure)+{+ buildUi();+ loadSource();+}++void FunctionDetailView::buildUi() {+ auto* root = new QVBoxLayout(this);+ root->setContentsMargins(0, 0, 0, 0);+ root->setSpacing(0);++ // Header bar+ auto* headerBar = new QWidget(this);+ auto* hh = new QHBoxLayout(headerBar);+ hh->setContentsMargins(12, 6, 12, 6);+ hh->setSpacing(8);++ headerLabel_ = new QLabel(name_, headerBar);+ QFont hf = headerLabel_->font();+ hf.setWeight(QFont::Medium);+ headerLabel_->setFont(hf);++ badgeLabel_ = new QLabel(isProcedure_ ? tr("Procedure") : tr("Function"), headerBar);+ badgeLabel_->setObjectName(isProcedure_+ ? QStringLiteral("procedureBadge")+ : QStringLiteral("functionBadge"));+ badgeLabel_->setContentsMargins(6, 2, 6, 2);++ copyBtn_ = new QPushButton(tr("Copy"), headerBar);+ copyBtn_->setCursor(Qt::PointingHandCursor);+ connect(copyBtn_, &QPushButton::clicked, this, &FunctionDetailView::onCopy);++ refreshBtn_ = new QPushButton(tr("Refresh"), headerBar);+ refreshBtn_->setCursor(Qt::PointingHandCursor);+ connect(refreshBtn_, &QPushButton::clicked, this, &FunctionDetailView::onRefresh);++ hh->addWidget(headerLabel_);+ hh->addWidget(badgeLabel_);+ hh->addStretch();+ hh->addWidget(copyBtn_);+ hh->addWidget(refreshBtn_);+ root->addWidget(headerBar);++ auto* div = new QFrame(this);+ div->setFrameShape(QFrame::HLine);+ root->addWidget(div);++ // Source editor (readonly)+ editor_ = new QPlainTextEdit(this);+ editor_->setReadOnly(true);+ QFont mono = QFontDatabase::systemFont(QFontDatabase::FixedFont);+ mono.setPointSize(12);+ editor_->setFont(mono);+ editor_->setFrameShape(QFrame::NoFrame);+ editor_->setLineWrapMode(QPlainTextEdit::NoWrap);++ new SqlHighlighter(editor_->document());++ root->addWidget(editor_, 1);+}++void FunctionDetailView::loadSource() {+ if (!adapter_) return;++ const std::optional<std::string> schemaOpt =+ schema_.isEmpty() ? std::nullopt+ : std::make_optional(schema_.toStdString());+ try {+ std::string src;+ if (isProcedure_) {+ src = adapter_->getProcedureSource(name_.toStdString(), schemaOpt);+ } else {+ src = adapter_->getFunctionSource(name_.toStdString(), schemaOpt);+ }+ editor_->setPlainText(QString::fromUtf8(src.c_str()));+ } catch (const GridexError& e) {+ editor_->setPlainText(tr("-- Error loading source: %1")+ .arg(QString::fromUtf8(e.what())));+ } catch (const std::exception& e) {+ editor_->setPlainText(tr("-- Error: %1").arg(QString::fromUtf8(e.what())));+ }+}++void FunctionDetailView::onCopy() {+ QApplication::clipboard()->setText(editor_->toPlainText());+}++void FunctionDetailView::onRefresh() {+ loadSource();+}++}diff --git a/linux/src/Presentation/Views/FunctionDetail/FunctionDetailView.h b/linux/src/Presentation/Views/FunctionDetail/FunctionDetailView.hnew file mode 100644index 0000000..88fb6b1--- /dev/null+++ b/linux/src/Presentation/Views/FunctionDetail/FunctionDetailView.h@@ -0,0 +1,44 @@+#pragma once++#include <QWidget>+#include <QString>++class QLabel;+class QPlainTextEdit;+class QPushButton;++namespace gridex {++class IDatabaseAdapter;++class FunctionDetailView : public QWidget {+ Q_OBJECT++public:+ explicit FunctionDetailView(IDatabaseAdapter* adapter,+ const QString& schema,+ const QString& name,+ bool isProcedure,+ QWidget* parent = nullptr);++private slots:+ void onCopy();+ void onRefresh();++private:+ void buildUi();+ void loadSource();++ IDatabaseAdapter* adapter_ = nullptr;+ QString schema_;+ QString name_;+ bool isProcedure_ = false;++ QLabel* headerLabel_ = nullptr;+ QLabel* badgeLabel_ = nullptr;+ QPlainTextEdit* editor_ = nullptr;+ QPushButton* copyBtn_ = nullptr;+ QPushButton* refreshBtn_ = nullptr;+};++}diff --git a/linux/src/Presentation/Views/Home/HomeBrandingPanel.cpp b/linux/src/Presentation/Views/Home/HomeBrandingPanel.cppnew file mode 100644index 0000000..bdb8559--- /dev/null+++ b/linux/src/Presentation/Views/Home/HomeBrandingPanel.cpp@@ -0,0 +1,106 @@+#include "Presentation/Views/Home/HomeBrandingPanel.h"++#include <QFrame>+#include <QHBoxLayout>+#include <QLabel>+#include <QPainter>+#include <QPainterPath>+#include <QPixmap>+#include <QPushButton>+#include <QVBoxLayout>++namespace gridex {++namespace {++// One bottom-panel action row: icon (emoji fallback) + title. Match macOS HomeActionButton.+QPushButton* makeActionButton(const QString& emoji, const QString& title, QWidget* parent) {+ auto* btn = new QPushButton(parent);+ btn->setCursor(Qt::PointingHandCursor);+ btn->setFlat(true);+ btn->setMinimumHeight(32);+ btn->setText(QStringLiteral(" %1 %2").arg(emoji, title));+ return btn;+}++}++HomeBrandingPanel::HomeBrandingPanel(QWidget* parent) : QWidget(parent) {+ buildUi();+}++void HomeBrandingPanel::buildUi() {+ setFixedWidth(260);+ setAutoFillBackground(true);++ auto* root = new QVBoxLayout(this);+ root->setContentsMargins(0, 0, 0, 28);+ root->setSpacing(0);++ root->addStretch();++ // Logo + title block (centered)+ auto* titleStack = new QVBoxLayout();+ titleStack->setAlignment(Qt::AlignHCenter);+ titleStack->setSpacing(16);++ auto* logo = new QLabel(this);+ QPixmap src(QStringLiteral(":/logo.png"));+ if (src.isNull()) {+ logo->setText(QStringLiteral("G"));+ logo->setAlignment(Qt::AlignCenter);+ logo->setFixedSize(100, 100);+ logo->setStyleSheet("background-color: #378add; color: white; "+ "border-radius: 20px; font-size: 48px; font-weight: 700;");+ } else {+ logo->setFixedSize(100, 100);+ logo->setPixmap(src.scaled(100, 100, Qt::KeepAspectRatio, Qt::SmoothTransformation));+ logo->setAlignment(Qt::AlignCenter);+ }+ auto* logoHolder = new QHBoxLayout();+ logoHolder->addStretch();+ logoHolder->addWidget(logo);+ logoHolder->addStretch();+ titleStack->addLayout(logoHolder);++ auto* titleBlock = new QVBoxLayout();+ titleBlock->setSpacing(4);+ titleBlock->setAlignment(Qt::AlignHCenter);+ auto* title = new QLabel(QStringLiteral("Gridex"), this);+ title->setAlignment(Qt::AlignHCenter);+ titleBlock->addWidget(title);+ auto* sub = new QLabel(tr("AI-Native Database IDE"), this);+ sub->setAlignment(Qt::AlignHCenter);+ titleBlock->addWidget(sub);+ titleStack->addLayout(titleBlock);++ root->addLayout(titleStack);+ root->addStretch();++ // Bottom actions block+ auto* actions = new QVBoxLayout();+ actions->setContentsMargins(20, 0, 20, 0);+ actions->setSpacing(2);++ auto* backup = makeActionButton(QStringLiteral("⬆"), tr("Backup database…"), this);+ auto* restore = makeActionButton(QStringLiteral("⬇"), tr("Restore database…"), this);+ connect(backup, &QPushButton::clicked, this, &HomeBrandingPanel::backupRequested);+ connect(restore, &QPushButton::clicked, this, &HomeBrandingPanel::restoreRequested);+ actions->addWidget(backup);+ actions->addWidget(restore);++ auto* div = new QFrame(this);+ div->setFrameShape(QFrame::HLine);+ actions->addWidget(div);++ auto* newConn = makeActionButton(QStringLiteral("⊕"), tr("New Connection"), this);+ auto* newGroup = makeActionButton(QStringLiteral("🗀⁺"), tr("New Group"), this);+ connect(newConn, &QPushButton::clicked, this, &HomeBrandingPanel::newConnectionRequested);+ connect(newGroup, &QPushButton::clicked, this, &HomeBrandingPanel::newGroupRequested);+ actions->addWidget(newConn);+ actions->addWidget(newGroup);++ root->addLayout(actions);+}++}diff --git a/linux/src/Presentation/Views/Home/HomeBrandingPanel.h b/linux/src/Presentation/Views/Home/HomeBrandingPanel.hnew file mode 100644index 0000000..6630a78--- /dev/null+++ b/linux/src/Presentation/Views/Home/HomeBrandingPanel.h@@ -0,0 +1,27 @@+#pragma once++#include <QWidget>++namespace gridex {++// Left panel of the HomeView. Matches macOS brandingPanel 260px:+// [centered logo + title]+// Spacer+// Bottom action list: Backup, Restore, divider, New Connection, New Group+class HomeBrandingPanel : public QWidget {+ Q_OBJECT++public:+ explicit HomeBrandingPanel(QWidget* parent = nullptr);++signals:+ void newConnectionRequested();+ void newGroupRequested();+ void backupRequested();+ void restoreRequested();++private:+ void buildUi();+};++}diff --git a/linux/src/Presentation/Views/ImportSQL/SqlImportWizard.cpp b/linux/src/Presentation/Views/ImportSQL/SqlImportWizard.cppnew file mode 100644index 0000000..aa09664--- /dev/null+++ b/linux/src/Presentation/Views/ImportSQL/SqlImportWizard.cpp@@ -0,0 +1,334 @@+#include "Presentation/Views/ImportSQL/SqlImportWizard.h"++#include <QCheckBox>+#include <QFileDialog>+#include <QFile>+#include <QHBoxLayout>+#include <QLabel>+#include <QListWidget>+#include <QListWidgetItem>+#include <QPlainTextEdit>+#include <QProgressBar>+#include <QPushButton>+#include <QStandardPaths>+#include <QTextBlock>+#include <QVBoxLayout>+#include <QtConcurrent/QtConcurrent>+#include <QFutureWatcher>++#include "Core/Protocols/Database/IDatabaseAdapter.h"+#include "Core/Utils/SqlStatementSplitter.h"++namespace gridex {++namespace {++// Build a line-number map: for each statement index, store the 1-based line+// where it begins in the original source.+std::vector<int> buildLineMap(const std::string& src,+ const std::vector<std::string>& stmts) {+ std::vector<int> lines;+ lines.reserve(stmts.size());+ std::size_t searchFrom = 0;+ int currentLine = 1;+ for (const auto& stmt : stmts) {+ if (stmt.empty()) { lines.push_back(1); continue; }+ const auto pos = src.find(stmt.substr(0, std::min(stmt.size(), std::size_t{40})),+ searchFrom);+ if (pos == std::string::npos) {+ lines.push_back(currentLine);+ } else {+ int line = 1;+ for (std::size_t i = 0; i < pos && i < src.size(); ++i)+ if (src[i] == '\n') ++line;+ lines.push_back(line);+ currentLine = line;+ searchFrom = pos + 1;+ }+ }+ return lines;+}++} // namespace++// ---------------------------------------------------------------------------++SqlImportWizard::SqlImportWizard(IDatabaseAdapter* adapter,+ const QString& filePath,+ QWidget* parent)+ : QDialog(parent), adapter_(adapter), filePath_(filePath)+{+ setWindowTitle(tr("Import SQL Wizard"));+ setMinimumSize(700, 560);+ setAttribute(Qt::WA_DeleteOnClose, false);++ auto* root = new QVBoxLayout(this);+ root->setSpacing(8);+ root->setContentsMargins(12, 12, 12, 12);++ // ---- File row ----+ auto* fileRow = new QHBoxLayout;+ fileLabel_ = new QLabel(tr("(no file selected)"), this);+ fileLabel_->setWordWrap(false);+ fileLabel_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);+ browseBtn_ = new QPushButton(tr("Browse…"), this);+ browseBtn_->setCursor(Qt::PointingHandCursor);+ fileRow->addWidget(fileLabel_, 1);+ fileRow->addWidget(browseBtn_);+ root->addLayout(fileRow);++ // ---- Meta row: dialect + stmt count ----+ auto* metaRow = new QHBoxLayout;+ dialectLabel_ = new QLabel(this);+ stmtCountLabel_ = new QLabel(this);+ dialectLabel_->setStyleSheet(QStringLiteral("color: gray; font-size: 11px;"));+ stmtCountLabel_->setStyleSheet(QStringLiteral("color: gray; font-size: 11px;"));+ metaRow->addWidget(dialectLabel_);+ metaRow->addStretch();+ metaRow->addWidget(stmtCountLabel_);+ root->addLayout(metaRow);++ // ---- Preview ----+ auto* previewLbl = new QLabel(tr("Preview (first 2 000 chars):"), this);+ previewLbl->setStyleSheet(QStringLiteral("font-size: 11px;"));+ root->addWidget(previewLbl);++ previewEdit_ = new QPlainTextEdit(this);+ previewEdit_->setReadOnly(true);+ previewEdit_->setMaximumBlockCount(0);+ previewEdit_->setFont(QFont(QStringLiteral("Monospace"), 10));+ previewEdit_->setMinimumHeight(160);+ root->addWidget(previewEdit_, 2);++ // ---- Options ----+ transactionChk_ = new QCheckBox(tr("Run in transaction (rollback all on failure)"), this);+ transactionChk_->setChecked(true);+ continueErrChk_ = new QCheckBox(tr("Continue on error (collect all errors)"), this);+ continueErrChk_->setChecked(false);+ // The two options are mutually exclusive in a meaningful way, but we allow+ // the user to override: if both checked, continueErr takes precedence.+ root->addWidget(transactionChk_);+ root->addWidget(continueErrChk_);++ // ---- Progress ----+ progressBar_ = new QProgressBar(this);+ progressBar_->setRange(0, 100);+ progressBar_->setValue(0);+ progressBar_->setVisible(false);+ progressLabel_ = new QLabel(this);+ progressLabel_->setStyleSheet(QStringLiteral("font-size: 11px;"));+ progressLabel_->setVisible(false);+ root->addWidget(progressBar_);+ root->addWidget(progressLabel_);++ // ---- Error list ----+ auto* errLbl = new QLabel(tr("Errors (double-click to jump to line):"), this);+ errLbl->setStyleSheet(QStringLiteral("font-size: 11px;"));+ root->addWidget(errLbl);++ errorList_ = new QListWidget(this);+ errorList_->setMaximumHeight(120);+ errorList_->setSelectionMode(QAbstractItemView::SingleSelection);+ root->addWidget(errorList_);++ // ---- Button row ----+ auto* btnRow = new QHBoxLayout;+ btnRow->addStretch();+ closeBtn_ = new QPushButton(tr("Close"), this);+ importBtn_ = new QPushButton(tr("Import"), this);+ importBtn_->setDefault(true);+ importBtn_->setEnabled(false);+ closeBtn_->setCursor(Qt::PointingHandCursor);+ importBtn_->setCursor(Qt::PointingHandCursor);+ btnRow->addWidget(closeBtn_);+ btnRow->addWidget(importBtn_);+ root->addLayout(btnRow);++ connect(browseBtn_, &QPushButton::clicked, this, &SqlImportWizard::onBrowse);+ connect(importBtn_, &QPushButton::clicked, this, &SqlImportWizard::onImport);+ connect(closeBtn_, &QPushButton::clicked, this, &QDialog::accept);+ connect(errorList_, &QListWidget::itemDoubleClicked, this, [this](QListWidgetItem* item) {+ if (!item) return;+ onErrorDoubleClicked(errorList_->row(item));+ });++ if (!filePath_.isEmpty()) loadPreview();+}++SqlImportWizard::~SqlImportWizard() = default;++void SqlImportWizard::onBrowse() {+ const QString path = QFileDialog::getOpenFileName(+ this, tr("Open SQL File"),+ QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation),+ tr("SQL (*.sql);;All files (*)"));+ if (path.isEmpty()) return;+ filePath_ = path;+ loadPreview();+}++void SqlImportWizard::loadPreview() {+ errorList_->clear();+ progressBar_->setValue(0);+ progressBar_->setVisible(false);+ progressLabel_->setVisible(false);++ QFile f(filePath_);+ if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) {+ fileLabel_->setText(tr("Cannot open: %1").arg(filePath_));+ importBtn_->setEnabled(false);+ return;+ }+ const QByteArray raw = f.readAll();+ f.close();++ const std::string buf = raw.toStdString();+ statements_ = splitSqlStatements(buf);+ stmtLines_ = buildLineMap(buf, statements_);++ const QString fname = QFileInfo(filePath_).fileName();+ fileLabel_->setText(QStringLiteral("%1 (%2 bytes)").arg(fname).arg(raw.size()));++ const QString dialect = QString::fromStdString(detectSqlDialectHint(buf));+ dialectLabel_->setText(tr("Dialect hint: %1").arg(dialect));+ stmtCountLabel_->setText(tr("%1 statement(s)").arg(statements_.size()));++ const QString preview = QString::fromUtf8(raw).left(2000);+ previewEdit_->setPlainText(preview);++ importBtn_->setEnabled(!statements_.empty() && adapter_ != nullptr);+}++// ---------------------------------------------------------------------------+// Async import using QtConcurrent + signal/slot queued connection+// ---------------------------------------------------------------------------++void SqlImportWizard::onImport() {+ if (statements_.empty() || !adapter_) return;++ setImporting(true);+ errorList_->clear();+ progressBar_->setRange(0, static_cast<int>(statements_.size()));+ progressBar_->setValue(0);+ progressLabel_->setText(tr("Starting…"));++ const bool useTransaction = transactionChk_->isChecked() && !continueErrChk_->isChecked();+ const bool continueOnErr = continueErrChk_->isChecked();++ // Capture needed data for the worker; avoid capturing Qt widgets.+ auto stmts = statements_;+ auto* adapter = adapter_;++ // We emit progress via a lambda that routes through a queued connection.+ // Use a raw signal on *this* via QMetaObject::invokeMethod so the worker+ // thread can safely update the UI.+ auto* watcher = new QFutureWatcher<void>(this);++ connect(watcher, &QFutureWatcher<void>::finished, this, [this, watcher] {+ watcher->deleteLater();+ onImportFinished();+ });++ QFuture<void> fut = QtConcurrent::run([this, stmts, adapter, useTransaction, continueOnErr] {+ const int total = static_cast<int>(stmts.size());++ if (useTransaction) {+ try { adapter->beginTransaction(); }+ catch (const std::exception& e) {+ QMetaObject::invokeMethod(this, "onStatementDone", Qt::QueuedConnection,+ Q_ARG(int, 0), Q_ARG(int, total),+ Q_ARG(QString, tr("BEGIN failed: %1").arg(e.what())));+ return;+ }+ }++ bool aborted = false;+ for (int i = 0; i < total; ++i) {+ QString err;+ try {+ adapter->executeRaw(stmts[static_cast<std::size_t>(i)]);+ } catch (const std::exception& e) {+ err = QString::fromUtf8(e.what());+ }++ QMetaObject::invokeMethod(this, "onStatementDone", Qt::QueuedConnection,+ Q_ARG(int, i + 1), Q_ARG(int, total), Q_ARG(QString, err));++ if (!err.isEmpty() && !continueOnErr) {+ aborted = true;+ break;+ }+ }++ if (useTransaction) {+ try {+ if (aborted) adapter->rollbackTransaction();+ else adapter->commitTransaction();+ } catch (const std::exception& e) {+ const QString msg = aborted+ ? tr("ROLLBACK failed: %1").arg(e.what())+ : tr("COMMIT failed: %1").arg(e.what());+ QMetaObject::invokeMethod(this, "onStatementDone", Qt::QueuedConnection,+ Q_ARG(int, total), Q_ARG(int, total), Q_ARG(QString, msg));+ }+ }+ });++ watcher->setFuture(fut);+}++void SqlImportWizard::onStatementDone(int index, int total, const QString& error) {+ progressBar_->setValue(index);+ progressLabel_->setText(tr("Statement %1 / %2").arg(index).arg(total));++ if (!error.isEmpty()) {+ const int stmtIdx = index - 1;+ const int line = (stmtIdx >= 0 && stmtIdx < static_cast<int>(stmtLines_.size()))+ ? stmtLines_[static_cast<std::size_t>(stmtIdx)] : 0;+ const QString label = line > 0+ ? QStringLiteral("[line %1] %2").arg(line).arg(error)+ : error;+ auto* item = new QListWidgetItem(label);+ item->setData(Qt::UserRole, line);+ item->setForeground(Qt::red);+ errorList_->addItem(item);+ }+}++void SqlImportWizard::onImportFinished() {+ setImporting(false);+ const int errCount = errorList_->count();+ if (errCount == 0) {+ progressLabel_->setText(tr("Done — all %1 statement(s) executed successfully.")+ .arg(statements_.size()));+ } else {+ progressLabel_->setText(tr("Done — %1 error(s). See list below.")+ .arg(errCount));+ }+}++void SqlImportWizard::onErrorDoubleClicked(int row) {+ auto* item = errorList_->item(row);+ if (!item) return;+ const int line = item->data(Qt::UserRole).toInt();+QTextDocument* doc = previewEdit_->document();+ if (!doc || line <= 0) return;++ QTextBlock block = doc->findBlockByLineNumber(line - 1);+ if (!block.isValid()) block = doc->lastBlock();++ QTextCursor cur(block);+ previewEdit_->setTextCursor(cur);+ previewEdit_->ensureCursorVisible();+}++void SqlImportWizard::setImporting(bool active) {+ importBtn_->setEnabled(!active);+ browseBtn_->setEnabled(!active);+ transactionChk_->setEnabled(!active);+ continueErrChk_->setEnabled(!active);+ progressBar_->setVisible(true);+ progressLabel_->setVisible(true);+}++} // namespace gridexdiff --git a/linux/src/Presentation/Views/ImportSQL/SqlImportWizard.h b/linux/src/Presentation/Views/ImportSQL/SqlImportWizard.hnew file mode 100644index 0000000..7c62cea--- /dev/null+++ b/linux/src/Presentation/Views/ImportSQL/SqlImportWizard.h@@ -0,0 +1,66 @@+#pragma once++#include <memory>+#include <vector>+#include <string>+#include <QDialog>++class QLabel;+class QPlainTextEdit;+class QCheckBox;+class QProgressBar;+class QListWidget;+class QPushButton;++namespace gridex {++class IDatabaseAdapter;++struct ImportError {+ int stmtIndex;+ int approxLine;+ QString message;+};++class SqlImportWizard : public QDialog {+ Q_OBJECT++public:+ explicit SqlImportWizard(IDatabaseAdapter* adapter,+ const QString& filePath,+ QWidget* parent = nullptr);+ ~SqlImportWizard();++private slots:+ void onBrowse();+ void onImport();+ void onStatementDone(int index, int total, const QString& error);+ void onImportFinished();+ void onErrorDoubleClicked(int row);++private:+ void loadPreview();+ void setImporting(bool active);++ IDatabaseAdapter* adapter_;++ // Widgets+ QLabel* fileLabel_ = nullptr;+ QPushButton* browseBtn_ = nullptr;+ QLabel* dialectLabel_ = nullptr;+ QLabel* stmtCountLabel_ = nullptr;+ QPlainTextEdit* previewEdit_ = nullptr;+ QCheckBox* transactionChk_ = nullptr;+ QCheckBox* continueErrChk_ = nullptr;+ QProgressBar* progressBar_ = nullptr;+ QLabel* progressLabel_ = nullptr;+ QListWidget* errorList_ = nullptr;+ QPushButton* importBtn_ = nullptr;+ QPushButton* closeBtn_ = nullptr;++ QString filePath_;+ std::vector<std::string> statements_;+ std::vector<int> stmtLines_; // approx first-line of each stmt+};++} // namespace gridexdiff --git a/linux/src/Presentation/Views/MCP/MCPActivityView.cpp b/linux/src/Presentation/Views/MCP/MCPActivityView.cppnew file mode 100644index 0000000..367333d--- /dev/null+++ b/linux/src/Presentation/Views/MCP/MCPActivityView.cpp@@ -0,0 +1,365 @@+#include "Presentation/Views/MCP/MCPActivityView.h"++#include <QComboBox>+#include <QDateTime>+#include <QFileDialog>+#include <QFormLayout>+#include <QGroupBox>+#include <QHBoxLayout>+#include <QHeaderView>+#include <QLabel>+#include <QLineEdit>+#include <QMenu>+#include <QMessageBox>+#include <QPushButton>+#include <QSplitter>+#include <QTableWidget>+#include <QTextBrowser>+#include <QToolButton>+#include <QVBoxLayout>+#include <fstream>++#include "Presentation/Views/MCP/MCPWindowState.h"+#include "Services/MCP/MCPServer.h"++namespace gridex {++namespace {++QString statusColor(mcp::MCPAuditStatus s) {+ switch (s) {+ case mcp::MCPAuditStatus::Success: return "#639922";+ case mcp::MCPAuditStatus::Error: return "#e04b4a";+ case mcp::MCPAuditStatus::Denied: return "#ef9f27";+ case mcp::MCPAuditStatus::Timeout: return "#d4a017";+ }+ return "#888";+}++QString tierColor(int tier) {+ switch (tier) {+ case 1: return "#378add";+ case 2: return "#639922";+ case 3: return "#ef9f27";+ case 4: return "#e04b4a";+ case 5: return "#534ab7";+ }+ return "#888";+}++QString formatTimeShort(const std::string& iso) {+ auto dt = QDateTime::fromString(QString::fromStdString(iso), Qt::ISODate);+ if (!dt.isValid()) return QString::fromStdString(iso);+ return dt.toLocalTime().toString("HH:mm:ss");+}++QString formatTimeFull(const std::string& iso) {+ auto dt = QDateTime::fromString(QString::fromStdString(iso), Qt::ISODate);+ if (!dt.isValid()) return QString::fromStdString(iso);+ return dt.toLocalTime().toString("yyyy-MM-dd HH:mm:ss");+}++} // namespace++MCPActivityView::MCPActivityView(MCPWindowState* state, QWidget* parent)+ : QWidget(parent), state_(state) {+ buildUi();+ connect(state_, &MCPWindowState::fullActivityChanged, this, &MCPActivityView::refresh);+ state_->reloadFullActivity();+}++void MCPActivityView::buildUi() {+ auto* outer = new QVBoxLayout(this);+ outer->setContentsMargins(24, 16, 24, 16);+ outer->setSpacing(10);++ // Filter bar+ auto* filterBar = new QHBoxLayout();+ filterBar->setSpacing(10);+ search_ = new QLineEdit(this);+ search_->setPlaceholderText(tr("Search tool, SQL, or client"));+ search_->setClearButtonEnabled(true);+ search_->setObjectName(QStringLiteral("mcpSearch")); search_->setMaximumWidth(280);+ connect(search_, &QLineEdit::textChanged, this, &MCPActivityView::onFilterChanged);++ toolFilter_ = new QComboBox(this);+ toolFilter_->setFixedWidth(160);+ toolFilter_->addItem(tr("All Tools"), QString());+ connect(toolFilter_, QOverload<int>::of(&QComboBox::currentIndexChanged),+ this, &MCPActivityView::onFilterChanged);++ statusFilter_ = new QComboBox(this);+ statusFilter_->setFixedWidth(120);+ statusFilter_->addItem(tr("All Status"), QString());+ statusFilter_->addItem(tr("Success"), QStringLiteral("success"));+ statusFilter_->addItem(tr("Error"), QStringLiteral("error"));+ statusFilter_->addItem(tr("Denied"), QStringLiteral("denied"));+ statusFilter_->addItem(tr("Timeout"), QStringLiteral("timeout"));+ connect(statusFilter_, QOverload<int>::of(&QComboBox::currentIndexChanged),+ this, &MCPActivityView::onFilterChanged);++ auto* refreshBtn = new QToolButton(this);+ refreshBtn->setText(QStringLiteral("⟳"));+ refreshBtn->setToolTip(tr("Refresh"));+ connect(refreshBtn, &QToolButton::clicked, this, &MCPActivityView::onRefreshClicked);++ auto* menuBtn = new QToolButton(this);+ menuBtn->setText(QStringLiteral("⋯"));+ menuBtn->setPopupMode(QToolButton::InstantPopup);+ auto* m = new QMenu(menuBtn);+ m->addAction(tr("Export as JSON…"), this, &MCPActivityView::onExportClicked);+ m->addSeparator();+ m->addAction(tr("Clear Log…"), this, &MCPActivityView::onClearClicked);+ menuBtn->setMenu(m);++ filterBar->addWidget(search_);+ filterBar->addWidget(toolFilter_);+ filterBar->addWidget(statusFilter_);+ filterBar->addStretch();+ filterBar->addWidget(refreshBtn);+ filterBar->addWidget(menuBtn);+ outer->addLayout(filterBar);++ // Splitter: table | detail+ auto* splitter = new QSplitter(Qt::Horizontal, this);++ table_ = new QTableWidget(splitter);+ table_->setColumnCount(5);+ table_->setHorizontalHeaderLabels({tr("Time"), tr("Tool"), tr("Client"), tr("Status"), tr("Duration")});+ table_->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Interactive);+ table_->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);+ table_->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Interactive);+ table_->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Interactive);+ table_->horizontalHeader()->setSectionResizeMode(4, QHeaderView::Interactive);+ table_->verticalHeader()->setVisible(false);+ table_->verticalHeader()->setDefaultSectionSize(32);+ table_->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed);+ table_->setAlternatingRowColors(true);+ table_->setSelectionBehavior(QAbstractItemView::SelectRows);+ table_->setSelectionMode(QAbstractItemView::SingleSelection);+ table_->setEditTriggers(QAbstractItemView::NoEditTriggers);+ table_->setShowGrid(false);+ connect(table_, &QTableWidget::itemSelectionChanged, this, &MCPActivityView::onSelectionChanged);++ detailPanel_ = new QWidget(splitter);+ detailLayout_ = new QVBoxLayout(detailPanel_);+ detailLayout_->setContentsMargins(12, 8, 12, 8);+ detailPlaceholder_ = new QLabel(tr("Select an entry to see details."), detailPanel_);+ detailPlaceholder_->setAlignment(Qt::AlignCenter);+ detailPlaceholder_->setStyleSheet("color: palette(mid);");+ detailLayout_->addWidget(detailPlaceholder_);+ detailLayout_->addStretch();++ splitter->addWidget(table_);+ splitter->addWidget(detailPanel_);+ splitter->setStretchFactor(0, 3);+ splitter->setStretchFactor(1, 2);++ outer->addWidget(splitter, 1);+}++void MCPActivityView::onFilterChanged() { refresh(); }+void MCPActivityView::onRefreshClicked() { state_->reloadFullActivity(); }++void MCPActivityView::onExportClicked() {+ auto path = QFileDialog::getSaveFileName(this, tr("Export audit log"),+ QString(), tr("JSON Lines (*.jsonl);;All Files (*)"));+ if (path.isEmpty()) return;+ std::ofstream out(path.toStdString());+ if (!out) {+ QMessageBox::warning(this, tr("Export"), tr("Could not open file for writing."));+ return;+ }+ for (const auto& e : state_->fullActivity()) out << e.toJson().dump() << '\n';+}++void MCPActivityView::onClearClicked() {+ if (QMessageBox::question(this, tr("Clear audit log"),+ tr("Permanently delete the entire MCP audit log?"),+ QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {+ if (state_->server()) state_->server()->auditLogger().clearAll();+ state_->reloadFullActivity();+ }+}++void MCPActivityView::onSelectionChanged() {+ selectedRow_ = table_->currentRow();+ rebuildDetail();+}++void MCPActivityView::refresh() {+ // Populate tool filter from unique tools+ QString keepTool = toolFilter_->currentData().toString();+ QStringList tools;+ for (const auto& e : state_->fullActivity()) {+ QString t = QString::fromStdString(e.tool);+ if (!tools.contains(t)) tools << t;+ }+ tools.sort();+ toolFilter_->blockSignals(true);+ toolFilter_->clear();+ toolFilter_->addItem(tr("All Tools"), QString());+ for (const auto& t : tools) toolFilter_->addItem(t, t);+ int idx = toolFilter_->findData(keepTool);+ if (idx >= 0) toolFilter_->setCurrentIndex(idx);+ toolFilter_->blockSignals(false);++ // Filter+ const QString needle = search_->text().trimmed().toLower();+ const QString toolF = toolFilter_->currentData().toString();+ const QString statF = statusFilter_->currentData().toString();++ std::vector<const mcp::MCPAuditEntry*> rows;+ for (const auto& e : state_->fullActivity()) {+ if (!toolF.isEmpty() && QString::fromStdString(e.tool) != toolF) continue;+ if (!statF.isEmpty() && QString::fromStdString(mcp::toString(e.result.status)) != statF) continue;+ if (!needle.isEmpty()) {+ bool hit = QString::fromStdString(e.tool).toLower().contains(needle)+ || QString::fromStdString(e.client.name).toLower().contains(needle)+ || (e.input.sqlPreview && QString::fromStdString(*e.input.sqlPreview).toLower().contains(needle));+ if (!hit) continue;+ }+ rows.push_back(&e);+ }++ table_->setRowCount(static_cast<int>(rows.size()));+ for (int i = 0; i < static_cast<int>(rows.size()); ++i) {+ const auto* e = rows[i];+ auto* timeItem = new QTableWidgetItem(formatTimeShort(e->timestampIso8601));+ auto* toolItem = new QTableWidgetItem(QString::fromStdString(e->tool));+ toolItem->setForeground(QColor(tierColor(e->tier)));+ auto* clientItem = new QTableWidgetItem(QString::fromStdString(e->client.name));+ auto* statusItem = new QTableWidgetItem(QString::fromStdString(mcp::toString(e->result.status)));+ statusItem->setForeground(QColor(statusColor(e->result.status)));+ auto* durItem = new QTableWidgetItem(QString("%1ms").arg(e->result.durationMs));++ table_->setItem(i, 0, timeItem);+ table_->setItem(i, 1, toolItem);+ table_->setItem(i, 2, clientItem);+ table_->setItem(i, 3, statusItem);+ table_->setItem(i, 4, durItem);+ }+ selectedRow_ = -1;+ rebuildDetail();+}++void MCPActivityView::rebuildDetail() {+ while (auto* item = detailLayout_->takeAt(0)) {+ if (auto* w = item->widget()) w->deleteLater();+ delete item;+ }++ if (selectedRow_ < 0 || selectedRow_ >= static_cast<int>(state_->fullActivity().size())) {+ detailPlaceholder_ = new QLabel(tr("Select an entry to see details."), detailPanel_);+ detailPlaceholder_->setAlignment(Qt::AlignCenter);+ detailPlaceholder_->setStyleSheet("color: palette(mid);");+ detailLayout_->addWidget(detailPlaceholder_);+ detailLayout_->addStretch();+ return;+ }++ // We built table_ rows in the same order as filtered entries. Re-run filter+ // quickly to find the selected one.+ int k = 0;+ const mcp::MCPAuditEntry* selected = nullptr;+ const QString needle = search_->text().trimmed().toLower();+ const QString toolF = toolFilter_->currentData().toString();+ const QString statF = statusFilter_->currentData().toString();+ for (const auto& e : state_->fullActivity()) {+ if (!toolF.isEmpty() && QString::fromStdString(e.tool) != toolF) continue;+ if (!statF.isEmpty() && QString::fromStdString(mcp::toString(e.result.status)) != statF) continue;+ if (!needle.isEmpty()) {+ bool hit = QString::fromStdString(e.tool).toLower().contains(needle)+ || QString::fromStdString(e.client.name).toLower().contains(needle)+ || (e.input.sqlPreview && QString::fromStdString(*e.input.sqlPreview).toLower().contains(needle));+ if (!hit) continue;+ }+ if (k == selectedRow_) { selected = &e; break; }+ ++k;+ }+ if (!selected) return;++ auto makeBox = [&](const QString& title) {+ auto* gb = new QGroupBox(title, detailPanel_);+ gb->setFlat(true);+ return gb;+ };++ auto addRow = [&](QFormLayout* form, const QString& k, const QString& v, bool mono = false) {+ auto* val = new QLabel(v);+ val->setWordWrap(true);+ val->setTextInteractionFlags(Qt::TextSelectableByMouse);+ if (mono) {+ QFont f = val->font(); f.setFamily("monospace"); val->setFont(f);+ }+ form->addRow(k, val);+ };++ // Event+ {+ auto* gb = makeBox(tr("Event"));+ auto* f = new QFormLayout(gb);+ addRow(f, tr("Tool"), QString::fromStdString(selected->tool), true);+ addRow(f, tr("Tier"), QString("Tier %1").arg(selected->tier));+ addRow(f, tr("Time"), formatTimeFull(selected->timestampIso8601));+ addRow(f, tr("Event ID"), QString::fromStdString(selected->eventId.substr(0, 8)) + "…", true);+ detailLayout_->addWidget(gb);+ }+ // Client+ {+ auto* gb = makeBox(tr("Client"));+ auto* f = new QFormLayout(gb);+ addRow(f, tr("Name"), QString::fromStdString(selected->client.name));+ addRow(f, tr("Version"), QString::fromStdString(selected->client.version));+ addRow(f, tr("Transport"), QString::fromStdString(selected->client.transport));+ detailLayout_->addWidget(gb);+ }+ // Connection+ if (selected->connectionId || selected->connectionType) {+ auto* gb = makeBox(tr("Connection"));+ auto* f = new QFormLayout(gb);+ if (selected->connectionType) addRow(f, tr("Database"), QString::fromStdString(*selected->connectionType));+ if (selected->connectionId) addRow(f, tr("ID"), QString::fromStdString(selected->connectionId->substr(0, 8)) + "…", true);+ detailLayout_->addWidget(gb);+ }+ // Result+ {+ auto* gb = makeBox(tr("Result"));+ auto* f = new QFormLayout(gb);+ QString st = QString::fromStdString(mcp::toString(selected->result.status));+ st[0] = st[0].toUpper();+ auto* statusLbl = new QLabel(st);+ statusLbl->setStyleSheet(QString("color: %1;").arg(statusColor(selected->result.status)));+ f->addRow(tr("Status"), statusLbl);+ addRow(f, tr("Duration"), QString("%1ms").arg(selected->result.durationMs));+ if (selected->result.rowsReturned) addRow(f, tr("Rows returned"), QString::number(*selected->result.rowsReturned));+ if (selected->result.rowsAffected) addRow(f, tr("Rows affected"), QString::number(*selected->result.rowsAffected));+ detailLayout_->addWidget(gb);+ }+ // SQL+ if (selected->input.sqlPreview) {+ auto* gb = makeBox(tr("SQL"));+ auto* v = new QVBoxLayout(gb);+ auto* tb = new QTextBrowser(gb);+ tb->setPlainText(QString::fromStdString(*selected->input.sqlPreview));+ tb->setMaximumHeight(160);+ QFont f = tb->font(); f.setFamily("monospace"); tb->setFont(f);+ v->addWidget(tb);+ detailLayout_->addWidget(gb);+ }+ // Error+ if (selected->error) {+ auto* gb = makeBox(tr("Error"));+ auto* v = new QVBoxLayout(gb);+ auto* lbl = new QLabel(QString::fromStdString(*selected->error), gb);+ lbl->setWordWrap(true);+ lbl->setStyleSheet("color: #e04b4a;");+ lbl->setTextInteractionFlags(Qt::TextSelectableByMouse);+ v->addWidget(lbl);+ detailLayout_->addWidget(gb);+ }++ detailLayout_->addStretch();+}++} // namespace gridexdiff --git a/linux/src/Presentation/Views/MCP/MCPActivityView.h b/linux/src/Presentation/Views/MCP/MCPActivityView.hnew file mode 100644index 0000000..1f2c537--- /dev/null+++ b/linux/src/Presentation/Views/MCP/MCPActivityView.h@@ -0,0 +1,47 @@+#pragma once++#include <QWidget>++class QLineEdit;+class QComboBox;+class QTableWidget;+class QPushButton;+class QWidget;+class QVBoxLayout;+class QLabel;++namespace gridex {++class MCPWindowState;++class MCPActivityView : public QWidget {+ Q_OBJECT+public:+ explicit MCPActivityView(MCPWindowState* state, QWidget* parent = nullptr);++private slots:+ void refresh();+ void onFilterChanged();+ void onSelectionChanged();+ void onRefreshClicked();+ void onClearClicked();+ void onExportClicked();++private:+ void buildUi();+ void rebuildDetail();++ MCPWindowState* state_;+ QLineEdit* search_ = nullptr;+ QComboBox* toolFilter_ = nullptr;+ QComboBox* statusFilter_ = nullptr;+ QTableWidget* table_ = nullptr;++ QWidget* detailPanel_ = nullptr;+ QVBoxLayout* detailLayout_ = nullptr;+ QLabel* detailPlaceholder_ = nullptr;++ int selectedRow_ = -1;+};++} // namespace gridexdiff --git a/linux/src/Presentation/Views/MCP/MCPAdvancedView.cpp b/linux/src/Presentation/Views/MCP/MCPAdvancedView.cppnew file mode 100644index 0000000..f035f27--- /dev/null+++ b/linux/src/Presentation/Views/MCP/MCPAdvancedView.cpp@@ -0,0 +1,219 @@+#include "Presentation/Views/MCP/MCPAdvancedView.h"++#include <QCheckBox>+#include <QComboBox>+#include <QFrame>+#include <QScrollArea>+#include <QFormLayout>+#include <QGroupBox>+#include <QHBoxLayout>+#include <QLabel>+#include <QMessageBox>+#include <QPushButton>+#include <QSettings>+#include <QSpinBox>+#include <QVBoxLayout>++#include "Presentation/Views/MCP/MCPWindowState.h"+#include "Services/MCP/MCPServer.h"++namespace gridex {++namespace {++QSpinBox* makeSpin(QWidget* p, int min, int max, int step, const QString& suffix = QString()) {+ auto* s = new QSpinBox(p);+ s->setRange(min, max);+ s->setSingleStep(step);+ if (!suffix.isEmpty()) s->setSuffix(suffix);+ return s;+}++} // namespace++MCPAdvancedView::MCPAdvancedView(MCPWindowState* state, QWidget* parent)+ : QWidget(parent), state_(state) {+ buildUi();+ loadFromSettings();+ applyLimits();+}++void MCPAdvancedView::buildUi() {+ auto* rootLayout = new QVBoxLayout(this);+ rootLayout->setContentsMargins(0, 0, 0, 0);++ auto* scroll = new QScrollArea(this);+ scroll->setObjectName(QStringLiteral("mcpScroll"));+ scroll->setWidgetResizable(true);+ scroll->setFrameShape(QFrame::NoFrame);+ rootLayout->addWidget(scroll);++ auto* host = new QWidget(scroll);+ auto* hostH = new QHBoxLayout(host);+ hostH->setContentsMargins(24, 20, 24, 24);+ hostH->setSpacing(0);+ hostH->addStretch();+ auto* content = new QWidget(host);+ content->setMaximumWidth(900);+ auto* outer = new QVBoxLayout(content);+ outer->setContentsMargins(0, 0, 0, 0);+ outer->setSpacing(16);++ // Rate limits+ auto* rateBox = new QGroupBox(tr("Rate Limits"), this);+ auto* rf = new QFormLayout(rateBox);+ queriesPerMinute_ = makeSpin(rateBox, 10, 200, 10);+ queriesPerHour_ = makeSpin(rateBox, 100, 5000, 100);+ writesPerMinute_ = makeSpin(rateBox, 1, 50, 1);+ ddlPerMinute_ = makeSpin(rateBox, 1, 10, 1);+ rf->addRow(tr("Queries per minute"), queriesPerMinute_);+ rf->addRow(tr("Queries per hour"), queriesPerHour_);+ rf->addRow(tr("Writes per minute"), writesPerMinute_);+ rf->addRow(tr("DDL per minute"), ddlPerMinute_);+ outer->addWidget(rateBox);++ // Timeouts+ auto* toBox = new QGroupBox(tr("Timeouts"), this);+ auto* tof = new QFormLayout(toBox);+ queryTimeout_ = makeSpin(toBox, 5, 300, 5, "s");+ approvalTimeout_ = makeSpin(toBox, 10, 300, 10, "s");+ connectionTimeout_ = makeSpin(toBox, 5, 60, 5, "s");+ tof->addRow(tr("Query timeout"), queryTimeout_);+ tof->addRow(tr("Approval timeout"), approvalTimeout_);+ tof->addRow(tr("Connection timeout"), connectionTimeout_);+ outer->addWidget(toBox);++ // Audit log+ auto* audBox = new QGroupBox(tr("Audit Log"), this);+ auto* auf = new QFormLayout(audBox);+ retention_ = new QComboBox(audBox);+ retention_->addItem(tr("7 days"), 7);+ retention_->addItem(tr("30 days"), 30);+ retention_->addItem(tr("90 days"), 90);+ retention_->addItem(tr("1 year"), 365);+ retention_->addItem(tr("Forever"), 0);+ maxSizeMB_ = makeSpin(audBox, 10, 500, 10, " MB");+ auf->addRow(tr("Retention"), retention_);+ auf->addRow(tr("Max log size"), maxSizeMB_);+ auto* locLbl = new QLabel(audBox);+ locLbl->setTextInteractionFlags(Qt::TextSelectableByMouse);+ locLbl->setStyleSheet("color: palette(mid);");+ if (state_ && state_->server()) {+ locLbl->setText(QString::fromStdString(state_->server()->auditLogger().logFilePath()));+ }+ auf->addRow(tr("Location"), locLbl);+ outer->addWidget(audBox);++ // Security+ auto* secBox = new QGroupBox(tr("Security"), this);+ auto* sv = new QVBoxLayout(secBox);+ requireApprovalWrites_ = new QCheckBox(tr("Require approval for write operations"), secBox);+ allowRemoteHttp_ = new QCheckBox(tr("Allow remote HTTP connections"), secBox);+ sv->addWidget(requireApprovalWrites_);+ sv->addWidget(allowRemoteHttp_);+ auto* warn = new QLabel(+ tr("⚠ Remote HTTP allows connections from other machines. Use only on trusted networks."), secBox);+ warn->setWordWrap(true);+ warn->setStyleSheet("color: #ef9f27; font-size: small;");+ warn->setVisible(false);+ sv->addWidget(warn);+ connect(allowRemoteHttp_, &QCheckBox::toggled, warn, &QLabel::setVisible);+ outer->addWidget(secBox);++ // Reset+ auto* resetRow = new QHBoxLayout();+ resetRow->addStretch();+ auto* resetBtn = new QPushButton(tr("Reset to Defaults…"), this);+ connect(resetBtn, &QPushButton::clicked, this, &MCPAdvancedView::onResetClicked);+ resetRow->addWidget(resetBtn);+ outer->addLayout(resetRow);++ outer->addStretch();+ hostH->addWidget(content, 0, Qt::AlignTop);+ hostH->addStretch();+ scroll->setWidget(host);++ // Hook up save-on-change+ for (auto* s : {queriesPerMinute_, queriesPerHour_, writesPerMinute_, ddlPerMinute_,+ queryTimeout_, approvalTimeout_, connectionTimeout_, maxSizeMB_}) {+ connect(s, QOverload<int>::of(&QSpinBox::valueChanged), this, &MCPAdvancedView::onValueChanged);+ }+ connect(retention_, QOverload<int>::of(&QComboBox::currentIndexChanged),+ this, &MCPAdvancedView::onValueChanged);+ connect(requireApprovalWrites_, &QCheckBox::toggled, this, &MCPAdvancedView::onValueChanged);+ connect(allowRemoteHttp_, &QCheckBox::toggled, this, &MCPAdvancedView::onValueChanged);+}++void MCPAdvancedView::loadFromSettings() {+ QSettings s;+ queriesPerMinute_->setValue(s.value("mcp.rateLimit.queriesPerMinute", 60).toInt());+ queriesPerHour_ ->setValue(s.value("mcp.rateLimit.queriesPerHour", 1000).toInt());+ writesPerMinute_ ->setValue(s.value("mcp.rateLimit.writesPerMinute", 10).toInt());+ ddlPerMinute_ ->setValue(s.value("mcp.rateLimit.ddlPerMinute", 1).toInt());++ queryTimeout_ ->setValue(s.value("mcp.timeout.query", 30).toInt());+ approvalTimeout_ ->setValue(s.value("mcp.timeout.approval", 60).toInt());+ connectionTimeout_->setValue(s.value("mcp.timeout.connection", 10).toInt());++ int ret = s.value("mcp.audit.retentionDays", 90).toInt();+ int idx = retention_->findData(ret);+ retention_->setCurrentIndex(idx >= 0 ? idx : 2);+ maxSizeMB_->setValue(s.value("mcp.audit.maxSizeMB", 100).toInt());++ requireApprovalWrites_->setChecked(s.value("mcp.security.requireApprovalForWrites", true).toBool());+ allowRemoteHttp_ ->setChecked(s.value("mcp.security.allowRemoteHTTP", false).toBool());+}++void MCPAdvancedView::saveToSettings() {+ QSettings s;+ s.setValue("mcp.rateLimit.queriesPerMinute", queriesPerMinute_->value());+ s.setValue("mcp.rateLimit.queriesPerHour", queriesPerHour_->value());+ s.setValue("mcp.rateLimit.writesPerMinute", writesPerMinute_->value());+ s.setValue("mcp.rateLimit.ddlPerMinute", ddlPerMinute_->value());++ s.setValue("mcp.timeout.query", queryTimeout_->value());+ s.setValue("mcp.timeout.approval", approvalTimeout_->value());+ s.setValue("mcp.timeout.connection", connectionTimeout_->value());++ s.setValue("mcp.audit.retentionDays", retention_->currentData().toInt());+ s.setValue("mcp.audit.maxSizeMB", maxSizeMB_->value());++ s.setValue("mcp.security.requireApprovalForWrites", requireApprovalWrites_->isChecked());+ s.setValue("mcp.security.allowRemoteHTTP", allowRemoteHttp_->isChecked());+}++void MCPAdvancedView::applyLimits() {+ if (!state_ || !state_->server()) return;+ mcp::RateLimits l;+ l.queriesPerMinute = queriesPerMinute_->value();+ l.queriesPerHour = queriesPerHour_->value();+ l.writesPerMinute = writesPerMinute_->value();+ l.ddlPerMinute = ddlPerMinute_->value();+ state_->server()->rateLimiter().setLimits(l);+ state_->server()->auditLogger().setMaxFileSize(+ static_cast<qint64>(maxSizeMB_->value()) * 1024 * 1024);+}++void MCPAdvancedView::onValueChanged() {+ saveToSettings();+ applyLimits();+}++void MCPAdvancedView::onResetClicked() {+ if (QMessageBox::question(this, tr("Reset All Settings?"),+ tr("This will restore all MCP settings to their default values."),+ QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) return;+ queriesPerMinute_->setValue(60);+ queriesPerHour_ ->setValue(1000);+ writesPerMinute_ ->setValue(10);+ ddlPerMinute_ ->setValue(1);+ queryTimeout_ ->setValue(30);+ approvalTimeout_ ->setValue(60);+ connectionTimeout_->setValue(10);+ retention_->setCurrentIndex(retention_->findData(90));+ maxSizeMB_->setValue(100);+ requireApprovalWrites_->setChecked(true);+ allowRemoteHttp_ ->setChecked(false);+}++} // namespace gridexdiff --git a/linux/src/Presentation/Views/MCP/MCPAdvancedView.h b/linux/src/Presentation/Views/MCP/MCPAdvancedView.hnew file mode 100644index 0000000..4e87e38--- /dev/null+++ b/linux/src/Presentation/Views/MCP/MCPAdvancedView.h@@ -0,0 +1,47 @@+#pragma once++#include <QWidget>++class QSpinBox;+class QComboBox;+class QCheckBox;+class QPushButton;++namespace gridex {++class MCPWindowState;++class MCPAdvancedView : public QWidget {+ Q_OBJECT+public:+ explicit MCPAdvancedView(MCPWindowState* state, QWidget* parent = nullptr);++private slots:+ void onValueChanged();+ void onResetClicked();++private:+ void buildUi();+ void loadFromSettings();+ void saveToSettings();+ void applyLimits();++ MCPWindowState* state_;++ QSpinBox* queriesPerMinute_ = nullptr;+ QSpinBox* queriesPerHour_ = nullptr;+ QSpinBox* writesPerMinute_ = nullptr;+ QSpinBox* ddlPerMinute_ = nullptr;++ QSpinBox* queryTimeout_ = nullptr;+ QSpinBox* approvalTimeout_ = nullptr;+ QSpinBox* connectionTimeout_ = nullptr;++ QComboBox* retention_ = nullptr;+ QSpinBox* maxSizeMB_ = nullptr;++ QCheckBox* requireApprovalWrites_ = nullptr;+ QCheckBox* allowRemoteHttp_ = nullptr;+};++} // namespace gridexdiff --git a/linux/src/Presentation/Views/MCP/MCPConnectionsView.cpp b/linux/src/Presentation/Views/MCP/MCPConnectionsView.cppnew file mode 100644index 0000000..677bc09--- /dev/null+++ b/linux/src/Presentation/Views/MCP/MCPConnectionsView.cpp@@ -0,0 +1,146 @@+#include "Presentation/Views/MCP/MCPConnectionsView.h"++#include <QComboBox>+#include <QHBoxLayout>+#include <QHeaderView>+#include <QLabel>+#include <QLineEdit>+#include <QTableWidget>+#include <QVBoxLayout>++#include "Presentation/Views/MCP/MCPWindowState.h"++namespace gridex {++namespace {++QString displayNameQ(MCPConnectionMode m) {+ return QString::fromStdString(std::string(displayName(m)));+}++QString descriptionQ(MCPConnectionMode m) {+ return QString::fromStdString(std::string(description(m)));+}++} // namespace++MCPConnectionsView::MCPConnectionsView(MCPWindowState* state, QWidget* parent)+ : QWidget(parent), state_(state) {+ buildUi();+ connect(state_, &MCPWindowState::connectionsChanged, this, &MCPConnectionsView::refresh);+ refresh();+}++void MCPConnectionsView::buildUi() {+ auto* outer = new QVBoxLayout(this);+ outer->setContentsMargins(24, 16, 24, 16);+ outer->setSpacing(10);++ // Filter bar+ auto* filterBar = new QHBoxLayout();+ filterBar->setSpacing(10);+ search_ = new QLineEdit(this);+ search_->setObjectName(QStringLiteral("mcpSearch"));+ search_->setPlaceholderText(tr("Search connections"));+ search_->setClearButtonEnabled(true);+ search_->setMaximumWidth(300);+ connect(search_, &QLineEdit::textChanged, this, &MCPConnectionsView::onFilterChanged);++ modeFilter_ = new QComboBox(this);+ modeFilter_->addItem(tr("All Access"), QString());+ for (auto m : kAllMCPConnectionModes) {+ modeFilter_->addItem(displayNameQ(m),+ QString::fromStdString(std::string(rawValue(m))));+ }+ modeFilter_->setFixedWidth(140);+ connect(modeFilter_, QOverload<int>::of(&QComboBox::currentIndexChanged),+ this, &MCPConnectionsView::onFilterChanged);++ countLabel_ = new QLabel(this);+ countLabel_->setStyleSheet("color: palette(mid);");++ filterBar->addWidget(search_);+ filterBar->addWidget(modeFilter_);+ filterBar->addStretch();+ filterBar->addWidget(countLabel_);+ outer->addLayout(filterBar);++ // Table+ table_ = new QTableWidget(this);+ table_->setColumnCount(5);+ table_->setHorizontalHeaderLabels({tr("Name"), tr("Type"), tr("Host"), tr("Access"), tr("Description")});+ table_->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Interactive);+ table_->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Interactive);+ table_->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch);+ table_->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Interactive);+ table_->horizontalHeader()->setSectionResizeMode(4, QHeaderView::Stretch);+ table_->verticalHeader()->setVisible(false);+ table_->verticalHeader()->setDefaultSectionSize(44);+ table_->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed);+ table_->setAlternatingRowColors(true);+ table_->setSelectionBehavior(QAbstractItemView::SelectRows);+ table_->setEditTriggers(QAbstractItemView::NoEditTriggers);+ table_->setShowGrid(false);+ outer->addWidget(table_, 1);+}++void MCPConnectionsView::onFilterChanged() { refresh(); }++void MCPConnectionsView::onRowModeChanged(int row, int) {+ auto* combo = qobject_cast<QComboBox*>(table_->cellWidget(row, 3));+ if (!combo) return;+ QString id = combo->property("connId").toString();+ QString modeRaw = combo->currentData().toString();+ auto parsed = mcpConnectionModeFromRaw(modeRaw.toStdString());+ if (parsed) state_->updateConnectionMode(id, *parsed);+}++void MCPConnectionsView::refresh() {+ const QString needle = search_->text().trimmed().toLower();+ const QString filterRaw = modeFilter_->currentData().toString();++ // Build filtered list+ QVector<MCPConnectionRow> rows;+ for (const auto& r : state_->connections()) {+ if (!needle.isEmpty()) {+ bool hit = QString::fromStdString(r.config.name).toLower().contains(needle)+ || QString::fromStdString(r.config.displayHost()).toLower().contains(needle);+ if (!hit) continue;+ }+ if (!filterRaw.isEmpty()) {+ if (QString::fromStdString(std::string(rawValue(r.mode))) != filterRaw) continue;+ }+ rows.push_back(r);+ }++ countLabel_->setText(tr("%1 of %2 connections").arg(rows.size()).arg(state_->connections().size()));++ table_->blockSignals(true);+ table_->setRowCount(rows.size());+ for (int i = 0; i < rows.size(); ++i) {+ const auto& r = rows[i];+ auto* nameItem = new QTableWidgetItem(QString::fromStdString(r.config.name));+ auto* typeItem = new QTableWidgetItem(QString::fromStdString(std::string(displayName(r.config.databaseType))));+ auto* hostItem = new QTableWidgetItem(QString::fromStdString(r.config.displayHost()));+ auto* descItem = new QTableWidgetItem(descriptionQ(r.mode));++ table_->setItem(i, 0, nameItem);+ table_->setItem(i, 1, typeItem);+ table_->setItem(i, 2, hostItem);+ table_->setItem(i, 4, descItem);++ auto* combo = new QComboBox(table_);+ combo->setProperty("connId", QString::fromStdString(r.config.id));+ for (auto m : kAllMCPConnectionModes) {+ combo->addItem(displayNameQ(m),+ QString::fromStdString(std::string(rawValue(m))));+ if (m == r.mode) combo->setCurrentIndex(combo->count() - 1);+ }+ connect(combo, QOverload<int>::of(&QComboBox::currentIndexChanged),+ this, [this, i](int idx) { onRowModeChanged(i, idx); });+ table_->setCellWidget(i, 3, combo);+ }+ table_->blockSignals(false);+}++} // namespace gridexdiff --git a/linux/src/Presentation/Views/MCP/MCPConnectionsView.h b/linux/src/Presentation/Views/MCP/MCPConnectionsView.hnew file mode 100644index 0000000..29576ab--- /dev/null+++ b/linux/src/Presentation/Views/MCP/MCPConnectionsView.h@@ -0,0 +1,34 @@+#pragma once++#include <QWidget>++class QLineEdit;+class QComboBox;+class QLabel;+class QTableWidget;++namespace gridex {++class MCPWindowState;++class MCPConnectionsView : public QWidget {+ Q_OBJECT+public:+ explicit MCPConnectionsView(MCPWindowState* state, QWidget* parent = nullptr);++private slots:+ void refresh();+ void onFilterChanged();+ void onRowModeChanged(int row, int comboIndex);++private:+ void buildUi();++ MCPWindowState* state_;+ QLineEdit* search_ = nullptr;+ QComboBox* modeFilter_ = nullptr;+ QLabel* countLabel_ = nullptr;+ QTableWidget* table_ = nullptr;+};++} // namespace gridexdiff --git a/linux/src/Presentation/Views/MCP/MCPOverviewView.cpp b/linux/src/Presentation/Views/MCP/MCPOverviewView.cppnew file mode 100644index 0000000..5f1446f--- /dev/null+++ b/linux/src/Presentation/Views/MCP/MCPOverviewView.cpp@@ -0,0 +1,320 @@+#include "Presentation/Views/MCP/MCPOverviewView.h"++#include <QDateTime>+#include <QFrame>+#include <QHBoxLayout>+#include <QLabel>+#include <QPushButton>+#include <QScrollArea>+#include <QVBoxLayout>++#include "Presentation/Views/MCP/MCPWindowState.h"++namespace gridex {++namespace {++int countMode(const QVector<MCPConnectionRow>& rows, MCPConnectionMode m) {+ int n = 0;+ for (const auto& r : rows) if (r.mode == m) ++n;+ return n;+}++QString modeColorHex(MCPConnectionMode m) {+ switch (m) {+ case MCPConnectionMode::Locked: return "#e04b4a";+ case MCPConnectionMode::ReadOnly: return "#378add";+ case MCPConnectionMode::ReadWrite: return "#3ea82f";+ }+ return "#888";+}++QString statusColorHex(mcp::MCPAuditStatus s) {+ switch (s) {+ case mcp::MCPAuditStatus::Success: return "#3ea82f";+ case mcp::MCPAuditStatus::Error: return "#e04b4a";+ case mcp::MCPAuditStatus::Denied: return "#ef9f27";+ case mcp::MCPAuditStatus::Timeout: return "#d4a017";+ }+ return "#888";+}++QString relativeTime(const std::string& iso) {+ auto dt = QDateTime::fromString(QString::fromStdString(iso), Qt::ISODate);+ if (!dt.isValid()) return QString::fromStdString(iso);+ qint64 secs = dt.secsTo(QDateTime::currentDateTimeUtc());+ if (secs < 60) return "just now";+ if (secs < 3600) return QString("%1m ago").arg(secs / 60);+ if (secs < 86400) return QString("%1h ago").arg(secs / 3600);+ return QString("%1d ago").arg(secs / 86400);+}++QString formatUptime(int secs) {+ int h = secs / 3600;+ int m = (secs % 3600) / 60;+ int s = secs % 60;+ if (h > 0) return QString("%1h %2m").arg(h).arg(m);+ if (m > 0) return QString("%1m %2s").arg(m).arg(s);+ return QString("%1s").arg(s);+}++QFrame* makeCard(QWidget* parent) {+ auto* f = new QFrame(parent);+ f->setProperty("card", true);+ f->setFrameShape(QFrame::NoFrame);+ return f;+}++QLabel* makeSectionTitle(const QString& text, QWidget* parent) {+ auto* l = new QLabel(text, parent);+ l->setProperty("role", "section-title");+ return l;+}++} // namespace++MCPOverviewView::MCPOverviewView(MCPWindowState* state, QWidget* parent)+ : QWidget(parent), state_(state) {+ buildUi();+ connect(state_, &MCPWindowState::connectionsChanged, this, &MCPOverviewView::refresh);+ connect(state_, &MCPWindowState::recentActivityChanged, this, &MCPOverviewView::refresh);+ connect(state_, &MCPWindowState::serverRunningChanged, this, &MCPOverviewView::refresh);+ connect(state_, &MCPWindowState::uptimeChanged, this, &MCPOverviewView::refresh);+ refresh();+}++void MCPOverviewView::buildUi() {+ auto* rootLayout = new QVBoxLayout(this);+ rootLayout->setContentsMargins(0, 0, 0, 0);++ auto* scroll = new QScrollArea(this);+ scroll->setObjectName(QStringLiteral("mcpScroll"));+ scroll->setWidgetResizable(true);+ scroll->setFrameShape(QFrame::NoFrame);+ rootLayout->addWidget(scroll);++ auto* host = new QWidget(scroll);+ auto* hostH = new QHBoxLayout(host);+ hostH->setContentsMargins(24, 20, 24, 24);+ hostH->setSpacing(0);+ hostH->addStretch();++ auto* content = new QWidget(host);+ content->setMaximumWidth(900);+ auto* outer = new QVBoxLayout(content);+ outer->setContentsMargins(0, 0, 0, 0);+ outer->setSpacing(20);++ // ---- Running card ----+ auto* runningCard = makeCard(content);+ auto* runH = new QHBoxLayout(runningCard);+ runH->setContentsMargins(18, 16, 18, 16);+ runH->setSpacing(14);++ statusIcon_ = new QLabel(runningCard);+ statusIcon_->setFixedSize(42, 42);+ statusIcon_->setAlignment(Qt::AlignCenter);++ auto* titleBox = new QVBoxLayout();+ titleBox->setSpacing(2);+ statusTitle_ = new QLabel(runningCard);+ QFont tf = statusTitle_->font(); tf.setBold(true); tf.setPointSizeF(tf.pointSizeF() + 1.0);+ statusTitle_->setFont(tf);+ statusDetail_ = new QLabel(runningCard);+ statusDetail_->setProperty("role", "muted");+ statusDetail_->setWordWrap(true);+ titleBox->addWidget(statusTitle_);+ titleBox->addWidget(statusDetail_);++ runH->addWidget(statusIcon_);+ runH->addLayout(titleBox, 1);+ outer->addWidget(runningCard);++ // ---- Access summary ----+ outer->addWidget(makeSectionTitle(tr("Access"), content));+ auto* accessCard = makeCard(content);+ auto* accessV = new QVBoxLayout(accessCard);+ accessV->setContentsMargins(18, 14, 18, 14);+ accessV->setSpacing(10);++ auto addAccessRow = [&](const QString& label, QLabel** out, const QString& color) {+ auto* row = new QHBoxLayout();+ row->setSpacing(8);+ row->addWidget(new QLabel(label, accessCard), 1);+ auto* dot = new QLabel(accessCard);+ dot->setFixedSize(8, 8);+ dot->setStyleSheet(QString("background:%1; border-radius:4px;").arg(color));+ auto* count = new QLabel("0", accessCard);+ QFont cf = count->font(); cf.setFamily("monospace"); count->setFont(cf);+ row->addWidget(dot);+ row->addWidget(count);+ *out = count;+ accessV->addLayout(row);+ };+ addAccessRow(tr("Locked"), &lockedCount_, modeColorHex(MCPConnectionMode::Locked));+ addAccessRow(tr("Read-only"), &readOnlyCount_, modeColorHex(MCPConnectionMode::ReadOnly));+ addAccessRow(tr("Read-write"), &readWriteCount_, modeColorHex(MCPConnectionMode::ReadWrite));++ auto* manageBtn = new QPushButton(tr("Manage Connections…"), accessCard);+ manageBtn->setProperty("link", true);+ manageBtn->setCursor(Qt::PointingHandCursor);+ connect(manageBtn, &QPushButton::clicked, this, [this] { emit switchToTab(Tab::Connections); });+ accessV->addWidget(manageBtn, 0, Qt::AlignLeft);+ outer->addWidget(accessCard);++ // ---- Recent activity ----+ outer->addWidget(makeSectionTitle(tr("Recent Activity"), content));+ activityBox_ = makeCard(content);+ activityLayout_ = new QVBoxLayout(activityBox_);+ activityLayout_->setContentsMargins(18, 14, 18, 14);+ activityLayout_->setSpacing(10);+ outer->addWidget(activityBox_);++ // ---- Connections preview ----+ connectionsTitle_ = makeSectionTitle(tr("Connections"), content);+ outer->addWidget(connectionsTitle_);+ connectionsBox_ = makeCard(content);+ connectionsLayout_ = new QVBoxLayout(connectionsBox_);+ connectionsLayout_->setContentsMargins(18, 14, 18, 14);+ connectionsLayout_->setSpacing(10);+ outer->addWidget(connectionsBox_);++ outer->addStretch();+ hostH->addWidget(content, 0, Qt::AlignTop);+ hostH->addStretch();+ scroll->setWidget(host);+}++void MCPOverviewView::refresh() {+ const bool running = state_->isServerRunning();+ QString bg = running ? "rgba(62, 168, 47, 55)" : "rgba(128, 128, 128, 40)";+ QString fg = running ? "#3ea82f" : "#888";+ statusIcon_->setStyleSheet(QString(+ "background-color: %1; border-radius: 21px; color: %2; font-size: 22px; font-weight: bold;")+ .arg(bg).arg(fg));+ statusIcon_->setText(running ? QStringLiteral("✓") : QStringLiteral("⏸"));+ statusTitle_->setText(running ? tr("MCP Server is running") : tr("MCP Server is stopped"));++ if (!running) {+ statusDetail_->setText(tr("Start the server from the header to allow AI clients to access your databases."));+ } else {+ QStringList parts;+ int up = state_->uptimeSeconds();+ if (up > 0) parts << tr("Running for %1").arg(formatUptime(up));+ int active = 0;+ for (const auto& r : state_->connections()) if (r.mode != MCPConnectionMode::Locked) ++active;+ parts << tr("%1 of %2 connection%3 exposed")+ .arg(active).arg(state_->connections().size())+ .arg(state_->connections().size() == 1 ? "" : "s");+ statusDetail_->setText(parts.join(" · "));+ }++ lockedCount_ ->setText(QString::number(countMode(state_->connections(), MCPConnectionMode::Locked)));+ readOnlyCount_ ->setText(QString::number(countMode(state_->connections(), MCPConnectionMode::ReadOnly)));+ readWriteCount_->setText(QString::number(countMode(state_->connections(), MCPConnectionMode::ReadWrite)));++ // ---- Rebuild activity rows ----+ while (auto* item = activityLayout_->takeAt(0)) {+ if (auto* w = item->widget()) w->deleteLater();+ delete item;+ }+ const auto& recent = state_->recentActivity();+ if (recent.empty()) {+ auto* lbl = new QLabel(tr("No activity yet"), activityBox_);+ lbl->setProperty("role", "muted");+ activityLayout_->addWidget(lbl);+ } else {+ std::size_t n = std::min<std::size_t>(recent.size(), 5);+ for (std::size_t i = 0; i < n; ++i) {+ const auto& e = recent[i];+ auto* row = new QWidget(activityBox_);+ auto* rowH = new QHBoxLayout(row);+ rowH->setContentsMargins(0, 0, 0, 0);+ rowH->setSpacing(10);++ auto* dot = new QLabel(row);+ dot->setFixedSize(6, 6);+ dot->setStyleSheet(QString("background:%1; border-radius:3px;").arg(statusColorHex(e.result.status)));+ rowH->addWidget(dot, 0, Qt::AlignVCenter);++ auto* textCol = new QVBoxLayout();+ textCol->setSpacing(0);+ auto* primary = new QLabel(row);+ primary->setTextFormat(Qt::RichText);+ primary->setText(QString(+ "<span style='font-family:monospace;font-weight:600;'>%1</span>"+ " <span style='color:rgba(128,128,128,200);'>· %2</span>")+ .arg(QString::fromStdString(e.tool))+ .arg(QString::fromStdString(e.client.name)));+ auto* secondary = new QLabel(row);+ secondary->setProperty("role", "hint");+ secondary->setText(QString("%1 · %2ms")+ .arg(relativeTime(e.timestampIso8601))+ .arg(e.result.durationMs));+ textCol->addWidget(primary);+ textCol->addWidget(secondary);+ rowH->addLayout(textCol, 1);++ activityLayout_->addWidget(row);+ }+ if (recent.size() > 5) {+ auto* btn = new QPushButton(tr("View All Activity…"), activityBox_);+ btn->setProperty("link", true);+ btn->setCursor(Qt::PointingHandCursor);+ connect(btn, &QPushButton::clicked, this, [this] { emit switchToTab(Tab::Activity); });+ activityLayout_->addWidget(btn, 0, Qt::AlignLeft);+ }+ }++ // ---- Rebuild connection rows ----+ while (auto* item = connectionsLayout_->takeAt(0)) {+ if (auto* w = item->widget()) w->deleteLater();+ delete item;+ }+ const auto& conns = state_->connections();+ if (conns.isEmpty()) {+ connectionsBox_->hide();+ if (connectionsTitle_) connectionsTitle_->hide();+ } else {+ connectionsBox_->show();+ if (connectionsTitle_) connectionsTitle_->show();+ int n = std::min<int>(conns.size(), 5);+ for (int i = 0; i < n; ++i) {+ const auto& r = conns[i];+ auto* row = new QWidget(connectionsBox_);+ auto* rowH = new QHBoxLayout(row);+ rowH->setContentsMargins(0, 0, 0, 0);+ rowH->setSpacing(10);++ auto* dot = new QLabel(row);+ dot->setFixedSize(8, 8);+ dot->setStyleSheet(QString("background:%1; border-radius:4px;").arg(modeColorHex(r.mode)));+ rowH->addWidget(dot, 0, Qt::AlignVCenter);++ auto* name = new QLabel(QString::fromStdString(r.config.name), row);+ rowH->addWidget(name);+ auto* host = new QLabel(QString::fromStdString(r.config.displayHost()), row);+ host->setProperty("role", "muted");+ rowH->addWidget(host);+ rowH->addStretch();++ auto* badge = new QLabel(QString::fromStdString(std::string(displayName(r.mode))), row);+ badge->setStyleSheet(QString(+ "color:%1; font-size:11px; padding:2px 8px;"+ "background: rgba(128,128,128,25); border-radius: 4px;")+ .arg(modeColorHex(r.mode)));+ rowH->addWidget(badge);++ connectionsLayout_->addWidget(row);+ }+ if (conns.size() > 5) {+ auto* btn = new QPushButton(tr("Show all %1 connections…").arg(conns.size()), connectionsBox_);+ btn->setProperty("link", true);+ btn->setCursor(Qt::PointingHandCursor);+ connect(btn, &QPushButton::clicked, this, [this] { emit switchToTab(Tab::Connections); });+ connectionsLayout_->addWidget(btn, 0, Qt::AlignLeft);+ }+ }+}++} // namespace gridexdiff --git a/linux/src/Presentation/Views/MCP/MCPOverviewView.h b/linux/src/Presentation/Views/MCP/MCPOverviewView.hnew file mode 100644index 0000000..e80420a--- /dev/null+++ b/linux/src/Presentation/Views/MCP/MCPOverviewView.h@@ -0,0 +1,44 @@+#pragma once++#include <QWidget>++class QFrame;+class QLabel;+class QPushButton;+class QVBoxLayout;++namespace gridex {++class MCPWindowState;++class MCPOverviewView : public QWidget {+ Q_OBJECT+public:+ enum class Tab { Overview, Connections, Activity, Setup, Config };++ explicit MCPOverviewView(MCPWindowState* state, QWidget* parent = nullptr);++signals:+ void switchToTab(Tab tab);++private slots:+ void refresh();++private:+ void buildUi();++ MCPWindowState* state_;+ QLabel* statusIcon_ = nullptr;+ QLabel* statusTitle_ = nullptr;+ QLabel* statusDetail_ = nullptr;+ QLabel* lockedCount_ = nullptr;+ QLabel* readOnlyCount_ = nullptr;+ QLabel* readWriteCount_ = nullptr;+ QFrame* activityBox_ = nullptr;+ QVBoxLayout* activityLayout_ = nullptr;+ QFrame* connectionsBox_ = nullptr;+ QVBoxLayout* connectionsLayout_ = nullptr;+ QLabel* connectionsTitle_ = nullptr;+};++} // namespace gridexdiff --git a/linux/src/Presentation/Views/MCP/MCPSetupView.cpp b/linux/src/Presentation/Views/MCP/MCPSetupView.cppnew file mode 100644index 0000000..04c19d4--- /dev/null+++ b/linux/src/Presentation/Views/MCP/MCPSetupView.cpp@@ -0,0 +1,277 @@+#include "Presentation/Views/MCP/MCPSetupView.h"++#include <QApplication>+#include <QComboBox>+#include <QFrame>+#include <QScrollArea>+#include <QClipboard>+#include <QCoreApplication>+#include <QDesktopServices>+#include <QDir>+#include <QFile>+#include <QFileInfo>+#include <QFormLayout>+#include <QGroupBox>+#include <QHBoxLayout>+#include <QLabel>+#include <QMessageBox>+#include <QPlainTextEdit>+#include <QPushButton>+#include <QTimer>+#include <QUrl>+#include <QVBoxLayout>++#include <nlohmann/json.hpp>++namespace gridex {++namespace {++struct ClientSpec {+ const char* id;+ const char* displayName;+ const char* pathTemplate; // ~/ is expanded+};++static const ClientSpec kClients[] = {+ {"claude_desktop", "Claude Desktop",+ "~/.config/Claude/claude_desktop_config.json"},+ {"cursor", "Cursor", "~/.cursor/mcp.json"},+ {"windsurf", "Windsurf", "~/.windsurf/mcp.json"},+ {"claude_code", "Claude Code", "~/.claude/settings.json"},+};++QString expand(const QString& p) {+ if (p.startsWith("~")) return QDir::homePath() + p.mid(1);+ return p;+}++} // namespace++MCPSetupView::MCPSetupView(QWidget* parent) : QWidget(parent) {+ buildUi();+ onClientChanged();+}++void MCPSetupView::buildUi() {+ auto* rootLayout = new QVBoxLayout(this);+ rootLayout->setContentsMargins(0, 0, 0, 0);++ auto* scroll = new QScrollArea(this);+ scroll->setObjectName(QStringLiteral("mcpScroll"));+ scroll->setWidgetResizable(true);+ scroll->setFrameShape(QFrame::NoFrame);+ rootLayout->addWidget(scroll);++ auto* host = new QWidget(scroll);+ auto* hostH = new QHBoxLayout(host);+ hostH->setContentsMargins(24, 20, 24, 24);+ hostH->setSpacing(0);+ hostH->addStretch();+ auto* content = new QWidget(host);+ content->setMaximumWidth(900);+ auto* outer = new QVBoxLayout(content);+ outer->setContentsMargins(0, 0, 0, 0);+ outer->setSpacing(16);++ // Info banner+ auto* banner = new QFrame(this);+ banner->setObjectName(QStringLiteral("mcpBanner"));+ auto* bannerH = new QHBoxLayout(banner);+ bannerH->setContentsMargins(14, 12, 14, 12);+ bannerH->setSpacing(10);+ auto* bannerIcon = new QLabel(QStringLiteral("ℹ"), banner);+ bannerIcon->setStyleSheet("color: #378add; font-size: 16px; font-weight: bold;");+ auto* bannerTextBox = new QVBoxLayout();+ bannerTextBox->setSpacing(2);+ auto* bannerTitle = new QLabel(tr("This is a config file, not a terminal command"), banner);+ QFont btf = bannerTitle->font(); btf.setBold(true); bannerTitle->setFont(btf);+ auto* bannerSub = new QLabel(+ tr("Use \"Install\" below to add Gridex to your client automatically, or copy and paste into "+ "the config file manually."), banner);+ bannerSub->setProperty("role", "muted");+ bannerSub->setWordWrap(true);+ bannerTextBox->addWidget(bannerTitle);+ bannerTextBox->addWidget(bannerSub);+ bannerH->addWidget(bannerIcon, 0, Qt::AlignTop);+ bannerH->addLayout(bannerTextBox, 1);+ outer->addWidget(banner);++ // Client+ auto* clientBox = new QGroupBox(tr("Client"), this);+ auto* form = new QFormLayout(clientBox);+ clientCombo_ = new QComboBox(clientBox);+ for (const auto& c : kClients) clientCombo_->addItem(c.displayName, c.id);+ connect(clientCombo_, QOverload<int>::of(&QComboBox::currentIndexChanged),+ this, &MCPSetupView::onClientChanged);+ form->addRow(tr("AI Client"), clientCombo_);++ auto* pathRow = new QHBoxLayout();+ configPathLabel_ = new QLabel(clientBox);+ configPathLabel_->setTextInteractionFlags(Qt::TextSelectableByMouse);+ QFont f = configPathLabel_->font(); f.setFamily("monospace"); configPathLabel_->setFont(f);+ configPathLabel_->setStyleSheet("color: palette(mid);");+ auto* openBtn = new QPushButton(QStringLiteral("⎋"), clientBox);+ openBtn->setToolTip(tr("Open in file manager"));+ openBtn->setFlat(true);+ connect(openBtn, &QPushButton::clicked, this, &MCPSetupView::onOpenPathClicked);+ pathRow->addWidget(configPathLabel_, 1);+ pathRow->addWidget(openBtn);+ form->addRow(tr("Config file"), pathRow);+ outer->addWidget(clientBox);++ // Quick install+ auto* installBox = new QGroupBox(tr("Quick Install"), this);+ auto* installV = new QVBoxLayout(installBox);+ auto* buttons = new QHBoxLayout();+ installBtn_ = new QPushButton(tr("Install for Claude Desktop"), installBox);+ installBtn_->setDefault(true);+ installBtn_->setProperty("accent", true);+ installBtn_->setCursor(Qt::PointingHandCursor);+ installBtn_->setMinimumHeight(34);+ connect(installBtn_, &QPushButton::clicked, this, &MCPSetupView::onInstallClicked);+ copyBtn_ = new QPushButton(tr("Copy"), installBox);+ connect(copyBtn_, &QPushButton::clicked, this, &MCPSetupView::onCopyClicked);+ buttons->addWidget(installBtn_, 2);+ buttons->addWidget(copyBtn_, 1);+ installV->addLayout(buttons);+ auto* footer = new QLabel(+ tr("Install merges Gridex into your existing config automatically. A backup of the original "+ "file is kept next to it."), installBox);+ footer->setStyleSheet("color: palette(mid); font-size: small;");+ footer->setWordWrap(true);+ installV->addWidget(footer);+ outer->addWidget(installBox);++ // JSON preview+ auto* previewBox = new QGroupBox(tr("Configuration Preview"), this);+ auto* previewV = new QVBoxLayout(previewBox);+ jsonPreview_ = new QPlainTextEdit(previewBox);+ jsonPreview_->setReadOnly(true);+ QFont mf = jsonPreview_->font(); mf.setFamily("monospace"); jsonPreview_->setFont(mf);+ jsonPreview_->setMaximumHeight(180);+ previewV->addWidget(jsonPreview_);+ auto* previewFooter = new QLabel(+ tr("This is the JSON that will be merged into the mcpServers section of your config file."),+ previewBox);+ previewFooter->setStyleSheet("color: palette(mid); font-size: small;");+ previewFooter->setWordWrap(true);+ previewV->addWidget(previewFooter);+ outer->addWidget(previewBox);++ // Manual steps+ auto* stepsBox = new QGroupBox(tr("Manual Steps"), this);+ auto* stepsV = new QVBoxLayout(stepsBox);+ const QStringList steps = {+ tr("Click \"Install\" above, or copy the JSON manually"),+ tr("If manual: open the config file"),+ tr("Paste the JSON inside \"mcpServers\": { ... }"),+ tr("Save the file and restart the client"),+ tr("Ask: \"List my database connections\""),+ };+ for (int i = 0; i < steps.size(); ++i) {+ auto* row = new QLabel(stepsBox);+ row->setTextFormat(Qt::RichText);+ row->setWordWrap(true);+ row->setText(QString(+ "<b><span style='color:#378add;'>%1.</span></b> %2").arg(i + 1).arg(steps[i]));+ stepsV->addWidget(row);+ }+ outer->addWidget(stepsBox);++ outer->addStretch();+ hostH->addWidget(content, 0, Qt::AlignTop);+ hostH->addStretch();+ scroll->setWidget(host);+}++void MCPSetupView::onClientChanged() {+ configPathLabel_->setText(configPathForSelected());+ jsonPreview_->setPlainText(configJsonForSelected());+ installBtn_->setText(tr("Install for %1").arg(clientCombo_->currentText()));+}++QString MCPSetupView::configPathForSelected() const {+ QString id = clientCombo_->currentData().toString();+ for (const auto& c : kClients) if (id == c.id) return c.pathTemplate;+ return {};+}++QString MCPSetupView::configJsonForSelected() const {+ const QString exe = QCoreApplication::applicationFilePath();+ nlohmann::json j;+ j["mcpServers"]["gridex"] = {+ {"command", exe.toStdString()},+ {"args", nlohmann::json::array({"--mcp-stdio"})},+ };+ return QString::fromStdString(j.dump(2));+}++void MCPSetupView::onCopyClicked() {+ QApplication::clipboard()->setText(jsonPreview_->toPlainText());+ copyBtn_->setText(tr("Copied"));+ QTimer::singleShot(2000, this, [this] { copyBtn_->setText(tr("Copy")); });+}++void MCPSetupView::onOpenPathClicked() {+ QFileInfo fi(expand(configPathForSelected()));+ QDir dir = fi.dir();+ if (!dir.exists()) dir.mkpath(".");+ QDesktopServices::openUrl(QUrl::fromLocalFile(dir.absolutePath()));+}++void MCPSetupView::onInstallClicked() {+ const QString path = expand(configPathForSelected());+ const QString exe = QCoreApplication::applicationFilePath();++ QFileInfo fi(path);+ QDir dir = fi.dir();+ if (!dir.exists() && !dir.mkpath(".")) {+ QMessageBox::warning(this, tr("Install failed"),+ tr("Could not create config directory: %1").arg(dir.absolutePath()));+ return;+ }++ nlohmann::json existing = nlohmann::json::object();+ QFile file(path);+ if (file.exists()) {+ if (file.open(QIODevice::ReadOnly)) {+ QByteArray data = file.readAll();+ file.close();+ if (!data.isEmpty()) {+ try {+ existing = nlohmann::json::parse(data.toStdString());+ } catch (const std::exception&) {+ QMessageBox::warning(this, tr("Install failed"),+ tr("Existing config file is not valid JSON. Please fix or delete it, then try again."));+ return;+ }+ }+ // Backup+ QFile::copy(path, path + ".bak");+ }+ }++ nlohmann::json entry = {+ {"command", exe.toStdString()},+ {"args", nlohmann::json::array({"--mcp-stdio"})},+ };++ if (!existing.contains("mcpServers") || !existing["mcpServers"].is_object()) {+ existing["mcpServers"] = nlohmann::json::object();+ }+ existing["mcpServers"]["gridex"] = entry;++ if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {+ QMessageBox::warning(this, tr("Install failed"),+ tr("Could not write config file: %1").arg(path));+ return;+ }+ file.write(QByteArray::fromStdString(existing.dump(2)));+ file.close();++ QMessageBox::information(this, tr("Installed"),+ tr("Gridex has been added to %1's config. Restart %1 to apply.").arg(clientCombo_->currentText()));+}++} // namespace gridexdiff --git a/linux/src/Presentation/Views/MCP/MCPSetupView.h b/linux/src/Presentation/Views/MCP/MCPSetupView.hnew file mode 100644index 0000000..351a69b--- /dev/null+++ b/linux/src/Presentation/Views/MCP/MCPSetupView.h@@ -0,0 +1,35 @@+#pragma once++#include <QWidget>++#include <QComboBox>+class QLabel;+class QPlainTextEdit;+class QPushButton;++namespace gridex {++class MCPSetupView : public QWidget {+ Q_OBJECT+public:+ explicit MCPSetupView(QWidget* parent = nullptr);++private slots:+ void onClientChanged();+ void onCopyClicked();+ void onInstallClicked();+ void onOpenPathClicked();++private:+ void buildUi();+ QString configPathForSelected() const;+ QString configJsonForSelected() const;++ QComboBox* clientCombo_ = nullptr;+ QLabel* configPathLabel_ = nullptr;+ QPlainTextEdit* jsonPreview_ = nullptr;+ QPushButton* installBtn_ = nullptr;+ QPushButton* copyBtn_ = nullptr;+};++} // namespace gridexdiff --git a/linux/src/Presentation/Views/MCP/MCPStyle.h b/linux/src/Presentation/Views/MCP/MCPStyle.hnew file mode 100644index 0000000..930c2d2--- /dev/null+++ b/linux/src/Presentation/Views/MCP/MCPStyle.h@@ -0,0 +1,210 @@+#pragma once++// Shared stylesheet for MCPWindow and its 5 tab views.+//+// IMPORTANT: The app ships a global stylesheet (resources/style-dark.qss)+// that sets `QWidget { background-color: #1e1e2e; }`. That rule matches+// every widget in the app including our MCP children. To win in the+// cascade, every rule here is prefixed with `#mcpRoot` (the object name+// of MCPWindow) — that raises specificity above the global QWidget rule.++#include <QString>++namespace gridex {++inline QString kMCPStyleSheet = QStringLiteral(R"(+/* Root + all descendant QWidgets inside the MCP window get a uniform+ * surface color (matches the header). Individual tiles and controls then+ * override as needed below. */+QDialog#mcpRoot {+ background-color: #1e1e2e;+}+QDialog#mcpRoot QWidget {+ background-color: transparent;+}++/* ---- Header bar ---- */+QDialog#mcpRoot QWidget#mcpHeader {+ background-color: #1e1e2e;+ border-bottom: 1px solid rgba(255, 255, 255, 30);+}+QDialog#mcpRoot QLabel#mcpHeaderTitle {+ font-size: 15px;+ font-weight: 600;+ color: #cdd6f4;+}+QDialog#mcpRoot QLabel#mcpHeaderDetail {+ font-size: 11px;+ color: rgba(205, 214, 244, 160);+}+QDialog#mcpRoot QLabel#mcpStatusDot {+ background-color: rgba(255, 255, 255, 25);+ border-radius: 12px;+}++/* ---- Tab bar ---- */+QDialog#mcpRoot QTabWidget#mcpTabs::pane {+ border: none;+ background: #1e1e2e;+}+QDialog#mcpRoot QTabBar::tab {+ padding: 10px 22px;+ margin: 0 2px;+ border: none;+ background: transparent;+ color: rgba(205, 214, 244, 140);+ font-size: 13px;+}+QDialog#mcpRoot QTabBar::tab:selected {+ color: #cdd6f4;+ border-bottom: 2px solid #89b4fa;+ font-weight: 600;+}+QDialog#mcpRoot QTabBar::tab:hover:!selected {+ color: #cdd6f4;+}++/* ---- Scroll area ---- */+QDialog#mcpRoot QScrollArea#mcpScroll,+QDialog#mcpRoot QScrollArea#mcpScroll > QWidget,+QDialog#mcpRoot QScrollArea#mcpScroll > QWidget > QWidget {+ background: #1e1e2e;+ border: none;+}++/* ---- Card tile ---- */+QDialog#mcpRoot QFrame[card="true"] {+ background-color: #313244;+ border: 1px solid rgba(255, 255, 255, 20);+ border-radius: 8px;+}++/* ---- Section title ---- */+QDialog#mcpRoot QLabel[role="section-title"] {+ font-size: 14px;+ font-weight: 600;+ color: #cdd6f4;+ background-color: transparent;+}+QDialog#mcpRoot QLabel[role="muted"] {+ color: rgba(205, 214, 244, 170);+ font-size: 12px;+}+QDialog#mcpRoot QLabel[role="hint"] {+ color: rgba(205, 214, 244, 130);+ font-size: 11px;+}+QDialog#mcpRoot QLabel[role="mono"] {+ font-family: "Menlo", "Consolas", monospace;+ font-size: 12px;+ color: rgba(205, 214, 244, 170);+}++/* ---- Buttons ---- */+QDialog#mcpRoot QPushButton[accent="true"] {+ background-color: #89b4fa;+ color: #1e1e2e;+ border: none;+ border-radius: 5px;+ padding: 7px 18px;+ font-weight: 600;+ font-size: 12px;+}+QDialog#mcpRoot QPushButton[accent="true"]:hover { background-color: #a6c1fc; }+QDialog#mcpRoot QPushButton[accent="true"]:pressed { background-color: #6b96e0; }++QDialog#mcpRoot QPushButton[danger="true"] {+ background-color: #f38ba8;+ color: #1e1e2e;+ border: none;+ border-radius: 5px;+ padding: 7px 18px;+ font-weight: 600;+ font-size: 12px;+}+QDialog#mcpRoot QPushButton[danger="true"]:hover { background-color: #f59db7; }+QDialog#mcpRoot QPushButton[danger="true"]:pressed { background-color: #d77b96; }++QDialog#mcpRoot QPushButton[link="true"] {+ background: transparent;+ border: none;+ color: #89b4fa;+ padding: 4px 6px;+ text-align: left;+ font-size: 12px;+ font-weight: 500;+}+QDialog#mcpRoot QPushButton[link="true"]:hover { text-decoration: underline; }++/* ---- Inputs ---- */+QDialog#mcpRoot QLineEdit#mcpSearch {+ padding: 7px 10px;+ border: 1px solid rgba(255, 255, 255, 30);+ border-radius: 6px;+ background: #181825;+ color: #cdd6f4;+}+QDialog#mcpRoot QLineEdit#mcpSearch:focus { border-color: #89b4fa; }++QDialog#mcpRoot QComboBox {+ padding: 5px 10px;+ border: 1px solid rgba(255, 255, 255, 30);+ border-radius: 6px;+ background: #181825;+ color: #cdd6f4;+ min-height: 24px;+}+QDialog#mcpRoot QComboBox:focus { border-color: #89b4fa; }++QDialog#mcpRoot QSpinBox {+ padding: 4px 8px;+ border: 1px solid rgba(255, 255, 255, 30);+ border-radius: 4px;+ background: #181825;+ color: #cdd6f4;+}++QDialog#mcpRoot QPlainTextEdit {+ background: #181825;+ color: #cdd6f4;+ border: 1px solid rgba(255, 255, 255, 30);+ border-radius: 6px;+}++/* ---- Tables ---- */+QDialog#mcpRoot QTableWidget {+ background: #1e1e2e;+ alternate-background-color: rgba(255, 255, 255, 10);+ border: 1px solid rgba(255, 255, 255, 20);+ border-radius: 6px;+ gridline-color: transparent;+ selection-background-color: rgba(137, 180, 250, 80);+ selection-color: #cdd6f4;+ color: #cdd6f4;+}+QDialog#mcpRoot QTableWidget::item { padding: 8px 10px; }+QDialog#mcpRoot QHeaderView::section {+ background: #313244;+ color: rgba(205, 214, 244, 200);+ padding: 8px 10px;+ border: none;+ border-bottom: 1px solid rgba(255, 255, 255, 30);+ font-size: 11px;+ font-weight: 600;+}++/* ---- Info banner ---- */+QDialog#mcpRoot QFrame#mcpBanner {+ background-color: rgba(137, 180, 250, 40);+ border: 1px solid rgba(137, 180, 250, 80);+ border-radius: 6px;+}++/* ---- Splitter handle ---- */+QDialog#mcpRoot QSplitter::handle {+ background-color: rgba(255, 255, 255, 30);+ width: 1px;+}+)");++} // namespace gridexdiff --git a/linux/src/Presentation/Views/MCP/MCPWindow.cpp b/linux/src/Presentation/Views/MCP/MCPWindow.cppnew file mode 100644index 0000000..51fc65e--- /dev/null+++ b/linux/src/Presentation/Views/MCP/MCPWindow.cpp@@ -0,0 +1,147 @@+#include "Presentation/Views/MCP/MCPWindow.h"++#include <QFrame>+#include <QGraphicsDropShadowEffect>+#include <QHBoxLayout>+#include <QLabel>+#include <QPushButton>+#include <QStyle>+#include <QTabBar>+#include <QTabWidget>+#include <QVBoxLayout>++#include "Presentation/Views/MCP/MCPActivityView.h"+#include "Presentation/Views/MCP/MCPAdvancedView.h"+#include "Presentation/Views/MCP/MCPConnectionsView.h"+#include "Presentation/Views/MCP/MCPOverviewView.h"+#include "Presentation/Views/MCP/MCPSetupView.h"+#include "Presentation/Views/MCP/MCPStyle.h"+#include "Presentation/Views/MCP/MCPWindowState.h"+#include "Services/MCP/MCPServer.h"++namespace gridex {++MCPWindow::MCPWindow(mcp::MCPServer* server,+ IConnectionRepository* repo,+ QWidget* parent)+ : QDialog(parent), server_(server) {+ setObjectName(QStringLiteral("mcpRoot"));+ setWindowTitle(tr("MCP Server"));+ setModal(false);+ resize(1000, 700);+ setMinimumSize(860, 580);++ // Apply the MCP stylesheet to the whole subtree.+ setStyleSheet(kMCPStyleSheet);++ state_ = new MCPWindowState(server_, repo, this);+ buildUi();+ state_->start();+ refreshStatus();+}++MCPWindow::~MCPWindow() { state_->stop(); }++void MCPWindow::buildUi() {+ auto* outer = new QVBoxLayout(this);+ outer->setContentsMargins(0, 0, 0, 0);+ outer->setSpacing(0);++ // ---------------- Header ----------------+ auto* header = new QWidget(this);+ header->setObjectName(QStringLiteral("mcpHeader"));+ auto* hL = new QHBoxLayout(header);+ hL->setContentsMargins(24, 14, 24, 14);+ hL->setSpacing(12);++ statusDot_ = new QLabel(header);+ statusDot_->setObjectName(QStringLiteral("mcpStatusDot"));+ statusDot_->setFixedSize(24, 24);+ statusDot_->setAlignment(Qt::AlignCenter);++ auto* titles = new QVBoxLayout();+ titles->setSpacing(0);+ titles->setContentsMargins(0, 0, 0, 0);+ statusTitle_ = new QLabel(tr("MCP Server"), header);+ statusTitle_->setObjectName(QStringLiteral("mcpHeaderTitle"));+ statusDetail_ = new QLabel(header);+ statusDetail_->setObjectName(QStringLiteral("mcpHeaderDetail"));+ titles->addWidget(statusTitle_);+ titles->addWidget(statusDetail_);++ toggleBtn_ = new QPushButton(tr("Start Server"), header);+ toggleBtn_->setMinimumWidth(120);+ toggleBtn_->setCursor(Qt::PointingHandCursor);+ toggleBtn_->setProperty("accent", true);+ connect(toggleBtn_, &QPushButton::clicked, this, &MCPWindow::onToggleServerClicked);++ hL->addWidget(statusDot_);+ hL->addLayout(titles, 1);+ hL->addStretch();+ hL->addWidget(toggleBtn_);+ outer->addWidget(header);++ // ---------------- Tabs ----------------+ tabs_ = new QTabWidget(this);+ tabs_->setObjectName(QStringLiteral("mcpTabs"));+ tabs_->setDocumentMode(true);+ tabs_->tabBar()->setExpanding(false);++ auto* overview = new MCPOverviewView(state_, tabs_);+ auto* connections = new MCPConnectionsView(state_, tabs_);+ auto* activity = new MCPActivityView(state_, tabs_);+ auto* setup = new MCPSetupView(tabs_);+ auto* advanced = new MCPAdvancedView(state_, tabs_);+ tabs_->addTab(overview, tr("Overview"));+ tabs_->addTab(connections, tr("Connections"));+ tabs_->addTab(activity, tr("Activity"));+ tabs_->addTab(setup, tr("Setup"));+ tabs_->addTab(advanced, tr("Config"));+ connect(overview, &MCPOverviewView::switchToTab, this, [this](MCPOverviewView::Tab t) {+ tabs_->setCurrentIndex(static_cast<int>(t));+ });+ outer->addWidget(tabs_, 1);++ connect(state_, &MCPWindowState::serverRunningChanged, this, &MCPWindow::refreshStatus);+ connect(state_, &MCPWindowState::uptimeChanged, this, &MCPWindow::refreshStatus);+}++void MCPWindow::onToggleServerClicked() { state_->toggleServer(); }++void MCPWindow::selectTab(int index) { if (tabs_) tabs_->setCurrentIndex(index); }++void MCPWindow::refreshStatus() {+ const bool running = state_->isServerRunning();++ // The status dot uses a dynamic property so QSS can swap the background.+ statusDot_->setProperty("running", running);+ statusDot_->style()->unpolish(statusDot_);+ statusDot_->style()->polish(statusDot_);++ // Small inner pip painted via text (no pixmap needed).+ statusDot_->setText(QString("<span style='color:%1; font-size:14px;'>●</span>")+ .arg(running ? "#3ea82f" : "#888"));++ if (!running) {+ statusDetail_->setText(tr("Server is stopped"));+ } else {+ int up = state_->uptimeSeconds();+ if (up > 0) {+ int h = up / 3600, m = (up % 3600) / 60, s = up % 60;+ QString uptime = h > 0 ? QString("%1h %2m").arg(h).arg(m)+ : m > 0 ? QString("%1m %2s").arg(m).arg(s)+ : QString("%1s").arg(s);+ statusDetail_->setText(tr("Running · %1").arg(uptime));+ } else {+ statusDetail_->setText(tr("Running"));+ }+ }++ toggleBtn_->setText(running ? tr("Stop Server") : tr("Start Server"));+ toggleBtn_->setProperty("accent", !running);+ toggleBtn_->setProperty("danger", running);+ toggleBtn_->style()->unpolish(toggleBtn_);+ toggleBtn_->style()->polish(toggleBtn_);+}++} // namespace gridexdiff --git a/linux/src/Presentation/Views/MCP/MCPWindow.h b/linux/src/Presentation/Views/MCP/MCPWindow.hnew file mode 100644index 0000000..1c3821e--- /dev/null+++ b/linux/src/Presentation/Views/MCP/MCPWindow.h@@ -0,0 +1,44 @@+#pragma once++#include <QDialog>+#include <memory>++class QLabel;+class QPushButton;+class QTabWidget;++namespace gridex {++class IConnectionRepository;+class MCPWindowState;+namespace mcp { class MCPServer; }++// Top-level MCP Server management window. Non-modal: call show().+class MCPWindow : public QDialog {+ Q_OBJECT+public:+ explicit MCPWindow(mcp::MCPServer* server,+ IConnectionRepository* connectionRepo,+ QWidget* parent = nullptr);+ ~MCPWindow() override;++public slots:+ void selectTab(int index);++private slots:+ void refreshStatus();+ void onToggleServerClicked();++private:+ void buildUi();++ mcp::MCPServer* server_;+ MCPWindowState* state_; // QObject child+ QLabel* statusTitle_ = nullptr;+ QLabel* statusDetail_ = nullptr;+ QLabel* statusDot_ = nullptr;+ QPushButton* toggleBtn_ = nullptr;+ QTabWidget* tabs_ = nullptr;+};++} // namespace gridexdiff --git a/linux/src/Presentation/Views/MCP/MCPWindowState.cpp b/linux/src/Presentation/Views/MCP/MCPWindowState.cppnew file mode 100644index 0000000..b659eb1--- /dev/null+++ b/linux/src/Presentation/Views/MCP/MCPWindowState.cpp@@ -0,0 +1,108 @@+#include "Presentation/Views/MCP/MCPWindowState.h"++#include <QSettings>+#include <chrono>++#include "Domain/Repositories/IConnectionRepository.h"+#include "Services/MCP/MCPServer.h"++namespace gridex {++MCPWindowState::MCPWindowState(mcp::MCPServer* server,+ IConnectionRepository* connectionRepo,+ QObject* parent)+ : QObject(parent), server_(server), connectionRepo_(connectionRepo) {+ uptimeTimer_ = new QTimer(this);+ uptimeTimer_->setInterval(1000);+ connect(uptimeTimer_, &QTimer::timeout, this, [this] { emit uptimeChanged(); });+}++void MCPWindowState::start() {+ reloadConnections();+ reloadRecentActivity();+ uptimeTimer_->start();+}++void MCPWindowState::stop() {+ uptimeTimer_->stop();+}++int MCPWindowState::uptimeSeconds() const noexcept {+ if (!server_ || !server_->isRunning()) return 0;+ auto start = server_->startTime();+ auto now = std::chrono::system_clock::now();+ return static_cast<int>(std::chrono::duration_cast<std::chrono::seconds>(now - start).count());+}++bool MCPWindowState::isServerRunning() const noexcept {+ return server_ && server_->isRunning();+}++void MCPWindowState::loadModeFromSettings(const QString& id, MCPConnectionMode fallback) {+ QSettings s;+ QString key = QStringLiteral("mcp.connectionMode.") + id;+ QString raw = s.value(key).toString();+ auto parsed = mcpConnectionModeFromRaw(raw.toStdString());+ auto mode = parsed.value_or(fallback);+ if (server_) server_->setConnectionMode(id.toStdString(), mode);+}++void MCPWindowState::persistMode(const QString& id, MCPConnectionMode mode) {+ QSettings s;+ QString key = QStringLiteral("mcp.connectionMode.") + id;+ s.setValue(key, QString::fromStdString(std::string(rawValue(mode))));+}++void MCPWindowState::reloadConnections() {+ connections_.clear();+ if (!connectionRepo_) { emit connectionsChanged(); return; }+ auto configs = connectionRepo_->fetchAll();+ for (auto& c : configs) {+ QString id = QString::fromStdString(c.id);+ // Seed permission engine from QSettings (default: Locked).+ loadModeFromSettings(id, MCPConnectionMode::Locked);+ MCPConnectionRow row;+ row.config = std::move(c);+ row.mode = server_ ? server_->getConnectionMode(row.config.id)+ : MCPConnectionMode::Locked;+ connections_.push_back(std::move(row));+ }+ emit connectionsChanged();+}++void MCPWindowState::reloadRecentActivity() {+ if (!server_) return;+ recent_ = server_->auditLogger().recentEntries(10);+ emit recentActivityChanged();+}++void MCPWindowState::reloadFullActivity() {+ if (!server_) return;+ full_ = server_->auditLogger().recentEntries(500);+ emit fullActivityChanged();+}++void MCPWindowState::updateConnectionMode(const QString& connectionId, MCPConnectionMode mode) {+ if (!server_) return;+ server_->setConnectionMode(connectionId.toStdString(), mode);+ persistMode(connectionId, mode);+ for (auto& row : connections_) {+ if (QString::fromStdString(row.config.id) == connectionId) {+ row.mode = mode;+ break;+ }+ }+ emit connectionsChanged();+}++void MCPWindowState::toggleServer() {+ if (!server_) return;+ if (server_->isRunning()) server_->stop();+ else server_->start();+ QSettings s;+ s.setValue(QStringLiteral("mcp.enabled"), server_->isRunning());+ emit serverRunningChanged();+ emit uptimeChanged();+}++} // namespace gridexdiff --git a/linux/src/Presentation/Views/MCP/MCPWindowState.h b/linux/src/Presentation/Views/MCP/MCPWindowState.hnew file mode 100644index 0000000..54b5245--- /dev/null+++ b/linux/src/Presentation/Views/MCP/MCPWindowState.h@@ -0,0 +1,70 @@+#pragma once++// State holder for the MCP window. Lives for the lifetime of the window,+// drives the 5 tab views via Qt signals.++#include <QObject>+#include <QTimer>+#include <QVector>+#include <chrono>+#include <vector>++#include "Core/Models/Database/ConnectionConfig.h"+#include "Core/Enums/MCPConnectionMode.h"+#include "Services/MCP/Protocol.h"++namespace gridex {+class IConnectionRepository;+namespace mcp { class MCPServer; }++struct MCPConnectionRow {+ ConnectionConfig config;+ MCPConnectionMode mode = MCPConnectionMode::Locked;+};++class MCPWindowState : public QObject {+ Q_OBJECT+public:+ MCPWindowState(mcp::MCPServer* server,+ IConnectionRepository* connectionRepo,+ QObject* parent = nullptr);++ void start();+ void stop();++ const QVector<MCPConnectionRow>& connections() const noexcept { return connections_; }+ const std::vector<mcp::MCPAuditEntry>& recentActivity() const noexcept { return recent_; }+ const std::vector<mcp::MCPAuditEntry>& fullActivity() const noexcept { return full_; }++ int uptimeSeconds() const noexcept;+ bool isServerRunning() const noexcept;++ mcp::MCPServer* server() const noexcept { return server_; }++public slots:+ void reloadConnections();+ void reloadRecentActivity();+ void reloadFullActivity();+ void updateConnectionMode(const QString& connectionId, MCPConnectionMode mode);+ void toggleServer();++signals:+ void connectionsChanged();+ void recentActivityChanged();+ void fullActivityChanged();+ void uptimeChanged();+ void serverRunningChanged();++private:+ void loadModeFromSettings(const QString& id, MCPConnectionMode fallback);+ void persistMode(const QString& id, MCPConnectionMode mode);++ mcp::MCPServer* server_;+ IConnectionRepository* connectionRepo_;+ QVector<MCPConnectionRow> connections_;+ std::vector<mcp::MCPAuditEntry> recent_;+ std::vector<mcp::MCPAuditEntry> full_;+ QTimer* uptimeTimer_ = nullptr;+};++} // namespace gridexdiff --git a/linux/src/Presentation/Views/Main/WorkspaceView.cpp b/linux/src/Presentation/Views/Main/WorkspaceView.cppnew file mode 100644index 0000000..52ca01f--- /dev/null+++ b/linux/src/Presentation/Views/Main/WorkspaceView.cpp@@ -0,0 +1,579 @@+#include "Presentation/Views/Main/WorkspaceView.h"++#include <QFrame>+#include <QHBoxLayout>+#include <QLabel>+#include <QPushButton>+#include <QSplitter>+#include <QStackedWidget>+#include <QStyle>+#include <QTableView>+#include <QTimer>+#include <QVBoxLayout>++#include "Core/Enums/DatabaseType.h"+#include "Data/Keychain/SecretStore.h"+#include "Data/Persistence/AppDatabase.h"+#include "Presentation/ViewModels/WorkspaceState.h"+#include "Presentation/Views/CreateTable/CreateTableDialog.h"+#include "Presentation/Views/DataGrid/DataGridView.h"+#include "Presentation/Views/Redis/RedisKeyDetailView.h"+#include "Presentation/Views/MongoDB/MongoCollectionView.h"+#include "Data/Adapters/Redis/RedisAdapter.h"+#include "Data/Adapters/MongoDB/MongodbAdapter.h"+#include "Presentation/Views/DatabaseSwitcher/DatabaseSwitcherDialog.h"+#include "Presentation/Views/FunctionDetail/FunctionDetailView.h"+#include "Presentation/Views/Details/DetailsPanel.h"+#include "Presentation/Views/ERDiagram/ERDiagramView.h"+#include "Presentation/Views/QueryEditor/QueryEditorView.h"+#include "Presentation/Views/Sidebar/WorkspaceSidebar.h"+#include "Presentation/Views/StatusBar/StatusBarView.h"+#include "Presentation/Views/TabBar/WorkspaceTabBar.h"++namespace gridex {++WorkspaceView::WorkspaceView(WorkspaceState* state, SecretStore* secretStore,+ std::shared_ptr<AppDatabase> appDb, QWidget* parent)+ : QWidget(parent), state_(state), secretStore_(secretStore), appDb_(std::move(appDb)) {+ buildUi();+ if (state_) {+ connect(state_, &WorkspaceState::connectionOpened,+ this, &WorkspaceView::onConnectionOpened);+ connect(state_, &WorkspaceState::connectionClosed,+ this, &WorkspaceView::onConnectionClosed);+ }+}++void WorkspaceView::buildUi() {+ auto* outer = new QHBoxLayout(this);+ outer->setContentsMargins(0, 0, 0, 0);+ outer->setSpacing(0);++ // Horizontal splitter: [sidebar] | [mainHost] | [details]. Replaces the+ // old fixed-width boxes so the user can drag to resize each pane.+ rootSplitter_ = new QSplitter(Qt::Horizontal, this);+ rootSplitter_->setChildrenCollapsible(false);+ rootSplitter_->setHandleWidth(4);+ outer->addWidget(rootSplitter_);+ auto* root = rootSplitter_;++ // ---- Left sidebar ----+ sidebar_ = new WorkspaceSidebar(state_, appDb_, this);+ sidebar_->setMinimumWidth(180);+ connect(sidebar_, &WorkspaceSidebar::tableSelected,+ this, &WorkspaceView::onTableSelected);+ connect(sidebar_, &WorkspaceSidebar::tableDeleted,+ this, &WorkspaceView::onTableDeleted);+ connect(sidebar_, &WorkspaceSidebar::newTableRequested,+ this, &WorkspaceView::onNewTableRequested);+ connect(sidebar_, &WorkspaceSidebar::disconnectRequested,+ this, &WorkspaceView::disconnectRequested);+ connect(sidebar_, &WorkspaceSidebar::loadSavedQueryRequested, this,+ [this](const QString& sql) {+ onNewQueryTab();+ // The new tab's editor is now current in mainStack_+ auto* qe = qobject_cast<QueryEditorView*>(mainStack_->currentWidget());+ if (qe) qe->setSql(sql);+ });+ connect(sidebar_, &WorkspaceSidebar::functionSelected,+ this, &WorkspaceView::onFunctionSelected);+ connect(sidebar_, &WorkspaceSidebar::procedureSelected,+ this, &WorkspaceView::onProcedureSelected);+ root->addWidget(sidebar_);++ // leftDiv_ retained as a no-op placeholder so toggleSidebar still+ // references something; splitter handle does the actual separator.+ leftDiv_ = new QFrame(this);+ leftDiv_->setVisible(false);++ // ---- Center: toolbar row + TabBar + infoBar + content + StatusBar ----+ auto* mainHost = new QWidget(this);+ auto* mv = new QVBoxLayout(mainHost);+ mv->setContentsMargins(0, 0, 0, 0);+ mv->setSpacing(0);++ // Top bar: [sidebarBtn] [connDotBtn] [tabBar ...] [detailsBtn]+ auto* topBar = new QWidget(mainHost);+ topBar->setFixedHeight(38);+ auto* topH = new QHBoxLayout(topBar);+ topH->setContentsMargins(0, 0, 4, 0);+ topH->setSpacing(0);++ // Item 7: sidebar toggle button (☰)+ sidebarBtn_ = new QPushButton(QStringLiteral("☰"), topBar);+ sidebarBtn_->setFixedSize(28, 38);+ sidebarBtn_->setCheckable(true);+ sidebarBtn_->setChecked(true);+ sidebarBtn_->setToolTip(tr("Toggle Sidebar"));+ sidebarBtn_->setCursor(Qt::PointingHandCursor);+ sidebarBtn_->setProperty("toolbarIcon", true);+ connect(sidebarBtn_, &QPushButton::clicked, this, &WorkspaceView::toggleSidebar);+ topH->addWidget(sidebarBtn_);++ // Item 7: connection indicator dot button (●)+ connDotBtn_ = new QPushButton(QStringLiteral("●"), topBar);+ connDotBtn_->setObjectName(QStringLiteral("connDot"));+ connDotBtn_->setFixedSize(28, 38);+ connDotBtn_->setEnabled(false);+ connDotBtn_->setToolTip(tr("Connection status"));+ connDotBtn_->setProperty("connected", false);+ topH->addWidget(connDotBtn_);++ // ER Diagram button (hidden until a connection is open)+ erDiagramBtn_ = new QPushButton(QStringLiteral("⬡ ER"), topBar);+ erDiagramBtn_->setFixedSize(48, 38);+ erDiagramBtn_->setToolTip(tr("Open ER Diagram for current schema"));+ erDiagramBtn_->setVisible(false);+ erDiagramBtn_->setCursor(Qt::PointingHandCursor);+ erDiagramBtn_->setProperty("toolbarIcon", true);+ connect(erDiagramBtn_, &QPushButton::clicked,+ this, &WorkspaceView::onNewErDiagramTab);+ topH->addWidget(erDiagramBtn_);++ // Database switcher button (hidden until a connection is open)+ dbSwitcherBtn_ = new QPushButton(QStringLiteral("⬡ DB ▾"), topBar);+ dbSwitcherBtn_->setFixedHeight(38);+ dbSwitcherBtn_->setMinimumWidth(60);+ dbSwitcherBtn_->setToolTip(tr("Switch database"));+ dbSwitcherBtn_->setVisible(false);+ dbSwitcherBtn_->setCursor(Qt::PointingHandCursor);+ dbSwitcherBtn_->setProperty("toolbarIcon", true);+ connect(dbSwitcherBtn_, &QPushButton::clicked,+ this, &WorkspaceView::onOpenDatabaseSwitcher);+ topH->addWidget(dbSwitcherBtn_);++ tabBar_ = new WorkspaceTabBar(topBar);+ connect(tabBar_, &WorkspaceTabBar::newTabRequested,+ this, &WorkspaceView::onNewQueryTab);+ connect(tabBar_, &WorkspaceTabBar::tabSelected,+ this, &WorkspaceView::onTabSelected);+ connect(tabBar_, &WorkspaceTabBar::tabCloseRequested,+ this, &WorkspaceView::onTabCloseRequested);+ topH->addWidget(tabBar_, 1);++ // Toggle right panel+ detailsBtn_ = new QPushButton(QStringLiteral("⊟"), topBar);+ detailsBtn_->setCheckable(true);+ detailsBtn_->setChecked(true);+ detailsBtn_->setToolTip(tr("Toggle Details Panel"));+ detailsBtn_->setCursor(Qt::PointingHandCursor);+ detailsBtn_->setFixedSize(32, 38);+ detailsBtn_->setProperty("toolbarIcon", true);+ connect(detailsBtn_, &QPushButton::clicked, this, &WorkspaceView::toggleDetailsPanel);+ topH->addWidget(detailsBtn_);++ mv->addWidget(topBar);++ // Item 1: 28px connection info bar (hidden until connection opens)+ infoBar_ = new QLabel(mainHost);+ infoBar_->setFixedHeight(28);+ infoBar_->setAlignment(Qt::AlignVCenter | Qt::AlignLeft);+ infoBar_->setContentsMargins(12, 0, 12, 0);+ infoBar_->setVisible(false);+ mv->addWidget(infoBar_);++ mainStack_ = new QStackedWidget(mainHost);+ welcome_ = new QLabel(tr("Connected.\n\nDouble-click a table or press [+] to open a query tab."),+ mainStack_);+ welcome_->setAlignment(Qt::AlignCenter);+ mainStack_->addWidget(welcome_);+ mainStack_->setCurrentWidget(welcome_);+ mv->addWidget(mainStack_, 1);++ statusBar_ = new StatusBarView(mainHost);+ mv->addWidget(statusBar_);++ root->addWidget(mainHost);++ // ---- Right DetailsPanel ----+ detailsDiv_ = new QFrame(this);+ detailsDiv_->setVisible(false);++ detailsPanel_ = new DetailsPanel(secretStore_, state_, this);+ detailsPanel_->setMinimumWidth(220);+ root->addWidget(detailsPanel_);++ // Initial widths + stretch: only mainHost grows on window resize.+ root->setStretchFactor(0, 0);+ root->setStretchFactor(1, 1);+ root->setStretchFactor(2, 0);+ root->setSizes({280, 800, 340});+}++void WorkspaceView::toggleDetailsPanel() {+ const bool show = !detailsPanel_->isVisible();+ detailsPanel_->setVisible(show);+ detailsDiv_->setVisible(show);+ detailsBtn_->setChecked(show);+}++void WorkspaceView::toggleSidebar() {+ const bool show = !sidebar_->isVisible();+ sidebar_->setVisible(show);+ leftDiv_->setVisible(show);+ sidebarBtn_->setChecked(show);+}++void WorkspaceView::onTableSelected(const QString& schema, const QString& table) {+ if (!state_ || !state_->adapter()) return;+ const auto qualified = schema.isEmpty() ? table : (schema + "." + table);++ for (const auto& [id, w] : tabWidgets_) {+ if (w->property("gridex_table").toString() == qualified) {+ tabBar_->setActiveTab(QString::fromStdString(id));+ return;+ }+ }++ // MongoDB collections get a specialised document view.+ const bool isMongo = state_->adapter()->databaseType() == DatabaseType::MongoDB;+ if (isMongo) {+ auto* mongo = static_cast<MongodbAdapter*>(state_->adapter());+ auto* mv = new MongoCollectionView(mongo, table, mainStack_);+ mv->setProperty("gridex_table", qualified);+ mainStack_->addWidget(mv);+ const auto tabId = tabBar_->addTab(table);+ tabWidgets_[tabId.toStdString()] = mv;+ mainStack_->setCurrentWidget(mv);+ statusBar_->setSchema(schema);+ return;+ }++ // Redis keys get a specialised view; all other adapters use DataGridView.+ const bool isRedis = state_->adapter()->databaseType() == DatabaseType::Redis;+ if (isRedis) {+ auto* redis = static_cast<RedisAdapter*>(state_->adapter());+ auto* rv = new RedisKeyDetailView(redis, table, mainStack_);+ rv->setProperty("gridex_table", qualified);+ mainStack_->addWidget(rv);++ connect(rv, &RedisKeyDetailView::keyDeleted, this,+ [this](const QString& key) {+ // Close the tab and refresh the sidebar.+ const auto qualified2 = key;+ std::vector<std::string> toRemove;+ for (const auto& [id, w] : tabWidgets_) {+ if (w->property("gridex_table").toString() == qualified2)+ toRemove.push_back(id);+ }+ for (const auto& id : toRemove) {+ auto it = tabWidgets_.find(id);+ if (it != tabWidgets_.end()) {+ mainStack_->removeWidget(it->second);+ it->second->deleteLater();+ tabWidgets_.erase(it);+ }+ tabBar_->removeTab(QString::fromStdString(id));+ }+ if (tabWidgets_.empty()) mainStack_->setCurrentWidget(welcome_);+ if (sidebar_) sidebar_->refreshTree();+ });++ const auto tabId = tabBar_->addTab(table);+ tabWidgets_[tabId.toStdString()] = rv;+ mainStack_->setCurrentWidget(rv);+ statusBar_->setSchema(schema);+ return;+ }++ auto* dg = new DataGridView(mainStack_);+ dg->setProperty("gridex_table", qualified);+ dg->setAdapter(state_->adapter());+ mainStack_->addWidget(dg);++ connect(dg, &DataGridView::rowCountChanged, this,+ [this](int rows, int ms) {+ statusBar_->setRowCount(tr("%1 rows").arg(rows));+ statusBar_->setQueryTime(tr("%1ms").arg(ms));+ });++ connect(dg, &DataGridView::rowSelected, this,+ [this](const std::vector<std::pair<std::string, std::string>>& fields) {+ std::vector<DetailsPanel::FieldEntry> entries;+ entries.reserve(fields.size());+ for (const auto& [col, val] : fields)+ entries.push_back({col, val});+ detailsPanel_->setSelectedRow(entries);+ });++ connect(detailsPanel_, &DetailsPanel::fieldEdited, dg,+ [dg](int columnIndex, const QString& newValue) {+ auto* tv = dg->findChild<QTableView*>();+ if (!tv) return;+ const auto currentRow = tv->currentIndex().row();+ if (currentRow < 0) return;+ auto* model = tv->model();+ if (!model) return;+ const auto idx = model->index(currentRow, columnIndex);+ model->setData(idx, newValue, Qt::EditRole);+ });++ const auto tabId = tabBar_->addTab(qualified);+ tabWidgets_[tabId.toStdString()] = dg;+ mainStack_->setCurrentWidget(dg);+ dg->loadTable(schema, table);+ statusBar_->setSchema(schema);+}++void WorkspaceView::onNewQueryTab() {+ if (!state_ || !state_->adapter()) return;+ auto* qe = new QueryEditorView(mainStack_);+ qe->setAdapter(state_->adapter());+ mainStack_->addWidget(qe);++ connect(qe, &QueryEditorView::queryExecuted, this,+ [this](const QString& sql, int rows, int ms) {+ statusBar_->setRowCount(tr("%1 rows").arg(rows));+ statusBar_->setQueryTime(tr("%1ms").arg(ms));+ if (sidebar_) sidebar_->logQuery(sql, rows, ms);+ });+ connect(qe, &QueryEditorView::saveQueryRequested, this,+ [this](const QString& sql) {+ if (sidebar_) sidebar_->promptSaveQuery(sql);+ });++ const auto tabId = tabBar_->addTab(tr("Query"));+ tabWidgets_[tabId.toStdString()] = qe;+ mainStack_->setCurrentWidget(qe);+}++void WorkspaceView::onNewErDiagramTab() {+ if (!state_ || !state_->adapter()) return;++ // Determine the active schema from the status bar context (use nullopt for default).+ std::optional<std::string> schema;+ try {+ const auto db = state_->adapter()->currentDatabase();+ // listSchemas to check; leave schema as nullopt to use adapter default.+ (void)db;+ } catch (...) {}++ auto* er = new ERDiagramView(mainStack_);+ mainStack_->addWidget(er);++ const auto tabId = tabBar_->addTab(tr("ER Diagram"));+ tabWidgets_[tabId.toStdString()] = er;+ mainStack_->setCurrentWidget(er);++ // Load asynchronously — ERDiagramView::loadSchema is synchronous but schema+ // inspection may be slow; defer to next event loop tick so the tab appears first.+ QTimer::singleShot(0, er, [er, adapter = state_->adapter(), schema] {+ er->loadSchema(adapter, schema);+ });+}++void WorkspaceView::onTabSelected(const QString& id) {+ auto it = tabWidgets_.find(id.toStdString());+ if (it != tabWidgets_.end()) mainStack_->setCurrentWidget(it->second);+}++void WorkspaceView::onTabCloseRequested(const QString& id) {+ auto it = tabWidgets_.find(id.toStdString());+ if (it != tabWidgets_.end()) {+ mainStack_->removeWidget(it->second);+ it->second->deleteLater();+ tabWidgets_.erase(it);+ }+ tabBar_->removeTab(id);+ if (tabWidgets_.empty()) mainStack_->setCurrentWidget(welcome_);+}++void WorkspaceView::onTableDeleted(const QString& schema, const QString& table) {+ const auto qualified = schema.isEmpty() ? table : (schema + "." + table);+ // Close any open tab that shows the deleted table+ std::vector<std::string> toRemove;+ for (const auto& [id, w] : tabWidgets_) {+ if (w->property("gridex_table").toString() == qualified) {+ toRemove.push_back(id);+ }+ }+ for (const auto& id : toRemove) {+ auto it = tabWidgets_.find(id);+ if (it != tabWidgets_.end()) {+ mainStack_->removeWidget(it->second);+ it->second->deleteLater();+ tabWidgets_.erase(it);+ }+ tabBar_->removeTab(QString::fromStdString(id));+ }+ if (tabWidgets_.empty()) mainStack_->setCurrentWidget(welcome_);+}++void WorkspaceView::onNewTableRequested(const QString& schema) {+ if (!state_ || !state_->adapter()) return;+ auto* dlg = new CreateTableDialog(state_->adapter(), schema, this);+ connect(dlg, &CreateTableDialog::tableCreated, this,+ [this](const QString& /*tableName*/) {+ if (sidebar_) sidebar_->refreshTree();+ });+ dlg->setAttribute(Qt::WA_DeleteOnClose);+ dlg->exec();+}++void WorkspaceView::onFunctionSelected(const QString& schema, const QString& name) {+ if (!state_ || !state_->adapter()) return;+ const auto qualified = (schema.isEmpty() ? name : (schema + "." + name))+ + QStringLiteral(" [fn]");+ for (const auto& [id, w] : tabWidgets_) {+ if (w->property("gridex_routine").toString() == qualified) {+ tabBar_->setActiveTab(QString::fromStdString(id));+ return;+ }+ }+ auto* view = new FunctionDetailView(state_->adapter(), schema, name,+ false, mainStack_);+ view->setProperty("gridex_routine", qualified);+ mainStack_->addWidget(view);+ const auto tabId = tabBar_->addTab(name);+ tabWidgets_[tabId.toStdString()] = view;+ mainStack_->setCurrentWidget(view);+}++void WorkspaceView::onProcedureSelected(const QString& schema, const QString& name) {+ if (!state_ || !state_->adapter()) return;+ const auto qualified = (schema.isEmpty() ? name : (schema + "." + name))+ + QStringLiteral(" [proc]");+ for (const auto& [id, w] : tabWidgets_) {+ if (w->property("gridex_routine").toString() == qualified) {+ tabBar_->setActiveTab(QString::fromStdString(id));+ return;+ }+ }+ auto* view = new FunctionDetailView(state_->adapter(), schema, name,+ true, mainStack_);+ view->setProperty("gridex_routine", qualified);+ mainStack_->addWidget(view);+ const auto tabId = tabBar_->addTab(name);+ tabWidgets_[tabId.toStdString()] = view;+ mainStack_->setCurrentWidget(view);+}++void WorkspaceView::onOpenDatabaseSwitcher() {+ if (!state_ || !state_->adapter()) return;++ QString currentDb;+ try {+ const auto db = state_->adapter()->currentDatabase();+ if (db) currentDb = QString::fromStdString(*db);+ } catch (...) {}++ auto* dlg = new DatabaseSwitcherDialog(state_->adapter(), currentDb, this);+ connect(dlg, &DatabaseSwitcherDialog::databaseSelected, this,+ [this](const QString& dbName) {+ if (!state_ || !state_->adapter()) return;+ // Switch database: execute USE <db> for MySQL;+ // for PostgreSQL/SQLite reconnect with modified config.+ const DatabaseType dt = state_->adapter()->databaseType();+ try {+ if (dt == DatabaseType::MySQL) {+ state_->adapter()->executeRaw(+ "USE `" + dbName.toStdString() + "`");+ } else {+ // Reconnect silently — no HomeView flip.+ state_->switchDatabase(dbName.toStdString(), secretStore_);+ }+ } catch (...) {}++ // Update button label and reload sidebar+ dbSwitcherBtn_->setText(+ QStringLiteral("⬡ %1 ▾").arg(dbName));+ if (sidebar_) sidebar_->refreshTree();+ });+ dlg->setAttribute(Qt::WA_DeleteOnClose);+ dlg->exec();+}++void WorkspaceView::onConnectionOpened() {+ if (!state_) return;+ const auto& cfg = state_->config();+ const QString name = QString::fromUtf8(cfg.name.c_str());+ const QString host = QString::fromUtf8(cfg.displayHost().c_str());++ welcome_->setText(tr("Connected to %1.\n\nDouble-click a table or press [+] to open a query tab.")+ .arg(name));+ mainStack_->setCurrentWidget(welcome_);+ statusBar_->setConnection(tr("%1 — %2").arg(name, host));+ statusBar_->setSchema({});+ statusBar_->setRowCount({});+ statusBar_->setQueryTime({});+ detailsPanel_->clearSelectedRow();++ // Item 1: populate info bar.+ // serverVersion() may throw; fall back gracefully.+ QString version;+ try {+ if (state_->adapter()) {+ version = QString::fromStdString(state_->adapter()->serverVersion());+ }+ } catch (...) {}++ const QString dbType = QString::fromUtf8(+ displayName(cfg.databaseType).data(),+ static_cast<qsizetype>(displayName(cfg.databaseType).size()));+ const QString user = cfg.username+ ? QString::fromUtf8(cfg.username->c_str()) : QString{};+ const QString database = cfg.database+ ? QString::fromUtf8(cfg.database->c_str()) : QString{};++ QString infoText = QStringLiteral("● %1 · %2").arg(name, dbType);+ if (!version.isEmpty()) infoText += QStringLiteral(" %1").arg(version);+ if (!user.isEmpty()) infoText += QStringLiteral(" · %1").arg(user);+ if (!database.isEmpty()) infoText += QStringLiteral(" · %1").arg(database);++ infoBar_->setText(infoText);+ infoBar_->setVisible(true);++ // Show ER Diagram button now that a connection is live.+ erDiagramBtn_->setVisible(true);++ // Show database switcher button with current database name.+ {+ QString dbLabel = QStringLiteral("DB");+ const QString dbName = cfg.database+ ? QString::fromUtf8(cfg.database->c_str()) : QString{};+ if (!dbName.isEmpty()) dbLabel = dbName;+ dbSwitcherBtn_->setText(QStringLiteral("⬡ %1 ▾").arg(dbLabel));+ dbSwitcherBtn_->setVisible(true);+ }++ // Connection dot → active (Catppuccin green via style.qss).+ connDotBtn_->setProperty("connected", true);+ connDotBtn_->style()->unpolish(connDotBtn_);+ connDotBtn_->style()->polish(connDotBtn_);+}++void WorkspaceView::onConnectionClosed() {+ closeAllTabs();+ detailsPanel_->clearSelectedRow();+ welcome_->setText(tr("Disconnected."));+ mainStack_->setCurrentWidget(welcome_);+ statusBar_->setConnection({});+ statusBar_->setSchema({});+ statusBar_->setRowCount({});+ statusBar_->setQueryTime({});++ // Item 1: hide info bar on disconnect.+ infoBar_->setVisible(false);++ // Hide ER Diagram button when disconnected.+ erDiagramBtn_->setVisible(false);++ // Hide database switcher button when disconnected.+ dbSwitcherBtn_->setVisible(false);++ // Connection dot → inactive (gray via style.qss).+ connDotBtn_->setProperty("connected", false);+ connDotBtn_->style()->unpolish(connDotBtn_);+ connDotBtn_->style()->polish(connDotBtn_);+}++void WorkspaceView::closeAllTabs() {+ for (auto& [id, w] : tabWidgets_) {+ mainStack_->removeWidget(w);+ w->deleteLater();+ tabBar_->removeTab(QString::fromStdString(id));+ }+ tabWidgets_.clear();+}++}diff --git a/linux/src/Presentation/Views/Main/WorkspaceView.h b/linux/src/Presentation/Views/Main/WorkspaceView.hnew file mode 100644index 0000000..24812d3--- /dev/null+++ b/linux/src/Presentation/Views/Main/WorkspaceView.h@@ -0,0 +1,97 @@+#pragma once++#include <memory>+#include <QWidget>+#include <string>+#include <unordered_map>++class QFrame;+class QLabel;+class QPushButton;+class QSplitter;+class QStackedWidget;++namespace gridex {++class AppDatabase;+class DataGridView;+class DetailsPanel;+class FunctionDetailView;+class RedisKeyDetailView;+class MongoCollectionView;+class ERDiagramView;+class QueryEditorView;+class SecretStore;+class StatusBarView;+class WorkspaceSidebar;+class WorkspaceState;+class WorkspaceTabBar;++// Workspace: [Sidebar 280] | [Main: toolbar + infoBar + TabBar + content + StatusBar] | [DetailsPanel ~340]+// Item 1: 28px connection info bar between tab bar and content.+// Item 7: sidebar-toggle + connection indicator icon buttons left of tab bar.+class WorkspaceView : public QWidget {+ Q_OBJECT++public:+ explicit WorkspaceView(WorkspaceState* state,+ SecretStore* secretStore = nullptr,+ std::shared_ptr<AppDatabase> appDb = nullptr,+ QWidget* parent = nullptr);++public slots:+ void onNewQueryTab();+ void onNewErDiagramTab();+ void toggleDetailsPanel();+ void toggleSidebar();++signals:+ void disconnectRequested();++private slots:+ void onTableSelected(const QString& schema, const QString& table);+ void onTableDeleted(const QString& schema, const QString& table);+ void onNewTableRequested(const QString& schema);+ void onOpenDatabaseSwitcher();+ void onFunctionSelected(const QString& schema, const QString& name);+ void onProcedureSelected(const QString& schema, const QString& name);+ void onTabSelected(const QString& id);+ void onTabCloseRequested(const QString& id);+ void onConnectionOpened();+ void onConnectionClosed();++private:+ void buildUi();+ void closeAllTabs();++ WorkspaceState* state_ = nullptr;+ SecretStore* secretStore_ = nullptr;+ std::shared_ptr<AppDatabase> appDb_;+ QSplitter* rootSplitter_ = nullptr;+ WorkspaceSidebar* sidebar_ = nullptr;+ QFrame* leftDiv_ = nullptr;+ WorkspaceTabBar* tabBar_ = nullptr;+ QStackedWidget* mainStack_ = nullptr;+ QLabel* welcome_ = nullptr;+ QLabel* infoBar_ = nullptr; // Item 1: connection info+ StatusBarView* statusBar_ = nullptr;++ // Right details panel+ DetailsPanel* detailsPanel_ = nullptr;+ QFrame* detailsDiv_ = nullptr;+ QPushButton* detailsBtn_ = nullptr;++ // Item 7: left toolbar icon buttons+ QPushButton* sidebarBtn_ = nullptr;+ QPushButton* connDotBtn_ = nullptr;++ // ER Diagram toolbar button (shown only when connected)+ QPushButton* erDiagramBtn_ = nullptr;++ // Database switcher button (shown only when connected)+ QPushButton* dbSwitcherBtn_ = nullptr;++ std::unordered_map<std::string, QWidget*> tabWidgets_;+};++}diff --git a/linux/src/Presentation/Views/MongoDB/MongoCollectionView.cpp b/linux/src/Presentation/Views/MongoDB/MongoCollectionView.cppnew file mode 100644index 0000000..7b3f213--- /dev/null+++ b/linux/src/Presentation/Views/MongoDB/MongoCollectionView.cpp@@ -0,0 +1,369 @@+#include "Presentation/Views/MongoDB/MongoCollectionView.h"++#include <QApplication>+#include <QHBoxLayout>+#include <QInputDialog>+#include <QLabel>+#include <QLineEdit>+#include <QListWidget>+#include <QMessageBox>+#include <QPlainTextEdit>+#include <QPushButton>+#include <QSpinBox>+#include <QSplitter>+#include <QVBoxLayout>++#include "Data/Adapters/MongoDB/MongodbAdapter.h"++namespace gridex {++MongoCollectionView::MongoCollectionView(MongodbAdapter* adapter,+ const QString& collection,+ QWidget* parent)+ : QWidget(parent), adapter_(adapter), collection_(collection) {+ buildUi();+ reload();+}++void MongoCollectionView::buildUi() {+ auto* root = new QVBoxLayout(this);+ root->setContentsMargins(0, 0, 0, 0);+ root->setSpacing(0);++ // Toolbar+ auto* toolbar = new QWidget(this);+ toolbar->setFixedHeight(40);+ auto* th = new QHBoxLayout(toolbar);+ th->setContentsMargins(8, 4, 8, 4);+ th->setSpacing(6);++ titleLabel_ = new QLabel(collection_, toolbar);+ titleLabel_->setStyleSheet(QStringLiteral("font-weight: bold;"));+ th->addWidget(titleLabel_);++ th->addSpacing(8);++ filterEdit_ = new QLineEdit(toolbar);+ filterEdit_->setPlaceholderText(tr(R"(Filter JSON, e.g. {"name":"foo"})"));+ filterEdit_->setMinimumWidth(200);+ connect(filterEdit_, &QLineEdit::returnPressed, this, &MongoCollectionView::onRunFilter);+ th->addWidget(filterEdit_, 1);++ auto* limitLabel = new QLabel(tr("Limit:"), toolbar);+ th->addWidget(limitLabel);++ limitSpin_ = new QSpinBox(toolbar);+ limitSpin_->setRange(1, 1000);+ limitSpin_->setValue(50);+ limitSpin_->setFixedWidth(64);+ th->addWidget(limitSpin_);++ runBtn_ = new QPushButton(tr("Run"), toolbar);+ runBtn_->setFixedWidth(48);+ connect(runBtn_, &QPushButton::clicked, this, &MongoCollectionView::onRunFilter);+ th->addWidget(runBtn_);++ th->addSpacing(8);++ refreshBtn_ = new QPushButton(tr("⟳"), toolbar);+ refreshBtn_->setToolTip(tr("Refresh"));+ refreshBtn_->setFixedWidth(32);+ connect(refreshBtn_, &QPushButton::clicked, this, &MongoCollectionView::onRefresh);+ th->addWidget(refreshBtn_);++ insertBtn_ = new QPushButton(tr("+ Insert"), toolbar);+ connect(insertBtn_, &QPushButton::clicked, this, &MongoCollectionView::onInsert);+ th->addWidget(insertBtn_);++ deleteBtn_ = new QPushButton(tr("✕ Delete"), toolbar);+ connect(deleteBtn_, &QPushButton::clicked, this, &MongoCollectionView::onDeleteSelected);+ th->addWidget(deleteBtn_);++ root->addWidget(toolbar);++ // Separator+ auto* sep = new QFrame(this);+ sep->setFrameShape(QFrame::HLine);+ sep->setFrameShadow(QFrame::Sunken);+ root->addWidget(sep);++ // Split: doc list | json editor+ auto* splitter = new QSplitter(Qt::Horizontal, this);+ splitter->setHandleWidth(4);++ docList_ = new QListWidget(splitter);+ docList_->setMinimumWidth(200);+ connect(docList_, &QListWidget::itemClicked,+ this, &MongoCollectionView::onDocumentSelected);+ splitter->addWidget(docList_);++ auto* editorPane = new QWidget(splitter);+ auto* ev = new QVBoxLayout(editorPane);+ ev->setContentsMargins(4, 4, 4, 4);+ ev->setSpacing(4);++ jsonEditor_ = new QPlainTextEdit(editorPane);+ jsonEditor_->setPlaceholderText(tr("Select a document to edit…"));+ jsonEditor_->setFont(QFont(QStringLiteral("Monospace"), 11));+ ev->addWidget(jsonEditor_, 1);++ saveBtn_ = new QPushButton(tr("Save Document"), editorPane);+ saveBtn_->setEnabled(false);+ connect(saveBtn_, &QPushButton::clicked, this, &MongoCollectionView::onSaveDocument);+ ev->addWidget(saveBtn_);++ splitter->addWidget(editorPane);+ splitter->setStretchFactor(0, 0);+ splitter->setStretchFactor(1, 1);+ splitter->setSizes({260, 600});++ root->addWidget(splitter, 1);++ // Pagination bar+ auto* pagebar = new QWidget(this);+ pagebar->setFixedHeight(32);+ auto* ph = new QHBoxLayout(pagebar);+ ph->setContentsMargins(8, 2, 8, 2);+ ph->setSpacing(6);++ prevBtn_ = new QPushButton(tr("← Prev"), pagebar);+ prevBtn_->setEnabled(false);+ connect(prevBtn_, &QPushButton::clicked, this, &MongoCollectionView::onPrevPage);+ ph->addWidget(prevBtn_);++ pageLabel_ = new QLabel(pagebar);+ ph->addWidget(pageLabel_);++ nextBtn_ = new QPushButton(tr("Next →"), pagebar);+ nextBtn_->setEnabled(false);+ connect(nextBtn_, &QPushButton::clicked, this, &MongoCollectionView::onNextPage);+ ph->addWidget(nextBtn_);++ ph->addStretch(1);++ statusLabel_ = new QLabel(pagebar);+ ph->addWidget(statusLabel_);++ root->addWidget(pagebar);+}++void MongoCollectionView::reload() {+ currentSkip_ = 0;+ currentFilter_ = filterEdit_ ? filterEdit_->text().trimmed() : QString{};+ currentLimit_ = limitSpin_ ? limitSpin_->value() : 50;+ loadPage();+}++void MongoCollectionView::loadPage() {+ if (!adapter_) return;++ const std::string col = collection_.toStdString();+ const std::string filter = currentFilter_.toStdString();++ QApplication::setOverrideCursor(Qt::WaitCursor);+ try {+ totalCount_ = adapter_->countDocuments(col, filter);+ auto docs = adapter_->findDocuments(col, filter, currentLimit_, currentSkip_);++ docList_->clear();+ selectedIdJson_.clear();+ jsonEditor_->clear();+ saveBtn_->setEnabled(false);++ for (const auto& docJson : docs) {+ QString qjson = QString::fromStdString(docJson);+ // Extract _id value for display label+ QString label = qjson;+ const int oidStart = qjson.indexOf(QStringLiteral("\"$oid\""));+ const int strStart = qjson.indexOf(QStringLiteral("\"_id\""));+ if (oidStart != -1) {+ // ObjectId: find next string value after "$oid"+ const int colon = qjson.indexOf(':', oidStart);+ const int q1 = qjson.indexOf('"', colon + 1);+ const int q2 = qjson.indexOf('"', q1 + 1);+ if (q1 != -1 && q2 != -1)+ label = qjson.mid(q1 + 1, q2 - q1 - 1);+ } else if (strStart != -1) {+ const int colon = qjson.indexOf(':', strStart + 5);+ if (colon != -1) {+ const int q1 = qjson.indexOf('"', colon + 1);+ const int q2 = q1 != -1 ? qjson.indexOf('"', q1 + 1) : -1;+ if (q1 != -1 && q2 != -1)+ label = qjson.mid(q1 + 1, q2 - q1 - 1);+ }+ }+ // Append a short preview of remaining fields+ const int previewEnd = qjson.indexOf(',', 0);+ if (previewEnd != -1 && qjson.length() > previewEnd + 2) {+ const QString preview = qjson.mid(previewEnd + 1, 60).simplified();+ label += QStringLiteral(" — ") + preview + QStringLiteral("…");+ }++ auto* item = new QListWidgetItem(label);+ item->setData(Qt::UserRole, qjson);+ docList_->addItem(item);+ }++ updatePagination(totalCount_);+ statusLabel_->setText(tr("%1 documents").arg(totalCount_));+ } catch (const std::exception& ex) {+ showError(QString::fromLocal8Bit(ex.what()));+ }+ QApplication::restoreOverrideCursor();+}++void MongoCollectionView::updatePagination(long total) {+ const int pages = currentLimit_ > 0+ ? static_cast<int>((total + currentLimit_ - 1) / currentLimit_) : 1;+ const int currentPage = currentLimit_ > 0 ? currentSkip_ / currentLimit_ + 1 : 1;+ pageLabel_->setText(tr("Page %1 / %2").arg(currentPage).arg(pages));+ prevBtn_->setEnabled(currentSkip_ > 0);+ nextBtn_->setEnabled(currentSkip_ + currentLimit_ < static_cast<int>(total));+}++void MongoCollectionView::onRefresh() {+ reload();+}++void MongoCollectionView::onRunFilter() {+ currentFilter_ = filterEdit_->text().trimmed();+ currentLimit_ = limitSpin_->value();+ currentSkip_ = 0;+ loadPage();+}++void MongoCollectionView::onDocumentSelected(QListWidgetItem* item) {+ if (!item) return;+ const QString json = item->data(Qt::UserRole).toString();+ jsonEditor_->setPlainText(json);++ // Extract _id filter JSON for updates/deletes+ selectedIdJson_ = buildIdFilter(json);+ saveBtn_->setEnabled(!selectedIdJson_.isEmpty());+}++QString MongoCollectionView::buildIdFilter(const QString& docJson) const {+ // Look for "$oid" pattern → ObjectId+ const int oidStart = docJson.indexOf(QStringLiteral("\"$oid\""));+ if (oidStart != -1) {+ const int colon = docJson.indexOf(':', oidStart);+ const int q1 = docJson.indexOf('"', colon + 1);+ const int q2 = q1 != -1 ? docJson.indexOf('"', q1 + 1) : -1;+ if (q1 != -1 && q2 != -1) {+ const QString oid = docJson.mid(q1 + 1, q2 - q1 - 1);+ return QStringLiteral("{\"_id\":{\"$oid\":\"%1\"}}").arg(oid);+ }+ }+ // Fallback: string _id+ const int idStart = docJson.indexOf(QStringLiteral("\"_id\""));+ if (idStart != -1) {+ const int colon = docJson.indexOf(':', idStart + 5);+ if (colon != -1) {+ const int q1 = docJson.indexOf('"', colon + 1);+ const int q2 = q1 != -1 ? docJson.indexOf('"', q1 + 1) : -1;+ if (q1 != -1 && q2 != -1) {+ const QString sid = docJson.mid(q1 + 1, q2 - q1 - 1);+ return QStringLiteral("{\"_id\":\"%1\"}").arg(sid);+ }+ }+ }+ return {};+}++void MongoCollectionView::onSaveDocument() {+ if (!adapter_ || selectedIdJson_.isEmpty()) return;+ const std::string idFilter = selectedIdJson_.toStdString();+ const std::string json = jsonEditor_->toPlainText().toStdString();+ try {+ adapter_->updateDocument(collection_.toStdString(), idFilter, json);+ statusLabel_->setText(tr("Saved."));+ reload();+ } catch (const std::exception& ex) {+ showError(QString::fromLocal8Bit(ex.what()));+ }+}++void MongoCollectionView::onInsert() {+ if (!adapter_) return;++ auto* dlg = new QDialog(this);+ dlg->setWindowTitle(tr("Insert Document — %1").arg(collection_));+ dlg->setAttribute(Qt::WA_DeleteOnClose);+ dlg->resize(520, 400);++ auto* vl = new QVBoxLayout(dlg);+ auto* editor = new QPlainTextEdit(dlg);+ editor->setFont(QFont(QStringLiteral("Monospace"), 11));+ editor->setPlainText(QStringLiteral("{\n \n}"));+ vl->addWidget(editor, 1);++ auto* btns = new QHBoxLayout;+ auto* cancelBtn = new QPushButton(tr("Cancel"), dlg);+ auto* okBtn = new QPushButton(tr("Insert"), dlg);+ okBtn->setDefault(true);+ btns->addStretch();+ btns->addWidget(cancelBtn);+ btns->addWidget(okBtn);+ vl->addLayout(btns);++ connect(cancelBtn, &QPushButton::clicked, dlg, &QDialog::reject);+ connect(okBtn, &QPushButton::clicked, dlg, [this, dlg, editor]() {+ const std::string json = editor->toPlainText().toStdString();+ try {+ const auto insertedId = adapter_->insertDocument(+ collection_.toStdString(), json);+ dlg->accept();+ statusLabel_->setText(tr("Inserted: %1").arg(+ QString::fromStdString(insertedId)));+ reload();+ } catch (const std::exception& ex) {+ QMessageBox::critical(dlg, tr("Insert Failed"),+ QString::fromLocal8Bit(ex.what()));+ }+ });++ dlg->exec();+}++void MongoCollectionView::onDeleteSelected() {+ if (!adapter_) return;+ auto* item = docList_->currentItem();+ if (!item) {+ QMessageBox::information(this, tr("Delete"), tr("Select a document first."));+ return;+ }+ const QString idFilter = buildIdFilter(item->data(Qt::UserRole).toString());+ if (idFilter.isEmpty()) {+ showError(tr("Cannot determine document _id"));+ return;+ }+ const auto ret = QMessageBox::question(+ this, tr("Delete Document"),+ tr("Delete document with filter:\n%1\n\nThis cannot be undone.").arg(idFilter),+ QMessageBox::Yes | QMessageBox::No);+ if (ret != QMessageBox::Yes) return;+ try {+ adapter_->deleteDocument(collection_.toStdString(), idFilter.toStdString());+ statusLabel_->setText(tr("Deleted."));+ reload();+ } catch (const std::exception& ex) {+ showError(QString::fromLocal8Bit(ex.what()));+ }+}++void MongoCollectionView::onPrevPage() {+ currentSkip_ = std::max(0, currentSkip_ - currentLimit_);+ loadPage();+}++void MongoCollectionView::onNextPage() {+ currentSkip_ += currentLimit_;+ loadPage();+}++void MongoCollectionView::showError(const QString& msg) {+ statusLabel_->setText(QStringLiteral("Error: ") + msg);+ QMessageBox::critical(this, tr("MongoDB Error"), msg);+}++} // namespace gridexdiff --git a/linux/src/Presentation/Views/MongoDB/MongoCollectionView.h b/linux/src/Presentation/Views/MongoDB/MongoCollectionView.hnew file mode 100644index 0000000..10c6350--- /dev/null+++ b/linux/src/Presentation/Views/MongoDB/MongoCollectionView.h@@ -0,0 +1,71 @@+#pragma once++#include <QWidget>+#include <string>++class QLabel;+class QLineEdit;+class QListWidget;+class QListWidgetItem;+class QPlainTextEdit;+class QPushButton;+class QSpinBox;++namespace gridex {++class MongodbAdapter;++class MongoCollectionView : public QWidget {+ Q_OBJECT+public:+ explicit MongoCollectionView(MongodbAdapter* adapter,+ const QString& collection,+ QWidget* parent = nullptr);++ void reload();++private slots:+ void onRefresh();+ void onInsert();+ void onDeleteSelected();+ void onRunFilter();+ void onSaveDocument();+ void onDocumentSelected(QListWidgetItem* item);+ void onPrevPage();+ void onNextPage();++private:+ void buildUi();+ void loadPage();+ void updatePagination(long total);+ void showError(const QString& msg);+ QString buildIdFilter(const QString& idStr) const;++ MongodbAdapter* adapter_ = nullptr;+ QString collection_;++ QLabel* titleLabel_ = nullptr;+ QLineEdit* filterEdit_ = nullptr;+ QSpinBox* limitSpin_ = nullptr;+ QPushButton* runBtn_ = nullptr;+ QPushButton* insertBtn_ = nullptr;+ QPushButton* deleteBtn_ = nullptr;+ QPushButton* refreshBtn_ = nullptr;++ QListWidget* docList_ = nullptr;+ QPlainTextEdit* jsonEditor_ = nullptr;+ QPushButton* saveBtn_ = nullptr;+ QLabel* statusLabel_ = nullptr;++ QPushButton* prevBtn_ = nullptr;+ QPushButton* nextBtn_ = nullptr;+ QLabel* pageLabel_ = nullptr;++ int currentSkip_ = 0;+ int currentLimit_ = 50;+ long totalCount_ = 0;+ QString currentFilter_;+ QString selectedIdJson_;+};++} // namespace gridexdiff --git a/linux/src/Presentation/Views/QueryEditor/Autocomplete/AutocompleteProvider.cpp b/linux/src/Presentation/Views/QueryEditor/Autocomplete/AutocompleteProvider.cppnew file mode 100644index 0000000..68ecba6--- /dev/null+++ b/linux/src/Presentation/Views/QueryEditor/Autocomplete/AutocompleteProvider.cpp@@ -0,0 +1,578 @@+#include "Presentation/Views/QueryEditor/Autocomplete/AutocompleteProvider.h"++#include <QRegularExpression>+#include <QSet>+#include <algorithm>+#include <unordered_map>++namespace gridex {++namespace {++const QSet<QString>& primaryKeywords() {+ static const QSet<QString> set = {+ "SELECT", "FROM", "WHERE", "JOIN", "LEFT JOIN", "RIGHT JOIN", "INNER JOIN",+ "ORDER BY", "GROUP BY", "INSERT INTO", "UPDATE", "DELETE", "SET",+ "AND", "OR", "ON", "AS", "DISTINCT", "LIMIT", "HAVING",+ "CREATE TABLE", "ALTER TABLE", "DROP TABLE", "WITH"+ };+ return set;+}++int typeRank(CompletionType t) {+ switch (t) {+ case CompletionType::Keyword: return 0;+ case CompletionType::Table: return 1;+ case CompletionType::Column: return 2;+ case CompletionType::Function: return 3;+ case CompletionType::Join: return 4;+ }+ return 0;+}++QString aliasOrName(const TableRef& r) {+ return r.alias.value_or(r.name);+}++// Pick a short alias (1-3 chars) not already used in the scope.+QString suggestAlias(const QString& table, const std::vector<TableRef>& existing) {+ QSet<QString> used;+ for (const auto& r : existing) used.insert(aliasOrName(r).toLower());+ for (int len = 1; len <= 3; ++len) {+ const QString cand = table.left(len).toLower();+ if (!used.contains(cand)) return cand;+ }+ return table.toLower();+}++} // namespace++// --------------------------------------------------------------------+// Static keyword / function tables+// --------------------------------------------------------------------++const QStringList& AutocompleteProvider::sqlKeywords() {+ static const QStringList kws = {+ "SELECT", "FROM", "WHERE", "JOIN", "LEFT", "RIGHT", "INNER", "OUTER",+ "FULL", "CROSS", "ON", "AND", "OR", "NOT", "IN", "EXISTS", "BETWEEN",+ "LIKE", "ILIKE", "IS", "NULL", "AS", "ORDER", "BY", "GROUP", "HAVING",+ "LIMIT", "OFFSET", "UNION", "ALL", "DISTINCT", "INSERT", "INTO", "VALUES",+ "UPDATE", "SET", "DELETE", "CREATE", "TABLE", "ALTER", "DROP", "INDEX",+ "VIEW", "IF", "THEN", "ELSE", "END", "CASE", "WHEN", "WITH", "RECURSIVE",+ "RETURNING", "EXPLAIN", "ANALYZE", "BEGIN", "COMMIT", "ROLLBACK",+ "LEFT JOIN", "RIGHT JOIN", "INNER JOIN", "FULL JOIN", "CROSS JOIN",+ "ORDER BY", "GROUP BY", "INSERT INTO", "CREATE TABLE", "ALTER TABLE",+ "DROP TABLE", "NOT NULL", "PRIMARY KEY", "FOREIGN KEY", "REFERENCES"+ };+ return kws;+}++const std::vector<AutocompleteProvider::FunctionInfo>& AutocompleteProvider::sqlFunctions() {+ static const std::vector<FunctionInfo> fns = {+ {"COUNT", "COUNT(expr) -> int", "COUNT()"},+ {"SUM", "SUM(expr) -> numeric", "SUM()"},+ {"AVG", "AVG(expr) -> numeric", "AVG()"},+ {"MIN", "MIN(expr) -> value", "MIN()"},+ {"MAX", "MAX(expr) -> value", "MAX()"},+ {"COALESCE", "COALESCE(val, ...) -> value", "COALESCE(, )"},+ {"NULLIF", "NULLIF(a, b) -> value", "NULLIF(, )"},+ {"CAST", "CAST(expr AS type)", "CAST( AS )"},+ {"CONCAT", "CONCAT(str, ...) -> text", "CONCAT(, )"},+ {"LENGTH", "LENGTH(str) -> int", "LENGTH()"},+ {"UPPER", "UPPER(str) -> text", "UPPER()"},+ {"LOWER", "LOWER(str) -> text", "LOWER()"},+ {"TRIM", "TRIM(str) -> text", "TRIM()"},+ {"SUBSTRING", "SUBSTRING(str, pos, len)", "SUBSTRING(, , )"},+ {"REPLACE", "REPLACE(str, from, to)", "REPLACE(, , )"},+ {"NOW", "NOW() -> timestamp", "NOW()"},+ {"CURRENT_TIMESTAMP", "CURRENT_TIMESTAMP", "CURRENT_TIMESTAMP"},+ {"EXTRACT", "EXTRACT(field FROM source)", "EXTRACT( FROM )"},+ {"DATE_TRUNC", "DATE_TRUNC(field, source)", "DATE_TRUNC(, )"},+ {"ROW_NUMBER", "ROW_NUMBER() OVER (...)", "ROW_NUMBER() OVER ()"},+ {"RANK", "RANK() OVER (...)", "RANK() OVER ()"},+ {"DENSE_RANK", "DENSE_RANK() OVER (...)", "DENSE_RANK() OVER ()"},+ {"LAG", "LAG(expr, offset, default)", "LAG(, 1)"},+ {"LEAD", "LEAD(expr, offset, default)", "LEAD(, 1)"},+ {"STRING_AGG", "STRING_AGG(expr, delimiter)", "STRING_AGG(, ',')"},+ {"ARRAY_AGG", "ARRAY_AGG(expr) -> array", "ARRAY_AGG()"},+ {"JSON_AGG", "JSON_AGG(expr) -> json", "JSON_AGG()"},+ {"JSONB_AGG", "JSONB_AGG(expr) -> jsonb", "JSONB_AGG()"},+ {"ROUND", "ROUND(num, decimals)", "ROUND(, 2)"},+ {"CEIL", "CEIL(num) -> int", "CEIL()"},+ {"FLOOR", "FLOOR(num) -> int", "FLOOR()"},+ {"ABS", "ABS(num) -> num", "ABS()"},+ {"GREATEST", "GREATEST(val, ...) -> value", "GREATEST(, )"},+ {"LEAST", "LEAST(val, ...) -> value", "LEAST(, )"},+ {"EXISTS", "EXISTS(subquery) -> bool", "EXISTS ()"},+ {"IN", "expr IN (values)", "IN ()"},+ {"BETWEEN", "expr BETWEEN a AND b", "BETWEEN AND "},+ {"LIKE", "expr LIKE pattern", "LIKE '%%'"},+ {"ILIKE", "expr ILIKE pattern", "ILIKE '%%'"},+ {"GEN_RANDOM_UUID", "GEN_RANDOM_UUID() -> uuid", "GEN_RANDOM_UUID()"},+ {"TO_CHAR", "TO_CHAR(val, format)", "TO_CHAR(, '')"},+ {"TO_DATE", "TO_DATE(str, format)", "TO_DATE(, '')"},+ };+ return fns;+}++// --------------------------------------------------------------------+// Schema+// --------------------------------------------------------------------++void AutocompleteProvider::updateSchema(const std::vector<TableDescription>& tables) {+ tableNames_.clear();+ columnsByTable_.clear();+ foreignKeysByTable_.clear();+ allColumnNames_.clear();++ QSet<QString> allCols;+ for (const auto& td : tables) {+ tableNames_.emplace_back(QString::fromStdString(td.name));+ columnsByTable_[td.name] = td.columns;+ foreignKeysByTable_[td.name] = td.foreignKeys;+ for (const auto& c : td.columns) allCols.insert(QString::fromStdString(c.name));+ }+ std::sort(tableNames_.begin(), tableNames_.end());+ allColumnNames_ = allCols.values();+ std::sort(allColumnNames_.begin(), allColumnNames_.end());+}++void AutocompleteProvider::trackUsed(const QString& text) {+ recentlyUsed_.erase(std::remove(recentlyUsed_.begin(), recentlyUsed_.end(), text),+ recentlyUsed_.end());+ recentlyUsed_.insert(recentlyUsed_.begin(), text);+ if (recentlyUsed_.size() > 50) recentlyUsed_.pop_back();+}++// --------------------------------------------------------------------+// Fuzzy+// --------------------------------------------------------------------++std::optional<int> AutocompleteProvider::fuzzyScore(const QString& query,+ const QString& candidate) {+ if (query.isEmpty()) return 0;+ const QString q = query.toLower();+ const QString c = candidate.toLower();++ if (q == c) return 1000;+ if (c.startsWith(q)) {+ const int lengthPenalty = std::max(0, static_cast<int>(candidate.size() - query.size()));+ return 500 - lengthPenalty;+ }+ // Word-boundary prefix+ const QStringList words = c.split(QRegularExpression(R"([_\. ])"), Qt::SkipEmptyParts);+ for (const auto& w : words) {+ if (w.startsWith(q)) {+ return 200 - std::max(0, static_cast<int>(candidate.size() - query.size()));+ }+ }+ // Subsequence fuzzy+ int qi = 0;+ int score = 0;+ int consecutive = 0;+ int lastMatchIndex = -2;+ for (int ci = 0; ci < c.size(); ++ci) {+ if (qi >= q.size()) break;+ if (c[ci] == q[qi]) {+ ++score;+ if (ci == lastMatchIndex + 1) {+ ++consecutive;+ score += consecutive;+ } else {+ consecutive = 0;+ }+ if (ci > 0) {+ const QChar prev = c[ci - 1];+ if (prev == '_' || prev == '.') score += 3;+ }+ lastMatchIndex = ci;+ ++qi;+ }+ }+ if (qi == q.size()) return score;+ return std::nullopt;+}++std::vector<int> AutocompleteProvider::fuzzyMatchRanges(const QString& query,+ const QString& candidate) {+ std::vector<int> ranges;+ const QString q = query.toLower();+ const QString c = candidate.toLower();+ int qi = 0;+ for (int ci = 0; ci < c.size(); ++ci) {+ if (qi >= q.size()) break;+ if (c[ci] == q[qi]) { ranges.push_back(ci); ++qi; }+ }+ return ranges;+}++// --------------------------------------------------------------------+// Suggestions+// --------------------------------------------------------------------++static std::vector<CompletionItem> keywordSuggestions(const QString& prefix) {+ std::vector<CompletionItem> items;+ for (const auto& kw : AutocompleteProvider::sqlKeywords()) {+ const auto s = AutocompleteProvider::fuzzyScore(prefix, kw);+ if (!s) continue;+ int boost = primaryKeywords().contains(kw) ? 100 : 0;+ items.push_back({kw, CompletionType::Keyword, QString{}, kw, *s + boost,+ AutocompleteProvider::fuzzyMatchRanges(prefix, kw)});+ }+ return items;+}++static std::vector<CompletionItem> tableSuggestions(const QString& prefix,+ const std::vector<QString>& tableNames,+ const std::unordered_map<std::string, std::vector<ColumnInfo>>& columnsByTable) {+ std::vector<CompletionItem> items;+ for (const auto& name : tableNames) {+ if (!prefix.isEmpty() && !AutocompleteProvider::fuzzyScore(prefix, name)) continue;+ const int score = prefix.isEmpty() ? 0+ : AutocompleteProvider::fuzzyScore(prefix, name).value_or(0);+ int cols = 0;+ auto it = columnsByTable.find(name.toStdString());+ if (it != columnsByTable.end()) cols = static_cast<int>(it->second.size());+ items.push_back({+ name, CompletionType::Table,+ QString::number(cols) + " cols",+ name, score,+ prefix.isEmpty() ? std::vector<int>{}+ : AutocompleteProvider::fuzzyMatchRanges(prefix, name)+ });+ }+ return items;+}++static std::vector<CompletionItem> columnSuggestions(+ const std::optional<QString>& table,+ const QString& prefix,+ const std::vector<TableRef>& scope,+ const std::unordered_map<std::string, std::vector<ColumnInfo>>& columnsByTable) {+ std::vector<CompletionItem> items;++ auto pushColumn = [&](const ColumnInfo& col, const QString& qualifier, int baseScore) {+ const QString cname = QString::fromStdString(col.name);+ if (!prefix.isEmpty() && !AutocompleteProvider::fuzzyScore(prefix, cname)) return;+ int score = prefix.isEmpty() ? baseScore+ : AutocompleteProvider::fuzzyScore(prefix, cname).value_or(0);+ if (col.isPrimaryKey) score += 5;+ const QString detail = QString::fromStdString(col.dataType) + " · " + qualifier;+ items.push_back({+ cname, CompletionType::Column, detail, cname, score,+ prefix.isEmpty() ? std::vector<int>{}+ : AutocompleteProvider::fuzzyMatchRanges(prefix, cname)+ });+ };++ // Columns from specific table (highest priority)+ if (table) {+ auto it = columnsByTable.find(table->toStdString());+ if (it != columnsByTable.end()) {+ for (const auto& c : it->second) pushColumn(c, *table, 10);+ }+ } else {+ // Scope-wide columns with qualifier = alias or table name+ QSet<QString> scopeNames;+ for (const auto& r : scope) scopeNames.insert(r.name);+ for (const auto& r : scope) {+ auto it = columnsByTable.find(r.name.toStdString());+ if (it == columnsByTable.end()) continue;+ const QString qualifier = aliasOrName(r);+ for (const auto& c : it->second) {+ const QString cname = QString::fromStdString(c.name);+ if (!prefix.isEmpty() && !AutocompleteProvider::fuzzyScore(prefix, cname)) continue;+ int score = prefix.isEmpty() ? 8+ : AutocompleteProvider::fuzzyScore(prefix, cname).value_or(0);+ if (c.isPrimaryKey) score += 5;+ if (scopeNames.contains(r.name)) score += 3;+ items.push_back({+ cname, CompletionType::Column,+ QString::fromStdString(c.dataType) + " · " + qualifier,+ cname, score,+ prefix.isEmpty() ? std::vector<int>{}+ : AutocompleteProvider::fuzzyMatchRanges(prefix, cname)+ });+ }+ }+ }++ // Dedupe by column name, keeping highest score.+ std::unordered_map<std::string, int> seen;+ std::vector<CompletionItem> deduped;+ for (const auto& it : items) {+ const std::string key = it.text.toLower().toStdString();+ auto existing = seen.find(key);+ if (existing == seen.end() || existing->second < it.score) {+ seen[key] = it.score;+ deduped.push_back(it);+ }+ }+ return deduped;+}++static std::vector<CompletionItem> functionSuggestions(const QString& prefix) {+ std::vector<CompletionItem> items;+ for (const auto& fn : AutocompleteProvider::sqlFunctions()) {+ if (!prefix.isEmpty() && !AutocompleteProvider::fuzzyScore(prefix, fn.name)) continue;+ int score = prefix.isEmpty() ? 0+ : (AutocompleteProvider::fuzzyScore(prefix, fn.name).value_or(0) - 10);+ items.push_back({+ fn.name, CompletionType::Function, fn.signature, fn.snippet, score,+ prefix.isEmpty() ? std::vector<int>{}+ : AutocompleteProvider::fuzzyMatchRanges(prefix, fn.name)+ });+ }+ return items;+}++static std::vector<CompletionItem> joinSuggestions(+ const std::vector<TableRef>& fromTables,+ const QString& prefix,+ const std::unordered_map<std::string, std::vector<ForeignKeyInfo>>& fksByTable,+ const std::vector<QString>& tableNames,+ const std::unordered_map<std::string, std::vector<ColumnInfo>>& columnsByTable) {+ std::vector<CompletionItem> items;++ auto tryMatch = [&](const QString& insertText, const QString& needle) -> bool {+ if (prefix.isEmpty()) return true;+ if (AutocompleteProvider::fuzzyScore(prefix, insertText)) return true;+ if (AutocompleteProvider::fuzzyScore(prefix, needle)) return true;+ return false;+ };++ for (const auto& tref : fromTables) {+ const QString alias = aliasOrName(tref);++ // Forward FKs from this table+ auto it = fksByTable.find(tref.name.toStdString());+ if (it != fksByTable.end()) {+ for (const auto& fk : it->second) {+ const QString refTable = QString::fromStdString(fk.referencedTable);+ const QString refAlias = suggestAlias(refTable, fromTables);+ QStringList onParts;+ const std::size_t n = std::min(fk.columns.size(), fk.referencedColumns.size());+ for (std::size_t i = 0; i < n; ++i) {+ onParts << QString("%1.%2 = %3.%4")+ .arg(alias, QString::fromStdString(fk.columns[i]),+ refAlias, QString::fromStdString(fk.referencedColumns[i]));+ }+ const QString onClause = onParts.join(" AND ");+ const QString text = QString("JOIN %1 %2 ON %3").arg(refTable, refAlias, onClause);+ if (!tryMatch(text, refTable)) continue;+ QStringList cols;+ for (const auto& c : fk.columns) cols << QString::fromStdString(c);+ items.push_back({text, CompletionType::Join, "FK: " + cols.join(","),+ text, 20, {}});+ }+ }++ // Reverse FKs: other tables referencing this one+ for (const auto& [otherTableStd, fks] : fksByTable) {+ const QString otherTable = QString::fromStdString(otherTableStd);+ if (otherTable == tref.name) continue;+ for (const auto& fk : fks) {+ if (QString::fromStdString(fk.referencedTable) != tref.name) continue;+ const QString refAlias = suggestAlias(otherTable, fromTables);+ QStringList onParts;+ const std::size_t n = std::min(fk.columns.size(), fk.referencedColumns.size());+ for (std::size_t i = 0; i < n; ++i) {+ onParts << QString("%1.%2 = %3.%4")+ .arg(alias, QString::fromStdString(fk.referencedColumns[i]),+ refAlias, QString::fromStdString(fk.columns[i]));+ }+ const QString text = QString("JOIN %1 %2 ON %3")+ .arg(otherTable, refAlias, onParts.join(" AND "));+ if (!tryMatch(text, otherTable)) continue;+ QStringList cols;+ for (const auto& c : fk.columns) cols << QString::fromStdString(c);+ items.push_back({text, CompletionType::Join,+ "FK: " + otherTable + "." + cols.join(","),+ text, 18, {}});+ }+ }+ }++ // Fallback: plain JOIN <table>+ if (items.empty()) {+ const auto tables = tableSuggestions(prefix, tableNames, columnsByTable);+ for (const auto& t : tables) {+ items.push_back({+ "JOIN " + t.text, CompletionType::Join, t.detail,+ "JOIN " + t.insertText, t.score, {}+ });+ }+ }+ return items;+}++static std::vector<CompletionItem> selectListSuggestions(+ const QString& prefix,+ const std::vector<TableRef>& scope,+ const std::unordered_map<std::string, std::vector<ColumnInfo>>& columnsByTable) {+ std::vector<CompletionItem> items;++ // Star+ if (prefix.isEmpty() || QString("*").startsWith(prefix)) {+ items.push_back({"*", CompletionType::Keyword, "All columns", "*", 20, {}});+ }+ // Functions+ auto fns = functionSuggestions(prefix);+ for (auto& f : fns) { f.score += 5; items.push_back(std::move(f)); }++ // Scope columns+ auto cols = columnSuggestions(std::nullopt, prefix, scope, columnsByTable);+ items.insert(items.end(), cols.begin(), cols.end());++ // DISTINCT+ auto dscore = AutocompleteProvider::fuzzyScore(prefix, "DISTINCT");+ if (prefix.isEmpty() || dscore) {+ items.push_back({+ "DISTINCT", CompletionType::Keyword, QString{}, "DISTINCT",+ prefix.isEmpty() ? 8 : dscore.value_or(0),+ prefix.isEmpty() ? std::vector<int>{}+ : AutocompleteProvider::fuzzyMatchRanges(prefix, "DISTINCT")+ });+ }+ return items;+}++static std::vector<CompletionItem> afterIdentifierSuggestions(const QString& clause,+ const QString& prefix) {+ QStringList next;+ if (clause == "SELECT") {+ next = {"FROM"};+ } else if (clause == "FROM") {+ next = {"WHERE", "JOIN", "LEFT JOIN", "RIGHT JOIN", "INNER JOIN",+ "FULL JOIN", "CROSS JOIN", "ORDER BY", "GROUP BY",+ "LIMIT", "OFFSET", "UNION", "RETURNING"};+ } else if (clause == "JOIN") {+ next = {"ON", "WHERE", "JOIN", "LEFT JOIN", "RIGHT JOIN",+ "ORDER BY", "GROUP BY", "LIMIT"};+ } else if (clause == "WHERE") {+ next = {"AND", "OR", "ORDER BY", "GROUP BY", "LIMIT", "UNION", "RETURNING"};+ } else if (clause == "ORDER BY" || clause == "GROUP BY") {+ next = {"LIMIT", "OFFSET", "ASC", "DESC"};+ } else if (clause == "HAVING") {+ next = {"ORDER BY", "LIMIT"};+ } else if (clause == "INSERT") {+ next = {"VALUES", "SELECT", "RETURNING"};+ } else {+ next = {"SELECT", "FROM", "WHERE", "JOIN", "ORDER BY",+ "GROUP BY", "LIMIT", "HAVING", "AND", "OR"};+ }+ std::vector<CompletionItem> items;+ for (const auto& kw : next) {+ auto s = AutocompleteProvider::fuzzyScore(prefix, kw);+ if (!prefix.isEmpty() && !s) continue;+ int score = prefix.isEmpty() ? 15 : s.value_or(0) + 10;+ items.push_back({+ kw, CompletionType::Keyword, QString{}, kw, score,+ prefix.isEmpty() ? std::vector<int>{}+ : AutocompleteProvider::fuzzyMatchRanges(prefix, kw)+ });+ }+ return items;+}++std::vector<CompletionItem> AutocompleteProvider::suggestions(+ const CompletionContext& ctx) const {+ std::vector<CompletionItem> items;+ const auto& prefix = ctx.prefix;+ const auto& trig = ctx.trigger;++ switch (trig.kind) {+ case CompletionTriggerKind::None:+ return {};+ case CompletionTriggerKind::Keyword:+ items = keywordSuggestions(prefix);+ break;+ case CompletionTriggerKind::Table:+ items = tableSuggestions(prefix, tableNames_, columnsByTable_);+ break;+ case CompletionTriggerKind::Column:+ items = columnSuggestions(trig.columnTable, prefix, ctx.scopeTables,+ columnsByTable_);+ break;+ case CompletionTriggerKind::Join:+ items = joinSuggestions(trig.joinFromTables, prefix,+ foreignKeysByTable_, tableNames_, columnsByTable_);+ break;+ case CompletionTriggerKind::SelectList:+ items = selectListSuggestions(prefix, trig.selectScopeTables, columnsByTable_);+ break;+ case CompletionTriggerKind::AfterIdentifier:+ items = afterIdentifierSuggestions(trig.afterIdentClause, prefix);+ break;+ case CompletionTriggerKind::Function:+ items = functionSuggestions(prefix);+ break;+ case CompletionTriggerKind::General: {+ if (prefix.isEmpty()) return {};+ auto a = keywordSuggestions(prefix);+ auto b = tableSuggestions(prefix, tableNames_, columnsByTable_);+ auto c = functionSuggestions(prefix);+ items.insert(items.end(), a.begin(), a.end());+ items.insert(items.end(), b.begin(), b.end());+ items.insert(items.end(), c.begin(), c.end());+ // All-columns search+ for (const auto& [tnameStd, cols] : columnsByTable_) {+ const QString tname = QString::fromStdString(tnameStd);+ for (const auto& col : cols) {+ const QString cname = QString::fromStdString(col.name);+ auto s = AutocompleteProvider::fuzzyScore(prefix, cname);+ if (!s) continue;+ items.push_back({+ cname, CompletionType::Column,+ QString::fromStdString(col.dataType) + " · " + tname,+ cname, *s + (col.isPrimaryKey ? 3 : 0),+ AutocompleteProvider::fuzzyMatchRanges(prefix, cname)+ });+ }+ }+ break;+ }+ }++ // Recently-used boost+ for (auto& it : items) {+ auto pos = std::find(recentlyUsed_.begin(), recentlyUsed_.end(), it.text);+ if (pos != recentlyUsed_.end()) {+ const int idx = static_cast<int>(pos - recentlyUsed_.begin());+ it.score += 30 - idx;+ }+ }++ // Dedup by (text lower, type)+ std::unordered_map<std::string, int> seenScore;+ std::vector<CompletionItem> deduped;+ for (const auto& it : items) {+ const std::string key = (it.text.toLower() + "|" ++ QString::number(static_cast<int>(it.type))).toStdString();+ auto ex = seenScore.find(key);+ if (ex == seenScore.end()) {+ seenScore[key] = it.score;+ deduped.push_back(it);+ } else if (it.score > ex->second) {+ ex->second = it.score;+ for (auto& d : deduped) {+ const std::string dkey = (d.text.toLower() + "|" ++ QString::number(static_cast<int>(d.type))).toStdString();+ if (dkey == key) { d = it; break; }+ }+ }+ }++ // Sort: score desc, then type priority, then alpha+ std::sort(deduped.begin(), deduped.end(),+ [](const CompletionItem& a, const CompletionItem& b) {+ if (a.score != b.score) return a.score > b.score;+ if (a.type != b.type) return typeRank(a.type) < typeRank(b.type);+ return a.text < b.text;+ });++ if (deduped.size() > 20) deduped.resize(20);+ return deduped;+}++} // namespace gridexdiff --git a/linux/src/Presentation/Views/QueryEditor/Autocomplete/AutocompleteProvider.h b/linux/src/Presentation/Views/QueryEditor/Autocomplete/AutocompleteProvider.hnew file mode 100644index 0000000..0090553--- /dev/null+++ b/linux/src/Presentation/Views/QueryEditor/Autocomplete/AutocompleteProvider.h@@ -0,0 +1,48 @@+#pragma once++#include "Core/Models/Schema/SchemaSnapshot.h"+#include "Presentation/Views/QueryEditor/Autocomplete/CompletionModels.h"++#include <QString>+#include <QStringList>+#include <unordered_map>+#include <vector>++namespace gridex {++// Context-aware SQL autocomplete with FK-based JOIN suggestions, fuzzy+// matching, and smart ranking. Stateless per-call: call updateSchema once+// when the adapter changes, then suggestions() per keystroke.+class AutocompleteProvider {+public:+ // Feed table/column/FK metadata; sorts table names and flattens columns.+ void updateSchema(const std::vector<TableDescription>& tables);++ // Track item text so it ranks higher on future completions.+ void trackUsed(const QString& text);++ // Top-20 suggestions for the given parser output.+ std::vector<CompletionItem> suggestions(const CompletionContext& ctx) const;++ // Exposed so the UI can highlight substring matches using the same+ // scoring used for ranking.+ static std::optional<int> fuzzyScore(const QString& query, const QString& candidate);+ static std::vector<int> fuzzyMatchRanges(const QString& query, const QString& candidate);++ struct FunctionInfo {+ QString name;+ QString signature;+ QString snippet;+ };+ static const QStringList& sqlKeywords();+ static const std::vector<FunctionInfo>& sqlFunctions();++private:+ std::vector<QString> tableNames_;+ std::unordered_map<std::string, std::vector<ColumnInfo>> columnsByTable_;+ std::unordered_map<std::string, std::vector<ForeignKeyInfo>> foreignKeysByTable_;+ QStringList allColumnNames_;+ std::vector<QString> recentlyUsed_;+};++} // namespace gridexdiff --git a/linux/src/Presentation/Views/QueryEditor/Autocomplete/CompletionModels.h b/linux/src/Presentation/Views/QueryEditor/Autocomplete/CompletionModels.hnew file mode 100644index 0000000..09dcbab--- /dev/null+++ b/linux/src/Presentation/Views/QueryEditor/Autocomplete/CompletionModels.h@@ -0,0 +1,60 @@+#pragma once++#include <QString>+#include <optional>+#include <vector>++namespace gridex {++struct TableRef {+ QString name;+ std::optional<QString> alias;+};++enum class CompletionType {+ Keyword,+ Table,+ Column,+ Function,+ Join,+};++struct CompletionItem {+ QString text;+ CompletionType type = CompletionType::Keyword;+ QString detail; // optional+ QString insertText;+ int score = 0;+ std::vector<int> matchRanges; // char indices for highlight+};++enum class CompletionTriggerKind {+ None,+ Keyword,+ Table,+ Column,+ Join,+ SelectList,+ AfterIdentifier,+ Function,+ General,+};++struct CompletionTrigger {+ CompletionTriggerKind kind = CompletionTriggerKind::General;++ // Trigger-specific payloads. Unused fields stay empty.+ std::optional<QString> columnTable; // Column+ std::vector<TableRef> joinFromTables; // Join+ std::vector<TableRef> selectScopeTables; // SelectList+ QString afterIdentClause; // AfterIdentifier+ std::vector<TableRef> afterIdentScope; // AfterIdentifier+};++struct CompletionContext {+ CompletionTrigger trigger;+ QString prefix;+ std::vector<TableRef> scopeTables;+};++} // namespace gridexdiff --git a/linux/src/Presentation/Views/QueryEditor/Autocomplete/CompletionPopup.cpp b/linux/src/Presentation/Views/QueryEditor/Autocomplete/CompletionPopup.cppnew file mode 100644index 0000000..ffb7d95--- /dev/null+++ b/linux/src/Presentation/Views/QueryEditor/Autocomplete/CompletionPopup.cpp@@ -0,0 +1,131 @@+#include "Presentation/Views/QueryEditor/Autocomplete/CompletionPopup.h"++#include <QHBoxLayout>+#include <QKeyEvent>+#include <QLabel>+#include <QListWidget>+#include <QListWidgetItem>+#include <QVBoxLayout>++namespace gridex {++namespace {+constexpr int kRowHeight = 22;+constexpr int kMaxVisible = 10;+constexpr int kWindowWidth = 440;+constexpr int kIconCellPx = 18;+} // namespace++CompletionPopup::CompletionPopup(QWidget* parent)+ : QFrame(parent) {+ // Tool window that never steals focus and never grabs keyboard/mouse.+ // Qt::Popup would grab input and leave the editor unreachable once the+ // popup is re-shown (e.g. after accept -> debounce re-fire). Qt::Tool ++ // WindowDoesNotAcceptFocus keeps all key events going to the editor, and+ // eventFilter on the editor routes navigation keys to this popup.+ setWindowFlags(Qt::Tool | Qt::FramelessWindowHint+ | Qt::WindowDoesNotAcceptFocus+ | Qt::NoDropShadowWindowHint);+ setAttribute(Qt::WA_ShowWithoutActivating);+ setFocusPolicy(Qt::NoFocus);+ setFrameShape(QFrame::Box);+ setLineWidth(1);++ buildUi();+}++void CompletionPopup::buildUi() {+ auto* root = new QVBoxLayout(this);+ root->setContentsMargins(0, 4, 0, 0);+ root->setSpacing(0);++ list_ = new QListWidget(this);+ list_->setFocusPolicy(Qt::NoFocus);+ list_->setFrameShape(QFrame::NoFrame);+ list_->setSelectionMode(QAbstractItemView::SingleSelection);+ list_->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);+ list_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);+ list_->setUniformItemSizes(true);+ root->addWidget(list_, 1);++ connect(list_, &QListWidget::itemClicked, this,+ [this](QListWidgetItem* it) {+ const int idx = list_->row(it);+ if (idx >= 0 && idx < static_cast<int>(items_.size())) {+ emit accepted(items_[idx]);+ }+ });++ footer_ = new QLabel(+ tr("<span style='color:#777'>↑↓ Nav ⏎ Tab Accept Esc Dismiss</span>"),+ this);+ footer_->setTextFormat(Qt::RichText);+ root->addWidget(footer_);+}++QString CompletionPopup::typeLabel(CompletionType t) const {+ switch (t) {+ case CompletionType::Keyword: return "kw";+ case CompletionType::Table: return "T";+ case CompletionType::Column: return "col";+ case CompletionType::Function: return "fn";+ case CompletionType::Join: return "J";+ }+ return "?";+}++void CompletionPopup::setItems(const std::vector<CompletionItem>& items) {+ items_ = items;+ list_->clear();+ for (const auto& it : items_) {+ QString line = QString("%1 %2").arg(typeLabel(it.type), -3).arg(it.text);+ if (!it.detail.isEmpty()) {+ line += " ";+ line += it.detail;+ }+ auto* wi = new QListWidgetItem(line);+ list_->addItem(wi);+ }+ if (!items_.empty()) list_->setCurrentRow(0);++ const int visible = std::min<int>(items_.size(), kMaxVisible);+ const int h = visible * kRowHeight + 4 + 20 /* footer */;+ setFixedSize(kWindowWidth, std::max(h, kRowHeight + 24));+ Q_UNUSED(kIconCellPx);+}++int CompletionPopup::selectedIndex() const {+ return list_->currentRow();+}++void CompletionPopup::moveSelection(int delta) {+ if (items_.empty()) return;+ int i = list_->currentRow() + delta;+ const int n = static_cast<int>(items_.size());+ if (i < 0) i = n - 1;+ if (i >= n) i = 0;+ list_->setCurrentRow(i);+ list_->scrollToItem(list_->currentItem());+}++const CompletionItem* CompletionPopup::selectedItem() const {+ const int idx = list_->currentRow();+ if (idx < 0 || idx >= static_cast<int>(items_.size())) return nullptr;+ return &items_[idx];+}++void CompletionPopup::keyPressEvent(QKeyEvent* event) {+ // The editor forwards relevant keys to the popup via public methods; this+ // handler only fires if the popup itself somehow receives focus.+ if (event->key() == Qt::Key_Escape) { emit dismissed(); return; }+ if (event->key() == Qt::Key_Up) { moveSelection(-1); return; }+ if (event->key() == Qt::Key_Down) { moveSelection(+1); return; }+ if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter+ || event->key() == Qt::Key_Tab) {+ if (auto* it = selectedItem()) emit accepted(*it);+ return;+ }+ QFrame::keyPressEvent(event);+}++} // namespace gridexdiff --git a/linux/src/Presentation/Views/QueryEditor/Autocomplete/CompletionPopup.h b/linux/src/Presentation/Views/QueryEditor/Autocomplete/CompletionPopup.hnew file mode 100644index 0000000..3170cdd--- /dev/null+++ b/linux/src/Presentation/Views/QueryEditor/Autocomplete/CompletionPopup.h@@ -0,0 +1,44 @@+#pragma once++#include "Presentation/Views/QueryEditor/Autocomplete/CompletionModels.h"++#include <QFrame>+#include <vector>++class QListWidget;+class QListWidgetItem;+class QLabel;++namespace gridex {++// Borderless popup showing up to 10 completion rows + footer hint.+// Arrow keys navigate; Enter/Tab emits accepted() with the selected item.+// Escape emits dismissed(). Mouse click also accepts.+class CompletionPopup : public QFrame {+ Q_OBJECT+public:+ explicit CompletionPopup(QWidget* parent = nullptr);++ void setItems(const std::vector<CompletionItem>& items);+ bool isEmpty() const { return items_.empty(); }+ int selectedIndex() const;+ void moveSelection(int delta);+ const CompletionItem* selectedItem() const;++signals:+ void accepted(const CompletionItem& item);+ void dismissed();++protected:+ void keyPressEvent(QKeyEvent* event) override;++private:+ void buildUi();+ QString typeLabel(CompletionType t) const;++ QListWidget* list_ = nullptr;+ QLabel* footer_ = nullptr;+ std::vector<CompletionItem> items_;+};++} // namespace gridexdiff --git a/linux/src/Presentation/Views/QueryEditor/Autocomplete/SqlContextParser.cpp b/linux/src/Presentation/Views/QueryEditor/Autocomplete/SqlContextParser.cppnew file mode 100644index 0000000..8e6fc15--- /dev/null+++ b/linux/src/Presentation/Views/QueryEditor/Autocomplete/SqlContextParser.cpp@@ -0,0 +1,451 @@+#include "Presentation/Views/QueryEditor/Autocomplete/SqlContextParser.h"++#include <QRegularExpression>+#include <QSet>++namespace gridex {++namespace {++struct Token {+ QString value;+ QString upper;+};++// Punctuation tokens that never count as identifiers for keyword-distance.+const QSet<QString>& punctuationTokens() {+ static const QSet<QString> set = {+ ",", "(", ")", ".", ";", "*", "=", ">", "<", "!"+ };+ return set;+}++// Clause-starting SQL keywords. Used for boundary detection when scanning+// backwards from cursor.+const QSet<QString>& clauseKeywords() {+ static const QSet<QString> set = {+ "SELECT", "FROM", "WHERE", "JOIN", "ON", "AND", "OR", "NOT",+ "ORDER", "GROUP", "BY", "HAVING", "LIMIT", "OFFSET", "UNION",+ "INSERT", "INTO", "VALUES", "UPDATE", "SET", "DELETE",+ "LEFT", "RIGHT", "INNER", "OUTER", "FULL", "CROSS", "NATURAL",+ "CREATE", "ALTER", "DROP", "TABLE", "INDEX", "VIEW",+ "WITH", "AS", "DISTINCT", "ALL", "EXISTS", "IN", "BETWEEN",+ "LIKE", "ILIKE", "IS", "NULL", "CASE", "WHEN", "THEN", "ELSE", "END",+ "RETURNING", "EXPLAIN", "ANALYZE", "BEGIN", "COMMIT", "ROLLBACK"+ };+ return set;+}++bool isJoinModifier(const QString& upper) {+ return upper == "LEFT" || upper == "RIGHT" || upper == "INNER"+ || upper == "OUTER" || upper == "FULL" || upper == "CROSS"+ || upper == "NATURAL";+}++bool isInsideString(const QString& text) {+ bool inSingle = false;+ for (QChar ch : text) if (ch == '\'') inSingle = !inSingle;+ return inSingle;+}++QString isolateCurrentStatement(const QString& text) {+ const int last = text.lastIndexOf(';');+ if (last < 0) return text;+ return text.mid(last + 1);+}++QString currentWord(const QString& text) {+ int start = text.length();+ while (start > 0) {+ const QChar ch = text.at(start - 1);+ if (ch.isLetterOrNumber() || ch == '_' || ch == '.') {+ --start;+ } else {+ break;+ }+ }+ return text.mid(start);+}++std::optional<QString> prefixBeforeDot(const QString& word) {+ const int dot = word.indexOf('.');+ if (dot < 0) return std::nullopt;+ return word.left(dot);+}++std::vector<Token> tokenize(const QString& text) {+ // Strings and comments: matched but skipped.+ // Words: \w+. Punctuation: single-char ops.+ static const QRegularExpression re(+ QStringLiteral(R"((?:'[^']*')|(?:--[^\n]*)|(?:/\*[\s\S]*?\*/)|(?:\w+)|(?:[.,();=<>!*]))"),+ QRegularExpression::UseUnicodePropertiesOption);++ std::vector<Token> tokens;+ auto it = re.globalMatch(text);+ while (it.hasNext()) {+ const auto m = it.next();+ const QString v = m.captured(0);+ if (v.startsWith('\'') || v.startsWith("--") || v.startsWith("/*")) continue;+ tokens.push_back({v, v.toUpper()});+ }+ return tokens;+}++// Resolve alias/table-name lookup within the current statement scope.+std::optional<QString> resolveAlias(const QString& needle,+ const std::vector<TableRef>& scope) {+ for (const auto& r : scope) {+ if (r.alias.has_value() && *r.alias == needle) return r.name;+ }+ for (const auto& r : scope) {+ if (r.name == needle) return r.name;+ }+ return needle;+}++QString resolveSchemaPrefix(const std::vector<Token>& tokens, int& i) {+ QString name = tokens[i].value;+ ++i;+ if (i < static_cast<int>(tokens.size()) && tokens[i].value == ".") {+ ++i;+ if (i < static_cast<int>(tokens.size())) {+ name = tokens[i].value;+ ++i;+ }+ }+ return name;+}++std::vector<TableRef> extractAllTables(const std::vector<Token>& tokens) {+ std::vector<TableRef> tables;+ int i = 0;+ const int n = static_cast<int>(tokens.size());++ while (i < n) {+ const QString upper = tokens[i].upper;++ if (upper == "FROM" || upper == "JOIN") {+ ++i;+ if (i >= n) break;+ const QString tableName = resolveSchemaPrefix(tokens, i);++ std::optional<QString> alias;+ if (i < n) {+ const QString& next = tokens[i].upper;+ if (next == "AS") {+ ++i;+ if (i < n) { alias = tokens[i].value; ++i; }+ } else if (!clauseKeywords().contains(next)+ && next != "ON" && next != "," && next != "("+ && next != ")" && next != ";" && next != "*") {+ alias = tokens[i].value;+ ++i;+ }+ }+ tables.push_back({tableName, alias});+ continue;+ }++ if (upper == "UPDATE") {+ ++i;+ if (i < n && !clauseKeywords().contains(tokens[i].upper)) {+ const QString tableName = resolveSchemaPrefix(tokens, i);+ std::optional<QString> alias;+ if (i < n && tokens[i].upper == "AS") {+ ++i;+ if (i < n) { alias = tokens[i].value; ++i; }+ } else if (i < n && tokens[i].upper == "SET") {+ // no alias+ } else if (i < n && !clauseKeywords().contains(tokens[i].upper)) {+ alias = tokens[i].value;+ ++i;+ }+ tables.push_back({tableName, alias});+ continue;+ }+ }++ ++i;+ }++ return tables;+}++std::optional<QString> findUpdateTable(const std::vector<Token>& tokens) {+ for (std::size_t i = 0; i < tokens.size(); ++i) {+ if (tokens[i].upper == "UPDATE" && i + 1 < tokens.size()) {+ return tokens[i + 1].value;+ }+ }+ return std::nullopt;+}++std::optional<QString> findInsertTable(const std::vector<Token>& tokens) {+ for (std::size_t i = 0; i < tokens.size(); ++i) {+ if (tokens[i].upper == "INTO" && i + 1 < tokens.size()) {+ return tokens[i + 1].value;+ }+ }+ return std::nullopt;+}++// Detect `INSERT INTO table (` — returns table name if matched.+std::optional<QString> findInsertIntoParenContext(const std::vector<Token>& tokens) {+ const int count = static_cast<int>(tokens.size());+ if (count < 3) return std::nullopt;++ const int beforeParen = count - 2;+ const int beforeTable = count - 3;++ if (beforeTable >= 0 && tokens[beforeTable].upper == "INTO") {+ return tokens[beforeParen].value;+ }+ // INSERT INTO schema.table (+ if (count >= 5) {+ const int dotPos = count - 3;+ const int intoPos = count - 5;+ if (dotPos >= 0 && tokens[dotPos].value == "."+ && intoPos >= 0 && tokens[intoPos].upper == "INTO") {+ return tokens[beforeParen].value;+ }+ }+ return std::nullopt;+}++QString findCurrentClause(const std::vector<Token>& tokens) {+ for (int i = static_cast<int>(tokens.size()) - 1; i >= 0; --i) {+ const QString& u = tokens[i].upper;+ if (u == "SELECT" || u == "FROM" || u == "WHERE" || u == "HAVING" || u == "SET") {+ return u;+ }+ if (u == "JOIN") return "JOIN";+ if (u == "ORDER") {+ if (i + 1 < static_cast<int>(tokens.size()) && tokens[i + 1].upper == "BY") {+ return "ORDER BY";+ }+ return u;+ }+ if (u == "GROUP") {+ if (i + 1 < static_cast<int>(tokens.size()) && tokens[i + 1].upper == "BY") {+ return "GROUP BY";+ }+ return u;+ }+ if (u == "INSERT" || u == "INTO") return "INSERT";+ }+ return "";+}++// Find the nearest clause keyword when scanning backwards; also count the+// number of identifier tokens between that keyword and the cursor.+std::optional<std::pair<QString, int>> findPreviousKeywordWithDistance(+ const std::vector<Token>& tokens) {+ int identifierCount = 0;+ for (int i = static_cast<int>(tokens.size()) - 1; i >= 0; --i) {+ const QString& u = tokens[i].upper;+ if (clauseKeywords().contains(u)) {+ return std::make_pair(u, identifierCount);+ }+ if (!punctuationTokens().contains(tokens[i].value)) {+ ++identifierCount;+ }+ }+ return std::nullopt;+}++// Build the actual CompletionTrigger payload from raw tokens + prefix.+CompletionTrigger determineTrigger(const std::vector<Token>& tokens,+ const QString& prefix,+ const std::vector<TableRef>& scope) {+ CompletionTrigger trig;++ // Dot notation: alias.column+ if (prefix.contains('.')) {+ const auto before = prefixBeforeDot(prefix);+ if (before) {+ trig.kind = CompletionTriggerKind::Column;+ trig.columnTable = resolveAlias(*before, scope);+ return trig;+ }+ }++ if (tokens.empty()) {+ trig.kind = CompletionTriggerKind::General;+ return trig;+ }++ // Strip the current in-progress word from the effective token list so+ // keyword-detection operates on the last committed identifier.+ std::vector<Token> effective = tokens;+ if (!prefix.isEmpty() && !effective.empty()+ && effective.back().value.toLower() == prefix.toLower()) {+ effective.pop_back();+ }++ if (effective.empty()) {+ trig.kind = prefix.isEmpty() ? CompletionTriggerKind::None+ : CompletionTriggerKind::General;+ return trig;+ }++ const Token& last = effective.back();+ const QString u = last.upper;++ // === Keyword-immediate triggers ===+ if (u == "JOIN") {+ trig.kind = CompletionTriggerKind::Join;+ trig.joinFromTables = scope;+ return trig;+ }+ if (isJoinModifier(u)) {+ trig.kind = CompletionTriggerKind::Keyword;+ return trig;+ }+ if (u == "FROM" || u == "INTO" || u == "TABLE" || u == "UPDATE") {+ trig.kind = CompletionTriggerKind::Table;+ return trig;+ }+ if (u == "SELECT" || u == "DISTINCT") {+ trig.kind = CompletionTriggerKind::SelectList;+ trig.selectScopeTables = scope;+ return trig;+ }+ if (u == "WHERE" || u == "AND" || u == "OR" || u == "ON"+ || u == "HAVING" || u == "BY") {+ trig.kind = CompletionTriggerKind::Column;+ return trig;+ }+ if (u == "SET") {+ trig.kind = CompletionTriggerKind::Column;+ trig.columnTable = findUpdateTable(effective);+ return trig;+ }+ if (last.value == "*") {+ trig.kind = CompletionTriggerKind::AfterIdentifier;+ trig.afterIdentClause = "SELECT";+ trig.afterIdentScope = scope;+ return trig;+ }++ if (last.value == ",") {+ const QString clause = findCurrentClause(effective);+ if (clause == "SELECT") {+ trig.kind = CompletionTriggerKind::SelectList;+ trig.selectScopeTables = scope;+ } else if (clause == "FROM" || clause == "JOIN") {+ trig.kind = CompletionTriggerKind::Table;+ } else if (clause == "ORDER BY" || clause == "GROUP BY") {+ trig.kind = CompletionTriggerKind::Column;+ } else if (clause == "INSERT") {+ trig.kind = CompletionTriggerKind::Column;+ trig.columnTable = findInsertTable(effective);+ } else {+ trig.kind = CompletionTriggerKind::Column;+ }+ return trig;+ }++ if (last.value == "(") {+ // INSERT INTO t (+ if (auto t = findInsertIntoParenContext(effective)) {+ trig.kind = CompletionTriggerKind::Column;+ trig.columnTable = t;+ return trig;+ }+ // Function args: if previous is a known function name, suggest columns.+ // (We don't have the function list here — delegate to generic Column.)+ trig.kind = CompletionTriggerKind::SelectList;+ trig.selectScopeTables = scope;+ return trig;+ }++ if (last.value == "=" || last.value == ">" || last.value == "<" || last.value == "!") {+ trig.kind = CompletionTriggerKind::Column;+ return trig;+ }++ // === Non-keyword last token (identifier, alias, table, column) ===+ if (prefix.isEmpty()) {+ trig.kind = CompletionTriggerKind::AfterIdentifier;+ trig.afterIdentClause = findCurrentClause(effective);+ trig.afterIdentScope = scope;+ return trig;+ }++ // === Prefix being typed ===+ if (auto kwDist = findPreviousKeywordWithDistance(effective)) {+ const QString kw = kwDist->first;+ const int distance = kwDist->second;++ if (kw == "FROM" || kw == "INTO" || kw == "TABLE") {+ trig.kind = (distance == 0) ? CompletionTriggerKind::Table+ : CompletionTriggerKind::Keyword;+ return trig;+ }+ if (kw == "UPDATE") {+ trig.kind = (distance == 0) ? CompletionTriggerKind::Table+ : CompletionTriggerKind::Keyword;+ return trig;+ }+ if (kw == "JOIN") {+ if (distance == 0) {+ trig.kind = CompletionTriggerKind::Join;+ trig.joinFromTables = scope;+ } else {+ trig.kind = CompletionTriggerKind::Keyword;+ }+ return trig;+ }+ if (kw == "SELECT" || kw == "DISTINCT") {+ trig.kind = CompletionTriggerKind::SelectList;+ trig.selectScopeTables = scope;+ return trig;+ }+ if (kw == "WHERE" || kw == "AND" || kw == "OR" || kw == "ON"+ || kw == "HAVING" || kw == "BY") {+ if (distance >= 2) {+ trig.kind = CompletionTriggerKind::Keyword;+ } else {+ trig.kind = CompletionTriggerKind::Column;+ }+ return trig;+ }+ if (kw == "SET") {+ if (distance == 0) {+ trig.kind = CompletionTriggerKind::Column;+ trig.columnTable = findUpdateTable(effective);+ } else {+ trig.kind = CompletionTriggerKind::Keyword;+ }+ return trig;+ }+ }++ trig.kind = CompletionTriggerKind::General;+ return trig;+}++} // namespace++CompletionContext SqlContextParser::parse(const QString& sql, int cursorOffset) const {+ const int safe = std::clamp<int>(cursorOffset, 0, static_cast<int>(sql.size()));+ const QString fullText = sql.left(safe);++ CompletionContext ctx;++ // Cursor inside a string literal → no completions.+ if (isInsideString(fullText)) {+ ctx.trigger.kind = CompletionTriggerKind::None;+ return ctx;+ }++ const QString statement = isolateCurrentStatement(fullText);+ ctx.prefix = currentWord(statement);++ const auto tokens = tokenize(statement);+ ctx.scopeTables = extractAllTables(tokens);+ ctx.trigger = determineTrigger(tokens, ctx.prefix, ctx.scopeTables);+ return ctx;+}++} // namespace gridexdiff --git a/linux/src/Presentation/Views/QueryEditor/Autocomplete/SqlContextParser.h b/linux/src/Presentation/Views/QueryEditor/Autocomplete/SqlContextParser.hnew file mode 100644index 0000000..df2a215--- /dev/null+++ b/linux/src/Presentation/Views/QueryEditor/Autocomplete/SqlContextParser.h@@ -0,0 +1,18 @@+#pragma once++#include "Presentation/Views/QueryEditor/Autocomplete/CompletionModels.h"++#include <QString>++namespace gridex {++// Parses SQL text up to cursor position to determine autocomplete context.+// Handles: statement isolation (split by ;), string literal detection,+// alias/CTE extraction, multi-table scope, compound keywords, positional+// awareness (clause-aware next-keyword suggestions).+class SqlContextParser {+public:+ CompletionContext parse(const QString& sql, int cursorOffset) const;+};++} // namespace gridexdiff --git a/linux/src/Presentation/Views/QueryEditor/QueryEditorView.cpp b/linux/src/Presentation/Views/QueryEditor/QueryEditorView.cppnew file mode 100644index 0000000..ca925c8--- /dev/null+++ b/linux/src/Presentation/Views/QueryEditor/QueryEditorView.cpp@@ -0,0 +1,569 @@+#include "Presentation/Views/QueryEditor/QueryEditorView.h"++#include <QAction>+#include <QApplication>+#include <QElapsedTimer>+#include <QFileDialog>+#include <QMenu>+#include <QMessageBox>+#include <QStandardPaths>+#include <QTextStream>+#include <QFile>+#include <QJsonArray>+#include <QJsonDocument>+#include <QJsonObject>+#include <QFont>+#include <QFrame>+#include <QHBoxLayout>+#include <QHeaderView>+#include <QInputMethodEvent>+#include <QKeyEvent>+#include <QLabel>+#include <QPlainTextEdit>+#include <QPointer>+#include <QPushButton>+#include <QScreen>+#include <QSplitter>+#include <QTableView>+#include <QTextBlock>+#include <QTextCursor>+#include <QTextLayout>+#include <QTimer>+#include <QtConcurrent/QtConcurrent>+#include <QVBoxLayout>++#include "Core/Errors/GridexError.h"+#include "Core/Protocols/Database/IDatabaseAdapter.h"+#include "Presentation/Views/DataGrid/QueryResultModel.h"+#include "Presentation/Views/QueryEditor/Autocomplete/AutocompleteProvider.h"+#include "Presentation/Views/QueryEditor/Autocomplete/CompletionModels.h"+#include "Presentation/Views/QueryEditor/Autocomplete/CompletionPopup.h"+#include "Presentation/Views/QueryEditor/Autocomplete/SqlContextParser.h"+#include "Presentation/Views/QueryEditor/SqlHighlighter.h"++namespace gridex {++namespace {++// QPlainTextEdit subclass that suppresses the built-in placeholder while an+// IME composition (preedit text) is active. Qt's paintEvent only checks+// document()->isEmpty() when deciding whether to draw the placeholder, not+// whether the current block has preedit text — so typing Vietnamese Telex/VNI+// leaves the placeholder overlapping the composing character until commit+// (space/punctuation). We swap placeholder text with "" for the duration of+// the paint, then restore it, so callers observe no state change.+class IMEAwareTextEdit : public QPlainTextEdit {+public:+ using QPlainTextEdit::QPlainTextEdit;++protected:+ void paintEvent(QPaintEvent* event) override {+ const bool suppress = document()->isEmpty() && hasPreeditText();+ QString savedPlaceholder;+ if (suppress) {+ savedPlaceholder = placeholderText();+ QPlainTextEdit::setPlaceholderText(QString{});+ }+ QPlainTextEdit::paintEvent(event);+ if (suppress) {+ QPlainTextEdit::setPlaceholderText(savedPlaceholder);+ }+ }++ void inputMethodEvent(QInputMethodEvent* event) override {+ QPlainTextEdit::inputMethodEvent(event);+ // Force viewport repaint so placeholder is cleared as soon as+ // preedit appears (instead of lagging until the next paint trigger).+ viewport()->update();+ }++private:+ bool hasPreeditText() const {+ auto* layout = textCursor().block().layout();+ return layout && !layout->preeditAreaText().isEmpty();+ }+};++} // namespace++QueryEditorView::QueryEditorView(QWidget* parent)+ : QWidget(parent),+ provider_(std::make_unique<AutocompleteProvider>()),+ parser_(std::make_unique<SqlContextParser>()) {+ buildUi();+}++QueryEditorView::~QueryEditorView() = default;++void QueryEditorView::buildUi() {+ auto* root = new QVBoxLayout(this);+ root->setContentsMargins(0, 0, 0, 0);+ root->setSpacing(0);++ // ---- Toolbar: [Run ▶] [status ...] ----+ auto* top = new QWidget(this);+ top->setFixedHeight(32);+ top->setAutoFillBackground(true);+ auto* topH = new QHBoxLayout(top);+ topH->setContentsMargins(8, 0, 12, 0);+ topH->setSpacing(10);++ runBtn_ = new QPushButton(tr("▶ Run"), top);+ runBtn_->setObjectName(QStringLiteral("primaryButton")); // styled in style.qss+ runBtn_->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Return));+ runBtn_->setToolTip(tr("Execute query (Ctrl+Enter)"));+ connect(runBtn_, &QPushButton::clicked, this, &QueryEditorView::onRunClicked);+ topH->addWidget(runBtn_);++ statusLbl_ = new QLabel(QString{}, top);+ topH->addWidget(statusLbl_, 1);++ auto* saveBtn = new QPushButton(tr("⭐ Save"), top);+ saveBtn->setToolTip(tr("Save this query to Saved Queries"));+ connect(saveBtn, &QPushButton::clicked, this, [this] {+ const QString sql = editor_ ? editor_->toPlainText().trimmed() : QString{};+ if (!sql.isEmpty()) emit saveQueryRequested(sql);+ });+ topH->addWidget(saveBtn);++ root->addWidget(top);++ auto* topDiv = new QFrame(this);+ topDiv->setFrameShape(QFrame::HLine);+ root->addWidget(topDiv);++ // ---- Splitter: editor (top) | result grid (bottom) ----+ splitter_ = new QSplitter(Qt::Vertical, this);++ editor_ = new IMEAwareTextEdit(splitter_);+ editor_->setPlaceholderText(tr("SELECT * FROM ..."));+ editor_->setFrameShape(QFrame::NoFrame);+ editor_->setTabStopDistance(32);+ QFont mono(QStringLiteral("Monospace"));+ mono.setStyleHint(QFont::Monospace);+ mono.setPointSize(12);+ editor_->setFont(mono);+ editor_->installEventFilter(this);+ hl_ = new SqlHighlighter(editor_->document());+ splitter_->addWidget(editor_);++ // ---- Autocomplete wiring ----+ popup_ = new CompletionPopup(this);+ popup_->hide();+ connect(popup_, &CompletionPopup::accepted, this, &QueryEditorView::acceptCompletion);+ connect(popup_, &CompletionPopup::dismissed, this, &QueryEditorView::hidePopup);++ // Debounce textChanged so we don't reparse on every keystroke for large+ // SQL files. 60ms feels instant while skipping rapid-fire edits.+ debounce_ = new QTimer(this);+ debounce_->setSingleShot(true);+ debounce_->setInterval(60);+ connect(debounce_, &QTimer::timeout, this, &QueryEditorView::maybeShowCompletions);+ connect(editor_, &QPlainTextEdit::textChanged, this, [this]() {+ if (debounce_) debounce_->start();+ });++ // Result grid below editor.+ resultView_ = new QTableView(splitter_);+ resultView_->setFrameShape(QFrame::NoFrame);+ resultView_->setAlternatingRowColors(true);+ resultView_->setShowGrid(true);+ resultView_->setSelectionBehavior(QAbstractItemView::SelectItems);+ resultView_->setEditTriggers(QAbstractItemView::NoEditTriggers);+ resultView_->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);+ resultView_->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);+ resultView_->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);+ resultView_->horizontalHeader()->setStretchLastSection(true);+ resultView_->verticalHeader()->setDefaultSectionSize(30);++ resultModel_ = new QueryResultModel(this);+ resultView_->setModel(resultModel_);+ splitter_->addWidget(resultView_);++ // ---- Export button overlay at bottom-right of result table ----+ exportResultMenu_ = new QMenu(resultView_);+ auto* actCsv = exportResultMenu_->addAction(tr("Export as CSV..."));+ auto* actSql = exportResultMenu_->addAction(tr("Export as SQL INSERT..."));+ auto* actJson = exportResultMenu_->addAction(tr("Export as JSON..."));+ connect(actCsv, &QAction::triggered, this, &QueryEditorView::exportResultAsCsv);+ connect(actSql, &QAction::triggered, this, &QueryEditorView::exportResultAsSql);+ connect(actJson, &QAction::triggered, this, &QueryEditorView::exportResultAsJson);++ exportResultBtn_ = new QPushButton(QStringLiteral("⇩ Export ▾"), resultView_);+ exportResultBtn_->setFixedSize(92, 26);+ exportResultBtn_->setToolTip(tr("Export query result"));+ exportResultBtn_->setCursor(Qt::PointingHandCursor);+ exportResultBtn_->setMenu(exportResultMenu_);+ exportResultBtn_->hide(); // shown when result has rows+ // Reposition on result view resize. Install filter on resultView_ so we+ // catch QEvent::Resize regardless of who triggered it (splitter, window).+ resultView_->installEventFilter(this);+ // Show/hide button when model data changes.+ connect(resultModel_, &QAbstractTableModel::modelReset, this, [this]() {+ const bool hasData = resultModel_->rowCount() > 0;+ exportResultBtn_->setVisible(hasData);+ if (hasData) {+ // Position: bottom-right with 14px margin to clear scrollbars.+ const int x = resultView_->width() - exportResultBtn_->width() - 14;+ const int y = resultView_->height() - exportResultBtn_->height() - 14;+ exportResultBtn_->move(x, y);+ exportResultBtn_->raise();+ }+ });++ splitter_->setStretchFactor(0, 1);+ splitter_->setStretchFactor(1, 2);+ splitter_->setSizes({200, 400});++ root->addWidget(splitter_, 1);+}++void QueryEditorView::setSql(const QString& sql) {+ if (editor_) editor_->setPlainText(sql);+}++void QueryEditorView::setAdapter(IDatabaseAdapter* adapter) {+ adapter_ = adapter;+ runBtn_->setEnabled(adapter_ != nullptr);+ if (!adapter_) {+ resultModel_->clear();+ statusLbl_->setText(QString{});+ if (provider_) provider_->updateSchema({});+ return;+ }+ reloadSchema();+}++void QueryEditorView::reloadSchema() {+ if (!adapter_ || !provider_) return;++ // Fetch listTables + describeTable on a worker thread so the UI doesn't+ // stall on large schemas. Result is applied back on the GUI thread.+ IDatabaseAdapter* adapter = adapter_;+ QPointer<QueryEditorView> self(this);+ (void)QtConcurrent::run([self, adapter]() {+ std::vector<TableDescription> tables;+ try {+ const auto infos = adapter->listTables(std::nullopt);+ for (const auto& info : infos) {+ if (info.type != TableKind::Table) continue;+ try {+ tables.push_back(adapter->describeTable(info.name, std::nullopt));+ } catch (...) { /* skip broken tables */ }+ }+ } catch (...) {+ // Best-effort. Empty schema is valid (just no suggestions).+ }+ QMetaObject::invokeMethod(qApp, [self, tables]() {+ if (self && self->provider_) self->provider_->updateSchema(tables);+ }, Qt::QueuedConnection);+ });+}++void QueryEditorView::hidePopup() {+ if (debounce_) debounce_->stop(); // cancel pending re-show+ if (popup_) popup_->hide();+}++void QueryEditorView::triggerCompletionNow() {+ // Force a fresh context computation regardless of prefix length.+ if (!provider_) return;+ const auto text = editor_->toPlainText();+ const int offset = editor_->textCursor().position();+ auto ctx = parser_->parse(text, offset);+ auto items = provider_->suggestions(ctx);+ if (items.empty()) { hidePopup(); return; }+ popup_->setItems(items);++ // Position popup just below the cursor.+ const auto rect = editor_->cursorRect();+ const QPoint gpos = editor_->viewport()->mapToGlobal(+ QPoint(rect.left(), rect.bottom() + 2));+ popup_->move(gpos);+ popup_->show();+ // X11/Wayland may pull focus to the newly-shown tool window despite+ // WA_ShowWithoutActivating — force focus back so keystrokes keep going+ // to the editor for inline filtering of the suggestion list.+ editor_->setFocus(Qt::OtherFocusReason);+}++void QueryEditorView::maybeShowCompletions() {+ if (!provider_) return;++ // Respect 2-char auto-trigger rule: only auto-popup when prefix has >=2+ // chars. Ctrl+Space still forces via triggerCompletionNow().+ const auto text = editor_->toPlainText();+ const int offset = editor_->textCursor().position();+ const auto ctx = parser_->parse(text, offset);+ if (ctx.prefix.size() < 2 && ctx.trigger.kind != CompletionTriggerKind::None) {+ hidePopup();+ return;+ }+ auto items = provider_->suggestions(ctx);+ if (items.empty()) { hidePopup(); return; }+ popup_->setItems(items);++ const auto rect = editor_->cursorRect();+ const QPoint gpos = editor_->viewport()->mapToGlobal(+ QPoint(rect.left(), rect.bottom() + 2));+ popup_->move(gpos);+ if (!popup_->isVisible()) {+ popup_->show();+ editor_->setFocus(Qt::OtherFocusReason);+ }+}++void QueryEditorView::acceptCompletion(const CompletionItem& item) {+ if (!editor_) return;+ // Replace current word (the in-progress prefix) with item.insertText.+ auto cursor = editor_->textCursor();+ // Walk back while previous char is [A-Za-z0-9_.]+ const QString doc = editor_->toPlainText();+ int pos = cursor.position();+ int start = pos;+ while (start > 0) {+ const QChar ch = doc.at(start - 1);+ if (ch.isLetterOrNumber() || ch == '_' || ch == '.') --start; else break;+ }+ cursor.setPosition(start, QTextCursor::MoveAnchor);+ cursor.setPosition(pos, QTextCursor::KeepAnchor);+ cursor.insertText(item.insertText);++ if (provider_) provider_->trackUsed(item.text);+ hidePopup();+}++void QueryEditorView::onRunClicked() {+ if (!adapter_) return;+ const auto sql = editor_->toPlainText().trimmed().toStdString();+ if (sql.empty()) return;++ statusLbl_->setText(tr("Running…"));++ QElapsedTimer timer;+ timer.start();+ try {+ auto result = adapter_->executeRaw(sql);+ const int n = static_cast<int>(result.rows.size());+ const int cols = static_cast<int>(result.columns.size());+ const int ms = static_cast<int>(timer.elapsed());+ resultModel_->setResult(std::move(result));+ resultView_->resizeColumnsToContents();++ // Stretch last column to fill viewport when total column width < view width.+ if (auto* h = resultView_->horizontalHeader()) {+ const int cc = resultModel_->columnCount();+ if (cc > 0) {+ int used = 0;+ for (int i = 0; i < cc - 1; ++i) used += h->sectionSize(i);+ const int avail = resultView_->viewport()->width() - used;+ if (avail > h->sectionSize(cc - 1))+ h->resizeSection(cc - 1, avail);+ }+ }++ statusLbl_->setStyleSheet(QStringLiteral("color: #a6e3a1;")); // success (catppuccin green)+ statusLbl_->setText(tr("%1 rows × %2 cols · %3 ms").arg(n).arg(cols).arg(ms));+ emit queryExecuted(QString::fromStdString(sql), n, ms);+ } catch (const GridexError& e) {+ resultModel_->clear();+ statusLbl_->setStyleSheet(QStringLiteral("color: #f38ba8;")); // error (catppuccin red)+ statusLbl_->setText(QString::fromUtf8(e.what()));+ }+}++bool QueryEditorView::eventFilter(QObject* obj, QEvent* event) {+ // Reposition export overlay when the result view resizes.+ if (obj == resultView_ && event->type() == QEvent::Resize+ && exportResultBtn_ && exportResultBtn_->isVisible()) {+ const int x = resultView_->width() - exportResultBtn_->width() - 14;+ const int y = resultView_->height() - exportResultBtn_->height() - 14;+ exportResultBtn_->move(x, y);+ }++ if (obj == editor_ && event->type() == QEvent::KeyPress) {+ auto* ke = static_cast<QKeyEvent*>(event);++ // Ctrl+Enter -> Run (takes priority over popup).+ if ((ke->key() == Qt::Key_Return || ke->key() == Qt::Key_Enter)+ && (ke->modifiers() & Qt::ControlModifier)) {+ onRunClicked();+ return true;+ }++ // Ctrl+Space -> force-open completion popup.+ if (ke->key() == Qt::Key_Space && (ke->modifiers() & Qt::ControlModifier)) {+ triggerCompletionNow();+ return true;+ }++ // While popup is visible, intercept navigation/accept/dismiss keys.+ if (popup_ && popup_->isVisible()) {+ switch (ke->key()) {+ case Qt::Key_Up: popup_->moveSelection(-1); return true;+ case Qt::Key_Down: popup_->moveSelection(+1); return true;+ case Qt::Key_Escape: hidePopup(); return true;+ case Qt::Key_Return:+ case Qt::Key_Enter:+ case Qt::Key_Tab:+ if (auto* it = popup_->selectedItem()) {+ acceptCompletion(*it);+ }+ return true;+ default:+ break;+ }+ }+ }+ return QWidget::eventFilter(obj, event);+}++// --------------------------------------------------------------------+// Result export+// --------------------------------------------------------------------++namespace {++// CSV cell: quote if value contains separator, quote char, CR/LF.+// Quote char inside cell is doubled. Null -> empty cell (standard CSV).+QString csvCell(const RowValue& v) {+ if (v.isNull()) return QString{};+ const QString s = QString::fromStdString(v.displayString());+ if (s.contains(',') || s.contains('"') || s.contains('\n') || s.contains('\r')) {+ QString escaped = s;+ escaped.replace('"', QStringLiteral("\"\""));+ return '"' + escaped + '"';+ }+ return s;+}++// SQL literal: NULL, numbers unquoted, strings with single-quote escape.+// Conservative: treat everything except NULL as string-literal. DB engines+// will coerce when inserting.+QString sqlLiteral(const RowValue& v) {+ if (v.isNull()) return QStringLiteral("NULL");+ const QString s = QString::fromStdString(v.displayString());+ // Numbers/booleans pass through unquoted.+ bool ok = false;+ s.toDouble(&ok);+ if (ok) return s;+ if (s == QLatin1String("true") || s == QLatin1String("false")) return s;+ QString escaped = s;+ escaped.replace('\'', QStringLiteral("''"));+ return '\'' + escaped + '\'';+}++// Default filename from the first column's table name if present, else+// "query-result".+QString defaultExportStem(const QueryResult& r) {+ for (const auto& c : r.columns) {+ if (c.tableName && !c.tableName->empty()) {+ return QString::fromStdString(*c.tableName);+ }+ }+ return QStringLiteral("query-result");+}++} // namespace++void QueryEditorView::exportResultAsCsv() {+ const auto& r = resultModel_->result();+ if (r.rows.empty()) return;++ const QString dir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);+ const QString defaultPath = dir + "/" + defaultExportStem(r) + ".csv";+ const QString path = QFileDialog::getSaveFileName(+ this, tr("Export Result as CSV"), defaultPath, tr("CSV (*.csv)"));+ if (path.isEmpty()) return;++ const QString outPath = path.endsWith(".csv", Qt::CaseInsensitive) ? path : path + ".csv";+ QFile f(outPath);+ if (!f.open(QIODevice::WriteOnly | QIODevice::Text)) {+ QMessageBox::warning(this, tr("Export CSV"),+ tr("Cannot open file for writing:\n%1").arg(outPath));+ return;+ }+ QTextStream out(&f);++ // Header+ QStringList header;+ for (const auto& c : r.columns) header << QString::fromStdString(c.name);+ out << header.join(',') << '\n';++ // Rows+ for (const auto& row : r.rows) {+ QStringList cells;+ cells.reserve(static_cast<int>(row.size()));+ for (const auto& v : row) cells << csvCell(v);+ out << cells.join(',') << '\n';+ }+}++void QueryEditorView::exportResultAsSql() {+ const auto& r = resultModel_->result();+ if (r.rows.empty()) return;++ const QString tableName = defaultExportStem(r);+ const QString dir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);+ const QString defaultPath = dir + "/" + tableName + ".sql";+ const QString path = QFileDialog::getSaveFileName(+ this, tr("Export Result as SQL"), defaultPath, tr("SQL (*.sql)"));+ if (path.isEmpty()) return;++ const QString outPath = path.endsWith(".sql", Qt::CaseInsensitive) ? path : path + ".sql";+ QFile f(outPath);+ if (!f.open(QIODevice::WriteOnly | QIODevice::Text)) {+ QMessageBox::warning(this, tr("Export SQL"),+ tr("Cannot open file for writing:\n%1").arg(outPath));+ return;+ }+ QTextStream out(&f);++ // Column list: "col1", "col2", ...+ QStringList colList;+ for (const auto& c : r.columns) colList << '"' + QString::fromStdString(c.name) + '"';+ const QString colsJoined = colList.join(", ");+ const QString header = QString("INSERT INTO \"%1\" (%2) VALUES").arg(tableName, colsJoined);++ for (const auto& row : r.rows) {+ QStringList vals;+ vals.reserve(static_cast<int>(row.size()));+ for (const auto& v : row) vals << sqlLiteral(v);+ out << header << " (" << vals.join(", ") << ");\n";+ }+}++void QueryEditorView::exportResultAsJson() {+ const auto& r = resultModel_->result();+ if (r.rows.empty()) return;++ const QString dir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);+ const QString defaultPath = dir + "/" + defaultExportStem(r) + ".json";+ const QString path = QFileDialog::getSaveFileName(+ this, tr("Export Result as JSON"), defaultPath, tr("JSON (*.json)"));+ if (path.isEmpty()) return;++ const QString outPath = path.endsWith(".json", Qt::CaseInsensitive) ? path : path + ".json";+ QFile f(outPath);+ if (!f.open(QIODevice::WriteOnly | QIODevice::Text)) {+ QMessageBox::warning(this, tr("Export JSON"),+ tr("Cannot open file for writing:\n%1").arg(outPath));+ return;+ }++ QJsonArray rowsArr;+ for (const auto& row : r.rows) {+ QJsonObject obj;+ for (std::size_t c = 0; c < r.columns.size() && c < row.size(); ++c) {+ const QString key = QString::fromStdString(r.columns[c].name);+ const auto& v = row[c];+ if (v.isNull()) obj.insert(key, QJsonValue::Null);+ else obj.insert(key, QString::fromStdString(v.displayString()));+ }+ rowsArr.append(obj);+ }+ QJsonDocument doc(rowsArr);+ f.write(doc.toJson(QJsonDocument::Indented));+}++}diff --git a/linux/src/Presentation/Views/QueryEditor/QueryEditorView.h b/linux/src/Presentation/Views/QueryEditor/QueryEditorView.hnew file mode 100644index 0000000..436755e--- /dev/null+++ b/linux/src/Presentation/Views/QueryEditor/QueryEditorView.h@@ -0,0 +1,76 @@+#pragma once++#include <QWidget>+#include <memory>++class QLabel;+class QMenu;+class QPlainTextEdit;+class QPushButton;+class QSplitter;+class QTableView;+class QTimer;++namespace gridex {++class IDatabaseAdapter;+class QueryResultModel;+class SqlHighlighter;+class AutocompleteProvider;+class CompletionPopup;+class SqlContextParser;+struct CompletionItem;++// Split view: SQL editor on top + result grid on bottom.+// Ctrl+Enter / Run button executes the current text via adapter.executeRaw.+class QueryEditorView : public QWidget {+ Q_OBJECT++public:+ explicit QueryEditorView(QWidget* parent = nullptr);+ ~QueryEditorView() override;++ void setAdapter(IDatabaseAdapter* adapter);+ void setSql(const QString& sql);++signals:+ void queryExecuted(const QString& sql, int rowCount, int durationMs);+ void saveQueryRequested(const QString& sql);++private slots:+ void onRunClicked();+ void maybeShowCompletions();+ void exportResultAsCsv();+ void exportResultAsSql();+ void exportResultAsJson();++private:+ void buildUi();+ bool eventFilter(QObject* obj, QEvent* event) override;++ // Autocomplete helpers+ void triggerCompletionNow(); // force (Ctrl+Space)+ void hidePopup();+ void acceptCompletion(const CompletionItem& item);+ void reloadSchema(); // async fetch via adapter++ IDatabaseAdapter* adapter_ = nullptr;++ QPlainTextEdit* editor_ = nullptr;+ SqlHighlighter* hl_ = nullptr;+ QPushButton* runBtn_ = nullptr;+ QLabel* statusLbl_ = nullptr;+ QSplitter* splitter_ = nullptr;+ QTableView* resultView_ = nullptr;+ QueryResultModel* resultModel_ = nullptr;++ QPushButton* exportResultBtn_ = nullptr;+ QMenu* exportResultMenu_ = nullptr;++ std::unique_ptr<AutocompleteProvider> provider_;+ std::unique_ptr<SqlContextParser> parser_;+ CompletionPopup* popup_ = nullptr;+ QTimer* debounce_ = nullptr;+};++}diff --git a/linux/src/Presentation/Views/QueryEditor/SqlHighlighter.cpp b/linux/src/Presentation/Views/QueryEditor/SqlHighlighter.cppnew file mode 100644index 0000000..958846a--- /dev/null+++ b/linux/src/Presentation/Views/QueryEditor/SqlHighlighter.cpp@@ -0,0 +1,148 @@+#include "Presentation/Views/QueryEditor/SqlHighlighter.h"++#include <QColor>++namespace gridex {++SqlHighlighter::SqlHighlighter(QTextDocument* parent) : QSyntaxHighlighter(parent) {+ // Keyword format — blue bold.+ keywordFmt_.setForeground(QColor(56, 118, 211));+ keywordFmt_.setFontWeight(QFont::Bold);++ // Function format — purple.+ functionFmt_.setForeground(QColor(136, 57, 195));++ // Type format — teal.+ typeFmt_.setForeground(QColor(0, 128, 128));++ // String format — green.+ stringFmt_.setForeground(QColor(80, 161, 79));++ // Number format — orange.+ numberFmt_.setForeground(QColor(206, 125, 30));++ // Comment format — gray italic.+ commentFmt_.setForeground(QColor(140, 140, 140));+ commentFmt_.setFontItalic(true);++ // SQL keywords (case insensitive).+ const QStringList keywords = {+ "SELECT", "FROM", "WHERE", "AND", "OR", "NOT", "IN", "BETWEEN", "LIKE",+ "IS", "NULL", "AS", "ON", "JOIN", "LEFT", "RIGHT", "INNER", "OUTER",+ "FULL", "CROSS", "NATURAL", "USING", "ORDER", "BY", "GROUP", "HAVING",+ "LIMIT", "OFFSET", "UNION", "ALL", "INTERSECT", "EXCEPT", "INSERT",+ "INTO", "VALUES", "UPDATE", "SET", "DELETE", "CREATE", "TABLE", "ALTER",+ "DROP", "INDEX", "VIEW", "DATABASE", "SCHEMA", "IF", "EXISTS", "CASCADE",+ "RESTRICT", "ADD", "COLUMN", "RENAME", "TO", "PRIMARY", "KEY", "FOREIGN",+ "REFERENCES", "UNIQUE", "CHECK", "DEFAULT", "CONSTRAINT", "BEGIN",+ "COMMIT", "ROLLBACK", "TRANSACTION", "SAVEPOINT", "GRANT", "REVOKE",+ "WITH", "RECURSIVE", "CASE", "WHEN", "THEN", "ELSE", "END", "DISTINCT",+ "ASC", "DESC", "NULLS", "FIRST", "LAST", "FETCH", "NEXT", "ROWS",+ "ONLY", "TRUE", "FALSE", "RETURNING", "EXPLAIN", "ANALYZE", "TRUNCATE",+ "TEMP", "TEMPORARY", "REPLACE", "CONFLICT", "DO", "NOTHING",+ };+ for (const auto& kw : keywords) {+ rules_.push_back({+ QRegularExpression("\\b" + kw + "\\b", QRegularExpression::CaseInsensitiveOption),+ keywordFmt_+ });+ }++ // SQL types.+ const QStringList types = {+ "INT", "INTEGER", "BIGINT", "SMALLINT", "TINYINT", "SERIAL", "BIGSERIAL",+ "TEXT", "VARCHAR", "CHAR", "CHARACTER", "BOOLEAN", "BOOL", "FLOAT",+ "DOUBLE", "DECIMAL", "NUMERIC", "REAL", "DATE", "TIME", "TIMESTAMP",+ "TIMESTAMPTZ", "INTERVAL", "UUID", "JSON", "JSONB", "BYTEA", "BLOB",+ "CLOB", "XML", "ARRAY", "MONEY", "BIT", "VARYING",+ };+ for (const auto& t : types) {+ rules_.push_back({+ QRegularExpression("\\b" + t + "\\b", QRegularExpression::CaseInsensitiveOption),+ typeFmt_+ });+ }++ // Common functions.+ const QStringList functions = {+ "COUNT", "SUM", "AVG", "MIN", "MAX", "COALESCE", "NULLIF", "CAST",+ "EXTRACT", "NOW", "CURRENT_TIMESTAMP", "CURRENT_DATE", "CURRENT_TIME",+ "LOWER", "UPPER", "LENGTH", "TRIM", "SUBSTRING", "REPLACE", "CONCAT",+ "ABS", "ROUND", "FLOOR", "CEIL", "CEILING", "RANDOM", "GREATEST",+ "LEAST", "ROW_NUMBER", "RANK", "DENSE_RANK", "LAG", "LEAD", "OVER",+ "PARTITION", "STRING_AGG", "ARRAY_AGG", "JSON_AGG", "JSONB_AGG",+ "FORMAT", "TO_CHAR", "TO_DATE", "TO_TIMESTAMP", "TO_NUMBER",+ "PG_TOTAL_RELATION_SIZE", "VERSION", "DATABASE", "SCHEMA",+ };+ for (const auto& fn : functions) {+ rules_.push_back({+ QRegularExpression("\\b" + fn + "\\s*(?=\\()", QRegularExpression::CaseInsensitiveOption),+ functionFmt_+ });+ }++ // Numbers.+ rules_.push_back({+ QRegularExpression("\\b\\d+\\.?\\d*([eE][+-]?\\d+)?\\b"),+ numberFmt_+ });++ // Single-quoted strings.+ rules_.push_back({+ QRegularExpression("'[^']*'"),+ stringFmt_+ });++ // Double-quoted identifiers (highlight distinctly with string fmt).+ rules_.push_back({+ QRegularExpression("\"[^\"]*\""),+ stringFmt_+ });++ // Single-line comments (-- ...)+ rules_.push_back({+ QRegularExpression("--[^\n]*"),+ commentFmt_+ });++ // Block comments handled specially via highlightBlock state.+ blockCommentStart_ = QRegularExpression("/\\*");+ blockCommentEnd_ = QRegularExpression("\\*/");+}++void SqlHighlighter::highlightBlock(const QString& text) {+ // Apply pattern-based rules first.+ for (const auto& rule : rules_) {+ auto it = rule.pattern.globalMatch(text);+ while (it.hasNext()) {+ auto match = it.next();+ setFormat(static_cast<int>(match.capturedStart()),+ static_cast<int>(match.capturedLength()),+ rule.format);+ }+ }++ // Block comments spanning multiple lines. State encodes whether we're inside /* */.+ setCurrentBlockState(0);+ int startIndex = 0;+ if (previousBlockState() != 1) {+ auto m = blockCommentStart_.match(text);+ startIndex = m.hasMatch() ? static_cast<int>(m.capturedStart()) : -1;+ }+ while (startIndex >= 0) {+ auto endMatch = blockCommentEnd_.match(text, startIndex + 2);+ int endIndex = endMatch.hasMatch() ? static_cast<int>(endMatch.capturedStart()) : -1;+ int length;+ if (endIndex < 0) {+ setCurrentBlockState(1);+ length = text.length() - startIndex;+ } else {+ length = endIndex - startIndex + static_cast<int>(endMatch.capturedLength());+ }+ setFormat(startIndex, length, commentFmt_);+ auto nextMatch = blockCommentStart_.match(text, startIndex + length);+ startIndex = nextMatch.hasMatch() ? static_cast<int>(nextMatch.capturedStart()) : -1;+ }+}++}diff --git a/linux/src/Presentation/Views/QueryEditor/SqlHighlighter.h b/linux/src/Presentation/Views/QueryEditor/SqlHighlighter.hnew file mode 100644index 0000000..c6d8697--- /dev/null+++ b/linux/src/Presentation/Views/QueryEditor/SqlHighlighter.h@@ -0,0 +1,40 @@+#pragma once++#include <QRegularExpression>+#include <QSyntaxHighlighter>+#include <QTextCharFormat>+#include <vector>++namespace gridex {++// Generic SQL syntax highlighter. Covers standard SQL keywords, strings,+// numbers, single-line (--) and block (/* */) comments, and common functions.+// Dialect-specific keywords can be added per-adapter later.+class SqlHighlighter : public QSyntaxHighlighter {+ Q_OBJECT++public:+ explicit SqlHighlighter(QTextDocument* parent = nullptr);++protected:+ void highlightBlock(const QString& text) override;++private:+ struct Rule {+ QRegularExpression pattern;+ QTextCharFormat format;+ };+ std::vector<Rule> rules_;++ QTextCharFormat keywordFmt_;+ QTextCharFormat functionFmt_;+ QTextCharFormat stringFmt_;+ QTextCharFormat numberFmt_;+ QTextCharFormat commentFmt_;+ QTextCharFormat typeFmt_;++ QRegularExpression blockCommentStart_;+ QRegularExpression blockCommentEnd_;+};++}diff --git a/linux/src/Presentation/Views/QueryLog/QueryLogPanel.cpp b/linux/src/Presentation/Views/QueryLog/QueryLogPanel.cppnew file mode 100644index 0000000..fecbe06--- /dev/null+++ b/linux/src/Presentation/Views/QueryLog/QueryLogPanel.cpp@@ -0,0 +1,87 @@+#include "Presentation/Views/QueryLog/QueryLogPanel.h"++#include <QDateTime>+#include <QFrame>+#include <QHBoxLayout>+#include <QLabel>+#include <QPlainTextEdit>+#include <QPushButton>+#include <QScrollBar>+#include <QVBoxLayout>++namespace gridex {++QueryLogPanel::QueryLogPanel(QWidget* parent) : QWidget(parent) {+ buildUi();+}++void QueryLogPanel::buildUi() {+ auto* root = new QVBoxLayout(this);+ root->setContentsMargins(0, 0, 0, 0);+ root->setSpacing(0);++ // ---- Header row (always visible) ----+ auto* topDiv = new QFrame(this);+ topDiv->setFrameShape(QFrame::HLine);+ root->addWidget(topDiv);++ header_ = new QWidget(this);+ header_->setObjectName("QueryLogHeader");+ header_->setFixedHeight(26);+ header_->setAutoFillBackground(true);+ auto* headerH = new QHBoxLayout(header_);+ headerH->setContentsMargins(8, 0, 8, 0);+ headerH->setSpacing(6);++ toggleBtn_ = new QPushButton(QStringLiteral("▾"), header_);+ toggleBtn_->setObjectName("QueryLogToggle");+ toggleBtn_->setFixedSize(20, 20);+ toggleBtn_->setCursor(Qt::PointingHandCursor);+ connect(toggleBtn_, &QPushButton::clicked, this, [this] {+ setExpanded(!expanded_);+ emit toggleRequested();+ });+ headerH->addWidget(toggleBtn_);++ titleLabel_ = new QLabel(tr("Console log"), header_);+ titleLabel_->setObjectName("QueryLogTitle");+ headerH->addWidget(titleLabel_);+ headerH->addStretch();++ auto* clearBtn = new QPushButton(tr("Clear"), header_);+ clearBtn->setObjectName("QueryLogClear");+ clearBtn->setCursor(Qt::PointingHandCursor);+ connect(clearBtn, &QPushButton::clicked, this, [this] {+ if (logEdit_) logEdit_->clear();+ });+ headerH->addWidget(clearBtn);++ root->addWidget(header_);++ // ---- Log body (collapsible) ----+ logEdit_ = new QPlainTextEdit(this);+ logEdit_->setObjectName("QueryLogEdit");+ logEdit_->setReadOnly(true);+ logEdit_->setMaximumHeight(130);+ logEdit_->setMinimumHeight(80);+ logEdit_->setPlaceholderText(tr("Execute a query or select a table to see the log"));+ root->addWidget(logEdit_);+}++void QueryLogPanel::appendQuery(const QString& sql, int durationMs) {+ if (!logEdit_) return;+ const QString ts = QDateTime::currentDateTime().toString(QStringLiteral("hh:mm:ss.zzz"));+ const QString line = QStringLiteral("[%1] (%2ms) %3").arg(ts).arg(durationMs).arg(sql.trimmed());+ logEdit_->appendPlainText(line);+ // Scroll to bottom so the latest entry is always visible.+ auto* sb = logEdit_->verticalScrollBar();+ if (sb) sb->setValue(sb->maximum());+}++void QueryLogPanel::setExpanded(bool expanded) {+ expanded_ = expanded;+ if (logEdit_) logEdit_->setVisible(expanded_);+ toggleBtn_->setText(expanded_ ? QStringLiteral("▾") : QStringLiteral("▸"));+}++}diff --git a/linux/src/Presentation/Views/QueryLog/QueryLogPanel.h b/linux/src/Presentation/Views/QueryLog/QueryLogPanel.hnew file mode 100644index 0000000..f0db20c--- /dev/null+++ b/linux/src/Presentation/Views/QueryLog/QueryLogPanel.h@@ -0,0 +1,41 @@+#pragma once++#include <QWidget>++class QLabel;+class QPlainTextEdit;+class QPushButton;++namespace gridex {++// Collapsible SQL log panel — shows executed queries with timestamps.+// Lives at the bottom of DataGridView below the table.+// Toggle visibility via the collapse button in the header row.+class QueryLogPanel : public QWidget {+ Q_OBJECT++public:+ explicit QueryLogPanel(QWidget* parent = nullptr);++ // Append a query entry; called after every adapter execution.+ void appendQuery(const QString& sql, int durationMs);++ // Expand / collapse the body (plain text area).+ void setExpanded(bool expanded);+ [[nodiscard]] bool isExpanded() const noexcept { return expanded_; }++signals:+ void toggleRequested();++private:+ void buildUi();++ bool expanded_ = true;++ QWidget* header_ = nullptr;+ QPushButton* toggleBtn_ = nullptr;+ QLabel* titleLabel_ = nullptr;+ QPlainTextEdit* logEdit_ = nullptr;+};++}diff --git a/linux/src/Presentation/Views/Redis/RedisKeyDetailView.cpp b/linux/src/Presentation/Views/Redis/RedisKeyDetailView.cppnew file mode 100644index 0000000..4d42427--- /dev/null+++ b/linux/src/Presentation/Views/Redis/RedisKeyDetailView.cpp@@ -0,0 +1,516 @@+#include "Presentation/Views/Redis/RedisKeyDetailView.h"++#include <QHBoxLayout>+#include <QLabel>+#include <QLineEdit>+#include <QListWidget>+#include <QMessageBox>+#include <QPlainTextEdit>+#include <QPushButton>+#include <QSpinBox>+#include <QStackedWidget>+#include <QTableWidget>+#include <QHeaderView>+#include <QVBoxLayout>++#include "Data/Adapters/Redis/RedisAdapter.h"++namespace gridex {++RedisKeyDetailView::RedisKeyDetailView(RedisAdapter* adapter,+ const QString& key,+ QWidget* parent)+ : QWidget(parent), adapter_(adapter), key_(key) {+ buildUi();+ reload();+}++void RedisKeyDetailView::buildUi() {+ auto* root = new QVBoxLayout(this);+ root->setContentsMargins(0, 0, 0, 0);+ root->setSpacing(0);+ buildHeader(root);++ auto* div = new QFrame(this);+ div->setFrameShape(QFrame::HLine);+ div->setFrameShadow(QFrame::Sunken);+ root->addWidget(div);++ body_ = new QStackedWidget(this);+ buildStringPage();+ buildListPage();+ buildHashPage();+ buildSetPage();+ buildZSetPage();+ buildStreamPage();+ root->addWidget(body_, 1);+}++void RedisKeyDetailView::buildHeader(QVBoxLayout* root) {+ auto* bar = new QWidget(this);+ bar->setFixedHeight(44);+ auto* h = new QHBoxLayout(bar);+ h->setContentsMargins(10, 0, 10, 0);+ h->setSpacing(8);++ auto* keyLabel = new QLabel(key_, bar);+ keyLabel->setStyleSheet(QStringLiteral("font-weight:600; font-family:monospace;"));+ h->addWidget(keyLabel);++ typeBadge_ = new QLabel(bar);+ typeBadge_->setStyleSheet(+ QStringLiteral("font-size:10px; font-weight:bold; padding:2px 6px;"+ " border-radius:3px; background:#5c6bc0; color:white;"));+ h->addWidget(typeBadge_);++ ttlLabel_ = new QLabel(bar);+ ttlLabel_->setStyleSheet(QStringLiteral("color:gray; font-size:11px;"));+ h->addWidget(ttlLabel_);++ h->addStretch(1);++ ttlSpin_ = new QSpinBox(bar);+ ttlSpin_->setRange(1, 2147483647);+ ttlSpin_->setValue(3600);+ ttlSpin_->setFixedWidth(80);+ ttlSpin_->setToolTip(tr("TTL in seconds"));+ h->addWidget(ttlSpin_);++ expireBtn_ = new QPushButton(tr("Expire"), bar);+ expireBtn_->setFixedHeight(26);+ connect(expireBtn_, &QPushButton::clicked, this, &RedisKeyDetailView::onExpire);+ h->addWidget(expireBtn_);++ persistBtn_ = new QPushButton(tr("Persist"), bar);+ persistBtn_->setFixedHeight(26);+ connect(persistBtn_, &QPushButton::clicked, this, &RedisKeyDetailView::onPersist);+ h->addWidget(persistBtn_);++ auto* delBtn = new QPushButton(tr("Delete Key"), bar);+ delBtn->setFixedHeight(26);+ delBtn->setStyleSheet(QStringLiteral("color:#e53935;"));+ connect(delBtn, &QPushButton::clicked, this, &RedisKeyDetailView::onDeleteKey);+ h->addWidget(delBtn);++ root->addWidget(bar);+}++void RedisKeyDetailView::buildStringPage() {+ stringPage_ = new QWidget(body_);+ auto* v = new QVBoxLayout(stringPage_);+ v->setContentsMargins(10, 10, 10, 10);+ v->setSpacing(6);++ strEdit_ = new QPlainTextEdit(stringPage_);+ strEdit_->setFont(QFont(QStringLiteral("monospace"), 11));+ v->addWidget(strEdit_, 1);++ auto* saveBtn = new QPushButton(tr("Save"), stringPage_);+ saveBtn->setFixedWidth(80);+ connect(saveBtn, &QPushButton::clicked, this, &RedisKeyDetailView::onStringSave);+ v->addWidget(saveBtn, 0, Qt::AlignRight);++ body_->addWidget(stringPage_);+}++void RedisKeyDetailView::buildListPage() {+ listPage_ = new QWidget(body_);+ auto* v = new QVBoxLayout(listPage_);+ v->setContentsMargins(10, 10, 10, 10);+ v->setSpacing(6);++ listWidget_ = new QListWidget(listPage_);+ listWidget_->setFont(QFont(QStringLiteral("monospace"), 11));+ v->addWidget(listWidget_, 1);++ auto* row = new QHBoxLayout;+ listInput_ = new QLineEdit(listPage_);+ listInput_->setPlaceholderText(tr("value"));+ row->addWidget(listInput_, 1);++ auto* pushHead = new QPushButton(tr("Push Head"), listPage_);+ connect(pushHead, &QPushButton::clicked, this, &RedisKeyDetailView::onListPushHead);+ row->addWidget(pushHead);++ auto* pushTail = new QPushButton(tr("Push Tail"), listPage_);+ connect(pushTail, &QPushButton::clicked, this, &RedisKeyDetailView::onListPushTail);+ row->addWidget(pushTail);++ auto* popHead = new QPushButton(tr("Pop Head"), listPage_);+ connect(popHead, &QPushButton::clicked, this, [this]{ onListPop(true); });+ row->addWidget(popHead);++ auto* popTail = new QPushButton(tr("Pop Tail"), listPage_);+ connect(popTail, &QPushButton::clicked, this, [this]{ onListPop(false); });+ row->addWidget(popTail);++ auto* remBtn = new QPushButton(tr("Remove"), listPage_);+ connect(remBtn, &QPushButton::clicked, this, &RedisKeyDetailView::onListRemove);+ row->addWidget(remBtn);++ v->addLayout(row);+ body_->addWidget(listPage_);+}++void RedisKeyDetailView::buildHashPage() {+ hashPage_ = new QWidget(body_);+ auto* v = new QVBoxLayout(hashPage_);+ v->setContentsMargins(10, 10, 10, 10);+ v->setSpacing(6);++ hashTable_ = new QTableWidget(0, 2, hashPage_);+ hashTable_->setHorizontalHeaderLabels({tr("Field"), tr("Value")});+ hashTable_->horizontalHeader()->setStretchLastSection(true);+ hashTable_->setSelectionBehavior(QAbstractItemView::SelectRows);+ hashTable_->setEditTriggers(QAbstractItemView::NoEditTriggers);+ v->addWidget(hashTable_, 1);++ auto* row = new QHBoxLayout;+ hashField_ = new QLineEdit(hashPage_);+ hashField_->setPlaceholderText(tr("field"));+ hashField_->setFixedWidth(140);+ row->addWidget(hashField_);++ hashValue_ = new QLineEdit(hashPage_);+ hashValue_->setPlaceholderText(tr("value"));+ row->addWidget(hashValue_, 1);++ auto* addBtn = new QPushButton(tr("Add / Update"), hashPage_);+ connect(addBtn, &QPushButton::clicked, this, &RedisKeyDetailView::onHashAdd);+ row->addWidget(addBtn);++ auto* delBtn = new QPushButton(tr("Delete Row"), hashPage_);+ connect(delBtn, &QPushButton::clicked, this, &RedisKeyDetailView::onHashDelete);+ row->addWidget(delBtn);++ v->addLayout(row);+ body_->addWidget(hashPage_);+}++void RedisKeyDetailView::buildSetPage() {+ setPage_ = new QWidget(body_);+ auto* v = new QVBoxLayout(setPage_);+ v->setContentsMargins(10, 10, 10, 10);+ v->setSpacing(6);++ setList_ = new QListWidget(setPage_);+ setList_->setFont(QFont(QStringLiteral("monospace"), 11));+ v->addWidget(setList_, 1);++ auto* row = new QHBoxLayout;+ setInput_ = new QLineEdit(setPage_);+ setInput_->setPlaceholderText(tr("member"));+ row->addWidget(setInput_, 1);++ auto* addBtn = new QPushButton(tr("Add"), setPage_);+ connect(addBtn, &QPushButton::clicked, this, &RedisKeyDetailView::onSetAdd);+ row->addWidget(addBtn);++ auto* remBtn = new QPushButton(tr("Remove"), setPage_);+ connect(remBtn, &QPushButton::clicked, this, &RedisKeyDetailView::onSetRemove);+ row->addWidget(remBtn);++ v->addLayout(row);+ body_->addWidget(setPage_);+}++void RedisKeyDetailView::buildZSetPage() {+ zsetPage_ = new QWidget(body_);+ auto* v = new QVBoxLayout(zsetPage_);+ v->setContentsMargins(10, 10, 10, 10);+ v->setSpacing(6);++ zsetTable_ = new QTableWidget(0, 2, zsetPage_);+ zsetTable_->setHorizontalHeaderLabels({tr("Member"), tr("Score")});+ zsetTable_->horizontalHeader()->setStretchLastSection(true);+ zsetTable_->setSelectionBehavior(QAbstractItemView::SelectRows);+ zsetTable_->setEditTriggers(QAbstractItemView::NoEditTriggers);+ v->addWidget(zsetTable_, 1);++ auto* row = new QHBoxLayout;+ zsetMember_ = new QLineEdit(zsetPage_);+ zsetMember_->setPlaceholderText(tr("member"));+ row->addWidget(zsetMember_, 1);++ zsetScore_ = new QLineEdit(zsetPage_);+ zsetScore_->setPlaceholderText(tr("score"));+ zsetScore_->setFixedWidth(80);+ row->addWidget(zsetScore_);++ auto* addBtn = new QPushButton(tr("Add / Update"), zsetPage_);+ connect(addBtn, &QPushButton::clicked, this, &RedisKeyDetailView::onZSetAdd);+ row->addWidget(addBtn);++ auto* remBtn = new QPushButton(tr("Remove"), zsetPage_);+ connect(remBtn, &QPushButton::clicked, this, &RedisKeyDetailView::onZSetRemove);+ row->addWidget(remBtn);++ v->addLayout(row);+ body_->addWidget(zsetPage_);+}++void RedisKeyDetailView::buildStreamPage() {+ streamPage_ = new QWidget(body_);+ auto* v = new QVBoxLayout(streamPage_);+ v->setContentsMargins(10, 10, 10, 10);++ streamTable_ = new QTableWidget(0, 2, streamPage_);+ streamTable_->setHorizontalHeaderLabels({tr("ID"), tr("Fields")});+ streamTable_->horizontalHeader()->setStretchLastSection(true);+ streamTable_->setEditTriggers(QAbstractItemView::NoEditTriggers);+ v->addWidget(streamTable_, 1);++ body_->addWidget(streamPage_);+}++// ---- reload ----++void RedisKeyDetailView::reload() {+ if (!adapter_) return;+ try {+ auto detail = adapter_->keyDetail(key_.toStdString());+ const QString type = QString::fromStdString(detail.type);+ typeBadge_->setText(type.toUpper());++ if (detail.ttl == -1) {+ ttlLabel_->setText(tr("no expiry"));+ } else if (detail.ttl == -2) {+ ttlLabel_->setText(tr("(missing)"));+ } else {+ ttlLabel_->setText(tr("TTL: %1s").arg(detail.ttl));+ }++ loadContent(detail.type);+ } catch (const std::exception& e) {+ showError(QString::fromUtf8(e.what()));+ }+}++void RedisKeyDetailView::loadContent(const std::string& type) {+ try {+ if (type == "string") {+ auto val = adapter_->getString(key_.toStdString());+ strEdit_->setPlainText(QString::fromStdString(val));+ body_->setCurrentWidget(stringPage_);++ } else if (type == "list") {+ auto items = adapter_->lrange(key_.toStdString());+ listWidget_->clear();+ for (const auto& it : items)+ listWidget_->addItem(QString::fromStdString(it));+ body_->setCurrentWidget(listPage_);++ } else if (type == "hash") {+ auto fields = adapter_->hgetall(key_.toStdString());+ hashTable_->setRowCount(0);+ for (const auto& [f, v] : fields) {+ const int r = hashTable_->rowCount();+ hashTable_->insertRow(r);+ hashTable_->setItem(r, 0, new QTableWidgetItem(QString::fromStdString(f)));+ hashTable_->setItem(r, 1, new QTableWidgetItem(QString::fromStdString(v)));+ }+ body_->setCurrentWidget(hashPage_);++ } else if (type == "set") {+ auto members = adapter_->smembers(key_.toStdString());+ setList_->clear();+ for (const auto& m : members)+ setList_->addItem(QString::fromStdString(m));+ body_->setCurrentWidget(setPage_);++ } else if (type == "zset") {+ auto members = adapter_->zrangeWithScores(key_.toStdString());+ zsetTable_->setRowCount(0);+ for (const auto& [m, s] : members) {+ const int r = zsetTable_->rowCount();+ zsetTable_->insertRow(r);+ zsetTable_->setItem(r, 0, new QTableWidgetItem(QString::fromStdString(m)));+ zsetTable_->setItem(r, 1, new QTableWidgetItem(QString::number(s)));+ }+ body_->setCurrentWidget(zsetPage_);++ } else if (type == "stream") {+ auto entries = adapter_->xrevrange(key_.toStdString(), 50);+ streamTable_->setRowCount(0);+ for (const auto& entry : entries) {+ const int r = streamTable_->rowCount();+ streamTable_->insertRow(r);+ streamTable_->setItem(r, 0, new QTableWidgetItem(+ QString::fromStdString(entry.id)));+ QString fields;+ for (const auto& [fk, fv] : entry.fields)+ fields += QString::fromStdString(fk) + "=" + QString::fromStdString(fv) + " ";+ streamTable_->setItem(r, 1, new QTableWidgetItem(fields.trimmed()));+ }+ body_->setCurrentWidget(streamPage_);+ }+ } catch (const std::exception& e) {+ showError(QString::fromUtf8(e.what()));+ }+}++// ---- slots ----++void RedisKeyDetailView::onPersist() {+ try {+ adapter_->persistKey(key_.toStdString());+ reload();+ } catch (const std::exception& e) { showError(QString::fromUtf8(e.what())); }+}++void RedisKeyDetailView::onExpire() {+ try {+ adapter_->expireKey(key_.toStdString(), ttlSpin_->value());+ reload();+ } catch (const std::exception& e) { showError(QString::fromUtf8(e.what())); }+}++void RedisKeyDetailView::onDeleteKey() {+ try {+ adapter_->deleteKey(key_.toStdString());+ emit keyDeleted(key_);+ } catch (const std::exception& e) { showError(QString::fromUtf8(e.what())); }+}++void RedisKeyDetailView::onStringSave() {+ try {+ adapter_->setString(key_.toStdString(), strEdit_->toPlainText().toStdString());+ reload();+ } catch (const std::exception& e) { showError(QString::fromUtf8(e.what())); }+}++void RedisKeyDetailView::onListPushHead() {+ const auto val = listInput_->text().trimmed();+ if (val.isEmpty()) return;+ try {+ adapter_->lpush(key_.toStdString(), val.toStdString());+ listInput_->clear();+ reload();+ } catch (const std::exception& e) { showError(QString::fromUtf8(e.what())); }+}++void RedisKeyDetailView::onListPushTail() {+ const auto val = listInput_->text().trimmed();+ if (val.isEmpty()) return;+ try {+ adapter_->rpush(key_.toStdString(), val.toStdString());+ listInput_->clear();+ reload();+ } catch (const std::exception& e) { showError(QString::fromUtf8(e.what())); }+}++void RedisKeyDetailView::onListPop(bool head) {+ try {+ if (head) adapter_->lpop(key_.toStdString());+ else adapter_->rpop(key_.toStdString());+ reload();+ } catch (const std::exception& e) { showError(QString::fromUtf8(e.what())); }+}++void RedisKeyDetailView::onListRemove() {+ const auto val = listInput_->text().trimmed();+ if (val.isEmpty()) {+ auto* cur = listWidget_->currentItem();+ if (!cur) return;+ try {+ adapter_->lrem(key_.toStdString(), cur->text().toStdString());+ reload();+ } catch (const std::exception& e) { showError(QString::fromUtf8(e.what())); }+ return;+ }+ try {+ adapter_->lrem(key_.toStdString(), val.toStdString());+ reload();+ } catch (const std::exception& e) { showError(QString::fromUtf8(e.what())); }+}++void RedisKeyDetailView::onHashAdd() {+ const auto field = hashField_->text().trimmed();+ if (field.isEmpty()) return;+ try {+ adapter_->hset(key_.toStdString(), field.toStdString(),+ hashValue_->text().toStdString());+ hashField_->clear();+ hashValue_->clear();+ reload();+ } catch (const std::exception& e) { showError(QString::fromUtf8(e.what())); }+}++void RedisKeyDetailView::onHashDelete() {+ const int row = hashTable_->currentRow();+ if (row < 0) return;+ auto* item = hashTable_->item(row, 0);+ if (!item) return;+ try {+ adapter_->hdel(key_.toStdString(), item->text().toStdString());+ reload();+ } catch (const std::exception& e) { showError(QString::fromUtf8(e.what())); }+}++void RedisKeyDetailView::onSetAdd() {+ const auto member = setInput_->text().trimmed();+ if (member.isEmpty()) return;+ try {+ adapter_->sadd(key_.toStdString(), member.toStdString());+ setInput_->clear();+ reload();+ } catch (const std::exception& e) { showError(QString::fromUtf8(e.what())); }+}++void RedisKeyDetailView::onSetRemove() {+ const auto member = setInput_->text().trimmed();+ if (!member.isEmpty()) {+ try {+ adapter_->srem(key_.toStdString(), member.toStdString());+ setInput_->clear();+ reload();+ } catch (const std::exception& e) { showError(QString::fromUtf8(e.what())); }+ return;+ }+ auto* cur = setList_->currentItem();+ if (!cur) return;+ try {+ adapter_->srem(key_.toStdString(), cur->text().toStdString());+ reload();+ } catch (const std::exception& e) { showError(QString::fromUtf8(e.what())); }+}++void RedisKeyDetailView::onZSetAdd() {+ const auto member = zsetMember_->text().trimmed();+ if (member.isEmpty()) return;+ bool ok = false;+ const double score = zsetScore_->text().toDouble(&ok);+ if (!ok) { showError(tr("Invalid score")); return; }+ try {+ adapter_->zadd(key_.toStdString(), score, member.toStdString());+ zsetMember_->clear();+ zsetScore_->clear();+ reload();+ } catch (const std::exception& e) { showError(QString::fromUtf8(e.what())); }+}++void RedisKeyDetailView::onZSetRemove() {+ const auto member = zsetMember_->text().trimmed();+ if (!member.isEmpty()) {+ try {+ adapter_->zrem(key_.toStdString(), member.toStdString());+ zsetMember_->clear();+ reload();+ } catch (const std::exception& e) { showError(QString::fromUtf8(e.what())); }+ return;+ }+ const int row = zsetTable_->currentRow();+ if (row < 0) return;+ auto* item = zsetTable_->item(row, 0);+ if (!item) return;+ try {+ adapter_->zrem(key_.toStdString(), item->text().toStdString());+ reload();+ } catch (const std::exception& e) { showError(QString::fromUtf8(e.what())); }+}++void RedisKeyDetailView::showError(const QString& msg) {+ QMessageBox::warning(this, tr("Redis Error"), msg);+}++} // namespace gridexdiff --git a/linux/src/Presentation/Views/Redis/RedisKeyDetailView.h b/linux/src/Presentation/Views/Redis/RedisKeyDetailView.hnew file mode 100644index 0000000..a81f0eb--- /dev/null+++ b/linux/src/Presentation/Views/Redis/RedisKeyDetailView.h@@ -0,0 +1,95 @@+#pragma once++#include <QWidget>+#include <string>++class QLabel;+class QLineEdit;+class QListWidget;+class QPlainTextEdit;+class QPushButton;+class QSpinBox;+class QStackedWidget;+class QTableWidget;+class QVBoxLayout;++namespace gridex {++class RedisAdapter;++class RedisKeyDetailView : public QWidget {+ Q_OBJECT+public:+ explicit RedisKeyDetailView(RedisAdapter* adapter,+ const QString& key,+ QWidget* parent = nullptr);++ void reload();++signals:+ void keyDeleted(const QString& key);++private slots:+ void onPersist();+ void onExpire();+ void onDeleteKey();+ void onStringSave();+ void onListPushHead();+ void onListPushTail();+ void onListPop(bool head);+ void onListRemove();+ void onHashAdd();+ void onHashDelete();+ void onSetAdd();+ void onSetRemove();+ void onZSetAdd();+ void onZSetRemove();++private:+ void buildUi();+ void buildHeader(QVBoxLayout* root);+ void buildStringPage();+ void buildListPage();+ void buildHashPage();+ void buildSetPage();+ void buildZSetPage();+ void buildStreamPage();+ void loadContent(const std::string& type);+ void showError(const QString& msg);++ RedisAdapter* adapter_ = nullptr;+ QString key_;++ QLabel* typeBadge_ = nullptr;+ QLabel* ttlLabel_ = nullptr;+ QSpinBox* ttlSpin_ = nullptr;+ QPushButton* persistBtn_ = nullptr;+ QPushButton* expireBtn_ = nullptr;+ QStackedWidget* body_ = nullptr;++ QWidget* stringPage_ = nullptr;+ QPlainTextEdit* strEdit_ = nullptr;++ QWidget* listPage_ = nullptr;+ QListWidget* listWidget_ = nullptr;+ QLineEdit* listInput_ = nullptr;++ QWidget* hashPage_ = nullptr;+ QTableWidget* hashTable_ = nullptr;+ QLineEdit* hashField_ = nullptr;+ QLineEdit* hashValue_ = nullptr;++ QWidget* setPage_ = nullptr;+ QListWidget* setList_ = nullptr;+ QLineEdit* setInput_ = nullptr;++ QWidget* zsetPage_ = nullptr;+ QTableWidget* zsetTable_ = nullptr;+ QLineEdit* zsetMember_ = nullptr;+ QLineEdit* zsetScore_ = nullptr;++ QWidget* streamPage_ = nullptr;+ QTableWidget* streamTable_ = nullptr;+};++} // namespace gridexdiff --git a/linux/src/Presentation/Views/Settings/SettingsDialog.cpp b/linux/src/Presentation/Views/Settings/SettingsDialog.cppnew file mode 100644index 0000000..91cbed9--- /dev/null+++ b/linux/src/Presentation/Views/Settings/SettingsDialog.cpp@@ -0,0 +1,380 @@+#include "Presentation/Views/Settings/SettingsDialog.h"++#include <QApplication>+#include <QComboBox>+#include <QFormLayout>+#include <QFrame>+#include <QFutureWatcher>+#include <QHBoxLayout>+#include <QLabel>+#include <QLineEdit>+#include <QListWidget>+#include <QMessageBox>+#include <QPointer>+#include <QProgressBar>+#include <QPushButton>+#include <QSettings>+#include <QStackedWidget>+#include <QTimer>+#include <QToolButton>+#include <QVBoxLayout>+#include <QtConcurrent/QtConcurrent>++#include "Data/Keychain/SecretStore.h"+#include "Presentation/Theme/ThemeManager.h"+#include "Presentation/ViewModels/AIChatViewModel.h"+#include "Services/AI/AIServiceFactory.h"++namespace gridex {++namespace {++constexpr const char* kProviders[] = {"Anthropic", "OpenAI", "Ollama", "Gemini"};++QString endpointKey(const QString& provider) {+ return QStringLiteral("ai/endpoint/") + provider;+}++QString endpointPlaceholder(const QString& provider) {+ if (provider == QLatin1String("Ollama"))+ return QStringLiteral("http://localhost:11434");+ if (provider == QLatin1String("OpenAI"))+ return QStringLiteral("https://api.openai.com/v1 (or OpenAI-compatible URL)");+ if (provider == QLatin1String("Anthropic"))+ return QStringLiteral("https://api.anthropic.com");+ if (provider == QLatin1String("Gemini"))+ return QStringLiteral("https://generativelanguage.googleapis.com");+ return QStringLiteral("https://…");+}++} // namespace++SettingsDialog::SettingsDialog(SecretStore* secretStore, QWidget* parent)+ : QDialog(parent), secretStore_(secretStore) {+ buildUi();+ // Initial load from saved default.+ QSettings s;+ const QString savedProvider = s.value("ai/provider", QStringLiteral("Anthropic")).toString();+ providerCombo_->setCurrentText(savedProvider);+ onProviderChanged(savedProvider);+}++void SettingsDialog::buildUi() {+ setWindowTitle(tr("Preferences"));+ setMinimumSize(720, 440);++ auto* root = new QHBoxLayout(this);+ root->setContentsMargins(0, 0, 0, 0);+ root->setSpacing(0);++ navList_ = new QListWidget(this);+ navList_->setFixedWidth(180);+ navList_->setFrameShape(QFrame::NoFrame);+ navList_->addItem(tr("AI Providers"));+ navList_->addItem(tr("Appearance"));+ root->addWidget(navList_);++ auto* div = new QFrame(this);+ div->setFrameShape(QFrame::VLine);+ root->addWidget(div);++ pages_ = new QStackedWidget(this);+ root->addWidget(pages_, 1);++ auto* aiPage = new QWidget(pages_);+ buildAiPage(aiPage);+ pages_->addWidget(aiPage);++ auto* appearancePage = new QWidget(pages_);+ buildAppearancePage(appearancePage);+ pages_->addWidget(appearancePage);++ connect(navList_, &QListWidget::currentRowChanged,+ pages_, &QStackedWidget::setCurrentIndex);+ navList_->setCurrentRow(0);+}++void SettingsDialog::buildAiPage(QWidget* page) {+ auto* root = new QVBoxLayout(page);+ root->setContentsMargins(24, 24, 24, 24);+ root->setSpacing(14);++ auto* title = new QLabel(tr("AI Providers"), page);+ {+ QFont f = title->font();+ f.setPointSize(14);+ f.setWeight(QFont::DemiBold);+ title->setFont(f);+ }+ root->addWidget(title);++ auto* desc = new QLabel(+ tr("Pick a provider and model. API keys are stored encrypted in the "+ "system keychain (libsecret); endpoints override the default base "+ "URL (useful for self-hosted or OpenAI-compatible servers)."),+ page);+ desc->setWordWrap(true);+ desc->setForegroundRole(QPalette::PlaceholderText);+ root->addWidget(desc);++ auto* form = new QFormLayout();+ form->setLabelAlignment(Qt::AlignRight);+ form->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);+ form->setHorizontalSpacing(12);+ form->setVerticalSpacing(10);++ // Provider+ providerCombo_ = new QComboBox(page);+ for (const char* p : kProviders) providerCombo_->addItem(p);+ connect(providerCombo_, &QComboBox::currentTextChanged,+ this, &SettingsDialog::onProviderChanged);+ form->addRow(tr("Provider:"), providerCombo_);++ // Model + spinner+ auto* modelRow = new QWidget(page);+ auto* mrH = new QHBoxLayout(modelRow);+ mrH->setContentsMargins(0, 0, 0, 0);+ mrH->setSpacing(6);+ modelCombo_ = new QComboBox(modelRow);+ modelCombo_->setMinimumWidth(260);+ connect(modelCombo_, &QComboBox::currentTextChanged,+ this, &SettingsDialog::onModelChanged);+ mrH->addWidget(modelCombo_, 1);+ modelSpinner_ = new QProgressBar(modelRow);+ modelSpinner_->setFixedSize(80, 16);+ modelSpinner_->setRange(0, 0); // indeterminate animation+ modelSpinner_->setTextVisible(false);+ modelSpinner_->hide();+ mrH->addWidget(modelSpinner_);+ modelStatus_ = new QLabel(modelRow);+ modelStatus_->setForegroundRole(QPalette::PlaceholderText);+ mrH->addWidget(modelStatus_);+ form->addRow(tr("Model:"), modelRow);++ // API Key + eye toggle+ auto* keyRow = new QWidget(page);+ auto* keyH = new QHBoxLayout(keyRow);+ keyH->setContentsMargins(0, 0, 0, 0);+ keyH->setSpacing(6);+ apiKeyEdit_ = new QLineEdit(keyRow);+ apiKeyEdit_->setEchoMode(QLineEdit::Password);+ apiKeyEdit_->setClearButtonEnabled(true);+ apiKeyEdit_->setPlaceholderText(tr("Paste API key…"));+ // Debounce: wait 600 ms after the user stops typing, then fetch models.+ keyDebounce_ = new QTimer(this);+ keyDebounce_->setSingleShot(true);+ keyDebounce_->setInterval(600);+ connect(keyDebounce_, &QTimer::timeout, this, &SettingsDialog::onKeyEditTimeout);+ connect(apiKeyEdit_, &QLineEdit::textChanged, this, [this](const QString&) {+ keyDebounce_->start();+ });+ keyH->addWidget(apiKeyEdit_, 1);+ auto* eye = new QToolButton(keyRow);+ eye->setText(QStringLiteral("👁"));+ eye->setToolTip(tr("Show/hide key"));+ eye->setCheckable(true);+ connect(eye, &QToolButton::toggled, this, [this](bool on) {+ apiKeyEdit_->setEchoMode(on ? QLineEdit::Normal : QLineEdit::Password);+ });+ keyH->addWidget(eye);+ form->addRow(tr("API Key:"), keyRow);++ // Custom endpoint+ endpointEdit_ = new QLineEdit(page);+ endpointEdit_->setClearButtonEnabled(true);+ form->addRow(tr("Custom endpoint:"), endpointEdit_);++ root->addLayout(form);+ root->addStretch();++ // Save / Close row+ auto* btnRow = new QWidget(page);+ auto* btnH = new QHBoxLayout(btnRow);+ btnH->setContentsMargins(0, 0, 0, 0);+ btnH->addStretch();++ auto* closeBtn = new QPushButton(tr("Close"), btnRow);+ connect(closeBtn, &QPushButton::clicked, this, &QDialog::accept);+ btnH->addWidget(closeBtn);++ saveBtn_ = new QPushButton(tr("Save"), btnRow);+ saveBtn_->setObjectName(QStringLiteral("primaryButton"));+ saveBtn_->setDefault(true);+ connect(saveBtn_, &QPushButton::clicked, this, &SettingsDialog::onSaveClicked);+ btnH->addWidget(saveBtn_);++ root->addWidget(btnRow);+}++void SettingsDialog::loadForProvider(const QString& provider) {+ // API key from keychain.+ QString savedKey;+ if (secretStore_ && secretStore_->isAvailable()) {+ const auto key = secretStore_->loadAPIKey(provider.toStdString());+ if (key) savedKey = QString::fromStdString(*key);+ }+ apiKeyEdit_->blockSignals(true);+ apiKeyEdit_->setText(savedKey);+ apiKeyEdit_->blockSignals(false);++ // Custom endpoint.+ QSettings s;+ endpointEdit_->setPlaceholderText(endpointPlaceholder(provider));+ endpointEdit_->setText(s.value(endpointKey(provider)).toString());++ // Fetch models with the saved key (empty key falls back to hardcoded+ // defaults without hitting the network).+ fetchModels(provider, savedKey);+}++void SettingsDialog::onKeyEditTimeout() {+ fetchModels(providerCombo_->currentText(), apiKeyEdit_->text().trimmed());+}++void SettingsDialog::fetchModels(const QString& provider, const QString& apiKey) {+ // Show spinner + status while fetching.+ modelSpinner_->show();+ modelStatus_->setText(tr("Loading models…"));+ modelCombo_->setEnabled(false);++ // Snapshot the saved selection so we can try to restore it after refresh.+ QSettings s;+ const QString savedProvider = s.value("ai/provider").toString();+ const QString savedModel = s.value("ai/model").toString();++ const auto providerStd = provider.toStdString();+ const auto keyStd = apiKey.toStdString();+ // Pick up a custom endpoint — user may be typing it right now.+ const auto urlStd = endpointEdit_->text().trimmed().toStdString();++ auto* watcher = new QFutureWatcher<std::vector<LLMModel>>(this);+ connect(watcher, &QFutureWatcher<std::vector<LLMModel>>::finished, this,+ [this, watcher, provider, savedProvider, savedModel]() {+ const auto models = watcher->result();+ watcher->deleteLater();++ // Ignore if the user already switched to a different provider.+ if (providerCombo_->currentText() != provider) return;++ modelCombo_->blockSignals(true);+ modelCombo_->clear();+ for (const auto& m : models) {+ modelCombo_->addItem(QString::fromStdString(m.name),+ QString::fromStdString(m.id));+ }+ if (!savedModel.isEmpty() && provider == savedProvider) {+ int idx = modelCombo_->findData(savedModel);+ if (idx < 0) idx = modelCombo_->findText(savedModel);+ if (idx >= 0) modelCombo_->setCurrentIndex(idx);+ }+ modelCombo_->blockSignals(false);++ modelSpinner_->hide();+ modelCombo_->setEnabled(true);+ if (models.empty()) {+ const bool hasKey = !apiKeyEdit_->text().trimmed().isEmpty();+ modelStatus_->setText(hasKey+ ? tr("No models returned — check API key or endpoint.")+ : tr("Enter API key to load models."));+ } else {+ modelStatus_->setText(tr("%1 models").arg(models.size()));+ }+ });++ auto future = QtConcurrent::run([providerStd, keyStd, urlStd]() {+ try {+ auto svc = AIServiceFactory::createAIService(providerStd, keyStd, urlStd);+ return svc->availableModels();+ } catch (...) {+ return std::vector<LLMModel>{};+ }+ });+ watcher->setFuture(future);+}++void SettingsDialog::onProviderChanged(const QString& provider) {+ loadForProvider(provider);+}++void SettingsDialog::onModelChanged(const QString& /*modelName*/) {+ // No-op until Save; avoids writing on every keystroke.+}++void SettingsDialog::buildAppearancePage(QWidget* page) {+ auto* root = new QVBoxLayout(page);+ root->setContentsMargins(24, 24, 24, 24);+ root->setSpacing(14);++ auto* title = new QLabel(tr("Appearance"), page);+ {+ QFont f = title->font();+ f.setPointSize(14);+ f.setWeight(QFont::DemiBold);+ title->setFont(f);+ }+ root->addWidget(title);++ auto* form = new QFormLayout();+ form->setLabelAlignment(Qt::AlignRight);+ form->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);+ form->setHorizontalSpacing(12);+ form->setVerticalSpacing(10);++ themeCombo_ = new QComboBox(page);+ themeCombo_->addItem(tr("Light"), QStringLiteral("Light"));+ themeCombo_->addItem(tr("Dark"), QStringLiteral("Dark"));+ themeCombo_->addItem(tr("Auto (system)"), QStringLiteral("Auto"));++ const auto current = ThemeManager::instance().mode();+ const int idx = (current == ThemeManager::Mode::Light) ? 0+ : (current == ThemeManager::Mode::Dark) ? 1+ : 2;+ themeCombo_->setCurrentIndex(idx);++ connect(themeCombo_, &QComboBox::currentIndexChanged, this, [this](int i) {+ const ThemeManager::Mode mode = (i == 0) ? ThemeManager::Mode::Light+ : (i == 1) ? ThemeManager::Mode::Dark+ : ThemeManager::Mode::Auto;+ ThemeManager::instance().setMode(mode, qobject_cast<QApplication*>(QApplication::instance()));+ });++ form->addRow(tr("Theme:"), themeCombo_);+ root->addLayout(form);+ root->addStretch();+}++void SettingsDialog::onSaveClicked() {+ const QString provider = providerCombo_->currentText();+ const QString model = modelCombo_->currentData().toString().isEmpty()+ ? modelCombo_->currentText()+ : modelCombo_->currentData().toString();+ const QString key = apiKeyEdit_->text().trimmed();+ const QString endpoint = endpointEdit_->text().trimmed();++ // Persist default provider + model (used by AIChatViewModel on start).+ QSettings s;+ s.setValue("ai/provider", provider);+ if (!model.isEmpty()) s.setValue("ai/model", model);++ // Custom endpoint (may be empty to fall back to provider default).+ if (endpoint.isEmpty()) s.remove(endpointKey(provider));+ else s.setValue(endpointKey(provider), endpoint);++ // API key → system keychain.+ if (secretStore_) {+ try {+ if (key.isEmpty()) {+ secretStore_->remove(std::string("ai.apikey.") + provider.toStdString());+ } else {+ secretStore_->saveAPIKey(provider.toStdString(), key.toStdString());+ }+ } catch (const std::exception& e) {+ QMessageBox::critical(this, tr("Save failed"), QString::fromUtf8(e.what()));+ return;+ }+ }++ accept();+}++} // namespace gridexdiff --git a/linux/src/Presentation/Views/Settings/SettingsDialog.h b/linux/src/Presentation/Views/Settings/SettingsDialog.hnew file mode 100644index 0000000..4d46818--- /dev/null+++ b/linux/src/Presentation/Views/Settings/SettingsDialog.h@@ -0,0 +1,56 @@+#pragma once++#include <QDialog>++class QComboBox;+class QLabel;+class QLineEdit;+class QListWidget;+class QProgressBar;+class QPushButton;+class QStackedWidget;+class QTimer;++namespace gridex {++class SecretStore;++class SettingsDialog : public QDialog {+ Q_OBJECT+public:+ explicit SettingsDialog(SecretStore* secretStore, QWidget* parent = nullptr);++private slots:+ void onProviderChanged(const QString& provider);+ void onModelChanged(const QString& modelName);+ void onSaveClicked();+ void onKeyEditTimeout();++private:+ void buildUi();+ void buildAiPage(QWidget* page);+ void buildAppearancePage(QWidget* page);+ void loadForProvider(const QString& provider);+ void fetchModels(const QString& provider, const QString& apiKey);++ SecretStore* secretStore_ = nullptr;++ QListWidget* navList_ = nullptr;+ QStackedWidget* pages_ = nullptr;++ // AI page controls.+ QComboBox* providerCombo_ = nullptr;+ QComboBox* modelCombo_ = nullptr;+ QLineEdit* apiKeyEdit_ = nullptr;+ QLineEdit* endpointEdit_ = nullptr;+ QProgressBar* modelSpinner_ = nullptr;+ QLabel* modelStatus_ = nullptr;+ QPushButton* saveBtn_ = nullptr;++ QTimer* keyDebounce_ = nullptr;++ // Appearance page controls.+ QComboBox* themeCombo_ = nullptr;+};++} // namespace gridexdiff --git a/linux/src/Presentation/Views/Sidebar/ConnectionRowWidget.cpp b/linux/src/Presentation/Views/Sidebar/ConnectionRowWidget.cppnew file mode 100644index 0000000..69e03ca--- /dev/null+++ b/linux/src/Presentation/Views/Sidebar/ConnectionRowWidget.cpp@@ -0,0 +1,122 @@+#include "Presentation/Views/Sidebar/ConnectionRowWidget.h"++#include <QHBoxLayout>+#include <QLabel>+#include <QString>+#include <QVBoxLayout>++namespace gridex {++namespace {++// Brand-inspired palette per DB type — matches macOS DatabaseTypeIcon hues.+struct IconSpec { QString hex; QString letter; };+IconSpec iconSpec(DatabaseType t) {+ switch (t) {+ case DatabaseType::PostgreSQL: return {"#336791", "P"};+ case DatabaseType::MySQL: return {"#F29111", "M"};+ case DatabaseType::SQLite: return {"#003B57", "S"};+ case DatabaseType::Redis: return {"#DC382D", "R"};+ case DatabaseType::MongoDB: return {"#4DB33D", "M"};+ case DatabaseType::MSSQL: return {"#CC2927", "T"};+ }+ return {"#888888", "?"};+}++QString subtitleFor(const ConnectionConfig& c) {+ if (c.databaseType == DatabaseType::SQLite) {+ return c.filePath ? QString::fromUtf8(c.filePath->c_str()) : QStringLiteral("No file");+ }+ QString s = QString::fromUtf8(c.displayHost().c_str());+ if (c.database && !c.database->empty()) {+ s += QStringLiteral(" / ") + QString::fromUtf8(c.database->c_str());+ }+ return s;+}++}++ConnectionRowWidget::ConnectionRowWidget(const ConnectionConfig& config, QWidget* parent)+ : QWidget(parent), connectionId_(QString::fromUtf8(config.id.c_str())) {+ buildUi(config);+ applyPalette();+}++void ConnectionRowWidget::buildUi(const ConnectionConfig& config) {+ setAutoFillBackground(true);+ setAttribute(Qt::WA_StyledBackground, true);++ auto* root = new QHBoxLayout(this);+ root->setContentsMargins(10, 8, 10, 8);+ root->setSpacing(12);++ // --- 1) Color bar (3×28) ---+ colorBar_ = new QLabel(this);+ colorBar_->setFixedSize(3, 28);+ if (config.colorTag) {+ const auto rgb = rgbColor(*config.colorTag);+ colorBar_->setStyleSheet(QString("background-color: rgb(%1,%2,%3); border-radius: 1px;")+ .arg(rgb.r).arg(rgb.g).arg(rgb.b));+ }+ root->addWidget(colorBar_);++ // --- 2) DB type icon (32×32 rounded square with letter) ---+ const auto spec = iconSpec(config.databaseType);+ iconBox_ = new QWidget(this);+ iconBox_->setFixedSize(32, 32);+ iconBox_->setStyleSheet(QString("background-color: %1; border-radius: 7px;").arg(spec.hex));+ auto* iconLay = new QVBoxLayout(iconBox_);+ iconLay->setContentsMargins(0, 0, 0, 0);+ iconLetter_ = new QLabel(spec.letter, iconBox_);+ iconLetter_->setAlignment(Qt::AlignCenter);+ iconLay->addWidget(iconLetter_);+ root->addWidget(iconBox_);++ // --- 3) Name + env badge + subtitle ---+ auto* textCol = new QVBoxLayout();+ textCol->setContentsMargins(0, 0, 0, 0);+ textCol->setSpacing(3);++ auto* nameRow = new QHBoxLayout();+ nameRow->setContentsMargins(0, 0, 0, 0);+ nameRow->setSpacing(6);+ nameLabel_ = new QLabel(QString::fromUtf8(config.name.c_str()), this);+ nameRow->addWidget(nameLabel_);++ if (config.colorTag) {+ const auto rgb = rgbColor(*config.colorTag);+ envBadge_ = new QLabel(QString::fromUtf8(std::string(environmentHint(*config.colorTag)).c_str()).toUpper(), this);+ envBadge_->setStyleSheet(+ QString("color: rgb(%1,%2,%3); font-size: 9px; font-weight: 700;"+ "letter-spacing: 0.3px;"+ "background-color: rgba(%1,%2,%3,36); padding: 1px 5px; border-radius: 3px;")+ .arg(rgb.r).arg(rgb.g).arg(rgb.b));+ nameRow->addWidget(envBadge_);+ }+ nameRow->addStretch();+ textCol->addLayout(nameRow);++ subtitle_ = new QLabel(subtitleFor(config), this);+ subtitle_->setTextFormat(Qt::PlainText);+ textCol->addWidget(subtitle_);+ root->addLayout(textCol, 1);++ // --- 4) DB type label ---+ typeLabel_ = new QLabel(+ QString::fromUtf8(std::string(displayName(config.databaseType)).c_str()).toUpper(),+ this);+ root->addWidget(typeLabel_);+}++void ConnectionRowWidget::setSelected(bool selected) {+ if (selected_ == selected) return;+ selected_ = selected;+ applyPalette();+}++void ConnectionRowWidget::applyPalette() {+ // Hover + selection background are drawn by the QListWidget::item rule in+ // style.qss — the custom row widget just paints its children.+}++}diff --git a/linux/src/Presentation/Views/Sidebar/ConnectionRowWidget.h b/linux/src/Presentation/Views/Sidebar/ConnectionRowWidget.hnew file mode 100644index 0000000..d5e9185--- /dev/null+++ b/linux/src/Presentation/Views/Sidebar/ConnectionRowWidget.h@@ -0,0 +1,40 @@+#pragma once++#include <QWidget>++#include "Core/Models/Database/ConnectionConfig.h"++class QLabel;++namespace gridex {++// Single connection row matching macOS ConnectionRow layout:+// [colorBar 3x28] [DBIcon 32x32] [Name + envBadge + subtitle] [spacer] [TYPE]+// Selection + hover are driven by the parent QListWidget's state through+// setSelected(bool).+class ConnectionRowWidget : public QWidget {+ Q_OBJECT++public:+ explicit ConnectionRowWidget(const ConnectionConfig& config, QWidget* parent = nullptr);++ void setSelected(bool selected);+ [[nodiscard]] QString connectionId() const { return connectionId_; }++private:+ void buildUi(const ConnectionConfig& config);+ void applyPalette();++ QString connectionId_;+ bool selected_ = false;++ QLabel* colorBar_ = nullptr;+ QWidget* iconBox_ = nullptr;+ QLabel* iconLetter_ = nullptr;+ QLabel* nameLabel_ = nullptr;+ QLabel* envBadge_ = nullptr;+ QLabel* subtitle_ = nullptr;+ QLabel* typeLabel_ = nullptr;+};++}diff --git a/linux/src/Presentation/Views/Sidebar/ConnectionSidebar.cpp b/linux/src/Presentation/Views/Sidebar/ConnectionSidebar.cppnew file mode 100644index 0000000..0723931--- /dev/null+++ b/linux/src/Presentation/Views/Sidebar/ConnectionSidebar.cpp@@ -0,0 +1,285 @@+#include "Presentation/Views/Sidebar/ConnectionSidebar.h"++#include <QAction>+#include <QFrame>+#include <QHBoxLayout>+#include <QInputDialog>+#include <QLabel>+#include <QLineEdit>+#include <QMenu>+#include <QPushButton>+#include <QStackedWidget>+#include <QTreeWidget>+#include <QTreeWidgetItem>+#include <QVBoxLayout>+#include <QVariant>++#include "Data/Persistence/AppDatabase.h"+#include "Presentation/ViewModels/ConnectionListViewModel.h"+#include "Presentation/Views/Sidebar/ConnectionRowWidget.h"++namespace gridex {++namespace {+constexpr int kRoleConnectionId = Qt::UserRole + 1;+constexpr int kRoleIsGroup = Qt::UserRole + 2;+constexpr int kPageEmpty = 0;+constexpr int kPageTree = 1;++QPushButton* makeToolbarButton(const QString& icon, const QString& tooltip, QWidget* parent) {+ auto* btn = new QPushButton(icon, parent);+ btn->setToolTip(tooltip);+ btn->setFixedSize(28, 28);+ return btn;+}+}++ConnectionSidebar::ConnectionSidebar(ConnectionListViewModel* viewModel,+ std::shared_ptr<AppDatabase> appDb,+ QWidget* parent)+ : QWidget(parent), viewModel_(viewModel), appDb_(std::move(appDb)) {+ buildUi();+ if (viewModel_) {+ connect(viewModel_, &ConnectionListViewModel::connectionsChanged,+ this, &ConnectionSidebar::onViewModelChanged);+ onViewModelChanged();+ }+}++void ConnectionSidebar::buildUi() {+ auto* root = new QVBoxLayout(this);+ root->setContentsMargins(0, 0, 0, 0);+ root->setSpacing(0);++ auto* toolbar = new QWidget(this);+ auto* h = new QHBoxLayout(toolbar);+ h->setContentsMargins(16, 10, 16, 10);+ h->setSpacing(10);++ searchEdit_ = new QLineEdit(toolbar);+ searchEdit_->setPlaceholderText(tr("Search connections..."));+ searchEdit_->setClearButtonEnabled(true);+ connect(searchEdit_, &QLineEdit::textChanged,+ this, &ConnectionSidebar::onSearchChanged);+ h->addWidget(searchEdit_, 1);++ auto* addBtn = makeToolbarButton(QStringLiteral("+"), tr("New Connection"), toolbar);+ connect(addBtn, &QPushButton::clicked, this, &ConnectionSidebar::addConnectionRequested);+ h->addWidget(addBtn);++ auto* groupBtn = makeToolbarButton(QStringLiteral("🗀⁺"), tr("New Group"), toolbar);+ connect(groupBtn, &QPushButton::clicked, this, &ConnectionSidebar::newGroupRequested);+ h->addWidget(groupBtn);++ root->addWidget(toolbar);++ auto* div = new QFrame(this);+ div->setFrameShape(QFrame::HLine);+ root->addWidget(div);++ body_ = new QStackedWidget(this);++ // Page 0: empty state+ auto* empty = new QWidget(body_);+ auto* ev = new QVBoxLayout(empty);+ ev->setContentsMargins(24, 24, 24, 24);+ ev->addStretch();+ auto* emptyIcon = new QLabel(QStringLiteral("🗄"), empty);+ emptyIcon->setAlignment(Qt::AlignCenter);+ ev->addWidget(emptyIcon);+ auto* emptyTitle = new QLabel(tr("No connections yet"), empty);+ emptyTitle->setAlignment(Qt::AlignCenter);+ ev->addWidget(emptyTitle);+ auto* emptySub = new QLabel(tr("Create your first database connection to get started"), empty);+ emptySub->setAlignment(Qt::AlignCenter);+ emptySub->setWordWrap(true);+ ev->addWidget(emptySub);+ auto* createBtn = new QPushButton(tr("Create Connection"), empty);+ connect(createBtn, &QPushButton::clicked, this, &ConnectionSidebar::addConnectionRequested);+ auto* createRow = new QHBoxLayout();+ createRow->addStretch();+ createRow->addWidget(createBtn);+ createRow->addStretch();+ ev->addSpacing(8);+ ev->addLayout(createRow);+ ev->addStretch();+ body_->addWidget(empty);++ // Page 1: grouped tree+ tree_ = new QTreeWidget(body_);+ tree_->setHeaderHidden(true);+ tree_->setFrameShape(QFrame::NoFrame);+ tree_->setContextMenuPolicy(Qt::CustomContextMenu);+ tree_->setSelectionMode(QAbstractItemView::SingleSelection);+ tree_->setRootIsDecorated(true);+ connect(tree_, &QTreeWidget::itemDoubleClicked,+ this, &ConnectionSidebar::onItemDoubleClicked);+ connect(tree_, &QTreeWidget::customContextMenuRequested,+ this, &ConnectionSidebar::onContextMenuRequested);+ body_->addWidget(tree_);++ body_->setCurrentIndex(kPageEmpty);+ root->addWidget(body_, 1);+}++void ConnectionSidebar::onViewModelChanged() {+ tree_->clear();+ if (!viewModel_) return;++ const auto search = searchEdit_->text().toLower();+ const auto& connections = viewModel_->connections();++ QMap<QString, QTreeWidgetItem*> groupItems;+ int shownCount = 0;++ auto getOrCreateGroup = [&](const QString& groupName) -> QTreeWidgetItem* {+ if (groupItems.contains(groupName)) return groupItems[groupName];+ auto* gi = new QTreeWidgetItem(tree_);+ gi->setText(0, groupName);+ gi->setData(0, kRoleIsGroup, true);+ gi->setData(0, kRoleConnectionId, QString{});+ gi->setFlags(gi->flags() & ~Qt::ItemIsSelectable);+ groupItems[groupName] = gi;+ return gi;+ };++ for (const auto& c : connections) {+ const QString name = QString::fromUtf8(c.name.c_str());+ if (!search.isEmpty() && !name.toLower().contains(search)) continue;++ const QString groupName = c.group+ ? QString::fromUtf8(c.group->c_str())+ : tr("Ungrouped");++ auto* parent = getOrCreateGroup(groupName);++ auto* item = new QTreeWidgetItem(parent);+ item->setData(0, kRoleConnectionId, QString::fromUtf8(c.id.c_str()));+ item->setData(0, kRoleIsGroup, false);+ item->setSizeHint(0, QSize(0, 52));++ auto* row = new ConnectionRowWidget(c, tree_);+ tree_->setItemWidget(item, 0, row);+ ++shownCount;+ }++ tree_->expandAll();++ const bool hasAny = !connections.empty();+ body_->setCurrentIndex((hasAny || !search.isEmpty()) ? kPageTree : kPageEmpty);+}++void ConnectionSidebar::onSearchChanged(const QString&) {+ onViewModelChanged();+}++QString ConnectionSidebar::idOfItem(QTreeWidgetItem* item) const {+ if (!item) return {};+ return item->data(0, kRoleConnectionId).toString();+}++void ConnectionSidebar::onItemDoubleClicked(QTreeWidgetItem* item, int) {+ if (!item || item->data(0, kRoleIsGroup).toBool()) return;+ const auto id = idOfItem(item);+ if (!id.isEmpty()) emit connectionSelected(id);+}++void ConnectionSidebar::onContextMenuRequested(const QPoint& pos) {+ auto* item = tree_->itemAt(pos);+ QMenu menu(this);++ if (item && item->data(0, kRoleIsGroup).toBool()) {+ const QString groupName = item->text(0);++ auto* renameAct = menu.addAction(tr("Rename Group..."));+ connect(renameAct, &QAction::triggered, this, [this, groupName] {+ bool ok = false;+ const QString newName = QInputDialog::getText(+ this, tr("Rename Group"), tr("New name:"),+ QLineEdit::Normal, groupName, &ok);+ if (!ok || newName.trimmed().isEmpty()) return;+ if (!appDb_) return;+ // Move all connections in this group to newName+ if (viewModel_) {+ for (const auto& c : viewModel_->connections()) {+ const QString cGroup = c.group+ ? QString::fromUtf8(c.group->c_str()) : tr("Ungrouped");+ if (cGroup == groupName) {+ try {+ appDb_->setConnectionGroup(c.id, newName.trimmed().toStdString());+ } catch (...) {}+ }+ }+ viewModel_->reload();+ }+ });++ auto* deleteGroupAct = menu.addAction(tr("Delete Group"));+ connect(deleteGroupAct, &QAction::triggered, this, [this, groupName] {+ if (!appDb_ || !viewModel_) return;+ for (const auto& c : viewModel_->connections()) {+ const QString cGroup = c.group+ ? QString::fromUtf8(c.group->c_str()) : tr("Ungrouped");+ if (cGroup == groupName) {+ try { appDb_->setConnectionGroup(c.id, {}); } catch (...) {}+ }+ }+ viewModel_->reload();+ });++ menu.addSeparator();++ } else if (item && !item->data(0, kRoleIsGroup).toBool()) {+ const auto id = idOfItem(item);++ auto* openAct = menu.addAction(tr("Connect"));+ connect(openAct, &QAction::triggered, this,+ [this, id] { emit connectionSelected(id); });++ auto* editAct = menu.addAction(tr("Edit…"));+ connect(editAct, &QAction::triggered, this,+ [this, id] { emit editConnectionRequested(id); });++ auto* moveAct = menu.addAction(tr("Move to Group..."));+ connect(moveAct, &QAction::triggered, this, [this, id] {+ if (!appDb_ || !viewModel_) return;+ // Collect existing group names+ QStringList groups;+ groups << tr("(Ungrouped)");+ for (const auto& c : viewModel_->connections()) {+ if (c.group) {+ const QString g = QString::fromUtf8(c.group->c_str());+ if (!groups.contains(g)) groups << g;+ }+ }+ bool ok = false;+ const QString chosen = QInputDialog::getItem(+ this, tr("Move to Group"), tr("Select or type a group:"),+ groups, 0, /*editable*/ true, &ok);+ if (!ok) return;+ const std::string newGroup = (chosen == tr("(Ungrouped)"))+ ? std::string{} : chosen.trimmed().toStdString();+ try {+ appDb_->setConnectionGroup(id.toStdString(), newGroup);+ viewModel_->reload();+ } catch (const std::exception& e) {+ (void)e;+ }+ });++ menu.addSeparator();++ auto* delAct = menu.addAction(tr("Delete"));+ connect(delAct, &QAction::triggered, this,+ [this, id] { emit removeConnectionRequested(id); });++ menu.addSeparator();+ }++ auto* addAct = menu.addAction(tr("New Connection…"));+ connect(addAct, &QAction::triggered, this, &ConnectionSidebar::addConnectionRequested);++ menu.exec(tree_->viewport()->mapToGlobal(pos));+}++}diff --git a/linux/src/Presentation/Views/Sidebar/ConnectionSidebar.h b/linux/src/Presentation/Views/Sidebar/ConnectionSidebar.hnew file mode 100644index 0000000..0989621--- /dev/null+++ b/linux/src/Presentation/Views/Sidebar/ConnectionSidebar.h@@ -0,0 +1,50 @@+#pragma once++#include <memory>+#include <QWidget>+#include <string>++class QLineEdit;+class QStackedWidget;+class QTreeWidget;+class QTreeWidgetItem;++namespace gridex {++class AppDatabase;+class ConnectionListViewModel;++class ConnectionSidebar : public QWidget {+ Q_OBJECT++public:+ explicit ConnectionSidebar(ConnectionListViewModel* viewModel,+ std::shared_ptr<AppDatabase> appDb,+ QWidget* parent = nullptr);++signals:+ void addConnectionRequested();+ void newGroupRequested();+ void editConnectionRequested(const QString& connectionId);+ void removeConnectionRequested(const QString& connectionId);+ void connectionSelected(const QString& connectionId);++private slots:+ void onViewModelChanged();+ void onContextMenuRequested(const QPoint& pos);+ void onSearchChanged(const QString& text);+ void onItemDoubleClicked(QTreeWidgetItem* item, int column);++private:+ void buildUi();+ QString idOfItem(QTreeWidgetItem* item) const;++ ConnectionListViewModel* viewModel_;+ std::shared_ptr<AppDatabase> appDb_;++ QLineEdit* searchEdit_ = nullptr;+ QStackedWidget* body_ = nullptr;+ QTreeWidget* tree_ = nullptr;+};++}diff --git a/linux/src/Presentation/Views/Sidebar/WorkspaceSidebar.cpp b/linux/src/Presentation/Views/Sidebar/WorkspaceSidebar.cppnew file mode 100644index 0000000..d5fb0c3--- /dev/null+++ b/linux/src/Presentation/Views/Sidebar/WorkspaceSidebar.cpp@@ -0,0 +1,1226 @@+#include "Presentation/Views/Sidebar/WorkspaceSidebar.h"++#include <chrono>+#include <QApplication>+#include <QClipboard>+#include <QComboBox>+#include <QFile>+#include <QFileDialog>+#include <QFrame>+#include <QHBoxLayout>+#include <QHeaderView>+#include <QInputDialog>+#include <QLabel>+#include <QLineEdit>+#include <QListWidget>+#include <QListWidgetItem>+#include <QMenu>+#include <QMessageBox>+#include <QPushButton>+#include <QStackedWidget>+#include <QStandardItem>+#include <QStandardItemModel>+#include <QStandardPaths>+#include <QTextStream>+#include <QTreeView>+#include <QTreeWidget>+#include <QTreeWidgetItem>+#include <QVBoxLayout>++#include "Core/Errors/GridexError.h"+#include "Core/Utils/SqlStatementSplitter.h"+#include "Presentation/Views/ImportSQL/SqlImportWizard.h"+#include "Core/Enums/DatabaseType.h"+#include "Core/Enums/SQLDialect.h"+#include "Core/Models/Schema/SchemaSnapshot.h"+#include "Data/Keychain/SecretStore.h"+#include "Data/Persistence/AppDatabase.h"+#include "Data/Persistence/SavedQueryRepository.h"+#include "Presentation/ViewModels/WorkspaceState.h"+#include "Presentation/Views/Backup/BackupProgressDialog.h"+#include "Presentation/Views/TableList/TableGridView.h"+#include "Services/Export/DatabaseDumpRunner.h"+#include "Services/Export/ExportService.h"++namespace gridex {++namespace {++constexpr int kRoleKind = Qt::UserRole + 1;+constexpr int kRoleSchemaName = Qt::UserRole + 2;+constexpr int kRoleTableName = Qt::UserRole + 3;+constexpr int kRoleLoaded = Qt::UserRole + 4;+constexpr int kRoleRoutineName = Qt::UserRole + 5;++enum NodeKind {+ NodeSchema = 1,+ NodeTable = 2,+ NodePlaceholder = 3,+ NodeFunctionsGroup = 4,+ NodeProceduresGroup = 5,+ NodeFunction = 6,+ NodeProcedure = 7+};++// splitSqlStatements is defined in Core/Utils/SqlStatementSplitter.h++// Parse one CSV row according to RFC 4180. Input is a single line (or block+// when the row spans newlines inside quotes). We operate on the full CSV+// blob and advance a cursor so that multi-line quoted fields work.+struct CsvParser {+ QString text;+ int pos = 0;++ bool atEnd() const { return pos >= text.size(); }++ // Returns next row as list of fields; empty vector when no more rows.+ QStringList readRow() {+ QStringList fields;+ if (atEnd()) return fields;++ QString cell;+ bool quoted = false;+ while (pos < text.size()) {+ const QChar c = text.at(pos);+ if (quoted) {+ if (c == '"') {+ if (pos + 1 < text.size() && text.at(pos + 1) == '"') {+ cell.append('"');+ pos += 2;+ continue;+ }+ quoted = false;+ ++pos;+ continue;+ }+ cell.append(c);+ ++pos;+ continue;+ }+ if (c == '"' && cell.isEmpty()) { quoted = true; ++pos; continue; }+ if (c == ',') { fields << cell; cell.clear(); ++pos; continue; }+ if (c == '\r') { ++pos; continue; } // ignore+ if (c == '\n') { ++pos; fields << cell; return fields; }+ cell.append(c);+ ++pos;+ }+ // Last field (no trailing newline)+ fields << cell;+ return fields;+ }+};++QPushButton* makeTabButton(const QString& glyph, const QString& tooltip, QWidget* parent) {+ auto* btn = new QPushButton(glyph, parent);+ btn->setCheckable(true);+ btn->setAutoExclusive(true);+ btn->setCursor(Qt::PointingHandCursor);+ btn->setFixedHeight(28);+ btn->setToolTip(tooltip);+ btn->setFlat(true);+ btn->setProperty("tab", true); // styled via style.qss QPushButton[tab="true"]+ return btn;+}++}++WorkspaceSidebar::~WorkspaceSidebar() = default;++WorkspaceSidebar::WorkspaceSidebar(WorkspaceState* state,+ std::shared_ptr<AppDatabase> appDb,+ QWidget* parent)+ : QWidget(parent), state_(state), appDb_(std::move(appDb)) {+ if (appDb_) savedQueryRepo_ = std::make_unique<SavedQueryRepository>(appDb_);+ buildUi();+ if (appDb_) loadHistoryFromDb();+ if (savedQueryRepo_) reloadSavedQueriesTree();+ if (state_) {+ connect(state_, &WorkspaceState::connectionOpened,+ this, &WorkspaceSidebar::onConnectionOpened);+ connect(state_, &WorkspaceState::connectionClosed,+ this, &WorkspaceSidebar::onConnectionClosed);+ if (state_->isOpen()) onConnectionOpened();+ }+}++void WorkspaceSidebar::buildUi() {+ auto* root = new QVBoxLayout(this);+ root->setContentsMargins(0, 0, 0, 0);+ root->setSpacing(0);++ // ---- Tab bar (Items / Queries / History) ----+ auto* tabBar = new QWidget(this);+ auto* tabH = new QHBoxLayout(tabBar);+ tabH->setContentsMargins(6, 4, 6, 4);+ tabH->setSpacing(1);++ itemsTabBtn_ = makeTabButton(QStringLiteral("🗂"), tr("Items"), tabBar);+ queriesTabBtn_ = makeTabButton(QStringLiteral("📄"), tr("Queries"), tabBar);+ historyTabBtn_ = makeTabButton(QStringLiteral("🕑"), tr("History"), tabBar);+ savedTabBtn_ = makeTabButton(QStringLiteral("⭐"), tr("Saved"), tabBar);+ itemsTabBtn_->setChecked(true);+ tabH->addWidget(itemsTabBtn_, 1);+ tabH->addWidget(queriesTabBtn_, 1);+ tabH->addWidget(historyTabBtn_, 1);+ tabH->addWidget(savedTabBtn_, 1);+ connect(itemsTabBtn_, &QPushButton::clicked, this, [this] { onTabClicked(0); });+ connect(queriesTabBtn_, &QPushButton::clicked, this, [this] { onTabClicked(1); });+ connect(historyTabBtn_, &QPushButton::clicked, this, [this] { onTabClicked(2); });+ connect(savedTabBtn_, &QPushButton::clicked, this, [this] { onTabClicked(3); });+ root->addWidget(tabBar);++ auto* tabDiv = new QFrame(this);+ tabDiv->setFrameShape(QFrame::HLine);+ root->addWidget(tabDiv);++ // ---- Body: stacked (Items tab, empty tabs for Queries/History) ----+ body_ = new QStackedWidget(this);++ // Items tab+ auto* itemsPage = new QWidget(body_);+ auto* itemsV = new QVBoxLayout(itemsPage);+ itemsV->setContentsMargins(0, 0, 0, 0);+ itemsV->setSpacing(0);++ auto* searchRow = new QWidget(itemsPage);+ auto* searchH = new QHBoxLayout(searchRow);+ searchH->setContentsMargins(8, 6, 8, 6);+ searchH->setSpacing(4);+ searchEdit_ = new QLineEdit(searchRow);+ searchEdit_->setPlaceholderText(tr("Search tables..."));+ searchEdit_->setClearButtonEnabled(true);+ connect(searchEdit_, &QLineEdit::textChanged,+ this, &WorkspaceSidebar::onSearchChanged);+ searchH->addWidget(searchEdit_);++ gridToggleBtn_ = new QPushButton(QStringLiteral("⊞"), searchRow);+ gridToggleBtn_->setFixedSize(26, 26);+ gridToggleBtn_->setCheckable(true);+ gridToggleBtn_->setChecked(false);+ gridToggleBtn_->setToolTip(tr("Toggle Grid View"));+ gridToggleBtn_->setCursor(Qt::PointingHandCursor);+ connect(gridToggleBtn_, &QPushButton::toggled, this, [this](bool checked) {+ itemsViewStack_->setCurrentIndex(checked ? 1 : 0);+ searchEdit_->setPlaceholderText(checked ? tr("Filter tables...") : tr("Search tables..."));+ if (checked && tableGrid_) tableGrid_->reload();+ });+ searchH->addWidget(gridToggleBtn_);++ itemsV->addWidget(searchRow);++ auto* searchDiv = new QFrame(itemsPage);+ searchDiv->setFrameShape(QFrame::HLine);+ itemsV->addWidget(searchDiv);++ // Stacked: page 0 = tree, page 1 = grid+ itemsViewStack_ = new QStackedWidget(itemsPage);++ tree_ = new QTreeView(itemsViewStack_);+ tree_->setHeaderHidden(true);+ tree_->setEditTriggers(QAbstractItemView::NoEditTriggers);+ tree_->setSelectionBehavior(QAbstractItemView::SelectRows);+ tree_->setFrameShape(QFrame::NoFrame);+ tree_->setContextMenuPolicy(Qt::CustomContextMenu);++ model_ = new QStandardItemModel(this);+ tree_->setModel(model_);++ connect(tree_, &QTreeView::expanded,+ this, &WorkspaceSidebar::onItemExpanded);+ connect(tree_, &QTreeView::doubleClicked,+ this, &WorkspaceSidebar::onItemDoubleClicked);+ connect(tree_, &QTreeView::customContextMenuRequested,+ this, &WorkspaceSidebar::onContextMenuRequested);++ itemsViewStack_->addWidget(tree_);++ tableGrid_ = new TableGridView(state_, itemsViewStack_);+ connect(tableGrid_, &TableGridView::tableSelected,+ this, &WorkspaceSidebar::tableSelected);+ connect(tableGrid_, &TableGridView::tableDeleted,+ this, &WorkspaceSidebar::tableDeleted);+ itemsViewStack_->addWidget(tableGrid_);++ itemsViewStack_->setCurrentIndex(0);+ itemsV->addWidget(itemsViewStack_, 1);++ // Bottom bar: schema selector + DB info + disconnect+ auto* bottomDiv = new QFrame(itemsPage);+ bottomDiv->setFrameShape(QFrame::HLine);+ itemsV->addWidget(bottomDiv);++ auto* bottomBar = new QWidget(itemsPage);+ auto* bottomV = new QVBoxLayout(bottomBar);+ bottomV->setContentsMargins(8, 6, 8, 6);+ bottomV->setSpacing(4);++ // Schema selector row+ auto* schemaRow = new QWidget(bottomBar);+ auto* schemaH = new QHBoxLayout(schemaRow);+ schemaH->setContentsMargins(0, 0, 0, 0);+ schemaH->setSpacing(6);++ schemaCombo_ = new QComboBox(schemaRow);+ schemaCombo_->setToolTip(tr("Active schema"));+ schemaCombo_->setSizeAdjustPolicy(QComboBox::AdjustToContents);+ connect(schemaCombo_, QOverload<int>::of(&QComboBox::currentIndexChanged),+ this, &WorkspaceSidebar::onSchemaChanged);+ schemaH->addWidget(schemaCombo_);+ schemaH->addStretch();++ bottomV->addWidget(schemaRow);++ // DB info label+ dbInfoLabel_ = new QLabel(bottomBar);+ dbInfoLabel_->setWordWrap(false);+ bottomV->addWidget(dbInfoLabel_);++ // Bottom action row: [New Table] [Disconnect]+ auto* disconnRow = new QWidget(bottomBar);+ auto* disconnH = new QHBoxLayout(disconnRow);+ disconnH->setContentsMargins(0, 0, 0, 0);+ disconnH->setSpacing(6);++ newTableBtn_ = new QPushButton(tr("+ New Table"), disconnRow);+ connect(newTableBtn_, &QPushButton::clicked, this, [this] {+ const QString schema = schemaCombo_ ? schemaCombo_->currentText() : QString{};+ emit newTableRequested(schema);+ });++ disconnectBtn_ = new QPushButton(tr("Disconnect"), disconnRow);+ connect(disconnectBtn_, &QPushButton::clicked,+ this, &WorkspaceSidebar::disconnectRequested);++ disconnH->addWidget(newTableBtn_);+ disconnH->addStretch();+ disconnH->addWidget(disconnectBtn_);+ bottomV->addWidget(disconnRow);++ itemsV->addWidget(bottomBar);++ body_->addWidget(itemsPage);++ // Queries tab placeholder+ auto* queriesPage = new QWidget(body_);+ auto* qv = new QVBoxLayout(queriesPage);+ qv->addStretch();+ auto* noQ = new QLabel(tr("📄\nNo Queries"), queriesPage);+ noQ->setAlignment(Qt::AlignCenter);+ qv->addWidget(noQ);+ qv->addStretch();+ body_->addWidget(queriesPage);++ // History tab+ auto* historyPage = new QWidget(body_);+ auto* hv = new QVBoxLayout(historyPage);+ hv->setContentsMargins(0, 0, 0, 0);+ hv->setSpacing(0);+ historyList_ = new QListWidget(historyPage);+ historyList_->setFrameShape(QFrame::NoFrame);+ historyList_->setSelectionMode(QAbstractItemView::SingleSelection);+ historyList_->setContextMenuPolicy(Qt::CustomContextMenu);+ historyList_->setToolTip(tr("Double-click to copy SQL to clipboard"));+ connect(historyList_, &QListWidget::itemDoubleClicked, this,+ [this](QListWidgetItem* item) {+ if (!item) return;+ QApplication::clipboard()->setText(item->data(Qt::UserRole).toString());+ });+ connect(historyList_, &QListWidget::customContextMenuRequested, this,+ [this](const QPoint& pos) {+ QMenu menu(this);+ auto* clearAct = menu.addAction(tr("Clear History"));+ connect(clearAct, &QAction::triggered, this, [this] {+ if (!appDb_) return;+ const auto btn = QMessageBox::question(this, tr("Clear History"),+ tr("Remove all query history?"),+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);+ if (btn != QMessageBox::Yes) return;+ try { appDb_->clearAllHistory(); } catch (...) {}+ historyList_->clear();+ });+ menu.exec(historyList_->viewport()->mapToGlobal(pos));+ });+ hv->addWidget(historyList_, 1);+ body_->addWidget(historyPage);++ // Saved queries tab+ auto* savedPage = new QWidget(body_);+ auto* sv = new QVBoxLayout(savedPage);+ sv->setContentsMargins(0, 0, 0, 0);+ sv->setSpacing(0);+ savedTree_ = new QTreeWidget(savedPage);+ savedTree_->setHeaderHidden(true);+ savedTree_->setFrameShape(QFrame::NoFrame);+ savedTree_->setContextMenuPolicy(Qt::CustomContextMenu);+ savedTree_->setSelectionMode(QAbstractItemView::SingleSelection);+ connect(savedTree_, &QTreeWidget::itemDoubleClicked, this,+ [this](QTreeWidgetItem* item, int) {+ if (!item || item->childCount() > 0) return;+ const QString sql = item->data(0, Qt::UserRole).toString();+ if (!sql.isEmpty()) emit loadSavedQueryRequested(sql);+ });+ connect(savedTree_, &QTreeWidget::customContextMenuRequested,+ this, &WorkspaceSidebar::onSavedQueryContextMenu);+ sv->addWidget(savedTree_, 1);+ body_->addWidget(savedPage);++ body_->setCurrentIndex(0);+ root->addWidget(body_, 1);+}++void WorkspaceSidebar::refreshTree() {+ onConnectionOpened();+}++void WorkspaceSidebar::onTabClicked(int tab) {+ activeTab_ = tab;+ itemsTabBtn_->setChecked(tab == 0);+ queriesTabBtn_->setChecked(tab == 1);+ historyTabBtn_->setChecked(tab == 2);+ savedTabBtn_->setChecked(tab == 3);+ body_->setCurrentIndex(tab);+}++void WorkspaceSidebar::onConnectionOpened() {+ loadSchemas();++ // Populate schema combo from adapter.+ if (schemaCombo_ && state_ && state_->adapter()) {+ // Block signals while rebuilding to avoid triggering reload mid-populate.+ QSignalBlocker blocker(schemaCombo_);+ schemaCombo_->clear();+ try {+ const auto schemas = state_->adapter()->listSchemas(std::nullopt);+ for (const auto& s : schemas) {+ schemaCombo_->addItem(QString::fromUtf8(s.c_str()));+ }+ } catch (const GridexError&) {}+ // Default to "public" if present, else index 0.+ const int pubIdx = schemaCombo_->findText(QStringLiteral("public"));+ schemaCombo_->setCurrentIndex(pubIdx >= 0 ? pubIdx : 0);+ }++ // DB info: "name · dbtype · host"+ if (dbInfoLabel_ && state_) {+ const auto& cfg = state_->config();+ const QString dbType = QString::fromUtf8(+ displayName(cfg.databaseType).data(),+ static_cast<qsizetype>(displayName(cfg.databaseType).size()));+ const QString host = QString::fromUtf8(cfg.displayHost().c_str());+ dbInfoLabel_->setText(QStringLiteral("%1 · %2").arg(dbType, host));+ }+}++void WorkspaceSidebar::onConnectionClosed() {+ model_->clear();+ if (schemaCombo_) schemaCombo_->clear();+ if (dbInfoLabel_) dbInfoLabel_->clear();+}++void WorkspaceSidebar::loadSchemas() {+ model_->clear();+ if (!state_ || !state_->adapter()) return;++ try {+ const auto schemas = state_->adapter()->listSchemas(std::nullopt);+ for (const auto& s : schemas) {+ auto* schemaItem = new QStandardItem(QString::fromUtf8(s.c_str()));+ schemaItem->setData(NodeSchema, kRoleKind);+ schemaItem->setData(QString::fromUtf8(s.c_str()), kRoleSchemaName);+ schemaItem->setData(false, kRoleLoaded);++ // Insert placeholder child so the expand arrow shows up.+ auto* placeholder = new QStandardItem(tr("(loading...)"));+ placeholder->setData(NodePlaceholder, kRoleKind);+ schemaItem->appendRow(placeholder);++ model_->appendRow(schemaItem);+ }+ // If only one schema, auto-expand it for convenience.+ if (schemas.size() == 1 && model_->rowCount() > 0) {+ tree_->expand(model_->index(0, 0));+ }+ } catch (const GridexError&) {+ auto* err = new QStandardItem(tr("(schema listing failed)"));+ err->setEnabled(false);+ model_->appendRow(err);+ }+}++void WorkspaceSidebar::onItemExpanded(const QModelIndex& index) {+ auto* item = model_->itemFromIndex(index);+ if (!item) return;+ if (item->data(kRoleLoaded).toBool()) return;++ const int kind = item->data(kRoleKind).toInt();+ const QString schema = item->data(kRoleSchemaName).toString();++ if (kind == NodeSchema) {+ item->removeRows(0, item->rowCount());+ loadTablesForSchema(item, schema);+ item->setData(true, kRoleLoaded);+ } else if (kind == NodeFunctionsGroup) {+ item->removeRows(0, item->rowCount());+ loadFunctionsForSchema(item, schema);+ item->setData(true, kRoleLoaded);+ } else if (kind == NodeProceduresGroup) {+ item->removeRows(0, item->rowCount());+ loadProceduresForSchema(item, schema);+ item->setData(true, kRoleLoaded);+ }+}++void WorkspaceSidebar::loadTablesForSchema(QStandardItem* schemaItem, const QString& schemaName) {+ if (!state_ || !state_->adapter()) return;+ try {+ const auto tables = state_->adapter()->listTables(schemaName.toStdString());+ if (tables.empty()) {+ auto* empty = new QStandardItem(tr("(no tables)"));+ empty->setEnabled(false);+ schemaItem->appendRow(empty);+ } else {+ for (const auto& t : tables) {+ auto* tableItem = new QStandardItem(QString::fromUtf8(t.name.c_str()));+ tableItem->setData(NodeTable, kRoleKind);+ tableItem->setData(schemaName, kRoleSchemaName);+ tableItem->setData(QString::fromUtf8(t.name.c_str()), kRoleTableName);+ schemaItem->appendRow(tableItem);+ }+ }+ } catch (const GridexError& e) {+ auto* err = new QStandardItem(QString::fromUtf8(e.what()));+ err->setEnabled(false);+ schemaItem->appendRow(err);+ }++ // Functions group node+ auto* fnGroup = new QStandardItem(tr("Functions"));+ fnGroup->setData(NodeFunctionsGroup, kRoleKind);+ fnGroup->setData(schemaName, kRoleSchemaName);+ fnGroup->setData(false, kRoleLoaded);+ auto* fnPlaceholder = new QStandardItem(tr("(loading...)"));+ fnPlaceholder->setData(NodePlaceholder, kRoleKind);+ fnGroup->appendRow(fnPlaceholder);+ schemaItem->appendRow(fnGroup);++ // Procedures group node+ auto* procGroup = new QStandardItem(tr("Procedures"));+ procGroup->setData(NodeProceduresGroup, kRoleKind);+ procGroup->setData(schemaName, kRoleSchemaName);+ procGroup->setData(false, kRoleLoaded);+ auto* procPlaceholder = new QStandardItem(tr("(loading...)"));+ procPlaceholder->setData(NodePlaceholder, kRoleKind);+ procGroup->appendRow(procPlaceholder);+ schemaItem->appendRow(procGroup);+}++void WorkspaceSidebar::loadFunctionsForSchema(QStandardItem* parent, const QString& schemaName) {+ if (!state_ || !state_->adapter()) return;+ try {+ const std::optional<std::string> schemaOpt =+ schemaName.isEmpty() ? std::nullopt+ : std::make_optional(schemaName.toStdString());+ const auto fns = state_->adapter()->listFunctions(schemaOpt);+ if (fns.empty()) {+ auto* empty = new QStandardItem(tr("(none)"));+ empty->setEnabled(false);+ parent->appendRow(empty);+ return;+ }+ for (const auto& fn : fns) {+ auto* item = new QStandardItem(QString::fromUtf8(fn.c_str()));+ item->setData(NodeFunction, kRoleKind);+ item->setData(schemaName, kRoleSchemaName);+ item->setData(QString::fromUtf8(fn.c_str()), kRoleRoutineName);+ parent->appendRow(item);+ }+ } catch (const GridexError&) {+ auto* empty = new QStandardItem(tr("(none)"));+ empty->setEnabled(false);+ parent->appendRow(empty);+ }+}++void WorkspaceSidebar::loadProceduresForSchema(QStandardItem* parent, const QString& schemaName) {+ if (!state_ || !state_->adapter()) return;+ try {+ const std::optional<std::string> schemaOpt =+ schemaName.isEmpty() ? std::nullopt+ : std::make_optional(schemaName.toStdString());+ const auto procs = state_->adapter()->listProcedures(schemaOpt);+ if (procs.empty()) {+ auto* empty = new QStandardItem(tr("(none)"));+ empty->setEnabled(false);+ parent->appendRow(empty);+ return;+ }+ for (const auto& p : procs) {+ auto* item = new QStandardItem(QString::fromUtf8(p.c_str()));+ item->setData(NodeProcedure, kRoleKind);+ item->setData(schemaName, kRoleSchemaName);+ item->setData(QString::fromUtf8(p.c_str()), kRoleRoutineName);+ parent->appendRow(item);+ }+ } catch (const GridexError&) {+ auto* empty = new QStandardItem(tr("(none)"));+ empty->setEnabled(false);+ parent->appendRow(empty);+ }+}++void WorkspaceSidebar::onItemDoubleClicked(const QModelIndex& index) {+ auto* item = model_->itemFromIndex(index);+ if (!item) return;+ const int kind = item->data(kRoleKind).toInt();+ const QString schema = item->data(kRoleSchemaName).toString();+ if (kind == NodeTable) {+ emit tableSelected(schema, item->data(kRoleTableName).toString());+ } else if (kind == NodeFunction) {+ emit functionSelected(schema, item->data(kRoleRoutineName).toString());+ } else if (kind == NodeProcedure) {+ emit procedureSelected(schema, item->data(kRoleRoutineName).toString());+ }+}++void WorkspaceSidebar::onSchemaChanged(int /*index*/) {+ reloadActiveSchema();+}++void WorkspaceSidebar::reloadActiveSchema() {+ if (!schemaCombo_ || schemaCombo_->count() == 0) return;+ const QString schema = schemaCombo_->currentText();+ // Reload tree with only the selected schema's tables visible.+ model_->clear();+ if (!state_ || !state_->adapter()) return;+ auto* schemaItem = new QStandardItem(schema);+ schemaItem->setData(NodeSchema, kRoleKind);+ schemaItem->setData(schema, kRoleSchemaName);+ schemaItem->setData(false, kRoleLoaded);+ auto* placeholder = new QStandardItem(tr("(loading...)"));+ placeholder->setData(NodePlaceholder, kRoleKind);+ schemaItem->appendRow(placeholder);+ model_->appendRow(schemaItem);+ tree_->expand(model_->index(0, 0));+}++void WorkspaceSidebar::onSearchChanged(const QString& text) {+ // In grid mode, delegate filtering to TableGridView.+ if (gridToggleBtn_ && gridToggleBtn_->isChecked()) {+ if (tableGrid_) tableGrid_->onSearchChanged(text);+ return;+ }++ // Simple hide/show filter across schemas+tables. For v1 we do a flat walk.+ const auto lower = text.trimmed().toLower();+ for (int i = 0; i < model_->rowCount(); ++i) {+ auto* schemaItem = model_->item(i);+ bool schemaMatches = lower.isEmpty() ||+ schemaItem->text().toLower().contains(lower);+ bool anyChildMatches = false;+ for (int j = 0; j < schemaItem->rowCount(); ++j) {+ auto* child = schemaItem->child(j);+ const bool ok = lower.isEmpty() || child->text().toLower().contains(lower);+ tree_->setRowHidden(j, schemaItem->index(), !ok);+ anyChildMatches = anyChildMatches || ok;+ }+ tree_->setRowHidden(i, QModelIndex(), !(schemaMatches || anyChildMatches));+ }+}++void WorkspaceSidebar::onContextMenuRequested(const QPoint& pos) {+ const QModelIndex index = tree_->indexAt(pos);+ auto* item = index.isValid() ? model_->itemFromIndex(index) : nullptr;+ const int kind = item ? item->data(kRoleKind).toInt() : 0;++ QMenu menu(this);++ // Refresh is always first — works on blank area, schema nodes, and+ // table nodes. Full reload is cheap and keeps schemas + tables in sync.+ auto* refreshAction = menu.addAction(tr("Refresh"));+ refreshAction->setShortcut(QKeySequence::Refresh);+ connect(refreshAction, &QAction::triggered, this, [this] { loadSchemas(); });++ // Blank area or schema node: Refresh + import/backup/restore actions.+ if (!item || kind != NodeTable) {+ menu.addSeparator();++ auto* runSqlAct = menu.addAction(tr("Run SQL File..."));+ auto* backupAct = menu.addAction(tr("Backup Database..."));+ auto* restoreAct = menu.addAction(tr("Restore Database..."));+ const bool hasAdapter = state_ && state_->adapter();+ runSqlAct->setEnabled(hasAdapter);+ backupAct->setEnabled(hasAdapter);+ restoreAct->setEnabled(hasAdapter);+ connect(runSqlAct, &QAction::triggered, this, &WorkspaceSidebar::runSqlFile);+ connect(backupAct, &QAction::triggered, this, &WorkspaceSidebar::backupDatabase);+ connect(restoreAct, &QAction::triggered, this, &WorkspaceSidebar::restoreDatabase);++ menu.exec(tree_->viewport()->mapToGlobal(pos));+ return;+ }++ menu.addSeparator();++ const QString schema = item->data(kRoleSchemaName).toString();+ const QString table = item->data(kRoleTableName).toString();++ // Open / view actions+ auto* openAction = menu.addAction(tr("Open in New Tab"));+ connect(openAction, &QAction::triggered, this, [this, schema, table] {+ emit tableSelected(schema, table);+ });++ auto* structureAction = menu.addAction(tr("View Structure"));+ connect(structureAction, &QAction::triggered, this, [this, schema, table] {+ emit tableSelected(schema, table);+ });++ menu.addSeparator();++ // Copy actions+ auto* copyNameAction = menu.addAction(tr("Copy Table Name"));+ connect(copyNameAction, &QAction::triggered, this, [table] {+ QApplication::clipboard()->setText(table);+ });++ const QString selectSql = QStringLiteral("SELECT * FROM %1 LIMIT 100;").arg(table);+ auto* copySelectAction = menu.addAction(tr("Copy SELECT * FROM..."));+ connect(copySelectAction, &QAction::triggered, this, [selectSql] {+ QApplication::clipboard()->setText(selectSql);+ });++ auto* copyDdlAction = menu.addAction(tr("Copy CREATE TABLE..."));+ connect(copyDdlAction, &QAction::triggered, this, [this, schema, table] {+ if (!state_ || !state_->adapter()) return;+ try {+ const auto desc = state_->adapter()->describeTable(+ table.toStdString(),+ schema.isEmpty() ? std::nullopt : std::make_optional(schema.toStdString()));+ const SQLDialect dialect = sqlDialect(state_->adapter()->databaseType());+ const QString ddl = QString::fromStdString(desc.toDDL(dialect));+ QApplication::clipboard()->setText(ddl);+ } catch (const GridexError& e) {+ QMessageBox::warning(this, tr("Copy DDL Failed"), QString::fromUtf8(e.what()));+ }+ });++ menu.addSeparator();++ // Truncate+ auto* truncateAction = menu.addAction(tr("Truncate Table..."));+ connect(truncateAction, &QAction::triggered, this, [this, schema, table] {+ if (!state_ || !state_->adapter()) return;+ const auto answer = QMessageBox::warning(+ this, tr("Truncate Table"),+ tr("Are you sure you want to truncate \"%1\"?\nAll rows will be deleted.").arg(table),+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);+ if (answer != QMessageBox::Yes) return;++ try {+ const DatabaseType dt = state_->adapter()->databaseType();+ std::string sql;+ if (dt == DatabaseType::SQLite) {+ sql = "DELETE FROM " + quoteIdentifier(sqlDialect(dt), table.toStdString());+ } else if (!schema.isEmpty()) {+ sql = "TRUNCATE TABLE "+ + quoteIdentifier(sqlDialect(dt), schema.toStdString())+ + "."+ + quoteIdentifier(sqlDialect(dt), table.toStdString());+ } else {+ sql = "TRUNCATE TABLE " + quoteIdentifier(sqlDialect(dt), table.toStdString());+ }+ state_->adapter()->executeRaw(sql);+ } catch (const GridexError& e) {+ QMessageBox::critical(this, tr("Truncate Failed"), QString::fromUtf8(e.what()));+ }+ });++ // Drop table+ auto* dropAction = menu.addAction(tr("Delete Table..."));+ connect(dropAction, &QAction::triggered, this, [this, schema, table] {+ if (!state_ || !state_->adapter()) return;+ const auto answer = QMessageBox::warning(+ this, tr("Delete Table"),+ tr("Are you sure you want to drop \"%1\"?\nThis action cannot be undone.").arg(table),+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);+ if (answer != QMessageBox::Yes) return;++ try {+ const DatabaseType dt = state_->adapter()->databaseType();+ std::string sql;+ if (!schema.isEmpty() &&+ dt != DatabaseType::SQLite &&+ dt != DatabaseType::MySQL)+ {+ sql = "DROP TABLE "+ + quoteIdentifier(sqlDialect(dt), schema.toStdString())+ + "."+ + quoteIdentifier(sqlDialect(dt), table.toStdString());+ } else {+ sql = "DROP TABLE " + quoteIdentifier(sqlDialect(dt), table.toStdString());+ }+ state_->adapter()->executeRaw(sql);+ // Refresh sidebar and notify WorkspaceView to close tabs+ loadSchemas();+ emit tableDeleted(schema, table);+ } catch (const GridexError& e) {+ QMessageBox::critical(this, tr("Delete Table Failed"), QString::fromUtf8(e.what()));+ }+ });++ menu.addSeparator();++ // Export+ auto* exportAction = menu.addAction(tr("Export Table..."));+ connect(exportAction, &QAction::triggered, this, [this, schema, table] {+ if (!state_ || !state_->adapter()) return;++ const QString path = QFileDialog::getSaveFileName(+ this, tr("Export Table — %1").arg(table),+ QStringLiteral("%1.csv").arg(table),+ tr("CSV (*.csv);;JSON (*.json);;SQL (*.sql)"));+ if (path.isEmpty()) return;++ try {+ const std::optional<std::string> schemaOpt =+ schema.isEmpty() ? std::nullopt+ : std::make_optional(schema.toStdString());+ const QueryResult result = state_->adapter()->fetchRows(+ table.toStdString(), schemaOpt,+ std::nullopt, std::nullopt, std::nullopt,+ 10000, 0);++ const std::string filePath = path.toStdString();+ if (path.endsWith(QStringLiteral(".json"), Qt::CaseInsensitive)) {+ ExportService::exportToJson(result, filePath);+ } else if (path.endsWith(QStringLiteral(".sql"), Qt::CaseInsensitive)) {+ ExportService::exportToSql(result, table.toStdString(), filePath);+ } else {+ ExportService::exportToCsv(result, filePath);+ }+ } catch (const std::exception& e) {+ QMessageBox::critical(this, tr("Export Failed"), QString::fromUtf8(e.what()));+ }+ });++ // Import CSV (table-specific)+ auto* importCsvAct = menu.addAction(tr("Import CSV..."));+ connect(importCsvAct, &QAction::triggered, this, [this, schema, table] {+ importCsv(schema, table);+ });++ menu.exec(tree_->viewport()->mapToGlobal(pos));+}++// --------------------------------------------------------------------+// Run SQL File (script importer)+// --------------------------------------------------------------------++void WorkspaceSidebar::runSqlFile() {+ if (!state_ || !state_->adapter()) return;++ const QString path = QFileDialog::getOpenFileName(+ this, tr("Run SQL File"),+ QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation),+ tr("SQL (*.sql);;All files (*)"));+ if (path.isEmpty()) return;++ auto* wizard = new SqlImportWizard(state_->adapter(), path, this);+ wizard->setWindowModality(Qt::WindowModal);+ wizard->setAttribute(Qt::WA_DeleteOnClose);+ connect(wizard, &QDialog::finished, this, [this] { loadSchemas(); });+ wizard->show();+}++// --------------------------------------------------------------------+// Import CSV (single table)+// --------------------------------------------------------------------++void WorkspaceSidebar::importCsv(const QString& schema, const QString& table) {+ if (!state_ || !state_->adapter()) return;++ const QString path = QFileDialog::getOpenFileName(+ this, tr("Import CSV into %1").arg(table),+ QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation),+ tr("CSV (*.csv);;All files (*)"));+ if (path.isEmpty()) return;++ QFile f(path);+ if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) {+ QMessageBox::warning(this, tr("Import CSV"),+ tr("Cannot open file: %1").arg(path));+ return;+ }+ QTextStream ts(&f);+ const QString body = ts.readAll();+ f.close();++ CsvParser parser{body, 0};+ const QStringList header = parser.readRow();+ if (header.isEmpty()) {+ QMessageBox::warning(this, tr("Import CSV"), tr("Empty CSV — no header row."));+ return;+ }++ // Fetch table columns to validate header ↔ table alignment.+ std::vector<ColumnInfo> tableCols;+ try {+ const auto schemaOpt = schema.isEmpty() ? std::nullopt+ : std::make_optional(schema.toStdString());+ const auto desc = state_->adapter()->describeTable(table.toStdString(), schemaOpt);+ tableCols = desc.columns;+ } catch (const GridexError& e) {+ QMessageBox::critical(this, tr("Import CSV"), QString::fromUtf8(e.what()));+ return;+ }++ // Column indexes in target table for each CSV header, by name match.+ // Missing columns → skip that CSV column entirely. Fewer columns in CSV+ // than table is fine (unset cols use default/NULL).+ std::vector<int> colMap; // size = header.size(); -1 if unmapped+ QStringList mappedNames;+ for (const auto& h : header) {+ int idx = -1;+ for (std::size_t i = 0; i < tableCols.size(); ++i) {+ if (QString::fromStdString(tableCols[i].name).compare(h, Qt::CaseInsensitive) == 0) {+ idx = static_cast<int>(i);+ break;+ }+ }+ colMap.push_back(idx);+ if (idx >= 0) mappedNames << h;+ }+ if (mappedNames.isEmpty()) {+ QMessageBox::warning(this, tr("Import CSV"),+ tr("No CSV columns match table columns. Check header names."));+ return;+ }++ const auto ok = QMessageBox::question(+ this, tr("Import CSV"),+ tr("Mapped %1 of %2 CSV columns. Continue?").arg(mappedNames.size()).arg(header.size()),+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Yes);+ if (ok != QMessageBox::Yes) return;++ const DatabaseType dt = state_->adapter()->databaseType();+ const SQLDialect dialect = sqlDialect(dt);+ const std::string qTable = (!schema.isEmpty() && dt != DatabaseType::SQLite && dt != DatabaseType::MySQL)+ ? quoteIdentifier(dialect, schema.toStdString()) + "." + quoteIdentifier(dialect, table.toStdString())+ : quoteIdentifier(dialect, table.toStdString());++ // Build column list once (only mapped cols, in CSV order).+ std::string colList;+ for (std::size_t i = 0; i < colMap.size(); ++i) {+ if (colMap[i] < 0) continue;+ if (!colList.empty()) colList += ", ";+ colList += quoteIdentifier(dialect, header[i].toStdString());+ }++ int inserted = 0;+ QStringList errors;+ while (!parser.atEnd()) {+ const QStringList fields = parser.readRow();+ if (fields.isEmpty() || (fields.size() == 1 && fields[0].isEmpty())) continue;++ std::string values;+ for (std::size_t i = 0; i < colMap.size(); ++i) {+ if (colMap[i] < 0) continue;+ if (!values.empty()) values += ", ";+ if (i >= static_cast<std::size_t>(fields.size()) || fields[i].isNull()) {+ values += "NULL";+ } else {+ // Quote everything as string; DB coerces. Escape '.+ QString v = fields[i];+ v.replace('\'', QStringLiteral("''"));+ values += '\'';+ values += v.toStdString();+ values += '\'';+ }+ }+ const std::string sql = "INSERT INTO " + qTable + " (" + colList + ") VALUES (" + values + ")";+ try {+ state_->adapter()->executeRaw(sql);+ ++inserted;+ } catch (const GridexError& e) {+ errors << QString::fromUtf8(e.what());+ if (errors.size() > 10) { errors << "... (truncated)"; break; }+ } catch (const std::exception& e) {+ errors << QString::fromUtf8(e.what());+ if (errors.size() > 10) { errors << "... (truncated)"; break; }+ }+ }++ if (errors.isEmpty()) {+ QMessageBox::information(this, tr("Import CSV"),+ tr("Inserted %1 rows into %2.").arg(inserted).arg(table));+ } else {+ QMessageBox::warning(this, tr("Import CSV"),+ tr("Inserted %1 rows with errors:\n\n%2").arg(inserted).arg(errors.join("\n")));+ }+}++// --------------------------------------------------------------------+// Backup / Restore — delegates to DatabaseDumpRunner service+// --------------------------------------------------------------------++void WorkspaceSidebar::backupDatabase() {+ if (!state_ || !state_->adapter()) return;+ const ConnectionConfig& cfg = state_->config();++ QString defName = QString::fromStdString(cfg.database.value_or(cfg.name));+ if (defName.isEmpty()) defName = QStringLiteral("backup");+ const QString path = QFileDialog::getSaveFileName(+ this, tr("Backup Database"),+ QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)+ + QStringLiteral("/") + defName + QStringLiteral(".sql"),+ tr("SQL Dump (*.sql);;All files (*)"));+ if (path.isEmpty()) return;++ std::optional<std::string> pw;+ SecretStore store;+ if (store.isAvailable()) pw = store.loadPassword(cfg.id);++ auto* dlg = new BackupProgressDialog(+ BackupProgressDialog::Mode::Backup, cfg, pw, path, this);+ dlg->setAttribute(Qt::WA_DeleteOnClose);+ dlg->setWindowModality(Qt::WindowModal);+ dlg->show();+ dlg->start();+}++void WorkspaceSidebar::restoreDatabase() {+ if (!state_ || !state_->adapter()) return;+ const ConnectionConfig& cfg = state_->config();++ const QString path = QFileDialog::getOpenFileName(+ this, tr("Restore Database"),+ QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation),+ tr("SQL Dump (*.sql);;All files (*)"));+ if (path.isEmpty()) return;++ const auto confirm = QMessageBox::warning(+ this, tr("Restore Database"),+ tr("This will execute SQL from:\n%1\n\nExisting data may be overwritten. Continue?").arg(path),+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);+ if (confirm != QMessageBox::Yes) return;++ std::optional<std::string> pw;+ SecretStore store;+ if (store.isAvailable()) pw = store.loadPassword(cfg.id);++ auto* dlg = new BackupProgressDialog(+ BackupProgressDialog::Mode::Restore, cfg, pw, path, this);+ dlg->setAttribute(Qt::WA_DeleteOnClose);+ dlg->setWindowModality(Qt::WindowModal);+ connect(dlg, &QDialog::finished, this, [this] { loadSchemas(); });+ dlg->show();+ dlg->start();+}++void WorkspaceSidebar::promptSaveQuery(const QString& sql) {+ if (!savedQueryRepo_) return;+ bool ok = false;+ const QString name = QInputDialog::getText(+ this, tr("Save Query"), tr("Query name:"),+ QLineEdit::Normal, QString{}, &ok);+ if (!ok || name.trimmed().isEmpty()) return;++ const QString group = QInputDialog::getText(+ this, tr("Save Query"), tr("Group (leave blank for Default):"),+ QLineEdit::Normal, QString{}, &ok);+ if (!ok) return;++ AppDatabase::SavedQueryRecord rec;+ // Generate a simple UUID-like id from timestamp+ const auto ts = std::chrono::duration_cast<std::chrono::microseconds>(+ std::chrono::system_clock::now().time_since_epoch()).count();+ rec.id = std::to_string(ts);+ rec.name = name.trimmed().toStdString();+ rec.groupName = group.trimmed().toStdString();+ rec.sql = sql.toStdString();+ rec.createdAt = std::chrono::system_clock::now();+ rec.updatedAt = rec.createdAt;++ try {+ savedQueryRepo_->save(rec);+ reloadSavedQueriesTree();+ } catch (const std::exception& e) {+ QMessageBox::warning(this, tr("Save Failed"), QString::fromUtf8(e.what()));+ }+}++void WorkspaceSidebar::logQuery(const QString& sql, int rowCount, int elapsedMs) {+ if (appDb_) {+ AppDatabase::HistoryEntry entry;+ entry.connectionId = state_ ? state_->config().id : std::string{};+ entry.sql = sql.toStdString();+ entry.executedAt = std::chrono::system_clock::now();+ entry.durationMs = elapsedMs;+ entry.rowCount = rowCount;+ entry.succeeded = true;+ try { appDb_->appendHistory(entry); } catch (...) {}+ }++ if (!historyList_) return;+ const QString preview = sql.simplified().left(80);+ const QString label = QStringLiteral("%1 rows · %2 ms │ %3")+ .arg(rowCount).arg(elapsedMs).arg(preview);+ auto* item = new QListWidgetItem(label);+ item->setData(Qt::UserRole, sql);+ item->setToolTip(sql);+ historyList_->insertItem(0, item);+ while (historyList_->count() > 200) {+ delete historyList_->takeItem(historyList_->count() - 1);+ }+}++void WorkspaceSidebar::loadHistoryFromDb() {+ if (!appDb_ || !historyList_) return;+ historyList_->clear();+ try {+ const auto entries = appDb_->listAllHistory(200);+ for (const auto& h : entries) {+ const QString sql = QString::fromStdString(h.sql);+ const QString preview = sql.simplified().left(80);+ const QString label = QStringLiteral("%1 rows · %2 ms │ %3")+ .arg(h.rowCount).arg(h.durationMs).arg(preview);+ auto* item = new QListWidgetItem(label);+ item->setData(Qt::UserRole, sql);+ item->setToolTip(sql);+ historyList_->addItem(item);+ }+ } catch (...) {}+}++void WorkspaceSidebar::reloadSavedQueriesTree() {+ if (!savedTree_ || !savedQueryRepo_) return;+ savedTree_->clear();+ try {+ const auto records = savedQueryRepo_->fetchAll();+ QMap<QString, QTreeWidgetItem*> groups;+ for (const auto& r : records) {+ const QString group = r.groupName.empty()+ ? tr("Default") : QString::fromStdString(r.groupName);+ if (!groups.contains(group)) {+ auto* gi = new QTreeWidgetItem(savedTree_);+ gi->setText(0, group);+ gi->setData(0, Qt::UserRole + 1, QStringLiteral("group"));+ gi->setData(0, Qt::UserRole + 2, group);+ groups[group] = gi;+ }+ auto* qi = new QTreeWidgetItem(groups[group]);+ qi->setText(0, QString::fromStdString(r.name));+ qi->setData(0, Qt::UserRole, QString::fromStdString(r.sql));+ qi->setData(0, Qt::UserRole + 1, QStringLiteral("query"));+ qi->setData(0, Qt::UserRole + 3, QString::fromStdString(r.id));+ }+ savedTree_->expandAll();+ } catch (...) {}+}++void WorkspaceSidebar::onSavedQueryContextMenu(const QPoint& pos) {+ auto* item = savedTree_->itemAt(pos);+ QMenu menu(this);+ const QString role = item ? item->data(0, Qt::UserRole + 1).toString() : QString{};++ if (role == QStringLiteral("query")) {+ const QString sql = item->data(0, Qt::UserRole).toString();+ const QString qid = item->data(0, Qt::UserRole + 3).toString();+ const QString qname = item->text(0);++ auto* runAct = menu.addAction(tr("Run"));+ connect(runAct, &QAction::triggered, this, [this, sql] {+ emit loadSavedQueryRequested(sql);+ });++ auto* editAct = menu.addAction(tr("Edit SQL..."));+ connect(editAct, &QAction::triggered, this, [this, qid, qname, sql] {+ if (!savedQueryRepo_) return;+ bool ok = false;+ const QString newSql = QInputDialog::getMultiLineText(+ this, tr("Edit Saved Query"), tr("SQL:"), sql, &ok);+ if (!ok || newSql.trimmed().isEmpty()) return;+ try {+ auto records = savedQueryRepo_->fetchAll();+ for (auto& r : records) {+ if (QString::fromStdString(r.id) == qid) {+ r.sql = newSql.toStdString();+ r.updatedAt = std::chrono::system_clock::now();+ savedQueryRepo_->save(r);+ break;+ }+ }+ reloadSavedQueriesTree();+ } catch (const std::exception& e) {+ QMessageBox::warning(this, tr("Edit Failed"), QString::fromUtf8(e.what()));+ }+ });++ auto* delAct = menu.addAction(tr("Delete"));+ connect(delAct, &QAction::triggered, this, [this, qid, qname] {+ if (!savedQueryRepo_) return;+ const auto btn = QMessageBox::question(this, tr("Delete Saved Query"),+ tr("Delete \"%1\"?").arg(qname),+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);+ if (btn != QMessageBox::Yes) return;+ try {+ savedQueryRepo_->remove(qid.toStdString());+ reloadSavedQueriesTree();+ } catch (const std::exception& e) {+ QMessageBox::warning(this, tr("Delete Failed"), QString::fromUtf8(e.what()));+ }+ });++ } else if (role == QStringLiteral("group")) {+ const QString groupName = item->data(0, Qt::UserRole + 2).toString();++ auto* renameAct = menu.addAction(tr("Rename Group..."));+ connect(renameAct, &QAction::triggered, this, [this, groupName] {+ if (!savedQueryRepo_) return;+ bool ok = false;+ const QString newName = QInputDialog::getText(+ this, tr("Rename Group"), tr("New name:"),+ QLineEdit::Normal, groupName, &ok);+ if (!ok || newName.trimmed().isEmpty()) return;+ try {+ auto records = savedQueryRepo_->fetchAll();+ for (auto& r : records) {+ if (QString::fromStdString(r.groupName) == groupName) {+ r.groupName = newName.toStdString();+ r.updatedAt = std::chrono::system_clock::now();+ savedQueryRepo_->save(r);+ }+ }+ reloadSavedQueriesTree();+ } catch (const std::exception& e) {+ QMessageBox::warning(this, tr("Rename Failed"), QString::fromUtf8(e.what()));+ }+ });++ auto* deleteGroupAct = menu.addAction(tr("Delete Group"));+ connect(deleteGroupAct, &QAction::triggered, this, [this, groupName] {+ if (!savedQueryRepo_) return;+ const auto btn = QMessageBox::question(this, tr("Delete Group"),+ tr("Delete group \"%1\" and move queries to Default?").arg(groupName),+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);+ if (btn != QMessageBox::Yes) return;+ try {+ auto records = savedQueryRepo_->fetchAll();+ for (auto& r : records) {+ if (QString::fromStdString(r.groupName) == groupName) {+ r.groupName = {};+ r.updatedAt = std::chrono::system_clock::now();+ savedQueryRepo_->save(r);+ }+ }+ reloadSavedQueriesTree();+ } catch (const std::exception& e) {+ QMessageBox::warning(this, tr("Delete Group Failed"), QString::fromUtf8(e.what()));+ }+ });+ }++ if (!menu.isEmpty()) menu.exec(savedTree_->viewport()->mapToGlobal(pos));+}++}diff --git a/linux/src/Presentation/Views/Sidebar/WorkspaceSidebar.h b/linux/src/Presentation/Views/Sidebar/WorkspaceSidebar.hnew file mode 100644index 0000000..57470cf--- /dev/null+++ b/linux/src/Presentation/Views/Sidebar/WorkspaceSidebar.h@@ -0,0 +1,116 @@+#pragma once++#include <memory>+#include <QWidget>+#include <string>++class QComboBox;+class QLabel;+class QLineEdit;+class QListWidget;+class QMenu;+class QStackedWidget;+class QStandardItem;+class QStandardItemModel;+class QTreeView;+class QTreeWidget;+class QTreeWidgetItem;+class QPushButton;++namespace gridex { class TableGridView; }++namespace gridex {++class AppDatabase;+class SavedQueryRepository;+class WorkspaceState;++// Left sidebar shown inside WorkspaceView once a connection is open.+// Mirrors macOS SidebarView layout:+// [tab bar: Items | Queries | History]+// [search bar]+// [tree: schemas (expand -> tables lazy loaded)]+// [bottom bar: schema selector ▾ | DB info | disconnect]+class WorkspaceSidebar : public QWidget {+ Q_OBJECT++public:+ explicit WorkspaceSidebar(WorkspaceState* state,+ std::shared_ptr<AppDatabase> appDb,+ QWidget* parent = nullptr);+ ~WorkspaceSidebar();++ void refreshTree();+ void logQuery(const QString& sql, int rowCount, int elapsedMs);+ void promptSaveQuery(const QString& sql);++signals:+ void tableSelected(const QString& schema, const QString& table);+ void tableDeleted(const QString& schema, const QString& table);+ void newTableRequested(const QString& schema);+ void disconnectRequested();+ void loadSavedQueryRequested(const QString& sql);+ void functionSelected(const QString& schema, const QString& name);+ void procedureSelected(const QString& schema, const QString& name);++private slots:+ void onConnectionOpened();+ void onConnectionClosed();+ void onItemExpanded(const QModelIndex& index);+ void onItemDoubleClicked(const QModelIndex& index);+ void onTabClicked(int tab);+ void onSearchChanged(const QString& text);+ void onSchemaChanged(int index);+ void onContextMenuRequested(const QPoint& pos);+ void onSavedQueryContextMenu(const QPoint& pos);++private:+ void buildUi();+ void loadSchemas();+ void loadTablesForSchema(QStandardItem* schemaItem, const QString& schemaName);+ void loadFunctionsForSchema(QStandardItem* parent, const QString& schemaName);+ void loadProceduresForSchema(QStandardItem* parent, const QString& schemaName);+ void reloadActiveSchema();+ void loadHistoryFromDb();+ void reloadSavedQueriesTree();++ // Data import / backup actions (wired via context menu).+ void runSqlFile();+ void importCsv(const QString& schema, const QString& table);+ void backupDatabase();+ void restoreDatabase();++ WorkspaceState* state_;+ std::shared_ptr<AppDatabase> appDb_;+ std::unique_ptr<SavedQueryRepository> savedQueryRepo_;++ // Tab bar (0=Items, 1=Queries, 2=History, 3=Saved)+ QPushButton* itemsTabBtn_ = nullptr;+ QPushButton* queriesTabBtn_ = nullptr;+ QPushButton* historyTabBtn_ = nullptr;+ QPushButton* savedTabBtn_ = nullptr;+ QStackedWidget* body_ = nullptr;+ int activeTab_ = 0;++ // Items tab+ QLineEdit* searchEdit_ = nullptr;+ QStackedWidget* itemsViewStack_ = nullptr; // 0=tree, 1=grid+ QPushButton* gridToggleBtn_ = nullptr;+ QTreeView* tree_ = nullptr;+ QStandardItemModel* model_ = nullptr;+ TableGridView* tableGrid_ = nullptr;++ // Bottom bar+ QComboBox* schemaCombo_ = nullptr;+ QLabel* dbInfoLabel_ = nullptr;+ QPushButton* disconnectBtn_ = nullptr;+ QPushButton* newTableBtn_ = nullptr;++ // History tab+ QListWidget* historyList_ = nullptr;++ // Saved queries tab+ QTreeWidget* savedTree_ = nullptr;+};++}diff --git a/linux/src/Presentation/Views/StatusBar/StatusBarView.cpp b/linux/src/Presentation/Views/StatusBar/StatusBarView.cppnew file mode 100644index 0000000..225022e--- /dev/null+++ b/linux/src/Presentation/Views/StatusBar/StatusBarView.cpp@@ -0,0 +1,61 @@+#include "Presentation/Views/StatusBar/StatusBarView.h"++#include <QFrame>+#include <QHBoxLayout>+#include <QLabel>++namespace gridex {++QLabel* StatusBarView::makeSeparator(QWidget* parent) {+ auto* s = new QLabel(QStringLiteral("|"), parent);+ s->setContentsMargins(6, 0, 6, 0);+ return s;+}++QLabel* StatusBarView::makeItem(QWidget* parent) {+ auto* l = new QLabel(QString{}, parent);+ return l;+}++StatusBarView::StatusBarView(QWidget* parent) : QWidget(parent) {+ buildUi();+}++void StatusBarView::buildUi() {+ setFixedHeight(24);+ setAutoFillBackground(true);++ auto* h = new QHBoxLayout(this);+ h->setContentsMargins(8, 0, 8, 0);+ h->setSpacing(0);++ connLabel_ = makeItem(this);+ schemaLabel_ = makeItem(this);+ rowsLabel_ = makeItem(this);+ timeLabel_ = makeItem(this);+ mcpLabel_ = makeItem(this);+ versionLabel_ = makeItem(this);++ connLabel_->setText(tr("Not connected"));+ versionLabel_->setText(QStringLiteral("v0.1"));++ h->addWidget(connLabel_);+ h->addWidget(makeSeparator(this));+ h->addWidget(schemaLabel_);+ h->addWidget(makeSeparator(this));+ h->addWidget(rowsLabel_);+ h->addWidget(makeSeparator(this));+ h->addWidget(timeLabel_);+ h->addStretch();+ h->addWidget(mcpLabel_);+ h->addWidget(makeSeparator(this));+ h->addWidget(versionLabel_);+}++void StatusBarView::setConnection(const QString& text) { connLabel_->setText(text.isEmpty() ? tr("Not connected") : text); }+void StatusBarView::setSchema(const QString& text) { schemaLabel_->setText(text); }+void StatusBarView::setRowCount(const QString& text) { rowsLabel_->setText(text); }+void StatusBarView::setQueryTime(const QString& text) { timeLabel_->setText(text); }+void StatusBarView::setMcpStatus(const QString& text) { mcpLabel_->setText(text); }++}diff --git a/linux/src/Presentation/Views/StatusBar/StatusBarView.h b/linux/src/Presentation/Views/StatusBar/StatusBarView.hnew file mode 100644index 0000000..a6f8bce--- /dev/null+++ b/linux/src/Presentation/Views/StatusBar/StatusBarView.h@@ -0,0 +1,37 @@+#pragma once++#include <QWidget>++class QLabel;++namespace gridex {++// 24px bottom bar matching macOS StatusBarSwiftUIView:+// [connection] | [schema] | [rows] | [time] [MCP] | [v0.1]+class StatusBarView : public QWidget {+ Q_OBJECT++public:+ explicit StatusBarView(QWidget* parent = nullptr);++public slots:+ void setConnection(const QString& text);+ void setSchema(const QString& text);+ void setRowCount(const QString& text);+ void setQueryTime(const QString& text);+ void setMcpStatus(const QString& text);++private:+ void buildUi();+ static QLabel* makeSeparator(QWidget* parent);+ static QLabel* makeItem(QWidget* parent);++ QLabel* connLabel_ = nullptr;+ QLabel* schemaLabel_ = nullptr;+ QLabel* rowsLabel_ = nullptr;+ QLabel* timeLabel_ = nullptr;+ QLabel* mcpLabel_ = nullptr;+ QLabel* versionLabel_ = nullptr;+};++}diff --git a/linux/src/Presentation/Views/TabBar/WorkspaceTabBar.cpp b/linux/src/Presentation/Views/TabBar/WorkspaceTabBar.cppnew file mode 100644index 0000000..dbda631--- /dev/null+++ b/linux/src/Presentation/Views/TabBar/WorkspaceTabBar.cpp@@ -0,0 +1,132 @@+#include "Presentation/Views/TabBar/WorkspaceTabBar.h"++#include <QHBoxLayout>+#include <QLabel>+#include <QPushButton>+#include <QUuid>++namespace gridex {++WorkspaceTabBar::WorkspaceTabBar(QWidget* parent) : QWidget(parent) {+ buildUi();+}++void WorkspaceTabBar::buildUi() {+ setFixedHeight(38);+ setAutoFillBackground(true);+ setObjectName(QStringLiteral("WorkspaceTabBar"));++ auto* root = new QHBoxLayout(this);+ root->setContentsMargins(0, 0, 0, 0);+ root->setSpacing(0);++ tabsLayout_ = new QHBoxLayout();+ tabsLayout_->setContentsMargins(0, 0, 0, 0);+ tabsLayout_->setSpacing(0);+ root->addLayout(tabsLayout_);++ plusBtn_ = new QPushButton(QStringLiteral("+"), this);+ plusBtn_->setObjectName(QStringLiteral("newTabButton"));+ plusBtn_->setFixedSize(36, 38);+ plusBtn_->setCursor(Qt::PointingHandCursor);+ plusBtn_->setToolTip(tr("New Query Tab (Ctrl+Shift+N)"));+ connect(plusBtn_, &QPushButton::clicked, this, &WorkspaceTabBar::newTabRequested);+ root->addWidget(plusBtn_);++ root->addStretch();+}++QString WorkspaceTabBar::addTab(const QString& label) {+ TabInfo t;+ t.id = QUuid::createUuid().toString(QUuid::WithoutBraces);+ t.label = label;+ tabs_.push_back(t);+ setActiveTab(t.id);+ return t.id;+}++void WorkspaceTabBar::removeTab(const QString& id) {+ auto it = std::find_if(tabs_.begin(), tabs_.end(),+ [&](const TabInfo& t) { return t.id == id; });+ if (it == tabs_.end()) return;+ const bool wasActive = activeId_ == id;+ const auto idx = std::distance(tabs_.begin(), it);+ tabs_.erase(it);++ if (wasActive && !tabs_.empty()) {+ const int next = std::min(static_cast<int>(idx), static_cast<int>(tabs_.size()) - 1);+ setActiveTab(tabs_[next].id);+ } else if (tabs_.empty()) {+ activeId_.clear();+ rebuildTabs();+ } else {+ rebuildTabs();+ }+}++void WorkspaceTabBar::setActiveTab(const QString& id) {+ activeId_ = id;+ rebuildTabs();+ emit tabSelected(id);+}++void WorkspaceTabBar::renameTab(const QString& id, const QString& label) {+ for (auto& t : tabs_) {+ if (t.id == id) { t.label = label; break; }+ }+ rebuildTabs();+}++void WorkspaceTabBar::rebuildTabs() {+ // Remove existing tab buttons from layout (delete old widgets).+ while (tabsLayout_->count() > 0) {+ auto* item = tabsLayout_->takeAt(0);+ if (item->widget()) item->widget()->deleteLater();+ delete item;+ }++ for (const auto& tab : tabs_) {+ const bool active = tab.id == activeId_;++ auto* btn = new QWidget(this);+ btn->setProperty("queryTab", true);+ btn->setProperty("active", active);+ btn->setFixedHeight(38);+ auto* h = new QHBoxLayout(btn);+ h->setContentsMargins(10, 0, 4, 0);+ h->setSpacing(5);++ // Colored connection-status dot (6×6, red when active, grey otherwise).+ auto* dot = new QLabel(btn);+ dot->setFixedSize(6, 6);+ dot->setObjectName(QStringLiteral("statusDot"));+ dot->setProperty("active", active);+ h->addWidget(dot);++ // Tab label — always visible text, bold when active.+ auto* label = new QPushButton(tab.label, btn);+ label->setFlat(true);+ label->setCursor(Qt::PointingHandCursor);+ label->setProperty("queryTabLabel", true);+ label->setProperty("active", active);+ const QString tabId = tab.id;+ connect(label, &QPushButton::clicked, this, [this, tabId] {+ setActiveTab(tabId);+ });+ h->addWidget(label);++ // Close button (×) — 18×18, flat.+ auto* closeBtn = new QPushButton(QStringLiteral("×"), btn);+ closeBtn->setFixedSize(18, 18);+ closeBtn->setCursor(Qt::PointingHandCursor);+ closeBtn->setObjectName(QStringLiteral("queryTabClose"));+ connect(closeBtn, &QPushButton::clicked, this, [this, tabId] {+ emit tabCloseRequested(tabId);+ });+ h->addWidget(closeBtn);++ tabsLayout_->addWidget(btn);+ }+}++}diff --git a/linux/src/Presentation/Views/TabBar/WorkspaceTabBar.h b/linux/src/Presentation/Views/TabBar/WorkspaceTabBar.hnew file mode 100644index 0000000..4b8989f--- /dev/null+++ b/linux/src/Presentation/Views/TabBar/WorkspaceTabBar.h@@ -0,0 +1,51 @@+#pragma once++#include <QWidget>+#include <QString>+#include <vector>++class QHBoxLayout;+class QPushButton;+class QScrollArea;++namespace gridex {++// Multi-tab bar matching macOS TabBarSwiftUIView:+// [Tab1 ×] [Tab2 ×] [+] ...spacer...+// Active tab highlighted with bottom accent bar. Each tab has a close button.+class WorkspaceTabBar : public QWidget {+ Q_OBJECT++public:+ struct TabInfo {+ QString id;+ QString label;+ };++ explicit WorkspaceTabBar(QWidget* parent = nullptr);++ // Returns the new tab's id.+ QString addTab(const QString& label);+ void removeTab(const QString& id);+ void setActiveTab(const QString& id);+ void renameTab(const QString& id, const QString& label);+ [[nodiscard]] QString activeTabId() const { return activeId_; }+ [[nodiscard]] int tabCount() const { return static_cast<int>(tabs_.size()); }++signals:+ void newTabRequested();+ void tabSelected(const QString& id);+ void tabCloseRequested(const QString& id);++private:+ void buildUi();+ void rebuildTabs();++ std::vector<TabInfo> tabs_;+ QString activeId_;+ QHBoxLayout* tabsLayout_ = nullptr;+ QPushButton* plusBtn_ = nullptr;+ int nextSeq_ = 1;+};++}diff --git a/linux/src/Presentation/Views/TableList/TableGridView.cpp b/linux/src/Presentation/Views/TableList/TableGridView.cppnew file mode 100644index 0000000..0331d20--- /dev/null+++ b/linux/src/Presentation/Views/TableList/TableGridView.cpp@@ -0,0 +1,312 @@+#include "Presentation/Views/TableList/TableGridView.h"++#include <QApplication>+#include <QClipboard>+#include <QComboBox>+#include <QFileDialog>+#include <QHBoxLayout>+#include <QLineEdit>+#include <QListView>+#include <QMenu>+#include <QMessageBox>+#include <QPushButton>+#include <QStandardItem>+#include <QStandardItemModel>+#include <QVBoxLayout>++#include "Core/Enums/SQLDialect.h"+#include "Core/Errors/GridexError.h"+#include "Presentation/ViewModels/WorkspaceState.h"+#include "Services/Export/ExportService.h"++namespace gridex {++namespace {+constexpr int kRoleTableName = Qt::UserRole + 1;+constexpr int kRoleSchemaName = Qt::UserRole + 2;+}++TableGridView::TableGridView(WorkspaceState* state, QWidget* parent)+ : QWidget(parent), state_(state) {+ buildUi();+ if (state_) {+ connect(state_, &WorkspaceState::connectionOpened,+ this, &TableGridView::onConnectionOpened);+ connect(state_, &WorkspaceState::connectionClosed,+ this, &TableGridView::onConnectionClosed);+ if (state_->isOpen()) onConnectionOpened();+ }+}++void TableGridView::buildUi() {+ auto* root = new QVBoxLayout(this);+ root->setContentsMargins(0, 0, 0, 0);+ root->setSpacing(0);++ // Toolbar: schema combo + search + refresh+ auto* toolbar = new QWidget(this);+ auto* tbH = new QHBoxLayout(toolbar);+ tbH->setContentsMargins(6, 6, 6, 6);+ tbH->setSpacing(6);++ schemaCb_ = new QComboBox(toolbar);+ schemaCb_->setToolTip(tr("Schema"));+ schemaCb_->setSizeAdjustPolicy(QComboBox::AdjustToContents);+ connect(schemaCb_, QOverload<int>::of(&QComboBox::currentIndexChanged),+ this, &TableGridView::onSchemaChanged);+ tbH->addWidget(schemaCb_);++ searchEd_ = new QLineEdit(toolbar);+ searchEd_->setPlaceholderText(tr("Filter tables..."));+ searchEd_->setClearButtonEnabled(true);+ connect(searchEd_, &QLineEdit::textChanged,+ this, [this](const QString& t) { onSearchChanged(t); });+ tbH->addWidget(searchEd_, 1);++ refreshBtn_ = new QPushButton(QStringLiteral("↻"), toolbar);+ refreshBtn_->setToolTip(tr("Refresh"));+ refreshBtn_->setFixedSize(28, 28);+ refreshBtn_->setCursor(Qt::PointingHandCursor);+ connect(refreshBtn_, &QPushButton::clicked, this, [this] { reload(); });+ tbH->addWidget(refreshBtn_);++ root->addWidget(toolbar);++ // Grid list view+ listView_ = new QListView(this);+ listView_->setViewMode(QListView::IconMode);+ listView_->setGridSize(QSize(110, 80));+ listView_->setIconSize(QSize(32, 32));+ listView_->setResizeMode(QListView::Adjust);+ listView_->setMovement(QListView::Static);+ listView_->setWordWrap(true);+ listView_->setEditTriggers(QAbstractItemView::NoEditTriggers);+ listView_->setSelectionMode(QAbstractItemView::SingleSelection);+ listView_->setContextMenuPolicy(Qt::CustomContextMenu);+ listView_->setFrameShape(QFrame::NoFrame);+ listView_->setUniformItemSizes(true);++ model_ = new QStandardItemModel(this);+ listView_->setModel(model_);++ connect(listView_, &QListView::doubleClicked,+ this, &TableGridView::onItemDoubleClicked);+ connect(listView_, &QListView::customContextMenuRequested,+ this, &TableGridView::onContextMenuRequested);++ root->addWidget(listView_, 1);+}++void TableGridView::reload() {+ const QString schema = schemaCb_ ? schemaCb_->currentText() : QString{};+ loadSchemas();+ if (!schema.isEmpty()) {+ const int idx = schemaCb_->findText(schema);+ if (idx >= 0) {+ QSignalBlocker blk(schemaCb_);+ schemaCb_->setCurrentIndex(idx);+ }+ }+ loadTables(schemaCb_ ? schemaCb_->currentText() : QString{});+}++void TableGridView::onConnectionOpened() {+ loadSchemas();+ loadTables(schemaCb_ ? schemaCb_->currentText() : QString{});+}++void TableGridView::onConnectionClosed() {+ if (schemaCb_) { QSignalBlocker blk(schemaCb_); schemaCb_->clear(); }+ model_->clear();+ allTableNames_.clear();+}++void TableGridView::loadSchemas() {+ if (!schemaCb_ || !state_ || !state_->adapter()) return;+ QSignalBlocker blk(schemaCb_);+ schemaCb_->clear();+ try {+ const auto schemas = state_->adapter()->listSchemas(std::nullopt);+ for (const auto& s : schemas)+ schemaCb_->addItem(QString::fromUtf8(s.c_str()));+ const int pubIdx = schemaCb_->findText(QStringLiteral("public"));+ schemaCb_->setCurrentIndex(pubIdx >= 0 ? pubIdx : 0);+ } catch (const GridexError&) {}+}++void TableGridView::loadTables(const QString& schema) {+ model_->clear();+ allTableNames_.clear();+ activeSchema_ = schema;+ if (!state_ || !state_->adapter()) return;++ try {+ const auto tables = state_->adapter()->listTables(schema.toStdString());+ for (const auto& t : tables) {+ const QString name = QString::fromUtf8(t.name.c_str());+ allTableNames_ << name;++ auto* item = new QStandardItem(name);+ item->setData(name, kRoleTableName);+ item->setData(schema, kRoleSchemaName);+ item->setIcon(QApplication::style()->standardIcon(QStyle::SP_FileDialogDetailedView));+ item->setToolTip(schema.isEmpty() ? name : (schema + "." + name));+ item->setTextAlignment(Qt::AlignHCenter | Qt::AlignBottom);+ model_->appendRow(item);+ }+ } catch (const GridexError& e) {+ auto* err = new QStandardItem(tr("(error)"));+ err->setEnabled(false);+ err->setToolTip(QString::fromUtf8(e.what()));+ model_->appendRow(err);+ }++ applyFilter(searchEd_ ? searchEd_->text() : QString{});+}++void TableGridView::applyFilter(const QString& text) {+ const QString lower = text.trimmed().toLower();+ for (int i = 0; i < model_->rowCount(); ++i) {+ auto* item = model_->item(i);+ const bool visible = lower.isEmpty() ||+ item->text().toLower().contains(lower);+ listView_->setRowHidden(i, !visible);+ }+}++void TableGridView::onSchemaChanged(int /*index*/) {+ loadTables(schemaCb_->currentText());+}++void TableGridView::onSearchChanged(const QString& text) {+ applyFilter(text);+}++void TableGridView::onItemDoubleClicked(const QModelIndex& index) {+ if (!index.isValid()) return;+ auto* item = model_->itemFromIndex(index);+ if (!item) return;+ emit tableSelected(item->data(kRoleSchemaName).toString(),+ item->data(kRoleTableName).toString());+}++void TableGridView::onContextMenuRequested(const QPoint& pos) {+ const QModelIndex index = listView_->indexAt(pos);+ if (!index.isValid()) return;+ auto* item = model_->itemFromIndex(index);+ if (!item) return;++ const QString schema = item->data(kRoleSchemaName).toString();+ const QString table = item->data(kRoleTableName).toString();++ QMenu menu(this);+ buildContextMenu(&menu, schema, table);+ menu.exec(listView_->viewport()->mapToGlobal(pos));+}++void TableGridView::buildContextMenu(QMenu* menu, const QString& schema, const QString& table) {+ auto* openAct = menu->addAction(tr("Open in New Tab"));+ connect(openAct, &QAction::triggered, this, [this, schema, table] {+ emit tableSelected(schema, table);+ });++ menu->addSeparator();++ auto* copyNameAct = menu->addAction(tr("Copy Table Name"));+ connect(copyNameAct, &QAction::triggered, this, [table] {+ QApplication::clipboard()->setText(table);+ });++ const QString selectSql = QStringLiteral("SELECT * FROM %1 LIMIT 100;").arg(table);+ auto* copySelectAct = menu->addAction(tr("Copy SELECT * FROM..."));+ connect(copySelectAct, &QAction::triggered, this, [selectSql] {+ QApplication::clipboard()->setText(selectSql);+ });++ menu->addSeparator();++ auto* truncateAct = menu->addAction(tr("Truncate Table..."));+ connect(truncateAct, &QAction::triggered, this, [this, schema, table] {+ if (!state_ || !state_->adapter()) return;+ const auto answer = QMessageBox::warning(+ this, tr("Truncate Table"),+ tr("Are you sure you want to truncate \"%1\"?\nAll rows will be deleted.").arg(table),+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);+ if (answer != QMessageBox::Yes) return;+ try {+ const DatabaseType dt = state_->adapter()->databaseType();+ std::string sql;+ if (dt == DatabaseType::SQLite) {+ sql = "DELETE FROM " + quoteIdentifier(sqlDialect(dt), table.toStdString());+ } else if (!schema.isEmpty()) {+ sql = "TRUNCATE TABLE "+ + quoteIdentifier(sqlDialect(dt), schema.toStdString())+ + "." + quoteIdentifier(sqlDialect(dt), table.toStdString());+ } else {+ sql = "TRUNCATE TABLE " + quoteIdentifier(sqlDialect(dt), table.toStdString());+ }+ state_->adapter()->executeRaw(sql);+ } catch (const GridexError& e) {+ QMessageBox::critical(this, tr("Truncate Failed"), QString::fromUtf8(e.what()));+ }+ });++ auto* dropAct = menu->addAction(tr("Delete Table..."));+ connect(dropAct, &QAction::triggered, this, [this, schema, table] {+ if (!state_ || !state_->adapter()) return;+ const auto answer = QMessageBox::warning(+ this, tr("Delete Table"),+ tr("Are you sure you want to drop \"%1\"?\nThis action cannot be undone.").arg(table),+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);+ if (answer != QMessageBox::Yes) return;+ try {+ const DatabaseType dt = state_->adapter()->databaseType();+ std::string sql;+ if (!schema.isEmpty() &&+ dt != DatabaseType::SQLite &&+ dt != DatabaseType::MySQL)+ {+ sql = "DROP TABLE "+ + quoteIdentifier(sqlDialect(dt), schema.toStdString())+ + "." + quoteIdentifier(sqlDialect(dt), table.toStdString());+ } else {+ sql = "DROP TABLE " + quoteIdentifier(sqlDialect(dt), table.toStdString());+ }+ state_->adapter()->executeRaw(sql);+ loadTables(schema);+ emit tableDeleted(schema, table);+ } catch (const GridexError& e) {+ QMessageBox::critical(this, tr("Delete Table Failed"), QString::fromUtf8(e.what()));+ }+ });++ menu->addSeparator();++ auto* exportAct = menu->addAction(tr("Export Table..."));+ connect(exportAct, &QAction::triggered, this, [this, schema, table] {+ if (!state_ || !state_->adapter()) return;+ const QString path = QFileDialog::getSaveFileName(+ this, tr("Export Table — %1").arg(table),+ QStringLiteral("%1.csv").arg(table),+ tr("CSV (*.csv);;JSON (*.json);;SQL (*.sql)"));+ if (path.isEmpty()) return;+ try {+ const std::optional<std::string> schemaOpt =+ schema.isEmpty() ? std::nullopt : std::make_optional(schema.toStdString());+ const QueryResult result = state_->adapter()->fetchRows(+ table.toStdString(), schemaOpt, std::nullopt, std::nullopt, std::nullopt,+ 10000, 0);+ const std::string fp = path.toStdString();+ if (path.endsWith(QStringLiteral(".json"), Qt::CaseInsensitive))+ ExportService::exportToJson(result, fp);+ else if (path.endsWith(QStringLiteral(".sql"), Qt::CaseInsensitive))+ ExportService::exportToSql(result, table.toStdString(), fp);+ else+ ExportService::exportToCsv(result, fp);+ } catch (const std::exception& e) {+ QMessageBox::critical(this, tr("Export Failed"), QString::fromUtf8(e.what()));+ }+ });+}++}diff --git a/linux/src/Presentation/Views/TableList/TableGridView.h b/linux/src/Presentation/Views/TableList/TableGridView.hnew file mode 100644index 0000000..992f2e1--- /dev/null+++ b/linux/src/Presentation/Views/TableList/TableGridView.h@@ -0,0 +1,59 @@+#pragma once++#include <QWidget>+#include <QString>+#include <QStringList>++class QComboBox;+class QLineEdit;+class QListView;+class QMenu;+class QPushButton;+class QStandardItemModel;++namespace gridex {++class WorkspaceState;++// Grid-view alternative to the tree sidebar: shows tables for the selected+// schema as icon tiles. Double-click emits tableSelected, right-click shows+// context menu matching the sidebar's table actions.+class TableGridView : public QWidget {+ Q_OBJECT++public:+ explicit TableGridView(WorkspaceState* state, QWidget* parent = nullptr);++ void reload();+ void onSearchChanged(const QString& text);++signals:+ void tableSelected(const QString& schema, const QString& table);+ void tableDeleted(const QString& schema, const QString& table);++private slots:+ void onSchemaChanged(int index);+ void onItemDoubleClicked(const QModelIndex& index);+ void onContextMenuRequested(const QPoint& pos);+ void onConnectionOpened();+ void onConnectionClosed();++private:+ void buildUi();+ void loadSchemas();+ void loadTables(const QString& schema);+ void applyFilter(const QString& text);+ void buildContextMenu(QMenu* menu, const QString& schema, const QString& table);++ WorkspaceState* state_ = nullptr;+ QComboBox* schemaCb_ = nullptr;+ QLineEdit* searchEd_ = nullptr;+ QPushButton* refreshBtn_ = nullptr;+ QListView* listView_ = nullptr;+ QStandardItemModel* model_ = nullptr;++ QStringList allTableNames_;+ QString activeSchema_;+};++}diff --git a/linux/src/Presentation/Views/TableStructure/TableStructureView.cpp b/linux/src/Presentation/Views/TableStructure/TableStructureView.cppnew file mode 100644index 0000000..f337b8d--- /dev/null+++ b/linux/src/Presentation/Views/TableStructure/TableStructureView.cpp@@ -0,0 +1,252 @@+#include "Presentation/Views/TableStructure/TableStructureView.h"++#include <QFrame>+#include <QHeaderView>+#include <QLabel>+#include <QScrollArea>+#include <QStandardItem>+#include <QStandardItemModel>+#include <QTableView>+#include <QVBoxLayout>++namespace gridex {++namespace {++QStandardItem* cell(const QString& text) {+ auto* item = new QStandardItem(text);+ item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);+ item->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft);+ return item;+}++QStandardItem* boolCell(bool value) {+ return cell(value ? QStringLiteral("✓") : QString{});+}++QString fromStdStr(const std::string& s) {+ return QString::fromUtf8(s.data(), static_cast<qsizetype>(s.size()));+}++QString optStr(const std::optional<std::string>& opt) {+ return opt ? fromStdStr(*opt) : QString{};+}++QString joinVec(const std::vector<std::string>& v) {+ QString out;+ for (std::size_t i = 0; i < v.size(); ++i) {+ if (i > 0) out += QStringLiteral(", ");+ out += fromStdStr(v[i]);+ }+ return out;+}++// Section header label matching macOS InlineStructureView divider style.+QLabel* makeSectionHeader(const QString& title, QWidget* parent) {+ auto* lbl = new QLabel(title, parent);+ return lbl;+}++} // namespace++// ---------------------------------------------------------------------------+// Construction+// ---------------------------------------------------------------------------++TableStructureView::TableStructureView(QWidget* parent) : QWidget(parent) {+ buildUi();+}++void TableStructureView::buildUi() {+ auto* outerV = new QVBoxLayout(this);+ outerV->setContentsMargins(0, 0, 0, 0);+ outerV->setSpacing(0);++ // Wrap everything in a QScrollArea so the single-page layout scrolls.+ scrollArea_ = new QScrollArea(this);+ scrollArea_->setFrameShape(QFrame::NoFrame);+ scrollArea_->setWidgetResizable(true);+ scrollArea_->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);+ scrollArea_->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);++ auto* container = new QWidget(scrollArea_);+ auto* vbox = new QVBoxLayout(container);+ vbox->setContentsMargins(0, 0, 0, 8);+ vbox->setSpacing(0);++ // ---- Columns section ----+ vbox->addWidget(makeSectionHeader(tr("Columns"), container));++ auto* colDiv = new QFrame(container);+ colDiv->setFrameShape(QFrame::HLine);+ vbox->addWidget(colDiv);++ colModel_ = new QStandardItemModel(0, 7, this);+ colModel_->setHorizontalHeaderLabels({+ tr("Name"), tr("Type"), tr("Nullable"),+ tr("Default"), tr("PK"), tr("Auto-Increment"), tr("Comment")+ });+ colView_ = makeTableView(container);+ colView_->setModel(colModel_);+ vbox->addWidget(colView_);++ // ---- Indexes section ----+ vbox->addSpacing(6);+ vbox->addWidget(makeSectionHeader(tr("Indexes"), container));++ auto* idxDiv = new QFrame(container);+ idxDiv->setFrameShape(QFrame::HLine);+ vbox->addWidget(idxDiv);++ idxModel_ = new QStandardItemModel(0, 4, this);+ idxModel_->setHorizontalHeaderLabels({+ tr("Name"), tr("Columns"), tr("Unique"), tr("Type")+ });+ idxView_ = makeTableView(container);+ idxView_->setModel(idxModel_);+ vbox->addWidget(idxView_);++ // ---- Foreign Keys section (hidden when empty) ----+ fkSection_ = new QWidget(container);+ auto* fkV = new QVBoxLayout(fkSection_);+ fkV->setContentsMargins(0, 0, 0, 0);+ fkV->setSpacing(0);++ fkV->addSpacing(6);+ fkV->addWidget(makeSectionHeader(tr("Foreign Keys"), fkSection_));++ auto* fkDiv = new QFrame(fkSection_);+ fkDiv->setFrameShape(QFrame::HLine);+ fkV->addWidget(fkDiv);++ fkModel_ = new QStandardItemModel(0, 6, this);+ fkModel_->setHorizontalHeaderLabels({+ tr("Name"), tr("Column"),+ tr("Referenced Table"), tr("Referenced Column"),+ tr("On Delete"), tr("On Update")+ });+ fkView_ = makeTableView(fkSection_);+ fkView_->setModel(fkModel_);+ fkV->addWidget(fkView_);++ fkSection_->setVisible(false);+ vbox->addWidget(fkSection_);++ vbox->addStretch();++ scrollArea_->setWidget(container);+ outerV->addWidget(scrollArea_);+}++// ---------------------------------------------------------------------------+// Public API+// ---------------------------------------------------------------------------++void TableStructureView::loadStructure(const TableDescription& desc) {+ populateColumns(desc.columns);+ populateIndexes(desc.indexes);+ populateForeignKeys(desc.foreignKeys);+}++void TableStructureView::clear() {+ colModel_->removeRows(0, colModel_->rowCount());+ idxModel_->removeRows(0, idxModel_->rowCount());+ fkModel_->removeRows(0, fkModel_->rowCount());+ if (fkSection_) fkSection_->setVisible(false);+}++// ---------------------------------------------------------------------------+// Private helpers+// ---------------------------------------------------------------------------++void TableStructureView::populateColumns(const std::vector<ColumnInfo>& columns) {+ colModel_->removeRows(0, colModel_->rowCount());+ colModel_->setRowCount(static_cast<int>(columns.size()));+ for (int row = 0; row < static_cast<int>(columns.size()); ++row) {+ const auto& c = columns[row];+ colModel_->setItem(row, 0, cell(fromStdStr(c.name)));+ colModel_->setItem(row, 1, cell(fromStdStr(c.dataType)));+ colModel_->setItem(row, 2, boolCell(c.isNullable));+ colModel_->setItem(row, 3, cell(optStr(c.defaultValue)));+ colModel_->setItem(row, 4, boolCell(c.isPrimaryKey));+ colModel_->setItem(row, 5, boolCell(c.isAutoIncrement));+ colModel_->setItem(row, 6, cell(optStr(c.comment)));+ }+ colView_->resizeColumnsToContents();+ colView_->horizontalHeader()->setStretchLastSection(true);+ // Adjust table height to content so scroll area calculates correctly.+ const int rowH = colView_->verticalHeader()->defaultSectionSize();+ const int hdrH = colView_->horizontalHeader()->height();+ const int rows = colModel_->rowCount();+ colView_->setFixedHeight(hdrH + rowH * std::max(rows, 1) + 4);+}++void TableStructureView::populateIndexes(const std::vector<IndexInfo>& indexes) {+ idxModel_->removeRows(0, idxModel_->rowCount());+ idxModel_->setRowCount(static_cast<int>(indexes.size()));+ for (int row = 0; row < static_cast<int>(indexes.size()); ++row) {+ const auto& idx = indexes[row];+ idxModel_->setItem(row, 0, cell(fromStdStr(idx.name)));+ idxModel_->setItem(row, 1, cell(joinVec(idx.columns)));+ idxModel_->setItem(row, 2, boolCell(idx.isUnique));+ idxModel_->setItem(row, 3, cell(optStr(idx.type)));+ }+ idxView_->resizeColumnsToContents();+ idxView_->horizontalHeader()->setStretchLastSection(true);+ const int rowH = idxView_->verticalHeader()->defaultSectionSize();+ const int hdrH = idxView_->horizontalHeader()->height();+ const int rows = idxModel_->rowCount();+ idxView_->setFixedHeight(hdrH + rowH * std::max(rows, 1) + 4);+}++void TableStructureView::populateForeignKeys(const std::vector<ForeignKeyInfo>& fks) {+ fkModel_->removeRows(0, fkModel_->rowCount());+ fkModel_->setRowCount(static_cast<int>(fks.size()));+ for (int row = 0; row < static_cast<int>(fks.size()); ++row) {+ const auto& fk = fks[row];+ fkModel_->setItem(row, 0, cell(optStr(fk.name)));+ fkModel_->setItem(row, 1, cell(joinVec(fk.columns)));+ fkModel_->setItem(row, 2, cell(fromStdStr(fk.referencedTable)));+ fkModel_->setItem(row, 3, cell(joinVec(fk.referencedColumns)));+ fkModel_->setItem(row, 4, cell(QString::fromUtf8(rawValue(fk.onDelete).data(),+ static_cast<qsizetype>(rawValue(fk.onDelete).size()))));+ fkModel_->setItem(row, 5, cell(QString::fromUtf8(rawValue(fk.onUpdate).data(),+ static_cast<qsizetype>(rawValue(fk.onUpdate).size()))));+ }+ fkView_->resizeColumnsToContents();+ fkView_->horizontalHeader()->setStretchLastSection(true);++ const bool hasFk = !fks.empty();+ fkSection_->setVisible(hasFk);+ if (hasFk) {+ const int rowH = fkView_->verticalHeader()->defaultSectionSize();+ const int hdrH = fkView_->horizontalHeader()->height();+ fkView_->setFixedHeight(hdrH + rowH * static_cast<int>(fks.size()) + 4);+ }+}++// ---------------------------------------------------------------------------+// Static factory+// ---------------------------------------------------------------------------++QTableView* TableStructureView::makeTableView(QWidget* parent) {+ auto* view = new QTableView(parent);+ view->setFrameShape(QFrame::NoFrame);+ view->setAlternatingRowColors(true);+ view->setShowGrid(true);+ view->setSelectionBehavior(QAbstractItemView::SelectRows);+ view->setSelectionMode(QAbstractItemView::SingleSelection);+ view->setEditTriggers(QAbstractItemView::NoEditTriggers);+ view->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);+ view->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);+ view->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);+ view->horizontalHeader()->setStretchLastSection(true);+ view->verticalHeader()->setDefaultSectionSize(30);+ view->verticalHeader()->hide();+ // Disable internal scroll so the outer QScrollArea drives scrolling.+ view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);+ view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);+ return view;+}++} // namespace gridexdiff --git a/linux/src/Presentation/Views/TableStructure/TableStructureView.h b/linux/src/Presentation/Views/TableStructure/TableStructureView.hnew file mode 100644index 0000000..67916d8--- /dev/null+++ b/linux/src/Presentation/Views/TableStructure/TableStructureView.h@@ -0,0 +1,49 @@+#pragma once++#include <QWidget>++#include "Core/Models/Schema/SchemaSnapshot.h"++class QScrollArea;+class QTableView;+class QStandardItemModel;++namespace gridex {++// Read-only structure viewer: single scrollable page with Columns + Indexes + Foreign Keys+// sections stacked vertically — matches macOS InlineStructureView (no separate tabs).+// Call loadStructure() whenever the active table changes; call clear() when no table selected.+class TableStructureView : public QWidget {+ Q_OBJECT++public:+ explicit TableStructureView(QWidget* parent = nullptr);++ void loadStructure(const TableDescription& desc);+ void clear();++private:+ void buildUi();+ void populateColumns(const std::vector<ColumnInfo>& columns);+ void populateIndexes(const std::vector<IndexInfo>& indexes);+ void populateForeignKeys(const std::vector<ForeignKeyInfo>& fks);++ static QTableView* makeTableView(QWidget* parent);++ QScrollArea* scrollArea_ = nullptr;++ // Columns section+ QTableView* colView_ = nullptr;+ QStandardItemModel* colModel_ = nullptr;++ // Indexes section+ QTableView* idxView_ = nullptr;+ QStandardItemModel* idxModel_ = nullptr;++ // Foreign Keys section+ QWidget* fkSection_ = nullptr;+ QTableView* fkView_ = nullptr;+ QStandardItemModel* fkModel_ = nullptr;+};++}diff --git a/linux/src/Presentation/Windows/Main/MainWindow.cpp b/linux/src/Presentation/Windows/Main/MainWindow.cppnew file mode 100644index 0000000..2714622--- /dev/null+++ b/linux/src/Presentation/Windows/Main/MainWindow.cpp@@ -0,0 +1,761 @@+#include "Presentation/Windows/Main/MainWindow.h"++#include <chrono>+#include <thread>++#include <QAction>+#include <QApplication>+#include <QFileDialog>+#include <QFrame>+#include <QHBoxLayout>+#include <QInputDialog>+#include <QLabel>+#include <QMenu>+#include <QMenuBar>+#include <QAbstractButton>+#include <QMessageBox>+#include <QPushButton>+#include <QSettings>+#include <QStackedWidget>+#include <QStandardPaths>+#include <QStatusBar>+#include <QString>+#include <QWidget>++#include <QJsonArray>+#include <QJsonDocument>+#include <QJsonObject>++#include "Core/Errors/GridexError.h"+#include "Core/Models/Database/ConnectionConfigJson.h"+#include "Data/Adapters/AdapterFactory.h"+#include "Data/Keychain/SecretStore.h"+#include "Data/Persistence/AppConnectionRepository.h"+#include "Data/Persistence/AppDatabase.h"+#include "Domain/UseCases/Connection/TestConnection.h"+#include "Presentation/ViewModels/ConnectionListViewModel.h"+#include "Services/Export/DatabaseDumpRunner.h"+#include "Services/SSH/SSHTunnelManager.h"+#include "Presentation/ViewModels/WorkspaceState.h"+#include "Presentation/Views/ConnectionForm/ConnectionFormDialog.h"+#include "Presentation/Views/Home/HomeBrandingPanel.h"+#include "Presentation/Views/Main/WorkspaceView.h"+#include "App/MCP/MCPConnectionProvider.h"+#include "Presentation/Views/MCP/MCPWindow.h"+#include "Presentation/Views/Settings/SettingsDialog.h"+#include "Presentation/Views/Sidebar/ConnectionSidebar.h"+#include "Presentation/Views/TabBar/WorkspaceTabBar.h"+#include "Services/MCP/MCPServer.h"+#include "Services/MCP/Security/ApprovalGate.h"++namespace gridex {++MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) {+ setWindowTitle(QStringLiteral("Gridex"));+ // Match macOS HomeView initial size (900x500 — focused connection picker).+ resize(900, 500);++ wireBackend();+ setupMenuBar();+ setupCentralLayout();+ setupStatusBar();++ viewModel_->reload();+}++MainWindow::~MainWindow() = default;++void MainWindow::wireBackend() {+ appDb_ = std::make_shared<AppDatabase>();+ try {+ appDb_->open(); // default path: $XDG_DATA_HOME/gridex/app.sqlite+ } catch (const GridexError& e) {+ QMessageBox::critical(this, tr("Storage error"),+ tr("Failed to open app database: %1").arg(QString::fromUtf8(e.what())));+ }+ repo_ = std::make_unique<AppConnectionRepository>(appDb_);+ secretStore_ = std::make_unique<SecretStore>();+ viewModel_ = std::make_unique<ConnectionListViewModel>(repo_.get());+ workspace_ = std::make_unique<WorkspaceState>();+ connect(viewModel_.get(), &ConnectionListViewModel::errorOccurred,+ this, &MainWindow::onVmError);++ // MCP server (stays stopped until user presses Start in the MCP window).+ mcpProvider_ = std::make_unique<MCPConnectionProvider>(repo_.get(), secretStore_.get());+ std::shared_ptr<mcp::IMCPConnectionProvider> providerShim(mcpProvider_.get(), [](auto*){});+ mcpServer_ = std::make_unique<mcp::MCPServer>(+ providerShim, "1.0.0", mcp::MCPTransportMode::InProcess);++ // Approval dialog callback — runs on the GUI main thread via QMetaObject.+ mcpServer_->approvalGate().setDialogCallback(+ [this](const std::string& tool,+ const std::string& description,+ const std::string& details,+ const std::string& connectionId,+ const mcp::MCPAuditClient& client) -> mcp::ApprovalResult {+ mcp::ApprovalResult result = mcp::ApprovalResult::Denied;+ QMetaObject::invokeMethod(this, [&]() {+ QMessageBox box(this);+ box.setWindowTitle(tr("%1 wants to:").arg(QString::fromStdString(client.name)));+ box.setText(QString::fromStdString(description));+ box.setInformativeText(QString::fromStdString(details)+ + "\n\nConnection: " + QString::fromStdString(connectionId.substr(0, 8)) + "…");+ box.setIcon(QMessageBox::Warning);+ auto* denyBtn = static_cast<QAbstractButton*>(box.addButton(tr("Deny"), QMessageBox::RejectRole));+ auto* onceBtn = static_cast<QAbstractButton*>(box.addButton(tr("Approve Once"), QMessageBox::AcceptRole));+ auto* sessionBtn = static_cast<QAbstractButton*>(box.addButton(tr("Approve for Session"), QMessageBox::AcceptRole));+ (void)tool;+ box.exec();+ QAbstractButton* clicked = box.clickedButton();+ if (clicked == sessionBtn) result = mcp::ApprovalResult::ApprovedForSession;+ else if (clicked == onceBtn) result = mcp::ApprovalResult::Approved;+ else result = mcp::ApprovalResult::Denied;+ (void)denyBtn;+ }, Qt::BlockingQueuedConnection);+ return result;+ });++ // Apply saved rate limits / audit retention.+ {+ QSettings s;+ mcp::RateLimits l;+ l.queriesPerMinute = s.value("mcp.rateLimit.queriesPerMinute", 60).toInt();+ l.queriesPerHour = s.value("mcp.rateLimit.queriesPerHour", 1000).toInt();+ l.writesPerMinute = s.value("mcp.rateLimit.writesPerMinute", 10).toInt();+ l.ddlPerMinute = s.value("mcp.rateLimit.ddlPerMinute", 1).toInt();+ mcpServer_->rateLimiter().setLimits(l);+ mcpServer_->auditLogger().setMaxFileSize(+ static_cast<qint64>(s.value("mcp.audit.maxSizeMB", 100).toInt()) * 1024 * 1024);+ }+}++void MainWindow::setupMenuBar() {+ // ---- File menu (matches macOS CommandGroup) ----+ auto* fileMenu = menuBar()->addMenu(tr("&File"));+ auto* newConn = fileMenu->addAction(tr("New &Connection..."));+ newConn->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_T));+ connect(newConn, &QAction::triggered, this, &MainWindow::onAddConnection);++ newQueryAction_ = fileMenu->addAction(tr("New &Query"));+ newQueryAction_->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_N));+ newQueryAction_->setEnabled(false);+ connect(newQueryAction_, &QAction::triggered, this, &MainWindow::onNewQueryTab);++ auto* closeTabAction = fileMenu->addAction(tr("Close &Tab"));+ closeTabAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_W));+ closeTabAction->setEnabled(true);+ connect(closeTabAction, &QAction::triggered, this, [this] {+ if (!workspaceView_ || !workspace_ || !workspace_->isOpen()) return;+ // Delegate to the tab bar to close the currently active tab.+ auto* bar = workspaceView_->findChild<WorkspaceTabBar*>();+ if (bar && !bar->activeTabId().isEmpty()) {+ bar->tabCloseRequested(bar->activeTabId());+ }+ });++ fileMenu->addSeparator();++ disconnectAction_ = fileMenu->addAction(tr("&Disconnect"));+ disconnectAction_->setEnabled(false);+ connect(disconnectAction_, &QAction::triggered, this, &MainWindow::onDisconnect);++ fileMenu->addSeparator();+ auto* importConns = fileMenu->addAction(tr("&Import Connections..."));+ connect(importConns, &QAction::triggered, this, &MainWindow::onImportConnections);+ auto* exportConns = fileMenu->addAction(tr("&Export Connections..."));+ connect(exportConns, &QAction::triggered, this, &MainWindow::onExportConnections);++ fileMenu->addSeparator();+ auto* prefs = fileMenu->addAction(tr("&Preferences..."));+ prefs->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Comma));+ connect(prefs, &QAction::triggered, this, &MainWindow::onOpenPreferences);++ fileMenu->addSeparator();+ auto* quit = fileMenu->addAction(tr("&Quit"));+ quit->setShortcut(QKeySequence::Quit);+ connect(quit, &QAction::triggered, qApp, &QApplication::quit);++ // ---- Query menu ----+ auto* queryMenu = menuBar()->addMenu(tr("&Query"));+ auto* runQuery = queryMenu->addAction(tr("&Run Query"));+ runQuery->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Return));+ runQuery->setEnabled(false); // wired in Phase 3d+ when QueryEditor is active++ auto* toolsMenu = menuBar()->addMenu(tr("&Tools"));+ auto* mcpAction = toolsMenu->addAction(tr("MCP Server…"));+ connect(mcpAction, &QAction::triggered, this, &MainWindow::onOpenMCPServer);++ auto* helpMenu = menuBar()->addMenu(tr("&Help"));+ auto* shortcuts = helpMenu->addAction(tr("Keyboard &Shortcuts"));+ shortcuts->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Slash));+ connect(shortcuts, &QAction::triggered, this, &MainWindow::onShowShortcuts);+ helpMenu->addSeparator();+ auto* about = helpMenu->addAction(tr("&About Gridex"));+ connect(about, &QAction::triggered, this, &MainWindow::onShowAbout);+}++void MainWindow::updateWorkspaceActions() {+ const bool open = workspace_ && workspace_->isOpen();+ newQueryAction_->setEnabled(open);+ disconnectAction_->setEnabled(open);+}++void MainWindow::onNewQueryTab() {+ if (!workspace_ || !workspace_->isOpen()) return;+ if (workspaceView_) workspaceView_->onNewQueryTab();+}++void MainWindow::onDisconnect() {+ if (!workspace_) return;+ workspace_->close();+ stack_->setCurrentIndex(0);+ resize(900, 500);+ updateWorkspaceActions();+}++void MainWindow::setupCentralLayout() {+ // Matches macOS MainView routing: HomeView vs WorkspaceView stacked.+ stack_ = new QStackedWidget(this);++ auto* home = new QWidget(stack_);+ auto* h = new QHBoxLayout(home);+ h->setContentsMargins(0, 0, 0, 0);+ h->setSpacing(0);++ brandPanel_ = new HomeBrandingPanel(home);+ connect(brandPanel_, &HomeBrandingPanel::newConnectionRequested,+ this, &MainWindow::onAddConnection);+ connect(brandPanel_, &HomeBrandingPanel::newGroupRequested,+ this, [this] { statusBar()->showMessage(tr("Use right-click on a connection to move it to a group"), 3000); });+ connect(brandPanel_, &HomeBrandingPanel::backupRequested,+ this, &MainWindow::onBackupRequested);+ connect(brandPanel_, &HomeBrandingPanel::restoreRequested,+ this, &MainWindow::onRestoreRequested);+ h->addWidget(brandPanel_);++ auto* divider = new QFrame(home);+ divider->setFrameShape(QFrame::VLine);+ h->addWidget(divider);++ connectionsPanel_ = new ConnectionSidebar(viewModel_.get(), appDb_, home);+ connect(connectionsPanel_, &ConnectionSidebar::addConnectionRequested,+ this, &MainWindow::onAddConnection);+ connect(connectionsPanel_, &ConnectionSidebar::newGroupRequested,+ this, [this] {+ bool ok = false;+ const QString name = QInputDialog::getText(this, tr("New Group"), tr("Group name:"),+ QLineEdit::Normal, QString{}, &ok);+ if (!ok || name.trimmed().isEmpty()) return;+ statusBar()->showMessage(tr("Group \"%1\" ready — move connections into it via right-click").arg(name), 4000);+ });+ connect(connectionsPanel_, &ConnectionSidebar::editConnectionRequested,+ this, &MainWindow::onEditConnection);+ connect(connectionsPanel_, &ConnectionSidebar::removeConnectionRequested,+ this, &MainWindow::onRemoveConnection);+ connect(connectionsPanel_, &ConnectionSidebar::connectionSelected,+ this, &MainWindow::onConnectionSelected);+ h->addWidget(connectionsPanel_, 1);++ stack_->addWidget(home);++ // Workspace page (built once; listens to WorkspaceState signals).+ workspaceView_ = new WorkspaceView(workspace_.get(), secretStore_.get(), appDb_, stack_);+ connect(workspaceView_, &WorkspaceView::disconnectRequested, this, &MainWindow::onDisconnect);+ connect(workspace_.get(), &WorkspaceState::connectionOpened, this, [this] {+ stack_->setCurrentIndex(1);+ resize(1280, 800);+ updateWorkspaceActions();+ });+ connect(workspace_.get(), &WorkspaceState::connectionClosed, this, [this] {+ stack_->setCurrentIndex(0);+ updateWorkspaceActions();+ });+ stack_->addWidget(workspaceView_);++ setCentralWidget(stack_);+}++void MainWindow::setupStatusBar() {+ statusBar()->showMessage(tr("Ready"));+}++void MainWindow::onAddConnection() {+ ConnectionFormDialog dialog(this);+ connect(&dialog, &ConnectionFormDialog::testRequested, this,+ [this, dlg = &dialog](const ConnectionConfig& cfg,+ const std::optional<std::string>& pw) {+ const auto start = std::chrono::steady_clock::now();+ try {+ ConnectionConfig effective = cfg;+ std::unique_ptr<SSHTunnelManager> tmpTunnel;++ // If SSH configured, create a temporary tunnel for the test.+ if (cfg.sshConfig) {+ tmpTunnel = std::make_unique<SSHTunnelManager>();+ auto sshPw = dlg->sshPassword();+ const auto localPort = tmpTunnel->establish(+ "test-probe", *cfg.sshConfig,+ cfg.host.value_or("localhost"),+ cfg.port.value_or(defaultPort(cfg.databaseType)),+ sshPw);+ effective.host = "127.0.0.1";+ effective.port = static_cast<int>(localPort);+ // Small delay to let relay thread call accept().+ std::this_thread::sleep_for(std::chrono::milliseconds(100));+ }++ auto adapter = createAdapter(cfg.databaseType);+ adapter->connect(effective, pw);+ const auto ver = adapter->serverVersion();+ adapter->disconnect();++ const auto ms = static_cast<int>(+ std::chrono::duration_cast<std::chrono::milliseconds>(+ std::chrono::steady_clock::now() - start).count());+ dlg->showTestResult(true,+ tr("Connected! %1 (%2ms)")+ .arg(QString::fromUtf8(ver.c_str())).arg(ms));+ } catch (const std::exception& e) {+ dlg->showTestResult(false, QString::fromUtf8(e.what()));+ }+ });++ const int result = dialog.exec();+ if (result == ConnectionFormDialog::Cancelled) return;++ auto cfg = dialog.config();+ viewModel_->upsert(cfg);++ if (dialog.storeInKeychain()) {+ if (auto pw = dialog.password()) {+ try { secretStore_->savePassword(cfg.id, *pw); }+ catch (const std::exception& e) {+ statusBar()->showMessage(tr("DB credentials not saved: %1").arg(e.what()), 5000);+ }+ }+ // Save SSH password separately if SSH is configured.+ if (auto sshPw = dialog.sshPassword(); sshPw && cfg.sshConfig) {+ try { secretStore_->saveSSHPassword(cfg.id, *sshPw); }+ catch (const std::exception& e) {+ statusBar()->showMessage(tr("SSH credentials not saved: %1").arg(e.what()), 5000);+ }+ }+ }+ const auto msg = result == ConnectionFormDialog::Connect+ ? tr("Connected to \"%1\"")+ : tr("Saved connection \"%1\"");+ statusBar()->showMessage(msg.arg(QString::fromUtf8(cfg.name.c_str())), 3000);+}++void MainWindow::onEditConnection(const QString& id) {+ const auto existing = viewModel_->find(id.toStdString());+ if (!existing) return;++ ConnectionFormDialog dialog(this);+ dialog.setConfig(*existing);+ try {+ if (auto pw = secretStore_->loadPassword(existing->id)) dialog.setPassword(*pw);+ } catch (...) {}+ // Load SSH password too.+ try {+ if (auto sshPw = secretStore_->loadSSHPassword(existing->id)) dialog.setSshPassword(*sshPw);+ } catch (...) {}++ connect(&dialog, &ConnectionFormDialog::testRequested, this,+ [this, dlg = &dialog](const ConnectionConfig& cfg,+ const std::optional<std::string>& pw) {+ const auto start = std::chrono::steady_clock::now();+ try {+ ConnectionConfig effective = cfg;+ std::unique_ptr<SSHTunnelManager> tmpTunnel;+ if (cfg.sshConfig) {+ tmpTunnel = std::make_unique<SSHTunnelManager>();+ auto sshPw = dlg->sshPassword();+ const auto localPort = tmpTunnel->establish(+ "test-probe", *cfg.sshConfig,+ cfg.host.value_or("localhost"),+ cfg.port.value_or(defaultPort(cfg.databaseType)),+ sshPw);+ effective.host = "127.0.0.1";+ effective.port = static_cast<int>(localPort);+ std::this_thread::sleep_for(std::chrono::milliseconds(100));+ }+ auto adapter = createAdapter(cfg.databaseType);+ adapter->connect(effective, pw);+ const auto ver = adapter->serverVersion();+ adapter->disconnect();+ const auto ms = static_cast<int>(+ std::chrono::duration_cast<std::chrono::milliseconds>(+ std::chrono::steady_clock::now() - start).count());+ dlg->showTestResult(true,+ tr("Connected! %1 (%2ms)")+ .arg(QString::fromUtf8(ver.c_str())).arg(ms));+ } catch (const std::exception& e) {+ dlg->showTestResult(false, QString::fromUtf8(e.what()));+ }+ });++ const int result = dialog.exec();+ if (result == ConnectionFormDialog::Cancelled) return;+ auto cfg = dialog.config();+ viewModel_->upsert(cfg);++ if (dialog.storeInKeychain()) {+ if (auto pw = dialog.password()) {+ try { secretStore_->savePassword(cfg.id, *pw); }+ catch (const std::exception& e) {+ statusBar()->showMessage(tr("DB credentials not saved: %1").arg(e.what()), 5000);+ }+ }+ if (auto sshPw = dialog.sshPassword(); sshPw && cfg.sshConfig) {+ try { secretStore_->saveSSHPassword(cfg.id, *sshPw); }+ catch (const std::exception& e) {+ statusBar()->showMessage(tr("SSH credentials not saved: %1").arg(e.what()), 5000);+ }+ }+ }+ statusBar()->showMessage(tr("Updated connection \"%1\"").arg(QString::fromUtf8(cfg.name.c_str())), 3000);+}++void MainWindow::onRemoveConnection(const QString& id) {+ const auto existing = viewModel_->find(id.toStdString());+ if (!existing) return;++ const auto btn = QMessageBox::question(+ this, tr("Delete connection"),+ tr("Delete connection \"%1\"? Stored credentials will also be removed.")+ .arg(QString::fromUtf8(existing->name.c_str())));+ if (btn != QMessageBox::Yes) return;++ try { secretStore_->removePassword(existing->id); } catch (...) {}+ viewModel_->remove(existing->id);+ statusBar()->showMessage(tr("Deleted"), 2000);+}++void MainWindow::onConnectionSelected(const QString& id) {+ const auto existing = viewModel_->find(id.toStdString());+ if (!existing) return;+ try {+ workspace_->open(*existing, std::nullopt, secretStore_.get());+ statusBar()->showMessage(+ tr("Connected to \"%1\"")+ .arg(QString::fromUtf8(existing->name.c_str())),+ 3000);+ } catch (const GridexError& e) {+ QMessageBox::critical(this, tr("Connection failed"),+ QString::fromUtf8(e.what()));+ } catch (const std::exception& e) {+ QMessageBox::critical(this, tr("Connection failed"),+ QString::fromUtf8(e.what()));+ } catch (...) {+ QMessageBox::critical(this, tr("Connection failed"),+ tr("Unknown error occurred during connection."));+ }+}++void MainWindow::onVmError(const QString& message) {+ statusBar()->showMessage(message, 6000);+}++void MainWindow::onOpenPreferences() {+ SettingsDialog dlg(secretStore_.get(), this);+ dlg.exec();+}++void MainWindow::onOpenMCPServer() {+ if (!mcpWindow_) {+ mcpWindow_ = new MCPWindow(mcpServer_.get(), repo_.get(), this);+ mcpWindow_->setAttribute(Qt::WA_DeleteOnClose);+ connect(mcpWindow_, &QObject::destroyed, this, [this] { mcpWindow_ = nullptr; });+ }+ mcpWindow_->show();+ mcpWindow_->raise();+ mcpWindow_->activateWindow();+}++void MainWindow::onShowAbout() {+ QMessageBox::about(this, tr("About Gridex"), tr(+ "<h2>Gridex</h2>"+ "<p><b>AI-Native Database IDE</b> (Linux build)</p>"+ "<p>Version 0.1 — 2026</p>"+ "<p>Connects to PostgreSQL, MySQL, SQLite, Redis, MongoDB, MSSQL with "+ "SSH tunnel support. Ships an AI chat assistant that speaks your "+ "schema.</p>"+ "<p>© 2026 Vurakit. MIT-licensed third-party components.</p>"));+}++void MainWindow::onShowShortcuts() {+ const QString html = tr(+ "<h3>Keyboard Shortcuts</h3>"+ "<table cellpadding='4' cellspacing='2'>"+ "<tr><th align='left'>Key</th><th align='left'>Action</th></tr>"+ "<tr><td><b>Ctrl+T</b></td><td>New Connection</td></tr>"+ "<tr><td><b>Ctrl+Shift+N</b></td><td>New Query Tab</td></tr>"+ "<tr><td><b>Ctrl+W</b></td><td>Close Tab</td></tr>"+ "<tr><td><b>Ctrl+Enter</b></td><td>Run Query</td></tr>"+ "<tr><td><b>Ctrl+Space</b></td><td>Autocomplete</td></tr>"+ "<tr><td><b>Ctrl+S</b></td><td>Commit pending changes</td></tr>"+ "<tr><td><b>Delete</b></td><td>Delete selected row(s)</td></tr>"+ "<tr><td><b>F5</b></td><td>Refresh table list</td></tr>"+ "<tr><td><b>Ctrl+,</b></td><td>Preferences</td></tr>"+ "<tr><td><b>Ctrl+/</b></td><td>This shortcut list</td></tr>"+ "<tr><td><b>Ctrl+Q</b></td><td>Quit</td></tr>"+ "</table>");+ QMessageBox box(this);+ box.setWindowTitle(tr("Keyboard Shortcuts"));+ box.setTextFormat(Qt::RichText);+ box.setText(html);+ box.setStandardButtons(QMessageBox::Ok);+ box.exec();+}++// ---- Backup / Restore (Home screen buttons) ----++namespace {++// Shows a picker over saved connections. Returns nullopt on cancel.+std::optional<ConnectionConfig> pickConnection(QWidget* parent,+ const std::vector<ConnectionConfig>& all,+ const QString& title) {+ if (all.empty()) {+ QMessageBox::information(parent, title,+ QObject::tr("No saved connections. Add one first."));+ return std::nullopt;+ }+ QStringList labels;+ labels.reserve(static_cast<int>(all.size()));+ for (const auto& c : all) {+ const QString name = QString::fromStdString(c.name);+ const QString host = QString::fromStdString(c.displayHost());+ labels << QString("%1 — %2").arg(name, host);+ }+ bool ok = false;+ const QString picked = QInputDialog::getItem(+ parent, title, QObject::tr("Select a connection:"),+ labels, 0, /*editable*/ false, &ok);+ if (!ok) return std::nullopt;+ const int idx = labels.indexOf(picked);+ if (idx < 0) return std::nullopt;+ return all[static_cast<std::size_t>(idx)];+}++} // namespace++void MainWindow::onBackupRequested() {+ const auto cfg = pickConnection(this, viewModel_->connections(), tr("Backup Database"));+ if (!cfg) return;++ if (!DatabaseDumpRunner::isSupported(cfg->databaseType)) {+ QMessageBox::warning(this, tr("Backup"),+ tr("Backup is not supported for this database type."));+ return;+ }++ QString defName = QString::fromStdString(cfg->database.value_or(cfg->name));+ if (defName.isEmpty()) defName = "backup";+ const QString path = QFileDialog::getSaveFileName(+ this, tr("Backup Database — %1").arg(QString::fromStdString(cfg->name)),+ QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)+ + "/" + defName + ".sql",+ tr("SQL Dump (*.sql);;All files (*)"));+ if (path.isEmpty()) return;++ std::optional<std::string> pw;+ if (secretStore_ && secretStore_->isAvailable()) pw = secretStore_->loadPassword(cfg->id);++ statusBar()->showMessage(tr("Backing up…"), 0);+ QApplication::processEvents();+ const auto r = DatabaseDumpRunner::backup(*cfg, pw, path.toStdString());+ statusBar()->clearMessage();++ if (!r.success) {+ QMessageBox::critical(this, tr("Backup Failed"),+ QString::fromStdString(r.errorOutput.empty()+ ? ("Exit code " + std::to_string(r.exitCode))+ : r.errorOutput));+ return;+ }+ QMessageBox::information(this, tr("Backup"),+ tr("Database dumped to:\n%1").arg(path));+}++void MainWindow::onRestoreRequested() {+ const auto cfg = pickConnection(this, viewModel_->connections(), tr("Restore Database"));+ if (!cfg) return;++ if (!DatabaseDumpRunner::isSupported(cfg->databaseType)) {+ QMessageBox::warning(this, tr("Restore"),+ tr("Restore is not supported for this database type."));+ return;+ }++ const QString path = QFileDialog::getOpenFileName(+ this, tr("Restore Database — %1").arg(QString::fromStdString(cfg->name)),+ QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation),+ tr("SQL Dump (*.sql);;All files (*)"));+ if (path.isEmpty()) return;++ const auto confirm = QMessageBox::warning(+ this, tr("Restore Database"),+ tr("This will execute SQL against \"%1\" from:\n%2\n\nExisting data may be overwritten. Continue?")+ .arg(QString::fromStdString(cfg->name), path),+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);+ if (confirm != QMessageBox::Yes) return;++ std::optional<std::string> pw;+ if (secretStore_ && secretStore_->isAvailable()) pw = secretStore_->loadPassword(cfg->id);++ statusBar()->showMessage(tr("Restoring…"), 0);+ QApplication::processEvents();+ const auto r = DatabaseDumpRunner::restore(*cfg, pw, path.toStdString());+ statusBar()->clearMessage();++ if (!r.success) {+ QMessageBox::critical(this, tr("Restore Failed"),+ QString::fromStdString(r.errorOutput.empty()+ ? ("Exit code " + std::to_string(r.exitCode))+ : r.errorOutput));+ return;+ }+ QMessageBox::information(this, tr("Restore"),+ tr("Database restored from:\n%1").arg(path));+}++void MainWindow::onExportConnections() {+ const auto& conns = viewModel_->connections();+ if (conns.empty()) {+ QMessageBox::information(this, tr("Export Connections"),+ tr("No connections to export."));+ return;+ }++ const QString path = QFileDialog::getSaveFileName(+ this, tr("Export Connections"),+ QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)+ + "/gridex-connections.json",+ tr("JSON (*.json)"));+ if (path.isEmpty()) return;++ QJsonArray arr;+ for (const auto& c : conns) {+ QJsonObject obj;+ obj[QStringLiteral("id")] = QString::fromStdString(c.id);+ obj[QStringLiteral("name")] = QString::fromStdString(c.name);+ obj[QStringLiteral("databaseType")] = QString::fromUtf8(rawValue(c.databaseType).data(),+ static_cast<qsizetype>(rawValue(c.databaseType).size()));+ obj[QStringLiteral("sslEnabled")] = c.sslEnabled;+ if (c.host) obj[QStringLiteral("host")] = QString::fromStdString(*c.host);+ if (c.port) obj[QStringLiteral("port")] = *c.port;+ if (c.database) obj[QStringLiteral("database")] = QString::fromStdString(*c.database);+ if (c.username) obj[QStringLiteral("username")] = QString::fromStdString(*c.username);+ if (c.group) obj[QStringLiteral("group")] = QString::fromStdString(*c.group);+ if (c.filePath) obj[QStringLiteral("filePath")] = QString::fromStdString(*c.filePath);+ obj[QStringLiteral("password")] = QStringLiteral("__RE_PROMPT__");+ if (c.sshConfig) {+ QJsonObject ssh;+ ssh[QStringLiteral("host")] = QString::fromStdString(c.sshConfig->host);+ ssh[QStringLiteral("port")] = c.sshConfig->port;+ ssh[QStringLiteral("username")] = QString::fromStdString(c.sshConfig->username);+ const auto am = rawValue(c.sshConfig->authMethod);+ ssh[QStringLiteral("authMethod")] = QString::fromUtf8(am.data(),+ static_cast<qsizetype>(am.size()));+ if (c.sshConfig->keyPath)+ ssh[QStringLiteral("keyPath")] = QString::fromStdString(*c.sshConfig->keyPath);+ ssh[QStringLiteral("sshPassword")] = QStringLiteral("__RE_PROMPT__");+ obj[QStringLiteral("sshConfig")] = ssh;+ }+ arr.append(obj);+ }++ QFile f(path);+ if (!f.open(QIODevice::WriteOnly | QIODevice::Text)) {+ QMessageBox::critical(this, tr("Export Failed"),+ tr("Cannot write to: %1").arg(path));+ return;+ }+ f.write(QJsonDocument(arr).toJson(QJsonDocument::Indented));+ f.close();+ statusBar()->showMessage(+ tr("Exported %1 connection(s) to %2").arg(conns.size()).arg(path), 4000);+}++void MainWindow::onImportConnections() {+ const QString path = QFileDialog::getOpenFileName(+ this, tr("Import Connections"),+ QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation),+ tr("JSON (*.json);;All files (*)"));+ if (path.isEmpty()) return;++ QFile f(path);+ if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) {+ QMessageBox::critical(this, tr("Import Failed"),+ tr("Cannot open: %1").arg(path));+ return;+ }+ const QByteArray raw = f.readAll();+ f.close();++ QJsonParseError err;+ const QJsonDocument doc = QJsonDocument::fromJson(raw, &err);+ if (err.error != QJsonParseError::NoError) {+ QMessageBox::critical(this, tr("Import Failed"),+ tr("Invalid JSON: %1").arg(err.errorString()));+ return;+ }+ if (!doc.isArray()) {+ QMessageBox::critical(this, tr("Import Failed"),+ tr("Expected a JSON array of connections."));+ return;+ }++ int imported = 0;+ QStringList errors;+ for (const auto& val : doc.array()) {+ if (!val.isObject()) continue;+ const QJsonObject obj = val.toObject();++ // Build a stripped JSON string for the existing decoder (no password fields)+ QJsonObject stripped = obj;+ stripped.remove(QStringLiteral("password"));+ stripped.remove(QStringLiteral("sshPassword"));+ if (stripped.contains(QStringLiteral("sshConfig"))) {+ QJsonObject ssh = stripped[QStringLiteral("sshConfig")].toObject();+ ssh.remove(QStringLiteral("sshPassword"));+ stripped[QStringLiteral("sshConfig")] = ssh;+ }++ try {+ const std::string cfgJson = QJsonDocument(stripped).toJson(QJsonDocument::Compact).toStdString();+ const ConnectionConfig cfg = json::decode(cfgJson);+ viewModel_->upsert(cfg);++ const QString pw = obj.value(QStringLiteral("password")).toString();+ if (pw == QStringLiteral("__RE_PROMPT__")) {+ bool ok = false;+ const QString entered = QInputDialog::getText(+ this,+ tr("Password for \"%1\"").arg(QString::fromStdString(cfg.name)),+ tr("Enter password (leave blank to skip):"),+ QLineEdit::Password, QString{}, &ok);+ if (ok && !entered.isEmpty() && secretStore_) {+ try { secretStore_->savePassword(cfg.id, entered.toStdString()); }+ catch (...) {}+ }+ }+ ++imported;+ } catch (const std::exception& e) {+ errors << QString::fromUtf8(e.what());+ }+ }++ if (errors.isEmpty()) {+ QMessageBox::information(this, tr("Import Connections"),+ tr("Imported %1 connection(s).").arg(imported));+ } else {+ QMessageBox::warning(this, tr("Import Connections"),+ tr("Imported %1 connection(s) with errors:\n\n%2")+ .arg(imported).arg(errors.join("\n")));+ }+}++}diff --git a/linux/src/Presentation/Windows/Main/MainWindow.h b/linux/src/Presentation/Windows/Main/MainWindow.hnew file mode 100644index 0000000..718cb85--- /dev/null+++ b/linux/src/Presentation/Windows/Main/MainWindow.h@@ -0,0 +1,78 @@+#pragma once++#include <QMainWindow>+#include <memory>++class QAction;+class QLabel;+class QStackedWidget;++namespace gridex {++class AppDatabase;+class AppConnectionRepository;+class ConnectionListViewModel;+class ConnectionSidebar;+class HomeBrandingPanel;+class MCPConnectionProvider;+class MCPWindow;+class SecretStore;+class WorkspaceState;+class WorkspaceView;+namespace mcp { class MCPServer; }++class MainWindow : public QMainWindow {+ Q_OBJECT++public:+ explicit MainWindow(QWidget* parent = nullptr);+ ~MainWindow() override;++private slots:+ void onAddConnection();+ void onEditConnection(const QString& id);+ void onRemoveConnection(const QString& id);+ void onConnectionSelected(const QString& id);+ void onNewQueryTab();+ void onDisconnect();+ void onVmError(const QString& message);+ void onBackupRequested();+ void onRestoreRequested();+ void onOpenPreferences();+ void onShowAbout();+ void onShowShortcuts();+ void onImportConnections();+ void onExportConnections();+ void onOpenMCPServer();++private:+ void setupMenuBar();+ void setupCentralLayout();+ void setupStatusBar();+ void wireBackend();+ void updateWorkspaceActions();++ // Backend (owned)+ std::shared_ptr<AppDatabase> appDb_;+ std::unique_ptr<AppConnectionRepository> repo_;+ std::unique_ptr<SecretStore> secretStore_;+ std::unique_ptr<ConnectionListViewModel> viewModel_;+ std::unique_ptr<WorkspaceState> workspace_;++ // MCP+ std::unique_ptr<MCPConnectionProvider> mcpProvider_;+ std::unique_ptr<mcp::MCPServer> mcpServer_;+ MCPWindow* mcpWindow_ = nullptr; // owned by Qt parent when shown++ // Menu actions that toggle enabled state with connection+ QAction* newQueryAction_ = nullptr;+ QAction* disconnectAction_ = nullptr;++ // UI (owned by Qt parent)+ QStackedWidget* stack_ = nullptr;+ HomeBrandingPanel* brandPanel_ = nullptr;+ ConnectionSidebar* connectionsPanel_ = nullptr;+ WorkspaceView* workspaceView_ = nullptr;+};++}diff --git a/linux/src/Services/AI/AIServiceFactory.cpp b/linux/src/Services/AI/AIServiceFactory.cppnew file mode 100644index 0000000..1f38b31--- /dev/null+++ b/linux/src/Services/AI/AIServiceFactory.cpp@@ -0,0 +1,34 @@+#include "Services/AI/AIServiceFactory.h"++#include <stdexcept>++#include "Services/AI/Providers/AnthropicProvider.h"+#include "Services/AI/Providers/GeminiProvider.h"+#include "Services/AI/Providers/OllamaProvider.h"+#include "Services/AI/Providers/OpenAIProvider.h"++namespace gridex {++std::unique_ptr<ILLMService>+AIServiceFactory::createAIService(const std::string& providerName,+ const std::string& apiKey,+ const std::string& baseUrl) {+ if (providerName == "Anthropic") {+ return std::make_unique<AnthropicProvider>(apiKey, baseUrl);+ }+ if (providerName == "OpenAI") {+ return std::make_unique<OpenAIProvider>(apiKey, baseUrl);+ }+ if (providerName == "Ollama") {+ // apiKey unused; Ollama is local.+ return baseUrl.empty()+ ? std::make_unique<OllamaProvider>()+ : std::make_unique<OllamaProvider>(baseUrl);+ }+ if (providerName == "Gemini") {+ return std::make_unique<GeminiProvider>(apiKey, baseUrl);+ }+ throw std::invalid_argument("AIServiceFactory: unknown provider '" + providerName + "'");+}++} // namespace gridexdiff --git a/linux/src/Services/AI/AIServiceFactory.h b/linux/src/Services/AI/AIServiceFactory.hnew file mode 100644index 0000000..b134486--- /dev/null+++ b/linux/src/Services/AI/AIServiceFactory.h@@ -0,0 +1,23 @@+#pragma once++#include <memory>+#include <string>++#include "Core/Protocols/AI/ILLMService.h"++namespace gridex {++// Creates the concrete ILLMService for a given provider name.+// providerName must be one of: "Anthropic", "OpenAI", "Ollama", "Gemini"+// apiKey is ignored for Ollama.+// baseUrl overrides the provider's default API endpoint (empty = default).+// Throws std::invalid_argument for unknown provider names.+class AIServiceFactory {+public:+ [[nodiscard]] static std::unique_ptr<ILLMService>+ createAIService(const std::string& providerName,+ const std::string& apiKey,+ const std::string& baseUrl = {});+};++} // namespace gridexdiff --git a/linux/src/Services/AI/Providers/AnthropicProvider.cpp b/linux/src/Services/AI/Providers/AnthropicProvider.cppnew file mode 100644index 0000000..a93dfe2--- /dev/null+++ b/linux/src/Services/AI/Providers/AnthropicProvider.cpp@@ -0,0 +1,158 @@+#include "Services/AI/Providers/AnthropicProvider.h"++#include <QEventLoop>+#include <QNetworkAccessManager>+#include <QNetworkReply>+#include <QNetworkRequest>+#include <QUrl>+#include <nlohmann/json.hpp>++#include "Core/Errors/GridexError.h"++namespace gridex {++namespace {++// Synchronous POST using Qt network stack + local event loop.+// Caller is expected to be on a non-GUI thread (QtConcurrent worker).+QByteArray qtPost(const QString& url,+ const QList<QPair<QString,QString>>& headers,+ const QByteArray& body) {+ QNetworkAccessManager nam;+ QNetworkRequest req{QUrl{url}};+ for (const auto& [k, v] : headers) {+ req.setRawHeader(k.toUtf8(), v.toUtf8());+ }++ QNetworkReply* reply = nam.post(req, body);++ QEventLoop loop;+ QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);+ loop.exec();++ if (reply->error() != QNetworkReply::NoError) {+ const std::string msg = reply->errorString().toStdString();+ reply->deleteLater();+ throw NetworkError("Network error: " + msg);+ }++ const int statusCode =+ reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();+ const QByteArray data = reply->readAll();+ reply->deleteLater();++ if (statusCode < 200 || statusCode >= 300) {+ throw GridexError(ErrorCategory::Network,+ "Anthropic HTTP " + std::to_string(statusCode) + ": "+ + data.left(200).toStdString());+ }+ return data;+}++QByteArray qtGet(const QString& url,+ const QList<QPair<QString,QString>>& headers) {+ QNetworkAccessManager nam;+ QNetworkRequest req{QUrl{url}};+ for (const auto& [k, v] : headers) req.setRawHeader(k.toUtf8(), v.toUtf8());++ QNetworkReply* reply = nam.get(req);+ QEventLoop loop;+ QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);+ loop.exec();++ if (reply->error() != QNetworkReply::NoError) {+ const std::string msg = reply->errorString().toStdString();+ reply->deleteLater();+ throw NetworkError("Network error: " + msg);+ }+ const int statusCode =+ reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();+ const QByteArray data = reply->readAll();+ reply->deleteLater();+ if (statusCode < 200 || statusCode >= 300) {+ throw GridexError(ErrorCategory::Network,+ "Anthropic HTTP " + std::to_string(statusCode) + ": "+ + data.left(200).toStdString());+ }+ return data;+}++} // namespace++AnthropicProvider::AnthropicProvider(std::string apiKey, std::string baseUrl)+ : apiKey_(std::move(apiKey)), baseUrl_(std::move(baseUrl)) {+ while (!baseUrl_.empty() && baseUrl_.back() == '/') baseUrl_.pop_back();+ if (baseUrl_.empty()) baseUrl_ = "https://api.anthropic.com";+}++std::string AnthropicProvider::sendMessage(+ const std::vector<LLMMessage>& messages,+ const std::string& systemPrompt,+ const std::string& model,+ int maxTokens,+ double temperature)+{+ using json = nlohmann::json;++ json body;+ body["model"] = model;+ body["max_tokens"] = maxTokens;+ body["temperature"] = temperature;+ if (!systemPrompt.empty()) body["system"] = systemPrompt;++ json msgs = json::array();+ for (const auto& m : messages) {+ msgs.push_back({+ {"role", LLMMessage::roleString(m.role)},+ {"content", m.content}+ });+ }+ body["messages"] = msgs;++ const QByteArray raw = qtPost(+ QString::fromStdString(baseUrl_ + "/v1/messages"),+ {+ {"Content-Type", "application/json"},+ {"x-api-key", QString::fromStdString(apiKey_)},+ {"anthropic-version", "2023-06-01"}+ },+ QByteArray::fromStdString(body.dump()));++ const auto resp = json::parse(raw.toStdString());+ if (resp.contains("content") && resp["content"].is_array()+ && !resp["content"].empty()) {+ const auto& first = resp["content"][0];+ if (first.contains("text")) return first["text"].get<std::string>();+ }+ throw GridexError(ErrorCategory::Internal,+ "Anthropic: unexpected response: " + raw.left(200).toStdString());+}++std::vector<LLMModel> AnthropicProvider::availableModels() {+ if (apiKey_.empty()) return {};+ try {+ const QByteArray raw = qtGet(+ QString::fromStdString(baseUrl_ + "/v1/models?limit=100"),+ {{"x-api-key", QString::fromStdString(apiKey_)},+ {"anthropic-version", QStringLiteral("2023-06-01")}});+ const auto j = nlohmann::json::parse(raw.toStdString());+ std::vector<LLMModel> out;+ if (j.contains("data") && j["data"].is_array()) {+ for (const auto& m : j["data"]) {+ const std::string id = m.value("id", std::string{});+ const std::string name = m.value("display_name", id);+ if (id.empty()) continue;+ out.push_back({id, name, "Anthropic", 200000, true});+ }+ }+ return out;+ } catch (...) {+ return {};+ }+}++bool AnthropicProvider::validateAPIKey() {+ return !apiKey_.empty();+}++} // namespace gridexdiff --git a/linux/src/Services/AI/Providers/AnthropicProvider.h b/linux/src/Services/AI/Providers/AnthropicProvider.hnew file mode 100644index 0000000..3bbb7b0--- /dev/null+++ b/linux/src/Services/AI/Providers/AnthropicProvider.h@@ -0,0 +1,35 @@+#pragma once++#include <string>+#include <vector>++#include "Core/Protocols/AI/ILLMService.h"++namespace gridex {++// Anthropic Claude provider.+// POST https://api.anthropic.com/v1/messages+// Auth: x-api-key header + anthropic-version: 2023-06-01+class AnthropicProvider : public ILLMService {+public:+ explicit AnthropicProvider(std::string apiKey, std::string baseUrl = {});++ [[nodiscard]] std::string providerName() const override { return "Anthropic"; }++ [[nodiscard]] std::string sendMessage(+ const std::vector<LLMMessage>& messages,+ const std::string& systemPrompt,+ const std::string& model,+ int maxTokens = 4096,+ double temperature = 0.7) override;++ [[nodiscard]] std::vector<LLMModel> availableModels() override;++ [[nodiscard]] bool validateAPIKey() override;++private:+ std::string apiKey_;+ std::string baseUrl_; // empty → default https://api.anthropic.com+};++} // namespace gridexdiff --git a/linux/src/Services/AI/Providers/GeminiProvider.cpp b/linux/src/Services/AI/Providers/GeminiProvider.cppnew file mode 100644index 0000000..367fe85--- /dev/null+++ b/linux/src/Services/AI/Providers/GeminiProvider.cpp@@ -0,0 +1,169 @@+#include "Services/AI/Providers/GeminiProvider.h"++#include <QEventLoop>+#include <QNetworkAccessManager>+#include <QNetworkReply>+#include <QNetworkRequest>+#include <QUrl>+#include <nlohmann/json.hpp>++#include "Core/Errors/GridexError.h"++namespace gridex {++namespace {++QByteArray qtPost(const QString& url,+ const QList<QPair<QString,QString>>& headers,+ const QByteArray& body) {+ QNetworkAccessManager nam;+ QNetworkRequest req{QUrl{url}};+ for (const auto& [k, v] : headers) req.setRawHeader(k.toUtf8(), v.toUtf8());++ QNetworkReply* reply = nam.post(req, body);+ QEventLoop loop;+ QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);+ loop.exec();++ if (reply->error() != QNetworkReply::NoError) {+ const std::string msg = reply->errorString().toStdString();+ reply->deleteLater();+ throw NetworkError("Network error: " + msg);+ }+ const int statusCode =+ reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();+ const QByteArray data = reply->readAll();+ reply->deleteLater();++ if (statusCode < 200 || statusCode >= 300) {+ throw GridexError(ErrorCategory::Network,+ "Gemini HTTP " + std::to_string(statusCode) + ": "+ + data.left(200).toStdString());+ }+ return data;+}++QByteArray qtGet(const QString& url) {+ QNetworkAccessManager nam;+ QNetworkRequest req{QUrl{url}};+ QNetworkReply* reply = nam.get(req);+ QEventLoop loop;+ QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);+ loop.exec();++ if (reply->error() != QNetworkReply::NoError) {+ const std::string msg = reply->errorString().toStdString();+ reply->deleteLater();+ throw NetworkError("Network error: " + msg);+ }+ const int statusCode =+ reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();+ const QByteArray data = reply->readAll();+ reply->deleteLater();+ if (statusCode < 200 || statusCode >= 300) {+ throw GridexError(ErrorCategory::Network,+ "Gemini HTTP " + std::to_string(statusCode) + ": "+ + data.left(200).toStdString());+ }+ return data;+}++} // namespace++GeminiProvider::GeminiProvider(std::string apiKey, std::string baseUrl)+ : apiKey_(std::move(apiKey)), baseUrl_(std::move(baseUrl)) {+ while (!baseUrl_.empty() && baseUrl_.back() == '/') baseUrl_.pop_back();+ if (baseUrl_.empty()) baseUrl_ = "https://generativelanguage.googleapis.com/v1beta";+}++std::string GeminiProvider::sendMessage(+ const std::vector<LLMMessage>& messages,+ const std::string& systemPrompt,+ const std::string& model,+ int maxTokens,+ double temperature)+{+ using json = nlohmann::json;++ // Gemini uses "user"/"model" roles, not "user"/"assistant".+ json contents = json::array();+ for (const auto& m : messages) {+ const std::string geminiRole =+ (m.role == LLMMessage::Role::Assistant) ? "model" : "user";+ contents.push_back({+ {"role", geminiRole},+ {"parts", json::array({{{"text", m.content}}})}+ });+ }++ json body;+ body["contents"] = contents;+ if (!systemPrompt.empty()) {+ body["systemInstruction"] = {+ {"parts", json::array({{{"text", systemPrompt}}})}+ };+ }+ body["generationConfig"] = {+ {"maxOutputTokens", maxTokens},+ {"temperature", temperature}+ };++ const QString url = QString::fromStdString(baseUrl_ + "/models/" + model)+ + ":generateContent?key="+ + QString::fromStdString(apiKey_);++ const QByteArray raw = qtPost(+ url,+ {{"Content-Type", "application/json"}},+ QByteArray::fromStdString(body.dump()));++ // {"candidates":[{"content":{"parts":[{"text":"..."}]}}]}+ const auto resp = json::parse(raw.toStdString());+ if (resp.contains("candidates") && resp["candidates"].is_array()+ && !resp["candidates"].empty()) {+ const auto& cand = resp["candidates"][0];+ if (cand.contains("content")+ && cand["content"].contains("parts")+ && cand["content"]["parts"].is_array()+ && !cand["content"]["parts"].empty()) {+ return cand["content"]["parts"][0]["text"].get<std::string>();+ }+ }+ throw GridexError(ErrorCategory::Internal,+ "Gemini: unexpected response: " + raw.left(200).toStdString());+}++std::vector<LLMModel> GeminiProvider::availableModels() {+ if (apiKey_.empty()) return {};+ try {+ const QString url = QString::fromStdString(baseUrl_ + "/models?key=")+ + QString::fromStdString(apiKey_);+ const QByteArray raw = qtGet(url);+ const auto j = nlohmann::json::parse(raw.toStdString());+ std::vector<LLMModel> out;+ if (j.contains("models") && j["models"].is_array()) {+ for (const auto& m : j["models"]) {+ // Only generateContent-capable models.+ bool supports = false;+ if (m.contains("supportedGenerationMethods")) {+ for (const auto& meth : m["supportedGenerationMethods"]) {+ if (meth.get<std::string>() == "generateContent") { supports = true; break; }+ }+ }+ if (!supports) continue;+ std::string name = m.value("name", std::string{});+ if (name.rfind("models/", 0) == 0) name = name.substr(7);+ if (name.empty()) continue;+ const std::string display = m.value("displayName", name);+ out.push_back({name, display, "Gemini", 1000000, true});+ }+ }+ return out;+ } catch (...) {+ return {};+ }+}++bool GeminiProvider::validateAPIKey() { return !apiKey_.empty(); }++} // namespace gridexdiff --git a/linux/src/Services/AI/Providers/GeminiProvider.h b/linux/src/Services/AI/Providers/GeminiProvider.hnew file mode 100644index 0000000..600e7d0--- /dev/null+++ b/linux/src/Services/AI/Providers/GeminiProvider.h@@ -0,0 +1,35 @@+#pragma once++#include <string>+#include <vector>++#include "Core/Protocols/AI/ILLMService.h"++namespace gridex {++// Google Gemini provider.+// POST https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key=<key>+// Uses native Gemini REST format (not the OpenAI-compatible endpoint).+class GeminiProvider : public ILLMService {+public:+ explicit GeminiProvider(std::string apiKey, std::string baseUrl = {});++ [[nodiscard]] std::string providerName() const override { return "Gemini"; }++ [[nodiscard]] std::string sendMessage(+ const std::vector<LLMMessage>& messages,+ const std::string& systemPrompt,+ const std::string& model,+ int maxTokens = 4096,+ double temperature = 0.7) override;++ [[nodiscard]] std::vector<LLMModel> availableModels() override;++ [[nodiscard]] bool validateAPIKey() override;++private:+ std::string apiKey_;+ std::string baseUrl_; // default: https://generativelanguage.googleapis.com/v1beta+};++} // namespace gridexdiff --git a/linux/src/Services/AI/Providers/OllamaProvider.cpp b/linux/src/Services/AI/Providers/OllamaProvider.cppnew file mode 100644index 0000000..898b71a--- /dev/null+++ b/linux/src/Services/AI/Providers/OllamaProvider.cpp@@ -0,0 +1,136 @@+#include "Services/AI/Providers/OllamaProvider.h"++#include <QEventLoop>+#include <QNetworkAccessManager>+#include <QNetworkReply>+#include <QNetworkRequest>+#include <QUrl>+#include <nlohmann/json.hpp>++#include "Core/Errors/GridexError.h"++namespace gridex {++namespace {++// Synchronous GET — returns body on HTTP 200, empty string otherwise.+// Throws NetworkError on transport failure.+QByteArray qtGet(const QString& url, int timeoutMs = 5000) {+ QNetworkAccessManager nam;+ QNetworkRequest req{QUrl{url}};++ QNetworkReply* reply = nam.get(req);+ QEventLoop loop;+ QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);+ loop.exec();++ if (reply->error() != QNetworkReply::NoError) {+ const std::string msg = reply->errorString().toStdString();+ reply->deleteLater();+ throw NetworkError("Network error: " + msg);+ }+ const int statusCode =+ reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();+ const QByteArray data = reply->readAll();+ reply->deleteLater();+ return (statusCode == 200) ? data : QByteArray{};+}++QByteArray qtPost(const QString& url,+ const QList<QPair<QString,QString>>& headers,+ const QByteArray& body) {+ QNetworkAccessManager nam;+ QNetworkRequest req{QUrl{url}};+ for (const auto& [k, v] : headers) req.setRawHeader(k.toUtf8(), v.toUtf8());++ QNetworkReply* reply = nam.post(req, body);+ QEventLoop loop;+ QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);+ loop.exec();++ if (reply->error() != QNetworkReply::NoError) {+ const std::string msg = reply->errorString().toStdString();+ reply->deleteLater();+ throw NetworkError("Network error: " + msg);+ }+ const int statusCode =+ reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();+ const QByteArray data = reply->readAll();+ reply->deleteLater();++ if (statusCode < 200 || statusCode >= 300) {+ throw GridexError(ErrorCategory::Network,+ "Ollama HTTP " + std::to_string(statusCode) + ": "+ + data.left(200).toStdString());+ }+ return data;+}++} // namespace++OllamaProvider::OllamaProvider(std::string baseUrl)+ : baseUrl_(std::move(baseUrl)) {+ while (!baseUrl_.empty() && baseUrl_.back() == '/') baseUrl_.pop_back();+}++std::string OllamaProvider::sendMessage(+ const std::vector<LLMMessage>& messages,+ const std::string& systemPrompt,+ const std::string& model,+ int /*maxTokens*/,+ double /*temperature*/)+{+ using json = nlohmann::json;++ json msgs = json::array();+ if (!systemPrompt.empty())+ msgs.push_back({{"role", "system"}, {"content", systemPrompt}});+ for (const auto& m : messages)+ msgs.push_back({{"role", LLMMessage::roleString(m.role)}, {"content", m.content}});++ json body;+ body["model"] = model;+ body["messages"] = msgs;+ body["stream"] = false;++ const QByteArray raw = qtPost(+ QString::fromStdString(baseUrl_ + "/api/chat"),+ {{"Content-Type", "application/json"}},+ QByteArray::fromStdString(body.dump()));++ const auto resp = json::parse(raw.toStdString());+ if (resp.contains("message") && resp["message"].contains("content"))+ return resp["message"]["content"].get<std::string>();++ throw GridexError(ErrorCategory::Internal,+ "Ollama: unexpected response: " + raw.left(200).toStdString());+}++std::vector<LLMModel> OllamaProvider::availableModels() {+ using json = nlohmann::json;+ try {+ const QByteArray raw = qtGet(QString::fromStdString(baseUrl_ + "/api/tags"));+ if (raw.isEmpty()) return {};+ const auto resp = json::parse(raw.toStdString());+ if (!resp.contains("models") || !resp["models"].is_array()) return {};+ std::vector<LLMModel> models;+ for (const auto& m : resp["models"]) {+ if (!m.contains("name")) continue;+ const std::string id = m["name"].get<std::string>();+ models.push_back({id, id, "Ollama", 128000, false});+ }+ return models;+ } catch (...) {+ return {};+ }+}++bool OllamaProvider::validateAPIKey() {+ try {+ return !qtGet(QString::fromStdString(baseUrl_ + "/api/tags")).isEmpty();+ } catch (...) {+ return false;+ }+}++} // namespace gridexdiff --git a/linux/src/Services/AI/Providers/OllamaProvider.h b/linux/src/Services/AI/Providers/OllamaProvider.hnew file mode 100644index 0000000..08b25c7--- /dev/null+++ b/linux/src/Services/AI/Providers/OllamaProvider.h@@ -0,0 +1,37 @@+#pragma once++#include <string>+#include <vector>++#include "Core/Protocols/AI/ILLMService.h"++namespace gridex {++// Local Ollama provider.+// POST http://localhost:11434/api/chat (stream:false)+// No auth required.+class OllamaProvider : public ILLMService {+public:+ // baseUrl defaults to http://localhost:11434+ explicit OllamaProvider(std::string baseUrl = "http://localhost:11434");++ [[nodiscard]] std::string providerName() const override { return "Ollama"; }++ [[nodiscard]] std::string sendMessage(+ const std::vector<LLMMessage>& messages,+ const std::string& systemPrompt,+ const std::string& model,+ int maxTokens = 4096,+ double temperature = 0.7) override;++ // Fetches installed models from GET /api/tags; returns empty list on error.+ [[nodiscard]] std::vector<LLMModel> availableModels() override;++ // Returns true when the Ollama daemon is reachable (GET /api/tags, HTTP 200).+ [[nodiscard]] bool validateAPIKey() override;++private:+ std::string baseUrl_;+};++} // namespace gridexdiff --git a/linux/src/Services/AI/Providers/OpenAIProvider.cpp b/linux/src/Services/AI/Providers/OpenAIProvider.cppnew file mode 100644index 0000000..86a6692--- /dev/null+++ b/linux/src/Services/AI/Providers/OpenAIProvider.cpp@@ -0,0 +1,147 @@+#include "Services/AI/Providers/OpenAIProvider.h"++#include <QEventLoop>+#include <QNetworkAccessManager>+#include <QNetworkReply>+#include <QNetworkRequest>+#include <QUrl>+#include <nlohmann/json.hpp>++#include "Core/Errors/GridexError.h"++namespace gridex {++namespace {++QByteArray qtPost(const QString& url,+ const QList<QPair<QString,QString>>& headers,+ const QByteArray& body) {+ QNetworkAccessManager nam;+ QNetworkRequest req{QUrl{url}};+ for (const auto& [k, v] : headers) req.setRawHeader(k.toUtf8(), v.toUtf8());++ QNetworkReply* reply = nam.post(req, body);+ QEventLoop loop;+ QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);+ loop.exec();++ if (reply->error() != QNetworkReply::NoError) {+ const std::string msg = reply->errorString().toStdString();+ reply->deleteLater();+ throw NetworkError("Network error: " + msg);+ }+ const int statusCode =+ reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();+ const QByteArray data = reply->readAll();+ reply->deleteLater();++ if (statusCode < 200 || statusCode >= 300) {+ throw GridexError(ErrorCategory::Network,+ "OpenAI HTTP " + std::to_string(statusCode) + ": "+ + data.left(200).toStdString());+ }+ return data;+}++QByteArray qtGet(const QString& url,+ const QList<QPair<QString,QString>>& headers) {+ QNetworkAccessManager nam;+ QNetworkRequest req{QUrl{url}};+ for (const auto& [k, v] : headers) req.setRawHeader(k.toUtf8(), v.toUtf8());++ QNetworkReply* reply = nam.get(req);+ QEventLoop loop;+ QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);+ loop.exec();++ if (reply->error() != QNetworkReply::NoError) {+ const std::string msg = reply->errorString().toStdString();+ reply->deleteLater();+ throw NetworkError("Network error: " + msg);+ }+ const int statusCode =+ reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();+ const QByteArray data = reply->readAll();+ reply->deleteLater();+ if (statusCode < 200 || statusCode >= 300) {+ throw GridexError(ErrorCategory::Network,+ "OpenAI HTTP " + std::to_string(statusCode) + ": "+ + data.left(200).toStdString());+ }+ return data;+}++} // namespace++OpenAIProvider::OpenAIProvider(std::string apiKey, std::string baseUrl)+ : apiKey_(std::move(apiKey)), baseUrl_(std::move(baseUrl)) {+ while (!baseUrl_.empty() && baseUrl_.back() == '/') baseUrl_.pop_back();+ if (baseUrl_.empty()) baseUrl_ = "https://api.openai.com/v1";+}++std::string OpenAIProvider::sendMessage(+ const std::vector<LLMMessage>& messages,+ const std::string& systemPrompt,+ const std::string& model,+ int maxTokens,+ double temperature)+{+ using json = nlohmann::json;++ json msgs = json::array();+ if (!systemPrompt.empty())+ msgs.push_back({{"role", "system"}, {"content", systemPrompt}});+ for (const auto& m : messages)+ msgs.push_back({{"role", LLMMessage::roleString(m.role)}, {"content", m.content}});++ json body;+ body["model"] = model;+ body["max_tokens"] = maxTokens;+ body["temperature"] = temperature;+ body["messages"] = msgs;++ const QByteArray raw = qtPost(+ QString::fromStdString(baseUrl_ + "/chat/completions"),+ {+ {"Content-Type", "application/json"},+ {"Authorization", "Bearer " + QString::fromStdString(apiKey_)}+ },+ QByteArray::fromStdString(body.dump()));++ const auto resp = json::parse(raw.toStdString());+ if (resp.contains("choices") && resp["choices"].is_array()+ && !resp["choices"].empty()) {+ const auto& first = resp["choices"][0];+ if (first.contains("message") && first["message"].contains("content"))+ return first["message"]["content"].get<std::string>();+ }+ throw GridexError(ErrorCategory::Internal,+ "OpenAI: unexpected response: " + raw.left(200).toStdString());+}++std::vector<LLMModel> OpenAIProvider::availableModels() {+ // Only live /models from the API — no hardcoded fallback. Empty result+ // signals the UI to show "enter API key" / "check key" state.+ if (apiKey_.empty()) return {};+ try {+ const QByteArray raw = qtGet(+ QString::fromStdString(baseUrl_ + "/models"),+ {{"Authorization", QString::fromStdString("Bearer " + apiKey_)}});+ const auto j = nlohmann::json::parse(raw.toStdString());+ std::vector<LLMModel> out;+ if (j.contains("data") && j["data"].is_array()) {+ for (const auto& m : j["data"]) {+ const std::string id = m.value("id", std::string{});+ if (id.empty()) continue;+ out.push_back({id, id, "OpenAI", 128000, true});+ }+ }+ return out;+ } catch (...) {+ return {};+ }+}++bool OpenAIProvider::validateAPIKey() { return !apiKey_.empty(); }++} // namespace gridexdiff --git a/linux/src/Services/AI/Providers/OpenAIProvider.h b/linux/src/Services/AI/Providers/OpenAIProvider.hnew file mode 100644index 0000000..d49511a--- /dev/null+++ b/linux/src/Services/AI/Providers/OpenAIProvider.h@@ -0,0 +1,35 @@+#pragma once++#include <string>+#include <vector>++#include "Core/Protocols/AI/ILLMService.h"++namespace gridex {++// OpenAI GPT provider.+// POST https://api.openai.com/v1/chat/completions+// Auth: Authorization: Bearer <key>+class OpenAIProvider : public ILLMService {+public:+ explicit OpenAIProvider(std::string apiKey, std::string baseUrl = {});++ [[nodiscard]] std::string providerName() const override { return "OpenAI"; }++ [[nodiscard]] std::string sendMessage(+ const std::vector<LLMMessage>& messages,+ const std::string& systemPrompt,+ const std::string& model,+ int maxTokens = 4096,+ double temperature = 0.7) override;++ [[nodiscard]] std::vector<LLMModel> availableModels() override;++ [[nodiscard]] bool validateAPIKey() override;++private:+ std::string apiKey_;+ std::string baseUrl_;+};++} // namespace gridexdiff --git a/linux/src/Services/CMakeLists.txt b/linux/src/Services/CMakeLists.txtnew file mode 100644index 0000000..142e25b--- /dev/null+++ b/linux/src/Services/CMakeLists.txt@@ -0,0 +1,57 @@+include(FetchContent)++find_package(PkgConfig REQUIRED)+pkg_check_modules(LIBSSH REQUIRED IMPORTED_TARGET libssh)++find_package(Qt6 6.4 REQUIRED COMPONENTS Network)++# nlohmann/json — header-only, fetched at configure time.+FetchContent_Declare(json+ URL https://github.com/nlohmann/json/releases/download/v3.11.3/json.tar.xz+ URL_HASH SHA256=d6c65aca6b1ed68e7a182f4757257b107ae403032760ed6ef121c9d55e81757d+)+FetchContent_MakeAvailable(json)++add_library(gridex-services STATIC+ SSH/SSHTunnelManager.cpp+ AI/AIServiceFactory.cpp+ AI/Providers/AnthropicProvider.cpp+ AI/Providers/OpenAIProvider.cpp+ AI/Providers/OllamaProvider.cpp+ AI/Providers/GeminiProvider.cpp+ Export/ExportService.cpp+ Export/DatabaseDumpRunner.cpp+ MCP/MCPServer.cpp+ MCP/Audit/AuditLogger.cpp+ MCP/Security/PermissionEngine.cpp+ MCP/Security/RateLimiter.cpp+ MCP/Security/ApprovalGate.cpp+ MCP/Security/RowCountEstimator.cpp+ MCP/Transport/StdioTransport.cpp+ MCP/Tools/ToolRegistry.cpp+ MCP/Tools/Tier1/ListConnectionsTool.cpp+ MCP/Tools/Tier1/ListTablesTool.cpp+ MCP/Tools/Tier1/DescribeTableTool.cpp+ MCP/Tools/Tier1/ListSchemasTool.cpp+ MCP/Tools/Tier1/GetSampleRowsTool.cpp+ MCP/Tools/Tier1/ListRelationshipsTool.cpp+ MCP/Tools/Tier2/QueryTool.cpp+ MCP/Tools/Tier2/ExplainQueryTool.cpp+ MCP/Tools/Tier2/SearchAcrossTablesTool.cpp+ MCP/Tools/Tier3/InsertRowsTool.cpp+ MCP/Tools/Tier3/UpdateRowsTool.cpp+ MCP/Tools/Tier3/DeleteRowsTool.cpp+ MCP/Tools/Tier3/ExecuteWriteQueryTool.cpp+)++target_include_directories(gridex-services PUBLIC+ ${CMAKE_CURRENT_SOURCE_DIR}/..+)++target_link_libraries(gridex-services+ PUBLIC gridex-core+ gridex-data+ Qt6::Network+ nlohmann_json::nlohmann_json+ PRIVATE PkgConfig::LIBSSH+)diff --git a/linux/src/Services/Export/DatabaseDumpRunner.cpp b/linux/src/Services/Export/DatabaseDumpRunner.cppnew file mode 100644index 0000000..44c5d5b--- /dev/null+++ b/linux/src/Services/Export/DatabaseDumpRunner.cpp@@ -0,0 +1,147 @@+#include "Services/Export/DatabaseDumpRunner.h"++#include <QProcess>+#include <QProcessEnvironment>+#include <QString>+#include <QStringList>++namespace gridex {++namespace {++struct DumpSpec {+ QString program;+ QStringList args;+ bool stdinRedirect = false; // Restore path: feed input file via stdin+ bool stdoutRedirect = false; // Backup path: capture stdout to output file+};++std::optional<DumpSpec> backupSpec(const ConnectionConfig& c, const QString& outPath) {+ DumpSpec s;+ switch (c.databaseType) {+ case DatabaseType::PostgreSQL:+ s.program = "pg_dump";+ s.args << "-h" << QString::fromStdString(c.host.value_or("localhost"))+ << "-p" << QString::number(c.port.value_or(5432))+ << "-U" << QString::fromStdString(c.username.value_or(""))+ << "-f" << outPath+ << QString::fromStdString(c.database.value_or(""));+ return s;+ case DatabaseType::MySQL:+ s.program = "mysqldump";+ s.args << "-h" << QString::fromStdString(c.host.value_or("localhost"))+ << "-P" << QString::number(c.port.value_or(3306))+ << "-u" << QString::fromStdString(c.username.value_or(""))+ << "--result-file=" + outPath+ << QString::fromStdString(c.database.value_or(""));+ return s;+ case DatabaseType::SQLite:+ s.program = "sqlite3";+ s.args << QString::fromStdString(c.filePath.value_or("")) << ".dump";+ s.stdoutRedirect = true;+ return s;+ default:+ return std::nullopt;+ }+}++std::optional<DumpSpec> restoreSpec(const ConnectionConfig& c, const QString& inPath) {+ DumpSpec s;+ switch (c.databaseType) {+ case DatabaseType::PostgreSQL:+ s.program = "psql";+ s.args << "-h" << QString::fromStdString(c.host.value_or("localhost"))+ << "-p" << QString::number(c.port.value_or(5432))+ << "-U" << QString::fromStdString(c.username.value_or(""))+ << "-d" << QString::fromStdString(c.database.value_or(""))+ << "-f" << inPath;+ return s;+ case DatabaseType::MySQL:+ s.program = "mysql";+ s.args << "-h" << QString::fromStdString(c.host.value_or("localhost"))+ << "-P" << QString::number(c.port.value_or(3306))+ << "-u" << QString::fromStdString(c.username.value_or(""))+ << QString::fromStdString(c.database.value_or(""));+ s.stdinRedirect = true;+ return s;+ case DatabaseType::SQLite:+ s.program = "sqlite3";+ s.args << QString::fromStdString(c.filePath.value_or(""));+ s.stdinRedirect = true;+ return s;+ default:+ return std::nullopt;+ }+}++DatabaseDumpRunner::Result runSpec(const DumpSpec& spec,+ const ConnectionConfig& cfg,+ const std::optional<std::string>& password,+ const QString& redirectPath) {+ DatabaseDumpRunner::Result r;+ r.tool = spec.program.toStdString();++ QProcessEnvironment env = QProcessEnvironment::systemEnvironment();+ if (password && !password->empty()) {+ if (cfg.databaseType == DatabaseType::PostgreSQL)+ env.insert("PGPASSWORD", QString::fromStdString(*password));+ else if (cfg.databaseType == DatabaseType::MySQL)+ env.insert("MYSQL_PWD", QString::fromStdString(*password));+ }++ QProcess proc;+ proc.setProcessEnvironment(env);+ if (spec.stdoutRedirect) {+ proc.setStandardOutputFile(redirectPath, QIODevice::Truncate);+ }+ if (spec.stdinRedirect) {+ proc.setStandardInputFile(redirectPath);+ }+ proc.start(spec.program, spec.args);+ if (!proc.waitForStarted(5000)) {+ r.errorOutput = "Could not start '" + r.tool ++ "'. Ensure it is installed and on PATH.";+ return r;+ }+ proc.waitForFinished(-1);+ r.exitCode = proc.exitCode();+ r.errorOutput = QString::fromUtf8(proc.readAllStandardError()).toStdString();+ r.success = (r.exitCode == 0);+ return r;+}++} // namespace++bool DatabaseDumpRunner::isSupported(DatabaseType dt) {+ return dt == DatabaseType::PostgreSQL+ || dt == DatabaseType::MySQL+ || dt == DatabaseType::SQLite;+}++DatabaseDumpRunner::Result DatabaseDumpRunner::backup(const ConnectionConfig& cfg,+ const std::optional<std::string>& password,+ const std::string& outPath) {+ const auto qOutPath = QString::fromStdString(outPath);+ const auto spec = backupSpec(cfg, qOutPath);+ if (!spec) {+ Result r;+ r.errorOutput = "Backup not supported for this database type.";+ return r;+ }+ return runSpec(*spec, cfg, password, qOutPath);+}++DatabaseDumpRunner::Result DatabaseDumpRunner::restore(const ConnectionConfig& cfg,+ const std::optional<std::string>& password,+ const std::string& inPath) {+ const auto qInPath = QString::fromStdString(inPath);+ const auto spec = restoreSpec(cfg, qInPath);+ if (!spec) {+ Result r;+ r.errorOutput = "Restore not supported for this database type.";+ return r;+ }+ return runSpec(*spec, cfg, password, qInPath);+}++} // namespace gridexdiff --git a/linux/src/Services/Export/DatabaseDumpRunner.h b/linux/src/Services/Export/DatabaseDumpRunner.hnew file mode 100644index 0000000..95b8844--- /dev/null+++ b/linux/src/Services/Export/DatabaseDumpRunner.h@@ -0,0 +1,39 @@+#pragma once++#include <optional>+#include <string>++#include "Core/Models/Database/ConnectionConfig.h"++namespace gridex {++// Blocking wrapper around pg_dump / mysqldump / sqlite3 (.dump) and their+// restore counterparts. Invoked from UI handlers; no threading here — the+// caller shows a modal spinner or accepts the freeze for now.+//+// Password is passed via environment variable (PGPASSWORD / MYSQL_PWD) so it+// never appears in `ps` output.+class DatabaseDumpRunner {+public:+ struct Result {+ bool success = false;+ int exitCode = 0;+ std::string errorOutput; // program's stderr when success=false+ std::string tool; // "pg_dump" / "mysqldump" / ...+ };++ // Backup: writes SQL dump to outPath. SQLite redirects sqlite3 stdout.+ [[nodiscard]] static Result backup(const ConnectionConfig& cfg,+ const std::optional<std::string>& password,+ const std::string& outPath);++ // Restore: reads inPath and pipes into psql/mysql/sqlite3.+ [[nodiscard]] static Result restore(const ConnectionConfig& cfg,+ const std::optional<std::string>& password,+ const std::string& inPath);++ // Returns true if the database type is supported by dump tooling.+ [[nodiscard]] static bool isSupported(DatabaseType dt);+};++} // namespace gridexdiff --git a/linux/src/Services/Export/ExportService.cpp b/linux/src/Services/Export/ExportService.cppnew file mode 100644index 0000000..876537b--- /dev/null+++ b/linux/src/Services/Export/ExportService.cpp@@ -0,0 +1,228 @@+#include "Services/Export/ExportService.h"++#include <fstream>+#include <stdexcept>+#include <string>++#include "Core/Models/Database/RowValue.h"+#include "Core/Models/Query/QueryResult.h"++namespace gridex {++namespace {++// RFC 4180: wrap field in double-quotes and escape inner double-quotes as "".+std::string csvEscape(const std::string& field) {+ bool needsQuoting = false;+ for (char c : field) {+ if (c == '"' || c == ',' || c == '\n' || c == '\r') {+ needsQuoting = true;+ break;+ }+ }+ if (!needsQuoting) return field;++ std::string out;+ out.reserve(field.size() + 2);+ out.push_back('"');+ for (char c : field) {+ if (c == '"') out.push_back('"'); // double the quote+ out.push_back(c);+ }+ out.push_back('"');+ return out;+}++// Minimal JSON string encoder: escapes control chars, backslash, double-quote.+std::string jsonEscapeString(const std::string& s) {+ std::string out;+ out.reserve(s.size() + 2);+ out.push_back('"');+ for (unsigned char c : s) {+ switch (c) {+ case '"': out += "\\\""; break;+ case '\\': out += "\\\\"; break;+ case '\n': out += "\\n"; break;+ case '\r': out += "\\r"; break;+ case '\t': out += "\\t"; break;+ default:+ if (c < 0x20) {+ // Unicode escape for other control characters+ char buf[8];+ std::snprintf(buf, sizeof(buf), "\\u%04x", c);+ out += buf;+ } else {+ out.push_back(static_cast<char>(c));+ }+ }+ }+ out.push_back('"');+ return out;+}++// SQL single-quote escape: double any single-quote inside the literal.+std::string sqlQuoteValue(const std::string& s) {+ std::string out;+ out.reserve(s.size() + 2);+ out.push_back('\'');+ for (char c : s) {+ if (c == '\'') out.push_back('\'');+ out.push_back(c);+ }+ out.push_back('\'');+ return out;+}++std::string rowValueToString(const RowValue& v) {+ if (v.isNull()) return "";+ if (const auto s = v.tryStringValue()) return *s;+ return "";+}++// Determine if a RowValue should be written as a bare number in SQL.+bool isNumericValue(const RowValue& v) {+ return v.isInteger() || v.isDouble();+}++bool isBoolValue(const RowValue& v) {+ return v.isBoolean();+}++void openFile(std::ofstream& f, const std::string& path) {+ f.open(path, std::ios::out | std::ios::trunc);+ if (!f.is_open()) {+ throw std::runtime_error("ExportService: cannot open file for writing: " + path);+ }+}++} // namespace++// ---------------------------------------------------------------------------+// CSV (RFC 4180)+// ---------------------------------------------------------------------------++void ExportService::exportToCsv(const QueryResult& result,+ const std::string& filePath) {+ std::ofstream f;+ openFile(f, filePath);++ // Header row+ for (std::size_t c = 0; c < result.columns.size(); ++c) {+ if (c > 0) f << ',';+ f << csvEscape(result.columns[c].name);+ }+ f << "\r\n";++ // Data rows+ for (const auto& row : result.rows) {+ for (std::size_t c = 0; c < result.columns.size(); ++c) {+ if (c > 0) f << ',';+ const std::string val = (c < row.size())+ ? rowValueToString(row[c]) : "";+ f << csvEscape(val);+ }+ f << "\r\n";+ }++ f.flush();+ if (f.fail()) {+ throw std::runtime_error("ExportService: write error on CSV file: " + filePath);+ }+}++// ---------------------------------------------------------------------------+// JSON — array of objects+// ---------------------------------------------------------------------------++void ExportService::exportToJson(const QueryResult& result,+ const std::string& filePath) {+ std::ofstream f;+ openFile(f, filePath);++ f << "[\n";+ for (std::size_t r = 0; r < result.rows.size(); ++r) {+ const auto& row = result.rows[r];+ f << " {";+ for (std::size_t c = 0; c < result.columns.size(); ++c) {+ if (c > 0) f << ", ";+ f << jsonEscapeString(result.columns[c].name) << ": ";++ if (c >= row.size() || row[c].isNull()) {+ f << "null";+ } else if (isNumericValue(row[c])) {+ f << rowValueToString(row[c]);+ } else if (isBoolValue(row[c])) {+ f << (row[c].asBoolean() ? "true" : "false");+ } else {+ // Raw JSON values are emitted without extra quoting.+ if (row[c].isJson()) {+ f << row[c].asJson();+ } else {+ f << jsonEscapeString(rowValueToString(row[c]));+ }+ }+ }+ f << "}";+ if (r + 1 < result.rows.size()) f << ",";+ f << "\n";+ }+ f << "]\n";++ f.flush();+ if (f.fail()) {+ throw std::runtime_error("ExportService: write error on JSON file: " + filePath);+ }+}++// ---------------------------------------------------------------------------+// SQL — INSERT INTO tableName (col1, col2, ...) VALUES (...), (...);+// ---------------------------------------------------------------------------++void ExportService::exportToSql(const QueryResult& result,+ const std::string& tableName,+ const std::string& filePath) {+ if (result.rows.empty()) {+ // Write an empty file — no rows to export.+ std::ofstream f;+ openFile(f, filePath);+ return;+ }++ std::ofstream f;+ openFile(f, filePath);++ // Build column list once+ std::string colList;+ for (std::size_t c = 0; c < result.columns.size(); ++c) {+ if (c > 0) colList += ", ";+ colList += result.columns[c].name;+ }++ // Emit one INSERT per row (portable; avoids multi-row INSERT size limits).+ const std::string prefix =+ "INSERT INTO " + tableName + " (" + colList + ") VALUES (";++ for (const auto& row : result.rows) {+ f << prefix;+ for (std::size_t c = 0; c < result.columns.size(); ++c) {+ if (c > 0) f << ", ";+ if (c >= row.size() || row[c].isNull()) {+ f << "NULL";+ } else if (isNumericValue(row[c])) {+ f << rowValueToString(row[c]);+ } else if (isBoolValue(row[c])) {+ f << (row[c].asBoolean() ? "1" : "0");+ } else {+ f << sqlQuoteValue(rowValueToString(row[c]));+ }+ }+ f << ");\n";+ }++ f.flush();+ if (f.fail()) {+ throw std::runtime_error("ExportService: write error on SQL file: " + filePath);+ }+}++} // namespace gridexdiff --git a/linux/src/Services/Export/ExportService.h b/linux/src/Services/Export/ExportService.hnew file mode 100644index 0000000..f8f401f--- /dev/null+++ b/linux/src/Services/Export/ExportService.h@@ -0,0 +1,26 @@+#pragma once++#include <string>++#include "Core/Models/Query/QueryResult.h"++namespace gridex {++// Static export helpers: CSV (RFC 4180), JSON array-of-objects, SQL INSERT.+// All methods throw std::runtime_error on I/O failure.+class ExportService {+public:+ ExportService() = delete;++ static void exportToCsv(const QueryResult& result,+ const std::string& filePath);++ static void exportToJson(const QueryResult& result,+ const std::string& filePath);++ static void exportToSql(const QueryResult& result,+ const std::string& tableName,+ const std::string& filePath);+};++}diff --git a/linux/src/Services/MCP/Audit/AuditLogger.cpp b/linux/src/Services/MCP/Audit/AuditLogger.cppnew file mode 100644index 0000000..f8f8b67--- /dev/null+++ b/linux/src/Services/MCP/Audit/AuditLogger.cpp@@ -0,0 +1,161 @@+#include "Services/MCP/Audit/AuditLogger.h"++#include <algorithm>+#include <chrono>+#include <cstdio>+#include <cstdlib>+#include <ctime>+#include <filesystem>+#include <fstream>+#include <iostream>+#include <sstream>++namespace gridex::mcp {++namespace fs = std::filesystem;++namespace {++std::string xdgDataHome() {+ if (const char* x = std::getenv("XDG_DATA_HOME"); x && *x) return x;+ if (const char* h = std::getenv("HOME"); h && *h) return std::string(h) + "/.local/share";+ return ".";+}++std::string isoTimestamp(std::chrono::system_clock::time_point tp, bool fileSafe = false) {+ std::time_t t = std::chrono::system_clock::to_time_t(tp);+ std::tm tm{};+ gmtime_r(&t, &tm);+ char buf[32];+ if (fileSafe) {+ std::strftime(buf, sizeof(buf), "%Y-%m-%dT%H-%M-%SZ", &tm);+ } else {+ std::strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%SZ", &tm);+ }+ return buf;+}++} // namespace++AuditLogger::AuditLogger() {+ fs::path dir = fs::path(xdgDataHome()) / "gridex";+ std::error_code ec;+ fs::create_directories(dir, ec);+ filePath_ = (dir / "mcp-audit.jsonl").string();+}++AuditLogger::~AuditLogger() { close(); }++void AuditLogger::ensureOpen() {+ if (out_.is_open()) return;+ out_.open(filePath_, std::ios::app);+}++void AuditLogger::rotateIfNeeded() {+ std::error_code ec;+ if (!fs::exists(filePath_, ec)) return;+ auto size = fs::file_size(filePath_, ec);+ if (ec || static_cast<std::int64_t>(size) < maxFileSize_) return;++ if (out_.is_open()) out_.close();++ std::string stamp = isoTimestamp(std::chrono::system_clock::now(), true);+ fs::path src(filePath_);+ fs::path dst = src.parent_path() / ("mcp-audit-" + stamp + ".jsonl");+ fs::rename(src, dst, ec);+}++void AuditLogger::log(const MCPAuditEntry& entry) {+ std::lock_guard lk(mu_);+ try {+ rotateIfNeeded();+ ensureOpen();+ if (!out_.is_open()) return;+ out_ << entry.toJson().dump() << '\n';+ out_.flush();+ } catch (const std::exception& e) {+ std::cerr << "[MCP Audit] Failed to log entry: " << e.what() << '\n';+ }+}++std::vector<MCPAuditEntry> AuditLogger::recentEntries(int limit) const {+ std::lock_guard lk(mu_);+ std::vector<MCPAuditEntry> out;+ std::ifstream in(filePath_);+ if (!in) return out;+ std::vector<std::string> lines;+ std::string line;+ while (std::getline(in, line)) {+ if (!line.empty()) lines.push_back(std::move(line));+ }+ int start = std::max<int>(0, static_cast<int>(lines.size()) - limit);+ for (int i = static_cast<int>(lines.size()) - 1; i >= start; --i) {+ try {+ auto j = nlohmann::json::parse(lines[i]);+ if (auto e = MCPAuditEntry::fromJson(j)) out.push_back(*e);+ } catch (...) {}+ }+ return out;+}++void AuditLogger::clearAll() {+ std::lock_guard lk(mu_);+ if (out_.is_open()) out_.close();+ std::error_code ec;+ fs::remove(filePath_, ec);+}++void AuditLogger::close() {+ std::lock_guard lk(mu_);+ if (out_.is_open()) out_.close();+}++// MCPAuditEntry::fromJson definition — placed here to avoid header bloat.+std::optional<MCPAuditEntry> MCPAuditEntry::fromJson(const nlohmann::json& j) {+ try {+ MCPAuditEntry e;+ e.timestampIso8601 = j.value("timestamp", "");+ e.eventId = j.value("eventId", "");+ e.tool = j.value("tool", "");+ e.tier = j.value("tier", 1);+ if (j.contains("connectionId")) e.connectionId = j["connectionId"].get<std::string>();+ if (j.contains("connectionType")) e.connectionType = j["connectionType"].get<std::string>();+ if (j.contains("error")) e.error = j["error"].get<std::string>();+ if (j.contains("client")) {+ e.client.name = j["client"].value("name", "unknown");+ e.client.version = j["client"].value("version", "0.0.0");+ e.client.transport = j["client"].value("transport", "stdio");+ }+ if (j.contains("input")) {+ const auto& i = j["input"];+ if (i.contains("sqlPreview")) e.input.sqlPreview = i["sqlPreview"].get<std::string>();+ if (i.contains("paramsCount")) e.input.paramsCount = i["paramsCount"].get<int>();+ if (i.contains("inputHash")) e.input.inputHash = i["inputHash"].get<std::string>();+ }+ if (j.contains("result")) {+ const auto& r = j["result"];+ std::string s = r.value("status", "success");+ e.result.status = (s == "success") ? MCPAuditStatus::Success+ : (s == "denied") ? MCPAuditStatus::Denied+ : (s == "timeout") ? MCPAuditStatus::Timeout+ : MCPAuditStatus::Error;+ e.result.durationMs = r.value("durationMs", 0);+ if (r.contains("rowsAffected")) e.result.rowsAffected = r["rowsAffected"].get<int>();+ if (r.contains("rowsReturned")) e.result.rowsReturned = r["rowsReturned"].get<int>();+ if (r.contains("bytesReturned")) e.result.bytesReturned = r["bytesReturned"].get<int>();+ }+ if (j.contains("security")) {+ const auto& s = j["security"];+ std::string modeStr = s.value("permissionMode", "locked");+ if (auto m = mcpConnectionModeFromRaw(modeStr)) e.security.mode = *m;+ if (s.contains("userApproved")) e.security.userApproved = s["userApproved"].get<bool>();+ if (s.contains("approvalSessionId")) e.security.approvalSessionId = s["approvalSessionId"].get<std::string>();+ if (s.contains("scopesApplied")) e.security.scopesApplied = s["scopesApplied"].get<std::vector<std::string>>();+ }+ return e;+ } catch (...) {+ return std::nullopt;+ }+}++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/Audit/AuditLogger.h b/linux/src/Services/MCP/Audit/AuditLogger.hnew file mode 100644index 0000000..ef00ef0--- /dev/null+++ b/linux/src/Services/MCP/Audit/AuditLogger.h@@ -0,0 +1,41 @@+#pragma once++#include <cstdint>+#include <fstream>+#include <mutex>+#include <string>+#include <vector>++#include "Services/MCP/Protocol.h"++namespace gridex::mcp {++// Async audit logger for MCP tool invocations. Writes JSONL to+// $XDG_DATA_HOME/gridex/mcp-audit.jsonl (defaults to ~/.local/share/gridex/...).+// Rotates when file size exceeds maxFileSize (default 100 MB).+class AuditLogger {+public:+ AuditLogger();+ ~AuditLogger();++ void log(const MCPAuditEntry& entry);++ std::vector<MCPAuditEntry> recentEntries(int limit = 100) const;+ void clearAll();+ void close();++ std::string logFilePath() const { return filePath_; }++ void setMaxFileSize(std::int64_t bytes) { maxFileSize_ = bytes; }++private:+ void rotateIfNeeded();+ void ensureOpen();++ mutable std::mutex mu_;+ std::string filePath_;+ std::ofstream out_;+ std::int64_t maxFileSize_ = 100LL * 1024 * 1024;+};++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/MCPServer.cpp b/linux/src/Services/MCP/MCPServer.cppnew file mode 100644index 0000000..51e7fc4--- /dev/null+++ b/linux/src/Services/MCP/MCPServer.cpp@@ -0,0 +1,226 @@+#include "Services/MCP/MCPServer.h"++#include <chrono>+#include <random>+#include <regex>+#include <sstream>++namespace gridex::mcp {++namespace {++std::string newUuid() {+ static thread_local std::mt19937_64 rng{std::random_device{}()};+ std::uniform_int_distribution<uint64_t> dist;+ uint64_t a = dist(rng), b = dist(rng);+ char buf[40];+ std::snprintf(buf, sizeof(buf),+ "%08x-%04x-%04x-%04x-%012llx",+ static_cast<uint32_t>(a >> 32),+ static_cast<uint16_t>(a >> 16) & 0xFFFF,+ (static_cast<uint16_t>(a) & 0x0FFF) | 0x4000,+ (static_cast<uint16_t>(b >> 48) & 0x3FFF) | 0x8000,+ static_cast<unsigned long long>(b & 0xFFFFFFFFFFFFULL));+ return buf;+}++std::string nowIso8601() {+ auto now = std::chrono::system_clock::now();+ std::time_t t = std::chrono::system_clock::to_time_t(now);+ std::tm tm{};+ gmtime_r(&t, &tm);+ char buf[32];+ std::strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%SZ", &tm);+ return buf;+}++} // namespace++MCPServer::MCPServer(std::shared_ptr<IMCPConnectionProvider> provider,+ std::string serverVersion,+ MCPTransportMode mode)+ : connectionProvider_(std::move(provider)),+ serverVersion_(std::move(serverVersion)),+ mode_(mode),+ toolRegistry_(std::make_unique<ToolRegistry>()),+ permissionEngine_(std::make_unique<PermissionEngine>()),+ auditLogger_(std::make_unique<AuditLogger>()),+ rateLimiter_(std::make_unique<RateLimiter>()),+ approvalGate_(std::make_unique<ApprovalGate>()) {+ toolRegistry_->registerBuiltins();+ if (mode_ == MCPTransportMode::Stdio) {+ transport_ = std::make_unique<StdioTransport>();+ }+}++MCPServer::~MCPServer() { stop(); }++void MCPServer::start() {+ bool expected = false;+ if (!running_.compare_exchange_strong(expected, true)) return;+ startTime_ = std::chrono::system_clock::now();+ if (transport_) {+ transport_->setHandler([this](const JSONRPCRequest& req) {+ auto resp = handleRequest(req);+ transport_->send(resp);+ });+ transport_->start();+ }+}++void MCPServer::stop() {+ if (!running_.exchange(false)) return;+ if (transport_) transport_->stop();+ auditLogger_->close();+}++void MCPServer::setConnectionMode(const std::string& id, MCPConnectionMode mode) {+ permissionEngine_->setMode(id, mode);+}++MCPConnectionMode MCPServer::getConnectionMode(const std::string& id) const {+ return permissionEngine_->getMode(id);+}++JSONRPCResponse MCPServer::handleRequest(const JSONRPCRequest& req) {+ if (req.method == "initialize") return handleInitialize(req);+ if (req.method == "initialized") return JSONRPCResponse::ok(req.id, nullptr); // notification+ if (req.method == "tools/list") return handleToolsList(req);+ if (req.method == "tools/call") return handleToolCall(req);+ if (req.method == "ping") return JSONRPCResponse::ok(req.id, json{{"pong", true}});+ if (req.method == "shutdown") {+ auto r = JSONRPCResponse::ok(req.id, nullptr);+ stop();+ return r;+ }+ return JSONRPCResponse::err(req.id, JSONRPCError::methodNotFound());+}++JSONRPCResponse MCPServer::handleInitialize(const JSONRPCRequest& req) {+ if (req.params.is_object() && req.params.contains("clientInfo")) {+ const auto& ci = req.params["clientInfo"];+ std::lock_guard lk(stateMu_);+ clientInfo_.name = ci.value("name", "unknown");+ clientInfo_.version = ci.value("version", "0.0.0");+ }+ json result = {+ {"serverInfo", {{"name", "gridex"}, {"version", serverVersion_}}},+ {"protocolVersion", "2024-11-05"},+ {"capabilities", {+ {"tools", {{"listChanged", true}}},+ {"resources", {{"subscribe", true}, {"listChanged", true}}},+ {"prompts", {{"listChanged", true}}},+ {"logging", json::object()},+ }},+ };+ return JSONRPCResponse::ok(req.id, result);+}++JSONRPCResponse MCPServer::handleToolsList(const JSONRPCRequest& req) {+ json arr = json::array();+ for (const auto& def : toolRegistry_->definitions()) arr.push_back(def.toJson());+ return JSONRPCResponse::ok(req.id, json{{"tools", arr}});+}++JSONRPCResponse MCPServer::handleToolCall(const JSONRPCRequest& req) {+ if (!req.params.is_object() || !req.params.contains("name") || !req.params["name"].is_string()) {+ return JSONRPCResponse::err(req.id, JSONRPCError::invalidParams());+ }+ const std::string toolName = req.params["name"].get<std::string>();+ json args = req.params.value("arguments", json::object());++ auto tool = toolRegistry_->get(toolName);+ if (!tool) {+ JSONRPCError e{static_cast<int>(MCPErrorCode::NotFound),+ "Tool '" + toolName + "' not found", std::nullopt};+ return JSONRPCResponse::err(req.id, e);+ }++ auto start = std::chrono::steady_clock::now();++ MCPClientInfo info;+ {+ std::lock_guard lk(stateMu_);+ info = clientInfo_;+ }+ MCPAuditClient clientAudit;+ clientAudit.name = info.name;+ clientAudit.version = info.version;+ clientAudit.transport = (mode_ == MCPTransportMode::Stdio) ? "stdio" : "in-process";++ std::optional<std::string> connIdOpt;+ std::optional<std::string> connTypeOpt;+ if (args.contains("connection_id") && args["connection_id"].is_string()) {+ std::string id = args["connection_id"].get<std::string>();+ connIdOpt = id;+ try {+ if (connectionProvider_ && connectionProvider_->hasConnection(id)) {+ for (const auto& c : connectionProvider_->listConnections()) {+ if (c.id == id) { connTypeOpt = std::string(rawValue(c.databaseType)); break; }+ }+ }+ } catch (...) {}+ }++ MCPToolContext ctx;+ ctx.connectionProvider = connectionProvider_.get();+ ctx.permissionEngine = permissionEngine_.get();+ ctx.auditLogger = auditLogger_.get();+ ctx.rateLimiter = rateLimiter_.get();+ ctx.approvalGate = approvalGate_.get();+ ctx.client = clientAudit;++ auto buildAudit = [&](MCPAuditStatus status, int durationMs, const std::optional<std::string>& err) {+ MCPAuditEntry e;+ e.timestampIso8601 = nowIso8601();+ e.eventId = newUuid();+ e.client = clientAudit;+ e.tool = toolName;+ e.tier = tierRawValue(tool->tier());+ e.connectionId = connIdOpt;+ e.connectionType = connTypeOpt;+ std::optional<std::string> sqlOpt;+ std::optional<int> paramsCountOpt;+ if (args.contains("sql") && args["sql"].is_string()) sqlOpt = args["sql"].get<std::string>();+ if (args.contains("params") && args["params"].is_array()) paramsCountOpt = static_cast<int>(args["params"].size());+ e.input = MCPAuditInput::fromSql(sqlOpt, paramsCountOpt);+ e.result = {status, std::nullopt, std::nullopt, durationMs, std::nullopt};+ e.security.mode = connIdOpt ? permissionEngine_->getMode(*connIdOpt) : MCPConnectionMode::Locked;+ e.error = err;+ return e;+ };++ try {+ auto toolResult = tool->execute(args, ctx);+ int durationMs = static_cast<int>(+ std::chrono::duration_cast<std::chrono::milliseconds>(+ std::chrono::steady_clock::now() - start).count());+ auditLogger_->log(buildAudit(+ toolResult.isError ? MCPAuditStatus::Error : MCPAuditStatus::Success,+ durationMs, std::nullopt));+ return JSONRPCResponse::ok(req.id, toolResult.toJson());+ } catch (const std::exception& e) {+ int durationMs = static_cast<int>(+ std::chrono::duration_cast<std::chrono::milliseconds>(+ std::chrono::steady_clock::now() - start).count());+ std::string msg = sanitizeError(e.what());+ auditLogger_->log(buildAudit(MCPAuditStatus::Error, durationMs, msg));+ return JSONRPCResponse::ok(req.id, MCPToolResult::errorResult(msg).toJson());+ }+}++std::string MCPServer::sanitizeError(const std::string& msg) {+ static const std::regex kHome(R"(/home/[^/\s]+)");+ static const std::regex kUsers(R"(/Users/[^/\s]+)");+ static const std::regex kPg(R"(postgres://[^\s]+)");+ static const std::regex kMy(R"(mysql://[^\s]+)");+ static const std::regex kMongo(R"(mongodb://[^\s]+)");+ std::string out = std::regex_replace(msg, kHome, "[path]");+ out = std::regex_replace(out, kUsers, "[path]");+ out = std::regex_replace(out, kPg, "[connection]");+ out = std::regex_replace(out, kMy, "[connection]");+ out = std::regex_replace(out, kMongo, "[connection]");+ return out;+}++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/MCPServer.h b/linux/src/Services/MCP/MCPServer.hnew file mode 100644index 0000000..8d6ccbd--- /dev/null+++ b/linux/src/Services/MCP/MCPServer.h@@ -0,0 +1,81 @@+#pragma once++#include <atomic>+#include <chrono>+#include <memory>+#include <mutex>+#include <string>++#include "Services/MCP/Audit/AuditLogger.h"+#include "Services/MCP/Protocol.h"+#include "Services/MCP/Security/ApprovalGate.h"+#include "Services/MCP/Security/PermissionEngine.h"+#include "Services/MCP/Security/RateLimiter.h"+#include "Services/MCP/Tools/MCPTool.h"+#include "Services/MCP/Tools/ToolRegistry.h"+#include "Services/MCP/Transport/StdioTransport.h"++namespace gridex::mcp {++enum class MCPTransportMode {+ Stdio, // CLI mode — read stdin, write stdout+ HttpOnly, // GUI mode — HTTP only (not yet implemented)+ InProcess, // GUI mode — no transport; used for exposing state to MCP window+};++// Central MCP server. Holds registries (tools, security, audit) and routes+// JSON-RPC requests from whichever transport is configured.+class MCPServer {+public:+ MCPServer(std::shared_ptr<IMCPConnectionProvider> connectionProvider,+ std::string serverVersion = "1.0.0",+ MCPTransportMode mode = MCPTransportMode::InProcess);+ ~MCPServer();++ void start();+ void stop();+ bool isRunning() const noexcept { return running_.load(); }+ std::chrono::system_clock::time_point startTime() const noexcept { return startTime_; }++ // Accessors for UI layer.+ PermissionEngine& permissionEngine() noexcept { return *permissionEngine_; }+ RateLimiter& rateLimiter() noexcept { return *rateLimiter_; }+ ApprovalGate& approvalGate() noexcept { return *approvalGate_; }+ AuditLogger& auditLogger() noexcept { return *auditLogger_; }+ ToolRegistry& toolRegistry() noexcept { return *toolRegistry_; }+ IMCPConnectionProvider& connectionProvider() noexcept { return *connectionProvider_; }++ // Per-connection mode.+ void setConnectionMode(const std::string& id, MCPConnectionMode mode);+ MCPConnectionMode getConnectionMode(const std::string& id) const;++ const MCPClientInfo& clientInfo() const noexcept { return clientInfo_; }++ // Manual request routing — for HTTP transport or in-process tests.+ JSONRPCResponse handleRequest(const JSONRPCRequest& request);++private:+ JSONRPCResponse handleInitialize(const JSONRPCRequest&);+ JSONRPCResponse handleToolsList(const JSONRPCRequest&);+ JSONRPCResponse handleToolCall(const JSONRPCRequest&);++ static std::string sanitizeError(const std::string& msg);++ std::shared_ptr<IMCPConnectionProvider> connectionProvider_;+ std::string serverVersion_;+ MCPTransportMode mode_;++ std::unique_ptr<StdioTransport> transport_;+ std::unique_ptr<ToolRegistry> toolRegistry_;+ std::unique_ptr<PermissionEngine> permissionEngine_;+ std::unique_ptr<AuditLogger> auditLogger_;+ std::unique_ptr<RateLimiter> rateLimiter_;+ std::unique_ptr<ApprovalGate> approvalGate_;++ std::atomic<bool> running_{false};+ std::chrono::system_clock::time_point startTime_{};+ mutable std::mutex stateMu_;+ MCPClientInfo clientInfo_;+};++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/Protocol.h b/linux/src/Services/MCP/Protocol.hnew file mode 100644index 0000000..1f1168f--- /dev/null+++ b/linux/src/Services/MCP/Protocol.h@@ -0,0 +1,311 @@+#pragma once++// MCP (Model Context Protocol) JSON-RPC 2.0 types + audit entry.+// Uses nlohmann::json for dynamic JSON (replaces Swift's hand-rolled JSONValue enum).++#include <chrono>+#include <optional>+#include <stdexcept>+#include <string>+#include <vector>++#include <nlohmann/json.hpp>++#include "Core/Enums/DatabaseType.h"+#include "Core/Enums/MCPConnectionMode.h"+#include "Core/Enums/MCPPermissionTier.h"++namespace gridex::mcp {++using nlohmann::json;++// JSON-RPC 2.0 error codes+struct JSONRPCError {+ int code = 0;+ std::string message;+ std::optional<json> data;++ json toJson() const {+ json j = {{"code", code}, {"message", message}};+ if (data) j["data"] = *data;+ return j;+ }++ static JSONRPCError parseError() { return {-32700, "Parse error", std::nullopt}; }+ static JSONRPCError invalidRequest() { return {-32600, "Invalid Request", std::nullopt}; }+ static JSONRPCError methodNotFound() { return {-32601, "Method not found", std::nullopt}; }+ static JSONRPCError invalidParams() { return {-32602, "Invalid params", std::nullopt}; }+ static JSONRPCError internalError() { return {-32603, "Internal error", std::nullopt}; }+};++// MCP-specific JSON-RPC error codes (negative, per spec "reserved for server use")+enum class MCPErrorCode : int {+ PermissionDenied = -32001,+ ApprovalTimeout = -32002,+ ApprovalDenied = -32003,+ ConnectionError = -32004,+ SyntaxError = -32005,+ NotFound = -32006,+ RateLimitExceeded = -32007,+ ScopeDenied = -32008,+ QueryTimeout = -32009,+};++// JSON-RPC request. id may be a string, int, or absent (notification).+struct JSONRPCRequest {+ json id; // null if notification+ std::string method;+ json params; // object or null++ static JSONRPCRequest fromJson(const json& j) {+ JSONRPCRequest r;+ if (j.contains("id")) r.id = j["id"];+ if (j.contains("method")) r.method = j.value("method", "");+ if (j.contains("params")) r.params = j["params"];+ return r;+ }+};++// JSON-RPC response.+struct JSONRPCResponse {+ json id; // echoes request id+ std::optional<json> result;+ std::optional<JSONRPCError> error;++ static JSONRPCResponse ok(const json& id, json result) {+ JSONRPCResponse r;+ r.id = id;+ r.result = std::move(result);+ return r;+ }++ static JSONRPCResponse err(const json& id, JSONRPCError error) {+ JSONRPCResponse r;+ r.id = id;+ r.error = std::move(error);+ return r;+ }++ json toJson() const {+ json j = {{"jsonrpc", "2.0"}};+ j["id"] = id; // may be null+ if (result) j["result"] = *result;+ else if (error) j["error"] = error->toJson();+ return j;+ }+};++// MCP tool content block (as returned from tools/call).+struct MCPContent {+ std::string type = "text";+ std::optional<std::string> text;+ std::optional<std::string> data; // base64 for images+ std::optional<std::string> mimeType;++ json toJson() const {+ json j = {{"type", type}};+ if (text) j["text"] = *text;+ if (data) j["data"] = *data;+ if (mimeType) j["mimeType"] = *mimeType;+ return j;+ }+};++// MCP tool execution result.+struct MCPToolResult {+ std::vector<MCPContent> content;+ bool isError = false;++ static MCPToolResult textResult(std::string text, bool err = false) {+ MCPToolResult r;+ MCPContent c;+ c.type = "text";+ c.text = std::move(text);+ r.content.push_back(std::move(c));+ r.isError = err;+ return r;+ }++ static MCPToolResult errorResult(std::string msg) {+ return textResult(std::move(msg), true);+ }++ json toJson() const {+ json arr = json::array();+ for (const auto& c : content) arr.push_back(c.toJson());+ json j = {{"content", arr}};+ if (isError) j["isError"] = true;+ return j;+ }+};++// MCP tool static definition (advertised via tools/list).+struct MCPToolDefinition {+ std::string name;+ std::string description;+ json inputSchema; // JSON Schema object++ json toJson() const {+ return {{"name", name}, {"description", description}, {"inputSchema", inputSchema}};+ }+};++// MCP client handshake info (learned during initialize).+struct MCPClientInfo {+ std::string name = "unknown";+ std::string version = "0.0.0";+};++// Audit record written to JSONL log.++enum class MCPAuditStatus { Success, Error, Denied, Timeout };++inline std::string toString(MCPAuditStatus s) {+ switch (s) {+ case MCPAuditStatus::Success: return "success";+ case MCPAuditStatus::Error: return "error";+ case MCPAuditStatus::Denied: return "denied";+ case MCPAuditStatus::Timeout: return "timeout";+ }+ return "error";+}++struct MCPAuditClient {+ std::string name = "unknown";+ std::string version = "0.0.0";+ std::string transport = "stdio";+};++struct MCPAuditInput {+ std::optional<std::string> sqlPreview;+ std::optional<int> paramsCount;+ std::optional<std::string> inputHash;++ static MCPAuditInput fromSql(const std::optional<std::string>& sql, std::optional<int> pc) {+ MCPAuditInput i;+ i.paramsCount = pc;+ if (sql) {+ const auto& s = *sql;+ i.sqlPreview = s.size() > 200 ? (s.substr(0, 200) + "...") : s;+ i.inputHash = "sha256:" + std::to_string(std::hash<std::string>{}(s));+ }+ return i;+ }+};++struct MCPAuditResult {+ MCPAuditStatus status = MCPAuditStatus::Success;+ std::optional<int> rowsAffected;+ std::optional<int> rowsReturned;+ int durationMs = 0;+ std::optional<int> bytesReturned;+};++struct MCPAuditSecurity {+ MCPConnectionMode mode = MCPConnectionMode::Locked;+ std::optional<bool> userApproved;+ std::optional<std::string> approvalSessionId;+ std::optional<std::vector<std::string>> scopesApplied;+};++struct MCPAuditEntry {+ std::string timestampIso8601;+ std::string eventId;+ MCPAuditClient client;+ std::string tool;+ int tier = 1;+ std::optional<std::string> connectionId; // UUID string+ std::optional<std::string> connectionType; // db type raw+ MCPAuditInput input;+ MCPAuditResult result;+ MCPAuditSecurity security;+ std::optional<std::string> error;++ json toJson() const {+ json clientJ = {{"name", client.name}, {"version", client.version}, {"transport", client.transport}};++ json inputJ = json::object();+ if (input.sqlPreview) inputJ["sqlPreview"] = *input.sqlPreview;+ if (input.paramsCount) inputJ["paramsCount"] = *input.paramsCount;+ if (input.inputHash) inputJ["inputHash"] = *input.inputHash;++ json resultJ = {{"status", toString(result.status)}, {"durationMs", result.durationMs}};+ if (result.rowsAffected) resultJ["rowsAffected"] = *result.rowsAffected;+ if (result.rowsReturned) resultJ["rowsReturned"] = *result.rowsReturned;+ if (result.bytesReturned) resultJ["bytesReturned"] = *result.bytesReturned;++ json securityJ = {{"permissionMode", std::string(rawValue(security.mode))}};+ if (security.userApproved) securityJ["userApproved"] = *security.userApproved;+ if (security.approvalSessionId) securityJ["approvalSessionId"] = *security.approvalSessionId;+ if (security.scopesApplied) securityJ["scopesApplied"] = *security.scopesApplied;++ json j = {+ {"timestamp", timestampIso8601},+ {"eventId", eventId},+ {"client", clientJ},+ {"tool", tool},+ {"tier", tier},+ {"input", inputJ},+ {"result", resultJ},+ {"security", securityJ},+ };+ if (connectionId) j["connectionId"] = *connectionId;+ if (connectionType) j["connectionType"] = *connectionType;+ if (error) j["error"] = *error;+ return j;+ }++ static std::optional<MCPAuditEntry> fromJson(const json& j);+};++// MCP tool error — thrown from inside tool.execute() to be caught by MCPServer.+class MCPToolError : public std::runtime_error {+public:+ enum class Kind {+ ConnectionNotFound,+ ConnectionNotConnected,+ TableNotFound,+ InvalidParameters,+ PermissionDenied,+ QueryFailed,+ RateLimitExceeded,+ };++ MCPToolError(Kind k, std::string message, int retryAfter = 0)+ : std::runtime_error(std::move(message)), kind_(k), retryAfter_(retryAfter) {}++ Kind kind() const noexcept { return kind_; }+ int retryAfterSeconds() const noexcept { return retryAfter_; }++ static MCPToolError invalidParameters(std::string msg) {+ return {Kind::InvalidParameters, "Invalid parameters: " + msg};+ }+ static MCPToolError connectionNotFound(const std::string& id) {+ return {Kind::ConnectionNotFound,+ "Connection '" + id + "' not found. Use list_connections to see available connections."};+ }+ static MCPToolError connectionNotConnected(const std::string& id) {+ return {Kind::ConnectionNotConnected,+ "Connection '" + id + "' is not active. The user needs to connect first."};+ }+ static MCPToolError tableNotFound(const std::string& name) {+ return {Kind::TableNotFound, "Table '" + name + "' not found."};+ }+ static MCPToolError permissionDenied(std::string msg) {+ return {Kind::PermissionDenied, std::move(msg)};+ }+ static MCPToolError queryFailed(const std::string& msg) {+ return {Kind::QueryFailed, "Query failed: " + msg};+ }+ static MCPToolError rateLimitExceeded(int retryAfter) {+ return {Kind::RateLimitExceeded,+ "Rate limit exceeded. Retry after " + std::to_string(retryAfter) + " seconds.",+ retryAfter};+ }++private:+ Kind kind_;+ int retryAfter_ = 0;+};++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/Security/ApprovalGate.cpp b/linux/src/Services/MCP/Security/ApprovalGate.cppnew file mode 100644index 0000000..7dfb11c--- /dev/null+++ b/linux/src/Services/MCP/Security/ApprovalGate.cpp@@ -0,0 +1,75 @@+#include "Services/MCP/Security/ApprovalGate.h"++namespace gridex::mcp {++void ApprovalGate::setDialogCallback(DialogCallback cb) {+ std::lock_guard lk(mu_);+ callback_ = std::move(cb);+}++bool ApprovalGate::requestApproval(const std::string& tool,+ const std::string& description,+ const std::string& details,+ const std::string& connectionId,+ const MCPAuditClient& client,+ std::chrono::seconds timeout) {+ // Fast-path: existing session approval.+ {+ std::lock_guard lk(mu_);+ SessionKey key{connectionId, tool};+ auto it = sessionApprovals_.find(key);+ if (it != sessionApprovals_.end()) {+ auto age = std::chrono::steady_clock::now() - it->second;+ if (age < kSessionTimeout) return true;+ sessionApprovals_.erase(it);+ }+ }++ DialogCallback cb;+ {+ std::lock_guard lk(mu_);+ cb = callback_;+ }+ if (!cb) {+ // No GUI dialog wired up → deny by default (stdio/CLI mode).+ return false;+ }++ // Run the dialog on a worker thread wrapped in future; the callback itself+ // is expected to marshal onto Qt main thread as needed.+ std::promise<ApprovalResult> prom;+ auto fut = prom.get_future();++ std::thread([cb, tool, description, details, connectionId, client, p = std::move(prom)]() mutable {+ try {+ p.set_value(cb(tool, description, details, connectionId, client));+ } catch (...) {+ p.set_value(ApprovalResult::Denied);+ }+ }).detach();++ if (fut.wait_for(timeout) != std::future_status::ready) {+ return false; // timeout → treat as denied+ }+ ApprovalResult r = fut.get();+ if (r == ApprovalResult::ApprovedForSession) {+ std::lock_guard lk(mu_);+ sessionApprovals_[SessionKey{connectionId, tool}] = std::chrono::steady_clock::now();+ }+ return r == ApprovalResult::Approved || r == ApprovalResult::ApprovedForSession;+}++void ApprovalGate::revokeSessionApproval(const std::string& connectionId) {+ std::lock_guard lk(mu_);+ for (auto it = sessionApprovals_.begin(); it != sessionApprovals_.end();) {+ if (it->first.connectionId == connectionId) it = sessionApprovals_.erase(it);+ else ++it;+ }+}++void ApprovalGate::revokeAllSessionApprovals() {+ std::lock_guard lk(mu_);+ sessionApprovals_.clear();+}++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/Security/ApprovalGate.h b/linux/src/Services/MCP/Security/ApprovalGate.hnew file mode 100644index 0000000..46839c0--- /dev/null+++ b/linux/src/Services/MCP/Security/ApprovalGate.h@@ -0,0 +1,66 @@+#pragma once++#include <chrono>+#include <functional>+#include <future>+#include <mutex>+#include <string>+#include <unordered_map>++#include "Services/MCP/Protocol.h"++namespace gridex::mcp {++enum class ApprovalResult { Approved, ApprovedForSession, Denied };++// Approval gate: asks the user to approve a write/DDL operation.+// In GUI mode a dialog callback is invoked on the Qt main thread.+// In stdio CLI mode (no GUI), the callback may default to auto-deny or auto-approve+// depending on config.+class ApprovalGate {+public:+ // dialogCallback is invoked with (tool, description, details, connectionId, client).+ // It must return an ApprovalResult. Safe to call from a background thread — the+ // implementation should marshal to the GUI thread internally if needed.+ using DialogCallback = std::function<ApprovalResult(+ const std::string& tool,+ const std::string& description,+ const std::string& details,+ const std::string& connectionId,+ const MCPAuditClient& client)>;++ void setDialogCallback(DialogCallback cb);++ // Blocks the calling thread up to `timeout` waiting for the user to respond.+ // Returns true if approved, false if denied or timed out.+ bool requestApproval(const std::string& tool,+ const std::string& description,+ const std::string& details,+ const std::string& connectionId,+ const MCPAuditClient& client,+ std::chrono::seconds timeout = std::chrono::seconds{60});++ void revokeSessionApproval(const std::string& connectionId);+ void revokeAllSessionApprovals();++private:+ struct SessionKey {+ std::string connectionId;+ std::string tool;+ bool operator==(const SessionKey& o) const noexcept {+ return connectionId == o.connectionId && tool == o.tool;+ }+ };+ struct SessionKeyHash {+ std::size_t operator()(const SessionKey& k) const noexcept {+ return std::hash<std::string>{}(k.connectionId) ^ (std::hash<std::string>{}(k.tool) << 1);+ }+ };++ mutable std::mutex mu_;+ DialogCallback callback_;+ std::unordered_map<SessionKey, std::chrono::steady_clock::time_point, SessionKeyHash> sessionApprovals_;+ static constexpr std::chrono::minutes kSessionTimeout{30};+};++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/Security/IdentifierValidator.h b/linux/src/Services/MCP/Security/IdentifierValidator.hnew file mode 100644index 0000000..881478b--- /dev/null+++ b/linux/src/Services/MCP/Security/IdentifierValidator.h@@ -0,0 +1,61 @@+#pragma once++// Allowlist check for SQL identifiers received from MCP clients. Rejects anything+// outside strict ASCII letters/digits/underscore with a letter-or-underscore+// first char. Defense-in-depth on top of SQLDialect::quoteIdentifier.++#include <optional>+#include <string>+#include <string_view>+#include <utility>++#include <nlohmann/json.hpp>++#include "Services/MCP/Protocol.h"++namespace gridex::mcp {++struct IdentifierValidator {+ static constexpr std::size_t kMaxLength = 128;++ static bool isValid(std::string_view id) {+ if (id.empty() || id.size() > kMaxLength) return false;+ auto letter = [](unsigned char c) {+ return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_';+ };+ auto digit = [](unsigned char c) { return c >= '0' && c <= '9'; };+ if (!letter(static_cast<unsigned char>(id[0]))) return false;+ for (std::size_t k = 1; k < id.size(); ++k) {+ unsigned char c = static_cast<unsigned char>(id[k]);+ if (!letter(c) && !digit(c)) return false;+ }+ return true;+ }++ static void validate(std::string_view id, const std::string& role = "identifier") {+ if (!isValid(id)) {+ throw MCPToolError::invalidParameters(+ role + " '" + std::string(id) + "' contains invalid characters. Allowed: "+ "letters, digits, underscore; must start with a letter or underscore; max "+ + std::to_string(kMaxLength) + " chars.");+ }+ }++ // Reads `table_name` and optional `schema` from params and validates both.+ static std::pair<std::string, std::optional<std::string>> extractTableAndSchema(const nlohmann::json& params) {+ if (!params.contains("table_name") || !params["table_name"].is_string()) {+ throw MCPToolError::invalidParameters("table_name is required");+ }+ std::string table = params["table_name"].get<std::string>();+ validate(table, "table_name");++ std::optional<std::string> schema;+ if (params.contains("schema") && params["schema"].is_string()) {+ schema = params["schema"].get<std::string>();+ validate(*schema, "schema");+ }+ return {std::move(table), std::move(schema)};+ }+};++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/Security/PermissionEngine.cpp b/linux/src/Services/MCP/Security/PermissionEngine.cppnew file mode 100644index 0000000..ca599e4--- /dev/null+++ b/linux/src/Services/MCP/Security/PermissionEngine.cpp@@ -0,0 +1,181 @@+#include "Services/MCP/Security/PermissionEngine.h"++#include <algorithm>+#include <array>+#include <cctype>+#include <regex>+#include <string_view>+#include <unordered_set>++#include "Services/MCP/Security/SQLSanitizer.h"++namespace gridex::mcp {++namespace {++static const std::array<std::string_view, 6> kReadOnlyPrefixes = {+ "SELECT", "SHOW", "EXPLAIN", "DESCRIBE", "DESC", "WITH"+};++static const std::array<std::string_view, 34> kDangerousKeywords = {+ "INSERT", "UPDATE", "DELETE", "MERGE", "UPSERT",+ "DROP", "CREATE", "ALTER", "TRUNCATE", "RENAME",+ "GRANT", "REVOKE",+ "CALL", "EXEC", "EXECUTE", "DO",+ "NEXTVAL", "SETVAL",+ "LO_IMPORT", "LO_EXPORT",+ "COPY", "VACUUM", "ANALYZE", "REINDEX", "CLUSTER", "REFRESH",+ "LOCK", "UNLOCK",+ "SET", "RESET", "BEGIN", "COMMIT", "ROLLBACK", "SAVEPOINT"+};++std::string toUpper(std::string s) {+ for (auto& c : s) c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));+ return s;+}++std::string trim(const std::string& s) {+ auto b = s.find_first_not_of(" \t\r\n");+ if (b == std::string::npos) return "";+ auto e = s.find_last_not_of(" \t\r\n");+ return s.substr(b, e - b + 1);+}++bool startsWith(const std::string& s, std::string_view prefix) {+ return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());+}++bool containsWord(const std::string& code, std::string_view word) {+ // Simple word boundary scan (ASCII only).+ auto isWord = [](unsigned char c) {+ return std::isalnum(c) || c == '_';+ };+ const std::size_t n = code.size();+ const std::size_t m = word.size();+ if (m == 0 || m > n) return false;+ for (std::size_t i = 0; i + m <= n; ++i) {+ if (i > 0 && isWord(static_cast<unsigned char>(code[i - 1]))) continue;+ if (i + m < n && isWord(static_cast<unsigned char>(code[i + m]))) continue;+ bool eq = true;+ for (std::size_t k = 0; k < m; ++k) {+ if (std::toupper(static_cast<unsigned char>(code[i + k])) != word[k]) { eq = false; break; }+ }+ if (eq) return true;+ }+ return false;+}++} // namespace++void PermissionEngine::setMode(const std::string& id, MCPConnectionMode mode) {+ std::lock_guard lk(mu_);+ modes_[id] = mode;+}++MCPConnectionMode PermissionEngine::getMode(const std::string& id) const {+ std::lock_guard lk(mu_);+ auto it = modes_.find(id);+ return it != modes_.end() ? it->second : MCPConnectionMode::Locked;+}++void PermissionEngine::removeMode(const std::string& id) {+ std::lock_guard lk(mu_);+ modes_.erase(id);+}++PermissionResult PermissionEngine::checkPermission(MCPPermissionTier tier, const std::string& id) const {+ return checkPermission(tier, getMode(id));+}++PermissionResult PermissionEngine::checkPermission(MCPPermissionTier tier, MCPConnectionMode mode) const {+ switch (tier) {+ case MCPPermissionTier::Schema:+ return allowsTier1(mode) ? PermissionResult::allowed()+ : PermissionResult::denied("Connection is locked. MCP access is disabled.");+ case MCPPermissionTier::Read:+ return allowsTier2(mode) ? PermissionResult::allowed()+ : PermissionResult::denied("Connection is locked. MCP access is disabled.");+ case MCPPermissionTier::Write:+ if (!allowsTier3(mode)) {+ return PermissionResult::denied(+ "This operation requires read-write mode. Ask the user to enable it in "+ "Connection Settings > MCP Access.");+ }+ return PermissionResult::requiresApproval();+ case MCPPermissionTier::Ddl:+ if (!allowsTier4(mode)) {+ return PermissionResult::denied(+ "DDL operations require read-write mode. Ask the user to enable it in "+ "Connection Settings > MCP Access.");+ }+ return PermissionResult::requiresApproval();+ case MCPPermissionTier::Advanced:+ return allowsTier5(mode) ? PermissionResult::allowed()+ : PermissionResult::denied("Connection is locked. MCP access is disabled.");+ }+ return PermissionResult::denied("Unknown tier.");+}++PermissionResult PermissionEngine::validateReadOnlyQuery(const std::string& sql) const {+ std::string code = stripCommentsAndStrings(sql);+ std::string upper = toUpper(trim(code));++ // One optional trailing `;` is fine; anything else is multi-statement.+ std::string withoutSemi = upper;+ if (!withoutSemi.empty() && withoutSemi.back() == ';') withoutSemi.pop_back();+ withoutSemi = trim(withoutSemi);+ if (withoutSemi.find(';') != std::string::npos) {+ return PermissionResult::denied("Multiple statements are not allowed in read-only mode.");+ }++ bool isRO = false;+ for (auto p : kReadOnlyPrefixes) if (startsWith(upper, p)) { isRO = true; break; }+ if (!isRO) {+ return PermissionResult::denied(+ "Only SELECT queries are allowed in read-only mode. This query appears to modify data.");+ }++ for (auto kw : kDangerousKeywords) {+ if (containsWord(code, kw)) {+ return PermissionResult::denied(+ "Query contains '" + std::string(kw) + "' which is not allowed in read-only mode.");+ }+ }+ return PermissionResult::allowed();+}++PermissionResult PermissionEngine::validateWhereClause(const std::optional<std::string>& where) const {+ if (!where) {+ return PermissionResult::denied(+ "WHERE clause is required for UPDATE/DELETE operations. Bare UPDATE/DELETE without WHERE is not allowed.");+ }+ std::string trimmed = trim(*where);+ if (trimmed.empty()) {+ return PermissionResult::denied("WHERE clause is required for UPDATE/DELETE operations.");+ }+ if (trimmed.find(';') != std::string::npos) {+ return PermissionResult::denied("WHERE clause must not contain ';' — statement terminators are forbidden.");+ }+ if (trimmed.find("--") != std::string::npos) {+ return PermissionResult::denied("WHERE clause must not contain '--' — SQL line comments are forbidden.");+ }+ if (trimmed.find("/*") != std::string::npos || trimmed.find("*/") != std::string::npos) {+ return PermissionResult::denied("WHERE clause must not contain '/*' or '*/' — SQL block comments are forbidden.");+ }++ std::string compact;+ compact.reserve(trimmed.size());+ for (char c : toUpper(trimmed)) {+ if (!std::isspace(static_cast<unsigned char>(c))) compact.push_back(c);+ }+ static const std::unordered_set<std::string> kTrivial = {+ "1=1", "TRUE", "1", "'1'='1'", "1<>0", "0=0", "2>1", "TRUE=TRUE", "NULLISNULL"+ };+ if (kTrivial.count(compact)) {+ return PermissionResult::denied(+ "Trivial WHERE clause '" + trimmed + "' is not allowed. Provide a meaningful predicate.");+ }+ return PermissionResult::allowed();+}++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/Security/PermissionEngine.h b/linux/src/Services/MCP/Security/PermissionEngine.hnew file mode 100644index 0000000..fb916a5--- /dev/null+++ b/linux/src/Services/MCP/Security/PermissionEngine.h@@ -0,0 +1,53 @@+#pragma once++#include <mutex>+#include <optional>+#include <string>+#include <unordered_map>+#include <variant>++#include "Core/Enums/MCPConnectionMode.h"+#include "Core/Enums/MCPPermissionTier.h"++namespace gridex::mcp {++// Three-way permission result: allowed, needs user approval, or denied with message.+class PermissionResult {+public:+ enum class Kind { Allowed, RequiresApproval, Denied };++ static PermissionResult allowed() { return {Kind::Allowed, {}}; }+ static PermissionResult requiresApproval() { return {Kind::RequiresApproval, {}}; }+ static PermissionResult denied(std::string message) { return {Kind::Denied, std::move(message)}; }++ Kind kind() const noexcept { return kind_; }+ bool isAllowed() const noexcept { return kind_ == Kind::Allowed; }+ bool requiresUserApproval() const noexcept { return kind_ == Kind::RequiresApproval; }+ const std::string& errorMessage() const noexcept { return message_; }++private:+ PermissionResult(Kind k, std::string msg) : kind_(k), message_(std::move(msg)) {}+ Kind kind_;+ std::string message_;+};++// Thread-safe permission engine. Holds per-connection MCPConnectionMode and+// exposes tier/SQL/WHERE-clause validation helpers.+class PermissionEngine {+public:+ void setMode(const std::string& connectionId, MCPConnectionMode mode);+ MCPConnectionMode getMode(const std::string& connectionId) const;+ void removeMode(const std::string& connectionId);++ PermissionResult checkPermission(MCPPermissionTier tier, const std::string& connectionId) const;+ PermissionResult checkPermission(MCPPermissionTier tier, MCPConnectionMode mode) const;++ PermissionResult validateReadOnlyQuery(const std::string& sql) const;+ PermissionResult validateWhereClause(const std::optional<std::string>& whereClause) const;++private:+ mutable std::mutex mu_;+ std::unordered_map<std::string, MCPConnectionMode> modes_;+};++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/Security/RateLimiter.cpp b/linux/src/Services/MCP/Security/RateLimiter.cppnew file mode 100644index 0000000..7dcdfe2--- /dev/null+++ b/linux/src/Services/MCP/Security/RateLimiter.cpp@@ -0,0 +1,93 @@+#include "Services/MCP/Security/RateLimiter.h"++#include <algorithm>++namespace gridex::mcp {++using namespace std::chrono;++void RateLimiter::setLimits(RateLimits l) {+ std::lock_guard lk(mu_);+ limits_ = l;+}++RateLimits RateLimiter::limits() const {+ std::lock_guard lk(mu_);+ return limits_;+}++RateLimitResult RateLimiter::checkBucket(Bucket& b, int limit, seconds window, Clock::time_point now) {+ auto cutoff = now - window;+ int count = 0;+ Clock::time_point oldest = Clock::time_point::max();+ for (auto t : b) {+ if (t > cutoff) {+ ++count;+ oldest = std::min(oldest, t);+ }+ }+ if (count >= limit) {+ int retry = static_cast<int>(duration_cast<seconds>(window - (now - oldest)).count());+ return RateLimitResult::exceeded(std::max(1, retry));+ }+ return RateLimitResult::allowed();+}++void RateLimiter::recordBucket(Bucket& b, Clock::time_point now, seconds maxAge) {+ b.push_back(now);+ auto cutoff = now - maxAge;+ while (!b.empty() && b.front() <= cutoff) b.pop_front();+}++RateLimitResult RateLimiter::checkLimit(MCPPermissionTier tier, const std::string& id) {+ std::lock_guard lk(mu_);+ auto now = Clock::now();+ switch (tier) {+ case MCPPermissionTier::Schema:+ case MCPPermissionTier::Read:+ case MCPPermissionTier::Advanced: {+ auto& b = queryCount_[id];+ if (auto r = checkBucket(b, limits_.queriesPerMinute, seconds{60}, now); !r.isAllowed()) return r;+ return checkBucket(b, limits_.queriesPerHour, seconds{3600}, now);+ }+ case MCPPermissionTier::Write:+ return checkBucket(writeCount_[id], limits_.writesPerMinute, seconds{60}, now);+ case MCPPermissionTier::Ddl:+ return checkBucket(ddlCount_[id], limits_.ddlPerMinute, seconds{60}, now);+ }+ return RateLimitResult::allowed();+}++void RateLimiter::recordUsage(MCPPermissionTier tier, const std::string& id) {+ std::lock_guard lk(mu_);+ auto now = Clock::now();+ switch (tier) {+ case MCPPermissionTier::Schema:+ case MCPPermissionTier::Read:+ case MCPPermissionTier::Advanced:+ recordBucket(queryCount_[id], now, seconds{3600});+ break;+ case MCPPermissionTier::Write:+ recordBucket(writeCount_[id], now, seconds{60});+ break;+ case MCPPermissionTier::Ddl:+ recordBucket(ddlCount_[id], now, seconds{60});+ break;+ }+}++void RateLimiter::resetLimits(const std::string& id) {+ std::lock_guard lk(mu_);+ queryCount_.erase(id);+ writeCount_.erase(id);+ ddlCount_.erase(id);+}++void RateLimiter::resetAll() {+ std::lock_guard lk(mu_);+ queryCount_.clear();+ writeCount_.clear();+ ddlCount_.clear();+}++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/Security/RateLimiter.h b/linux/src/Services/MCP/Security/RateLimiter.hnew file mode 100644index 0000000..d227179--- /dev/null+++ b/linux/src/Services/MCP/Security/RateLimiter.h@@ -0,0 +1,63 @@+#pragma once++#include <chrono>+#include <deque>+#include <mutex>+#include <optional>+#include <string>+#include <unordered_map>++#include "Core/Enums/MCPPermissionTier.h"++namespace gridex::mcp {++class RateLimitResult {+public:+ static RateLimitResult allowed() { return {true, 0}; }+ static RateLimitResult exceeded(int retryAfter) { return {false, retryAfter}; }++ bool isAllowed() const noexcept { return allowed_; }+ std::optional<int> retryAfterSeconds() const noexcept {+ return allowed_ ? std::optional<int>{} : std::optional<int>{retryAfter_};+ }++private:+ RateLimitResult(bool a, int r) : allowed_(a), retryAfter_(r) {}+ bool allowed_;+ int retryAfter_;+};++struct RateLimits {+ int queriesPerMinute = 60;+ int queriesPerHour = 1000;+ int writesPerMinute = 10;+ int ddlPerMinute = 1;+};++class RateLimiter {+public:+ // Limits are looked up at check time so QSettings changes apply live.+ void setLimits(RateLimits limits);+ RateLimits limits() const;++ RateLimitResult checkLimit(MCPPermissionTier tier, const std::string& connectionId);+ void recordUsage(MCPPermissionTier tier, const std::string& connectionId);++ void resetLimits(const std::string& connectionId);+ void resetAll();++private:+ using Clock = std::chrono::steady_clock;+ using Bucket = std::deque<Clock::time_point>;++ RateLimitResult checkBucket(Bucket& b, int limit, std::chrono::seconds window, Clock::time_point now);+ void recordBucket(Bucket& b, Clock::time_point now, std::chrono::seconds maxAge);++ mutable std::mutex mu_;+ RateLimits limits_;+ std::unordered_map<std::string, Bucket> queryCount_;+ std::unordered_map<std::string, Bucket> writeCount_;+ std::unordered_map<std::string, Bucket> ddlCount_;+};++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/Security/RowCountEstimator.cpp b/linux/src/Services/MCP/Security/RowCountEstimator.cppnew file mode 100644index 0000000..5db6380--- /dev/null+++ b/linux/src/Services/MCP/Security/RowCountEstimator.cpp@@ -0,0 +1,25 @@+#include "Services/MCP/Security/RowCountEstimator.h"++namespace gridex::mcp {++int RowCountEstimator::estimate(IDatabaseAdapter& adapter,+ const std::string& qualifiedTable,+ const std::string& whereClause,+ const ConnectionConfig& config) {+ if (!isSQL(config.databaseType)) return 0;+ const std::string sql = "SELECT COUNT(*) FROM " + qualifiedTable + " WHERE " + whereClause;+ try {+ auto result = adapter.executeRaw(sql);+ if (result.rows.empty() || result.rows.front().empty()) return 0;+ const auto& v = result.rows.front().front();+ if (v.isInteger()) return static_cast<int>(v.asInteger());+ if (v.isString()) {+ try { return std::stoi(v.asString()); } catch (...) { return 0; }+ }+ return 0;+ } catch (...) {+ return 0;+ }+}++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/Security/RowCountEstimator.h b/linux/src/Services/MCP/Security/RowCountEstimator.hnew file mode 100644index 0000000..508db2c--- /dev/null+++ b/linux/src/Services/MCP/Security/RowCountEstimator.h@@ -0,0 +1,20 @@+#pragma once++#include <string>++#include "Core/Models/Database/ConnectionConfig.h"+#include "Core/Protocols/Database/IDatabaseAdapter.h"++namespace gridex::mcp {++// Pre-approval row count estimation for write tools. Runs against the same+// (already validated & quoted) SQL shape that the write tool will execute, so it+// never reconstructs SQL from user-supplied substrings.+struct RowCountEstimator {+ static int estimate(IDatabaseAdapter& adapter,+ const std::string& qualifiedTable,+ const std::string& whereClause,+ const ConnectionConfig& config);+};++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/Security/SQLSanitizer.h b/linux/src/Services/MCP/Security/SQLSanitizer.hnew file mode 100644index 0000000..074dd22--- /dev/null+++ b/linux/src/Services/MCP/Security/SQLSanitizer.h@@ -0,0 +1,50 @@+#pragma once++// Strips comments and single-quoted string literals from SQL so syntactic checks+// (e.g. "contains WHERE?") aren't fooled by payloads in comments or literals.+// NOT for execution — security-side normalizer only.++#include <string>++namespace gridex::mcp {++inline std::string stripCommentsAndStrings(const std::string& sql) {+ std::string out;+ out.reserve(sql.size());+ const std::size_t n = sql.size();+ std::size_t i = 0;+ while (i < n) {+ const char c = sql[i];+ // -- line comment+ if (c == '-' && i + 1 < n && sql[i + 1] == '-') {+ while (i < n && sql[i] != '\n') ++i;+ continue;+ }+ // /* block comment */+ if (c == '/' && i + 1 < n && sql[i + 1] == '*') {+ i += 2;+ while (i + 1 < n && !(sql[i] == '*' && sql[i + 1] == '/')) ++i;+ if (i + 1 < n) i += 2;+ continue;+ }+ // 'literal' with '' escape+ if (c == '\'') {+ ++i;+ while (i < n) {+ if (sql[i] == '\'') {+ if (i + 1 < n && sql[i + 1] == '\'') { i += 2; continue; }+ ++i;+ break;+ }+ ++i;+ }+ out.push_back(' ');+ continue;+ }+ out.push_back(c);+ ++i;+ }+ return out;+}++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/Tools/MCPTool.h b/linux/src/Services/MCP/Tools/MCPTool.hnew file mode 100644index 0000000..b9b150a--- /dev/null+++ b/linux/src/Services/MCP/Tools/MCPTool.h@@ -0,0 +1,105 @@+#pragma once++#include <memory>+#include <optional>+#include <string>+#include <utility>++#include "Core/Enums/MCPPermissionTier.h"+#include "Core/Models/Database/ConnectionConfig.h"+#include "Core/Protocols/Database/IDatabaseAdapter.h"+#include "Services/MCP/Protocol.h"+#include "Services/MCP/Security/ApprovalGate.h"+#include "Services/MCP/Security/PermissionEngine.h"+#include "Services/MCP/Security/RateLimiter.h"++namespace gridex::mcp {++class AuditLogger;++// Provides on-demand database adapters for a given connection ID. MCP tools use+// this rather than taking the live app's single-adapter WorkspaceState, so tools+// can operate on any configured connection.+class IMCPConnectionProvider {+public:+ virtual ~IMCPConnectionProvider() = default;++ // Returns (adapter, config) for the given connection ID. Throws MCPToolError+ // if the connection does not exist or cannot be opened.+ virtual std::pair<std::shared_ptr<IDatabaseAdapter>, ConnectionConfig>+ openConnection(const std::string& connectionId) = 0;++ // Returns true if the connection is known (listed in the repository).+ virtual bool hasConnection(const std::string& connectionId) = 0;++ // Lists all known connections.+ virtual std::vector<ConnectionConfig> listConnections() = 0;+};++// Context bag passed to every tool invocation.+struct MCPToolContext {+ IMCPConnectionProvider* connectionProvider = nullptr;+ PermissionEngine* permissionEngine = nullptr;+ AuditLogger* auditLogger = nullptr;+ RateLimiter* rateLimiter = nullptr;+ ApprovalGate* approvalGate = nullptr;+ MCPAuditClient client;++ std::pair<std::shared_ptr<IDatabaseAdapter>, ConnectionConfig>+ getAdapter(const std::string& connectionId) const {+ if (!connectionProvider) {+ throw MCPToolError::connectionNotFound(connectionId);+ }+ return connectionProvider->openConnection(connectionId);+ }++ PermissionResult checkPermission(MCPPermissionTier tier, const std::string& connectionId) const {+ return permissionEngine->checkPermission(tier, connectionId);+ }++ void checkRateLimit(MCPPermissionTier tier, const std::string& connectionId) const {+ auto r = rateLimiter->checkLimit(tier, connectionId);+ if (auto retry = r.retryAfterSeconds()) {+ throw MCPToolError::rateLimitExceeded(*retry);+ }+ }++ void recordUsage(MCPPermissionTier tier, const std::string& connectionId) const {+ rateLimiter->recordUsage(tier, connectionId);+ }++ bool requestApproval(const std::string& tool,+ const std::string& description,+ const std::string& details,+ const std::string& connectionId) const {+ return approvalGate->requestApproval(tool, description, details, connectionId, client);+ }+};++// Tool interface. Implementations must be thread-safe — the registry hands out+// shared instances that may be invoked concurrently.+class MCPTool {+public:+ virtual ~MCPTool() = default;++ virtual std::string name() const = 0;+ virtual std::string description() const = 0;+ virtual MCPPermissionTier tier() const = 0;+ virtual nlohmann::json inputSchema() const = 0;++ virtual MCPToolResult execute(const nlohmann::json& params, const MCPToolContext& ctx) = 0;++ MCPToolDefinition definition() const {+ return {name(), description(), inputSchema()};+ }++ // Helper: extracts and UUID-validates `connection_id` from params.+ static std::string extractConnectionId(const nlohmann::json& params) {+ if (!params.contains("connection_id") || !params["connection_id"].is_string()) {+ throw MCPToolError::invalidParameters("connection_id is required");+ }+ return params["connection_id"].get<std::string>();+ }+};++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/Tools/Tier1/DescribeTableTool.cpp b/linux/src/Services/MCP/Tools/Tier1/DescribeTableTool.cppnew file mode 100644index 0000000..d573383--- /dev/null+++ b/linux/src/Services/MCP/Tools/Tier1/DescribeTableTool.cpp@@ -0,0 +1,124 @@+#include "Services/MCP/Tools/MCPTool.h"+#include "Services/MCP/Tools/ToolHelpers.h"++namespace gridex::mcp {++namespace {++class DescribeTableTool final : public MCPTool {+public:+ std::string name() const override { return "describe_table"; }+ std::string description() const override {+ return "Get detailed structure of a table including columns, data types, indexes, "+ "primary keys, foreign keys, and constraints.";+ }+ MCPPermissionTier tier() const override { return MCPPermissionTier::Schema; }++ nlohmann::json inputSchema() const override {+ return {+ {"type", "object"},+ {"properties", {+ {"connection_id", {{"type", "string"}, {"description", "Connection identifier"}}},+ {"table_name", {{"type", "string"}, {"description", "Name of the table to describe"}}},+ {"schema", {{"type", "string"}, {"description", "Optional schema name"}}},+ }},+ {"required", nlohmann::json::array({"connection_id", "table_name"})},+ };+ }++ MCPToolResult execute(const nlohmann::json& params, const MCPToolContext& ctx) override {+ const std::string connectionId = MCPTool::extractConnectionId(params);+ if (!params.contains("table_name") || !params["table_name"].is_string()) {+ throw MCPToolError::invalidParameters("table_name is required");+ }+ const std::string tableName = params["table_name"].get<std::string>();++ auto perm = ctx.checkPermission(tier(), connectionId);+ if (!perm.isAllowed() && !perm.requiresUserApproval()) {+ throw MCPToolError::permissionDenied(perm.errorMessage());+ }++ auto [adapter, config] = ctx.getAdapter(connectionId);+ std::optional<std::string> schemaName;+ if (params.contains("schema") && params["schema"].is_string()) {+ schemaName = params["schema"].get<std::string>();+ }++ auto desc = adapter->describeTable(tableName, schemaName);+ auto indexes = adapter->listIndexes(tableName, schemaName);+ auto foreignKeys = adapter->listForeignKeys(tableName, schemaName);++ nlohmann::json result = {+ {"name", desc.name},+ {"database_type", std::string(displayName(config.databaseType))},+ };+ if (desc.schema) result["schema"] = *desc.schema;+ if (desc.comment) result["comment"] = *desc.comment;+ if (desc.estimatedRowCount) result["estimated_rows"] = *desc.estimatedRowCount;++ nlohmann::json cols = nlohmann::json::array();+ nlohmann::json pk = nlohmann::json::array();+ for (const auto& c : desc.columns) {+ nlohmann::json col = {+ {"name", c.name},+ {"type", c.dataType},+ {"nullable", c.isNullable},+ };+ if (c.isPrimaryKey) { col["primary_key"] = true; pk.push_back(c.name); }+ if (c.defaultValue) col["default"] = *c.defaultValue;+ if (c.comment) col["comment"] = *c.comment;+ cols.push_back(std::move(col));+ }+ result["columns"] = cols;+ if (!pk.empty()) result["primary_key"] = pk;++ if (!indexes.empty()) {+ nlohmann::json idx = nlohmann::json::array();+ for (const auto& i : indexes) {+ idx.push_back({+ {"name", i.name},+ {"columns", i.columns},+ {"unique", i.isUnique},+ {"type", i.type.value_or("btree")},+ });+ }+ result["indexes"] = idx;+ }++ if (!foreignKeys.empty()) {+ nlohmann::json fks = nlohmann::json::array();+ for (const auto& fk : foreignKeys) {+ fks.push_back({+ {"name", fk.name.value_or("")},+ {"columns", fk.columns},+ {"references_table", fk.referencedTable},+ {"references_columns", fk.referencedColumns},+ });+ }+ result["foreign_keys"] = fks;+ }++ if (!desc.constraints.empty()) {+ nlohmann::json cs = nlohmann::json::array();+ for (const auto& c : desc.constraints) {+ cs.push_back({+ {"name", c.name},+ {"type", std::string(rawValue(c.type))},+ {"definition", c.definition.value_or("")},+ });+ }+ result["constraints"] = cs;+ }++ result["ddl"] = desc.toDDL(sqlDialect(config.databaseType));+ return MCPToolResult::textResult(result.dump(2));+ }+};++} // namespace++std::shared_ptr<MCPTool> makeDescribeTableTool() {+ return std::make_shared<DescribeTableTool>();+}++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/Tools/Tier1/GetSampleRowsTool.cpp b/linux/src/Services/MCP/Tools/Tier1/GetSampleRowsTool.cppnew file mode 100644index 0000000..8105f91--- /dev/null+++ b/linux/src/Services/MCP/Tools/Tier1/GetSampleRowsTool.cpp@@ -0,0 +1,81 @@+#include <algorithm>++#include "Services/MCP/Tools/MCPTool.h"++namespace gridex::mcp {++namespace {++class GetSampleRowsTool final : public MCPTool {+public:+ std::string name() const override { return "get_sample_rows"; }+ std::string description() const override {+ return "Get sample rows from a table to help understand data shape. Default limit 10, max 100.";+ }+ MCPPermissionTier tier() const override { return MCPPermissionTier::Schema; }++ nlohmann::json inputSchema() const override {+ return {+ {"type", "object"},+ {"properties", {+ {"connection_id", {{"type", "string"}, {"description", "Connection identifier"}}},+ {"table_name", {{"type", "string"}, {"description", "Name of the table"}}},+ {"limit", {{"type", "integer"},+ {"description", "Number of rows (default 10, max 100)"},+ {"default", 10}, {"minimum", 1}, {"maximum", 100}}},+ }},+ {"required", nlohmann::json::array({"connection_id", "table_name"})},+ };+ }++ MCPToolResult execute(const nlohmann::json& params, const MCPToolContext& ctx) override {+ const std::string connectionId = MCPTool::extractConnectionId(params);+ if (!params.contains("table_name") || !params["table_name"].is_string()) {+ throw MCPToolError::invalidParameters("table_name is required");+ }+ const std::string tableName = params["table_name"].get<std::string>();+ int limit = 10;+ if (params.contains("limit") && params["limit"].is_number_integer()) {+ limit = std::clamp(params["limit"].get<int>(), 1, 100);+ }++ auto perm = ctx.checkPermission(tier(), connectionId);+ if (!perm.isAllowed() && !perm.requiresUserApproval()) {+ throw MCPToolError::permissionDenied(perm.errorMessage());+ }++ auto [adapter, config] = ctx.getAdapter(connectionId);+ auto result = adapter->fetchRows(tableName, std::nullopt, std::nullopt,+ std::nullopt, std::nullopt, limit, 0);++ if (result.rows.empty()) {+ return MCPToolResult::textResult("Table '" + tableName + "' is empty.");+ }++ nlohmann::json rows = nlohmann::json::array();+ for (const auto& row : result.rows) {+ nlohmann::json r = nlohmann::json::object();+ for (std::size_t i = 0; i < result.columns.size() && i < row.size(); ++i) {+ r[result.columns[i].name] = row[i].displayString();+ }+ rows.push_back(std::move(r));+ }++ std::string header = "Sample " + std::to_string(rows.size()) + " row(s) from '" + tableName + "':\n";+ std::string cols = "Columns: ";+ for (std::size_t i = 0; i < result.columns.size(); ++i) {+ if (i > 0) cols += ", ";+ cols += result.columns[i].name + " (" + result.columns[i].dataType + ")";+ }+ cols += "\n\n";+ return MCPToolResult::textResult(header + cols + rows.dump(2));+ }+};++} // namespace++std::shared_ptr<MCPTool> makeGetSampleRowsTool() {+ return std::make_shared<GetSampleRowsTool>();+}++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/Tools/Tier1/ListConnectionsTool.cpp b/linux/src/Services/MCP/Tools/Tier1/ListConnectionsTool.cppnew file mode 100644index 0000000..5e38bcc--- /dev/null+++ b/linux/src/Services/MCP/Tools/Tier1/ListConnectionsTool.cpp@@ -0,0 +1,56 @@+#include "Services/MCP/Tools/MCPTool.h"++namespace gridex::mcp {++namespace {++class ListConnectionsTool final : public MCPTool {+public:+ std::string name() const override { return "list_connections"; }+ std::string description() const override {+ return "List all configured database connections. Returns connection IDs, names, and types "+ "(postgres/mysql/sqlite/redis/mongodb/mssql).";+ }+ MCPPermissionTier tier() const override { return MCPPermissionTier::Schema; }++ nlohmann::json inputSchema() const override {+ return {{"type", "object"}, {"properties", nlohmann::json::object()}};+ }++ MCPToolResult execute(const nlohmann::json&, const MCPToolContext& ctx) override {+ if (!ctx.connectionProvider) {+ return MCPToolResult::errorResult("No connection provider available.");+ }+ auto configs = ctx.connectionProvider->listConnections();++ nlohmann::json arr = nlohmann::json::array();+ for (const auto& c : configs) {+ auto mode = ctx.permissionEngine->getMode(c.id);+ if (mode == MCPConnectionMode::Locked) continue;+ nlohmann::json entry = {+ {"id", c.id},+ {"name", c.name},+ {"type", std::string(rawValue(c.databaseType))},+ {"host", c.displayHost()},+ {"database", c.database.value_or("")},+ {"is_connected", false}, // pool state is opaque to MCP+ {"mcp_mode", std::string(rawValue(mode))},+ };+ arr.push_back(std::move(entry));+ }++ if (arr.empty()) {+ return MCPToolResult::textResult(+ "No connections available for MCP access. All connections are either locked or none exist.");+ }+ return MCPToolResult::textResult(arr.dump(2));+ }+};++} // namespace++std::shared_ptr<MCPTool> makeListConnectionsTool() {+ return std::make_shared<ListConnectionsTool>();+}++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/Tools/Tier1/ListRelationshipsTool.cpp b/linux/src/Services/MCP/Tools/Tier1/ListRelationshipsTool.cppnew file mode 100644index 0000000..1fab0cf--- /dev/null+++ b/linux/src/Services/MCP/Tools/Tier1/ListRelationshipsTool.cpp@@ -0,0 +1,97 @@+#include "Services/MCP/Tools/MCPTool.h"++namespace gridex::mcp {++namespace {++class ListRelationshipsTool final : public MCPTool {+public:+ std::string name() const override { return "list_relationships"; }+ std::string description() const override {+ return "List foreign key relationships for a table. Returns both incoming and outgoing references.";+ }+ MCPPermissionTier tier() const override { return MCPPermissionTier::Schema; }++ nlohmann::json inputSchema() const override {+ return {+ {"type", "object"},+ {"properties", {+ {"connection_id", {{"type", "string"}, {"description", "Connection identifier"}}},+ {"table_name", {{"type", "string"}, {"description", "Name of the table"}}},+ }},+ {"required", nlohmann::json::array({"connection_id", "table_name"})},+ };+ }++ MCPToolResult execute(const nlohmann::json& params, const MCPToolContext& ctx) override {+ const std::string connectionId = MCPTool::extractConnectionId(params);+ if (!params.contains("table_name") || !params["table_name"].is_string()) {+ throw MCPToolError::invalidParameters("table_name is required");+ }+ const std::string tableName = params["table_name"].get<std::string>();++ auto perm = ctx.checkPermission(tier(), connectionId);+ if (!perm.isAllowed() && !perm.requiresUserApproval()) {+ throw MCPToolError::permissionDenied(perm.errorMessage());+ }++ auto [adapter, config] = ctx.getAdapter(connectionId);+ auto outgoing = adapter->listForeignKeys(tableName, std::nullopt);++ // Incoming: scan other tables for FKs pointing back at us.+ std::vector<std::pair<std::string, ForeignKeyInfo>> incoming; // (from_table, fk)+ try {+ auto allTables = adapter->listTables(std::nullopt);+ for (const auto& t : allTables) {+ if (t.name == tableName) continue;+ auto fks = adapter->listForeignKeys(t.name, std::nullopt);+ for (const auto& fk : fks) {+ if (fk.referencedTable == tableName) incoming.emplace_back(t.name, fk);+ }+ }+ } catch (...) {+ // Expensive scan may fail on huge DBs; treat as no incoming.+ }++ nlohmann::json result = {{"table", tableName}};++ if (!outgoing.empty()) {+ nlohmann::json out = nlohmann::json::array();+ for (const auto& fk : outgoing) {+ out.push_back({+ {"name", fk.name.value_or("")},+ {"columns", fk.columns},+ {"references_table", fk.referencedTable},+ {"references_columns", fk.referencedColumns},+ });+ }+ result["outgoing"] = out;+ } else {+ result["outgoing"] = "None";+ }++ if (!incoming.empty()) {+ nlohmann::json in = nlohmann::json::array();+ for (const auto& [fromTable, fk] : incoming) {+ in.push_back({+ {"from_table", fromTable},+ {"from_columns", fk.columns},+ {"to_columns", fk.referencedColumns},+ });+ }+ result["incoming"] = in;+ } else {+ result["incoming"] = "None";+ }++ return MCPToolResult::textResult(result.dump(2));+ }+};++} // namespace++std::shared_ptr<MCPTool> makeListRelationshipsTool() {+ return std::make_shared<ListRelationshipsTool>();+}++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/Tools/Tier1/ListSchemasTool.cpp b/linux/src/Services/MCP/Tools/Tier1/ListSchemasTool.cppnew file mode 100644index 0000000..b73e87a--- /dev/null+++ b/linux/src/Services/MCP/Tools/Tier1/ListSchemasTool.cpp@@ -0,0 +1,53 @@+#include "Services/MCP/Tools/MCPTool.h"++namespace gridex::mcp {++namespace {++class ListSchemasTool final : public MCPTool {+public:+ std::string name() const override { return "list_schemas"; }+ std::string description() const override {+ return "List schemas/databases available in a connection.";+ }+ MCPPermissionTier tier() const override { return MCPPermissionTier::Schema; }++ nlohmann::json inputSchema() const override {+ return {+ {"type", "object"},+ {"properties", {+ {"connection_id", {{"type", "string"}, {"description", "Connection identifier"}}},+ }},+ {"required", nlohmann::json::array({"connection_id"})},+ };+ }++ MCPToolResult execute(const nlohmann::json& params, const MCPToolContext& ctx) override {+ const std::string connectionId = MCPTool::extractConnectionId(params);++ auto perm = ctx.checkPermission(tier(), connectionId);+ if (!perm.isAllowed() && !perm.requiresUserApproval()) {+ throw MCPToolError::permissionDenied(perm.errorMessage());+ }++ auto [adapter, config] = ctx.getAdapter(connectionId);++ if (supportsSchemas(config.databaseType)) {+ auto schemas = adapter->listSchemas(std::nullopt);+ if (schemas.empty()) return MCPToolResult::textResult("No schemas found.");+ return MCPToolResult::textResult("Schemas: " + nlohmann::json(schemas).dump());+ }++ auto dbs = adapter->listDatabases();+ if (dbs.empty()) return MCPToolResult::textResult("No databases found.");+ return MCPToolResult::textResult("Databases: " + nlohmann::json(dbs).dump());+ }+};++} // namespace++std::shared_ptr<MCPTool> makeListSchemasTool() {+ return std::make_shared<ListSchemasTool>();+}++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/Tools/Tier1/ListTablesTool.cpp b/linux/src/Services/MCP/Tools/Tier1/ListTablesTool.cppnew file mode 100644index 0000000..24fbf8f--- /dev/null+++ b/linux/src/Services/MCP/Tools/Tier1/ListTablesTool.cpp@@ -0,0 +1,72 @@+#include "Services/MCP/Tools/MCPTool.h"+#include "Services/MCP/Tools/ToolHelpers.h"++namespace gridex::mcp {++namespace {++class ListTablesTool final : public MCPTool {+public:+ std::string name() const override { return "list_tables"; }+ std::string description() const override {+ return "List all tables in a database connection. Returns table names, schemas, and "+ "approximate row counts.";+ }+ MCPPermissionTier tier() const override { return MCPPermissionTier::Schema; }++ nlohmann::json inputSchema() const override {+ return {+ {"type", "object"},+ {"properties", {+ {"connection_id", {{"type", "string"}, {"description", "Connection identifier"}}},+ {"schema", {{"type", "string"}, {"description", "Optional schema/database filter"}}},+ }},+ {"required", nlohmann::json::array({"connection_id"})},+ };+ }++ MCPToolResult execute(const nlohmann::json& params, const MCPToolContext& ctx) override {+ const std::string connectionId = MCPTool::extractConnectionId(params);++ auto perm = ctx.checkPermission(tier(), connectionId);+ if (!perm.isAllowed() && !perm.requiresUserApproval()) {+ throw MCPToolError::permissionDenied(perm.errorMessage());+ }++ auto [adapter, config] = ctx.getAdapter(connectionId);+ std::optional<std::string> schemaFilter;+ if (params.contains("schema") && params["schema"].is_string()) {+ schemaFilter = params["schema"].get<std::string>();+ }++ auto tables = adapter->listTables(schemaFilter);++ nlohmann::json arr = nlohmann::json::array();+ for (const auto& t : tables) {+ nlohmann::json e = {+ {"name", t.name},+ {"type", std::string(rawValue(t.type))},+ };+ if (t.schema) e["schema"] = *t.schema;+ if (t.estimatedRowCount) e["estimated_rows"] = *t.estimatedRowCount;+ arr.push_back(std::move(e));+ }++ if (arr.empty()) {+ std::string msg = "No tables found";+ if (schemaFilter) msg += " in schema '" + *schemaFilter + "'";+ msg += ".";+ return MCPToolResult::textResult(msg);+ }+ return MCPToolResult::textResult(+ "Found " + std::to_string(arr.size()) + " table(s):\n" + arr.dump(2));+ }+};++} // namespace++std::shared_ptr<MCPTool> makeListTablesTool() {+ return std::make_shared<ListTablesTool>();+}++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/Tools/Tier2/ExplainQueryTool.cpp b/linux/src/Services/MCP/Tools/Tier2/ExplainQueryTool.cppnew file mode 100644index 0000000..2648a3f--- /dev/null+++ b/linux/src/Services/MCP/Tools/Tier2/ExplainQueryTool.cpp@@ -0,0 +1,85 @@+#include "Services/MCP/Tools/MCPTool.h"++namespace gridex::mcp {++namespace {++class ExplainQueryTool final : public MCPTool {+public:+ std::string name() const override { return "explain_query"; }+ std::string description() const override {+ return "Get EXPLAIN plan for a query without executing it. Helps AI understand query performance.";+ }+ MCPPermissionTier tier() const override { return MCPPermissionTier::Read; }++ nlohmann::json inputSchema() const override {+ return {+ {"type", "object"},+ {"properties", {+ {"connection_id", {{"type", "string"}, {"description", "Connection identifier"}}},+ {"sql", {{"type", "string"}, {"description", "SQL query to explain"}}},+ }},+ {"required", nlohmann::json::array({"connection_id", "sql"})},+ };+ }++ MCPToolResult execute(const nlohmann::json& params, const MCPToolContext& ctx) override {+ const std::string connectionId = MCPTool::extractConnectionId(params);+ if (!params.contains("sql") || !params["sql"].is_string()) {+ throw MCPToolError::invalidParameters("sql is required");+ }+ const std::string sql = params["sql"].get<std::string>();++ auto perm = ctx.checkPermission(tier(), connectionId);+ if (!perm.isAllowed() && !perm.requiresUserApproval()) {+ throw MCPToolError::permissionDenied(perm.errorMessage());+ }++ auto [adapter, config] = ctx.getAdapter(connectionId);++ std::string explainSql;+ switch (config.databaseType) {+ case DatabaseType::PostgreSQL:+ explainSql = "EXPLAIN (ANALYZE false, COSTS true, FORMAT TEXT) " + sql;+ break;+ case DatabaseType::MySQL:+ explainSql = "EXPLAIN " + sql;+ break;+ case DatabaseType::SQLite:+ explainSql = "EXPLAIN QUERY PLAN " + sql;+ break;+ case DatabaseType::MSSQL:+ explainSql = "SET SHOWPLAN_TEXT ON; " + sql + "; SET SHOWPLAN_TEXT OFF";+ break;+ case DatabaseType::MongoDB:+ case DatabaseType::Redis:+ return MCPToolResult::textResult(+ std::string("EXPLAIN is not supported for ")+ + std::string(displayName(config.databaseType)) + " connections.",+ true);+ }++ auto result = adapter->executeRaw(explainSql);+ std::string out = "Query Plan for: " + sql + "\n\n";+ if (result.rows.empty()) {+ out += "No plan information available.";+ } else {+ for (const auto& row : result.rows) {+ for (std::size_t i = 0; i < row.size(); ++i) {+ if (i > 0) out += " | ";+ out += row[i].displayString();+ }+ out += "\n";+ }+ }+ return MCPToolResult::textResult(out);+ }+};++} // namespace++std::shared_ptr<MCPTool> makeExplainQueryTool() {+ return std::make_shared<ExplainQueryTool>();+}++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/Tools/Tier2/QueryTool.cpp b/linux/src/Services/MCP/Tools/Tier2/QueryTool.cppnew file mode 100644index 0000000..404a9bb--- /dev/null+++ b/linux/src/Services/MCP/Tools/Tier2/QueryTool.cpp@@ -0,0 +1,121 @@+#include <algorithm>+#include <chrono>++#include "Services/MCP/Tools/MCPTool.h"+#include "Services/MCP/Tools/ToolHelpers.h"++namespace gridex::mcp {++namespace {++class QueryTool final : public MCPTool {+public:+ std::string name() const override { return "query"; }+ std::string description() const override {+ return "Execute a SQL query. In read-only mode, only SELECT statements are allowed. Returns "+ "rows with metadata (column types, row count, execution time).";+ }+ MCPPermissionTier tier() const override { return MCPPermissionTier::Read; }++ nlohmann::json inputSchema() const override {+ return {+ {"type", "object"},+ {"properties", {+ {"connection_id", {{"type", "string"}, {"description", "Connection identifier"}}},+ {"sql", {{"type", "string"}, {"description", "SQL query"}}},+ {"params", {{"type", "array"}, {"description", "Parameters for placeholders"}}},+ {"row_limit", {{"type", "integer"},+ {"description", "Maximum rows (default 1000, max 10000)"},+ {"default", 1000}, {"maximum", 10000}}},+ }},+ {"required", nlohmann::json::array({"connection_id", "sql"})},+ };+ }++ MCPToolResult execute(const nlohmann::json& params, const MCPToolContext& ctx) override {+ const std::string connectionId = MCPTool::extractConnectionId(params);+ if (!params.contains("sql") || !params["sql"].is_string()) {+ throw MCPToolError::invalidParameters("sql is required");+ }+ const std::string sql = params["sql"].get<std::string>();+ int rowLimit = 1000;+ if (params.contains("row_limit") && params["row_limit"].is_number_integer()) {+ rowLimit = std::clamp(params["row_limit"].get<int>(), 1, 10000);+ }++ auto perm = ctx.checkPermission(tier(), connectionId);+ if (!perm.isAllowed() && !perm.requiresUserApproval()) {+ throw MCPToolError::permissionDenied(perm.errorMessage());+ }++ auto mode = ctx.permissionEngine->getMode(connectionId);+ if (mode == MCPConnectionMode::ReadOnly) {+ auto r = ctx.permissionEngine->validateReadOnlyQuery(sql);+ if (r.kind() == PermissionResult::Kind::Denied) {+ throw MCPToolError::permissionDenied(r.errorMessage());+ }+ }++ auto [adapter, config] = ctx.getAdapter(connectionId);++ std::string finalSql = sql;+ std::string upper = toUpperAscii(sql);+ if (upper.find("LIMIT") == std::string::npos && isSQL(config.databaseType)) {+ std::string trimmed = trimSpaces(sql);+ while (!trimmed.empty() && trimmed.back() == ';') trimmed.pop_back();+ finalSql = trimmed + " LIMIT " + std::to_string(rowLimit);+ }++ std::vector<RowValue> queryParams;+ if (params.contains("params") && params["params"].is_array()) {+ for (const auto& p : params["params"]) queryParams.push_back(jsonToRowValue(p));+ }++ auto start = std::chrono::steady_clock::now();+ QueryResult result = queryParams.empty()+ ? adapter->executeRaw(finalSql)+ : adapter->executeWithRowValues(finalSql, queryParams);+ int durationMs = static_cast<int>(std::chrono::duration_cast<std::chrono::milliseconds>(+ std::chrono::steady_clock::now() - start).count());++ nlohmann::json cols = nlohmann::json::array();+ for (const auto& c : result.columns) {+ nlohmann::json j = {{"name", c.name}, {"type", c.dataType}};+ if (c.isNullable) j["nullable"] = true;+ cols.push_back(std::move(j));+ }++ nlohmann::json rows = nlohmann::json::array();+ std::size_t count = std::min<std::size_t>(result.rows.size(), static_cast<std::size_t>(rowLimit));+ for (std::size_t i = 0; i < count; ++i) {+ const auto& row = result.rows[i];+ nlohmann::json r = nlohmann::json::object();+ for (std::size_t k = 0; k < result.columns.size() && k < row.size(); ++k) {+ r[result.columns[k].name] = row[k].displayString();+ }+ rows.push_back(std::move(r));+ }++ nlohmann::json resp = {+ {"success", true},+ {"row_count", result.rowCount()},+ {"execution_time_ms", durationMs},+ {"columns", cols},+ {"rows", rows},+ };+ if (result.rowsAffected > 0) resp["rows_affected"] = result.rowsAffected;+ if (result.rows.size() > static_cast<std::size_t>(rowLimit)) {+ resp["truncated"] = true;+ resp["message"] = "Results truncated to " + std::to_string(rowLimit) + " rows";+ }+ return MCPToolResult::textResult(resp.dump(2));+ }+};++} // namespace++std::shared_ptr<MCPTool> makeQueryTool() {+ return std::make_shared<QueryTool>();+}++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/Tools/Tier2/SearchAcrossTablesTool.cpp b/linux/src/Services/MCP/Tools/Tier2/SearchAcrossTablesTool.cppnew file mode 100644index 0000000..c3f8859--- /dev/null+++ b/linux/src/Services/MCP/Tools/Tier2/SearchAcrossTablesTool.cpp@@ -0,0 +1,96 @@+#include "Services/MCP/Tools/MCPTool.h"+#include "Services/MCP/Tools/ToolHelpers.h"++namespace gridex::mcp {++namespace {++class SearchAcrossTablesTool final : public MCPTool {+public:+ std::string name() const override { return "search_across_tables"; }+ std::string description() const override {+ return "Search for a keyword across table names, column names, and column comments. "+ "Useful for discovering relevant data.";+ }+ MCPPermissionTier tier() const override { return MCPPermissionTier::Read; }++ nlohmann::json inputSchema() const override {+ return {+ {"type", "object"},+ {"properties", {+ {"connection_id", {{"type", "string"}, {"description", "Connection identifier"}}},+ {"keyword", {{"type", "string"}, {"description", "Keyword to search for"}}},+ }},+ {"required", nlohmann::json::array({"connection_id", "keyword"})},+ };+ }++ MCPToolResult execute(const nlohmann::json& params, const MCPToolContext& ctx) override {+ const std::string connectionId = MCPTool::extractConnectionId(params);+ if (!params.contains("keyword") || !params["keyword"].is_string()) {+ throw MCPToolError::invalidParameters("keyword is required");+ }+ const std::string keyword = params["keyword"].get<std::string>();++ auto perm = ctx.checkPermission(tier(), connectionId);+ if (!perm.isAllowed() && !perm.requiresUserApproval()) {+ throw MCPToolError::permissionDenied(perm.errorMessage());+ }++ auto [adapter, config] = ctx.getAdapter(connectionId);+ const std::string needle = toLowerAscii(keyword);++ auto contains = [&](const std::string& hay) {+ return toLowerAscii(hay).find(needle) != std::string::npos;+ };++ nlohmann::json matches = nlohmann::json::array();+ auto tables = adapter->listTables(std::nullopt);+ for (const auto& t : tables) {+ if (contains(t.name)) {+ matches.push_back({{"type", "table"}, {"table", t.name}, {"match", t.name}});+ }+ auto desc = adapter->describeTable(t.name, std::nullopt);+ for (const auto& col : desc.columns) {+ if (contains(col.name)) {+ matches.push_back({+ {"type", "column"},+ {"table", t.name},+ {"column", col.name},+ {"data_type", col.dataType},+ });+ }+ if (col.comment && contains(*col.comment)) {+ matches.push_back({+ {"type", "column_comment"},+ {"table", t.name},+ {"column", col.name},+ {"comment", *col.comment},+ });+ }+ }+ if (desc.comment && contains(*desc.comment)) {+ matches.push_back({+ {"type", "table_comment"},+ {"table", t.name},+ {"comment", *desc.comment},+ });+ }+ }++ if (matches.empty()) {+ return MCPToolResult::textResult("No matches found for '" + keyword + "'.");+ }+ return MCPToolResult::textResult(+ "Found " + std::to_string(matches.size()) + " match(es) for '" + keyword + "':\n"+ + matches.dump(2));+ }+};++} // namespace++std::shared_ptr<MCPTool> makeSearchAcrossTablesTool() {+ return std::make_shared<SearchAcrossTablesTool>();+}++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/Tools/Tier3/DeleteRowsTool.cpp b/linux/src/Services/MCP/Tools/Tier3/DeleteRowsTool.cppnew file mode 100644index 0000000..c612a25--- /dev/null+++ b/linux/src/Services/MCP/Tools/Tier3/DeleteRowsTool.cpp@@ -0,0 +1,85 @@+#include "Services/MCP/Tools/MCPTool.h"+#include "Services/MCP/Tools/ToolHelpers.h"+#include "Services/MCP/Security/IdentifierValidator.h"+#include "Services/MCP/Security/RowCountEstimator.h"++namespace gridex::mcp {++namespace {++class DeleteRowsTool final : public MCPTool {+public:+ std::string name() const override { return "delete_rows"; }+ std::string description() const override {+ return "Delete rows matching WHERE clause. Requires user approval. WHERE clause is MANDATORY.";+ }+ MCPPermissionTier tier() const override { return MCPPermissionTier::Write; }++ nlohmann::json inputSchema() const override {+ return {+ {"type", "object"},+ {"properties", {+ {"connection_id", {{"type", "string"}, {"description", "Connection identifier"}}},+ {"table_name", {{"type", "string"}, {"description", "Name of the table"}}},+ {"schema", {{"type", "string"}, {"description", "Optional schema name"}}},+ {"where", {{"type", "string"}, {"description", "WHERE clause (required)"}}},+ {"where_params", {{"type", "array"}, {"description", "Parameters for WHERE clause"}}},+ }},+ {"required", nlohmann::json::array({"connection_id", "table_name", "where"})},+ };+ }++ MCPToolResult execute(const nlohmann::json& params, const MCPToolContext& ctx) override {+ const std::string connectionId = MCPTool::extractConnectionId(params);+ auto [tableName, schemaName] = IdentifierValidator::extractTableAndSchema(params);++ if (!params.contains("where") || !params["where"].is_string()) {+ throw MCPToolError::invalidParameters(+ "where clause is required. Bare DELETE without WHERE is not allowed.");+ }+ const std::string whereClause = params["where"].get<std::string>();++ auto whereCheck = ctx.permissionEngine->validateWhereClause(whereClause);+ if (whereCheck.kind() == PermissionResult::Kind::Denied) {+ throw MCPToolError::permissionDenied(whereCheck.errorMessage());+ }++ auto perm = ctx.checkPermission(tier(), connectionId);+ if (perm.kind() == PermissionResult::Kind::Denied) {+ throw MCPToolError::permissionDenied(perm.errorMessage());+ }++ auto [adapter, config] = ctx.getAdapter(connectionId);+ SQLDialect dialect = sqlDialect(config.databaseType);+ std::string qualifiedTable = qualifiedIdentifier(dialect, tableName, schemaName);+ std::string deleteSql = "DELETE FROM " + qualifiedTable + " WHERE " + whereClause;++ int estimated = RowCountEstimator::estimate(*adapter, qualifiedTable, whereClause, config);++ if (perm.requiresUserApproval()) {+ std::string details = "SQL: " + deleteSql + "\n\nEstimated rows to delete: "+ + std::to_string(estimated)+ + "\n\nThis operation cannot be undone!";+ bool approved = ctx.requestApproval(+ name(),+ "Delete rows from '" + tableName + "' where " + whereClause,+ details,+ connectionId);+ if (!approved) throw MCPToolError::permissionDenied("User denied the operation.");+ }++ auto result = adapter->executeRaw(deleteSql);+ ctx.recordUsage(tier(), connectionId);+ return MCPToolResult::textResult(+ "Successfully deleted " + std::to_string(result.rowsAffected)+ + " row(s) from '" + tableName + "'.");+ }+};++} // namespace++std::shared_ptr<MCPTool> makeDeleteRowsTool() {+ return std::make_shared<DeleteRowsTool>();+}++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/Tools/Tier3/ExecuteWriteQueryTool.cpp b/linux/src/Services/MCP/Tools/Tier3/ExecuteWriteQueryTool.cppnew file mode 100644index 0000000..cd7d09e--- /dev/null+++ b/linux/src/Services/MCP/Tools/Tier3/ExecuteWriteQueryTool.cpp@@ -0,0 +1,122 @@+#include "Services/MCP/Security/SQLSanitizer.h"+#include "Services/MCP/Tools/MCPTool.h"+#include "Services/MCP/Tools/ToolHelpers.h"++namespace gridex::mcp {++namespace {++bool containsWordUpper(const std::string& s, std::string_view word) {+ auto isWord = [](unsigned char c) { return std::isalnum(c) || c == '_'; };+ const std::size_t n = s.size(), m = word.size();+ for (std::size_t i = 0; i + m <= n; ++i) {+ if (i > 0 && isWord(static_cast<unsigned char>(s[i - 1]))) continue;+ if (i + m < n && isWord(static_cast<unsigned char>(s[i + m]))) continue;+ bool eq = true;+ for (std::size_t k = 0; k < m; ++k) {+ if (s[i + k] != word[k]) { eq = false; break; }+ }+ if (eq) return true;+ }+ return false;+}++class ExecuteWriteQueryTool final : public MCPTool {+public:+ std::string name() const override { return "execute_write_query"; }+ std::string description() const override {+ return "Execute one write SQL statement (INSERT/UPDATE/DELETE). Requires user approval. "+ "Only available in read-write mode. Multi-statement input is rejected.";+ }+ // Tier::Ddl because this is the broadest write tool and hits rate-limit bucket accordingly.+ MCPPermissionTier tier() const override { return MCPPermissionTier::Ddl; }++ nlohmann::json inputSchema() const override {+ return {+ {"type", "object"},+ {"properties", {+ {"connection_id", {{"type", "string"}, {"description", "Connection identifier"}}},+ {"sql", {{"type", "string"}, {"description", "A single SQL statement"}}},+ {"params", {{"type", "array"}, {"description", "Parameters for placeholders"}}},+ }},+ {"required", nlohmann::json::array({"connection_id", "sql"})},+ };+ }++ MCPToolResult execute(const nlohmann::json& params, const MCPToolContext& ctx) override {+ const std::string connectionId = MCPTool::extractConnectionId(params);+ if (!params.contains("sql") || !params["sql"].is_string()) {+ throw MCPToolError::invalidParameters("sql is required");+ }+ const std::string sql = params["sql"].get<std::string>();++ const std::string codeOnly = stripCommentsAndStrings(sql);+ std::string upper = toUpperAscii(trimSpaces(codeOnly));++ std::string noSemi = upper;+ if (!noSemi.empty() && noSemi.back() == ';') noSemi.pop_back();+ noSemi = trimSpaces(noSemi);+ if (noSemi.find(';') != std::string::npos) {+ throw MCPToolError::invalidParameters(+ "Multiple statements are not allowed. Send one statement at a time.");+ }++ auto perm = ctx.checkPermission(tier(), connectionId);+ if (perm.kind() == PermissionResult::Kind::Denied) {+ throw MCPToolError::permissionDenied(perm.errorMessage());+ }++ if (startsWith(upper, "SELECT") || startsWith(upper, "WITH")) {+ throw MCPToolError::invalidParameters(+ "Use the 'query' tool for SELECT / WITH statements. This tool is for write operations only.");+ }++ if (startsWith(upper, "UPDATE") || startsWith(upper, "DELETE")) {+ if (!containsWordUpper(upper, "WHERE")) {+ throw MCPToolError::permissionDenied(+ "UPDATE/DELETE without WHERE clause is not allowed.");+ }+ auto pos = upper.find("WHERE");+ if (pos != std::string::npos) {+ std::string whereClause = trimSpaces(codeOnly.substr(pos + 5));+ auto wr = ctx.permissionEngine->validateWhereClause(whereClause);+ if (wr.kind() == PermissionResult::Kind::Denied) {+ throw MCPToolError::permissionDenied(wr.errorMessage());+ }+ }+ }++ auto [adapter, config] = ctx.getAdapter(connectionId);++ if (perm.requiresUserApproval()) {+ bool approved = ctx.requestApproval(+ name(), "Execute write query", "SQL:\n" + sql, connectionId);+ if (!approved) throw MCPToolError::permissionDenied("User denied the operation.");+ }++ std::vector<RowValue> rowParams;+ if (params.contains("params") && params["params"].is_array()) {+ for (const auto& p : params["params"]) rowParams.push_back(jsonToRowValue(p));+ }++ QueryResult result = rowParams.empty()+ ? adapter->executeRaw(sql)+ : adapter->executeWithRowValues(sql, rowParams);++ ctx.recordUsage(tier(), connectionId);++ std::string msg = "Query executed successfully.";+ if (result.rowsAffected > 0) {+ msg += " " + std::to_string(result.rowsAffected) + " row(s) affected.";+ }+ return MCPToolResult::textResult(msg);+ }+};++} // namespace++std::shared_ptr<MCPTool> makeExecuteWriteQueryTool() {+ return std::make_shared<ExecuteWriteQueryTool>();+}++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/Tools/Tier3/InsertRowsTool.cpp b/linux/src/Services/MCP/Tools/Tier3/InsertRowsTool.cppnew file mode 100644index 0000000..a1e220a--- /dev/null+++ b/linux/src/Services/MCP/Tools/Tier3/InsertRowsTool.cpp@@ -0,0 +1,88 @@+#include "Services/MCP/Tools/MCPTool.h"+#include "Services/MCP/Tools/ToolHelpers.h"+#include "Services/MCP/Security/IdentifierValidator.h"++namespace gridex::mcp {++namespace {++class InsertRowsTool final : public MCPTool {+public:+ std::string name() const override { return "insert_rows"; }+ std::string description() const override {+ return "Insert one or more rows into a table. Requires user approval. Returns affected count.";+ }+ MCPPermissionTier tier() const override { return MCPPermissionTier::Write; }++ nlohmann::json inputSchema() const override {+ return {+ {"type", "object"},+ {"properties", {+ {"connection_id", {{"type", "string"}, {"description", "Connection identifier"}}},+ {"table_name", {{"type", "string"}, {"description", "Name of the table to insert into"}}},+ {"schema", {{"type", "string"}, {"description", "Optional schema name"}}},+ {"rows", {{"type", "array"},+ {"description", "Array of row objects to insert"},+ {"items", {{"type", "object"}}}}},+ }},+ {"required", nlohmann::json::array({"connection_id", "table_name", "rows"})},+ };+ }++ MCPToolResult execute(const nlohmann::json& params, const MCPToolContext& ctx) override {+ const std::string connectionId = MCPTool::extractConnectionId(params);+ auto [tableName, schemaName] = IdentifierValidator::extractTableAndSchema(params);++ if (!params.contains("rows") || !params["rows"].is_array() || params["rows"].empty()) {+ throw MCPToolError::invalidParameters("rows must be a non-empty array");+ }+ const auto& rowsArr = params["rows"];++ auto perm = ctx.checkPermission(tier(), connectionId);+ if (perm.kind() == PermissionResult::Kind::Denied) {+ throw MCPToolError::permissionDenied(perm.errorMessage());+ }++ if (perm.requiresUserApproval()) {+ std::string preview;+ {+ nlohmann::json prev = nlohmann::json::array();+ std::size_t n = std::min<std::size_t>(rowsArr.size(), 5);+ for (std::size_t i = 0; i < n; ++i) prev.push_back(rowsArr[i]);+ preview = prev.dump(2);+ if (rowsArr.size() > 5) {+ preview += "\n... and " + std::to_string(rowsArr.size() - 5) + " more rows";+ }+ }+ bool approved = ctx.requestApproval(+ name(),+ "Insert " + std::to_string(rowsArr.size()) + " row(s) into '" + tableName + "'",+ preview,+ connectionId);+ if (!approved) throw MCPToolError::permissionDenied("User denied the operation.");+ }++ auto [adapter, config] = ctx.getAdapter(connectionId);+ int inserted = 0;+ for (const auto& rowVal : rowsArr) {+ if (!rowVal.is_object()) continue;+ std::unordered_map<std::string, RowValue> values;+ for (auto it = rowVal.begin(); it != rowVal.end(); ++it) {+ values[it.key()] = jsonToRowValue(it.value());+ }+ (void)adapter->insertRow(tableName, schemaName, values);+ ++inserted;+ }+ ctx.recordUsage(tier(), connectionId);+ return MCPToolResult::textResult(+ "Successfully inserted " + std::to_string(inserted) + " row(s) into '" + tableName + "'.");+ }+};++} // namespace++std::shared_ptr<MCPTool> makeInsertRowsTool() {+ return std::make_shared<InsertRowsTool>();+}++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/Tools/Tier3/UpdateRowsTool.cpp b/linux/src/Services/MCP/Tools/Tier3/UpdateRowsTool.cppnew file mode 100644index 0000000..9f6673f--- /dev/null+++ b/linux/src/Services/MCP/Tools/Tier3/UpdateRowsTool.cpp@@ -0,0 +1,105 @@+#include "Services/MCP/Tools/MCPTool.h"+#include "Services/MCP/Tools/ToolHelpers.h"+#include "Services/MCP/Security/IdentifierValidator.h"+#include "Services/MCP/Security/RowCountEstimator.h"++namespace gridex::mcp {++namespace {++class UpdateRowsTool final : public MCPTool {+public:+ std::string name() const override { return "update_rows"; }+ std::string description() const override {+ return "Update rows matching WHERE clause. Requires user approval. WHERE clause is "+ "MANDATORY (no bare UPDATE).";+ }+ MCPPermissionTier tier() const override { return MCPPermissionTier::Write; }++ nlohmann::json inputSchema() const override {+ return {+ {"type", "object"},+ {"properties", {+ {"connection_id", {{"type", "string"}, {"description", "Connection identifier"}}},+ {"table_name", {{"type", "string"}, {"description", "Name of the table"}}},+ {"schema", {{"type", "string"}, {"description", "Optional schema name"}}},+ {"set", {{"type", "object"}, {"description", "Column-value pairs to update"}}},+ {"where", {{"type", "string"}, {"description", "WHERE clause (required)"}}},+ {"where_params", {{"type", "array"}, {"description", "Parameters for WHERE clause"}}},+ }},+ {"required", nlohmann::json::array({"connection_id", "table_name", "set", "where"})},+ };+ }++ MCPToolResult execute(const nlohmann::json& params, const MCPToolContext& ctx) override {+ const std::string connectionId = MCPTool::extractConnectionId(params);+ auto [tableName, schemaName] = IdentifierValidator::extractTableAndSchema(params);++ if (!params.contains("set") || !params["set"].is_object() || params["set"].empty()) {+ throw MCPToolError::invalidParameters(+ "set must be a non-empty object with column-value pairs");+ }+ const auto& setObj = params["set"];+ for (auto it = setObj.begin(); it != setObj.end(); ++it) {+ IdentifierValidator::validate(it.key(), "column name");+ }++ if (!params.contains("where") || !params["where"].is_string()) {+ throw MCPToolError::invalidParameters(+ "where clause is required. Bare UPDATE without WHERE is not allowed.");+ }+ const std::string whereClause = params["where"].get<std::string>();++ auto whereCheck = ctx.permissionEngine->validateWhereClause(whereClause);+ if (whereCheck.kind() == PermissionResult::Kind::Denied) {+ throw MCPToolError::permissionDenied(whereCheck.errorMessage());+ }++ auto perm = ctx.checkPermission(tier(), connectionId);+ if (perm.kind() == PermissionResult::Kind::Denied) {+ throw MCPToolError::permissionDenied(perm.errorMessage());+ }++ auto [adapter, config] = ctx.getAdapter(connectionId);+ SQLDialect dialect = sqlDialect(config.databaseType);+ std::string qualifiedTable = qualifiedIdentifier(dialect, tableName, schemaName);++ std::string setClause;+ bool first = true;+ for (auto it = setObj.begin(); it != setObj.end(); ++it) {+ if (!first) setClause += ", ";+ first = false;+ setClause += quoteIdentifier(dialect, it.key()) + " = "+ + formatValueForSQL(it.value(), dialect);+ }+ std::string updateSql = "UPDATE " + qualifiedTable + " SET " + setClause+ + " WHERE " + whereClause;++ int estimated = RowCountEstimator::estimate(*adapter, qualifiedTable, whereClause, config);++ if (perm.requiresUserApproval()) {+ std::string details = "SQL: " + updateSql + "\n\nEstimated rows affected: "+ + std::to_string(estimated);+ bool approved = ctx.requestApproval(+ name(),+ "Update rows in '" + tableName + "' where " + whereClause,+ details,+ connectionId);+ if (!approved) throw MCPToolError::permissionDenied("User denied the operation.");+ }++ auto result = adapter->executeRaw(updateSql);+ ctx.recordUsage(tier(), connectionId);+ return MCPToolResult::textResult(+ "Successfully updated " + std::to_string(result.rowsAffected)+ + " row(s) in '" + tableName + "'.");+ }+};++} // namespace++std::shared_ptr<MCPTool> makeUpdateRowsTool() {+ return std::make_shared<UpdateRowsTool>();+}++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/Tools/ToolHelpers.h b/linux/src/Services/MCP/Tools/ToolHelpers.hnew file mode 100644index 0000000..6eb550e--- /dev/null+++ b/linux/src/Services/MCP/Tools/ToolHelpers.h@@ -0,0 +1,84 @@+#pragma once++// Shared helpers for MCP tool implementations.++#include <optional>+#include <string>++#include <nlohmann/json.hpp>++#include "Core/Enums/SQLDialect.h"+#include "Core/Models/Database/RowValue.h"++namespace gridex::mcp {++inline RowValue jsonToRowValue(const nlohmann::json& v) {+ if (v.is_null()) return RowValue::makeNull();+ if (v.is_boolean()) return RowValue::makeBoolean(v.get<bool>());+ if (v.is_number_integer()) return RowValue::makeInteger(v.get<std::int64_t>());+ if (v.is_number_float()) return RowValue::makeDouble(v.get<double>());+ if (v.is_string()) return RowValue::makeString(v.get<std::string>());+ if (v.is_array() || v.is_object()) return RowValue::makeJson(v.dump());+ return RowValue::makeNull();+}++inline std::string formatValueForSQL(const nlohmann::json& v, SQLDialect dialect) {+ if (v.is_null()) return "NULL";+ if (v.is_boolean()) {+ bool b = v.get<bool>();+ return dialect == SQLDialect::PostgreSQL+ ? (b ? "true" : "false")+ : (b ? "1" : "0");+ }+ if (v.is_number_integer()) return std::to_string(v.get<std::int64_t>());+ if (v.is_number_float()) return std::to_string(v.get<double>());+ auto escape = [](const std::string& s) {+ std::string out;+ out.reserve(s.size() + 2);+ out.push_back('\'');+ for (char c : s) {+ if (c == '\'') out.push_back('\'');+ out.push_back(c);+ }+ out.push_back('\'');+ return out;+ };+ if (v.is_string()) return escape(v.get<std::string>());+ return escape(v.dump());+}++inline std::string qualifiedIdentifier(SQLDialect dialect,+ const std::string& name,+ const std::optional<std::string>& schema) {+ if (schema && !schema->empty()) {+ return quoteIdentifier(dialect, *schema) + "." + quoteIdentifier(dialect, name);+ }+ return quoteIdentifier(dialect, name);+}++inline std::string toLowerAscii(std::string s) {+ for (auto& c : s) {+ if (c >= 'A' && c <= 'Z') c = static_cast<char>(c + ('a' - 'A'));+ }+ return s;+}++inline std::string toUpperAscii(std::string s) {+ for (auto& c : s) {+ if (c >= 'a' && c <= 'z') c = static_cast<char>(c - ('a' - 'A'));+ }+ return s;+}++inline std::string trimSpaces(std::string s) {+ auto b = s.find_first_not_of(" \t\r\n");+ if (b == std::string::npos) return "";+ auto e = s.find_last_not_of(" \t\r\n");+ return s.substr(b, e - b + 1);+}++inline bool startsWith(const std::string& s, std::string_view prefix) {+ return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());+}++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/Tools/ToolRegistry.cpp b/linux/src/Services/MCP/Tools/ToolRegistry.cppnew file mode 100644index 0000000..77d4725--- /dev/null+++ b/linux/src/Services/MCP/Tools/ToolRegistry.cpp@@ -0,0 +1,72 @@+#include "Services/MCP/Tools/ToolRegistry.h"++// Built-in tool forward declarations. The concrete classes live in+// Tier1/, Tier2/, Tier3/ subdirectories.+namespace gridex::mcp {+std::shared_ptr<MCPTool> makeListConnectionsTool();+std::shared_ptr<MCPTool> makeListTablesTool();+std::shared_ptr<MCPTool> makeDescribeTableTool();+std::shared_ptr<MCPTool> makeListSchemasTool();+std::shared_ptr<MCPTool> makeGetSampleRowsTool();+std::shared_ptr<MCPTool> makeListRelationshipsTool();+std::shared_ptr<MCPTool> makeQueryTool();+std::shared_ptr<MCPTool> makeExplainQueryTool();+std::shared_ptr<MCPTool> makeSearchAcrossTablesTool();+std::shared_ptr<MCPTool> makeInsertRowsTool();+std::shared_ptr<MCPTool> makeUpdateRowsTool();+std::shared_ptr<MCPTool> makeDeleteRowsTool();+std::shared_ptr<MCPTool> makeExecuteWriteQueryTool();++ToolRegistry::ToolRegistry() = default;+ToolRegistry::~ToolRegistry() = default;++void ToolRegistry::registerTool(std::shared_ptr<MCPTool> t) {+ if (!t) return;+ std::lock_guard lk(mu_);+ tools_[t->name()] = std::move(t);+}++void ToolRegistry::unregister(const std::string& name) {+ std::lock_guard lk(mu_);+ tools_.erase(name);+}++std::shared_ptr<MCPTool> ToolRegistry::get(const std::string& name) const {+ std::lock_guard lk(mu_);+ auto it = tools_.find(name);+ return it != tools_.end() ? it->second : nullptr;+}++std::vector<std::shared_ptr<MCPTool>> ToolRegistry::all() const {+ std::lock_guard lk(mu_);+ std::vector<std::shared_ptr<MCPTool>> out;+ out.reserve(tools_.size());+ for (const auto& [_, t] : tools_) out.push_back(t);+ return out;+}++std::vector<MCPToolDefinition> ToolRegistry::definitions() const {+ std::lock_guard lk(mu_);+ std::vector<MCPToolDefinition> out;+ out.reserve(tools_.size());+ for (const auto& [_, t] : tools_) out.push_back(t->definition());+ return out;+}++void ToolRegistry::registerBuiltins() {+ registerTool(makeListConnectionsTool());+ registerTool(makeListTablesTool());+ registerTool(makeDescribeTableTool());+ registerTool(makeListSchemasTool());+ registerTool(makeGetSampleRowsTool());+ registerTool(makeListRelationshipsTool());+ registerTool(makeQueryTool());+ registerTool(makeExplainQueryTool());+ registerTool(makeSearchAcrossTablesTool());+ registerTool(makeInsertRowsTool());+ registerTool(makeUpdateRowsTool());+ registerTool(makeDeleteRowsTool());+ registerTool(makeExecuteWriteQueryTool());+}++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/Tools/ToolRegistry.h b/linux/src/Services/MCP/Tools/ToolRegistry.hnew file mode 100644index 0000000..b874d5d--- /dev/null+++ b/linux/src/Services/MCP/Tools/ToolRegistry.h@@ -0,0 +1,33 @@+#pragma once++#include <memory>+#include <mutex>+#include <string>+#include <unordered_map>+#include <vector>++#include "Services/MCP/Tools/MCPTool.h"++namespace gridex::mcp {++class ToolRegistry {+public:+ ToolRegistry();+ ~ToolRegistry();++ void registerTool(std::shared_ptr<MCPTool> tool);+ void unregister(const std::string& name);++ std::shared_ptr<MCPTool> get(const std::string& name) const;+ std::vector<std::shared_ptr<MCPTool>> all() const;+ std::vector<MCPToolDefinition> definitions() const;++ // Registers all built-in tools (Tier 1-3).+ void registerBuiltins();++private:+ mutable std::mutex mu_;+ std::unordered_map<std::string, std::shared_ptr<MCPTool>> tools_;+};++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/Transport/StdioTransport.cpp b/linux/src/Services/MCP/Transport/StdioTransport.cppnew file mode 100644index 0000000..7444586--- /dev/null+++ b/linux/src/Services/MCP/Transport/StdioTransport.cpp@@ -0,0 +1,66 @@+#include "Services/MCP/Transport/StdioTransport.h"++#include <iostream>+#include <string>++namespace gridex::mcp {++StdioTransport::StdioTransport() = default;+StdioTransport::~StdioTransport() { stop(); }++void StdioTransport::setHandler(RequestHandler h) {+ std::lock_guard lk(handlerMu_);+ handler_ = std::move(h);+}++void StdioTransport::start() {+ bool expected = false;+ if (!running_.compare_exchange_strong(expected, true)) return;+ thread_ = std::thread(&StdioTransport::readLoop, this);+}++void StdioTransport::stop() {+ if (!running_.exchange(false)) return;+ // Note: std::cin is blocking on readLoop; we can't forcibly wake it. The+ // thread will exit when stdin closes (client disconnect). We detach so shutdown+ // isn't blocked. For an in-GUI lifecycle this is fine because the stdio server+ // only runs in --mcp-stdio mode where the process exits anyway.+ if (thread_.joinable()) thread_.detach();+}++void StdioTransport::readLoop() {+ std::string line;+ while (running_.load() && std::getline(std::cin, line)) {+ if (line.empty()) continue;+ try {+ auto j = nlohmann::json::parse(line);+ auto req = JSONRPCRequest::fromJson(j);+ RequestHandler h;+ {+ std::lock_guard lk(handlerMu_);+ h = handler_;+ }+ if (h) h(req);+ } catch (const std::exception&) {+ auto resp = JSONRPCResponse::err(nullptr, JSONRPCError::parseError());+ send(resp);+ }+ }+ running_ = false;+}++void StdioTransport::send(const JSONRPCResponse& response) {+ std::lock_guard lk(writeMu_);+ std::cout << response.toJson().dump() << '\n';+ std::cout.flush();+}++void StdioTransport::sendNotification(const std::string& method, const nlohmann::json& params) {+ std::lock_guard lk(writeMu_);+ nlohmann::json n = {{"jsonrpc", "2.0"}, {"method", method}};+ if (!params.is_null()) n["params"] = params;+ std::cout << n.dump() << '\n';+ std::cout.flush();+}++} // namespace gridex::mcpdiff --git a/linux/src/Services/MCP/Transport/StdioTransport.h b/linux/src/Services/MCP/Transport/StdioTransport.hnew file mode 100644index 0000000..ec690ff--- /dev/null+++ b/linux/src/Services/MCP/Transport/StdioTransport.h@@ -0,0 +1,39 @@+#pragma once++#include <atomic>+#include <functional>+#include <mutex>+#include <thread>++#include "Services/MCP/Protocol.h"++namespace gridex::mcp {++// Reads line-delimited JSON-RPC 2.0 from stdin, invokes a delegate on each request,+// writes responses to stdout. Blocking read on a dedicated thread.+class StdioTransport {+public:+ using RequestHandler = std::function<void(const JSONRPCRequest&)>;++ StdioTransport();+ ~StdioTransport();++ void setHandler(RequestHandler h);++ void start();+ void stop();++ void send(const JSONRPCResponse& response);+ void sendNotification(const std::string& method, const nlohmann::json& params);++private:+ void readLoop();++ std::atomic<bool> running_{false};+ std::thread thread_;+ std::mutex writeMu_;+ std::mutex handlerMu_;+ RequestHandler handler_;+};++} // namespace gridex::mcpdiff --git a/linux/src/Services/SSH/SSHTunnelManager.cpp b/linux/src/Services/SSH/SSHTunnelManager.cppnew file mode 100644index 0000000..6720833--- /dev/null+++ b/linux/src/Services/SSH/SSHTunnelManager.cpp@@ -0,0 +1,320 @@+#include "Services/SSH/SSHTunnelManager.h"++#include <arpa/inet.h>+#include <atomic>+#include <cstring>+#include <libssh/libssh.h>+#include <netinet/in.h>+#include <poll.h>+#include <sys/socket.h>+#include <thread>+#include <unistd.h>++#include "Core/Errors/GridexError.h"++namespace gridex {++struct SSHTunnelManager::Tunnel {+ std::string connectionId;+ std::uint16_t localPort = 0;+ std::atomic<Status> status{Status::Connecting};+ std::atomic<bool> stopFlag{false};+ std::thread thread;+ ssh_session sshSession = nullptr;+ int listenFd = -1;++ ~Tunnel() {+ stopFlag.store(true, std::memory_order_release);+ // Close listen socket to unblock accept().+ if (listenFd >= 0) { ::shutdown(listenFd, SHUT_RDWR); ::close(listenFd); listenFd = -1; }+ // Set SO_RCVTIMEO on SSH fd to unblock any blocking libssh call (H1 fix).+ if (sshSession) {+ const int sshFd = ssh_get_fd(sshSession);+ if (sshFd >= 0) {+ struct timeval tv{0, 500000}; // 500ms+ ::setsockopt(sshFd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));+ }+ }+ if (thread.joinable()) thread.join();+ if (sshSession) { ssh_disconnect(sshSession); ssh_free(sshSession); sshSession = nullptr; }+ }+};++namespace {++// Bind a TCP socket to 127.0.0.1:0 and return fd + assigned port.+std::pair<int, std::uint16_t> bindFreePort() {+ int fd = ::socket(AF_INET, SOCK_STREAM, 0);+ if (fd < 0) throw ConnectionError("SSH tunnel: socket() failed");++ // L1: removed SO_REUSEADDR — unnecessary for ephemeral port 0.++ sockaddr_in addr{};+ addr.sin_family = AF_INET;+ addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);+ addr.sin_port = 0;+ if (::bind(fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) < 0) {+ ::close(fd);+ throw ConnectionError("SSH tunnel: bind() failed");+ }+ if (::listen(fd, 1) < 0) {+ ::close(fd);+ throw ConnectionError("SSH tunnel: listen() failed");+ }+ socklen_t len = sizeof(addr);+ ::getsockname(fd, reinterpret_cast<sockaddr*>(&addr), &len);+ return {fd, ntohs(addr.sin_port)};+}++ssh_session createSshSession(const SSHTunnelConfig& cfg) {+ ssh_session s = ssh_new();+ if (!s) throw ConnectionError("SSH tunnel: ssh_new() failed");++ ssh_options_set(s, SSH_OPTIONS_HOST, cfg.host.c_str());+ int port = cfg.port;+ ssh_options_set(s, SSH_OPTIONS_PORT, &port);+ ssh_options_set(s, SSH_OPTIONS_USER, cfg.username.c_str());+ int timeout = 10;+ ssh_options_set(s, SSH_OPTIONS_TIMEOUT, &timeout);++ if (ssh_connect(s) != SSH_OK) {+ std::string msg = ssh_get_error(s);+ ssh_free(s);+ throw ConnectionError("SSH tunnel connect failed: " + msg);+ }++ // C2: Host key verification — warn on unknown/changed keys.+ // NOTE: Full interactive "accept new key?" UX deferred. For now, accept known+ // hosts from ~/.ssh/known_hosts and warn on CHANGED keys (MITM indicator).+ // Unknown keys are accepted silently (matches macOS AcceptAllHostKeysDelegate+ // behavior, documented as known security gap).+ const auto hkState = ssh_session_is_known_server(s);+ if (hkState == SSH_KNOWN_HOSTS_CHANGED) {+ ssh_disconnect(s);+ ssh_free(s);+ throw ConnectionError(+ "SSH host key CHANGED for " + cfg.host ++ " — possible MITM attack. Remove the old key from ~/.ssh/known_hosts if expected.");+ }+ // SSH_KNOWN_HOSTS_NOT_FOUND / SSH_KNOWN_HOSTS_UNKNOWN: accept (matches macOS).+ // Optionally write to known_hosts for future verification.+ if (hkState == SSH_KNOWN_HOSTS_OK) {+ // Already trusted — good.+ } else {+ // Unknown/not found — auto-accept and persist for next time.+ ssh_session_update_known_hosts(s);+ }++ // M3: Enable SSH keepalive to survive NAT/firewall idle timeouts.+ // Sends keepalive every 30 seconds after 2 missed responses.+ // (Requires libssh ≥ 0.8; ignored if unavailable.)+ // ssh_options_set(s, SSH_OPTIONS_NODELAY, &opt) not needed — TCP_NODELAY+ // is typically set by libssh on the control channel already.++ return s;+}++// Keyboard-interactive fallback — many OpenSSH servers use this instead of+// pure "password" auth. The server sends prompts; we answer with the password.+int tryKbdInteractive(ssh_session s, const char* pw) {+ int rc = ssh_userauth_kbdint(s, nullptr, nullptr);+ while (rc == SSH_AUTH_INFO) {+ const int nprompts = ssh_userauth_kbdint_getnprompts(s);+ for (int i = 0; i < nprompts; ++i) {+ ssh_userauth_kbdint_setanswer(s, static_cast<unsigned>(i), pw);+ }+ rc = ssh_userauth_kbdint(s, nullptr, nullptr);+ }+ return rc;+}++void authenticateSsh(ssh_session s, const SSHTunnelConfig& cfg,+ const std::optional<std::string>& password) {+ ssh_userauth_none(s, nullptr);++ int rc = SSH_AUTH_DENIED;+ const char* pw = password ? password->c_str() : "";++ switch (cfg.authMethod) {+ case SSHAuthMethod::Password:+ rc = ssh_userauth_password(s, nullptr, pw);+ if (rc != SSH_AUTH_SUCCESS) {+ rc = tryKbdInteractive(s, pw);+ }+ break;+ case SSHAuthMethod::PrivateKey:+ if (cfg.keyPath) {+ ssh_key key = nullptr;+ if (ssh_pki_import_privkey_file(cfg.keyPath->c_str(), nullptr, nullptr, nullptr, &key) == SSH_OK) {+ rc = ssh_userauth_publickey(s, nullptr, key);+ ssh_key_free(key);+ }+ }+ if (rc != SSH_AUTH_SUCCESS) {+ rc = ssh_userauth_publickey_auto(s, nullptr, nullptr);+ }+ break;+ case SSHAuthMethod::KeyWithPassphrase: {+ if (cfg.keyPath) {+ ssh_key key = nullptr;+ if (ssh_pki_import_privkey_file(cfg.keyPath->c_str(), pw, nullptr, nullptr, &key) == SSH_OK) {+ rc = ssh_userauth_publickey(s, nullptr, key);+ ssh_key_free(key);+ }+ }+ if (rc != SSH_AUTH_SUCCESS) {+ rc = ssh_userauth_publickey_auto(s, nullptr, pw);+ }+ break;+ }+ }+ if (rc != SSH_AUTH_SUCCESS) {+ throw AuthenticationError(std::string("SSH auth failed: ") + ssh_get_error(s));+ }+}++// H3 fix: loop ssh_channel_write until all bytes written (partial write handling).+bool channelWriteAll(ssh_channel ch, const char* data, uint32_t len) {+ uint32_t written = 0;+ while (written < len) {+ const int w = ssh_channel_write(ch, data + written, len - written);+ if (w <= 0) return false;+ written += static_cast<uint32_t>(w);+ }+ return true;+}++// Relay loop: accept one TCP client, open SSH forward channel, shuttle bytes.+void relayLoop(SSHTunnelManager::Tunnel* t, const std::string& remoteHost, int remotePort) {+ while (!t->stopFlag.load(std::memory_order_acquire)) {+ sockaddr_in client{};+ socklen_t clen = sizeof(client);+ int clientFd = ::accept(t->listenFd, reinterpret_cast<sockaddr*>(&client), &clen);+ if (clientFd < 0) break;++ ssh_channel ch = ssh_channel_new(t->sshSession);+ if (!ch || ssh_channel_open_forward(ch, remoteHost.c_str(), remotePort,+ "127.0.0.1", static_cast<int>(t->localPort)) != SSH_OK) {+ ::close(clientFd);+ if (ch) ssh_channel_free(ch);+ // If stopFlag set, exit cleanly; otherwise retry accept.+ if (t->stopFlag.load(std::memory_order_acquire)) break;+ continue;+ }++ t->status.store(SSHTunnelManager::Status::Connected, std::memory_order_release);++ constexpr int kBufSize = 32768;+ char buf[kBufSize];+ const int sshFd = ssh_get_fd(t->sshSession);++ while (!t->stopFlag.load(std::memory_order_acquire) && ssh_channel_is_open(ch)) {+ pollfd fds[2];+ fds[0] = {clientFd, POLLIN, 0};+ fds[1] = {sshFd, POLLIN, 0};+ int pr = ::poll(fds, 2, 500);+ if (pr < 0) break;++ // Check error/hangup FIRST (M1 fix: don't miss final data).+ const bool tcpErr = (fds[0].revents & (POLLERR | POLLHUP)) != 0;+ const bool sshErr = (fds[1].revents & (POLLERR | POLLHUP)) != 0;++ // TCP client → SSH channel+ if (fds[0].revents & POLLIN) {+ const ssize_t n = ::read(clientFd, buf, kBufSize);+ if (n <= 0) break;+ if (!channelWriteAll(ch, buf, static_cast<uint32_t>(n))) break; // H3 fix+ }++ // SSH channel → TCP client+ if (fds[1].revents & POLLIN) {+ const int n = ssh_channel_read_nonblocking(ch, buf, kBufSize, 0);+ if (n > 0) {+ ssize_t written = 0;+ while (written < n) {+ const ssize_t w = ::write(clientFd, buf + written, static_cast<size_t>(n - written));+ if (w <= 0) break;+ written += w;+ }+ if (written < n) break;+ } else if (n < 0) {+ break;+ }+ }++ if (ssh_channel_is_eof(ch)) break;+ // Break on errors only AFTER draining any remaining data above.+ if (tcpErr || sshErr) break;+ }++ // H2 fix: only send EOF if channel is still open and not already EOF'd.+ if (ssh_channel_is_open(ch) && !ssh_channel_is_eof(ch)) {+ ssh_channel_send_eof(ch);+ }+ ssh_channel_close(ch);+ ssh_channel_free(ch);+ ::close(clientFd);+ }+ t->status.store(SSHTunnelManager::Status::Disconnected, std::memory_order_release);+}++}++SSHTunnelManager::SSHTunnelManager() = default;++SSHTunnelManager::~SSHTunnelManager() { disconnectAll(); }++std::uint16_t SSHTunnelManager::establish(const std::string& connectionId,+ const SSHTunnelConfig& sshConfig,+ const std::string& remoteHost,+ int remotePort,+ const std::optional<std::string>& sshPassword) {+ disconnect(connectionId);++ auto t = std::make_unique<Tunnel>();+ t->connectionId = connectionId;++ // 1. Open SSH session + authenticate.+ t->sshSession = createSshSession(sshConfig);+ authenticateSsh(t->sshSession, sshConfig, sshPassword);++ // 2. Bind local TCP port.+ auto [fd, port] = bindFreePort();+ t->listenFd = fd;+ t->localPort = port;+ t->status.store(Status::Connected, std::memory_order_release);++ // C1 fix: insert into map BEFORE spawning relay thread so concurrent+ // disconnect() calls can find and stop the tunnel properly.+ auto* raw = t.get();+ {+ std::lock_guard lock(mutex_);+ tunnels_[connectionId] = std::move(t);+ }++ // 3. Spawn relay thread (tunnel is already in the map).+ const auto rh = remoteHost;+ const auto rp = remotePort;+ raw->thread = std::thread([raw, rh, rp] { relayLoop(raw, rh, rp); });++ return port;+}++void SSHTunnelManager::disconnect(const std::string& connectionId) {+ std::lock_guard lock(mutex_);+ tunnels_.erase(connectionId);+}++void SSHTunnelManager::disconnectAll() {+ std::lock_guard lock(mutex_);+ tunnels_.clear();+}++SSHTunnelManager::Status SSHTunnelManager::status(const std::string& connectionId) const {+ std::lock_guard lock(mutex_);+ auto it = tunnels_.find(connectionId);+ if (it == tunnels_.end()) return Status::Disconnected;+ return it->second->status.load(std::memory_order_acquire);+}++}diff --git a/linux/src/Services/SSH/SSHTunnelManager.h b/linux/src/Services/SSH/SSHTunnelManager.hnew file mode 100644index 0000000..af47773--- /dev/null+++ b/linux/src/Services/SSH/SSHTunnelManager.h@@ -0,0 +1,51 @@+#pragma once++#include <cstdint>+#include <functional>+#include <memory>+#include <mutex>+#include <optional>+#include <string>+#include <unordered_map>++#include "Core/Models/Database/ConnectionConfig.h"++namespace gridex {++// SSH local port forwarding using libssh.+// establish() opens an SSH session, binds a free local TCP port, and forwards+// traffic through the SSH tunnel to remoteHost:remotePort. The returned local+// port can be passed to the database adapter as "localhost:<port>".+//+// Each tunnel runs a dedicated background thread (select loop). A single TCP+// client is served at a time — sufficient for one-adapter-per-connection.+class SSHTunnelManager {+public:+ enum class Status { Connecting, Connected, Disconnected, Error };++ SSHTunnelManager();+ ~SSHTunnelManager();++ SSHTunnelManager(const SSHTunnelManager&) = delete;+ SSHTunnelManager& operator=(const SSHTunnelManager&) = delete;++ // Opens the tunnel and returns the local port the adapter should connect to.+ // Throws gridex::ConnectionError on failure.+ std::uint16_t establish(const std::string& connectionId,+ const SSHTunnelConfig& sshConfig,+ const std::string& remoteHost,+ int remotePort,+ const std::optional<std::string>& sshPassword);++ void disconnect(const std::string& connectionId);+ void disconnectAll();++ [[nodiscard]] Status status(const std::string& connectionId) const;++ struct Tunnel; // defined in .cpp+private:+ mutable std::mutex mutex_;+ std::unordered_map<std::string, std::unique_ptr<Tunnel>> tunnels_;+};++}diff --git a/linux/src/main.cpp b/linux/src/main.cppnew file mode 100644index 0000000..56cd6cc--- /dev/null+++ b/linux/src/main.cpp@@ -0,0 +1,104 @@+#include <QApplication>+#include <QSettings>+#include <QStringList>+#include <QStyleFactory>+#include <QThread>+#include <cstdio>+#include <exception>+#include <memory>++#include "App/MCP/MCPConnectionProvider.h"+#include "Data/Keychain/SecretStore.h"+#include "Data/Persistence/AppConnectionRepository.h"+#include "Data/Persistence/AppDatabase.h"+#include "Presentation/Theme/ThemeManager.h"+#include "Presentation/Windows/Main/MainWindow.h"+#include "Services/MCP/MCPServer.h"++namespace {++void seedConnectionModesFromSettings(gridex::mcp::MCPServer& server,+ gridex::AppConnectionRepository& repo) {+ QSettings s;+ for (const auto& c : repo.fetchAll()) {+ QString id = QString::fromStdString(c.id);+ QString raw = s.value(QStringLiteral("mcp.connectionMode.") + id).toString();+ auto m = gridex::mcpConnectionModeFromRaw(raw.toStdString());+ if (m) server.setConnectionMode(c.id, *m);+ }+}++int runMcpStdio(int argc, char* argv[]) {+ QApplication app(argc, argv);+ QApplication::setApplicationName(QStringLiteral("Gridex"));+ QApplication::setOrganizationName(QStringLiteral("Vurakit"));+ QApplication::setOrganizationDomain(QStringLiteral("vurakit.com"));++ auto db = std::make_shared<gridex::AppDatabase>();+ db->open();++ auto repo = std::make_unique<gridex::AppConnectionRepository>(db);+ auto secretStore = std::make_unique<gridex::SecretStore>();+ auto provider = std::make_unique<gridex::MCPConnectionProvider>(repo.get(), secretStore.get());++ std::shared_ptr<gridex::mcp::IMCPConnectionProvider> shim(provider.get(), [](auto*){});+ auto server = std::make_unique<gridex::mcp::MCPServer>(+ shim, "1.0.0", gridex::mcp::MCPTransportMode::Stdio);++ seedConnectionModesFromSettings(*server, *repo);++ QSettings s;+ gridex::mcp::RateLimits rl;+ rl.queriesPerMinute = s.value("mcp.rateLimit.queriesPerMinute", 60).toInt();+ rl.queriesPerHour = s.value("mcp.rateLimit.queriesPerHour", 1000).toInt();+ rl.writesPerMinute = s.value("mcp.rateLimit.writesPerMinute", 10).toInt();+ rl.ddlPerMinute = s.value("mcp.rateLimit.ddlPerMinute", 1).toInt();+ server->rateLimiter().setLimits(rl);++ server->start();+ // Background watcher quits Qt when stdin EOF causes the transport to stop.+ QThread* watcher = QThread::create([&]() {+ while (server->isRunning()) QThread::msleep(250);+ QMetaObject::invokeMethod(qApp, "quit", Qt::QueuedConnection);+ });+ watcher->start();+ int code = QApplication::exec();+ server->stop();+ watcher->wait(1000);+ return code;+}++} // namespace++int main(int argc, char* argv[]) {+ try {+ QStringList args;+ for (int i = 1; i < argc; ++i) args << QString::fromUtf8(argv[i]);+ if (args.contains(QStringLiteral("--mcp-stdio"))) {+ return runMcpStdio(argc, argv);+ }++ QApplication app(argc, argv);++ QApplication::setApplicationName(QStringLiteral("Gridex"));+ QApplication::setOrganizationName(QStringLiteral("Vurakit"));+ QApplication::setOrganizationDomain(QStringLiteral("vurakit.com"));++ if (auto* fusion = QStyleFactory::create(QStringLiteral("Fusion"))) {+ QApplication::setStyle(fusion);+ }++ gridex::ThemeManager::instance().apply(&app);++ gridex::MainWindow window;+ window.show();++ return QApplication::exec();+ } catch (const std::exception& e) {+ std::fprintf(stderr, "FATAL: %s\n", e.what());+ return 1;+ } catch (...) {+ std::fprintf(stderr, "FATAL: unknown exception\n");+ return 1;+ }+}diff --git a/linux/tests/CMakeLists.txt b/linux/tests/CMakeLists.txtnew file mode 100644index 0000000..8abc3bd--- /dev/null+++ b/linux/tests/CMakeLists.txt@@ -0,0 +1,21 @@+add_executable(sqlite-smoketest sqlite-smoketest.cpp)+target_link_libraries(sqlite-smoketest PRIVATE gridex-core gridex-data)++add_executable(phase2c-smoketest phase2c-smoketest.cpp)+target_link_libraries(phase2c-smoketest PRIVATE gridex-core gridex-data gridex-domain)++add_executable(phase2d-smoketest phase2d-smoketest.cpp)+target_link_libraries(phase2d-smoketest PRIVATE gridex-core gridex-data gridex-domain)++# Put test binaries under linux/bin-tests so they can be run without+# referencing the `build/` path segment. -UNDEBUG keeps assert() active even+# in Release builds since smoke tests rely on assertions for correctness checks.+set_target_properties(sqlite-smoketest phase2c-smoketest phase2d-smoketest PROPERTIES+ AUTOMOC OFF+ AUTORCC OFF+ AUTOUIC OFF+ RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/bin-tests+)+target_compile_options(sqlite-smoketest PRIVATE -UNDEBUG)+target_compile_options(phase2c-smoketest PRIVATE -UNDEBUG)+target_compile_options(phase2d-smoketest PRIVATE -UNDEBUG)diff --git a/linux/tests/docker-compose.yml b/linux/tests/docker-compose.ymlnew file mode 100644index 0000000..ccd6d1a--- /dev/null+++ b/linux/tests/docker-compose.yml@@ -0,0 +1,31 @@+services:+ gridex-pg:+ image: postgres:16-alpine+ container_name: gridex-pg-test+ environment:+ POSTGRES_USER: gridex+ POSTGRES_PASSWORD: gridex+ POSTGRES_DB: gridex_test+ ports:+ - "15432:5432"+ healthcheck:+ test: ["CMD-SHELL", "pg_isready -U gridex -d gridex_test"]+ interval: 2s+ timeout: 3s+ retries: 20++ gridex-mysql:+ image: mysql:8.0+ container_name: gridex-mysql-test+ environment:+ MYSQL_ROOT_PASSWORD: gridex+ MYSQL_DATABASE: gridex_test+ MYSQL_USER: gridex+ MYSQL_PASSWORD: gridex+ ports:+ - "13306:3306"+ healthcheck:+ test: ["CMD", "mysqladmin", "ping", "-h", "127.0.0.1", "-u", "gridex", "-pgridex"]+ interval: 3s+ timeout: 5s+ retries: 30diff --git a/linux/tests/phase2c-smoketest.cpp b/linux/tests/phase2c-smoketest.cppnew file mode 100644index 0000000..b5121b7--- /dev/null+++ b/linux/tests/phase2c-smoketest.cpp@@ -0,0 +1,170 @@+// Phase 2c smoke: SecretStore + JSON + ConnectionRepository + TestConnection UseCase.++#include <cassert>+#include <cstdio>+#include <filesystem>+#include <memory>++#include "Core/Models/Database/ConnectionConfig.h"+#include "Core/Models/Database/ConnectionConfigJson.h"+#include "Data/Keychain/SecretStore.h"+#include "Data/Persistence/AppConnectionRepository.h"+#include "Data/Persistence/AppDatabase.h"+#include "Domain/UseCases/Connection/ConnectDatabase.h"+#include "Domain/UseCases/Connection/DeleteConnection.h"+#include "Domain/UseCases/Connection/TestConnection.h"++using namespace gridex;++static ConnectionConfig makeSqliteConfig(const std::string& path, const std::string& id = "conn-sqlite-1") {+ ConnectionConfig c;+ c.id = id;+ c.name = "Local SQLite";+ c.databaseType = DatabaseType::SQLite;+ c.filePath = path;+ c.sslEnabled = false;+ return c;+}++static void testJsonRoundTrip() {+ auto cfg = makeSqliteConfig("/tmp/foo.db");+ cfg.colorTag = ColorTag::Green;+ cfg.group = "Dev";+ cfg.username = "alice";+ cfg.sshConfig = SSHTunnelConfig{"bastion", 2222, "op", SSHAuthMethod::PrivateKey, std::string{"/tmp/id"}};++ const auto encoded = json::encode(cfg);+ const auto decoded = json::decode(encoded);+ assert(decoded.id == cfg.id);+ assert(decoded.databaseType == DatabaseType::SQLite);+ assert(decoded.colorTag && *decoded.colorTag == ColorTag::Green);+ assert(decoded.filePath && *decoded.filePath == "/tmp/foo.db");+ assert(decoded.sshConfig && decoded.sshConfig->port == 2222);+ assert(decoded.sshConfig->authMethod == SSHAuthMethod::PrivateKey);+ std::printf("JSON round-trip OK (%zu bytes)\n", encoded.size());+}++static void testRepository() {+ const auto tmp = std::filesystem::temp_directory_path() / "gridex-repo-smoke.sqlite";+ std::error_code ec;+ std::filesystem::remove(tmp, ec);++ auto db = std::make_shared<AppDatabase>();+ db->open(tmp.string());++ AppConnectionRepository repo(db);+ auto cfg = makeSqliteConfig("/tmp/bar.db");+ cfg.group = "Prod";++ repo.save(cfg);+ const auto all = repo.fetchAll();+ assert(all.size() == 1);+ assert(all[0].id == cfg.id);+ assert(all[0].databaseType == DatabaseType::SQLite);++ const auto byId = repo.fetchById(cfg.id);+ assert(byId && byId->name == "Local SQLite");++ const auto byGroup = repo.fetchByGroup("Prod");+ assert(byGroup.size() == 1);++ repo.remove(cfg.id);+ assert(repo.fetchAll().empty());++ std::filesystem::remove(tmp, ec);+ std::printf("Repository CRUD round-trip OK\n");+}++static void testTestConnectionUseCase() {+ const auto tmp = std::filesystem::temp_directory_path() / "gridex-tc-smoke.sqlite";+ std::error_code ec;+ std::filesystem::remove(tmp, ec);+ // Pre-create the file so open+testConnection succeed+ { FILE* f = std::fopen(tmp.c_str(), "w"); if (f) std::fclose(f); }++ auto cfg = makeSqliteConfig(tmp.string());+ TestConnectionUseCase uc;+ const auto res = uc.execute(cfg, std::nullopt);+ assert(res.success);+ assert(res.serverVersion && res.serverVersion->rfind("SQLite ", 0) == 0);+ assert(res.latency.count() >= 0.0);++ std::filesystem::remove(tmp, ec);+ std::printf("TestConnection UseCase OK (version: %s)\n", res.serverVersion->c_str());+}++static void testConnectDatabaseUseCase() {+ const auto tmp = std::filesystem::temp_directory_path() / "gridex-connect-smoke.sqlite";+ std::error_code ec;+ std::filesystem::remove(tmp, ec);++ auto cfg = makeSqliteConfig(tmp.string());+ ConnectDatabaseUseCase uc;+ auto active = uc.execute(cfg, std::nullopt, /*loadInitialSchema=*/true);+ assert(active.adapter);+ assert(active.adapter->isConnected());+ const auto ver = active.adapter->serverVersion();+ assert(ver.rfind("SQLite ", 0) == 0);+ active.adapter->disconnect();++ std::filesystem::remove(tmp, ec);+ std::printf("ConnectDatabase UseCase OK\n");+}++static void testSecretStore() {+ SecretStore store("com.gridex.smoketest");+ if (!store.isAvailable()) {+ std::printf("SecretStore SKIPPED (no Secret Service — headless/WSL?)\n");+ return;+ }++ const std::string_view key = "phase2c.round-trip";+ store.save(key, "hunter2");+ const auto loaded = store.load(key);+ assert(loaded && *loaded == "hunter2");++ store.save(key, "hunter3"); // overwrite+ assert(*store.load(key) == "hunter3");++ store.remove(key);+ assert(!store.load(key).has_value());+ std::printf("SecretStore round-trip OK (store/load/overwrite/remove)\n");+}++static void testDeleteConnectionUseCase() {+ const auto tmp = std::filesystem::temp_directory_path() / "gridex-delete-smoke.sqlite";+ std::error_code ec;+ std::filesystem::remove(tmp, ec);++ auto db = std::make_shared<AppDatabase>();+ db->open(tmp.string());+ AppConnectionRepository repo(db);++ auto cfg = makeSqliteConfig("/tmp/del.db", "conn-to-delete");+ repo.save(cfg);+ assert(repo.fetchAll().size() == 1);++ SecretStore secrets("com.gridex.smoketest");+ DeleteConnectionUseCase uc(&repo, &secrets);+ uc.execute(cfg.id);+ assert(repo.fetchAll().empty());++ std::filesystem::remove(tmp, ec);+ std::printf("DeleteConnection UseCase OK\n");+}++int main() {+ try {+ testJsonRoundTrip();+ testRepository();+ testTestConnectionUseCase();+ testConnectDatabaseUseCase();+ testSecretStore();+ testDeleteConnectionUseCase();+ std::printf("ALL PHASE 2C SMOKE TESTS PASSED\n");+ return 0;+ } catch (const std::exception& e) {+ std::fprintf(stderr, "SMOKE FAILED: %s\n", e.what());+ return 1;+ }+}diff --git a/linux/tests/phase2d-smoketest.cpp b/linux/tests/phase2d-smoketest.cppnew file mode 100644index 0000000..3001cdb--- /dev/null+++ b/linux/tests/phase2d-smoketest.cpp@@ -0,0 +1,177 @@+// Phase 2d integration smoke: PostgresAdapter + MysqlAdapter against docker-compose stacks.+//+// Expected containers (linux/tests/docker-compose.yml):+// gridex-pg-test postgres://gridex:gridex@localhost:15432/gridex_test+// gridex-mysql-test mysql://gridex:gridex@localhost:13306/gridex_test+//+// Override endpoints with env vars:+// GRIDEX_TEST_PG_HOST / _PORT / _USER / _PASSWORD / _DB+// GRIDEX_TEST_MYSQL_HOST / _PORT / _USER / _PASSWORD / _DB++#include <cassert>+#include <cstdio>+#include <cstdlib>+#include <optional>+#include <string>++#include "Core/Enums/DatabaseType.h"+#include "Core/Models/Database/ConnectionConfig.h"+#include "Data/Adapters/AdapterFactory.h"+#include "Domain/UseCases/Connection/TestConnection.h"++using namespace gridex;++namespace {++std::string envOr(const char* key, const char* fallback) {+ const char* v = std::getenv(key);+ return (v && *v) ? std::string(v) : std::string(fallback);+}++int envIntOr(const char* key, int fallback) {+ const char* v = std::getenv(key);+ if (!v || !*v) return fallback;+ try { return std::stoi(v); } catch (...) { return fallback; }+}++ConnectionConfig pgConfig() {+ ConnectionConfig c;+ c.id = "pg-it";+ c.name = "IT-PG";+ c.databaseType = DatabaseType::PostgreSQL;+ c.host = envOr("GRIDEX_TEST_PG_HOST", "localhost");+ c.port = envIntOr("GRIDEX_TEST_PG_PORT", 15432);+ c.username = envOr("GRIDEX_TEST_PG_USER", "gridex");+ c.database = envOr("GRIDEX_TEST_PG_DB", "gridex_test");+ return c;+}++ConnectionConfig mysqlConfig() {+ ConnectionConfig c;+ c.id = "mysql-it";+ c.name = "IT-MySQL";+ c.databaseType = DatabaseType::MySQL;+ c.host = envOr("GRIDEX_TEST_MYSQL_HOST", "127.0.0.1");+ c.port = envIntOr("GRIDEX_TEST_MYSQL_PORT", 13306);+ c.username = envOr("GRIDEX_TEST_MYSQL_USER", "gridex");+ c.database = envOr("GRIDEX_TEST_MYSQL_DB", "gridex_test");+ return c;+}++void exercise(IDatabaseAdapter& a, const std::string& label) {+ std::printf("[%s] serverVersion: %s\n", label.c_str(), a.serverVersion().c_str());++ const auto one = a.executeRaw("SELECT 1");+ assert(one.rows.size() == 1 && one.rows[0].size() == 1);+ assert(one.rows[0][0].tryIntValue() == 1);+ std::printf("[%s] SELECT 1 -> %lld\n", label.c_str(),+ static_cast<long long>(one.rows[0][0].tryIntValue().value_or(-1)));++ a.executeRaw("DROP TABLE IF EXISTS gridex_smoke");+ a.executeRaw("CREATE TABLE gridex_smoke (id SERIAL PRIMARY KEY, note TEXT NOT NULL)");++ std::vector<QueryParameter> params;+ params.emplace_back(RowValue::makeString("hello"));+ if (a.databaseType() == DatabaseType::PostgreSQL) {+ a.execute("INSERT INTO gridex_smoke(note) VALUES($1)", params);+ } else {+ a.execute("INSERT INTO gridex_smoke(note) VALUES(?)", params);+ }++ const auto sel = a.executeRaw("SELECT id, note FROM gridex_smoke ORDER BY id");+ assert(sel.rows.size() == 1);+ assert(sel.rows[0][1].tryStringValue().value_or("") == "hello");++ const auto tables = a.listTables(std::nullopt);+ bool sawTable = false;+ for (const auto& t : tables) if (t.name == "gridex_smoke") { sawTable = true; break; }+ assert(sawTable);++ const auto desc = a.describeTable("gridex_smoke", std::nullopt);+ assert(desc.columns.size() == 2);+ bool sawPk = false;+ for (const auto& c : desc.columns) if (c.isPrimaryKey && c.name == "id") { sawPk = true; break; }+ assert(sawPk);++ a.executeRaw("DROP TABLE IF EXISTS gridex_smoke");+ std::printf("[%s] round-trip + schema OK\n", label.c_str());+}++} // namespace++int main() {+ // CREATE TABLE differs between PG (SERIAL) and MySQL (AUTO_INCREMENT).+ // We use dialect-specific DDL per adapter below.+ bool ranAny = false;++ // PostgreSQL+ try {+ auto cfg = pgConfig();+ TestConnectionUseCase tc;+ const auto res = tc.execute(cfg, std::string("gridex"));+ if (!res.success) {+ std::printf("[PG] test skipped (%s)\n", res.errorMessage.value_or("unreachable").c_str());+ } else {+ auto adapter = createAdapter(cfg.databaseType);+ adapter->connect(cfg, std::string("gridex"));+ exercise(*adapter, "PG");+ adapter->disconnect();+ ranAny = true;+ }+ } catch (const std::exception& e) {+ std::fprintf(stderr, "[PG] FAILED: %s\n", e.what());+ return 1;+ }++ // MySQL — CREATE TABLE needs AUTO_INCREMENT, not SERIAL. Special-case.+ try {+ auto cfg = mysqlConfig();+ TestConnectionUseCase tc;+ const auto res = tc.execute(cfg, std::string("gridex"));+ if (!res.success) {+ std::printf("[MySQL] test skipped (%s)\n", res.errorMessage.value_or("unreachable").c_str());+ } else {+ auto adapter = createAdapter(cfg.databaseType);+ adapter->connect(cfg, std::string("gridex"));+ std::printf("[MySQL] serverVersion: %s\n", adapter->serverVersion().c_str());++ const auto one = adapter->executeRaw("SELECT 1");+ assert(one.rows.size() == 1);+ assert(one.rows[0][0].tryIntValue() == 1);+ std::printf("[MySQL] SELECT 1 -> %lld\n",+ static_cast<long long>(one.rows[0][0].tryIntValue().value_or(-1)));++ adapter->executeRaw("DROP TABLE IF EXISTS gridex_smoke");+ adapter->executeRaw("CREATE TABLE gridex_smoke (id INT AUTO_INCREMENT PRIMARY KEY, note TEXT NOT NULL)");++ std::vector<QueryParameter> params;+ params.emplace_back(RowValue::makeString("world"));+ adapter->execute("INSERT INTO gridex_smoke(note) VALUES(?)", params);++ const auto sel = adapter->executeRaw("SELECT id, note FROM gridex_smoke ORDER BY id");+ assert(sel.rows.size() == 1);+ assert(sel.rows[0][1].tryStringValue().value_or("") == "world");++ const auto tables = adapter->listTables(std::nullopt);+ bool sawTable = false;+ for (const auto& t : tables) if (t.name == "gridex_smoke") { sawTable = true; break; }+ assert(sawTable);++ adapter->executeRaw("DROP TABLE IF EXISTS gridex_smoke");+ adapter->disconnect();+ std::printf("[MySQL] round-trip + schema OK\n");+ ranAny = true;+ }+ } catch (const std::exception& e) {+ std::fprintf(stderr, "[MySQL] FAILED: %s\n", e.what());+ return 1;+ }++ if (!ranAny) {+ std::printf("SKIPPED: neither PG nor MySQL container reachable. Start them with:\n"+ " docker compose -f linux/tests/docker-compose.yml up -d\n");+ return 0;+ }+ std::printf("ALL PHASE 2D SMOKE TESTS PASSED\n");+ return 0;+}diff --git a/linux/tests/sqlite-smoketest.cpp b/linux/tests/sqlite-smoketest.cppnew file mode 100644index 0000000..8cfa87b--- /dev/null+++ b/linux/tests/sqlite-smoketest.cpp@@ -0,0 +1,133 @@+// Smoke test for Phase 2b: SqliteAdapter + AppDatabase basic round-trip.+// Not a test framework — plain asserts. Invoked from CMake via a separate target.++#include <cassert>+#include <cstdio>+#include <cstdlib>+#include <filesystem>++#include "Core/Models/Database/ConnectionConfig.h"+#include "Core/Models/Database/RowValue.h"+#include "Data/Adapters/SQLite/SqliteAdapter.h"+#include "Data/Persistence/AppDatabase.h"++using namespace gridex;++static void testSqliteAdapter() {+ const auto tmp = std::filesystem::temp_directory_path() / "gridex-smoketest.sqlite";+ std::error_code ec;+ std::filesystem::remove(tmp, ec);++ ConnectionConfig cfg;+ cfg.id = "test-id";+ cfg.name = "smoke";+ cfg.databaseType = DatabaseType::SQLite;+ cfg.filePath = tmp.string();++ SqliteAdapter adapter;+ adapter.connect(cfg, std::nullopt);+ assert(adapter.isConnected());++ const auto ver = adapter.serverVersion();+ std::printf("server version: %s\n", ver.c_str());+ assert(ver.rfind("SQLite ", 0) == 0);++ (void)adapter.executeRaw("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT NOT NULL)");++ std::vector<QueryParameter> params;+ params.emplace_back(RowValue::makeString("Alice"));+ const auto ins1 = adapter.execute("INSERT INTO users(name) VALUES(?)", params);+ assert(ins1.rowsAffected == 1);++ std::unordered_map<std::string, RowValue> row2;+ row2["name"] = RowValue::makeString("Bob");+ const auto ins2 = adapter.insertRow("users", std::nullopt, row2);+ assert(ins2.rowsAffected == 1);++ const auto sel = adapter.executeRaw("SELECT id, name FROM users ORDER BY id");+ assert(sel.queryType == QueryType::Select);+ assert(sel.rows.size() == 2);+ assert(sel.columns.size() == 2);+ assert(sel.columns[0].name == "id");+ assert(sel.columns[1].name == "name");+ assert(sel.rows[0][1].asString() == "Alice");+ assert(sel.rows[1][1].asString() == "Bob");++ const auto one = adapter.executeRaw("SELECT 1");+ assert(one.rows.size() == 1);+ assert(one.rows[0][0].asInteger() == 1);++ const auto tables = adapter.listTables(std::nullopt);+ assert(tables.size() == 1);+ assert(tables[0].name == "users");++ const auto desc = adapter.describeTable("users", std::nullopt);+ assert(desc.columns.size() == 2);+ assert(desc.columns[0].isPrimaryKey);++ const auto snap = adapter.fullSchemaSnapshot(std::nullopt);+ assert(snap.databaseType == DatabaseType::SQLite);+ assert(snap.totalTableCount() == 1);++ adapter.disconnect();+ assert(!adapter.isConnected());+ std::filesystem::remove(tmp, ec);+ std::printf("SqliteAdapter smoke OK (2 rows round-trip, schema inspection OK)\n");+}++static void testAppDatabase() {+ const auto tmp = std::filesystem::temp_directory_path() / "gridex-appdb-smoketest.sqlite";+ std::error_code ec;+ std::filesystem::remove(tmp, ec);++ AppDatabase app;+ app.open(tmp.string());++ AppDatabase::ConnectionRecord rec;+ rec.id = "conn-1";+ rec.name = "Local Postgres";+ rec.databaseType = "postgresql";+ rec.configJson = R"({"host":"localhost","port":5432})";+ rec.updatedAt = std::chrono::system_clock::now();+ app.upsertConnection(rec);++ const auto list = app.listConnections();+ assert(list.size() == 1);+ assert(list[0].id == "conn-1");+ assert(list[0].name == "Local Postgres");++ app.setSetting("theme", "dark");+ const auto theme = app.getSetting("theme");+ assert(theme && *theme == "dark");++ AppDatabase::HistoryEntry h;+ h.connectionId = "conn-1";+ h.sql = "SELECT NOW()";+ h.executedAt = std::chrono::system_clock::now();+ h.durationMs = 7;+ h.succeeded = true;+ app.appendHistory(h);+ app.appendHistory(h);+ const auto hist = app.listHistory("conn-1", 10);+ assert(hist.size() == 2);+ assert(hist[0].sql == "SELECT NOW()");++ app.deleteConnection("conn-1");+ assert(app.listConnections().empty());++ app.close();+ std::filesystem::remove(tmp, ec);+ std::printf("AppDatabase smoke OK (connection CRUD, settings, history)\n");+}++int main() {+ try {+ testSqliteAdapter();+ testAppDatabase();+ std::printf("ALL PHASE 2B SMOKE TESTS PASSED\n");+ return 0;+ } catch (const std::exception& e) {+ std::fprintf(stderr, "SMOKE FAILED: %s\n", e.what());+ return 1;+ }+}