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++
chore: initial commit — Gridex macOS database IDE scaffold
Tobi4a6ec44a336b
diff --git a/.github/workflows/windows-release.yml b/.github/workflows/windows-release.ymlnew file mode 100644index 0000000..9973127--- /dev/null+++ b/.github/workflows/windows-release.yml@@ -0,0 +1,128 @@+# Windows Release pipeline for Gridex+# ---------------------------------------------------------------------+# Triggers on any git tag matching `v*.*.*` (semver). Delegates build ++# pack to the phase 01 PowerShell scripts in windows/scripts/ so the+# workflow stays a thin orchestration layer (single source of truth for+# MSBuild flags lives in build-unpackaged.ps1).+#+# Produces an unsigned Velopack release uploaded to the GitHub Release+# for the pushed tag. Signing is added in phase 05 via SignPath.+# ---------------------------------------------------------------------++name: Windows Release++on:+ push:+ tags:+ - 'v*.*.*'+ workflow_dispatch:+ inputs:+ version:+ description: "Version to pack (e.g. 0.1.0). Only used for manual runs."+ required: false+ default: "0.0.0-manual"++permissions:+ contents: write # needed for Release creation via vpk upload github++env:+ # vpk 0.0.1298 targets net9.0; allow running on any newer .NET runtime+ # installed on the runner (setup-dotnet pins 9.0.x below, but leave the+ # roll-forward on as a safety net for future vpk updates).+ DOTNET_ROLL_FORWARD: Major++jobs:+ release:+ runs-on: windows-2022+ timeout-minutes: 60++ steps:+ - name: Checkout+ uses: actions/checkout@v4+ with:+ fetch-depth: 0 # full history; vpk may inspect git metadata++ - name: Setup .NET 9 SDK+ uses: actions/setup-dotnet@v4+ with:+ dotnet-version: '9.0.x'++ - name: Setup MSBuild+ uses: microsoft/setup-msbuild@v2++ - name: Extract version from tag+ id: ver+ shell: pwsh+ run: |+ if ($env:GITHUB_REF -like 'refs/tags/v*') {+ $tag = "${{ github.ref_name }}"+ $version = $tag.TrimStart('v')+ } else {+ # workflow_dispatch fallback+ $version = "${{ github.event.inputs.version }}"+ $tag = "v$version"+ }+ Write-Host "Tag: $tag / Version: $version"+ "version=$version" | Out-File -FilePath $env:GITHUB_OUTPUT -Append+ "tag=$tag" | Out-File -FilePath $env:GITHUB_OUTPUT -Append++ - name: Install vpk CLI+ shell: pwsh+ run: .\windows\scripts\install-vpk-tool.ps1++ # Gridex.vcxproj hardcodes C:\vcpkg\installed\x64-windows\{include,lib}+ # and links against sqlite3/libpq/libmariadb/openssl/hiredis. GitHub+ # runners ship vcpkg at C:\vcpkg but do NOT pre-install these packages,+ # so we install them explicitly. Cache the installed tree to avoid+ # re-building openssl/libpq from source on every run.+ - name: Cache vcpkg installed tree+ id: vcpkg-cache+ uses: actions/cache@v4+ with:+ path: C:\vcpkg\installed+ # Bump v-suffix when changing the package list below so the+ # cache invalidates cleanly.+ key: vcpkg-x64-windows-v4-sqlite3-libpq-libmariadb-openssl-hiredis-nlohmann-httplib-mongocxx-libssh2++ - name: Install vcpkg dependencies+ if: steps.vcpkg-cache.outputs.cache-hit != 'true'+ shell: pwsh+ run: |+ & C:\vcpkg\vcpkg.exe install `+ sqlite3 libpq libmariadb openssl hiredis `+ nlohmann-json cpp-httplib `+ mongo-cxx-driver libssh2 `+ --triplet x64-windows `+ --recurse+ if ($LASTEXITCODE -ne 0) { throw "vcpkg install failed" }++ - name: Build unpackaged (Release x64)+ shell: pwsh+ run: .\windows\scripts\build-unpackaged.ps1 -Version ${{ steps.ver.outputs.version }}++ - name: Velopack pack+ shell: pwsh+ run: .\windows\scripts\pack-velopack.ps1 -Version ${{ steps.ver.outputs.version }}++ # TODO(phase 05): insert SignPath signing step here, between pack+ # and upload, once the SignPath Foundation cert is approved.+ # The step will submit windows/Releases/*.nupkg + Setup.exe to the+ # SignPath webhook and download signed artifacts back before upload.++ - name: Upload Setup.exe to GitHub Releases+ shell: pwsh+ env:+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ run: |+ # Only upload Gridex-stable-Setup.exe — users download and+ # run it directly. The nupkg/json/RELEASES files are Velopack+ # auto-update artifacts not needed when auto-update is disabled.+ $setup = "windows\Releases\Gridex-stable-Setup.exe"+ if (-not (Test-Path $setup)) {+ throw "Setup.exe not found at $setup"+ }+ gh release create ${{ steps.ver.outputs.tag }} `+ $setup `+ --title "${{ steps.ver.outputs.tag }}" `+ --notes "Gridex ${{ steps.ver.outputs.tag }} Windows Installer" `+ --latestdiff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..6b40daa--- /dev/null+++ b/.gitignore@@ -0,0 +1,100 @@+# Xcode+*.xcodeproj/+*.xcworkspace/+xcuserdata/+DerivedData/+build/+*.pbxuser+*.mode1v3+*.mode2v3+*.perspectivev3+*.xcuserstate+*.moved-aside+*.hmap+*.ipa+*.dSYM.zip+*.dSYM++# Swift Package Manager+.build/+.swiftpm/+Package.resolved++# macOS+.DS_Store+.AppleDouble+.LSOverride++# IDE+.idea/+.vscode/+*.swp+*.swo+*~++# Secrets+*.env+.env.*+!.env.example+credentials.json++# Internal / temporary+CLAUDE-CONTEXT.md+Untitled.png+list.md+plans/+docs/+# Distribution+*.dmg+*.app+*.zip+screenshot_mac/+plans/+# Windows / Visual Studio+.vs/+[Dd]ebug/+[Rr]elease/+x64/+x86/+ARM64/+*.user+*.suo+*.obj+*.pch+*.pdb+*.ilk+*.log+*.tlog/+*.idb+*.exe+*.dll+*.lib+*.exp+*.winmd+*.xbf+*.pri+*.appx+*.msix+*.lastbuildstate+*.FileListAbsolute.txt+*.cache+*.rsp+*.resfiles+*.resfiles.intermediate+*.Build.CppClean.log+*.vcxproj.FileListAbsolute.txt+packages/+Generated Files/+repomix-output.xml+screenshot_mac/++# Velopack release artifacts (Setup.exe, *.nupkg, releases.*.json, RELEASES)+windows/Releases/++# Cached vendor binaries (WebView2 bootstrap, etc.) — downloaded on demand+# by build-unpackaged.ps1, refreshed by CI on each run.+windows/vendor/++# Generated version header — written by build-unpackaged.ps1 -Version+# from the CI tag, falls back to 0.0.0-dev locally via __has_include.+windows/Gridex/GridexVersion.generated.h\ No newline at end of filediff --git a/CHANGELOG.md b/CHANGELOG.mdnew file mode 100644index 0000000..648437f--- /dev/null+++ b/CHANGELOG.md@@ -0,0 +1,594 @@+# Changelog++All notable changes to Gridex (formerly DataBridge) are documented in this file.++## [0.23.0] - 2026-04-12++### Added+- **MongoDB filter & sort support** — data grid filter panel now generates real BSON queries via `buildMongoFilter`:+ - All operators supported: `=`, `≠`, `>`, `<`, `≥`, `≤`, `LIKE`, `NOT LIKE`, `IS NULL`, `IS NOT NULL`, `IN`.+ - `LIKE` patterns translated to MongoDB `$regex` (case-insensitive, `%` → `.*`, `_` → `.`).+ - `_id` field auto-converts 24-char hex strings to `ObjectId` in filter values.+ - Multi-condition filters combined with `$and` / `$or` matching the combinator.+ - Sort applied via `.sort(Document)` on the cursor.+- **MongoDB nested field schema introspection** — `collectFieldPaths` recursively flattens embedded documents into dot-notation paths (e.g. `address.city`). Depth capped at 10 to avoid stack overflow on pathological docs. Array fields are recorded at the parent level (not expanded to `tags.0`) for more useful filter paths.+- **MongoDB array type detection** — `inferType` now returns `"array"` for BSON array documents instead of `"document"`.+- **Backup/Restore: MongoDB NDJSON** — pure Swift backup and restore without `mongodump`/`mongorestore`:+ - Backup streams all collections via MongoKitten cursor, writes one JSON line per document: `{"_collection":"name","_doc":{...}}`.+ - Restore parses NDJSON, groups by collection, batch-inserts via adapter.+ - Format extension: `.ndjson`.+- **Backup/Restore: Redis JSON snapshot** — pure Swift backup and restore without `redis-cli`:+ - Backup uses `SCAN` + `TYPE`/`GET`/`LRANGE`/`SMEMBERS`/`ZRANGE WITHSCORES`/`HGETALL` to capture all key types (string, list, set, zset, hash) + TTL. Written as NDJSON via `RedisJSONSerializer`.+ - Restore replays entries using `SET`/`RPUSH`/`SADD`/`ZADD`/`HSET` + `EXPIRE`.+ - Format extension: `.json`.+- **Backup/Restore: SQL Server native `.bak`** — uses SQL Server's built-in `BACKUP DATABASE … TO DISK` and `RESTORE DATABASE … FROM DISK` (T-SQL). Path is server-side; note for Docker users to volume-mount the path. RESTORE uses `SINGLE_USER WITH ROLLBACK IMMEDIATE` + `WITH REPLACE` pattern.+- **`RedisJSONSerializer`** — new helper that serializes/deserializes `RedisAdapter.RedisKeyEntry` to/from JSON strings. Handles all five Redis types with their native structures.++### Changed+- **AI Chat welcome screen** — empty chat now shows a welcome screen instead of a blank message list. Dividers removed for a cleaner layout; window background color applied.++### Fixed+- **MongoDB `documentToJSONString`** — BSON arrays now serialize as `[…]` instead of `{…}` by checking `doc.isArray`. Iteration switched from `for pair in doc` to `for key in doc.keys` + subscript to avoid iterator quirks with unusual BSON encodings.+- **MongoDB query guard** — added `guard parts.count >= 2` before split on `collectionName.find()` pattern to prevent out-of-bounds crash.+- **MongoDB fetchRows field paths** — `_id` is now always listed first; remaining fields collected with `collectFieldPaths` (dot-notation aware) instead of flat per-document iteration.++## [0.22.0] - 2026-04-11++### Added+- **Microsoft SQL Server support** — full integration as a 6th database type via [CosmoMSSQL](https://github.com/vkuttyp/CosmoSQLClient-Swift) (pure Swift NIO, TDS 7.4, no FreeTDS dependency). Compatible with SQL Server 2014+, Azure SQL Edge, Azure SQL Database.+ - **Connection pool** — `MSSQLConnectionPool` (max 5 conns) avoids concurrent stream conflicts.+ - **Schema introspection via `INFORMATION_SCHEMA`** — portable across all SQL Server variants. Lists databases, schemas (default `dbo`), tables, views, functions, procedures, columns, foreign keys.+ - **CRUD with parameter inlining** — works around CosmoMSSQL bug where RPC `sp_executesql` hardcodes transaction descriptor to 0. Inlines `@pN` placeholders into SQL with proper escaping (`N''` for unicode strings, `0xHEX` for binary, etc.) so transactions work correctly.+ - **Multi-batch script execution** — Query Editor splits scripts on `GO` separator. Uses dedicated script connection so `USE` statements persist across batches (e.g. `CREATE DATABASE → USE → CREATE TABLE` flows work).+ - **Auto-refresh after `USE`/`CREATE DATABASE`/`DROP DATABASE`** — sidebar and database picker sync to new state.+ - **MSSQL-specific dialect** — `[brackets]` identifier quoting, `@pN` placeholders, `OFFSET N ROWS FETCH NEXT M ROWS ONLY` pagination.+ - **MSSQL-aware ALTER TABLE** — uses `ADD col type` (no `COLUMN IF NOT EXISTS`), `EXEC sp_rename` for column rename, `ALTER COLUMN col type` for type change.+ - **Default schema `dbo`** — New Table tab defaults to `dbo` instead of `public` when adapter is MSSQL.+ - **37 native data types** — full list from [Microsoft Learn docs](https://learn.microsoft.com/sql/t-sql/data-types/data-types-transact-sql) including modern `VARCHAR(MAX)`, `NVARCHAR(MAX)`, `JSON`, `HIERARCHYID`, `GEOGRAPHY`, etc.+- **Stored procedures support (MSSQL)**:+ - Sidebar shows separate **Procedures** group with ▶ icon (green).+ - Procedure detail view with **parameter signature bar** — chips show `@id INT`, `@name NVARCHAR(100)`, `@result INT OUTPUT` parsed from `INFORMATION_SCHEMA.PARAMETERS`.+ - **"Execute" button** — auto-generates `EXEC [dbo].[procname] @p1 = NULL, @p2 = NULL OUTPUT;` template and opens it in a new query tab ready to fill.+- **SQL Editor smart script execution** — detect multi-statement scripts and run sequentially. SQL Server uses `GO` batch separator; other databases split on `;` (respecting quoted strings and `--` comments). Shows success status with statement count + rows affected for DDL/DML scripts.+- **Status banner separation** — success info no longer shown as red error; uses green ✓ status banner with `N statement(s) executed · M row(s) affected · 0.50s`.++### Fixed+- **MSSQL connection error handling** — wraps `SQLError` enum in `GridexError.queryExecutionFailed` with `String(describing:)` to preserve rich descriptions ("Server error 911: Database X does not exist") instead of generic "error 0".+- **MSSQL transaction commit** — UPDATE/INSERT/DELETE inside transactions now work correctly via parameter inlining (CosmoMSSQL RPC bug workaround).++## [0.21.0] - 2026-04-10++### Added+- **MongoDB support** — full integration as a 5th database type alongside PostgreSQL/MySQL/SQLite/Redis:+ - **MongoKitten driver** — pure Swift NIO-based, no C dependencies. Port 27017 default.+ - **Connection string field** — paste full `mongodb://` or `mongodb+srv://` URI with **Parse** button to auto-fill host/port/user/password/database/SSL. SRV URIs (Atlas, DigitalOcean) preserved verbatim for proper DNS lookup.+ - **Schema introspection** — collections appear as tables in sidebar; fields inferred from sampled documents (string/integer/double/boolean/date/objectId/document).+ - **CRUD via data grid** — Add row, edit cells, delete rows all route through MongoDB adapter using `insertOne`/`updateOne`/`deleteOne` (no SQL generation).+ - **Insert Document sheet** — JSON editor with auto-template from detected fields. Supports MongoDB Extended JSON shortcuts (`$oid`, `$date`). Allows inserting documents with any structure including new fields not in existing schema.+ - **Database management** — list/create/drop databases via shared connection pool. Database picker (⌘K) reconnects on switch.+ - **Schemaless structure view** — Structure tab shows detected fields as read-only info instead of editable column form (no ALTER TABLE in MongoDB).+ - **Create Collection** — simplified form (just collection name, no columns) for `New Table` tab when adapter is MongoDB.+ - **Auto ObjectId detection** — 24-char hex strings auto-converted to BSON ObjectId.++## [0.20.0] - 2026-04-09++### Added+- **SSH Tunnel support** — NIOSSH-based local port forwarding. ConnectionManager auto-detects SSH config, establishes tunnel, and redirects database connection through `127.0.0.1:localPort`. Password auth implemented, private key skeleton.+- **Delete Database** — trash button in Database Switcher (⌘K) with confirmation dialog. Disabled for currently active database. Uses `DROP DATABASE` for PostgreSQL/MySQL.+- **General Settings** — default page size (100/300/500/1000), confirm before delete toggle, auto-refresh sidebar with configurable interval, show query log default.+- **Editor Settings** — font size (8-24 with stepper), tab size (2/4/8), spaces vs tabs, word wrap, show line numbers, highlight current line.++### Removed+- **Dead import code** — removed unused `ImportService.swift` and `ImportDataUseCase.swift`. Import CSV/SQL already works directly via adapter in the UI views.++## [0.19.3] - 2026-04-09++### Added+- **Backup/Restore progress tracking** — no more endless spinner:+ - **Restore** (SQL): file piped through stdin in 64KB chunks, progress bar shows percentage based on bytes sent vs file size.+ - **Backup** (pg_dump/mysqldump): polls output file size every 0.5s, shows written size + elapsed time (e.g. `12.5 MB · 8s`).+ - Applies to PostgreSQL (psql, pg_dump) and MySQL (mysql, mysqldump).++## [0.19.2] - 2026-04-08++### Added+- **Build script** (`scripts/build-app.sh`) — builds `.app` bundle from SPM with compiled asset catalog, ad-hoc signing, and entitlements. Supports debug/release modes.++### Fixed+- **Edit cell background** — modified cell background (orange) only appears when value actually changes, not on every edit click. Fixed `justFinishedEditing` path not rebuilding pending change caches.+- **Edit cell blanks other columns** — after editing a cell, other columns in the same row appeared blank. Fixed by force-redrawing all visible cells after edit ends.+- **Cell background rendering** — `dirtyRect.fill()` replaced with `bounds.fill()` to ensure full cell background coverage.+- **Display cache sync** — `displayCache` now updates on cell edit, date edit, new row insert, and discard changes.+- **App logo missing in built .app** — `Bundle.module` (SPM) could not find `Assets.car` in `.app` bundle. Added multi-path logo loader that tries `.module`, main bundle, and explicit resource path.++## [0.19.1] - 2026-04-08++### Fixed+- **Data grid scroll performance** — eliminated per-frame bottlenecks:+ - Pre-computed display string cache (`displayCache`) avoids repeated `displayString` calls during scroll (600 array lookups vs 600 enum switches per frame).+ - Cached `NSAttributedString` in cells — reused across `draw()` calls instead of recreating dictionary + layout every frame.+ - Pre-truncate text at 300 chars before Core Text layout; blob display as `"(BLOB N bytes)"` with zero encoding cost.+ - Debounce increased 16ms → 100ms; column resize no longer triggers full visible-cell refresh.+ - Dirty checking in `configureCell` — only mark `needsDisplay` when cell content actually changed.+ - Removed `@Published` from high-frequency properties (`selectedRows`, `columnWidths`, `editingCell`, `insertedRowIndices`) to prevent SwiftUI body re-evaluation on every click/resize.+ - `DateFormatter` shared singleton instead of allocating per cell.+ - Tooltip computed only on text change, not every `viewFor` call.+- **Memory leak on tab close** — RAM did not decrease when closing data tabs:+ - Fixed Combine retain cycle: subscription held strong reference to `viewModel.objectWillChange`, keeping `DataGridViewState` alive indefinitely.+ - Coordinator `rows` snapshot now cleared via `releaseData()`.+ - `DataGridViewState.rows`, `displayCache`, `columns` explicitly cleared before removal from cache.+ - `queryEditorText` cleaned up on `closeAllTabs`.++## [0.19.0] - 2026-04-07++### Added+- **Google Gemini AI provider** — new LLM provider using OpenAI-compatible endpoint (`/v1beta/openai`). Streaming chat, model fetching from API, API key validation.+- **AI Settings UI** — configure provider (Gemini/Anthropic/OpenAI/Ollama), API key (Keychain), base URL, model picker with live fetch from API.+- **AI Chat wired to real LLM** — streaming responses with schema-aware system prompt. Replaces placeholder stub.+- **Attach tables to chat** — `+` button in chat input to select tables/views. Schema is sent inline in user message for precise, per-question context.+- **Chat history in-memory** — messages persist across tab switches (Details/Assistant), scoped per connection, cleared on disconnect.+- **SettingsLink integration** — gear icon and setup prompt in Assistant panel open macOS Settings window directly.++### Changed+- **Assistant tab always visible** — no longer requires `aiPanelVisible` toggle; shows setup prompt when no API key configured.++## [0.18.3] - 2026-04-07++### Added+- **SQL Editor button in toolbar** — `</>` icon in the header toolbar for quick access to open a new query editor tab.++### Fixed+- **Keyboard shortcuts not working (⌘K, ⌘⇧N, etc.)** — menu commands were disabled even after connecting to a database. Root cause: `AppState.active` (static weak var) is not reactive in SwiftUI, so `.disabled()` conditions were never re-evaluated. Fixed by using `@FocusedObject` with fallback to `AppState.active`.++## [0.18.2] - 2026-04-07++### Fixed+- **Truncate table** — now uses pending workflow (orange highlight → commit) instead of executing immediately. SQLite uses `DELETE FROM` since `TRUNCATE TABLE` is unsupported. Data grid refreshes automatically after commit.+- **Delete table cascade default** — cascade option is now enabled by default in the delete confirmation sheet.+- **Delete table error handling** — failed DROP no longer silently removes the table from pending; it stays marked (red) and shows an error alert so users can retry or adjust options.++## [0.18.1] - 2026-04-07++### Added+- **App version in status bar** — bottom-right corner shows current version (e.g. `v0.18.1`), read from Info.plist.++### Fixed+- **Connection with empty password** — previously silently aborted when no keychain entry existed. Now connects normally (needed for Redis without AUTH, passwordless databases).+- **Clearing saved password** — when user empties the password field and saves, the old keychain entry is now deleted. Previously the stale password persisted and was sent on reconnect, causing AUTH errors on passwordless Redis servers.++## [0.18.0] - 2026-04-07++### Changed+- **Rebrand: DataBridge → Gridex** — app name, bundle ID (`com.gridex.app`), all source code references, error types (`GridexError`), entitlements, and file names updated.+- **Project restructured:** `DataBridge/` → `macos/`, new empty `window/` folder for future Windows port.+- **Tests removed** — `DataBridgeTests/` deleted per project decision.+- Package name and executable renamed to `Gridex`.++## [0.17.0] - 2026-04-07++### Added+- **Redis pattern-based filter bar** — single search field with glob patterns (`user:*`, `*session*`), quick-filter presets menu, replaces SQL column filter for Redis connections.+- **ER Diagram toolbar button** — quick access from header toolbar (SQL databases only).++### Fixed+- **Critical crash fixes:**+ - `AppState.connect()`: force unwrap `group.next()!` replaced with safe `guard let` (connection timeout crash).+ - Redis `HGETALL`/`ZRANGE WITHSCORES` parsing: off-by-one in `stride` dropped the last field/member.+ - Redis `insertRow`/`updateRow`/`deleteRow`: keys with spaces broke command parsing — now uses direct `sendCommand()` API.+ - PostgreSQL `updateRow`/`deleteRow`: force unwrap `values[$1]!` replaced with safe `.compactMap`.+ - `ImportCSVSheet`: array index access on empty CSV replaced with safe `.first`.+ - Redis TLS: `try!` NIOSSLClientHandler replaced with proper `do/catch`.+- **Redis safety:**+ - Collection fetches capped at 10,000 items (LRANGE/SSCAN/ZRANGE) to prevent OOM.+ - SCAN loop checks connection state and caps at 100,000 keys.+- **UI error handling:** `TableStructureView`, `TableListView`, `ERDiagramViewModel`, `ConnectionFormPanel` now show errors to user with retry buttons instead of silent `print()`.+- **ImportSQLWizard:** hardcoded dark background color replaced with `NSColor.textBackgroundColor` (light mode fix).++### Changed+- **Toolbar:** all action buttons unified in single `primaryAction` group; commit icon changed to `text.insert`; AI brain icon removed; console log placeholder uses `terminal` icon.+- **Structure tab** hidden for Redis connections (key-value store has no table schema).++## [0.16.1] - 2026-04-06++### Fixed+- **Redis Server INFO** — fixed RESP `\r\n` line ending parsing that caused Server Info dashboard to show blank. Added error display for blocked commands.+- **Redis pipelined key loading** — `fetchRows()` now batches TYPE/TTL/value commands via NIO futures (~50x faster on cloud Redis).+- **Redis `listDatabases()`** — graceful fallback when `CONFIG GET` is blocked (Upstash, ElastiCache).++## [0.16.0] - 2026-04-06++### Added++#### Comprehensive Redis management+- **Add Key with type selection** — create string, hash, list, set, or sorted set keys from a dedicated sheet with field editors and optional TTL.+- **Key Detail View** — double-click any key to open a dedicated tab showing:+ - Hash: field/value table with inline add/delete+ - List: indexed items+ - Set: member list with add/remove+ - Sorted Set: member/score table with add/remove+ - String: full text view+ - TTL management (set/remove) and key rename from the header bar+ - Memory usage display (via `MEMORY USAGE`)+- **Server INFO Dashboard** — new tab showing all Redis server sections (Server, Memory, Clients, Stats, Keyspace) with key metrics cards (memory, clients, uptime, ops/sec, hit rate). Auto-refresh toggle (5s interval).+- **Slow Log Viewer** — new tab displaying `SLOWLOG GET` entries with ID, timestamp, duration, command, client. Reset button with confirmation.+- **DBSIZE in status bar** — total key count shown when connected to Redis.+- **Flush Database** — toolbar action + sidebar context menu with destructive confirmation dialog.+- **Key rename** — from the Key Detail View header.+- **Key duplicate** — uses `COPY` (Redis 6.2+) with type-aware fallback.+- **Redis CLI mode** — Query Editor shows "Redis CLI" label, hides Format/Minify/Explain buttons (SQL-only).+- **Redis sidebar context menu** — Browse Keys, Add Key, Server Info, Slow Log, Flush Database.+- **+ Key button** in DataGrid toolbar replaces "+ Row" for Redis connections.+- Toolbar buttons for Server Info and Slow Log (Redis-only, hidden for SQL databases).++## [0.15.1] - 2026-04-06++### Fixed+- **Redis TLS (rediss://)** — connections to cloud Redis providers (Upstash, AWS ElastiCache, etc.) now work via NIOSSL. A "TLS (rediss://)" checkbox is shown in the Redis connection form.+- **Password character count** — secure password fields now display the number of characters (e.g. "36") so users can verify pasted passwords.+- **Redis connection form cleanup** — SSL keys row hidden for Redis; TLS toggle replaces SSL mode picker.++## [0.15.0] - 2026-04-06++### Added++#### Redis connection support+- New **Redis** database type alongside PostgreSQL, MySQL, and SQLite.+- **RedisAdapter** maps the key-value store into DataBridge's relational model:+ - Virtual **"Keys"** table with columns: `key`, `type`, `value`, `ttl`.+ - SCAN-based pagination for browsing keys with pattern-matching filters.+ - Supports all Redis data types: string, list, set, sorted set, hash, stream.+ - Raw Redis command execution via the query editor (e.g. `SET foo bar`, `HGETALL myhash`).+ - RESP responses rendered as structured tables (arrays, key-value pairs, scalars).+ - MULTI/EXEC/DISCARD transaction support.+ - Database switching via `SELECT <db_number>` (db0–db15).+- **Connection form** adapted for Redis: host, port, optional password, database number (0–15).+- Red gradient badge ("Rd") in Home screen and sidebar.+- RediStack (swift-server/RediStack) added as dependency.++## [0.14.0] - 2026-04-06++### Added++#### Multi-window support — open multiple databases simultaneously+- **Cmd+N** now opens a new window with the Home connection picker, allowing you to connect to a different database in a separate window.+- Each window has its own independent `AppState`: separate connection, sidebar, tabs, and query history.+- Windows operate fully in parallel — edit data in PostgreSQL in one window while querying MySQL in another.++### Changed+- **New Query** shortcut moved from Cmd+N to **Cmd+Shift+N** (Cmd+N is now "New Window").+- `WindowCloseInterceptor` updated for multi-window: closing a window when others are open closes it directly; closing the last window disconnects and shows Home (preserves single-window UX).+- `AppState` ownership moved from the app-level `DataBridgeApp` scene to per-window `MainView` via `@StateObject`, with `@FocusedObject` routing menu commands to the active window.++## [0.13.0] - 2026-04-06++### Changed++#### Backup & Restore — TablePlus-style 3-column wizard+- Completely redesigned `BackupRestorePanel` to mirror the TablePlus backup dialog:+ - **Left column**: saved connection list (grouped, searchable, with DB type badges)+ - **Center column**: database list (auto-loaded via `listDatabases()` when a connection is selected; works even when not currently connected — creates a temporary adapter)+ - **Right column**: format picker (`--format=custom`, `--format=sql`, `--format=tar`), content selector (full / schema-only / data-only), compress toggle, or file browser for restore+ - **Footer**: "Start backup…" / "Start restore…" button with inline result (success/fail, file size, duration)+- File name header shows the selected database name as default backup filename.+- Auto-selects the active connection and database when opened from the sidebar while connected.++#### Home screen — Backup & Restore buttons+- Added "Backup database…" and "Restore database…" action buttons to the left branding panel on the Home screen, above "New Connection" / "New Group" (matches TablePlus layout).+- Opens the full 3-column wizard panel — user can pick any saved connection + database even when not connected.++### Fixed+- **Picker tag mismatch warning** — `selectedFormat` was initialized as `.custom` but SQLite/MySQL only support `.sql`, causing SwiftUI `Picker: the selection "custom" is invalid` console errors. Format is now initialized to `.sql` (universal) and reset to the first available format whenever the selected connection changes.++## [0.12.0] - 2026-04-06++### Added++#### ER Diagram — interactive schema visualization+- New **ER Diagram** tab type renders all tables and foreign-key relationships as an interactive graph using CoreGraphics/AppKit custom `NSView`.+- **Table cards** display column names, abbreviated data types, PK/FK badges, and NOT NULL indicators.+- **Relationship lines** drawn as bezier curves with arrowheads and cardinality markers (1 / N).+- **Drag** any table card to rearrange the layout.+- **Zoom**: Cmd+scroll, trackpad pinch, or toolbar +/− buttons.+- **Pan**: hold Space + drag, or drag on empty canvas area.+- **Auto layout**: Sugiyama-lite BFS layering based on FK relationships.+- **Fit to view**: scales and centers the diagram to fill the viewport.+- **Double-click** a table card to open its data grid tab.+- Hover highlight on table cards; selected card gets accent border.+- Dot-grid background pattern adapts to light/dark mode.+- Open via right-click **Tables** group → "ER Diagram" in the sidebar.++#### Database Backup & Restore+- New `BackupService` (`Services/Export/BackupService.swift`) — actor-based service that wraps native CLI tools:+ - **PostgreSQL**: `pg_dump` / `pg_restore` / `psql` — supports Custom (compressed), Plain SQL, and Tar formats.+ - **MySQL**: `mysqldump` / `mysql` — SQL format.+ - **SQLite**: direct file copy for backup, file replace for restore.+- Automatic tool discovery across Homebrew (Intel + ARM), Postgres.app, and system paths; falls back to `which`.+- New `BackupRestorePanel` — native `NSPanel` centered over the main window:+ - **Backup**: format picker, compress toggle, content selector (full / schema-only / data-only), `NSSavePanel` for output path, inline result (file size, duration, errors).+ - **Restore**: file browser with auto-format detection by extension, danger warning before overwrite, inline result with sidebar refresh on success.+ - Connection header shows name, host, database, and DB type badge.+- Sidebar bottom bar now has two new icon buttons: ↑ **Backup** and ↓ **Restore**.++## [0.11.1] - 2026-04-06++### Changed++- **Warning cleanup** — Cleared all compiler warnings flagged by Xcode (except the deprecated `SecKeychain*` APIs in `KeychainService`, which need a proper migration to the data-protection keychain):+ - `SQLiteAdapter.bind` — discard the result of `withUnsafeBytes` with `_ =`+ - `AppState.openTableStructure` — removed dangling `existing.id` expression that did nothing+ - `AppState.switchDatabase` — discard the result of the MySQL `USE` `executeRaw` call with `_ =`+ - `SQLContextParser.tableBeforeParen` — removed unused `schemaPos` local+ - `SQLFormatter.format` — `var clauseIndent` → `let`; removed the unused `inSelectList`, `inGroupOrderBy`, and JOIN-loop `u` locals that were written but never read+ - `ExportTableSheet.performExport` — dropped `await` in front of `showSavePanel` / `showDirectoryPanel` (both are synchronous `NSSavePanel`/`NSOpenPanel` wrappers)++## [0.11.0] - 2026-04-06++### Added++#### Import SQL Wizard — preview before execute+- New `ImportSQLWizard.swift` — opens after picking a `.sql` file via **Import → From SQL Dump…** in the Tables context menu.+- Shows file metadata (name, size, encoding picker) and a scrollable preview of the first 100,000 characters before hitting the database.+- Import result is rendered inline in the wizard (success/total count + first error) instead of via a separate alert.+- Sidebar is refreshed when the wizard closes (not during execution) so newly-imported tables appear without re-rendering the parent mid-import.++#### 10-second connection timeout+- `AppState.connect(config:password:)` now races the connection attempt against a 10-second timer via `withThrowingTaskGroup`. If the driver blocks (unreachable host, dropped packets, firewall) the UI no longer stays stuck on "Connecting…" forever — the user gets an error and can retry.++### Changed++#### Sidebar group header redesign+- Connection group headers are now rendered as minimal uppercase section labels (similar to Finder sidebar / Xcode navigator) instead of the previous rounded "folder" row.+- Inline `+` button on each group header opens the New Connection form for that group.+- Group count is displayed as a quiet monospaced-digit number next to the label.+- Context menu (New / Rename / Sort / Delete) and drag-and-drop drop target behavior are preserved.++#### Faster connect flow on Home view+- Clicking a saved connection on Home now loads the keychain password on a detached task so the main thread isn't blocked by a keychain prompt.+- If the user denies/cancels the keychain prompt (or there's no stored password), the connect flow silently aborts instead of attempting to connect with an empty password.+- SQLite connections skip the keychain lookup entirely (SQLite has no password).++### Fixed++- **App quit when closing the Connection form panel** — The global `WindowCloseInterceptor` (installed on every window that became key) was also being attached to `ConnectionFormPanel`, an `NSPanel`. Clicking its red ✕ posted `.windowCloseRequested`, which `MainView` interpreted as "Home → quit" and called `NSApplication.shared.terminate(nil)`. The interceptor is now only attached to the main content window — `NSPanel` instances and any window where `canBecomeMain == false` are skipped. Closing the connection form now just dismisses the panel.+- **Connection form panel appeared in the top-right corner of the screen** — `panel.center()` was called before the hosting controller had laid out, so the panel was positioned using the initial 580×520 contentRect and then drifted when its real size was applied. The panel is now centered over `NSApp.mainWindow` after calling `layoutIfNeeded()`, so it appears exactly in the middle of the app window.++## [0.10.0] - 2026-04-05++### Added++#### Table import (sidebar context menu)+- **Import → From CSV…** — Opens `ImportCSVSheet` with:+ - File picker for `.csv` files+ - Delimiter picker (`,` `;` `\t` `|`)+ - First-row-as-header toggle+ - **Auto column mapping** — CSV header columns are matched to table columns by name; user can override or skip via per-column Picker+ - Live preview of first 5 rows+ - Generates `INSERT INTO … VALUES …` for each row with proper quoting and escaping+ - Shows imported row count / errors+- **Import → From SQL Dump…** — Reads an `.sql` file, splits into statements, and executes each one against the active connection. Shows a result alert with success/fail counts and the first error message (if any).++#### Full-fidelity SQL export (matches TablePlus format)+New `ExportService.exportTableSQL(description:rows:databaseType:databaseName:to:)` emits:+- Header comment block with database name, table name, generation timestamp+- `DROP TABLE IF EXISTS "schema"."table"`+- `CREATE SEQUENCE IF NOT EXISTS …` — auto-detected from columns whose default contains `nextval(…)`+- `CREATE TABLE` with full column definitions (types, `NOT NULL`, `DEFAULT`), primary key constraint+- **Multi-row `INSERT`** — single statement for all rows, much smaller and faster than per-row statements+- **Type-aware value formatting**: numerics unquoted, booleans as `true`/`false`, strings/dates quoted & escaped+- `CREATE INDEX` for all non-primary-key indices, including `USING method`, `INCLUDE (…)`, and partial `WHERE` conditions (PostgreSQL)++The old `exportSQL(data:table:to:)` is kept for backward compatibility but `ExportTableSheet` now always routes SQL exports through the new method (calls `describeTable` first to fetch the structure).++#### Smart SQL statement splitter+- `SidebarItemRow.splitSQLStatements(_:)` — Full state-machine tokenizer that splits a SQL dump correctly:+ - Skips `;` inside single-quoted strings (handles `''` escape)+ - Skips `;` inside double-quoted identifiers+ - Skips `;` inside `--` line comments and `/* */` block comments+- Replaces the previous naive `components(separatedBy: ";")` approach that would mis-split dumps containing strings with semicolons or timestamps++### Fixed+- **SQL export was not re-importable** — Previously `exportSQL` emitted only `INSERT` statements without any schema. Importing the file into an empty database failed with `relation "table" does not exist`. The new export includes DROP/CREATE/sequences/indices so the file can recreate the table exactly.++### Changed+- Removed noisy `[Structure]` debug `print` statements from `PostgreSQLAdapter.describeTable`++## [0.9.0] - 2026-04-05++### Added++#### CreateTableView — synced with Structure editor+- **Columns table** now has the same 8 columns as the Structure editor: #, column_name, data_type, is_nullable, check, foreign_key, column_default, comment. The standalone `PK` checkbox column was removed; toggle primary key via right-click context menu ("Set as Primary Key" / "Unset Primary Key").+- **Foreign key editor popover** — click the `foreign_key` cell to open a popover with Referenced Table picker (loads from current schema) and Referenced Column field. Generates `FOREIGN KEY (col) REFERENCES table(col)` in the CREATE TABLE.+- **Default value editor popover** — click the `column_default` cell to open a tabbed popover (String / Expression) with quick-pick buttons for CURRENT_TIMESTAMP, NOW(), gen_random_uuid(), true, false.+- **CHECK constraint** editable inline in the check column, emitted as `CHECK (expr)` in CREATE TABLE.+- **Indexes table** now has the same 7 columns as Structure: index_name, index_algorithm, is_unique, column_name, condition, include, comment. Supports partial indexes (`WHERE`) and INCLUDE columns (PostgreSQL).+- **Inline "+ New column" / "+ New index" buttons** below each table (matches Structure editor style). The toolbar no longer has these buttons; toolbar now only shows table name input, schema label, and Create button.+- **Default table name** is pre-filled as `new_table` so the Create button is enabled immediately.+- **First column auto-selected** on view appear so it's immediately editable.+- **Auto-close Create Table tab** after successful creation.++#### Delete table — mark-for-deletion workflow+- **Delete table popup** with two options (matches TablePlus):+ - ☐ **Ignore foreign key checks** — MySQL `SET FOREIGN_KEY_CHECKS = 0` around the DROP.+ - ☐ **Cascade** — PostgreSQL `DROP TABLE … CASCADE`.+- **Tables are not dropped immediately** — clicking OK marks the table for deletion. The sidebar row shows a red background and strikethrough text so the user can see what's pending.+- **Undo Delete** — right-click a pending table to clear the mark.+- **Commit via toolbar ✓ button** — the existing Commit Changes toolbar button (`checkmark.circle`) now also commits pending table deletions by observing `.commitChanges` in the sidebar. Runs `DROP TABLE IF EXISTS` for each marked table, applies cascade/ignore-FK flags per-table, closes any open tabs referencing dropped tables, and refreshes the sidebar.+- `AppState.pendingTableDeletions` `[String: PendingTableDeletion]` holds the marked tables with their per-table options.+- `DeleteTableSheet.swift` — new SwiftUI sheet for the delete confirmation.++## [0.8.1] - 2026-04-05++### Added+- **Inline "+" button on Tables group** in the sidebar — click to open a new Create Table tab directly (tooltip: "New Table"). Makes the action discoverable without needing to right-click.+- **"New Table…" in table context menus** — Right-clicking a table now shows "New Table…" between "Open structure" and "Copy name". Right-clicking the "Tables" group row also shows "New Table…" and "Open Table List".++### Removed+- **Sidebar bottom bar `+` and trash buttons** — Replaced by the inline "+" button on the Tables group and the context menu actions. Bottom bar now only shows the schema picker.++## [0.8.0] - 2026-04-05++### Added+- **Window auto-resize on launch / connect**:+ - On app launch the main window shrinks to its compact minimum (900×500, centered) so the connection picker feels like a focused starting screen+ - When `activeConnectionId` becomes non-nil (user connects to a database), the window automatically zooms to fill the available screen via `NSWindow.zoom(nil)` so the user gets full workspace immediately+- **Persistent details panel width** — Width is now stored in `AppState.detailsPanelWidth` (default 320pt) and survives toggling the panel off and on. Previously every toggle reset the width to the SwiftUI ideal value.+- **Custom `ResizeHandle`** (NSViewRepresentable) — Draggable vertical divider for the details panel, backed by an `NSView` with native `mouseDown`/`mouseDragged` tracking. Avoids the SwiftUI `DragGesture` re-layout storm that caused jitter during drag. Cursor hit area is 7pt wide for easier grabbing; the visible divider is 1pt.++### Changed+- **Details panel max width** — Capped at 50% of the main screen (was a fixed 420pt). Minimum remains 220pt.+- **No animations on panel toggles** — Removed `withAnimation { ... }` wrappers and the `.animation(.easeInOut, value:)` modifier from sidebar/details/AI panel toggles. Panels now open and close instantly with a `.transaction { $0.disablesAnimations = true }` on the workspace root. Applies to: toolbar toggle buttons, Cmd+\\ (Toggle Sidebar), Cmd+Shift+A (Toggle AI Panel), and the details panel toggle.+- **Replaced `HSplitView` with fixed-width layout** for the details panel. `HSplitView` tracks its own width and resets it whenever the view is recreated; a plain `HStack` + `ResizeHandle` + explicit `.frame(width: detailsPanelWidth)` gives us full control over persistence.+- **Default window size** — Changed `.defaultSize(width: 1200, height: 700)` to `.defaultSize(width: 900, height: 500)` to match the new compact launch experience.++## [0.7.0] - 2026-04-05++### Added+- **Sidebar Query History tab** — Persistent SQL history via SwiftData:+ - Records ONLY queries run from the SQL editor (not data grid loads, structure inspections, or internal DML)+ - Grouped by day with sticky headers (Today, Yesterday, weekday name, date)+ - Row layout: status dot (green/red) · timestamp · duration (ms/s) · row count · favorite star+ - 3-line SQL preview with keyword syntax highlighting (SELECT, FROM, WHERE, JOIN… rendered bold purple)+ - Error message rendered in red beneath the SQL for failed queries+ - Hover actions: inline Copy / Paste buttons appear on mouse-over+ - Double-click a row to paste the SQL into the active query editor tab+ - Context menu: Paste to Editor, Copy SQL, Favorite/Unfavorite, Delete+ - Search bar filters by SQL text (server-side via SwiftData predicate)+ - Footer: entry count + Clear button (scoped to active connection)+ - Empty state with helpful hint+- **`AppState.recordQueryHistory`** — Dedicated method that persists a query to the SwiftData history store, separate from the in-memory `logQuery` used by the bottom SQL log panel+- **`AppState.queryHistoryVersion`** — `@Published` counter that increments when a history entry is saved, observed by `QueryHistoryTab` to trigger reload++### Fixed+- **Query history was never saved** — `SwiftDataQueryHistoryRepository` existed and was registered in DI but was only called from `QueryEngine`, which `QueryEditorView` and `DataGridView` bypass. `QueryEditorView.executeQuery` and `explainQuery` now call `recordQueryHistory` on both success and failure paths.++## [0.6.0] - 2026-04-05++### Added+- **SQL Formatter** — `Format` and `Minify` buttons next to `Run` in the query editor:+ - **Format** (Ctrl+Shift+F): beautifies SQL with clause keywords on their own line, arguments indented by one tab. SELECT columns split onto separate lines, JOINs aligned at base indent with target + ON inline, nested function calls and string literals preserved.+ - **Minify**: collapses SQL onto a single line with single-space separators (strings preserved).+ - `SQLFormatter.swift` with custom tokenizer aware of strings, comments, and multi-char operators.+- **Query editor text persistence** — Switching tabs no longer loses the query being written. `AppState.queryEditorText[tabId]` caches text per-tab; restored on `onAppear`, saved on `onChange`.+- **Run statement at cursor** — Clicking Run (or ⌘R) now executes the single SQL statement that contains the cursor, not the entire editor contents. Splits on `;` while ignoring semicolons inside strings and comments. `SQLEditorView.Coordinator` forwards cursor position via `textViewDidChangeSelection`.+- **AppKitDataGrid for query results** — Query editor results now render in the same `AppKitDataGrid` (NSTableView-backed) used for table data, with column resizing, row selection, copy row/cell context menu, and alternating row backgrounds.++### Fixed+- **PostgreSQL error messages** — Queries that fail with `PSQLError` previously surfaced as the opaque "`PostgresNIO.PSQLError error 1.`". The adapter now extracts `message`, `detail`, `hint`, `position`, and `sqlState` from `PSQLError.serverInfo` and re-throws as `DataBridgeError.queryExecutionFailed` with a human-readable message.++## [0.5.0] - 2026-04-05++### Added+- **SQL Autocomplete Engine** — Professional inline completion popup for the query editor:+ - **Fuzzy matching** with scoring: exact match (1000) > exact prefix (500) > word-boundary prefix (200) > fuzzy subsequence (1-50)+ - **Ranking**: primary SQL keywords boosted, recently-used items tracked, type priority (keyword > table > column > function > join)+ - **Search across all schema** — keywords, tables, columns (from every table), 40+ SQL functions with signature hints+ - **Fuzzy match highlighting** — matched characters rendered in bold + accent color+ - **Match types with icons**: `k` keyword, `T` table, `C` column, `f` function, `J` join+ - **Debounced typing** (80ms) with instant dismiss on space/semicolon/newline+ - **Dot-trigger** — typing `alias.` still works for column completion+ - **Manual trigger** via Ctrl+Space+- **`CompletionWindow`** — Custom NSPanel popup with NSStackView-based row layout:+ - Fixed window size (420pt wide, max 10 items)+ - Pure NSView frame layout (no NSScrollView/NSTableView) — eliminates horizontal scroll/overflow issues+ - Visual effect background with rounded corners+ - Arrow key navigation, Enter/Tab to insert, Escape to dismiss+ - Screen-edge clamping (never overflows visible screen)+- **`SQLContextParser`** — Lightweight SQL tokenizer for cursor context detection (not used in current "search-all" mode but kept for future context-aware suggestions)+- **App Icon (`.app` bundle)** — `dev.sh` now wraps the SPM executable into a proper `.app` bundle with Info.plist + AppIcon.icns so Finder/Dock show the DataBridge logo instead of the generic "exec" icon+- **`CFBundleIconFile=AppIcon`** added to Info.plist++### Fixed+- **Bundle the app** — Running the raw SPM executable showed the generic exec icon; `dev.sh` now builds `.app` bundle with icon + resources+- **Completion popup window level** — Changed from `.popUpMenu` to `.floating` with `hidesOnDeactivate=true` so the popup no longer overlays other apps when DataBridge loses focus+- **Fatal error: "Can't take a prefix of negative length"** — Clamped `cursorOffset` and `prefixLength` in completion coordinator to prevent crash when cursor is at position 0++### Changed+- Replaced `AppIcon.icns` and all Assets icon sizes with new logo+- `logo.png` updated++## [0.4.0] - 2026-04-04++### Added+- **Table Context Menu** — Right-click tables in sidebar with full action menu:+ - Open in new tab / Open structure+ - Copy name+ - Export... (CSV/JSON/SQL with multi-table selection, configurable options)+ - Copy Script As (CREATE TABLE, SELECT, INSERT, UPDATE, DELETE)+ - Truncate... / Delete... with confirmation dialogs+- **Export Dialog** — Split-panel export UI:+ - Left panel: table list with checkboxes (multi-select, default = right-clicked table)+ - Right panel: CSV/JSON/SQL format tabs with options (delimiter, quoting, line break, decimal, NULL handling, field names header)+ - Single table export via NSSavePanel, multi-table via folder picker+- **New Database Dialog** — Create new database from Cmd+K switcher (Name, Encoding, Collation)+- **Open Structure** — Context menu + `AppState.openTableStructure()` opens table directly in Structure mode+- **Pointer Cursor** — `ClickableModifier.swift` with `.pointerCursor()` and `.clickable()` modifiers applied across all interactive elements (sidebar items, tab bar, bottom bar buttons, structure editor, filter bar)+- **Structure Editor — Auto-track on deselect** — Editing a column/index and clicking away now auto-detects changes (name, type, nullable, default, comment) without requiring Enter+- **Structure Editor — Inline add buttons** — "+ New column" / "+ New index" buttons below each table for quick creation+- **Structure Editor — Bottom bar buttons** — `+ Column` and `+ Index` moved from toolbar to bottom bar next to Structure tab++### Changed+- `ContentTab` now includes `initialViewMode` field for opening tabs in specific mode+- `BottomTabBar` accepts `showAddIndex` binding and `onAddColumn` callback+- `+ Index` form changed from popover to sheet for consistent positioning+- Export menu item added to Database menu in menu bar++### Fixed+- "Open in new tab" no longer creates duplicate tabs (reuses existing via `openTable()`)+- Structure editor column cell views extracted into `@ViewBuilder` functions to prevent horizontal scroll on row select++## [0.3.0] - 2026-04-04++### Added+- **Create Table view** — Full table creation UI with columns (name, type, PK, nullable, default, comment) and indexes (name, columns, unique, algorithm)+- **SQL Log toggle** — Bottom bar button to show/hide query log panel+- **Structure editor UX** — Prevent horizontal scroll when selecting rows by extracting cell views and controlling `@FocusState`++### Changed+- Data type arrays changed from private to internal for reuse in CreateTableView++## [0.2.0] - 2026-04-04++### Added+- **Row color coding** — New rows (green), deleted rows (red), edited rows (orange) with full-row NSTableRowView backgrounds+- **Column default editor** — Tabbed popover with String/Expression/Sequence tabs+- **Mark-for-deletion** — Dropped columns/indexes stay visible with red background and strikethrough, context menu shows "Undo Drop"+- **RowBackgroundSetter** — NSViewRepresentable that walks NSView hierarchy to set NSTableRowView.backgroundColor++### Fixed+- NOT NULL column creation auto-adds DEFAULT based on data type (int→0, bool→false, timestamp→CURRENT_TIMESTAMP, etc.)+- Duplicate column prevention with `IF NOT EXISTS`+- TextField height increased with `.squareBorder` style+- Background colors clear after Apply via table reload++### Changed+- `TableDescription`, `IndexInfo`, `ForeignKeyInfo`, `ConstraintInfo` now conform to `Equatable`+- `listForeignKeys`/`listAllConstraints` return CHECK constraint definitions (all adapters)++## [0.1.0] - 2026-04-03++### Added+- **Editable Structure view** — Inline editing of columns (rename, type, nullable, default, comment) and indexes+- **Foreign Key editor** — Popover for creating/editing FK constraints with referenced table/column pickers+- **Index management** — Add/modify/drop indexes with algorithm, unique, condition, include, comment support+- **Structure change tracking** — `StructureChange` enum with SQL generation for ALTER TABLE operations+- **Commit preview** — Review generated SQL before applying structure changes++## [0.0.2] - 2026-04-02++### Added+- **DataGrid performance** — NSTableView-backed grid with virtualized rendering+- **FK/Enum/Boolean UI** — Clickable foreign key links, enum dropdowns, boolean toggles in data cells+- **Function editor** — View and edit database functions+- **Dark mode** — Full dark mode support++## [0.0.1] - 2026-04-01++### Added+- Initial release+- Connection management (PostgreSQL, MySQL, SQLite) with SSH tunnel support+- Database browser with sidebar tree (schemas, tables, views, functions)+- Data grid with pagination, sorting, filtering+- Query editor with syntax highlighting+- AI chat integration (Anthropic/OpenAI/Ollama)+- MCP server for external AI agentsdiff --git a/CLAUDE.md b/CLAUDE.mdnew file mode 100644index 0000000..4ae01b9--- /dev/null+++ b/CLAUDE.md@@ -0,0 +1,41 @@+# Gridex — AI-Native Database IDE for macOS++## Project Overview+Native macOS app (Swift, AppKit) combining a powerful database GUI with built-in AI chat.++## Architecture+Clean Architecture with 5 layers:+- **Core**: Protocols, Models, Enums, Errors, Extensions — zero dependencies+- **Domain**: Use Cases, Repository protocols — depends only on Core+- **Data**: Database adapters (SQLite, PostgreSQL, MySQL, Redis), SwiftData persistence, Keychain — implements Domain+- **Services**: Query Engine, AI (Anthropic/OpenAI/Ollama), SSH Tunnel, Import/Export+- **Presentation**: AppKit views (NSTableView, NSOutlineView, NSSplitView), SwiftUI settings, ViewModels, Coordinators++## Tech Stack+- **Language**: Swift 5.10++- **UI**: AppKit (primary) + SwiftUI (settings, forms)+- **Persistence**: SwiftData+- **Credentials**: macOS Keychain+- **DB Drivers**: PostgresNIO, MySQLNIO, SQLite3, RediStack+- **SSH**: swift-nio-ssh+- **AI**: Direct API calls to Anthropic/OpenAI, local Ollama++## Key Conventions+- All database adapters conform to `DatabaseAdapter` protocol+- All LLM providers conform to `LLMService` protocol+- Use `actor` for thread-safe services (ConnectionManager, QueryEngine)+- SwiftData `@Model` entities live in Data/Persistence/Models+- Domain models are plain structs (Codable, Sendable)+- Dependency injection via `DependencyContainer`+- Errors centralized in `GridexError` enum++## Folder Structure+- `macos/` — macOS app source code+- `window/` — Windows app (future)+- `Package.swift` — SPM manifest++## Build & Run+```bash+swift build+.build/debug/Gridex+```diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.mdnew file mode 100644index 0000000..6121803--- /dev/null+++ b/CODE_OF_CONDUCT.md@@ -0,0 +1,35 @@+# Code of Conduct++## Our Pledge++We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.++We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.++## Our Standards++Examples of behavior that contributes to a positive environment:++- Demonstrating empathy and kindness toward other people+- Being respectful of differing opinions, viewpoints, and experiences+- Giving and gracefully accepting constructive feedback+- Accepting responsibility, apologizing to those affected by our mistakes, and learning from the experience+- Focusing on what is best not just for us as individuals, but for the overall community++Examples of unacceptable behavior:++- The use of sexualized language or imagery, and sexual attention or advances of any kind+- Trolling, insulting or derogatory comments, and personal or political attacks+- Public or private harassment+- Publishing others' private information, such as a physical or email address, without their explicit permission+- Other conduct which could reasonably be considered inappropriate in a professional setting++## Enforcement++Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the maintainers at **[email protected]** (or the maintainer's GitHub-listed contact). All complaints will be reviewed and investigated promptly and fairly.++Maintainers are obligated to respect the privacy and security of the reporter of any incident.++## Attribution++This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 2.1, available at https://www.contributor-covenant.org/version/2/1/code_of_conduct.html.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdnew file mode 100644index 0000000..36a115c--- /dev/null+++ b/CONTRIBUTING.md@@ -0,0 +1,58 @@+# Contributing to Gridex++Thanks for your interest in improving Gridex. This document covers the basics; more context lives in [README.md](README.md) and [CLAUDE.md](CLAUDE.md).++## Ways to contribute++- **Bug reports** — open a GitHub issue with reproduction steps, expected vs. actual, and your OS/version.+- **Feature requests** — open an issue first to discuss. Describe the problem before the proposed solution.+- **Pull requests** — for anything beyond a small typo fix, please open an issue first so we can align on scope.+- **Documentation** — improvements to README, guides, or inline comments are always welcome.++## Development setup++Prerequisites:+- macOS 14 (Sonoma) or later+- Xcode 15.3+ / Swift 5.10++- (Optional) Node 20+ if working on the `landing/` folder++```bash+git clone https://github.com/YOUR_FORK/gridex.git+cd gridex++# Debug build — ad-hoc signed, runs locally+./scripts/build-app.sh+open dist/Gridex.app++# Or run directly (no bundle)+swift build+.build/debug/Gridex+```++## Project structure++```+macos/ macOS app (Swift + AppKit)+windows/ Windows app (C++ / WinUI3 / cppwinrt)+landing/ Marketing site (Next.js)+scripts/ Build, sign, notarize, release scripts+```++See [CLAUDE.md](CLAUDE.md) for architecture conventions (Clean Architecture, 5 layers).++## Code style++- Swift: follow the surrounding style. Prefer `struct` over `class` unless you need identity. Use `actor` for thread-safe services.+- No comments that restate what the code does. Add a comment only when the *why* is non-obvious.+- Small, focused commits. Conventional commits (`feat:`, `fix:`, `chore:`, `refactor:`) encouraged but not required.++## Pull request checklist++- [ ] Build passes: `swift build` succeeds with no new warnings+- [ ] Manual smoke test of the affected feature on macOS 14++- [ ] Updated [CHANGELOG.md](CHANGELOG.md) with a one-liner under the next unreleased version heading+- [ ] No personal API keys, paths, or credentials in the diff (automated via `.gitignore`)++## License++By contributing, you agree that your contributions will be licensed under the [Apache License 2.0](LICENSE) — the same license as the project.diff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..11eda90--- /dev/null+++ b/LICENSE@@ -0,0 +1,201 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for describing the origin of the Work and+ reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Support. While redistributing the Work or+ Derivative Works thereof, You may choose to offer, and charge a+ fee for, acceptance of support, warranty, indemnity, or other+ liability obligations and/or rights consistent with this License.+ However, in accepting such obligations, You may act only on Your+ own behalf and on Your sole responsibility, not on behalf of any+ other Contributor, and only if You agree to indemnify, defend,+ and hold each Contributor harmless for any liability incurred by,+ or claims asserted against, such Contributor by reason of your+ accepting any such warranty or support.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "page" as the copyright notice for easier identification+ within third-party archives.++ Copyright 2026 Thinh Nguyen++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied. See the License for the specific language governing permissions+ and limitations under the License.diff --git a/NOTICE b/NOTICEnew file mode 100644index 0000000..8cd7195--- /dev/null+++ b/NOTICE@@ -0,0 +1,15 @@+Gridex+Copyright 2026 Thinh Nguyen++This product includes software developed by Thinh Nguyen (https://gridex.app).++Licensed under the Apache License, Version 2.0 (the "License");+you may not use this file except in compliance with the License.+You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++Third-party components:+- swift-nio, swift-nio-ssh, PostgresNIO, MySQLNIO, RediStack, MongoKitten,+ Hummingbird, SQLite3 — see Package.resolved for versions and their respective+ Apache-2.0 / MIT licenses.diff --git a/Package.swift b/Package.swiftnew file mode 100644index 0000000..cf59cc9--- /dev/null+++ b/Package.swift@@ -0,0 +1,60 @@+// swift-tools-version: 5.10++import PackageDescription++let package = Package(+ name: "Gridex",+ platforms: [+ .macOS(.v14)+ ],+ products: [+ .executable(name: "Gridex", targets: ["Gridex"]),+ ],+ dependencies: [+ // PostgreSQL driver+ .package(url: "https://github.com/vapor/postgres-nio.git", from: "1.21.0"),+ // MySQL driver+ .package(url: "https://github.com/vapor/mysql-nio.git", from: "1.7.0"),+ // TLS for Redis and other NIO connections+ .package(url: "https://github.com/apple/swift-nio-ssl.git", from: "2.27.0"),+ // SSH tunneling+ .package(url: "https://github.com/apple/swift-nio-ssh.git", from: "0.8.0"),+ // Redis driver+ .package(url: "https://github.com/swift-server/RediStack.git", from: "1.6.0"),+ // MongoDB driver (pure Swift, NIO-based)+ .package(url: "https://github.com/orlandos-nl/MongoKitten.git", from: "7.9.0"),+ // MSSQL driver (TDS 7.4, pure Swift NIO, no FreeTDS)+ .package(url: "https://github.com/vkuttyp/CosmoSQLClient-Swift.git", branch: "main"),+ ],+ targets: [+ .executableTarget(+ name: "Gridex",+ dependencies: [+ .product(name: "PostgresNIO", package: "postgres-nio"),+ .product(name: "MySQLNIO", package: "mysql-nio"),+ .product(name: "RediStack", package: "RediStack"),+ .product(name: "MongoKitten", package: "MongoKitten"),+ .product(name: "CosmoMSSQL", package: "CosmoSQLClient-Swift"),+ .product(name: "NIOSSL", package: "swift-nio-ssl"),+ .product(name: "NIOSSH", package: "swift-nio-ssh"),+ ],+ path: "macos",+ exclude: [+ "Resources/Info.plist",+ ],+ resources: [+ .copy("Resources/Gridex.entitlements"),+ .process("Resources/Assets.xcassets"),+ ],+ linkerSettings: [+ .linkedLibrary("sqlite3"),+ .unsafeFlags([+ "-Xlinker", "-sectcreate",+ "-Xlinker", "__TEXT",+ "-Xlinker", "__info_plist",+ "-Xlinker", "macos/Resources/Info.plist",+ ]),+ ]+ ),+ ]+)diff --git a/README.md b/README.mdnew file mode 100644index 0000000..68d86fe--- /dev/null+++ b/README.md@@ -0,0 +1,102 @@+# Gridex++A native macOS database IDE built with Swift and AppKit. Connect to PostgreSQL, MySQL, SQLite, and Redis from a single app with a fast, keyboard-driven interface.++++++## Features++### Multi-Database Support+- **PostgreSQL** — full schema inspection, parameterized queries, SSL/TLS+- **MySQL** — information_schema queries, SSL support+- **SQLite** — file-based, WAL mode, zero config+- **Redis** — key browser, pattern filter, Server INFO dashboard, Slow Log viewer++### Data Grid+- Inline cell editing with type-aware parsing+- Sort, filter, and paginate large datasets+- Add/delete rows with pending changes and commit workflow+- Copy rows, export to CSV/SQL++### Query Editor+- Syntax highlighting and auto-completion (tables, columns, functions)+- Execute at cursor, explain plan, format SQL+- Per-tab query persistence+- Redis CLI mode with command execution++### Schema Tools+- Table structure viewer (columns, indexes, foreign keys, constraints)+- Create/alter tables with visual editor+- ER Diagram with auto-layout, zoom, pan, and FK relationship lines+- Function viewer with source code display++### Redis Management+- Virtual "Keys" table with SCAN-based browsing+- Key Detail View — edit hash fields, list items, set/zset members+- Pattern-based filter bar (glob syntax: `user:*`, `cache:?`)+- Server INFO dashboard with auto-refresh and key metrics+- Slow Log viewer, Flush DB, key rename/duplicate, TTL management++### Other+- Multi-window support (Cmd+N) — work with multiple databases simultaneously+- Backup & Restore wizard (pg_dump, mysqldump, SQLite copy)+- Query history with favorites (persisted via SwiftData)+- macOS Keychain integration for credential storage+- Dark mode native++## Requirements++- macOS 14.0 (Sonoma) or later+- Swift 5.10+++## Build & Run++```bash+git clone https://github.com/user/gridex.git+cd gridex+swift build+.build/debug/Gridex+```++## Architecture++Clean Architecture with 5 layers:++```+macos/+ Core/ Protocols, Models, Enums, Errors — zero dependencies+ Domain/ Use Cases, Repository protocols+ Data/ Database adapters, SwiftData persistence, Keychain+ Services/ Query Engine, AI, SSH, Import/Export+ Presentation/ AppKit + SwiftUI views, ViewModels+window/ Windows app (planned)+```++### Tech Stack+- **UI**: AppKit (primary) + SwiftUI (settings, forms, sheets)+- **Persistence**: SwiftData+- **DB Drivers**: [PostgresNIO](https://github.com/vapor/postgres-nio), [MySQLNIO](https://github.com/vapor/mysql-nio), SQLite3, [RediStack](https://github.com/swift-server/RediStack)+- **TLS**: [swift-nio-ssl](https://github.com/apple/swift-nio-ssl)+- **SSH**: [swift-nio-ssh](https://github.com/apple/swift-nio-ssh)++## Roadmap++- [ ] SSH tunnel connections+- [ ] AI chat with schema context (Anthropic/OpenAI/Ollama)+- [ ] Settings UI (themes, editor preferences, AI config)+- [ ] Data import (CSV, JSON, SQL dump)+- [ ] Windows port++## Contributing++Contributions are welcome! Please open an issue first to discuss what you'd like to change.++## License++Licensed under the [Apache License, Version 2.0](LICENSE).++Copyright © 2026 Thinh Nguyen.++You may use, modify, and distribute this software — including in commercial or closed-source products — provided you preserve the copyright notice and NOTICE file. See the LICENSE for full terms.diff --git a/SECURITY.md b/SECURITY.mdnew file mode 100644index 0000000..ca45040--- /dev/null+++ b/SECURITY.md@@ -0,0 +1,48 @@+# Security Policy++## Supported versions++Security fixes are provided for the latest minor release on `main`. Older releases are not patched.++| Version | Supported |+| ------- | ------------------ |+| latest | :white_check_mark: |+| older | :x: |++## Reporting a vulnerability++**Please do not open a public GitHub issue for security vulnerabilities.**++Email security reports to **[email protected]** (or the maintainer's GitHub-listed contact) with:++- A description of the issue+- Steps to reproduce+- The affected version+- (Optional) Proof-of-concept code++You can expect:++- Acknowledgement within **72 hours**+- An initial assessment within **7 days**+- A patch released as soon as feasible based on severity++Responsible disclosure is appreciated — please allow time for a fix before public disclosure. Credit will be given in release notes unless you prefer anonymity.++## Scope++In scope:+- The Gridex macOS app (`macos/`)+- The Gridex Windows app (`windows/`)+- Build and release scripts (`scripts/`)+- The landing site (`landing/`)++Out of scope:+- Third-party dependencies — report upstream (Swift NIO, PostgresNIO, etc.)+- Self-compiled forks with modifications+- Issues in versions older than the latest release++## Credential handling++Gridex stores database and SSH passwords in the macOS Keychain using `kSecClassGenericPassword`. Credentials never leave the user's machine except via the SSH tunnel or database connection the user explicitly configures. AI provider API keys are stored the same way.++If you believe credentials are being logged, transmitted, or stored insecurely, please report via the channel above.diff --git a/dev.sh b/dev.shnew file mode 100755index 0000000..d36f385--- /dev/null+++ b/dev.sh@@ -0,0 +1,74 @@+#!/bin/bash+# DataBridge dev script — watch & auto-rebuild + relaunch as .app bundle+# Usage: ./dev.sh++set -e++APP_NAME="DataBridge"+BUILD_DIR=".build/debug"+APP_BUNDLE="$BUILD_DIR/$APP_NAME.app"++build_app_bundle() {+ # Wrap the executable into a proper .app bundle with icon+ local contents="$APP_BUNDLE/Contents"+ local macos="$contents/MacOS"+ local resources="$contents/Resources"++ rm -rf "$APP_BUNDLE"+ mkdir -p "$macos" "$resources"++ # Copy executable+ cp "$BUILD_DIR/$APP_NAME" "$macos/$APP_NAME"++ # Copy Info.plist+ cp "DataBridge/Resources/Info.plist" "$contents/Info.plist"++ # Copy icon+ cp "DataBridge/Resources/AppIcon.icns" "$resources/AppIcon.icns"++ # Copy SPM-generated resources bundle (Assets.xcassets, entitlements)+ if [ -d "$BUILD_DIR/${APP_NAME}_${APP_NAME}.bundle" ]; then+ cp -R "$BUILD_DIR/${APP_NAME}_${APP_NAME}.bundle" "$resources/"+ fi++ # Refresh the Finder icon cache for this bundle+ touch "$APP_BUNDLE"+}++cleanup() {+ killall "$APP_NAME" 2>/dev/null || true+ exit 0+}+trap cleanup SIGINT SIGTERM++build_and_run() {+ echo "🔨 Building..."+ killall "$APP_NAME" 2>/dev/null || true++ if swift build 2>&1; then+ echo "📦 Creating .app bundle..."+ build_app_bundle+ echo "✅ Build succeeded — launching app..."+ open "$APP_BUNDLE"+ else+ echo "❌ Build failed"+ fi+ echo ""+ echo "👀 Watching for changes... (Ctrl+C to stop)"+}++# Initial build+build_and_run++# Watch for .swift file changes using a simple polling loop+# Install fswatch for better performance: brew install fswatch+LAST_HASH=""+while true; do+ sleep 2+ CURRENT_HASH=$(find DataBridge -name "*.swift" -newer "$BUILD_DIR/$APP_NAME" 2>/dev/null | head -1)+ if [ -n "$CURRENT_HASH" ]; then+ echo ""+ echo "📝 Change detected..."+ build_and_run+ fi+donediff --git a/landing/.gitignore b/landing/.gitignorenew file mode 100644index 0000000..5ef6a52--- /dev/null+++ b/landing/.gitignore@@ -0,0 +1,41 @@+# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.++# dependencies+/node_modules+/.pnp+.pnp.*+.yarn/*+!.yarn/patches+!.yarn/plugins+!.yarn/releases+!.yarn/versions++# testing+/coverage++# next.js+/.next/+/out/++# production+/build++# misc+.DS_Store+*.pem++# debug+npm-debug.log*+yarn-debug.log*+yarn-error.log*+.pnpm-debug.log*++# env files (can opt-in for committing if needed)+.env*++# vercel+.vercel++# typescript+*.tsbuildinfo+next-env.d.tsdiff --git a/landing/AGENTS.md b/landing/AGENTS.mdnew file mode 100644index 0000000..8bd0e39--- /dev/null+++ b/landing/AGENTS.md@@ -0,0 +1,5 @@+<!-- BEGIN:nextjs-agent-rules -->+# This is NOT the Next.js you know++This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` before writing any code. Heed deprecation notices.+<!-- END:nextjs-agent-rules -->diff --git a/landing/CLAUDE.md b/landing/CLAUDE.mdnew file mode 100644index 0000000..43c994c--- /dev/null+++ b/landing/CLAUDE.md@@ -0,0 +1 @@diff --git a/landing/README.md b/landing/README.mdnew file mode 100644index 0000000..e215bc4--- /dev/null+++ b/landing/README.md@@ -0,0 +1,36 @@+This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).++## Getting Started++First, run the development server:++```bash+npm run dev+# or+yarn dev+# or+pnpm dev+# or+bun dev+```++Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.++You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.++This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.++## Learn More++To learn more about Next.js, take a look at the following resources:++- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.+- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.++You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!++## Deploy on Vercel++The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.++Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.diff --git a/landing/eslint.config.mjs b/landing/eslint.config.mjsnew file mode 100644index 0000000..05e726d--- /dev/null+++ b/landing/eslint.config.mjs@@ -0,0 +1,18 @@+import { defineConfig, globalIgnores } from "eslint/config";+import nextVitals from "eslint-config-next/core-web-vitals";+import nextTs from "eslint-config-next/typescript";++const eslintConfig = defineConfig([+ ...nextVitals,+ ...nextTs,+ // Override default ignores of eslint-config-next.+ globalIgnores([+ // Default ignores of eslint-config-next:+ ".next/**",+ "out/**",+ "build/**",+ "next-env.d.ts",+ ]),+]);++export default eslintConfig;diff --git a/landing/next.config.ts b/landing/next.config.tsnew file mode 100644index 0000000..e9ffa30--- /dev/null+++ b/landing/next.config.ts@@ -0,0 +1,7 @@+import type { NextConfig } from "next";++const nextConfig: NextConfig = {+ /* config options here */+};++export default nextConfig;diff --git a/landing/package-lock.json b/landing/package-lock.jsonnew file mode 100644index 0000000..9ec72f0--- /dev/null+++ b/landing/package-lock.json@@ -0,0 +1,6581 @@+{+ "name": "landing",+ "version": "0.1.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "landing",+ "version": "0.1.0",+ "dependencies": {+ "next": "16.2.3",+ "react": "19.2.4",+ "react-dom": "19.2.4",+ "react-icons": "^5.6.0"+ },+ "devDependencies": {+ "@tailwindcss/postcss": "^4",+ "@types/node": "^20",+ "@types/react": "^19",+ "@types/react-dom": "^19",+ "eslint": "^9",+ "eslint-config-next": "16.2.3",+ "tailwindcss": "^4",+ "typescript": "^5"+ }+ },+ "node_modules/@alloc/quick-lru": {+ "version": "5.2.0",+ "resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz",+ "integrity": "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/@babel/code-frame": {+ "version": "7.29.0",+ "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz",+ "integrity": "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/helper-validator-identifier": "^7.28.5",+ "js-tokens": "^4.0.0",+ "picocolors": "^1.1.1"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/compat-data": {+ "version": "7.29.0",+ "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.0.tgz",+ "integrity": "sha512-T1NCJqT/j9+cn8fvkt7jtwbLBfLC/1y1c7NtCeXFRgzGTsafi68MRv8yzkYSapBnFA6L3U2VSc02ciDzoAJhJg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/core": {+ "version": "7.29.0",+ "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.0.tgz",+ "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/code-frame": "^7.29.0",+ "@babel/generator": "^7.29.0",+ "@babel/helper-compilation-targets": "^7.28.6",+ "@babel/helper-module-transforms": "^7.28.6",+ "@babel/helpers": "^7.28.6",+ "@babel/parser": "^7.29.0",+ "@babel/template": "^7.28.6",+ "@babel/traverse": "^7.29.0",+ "@babel/types": "^7.29.0",+ "@jridgewell/remapping": "^2.3.5",+ "convert-source-map": "^2.0.0",+ "debug": "^4.1.0",+ "gensync": "^1.0.0-beta.2",+ "json5": "^2.2.3",+ "semver": "^6.3.1"+ },+ "engines": {+ "node": ">=6.9.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/babel"+ }+ },+ "node_modules/@babel/generator": {+ "version": "7.29.1",+ "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.1.tgz",+ "integrity": "sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/parser": "^7.29.0",+ "@babel/types": "^7.29.0",+ "@jridgewell/gen-mapping": "^0.3.12",+ "@jridgewell/trace-mapping": "^0.3.28",+ "jsesc": "^3.0.2"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helper-compilation-targets": {+ "version": "7.28.6",+ "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.28.6.tgz",+ "integrity": "sha512-JYtls3hqi15fcx5GaSNL7SCTJ2MNmjrkHXg4FSpOA/grxK8KwyZ5bubHsCq8FXCkua6xhuaaBit+3b7+VZRfcA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/compat-data": "^7.28.6",+ "@babel/helper-validator-option": "^7.27.1",+ "browserslist": "^4.24.0",+ "lru-cache": "^5.1.1",+ "semver": "^6.3.1"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helper-globals": {+ "version": "7.28.0",+ "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.28.0.tgz",+ "integrity": "sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helper-module-imports": {+ "version": "7.28.6",+ "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.28.6.tgz",+ "integrity": "sha512-l5XkZK7r7wa9LucGw9LwZyyCUscb4x37JWTPz7swwFE/0FMQAGpiWUZn8u9DzkSBWEcK25jmvubfpw2dnAMdbw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/traverse": "^7.28.6",+ "@babel/types": "^7.28.6"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helper-module-transforms": {+ "version": "7.28.6",+ "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.28.6.tgz",+ "integrity": "sha512-67oXFAYr2cDLDVGLXTEABjdBJZ6drElUSI7WKp70NrpyISso3plG9SAGEF6y7zbha/wOzUByWWTJvEDVNIUGcA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/helper-module-imports": "^7.28.6",+ "@babel/helper-validator-identifier": "^7.28.5",+ "@babel/traverse": "^7.28.6"+ },+ "engines": {+ "node": ">=6.9.0"+ },+ "peerDependencies": {+ "@babel/core": "^7.0.0"+ }+ },+ "node_modules/@babel/helper-string-parser": {+ "version": "7.27.1",+ "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz",+ "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helper-validator-identifier": {+ "version": "7.28.5",+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz",+ "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helper-validator-option": {+ "version": "7.27.1",+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.27.1.tgz",+ "integrity": "sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helpers": {+ "version": "7.29.2",+ "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.2.tgz",+ "integrity": "sha512-HoGuUs4sCZNezVEKdVcwqmZN8GoHirLUcLaYVNBK2J0DadGtdcqgr3BCbvH8+XUo4NGjNl3VOtSjEKNzqfFgKw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/template": "^7.28.6",+ "@babel/types": "^7.29.0"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/parser": {+ "version": "7.29.2",+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.2.tgz",+ "integrity": "sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/types": "^7.29.0"+ },+ "bin": {+ "parser": "bin/babel-parser.js"+ },+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/@babel/template": {+ "version": "7.28.6",+ "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.28.6.tgz",+ "integrity": "sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/code-frame": "^7.28.6",+ "@babel/parser": "^7.28.6",+ "@babel/types": "^7.28.6"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/traverse": {+ "version": "7.29.0",+ "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.0.tgz",+ "integrity": "sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/code-frame": "^7.29.0",+ "@babel/generator": "^7.29.0",+ "@babel/helper-globals": "^7.28.0",+ "@babel/parser": "^7.29.0",+ "@babel/template": "^7.28.6",+ "@babel/types": "^7.29.0",+ "debug": "^4.3.1"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/types": {+ "version": "7.29.0",+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz",+ "integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/helper-string-parser": "^7.27.1",+ "@babel/helper-validator-identifier": "^7.28.5"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@emnapi/core": {+ "version": "1.9.2",+ "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.9.2.tgz",+ "integrity": "sha512-UC+ZhH3XtczQYfOlu3lNEkdW/p4dsJ1r/bP7H8+rhao3TTTMO1ATq/4DdIi23XuGoFY+Cz0JmCbdVl0hz9jZcA==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@emnapi/wasi-threads": "1.2.1",+ "tslib": "^2.4.0"+ }+ },+ "node_modules/@emnapi/runtime": {+ "version": "1.9.2",+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.9.2.tgz",+ "integrity": "sha512-3U4+MIWHImeyu1wnmVygh5WlgfYDtyf0k8AbLhMFxOipihf6nrWC4syIm/SwEeec0mNSafiiNnMJwbza/Is6Lw==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "tslib": "^2.4.0"+ }+ },+ "node_modules/@emnapi/wasi-threads": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz",+ "integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "tslib": "^2.4.0"+ }+ },+ "node_modules/@eslint-community/eslint-utils": {+ "version": "4.9.1",+ "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz",+ "integrity": "sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "eslint-visitor-keys": "^3.4.3"+ },+ "engines": {+ "node": "^12.22.0 || ^14.17.0 || >=16.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ },+ "peerDependencies": {+ "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0"+ }+ },+ "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": {+ "version": "3.4.3",+ "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz",+ "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": "^12.22.0 || ^14.17.0 || >=16.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ }+ },+ "node_modules/@eslint-community/regexpp": {+ "version": "4.12.2",+ "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz",+ "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^12.0.0 || ^14.0.0 || >=16.0.0"+ }+ },+ "node_modules/@eslint/config-array": {+ "version": "0.21.2",+ "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.21.2.tgz",+ "integrity": "sha512-nJl2KGTlrf9GjLimgIru+V/mzgSK0ABCDQRvxw5BjURL7WfH5uoWmizbH7QB6MmnMBd8cIC9uceWnezL1VZWWw==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "@eslint/object-schema": "^2.1.7",+ "debug": "^4.3.1",+ "minimatch": "^3.1.5"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ }+ },+ "node_modules/@eslint/config-helpers": {+ "version": "0.4.2",+ "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.4.2.tgz",+ "integrity": "sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "@eslint/core": "^0.17.0"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ }+ },+ "node_modules/@eslint/core": {+ "version": "0.17.0",+ "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.17.0.tgz",+ "integrity": "sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "@types/json-schema": "^7.0.15"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ }+ },+ "node_modules/@eslint/eslintrc": {+ "version": "3.3.5",+ "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.3.5.tgz",+ "integrity": "sha512-4IlJx0X0qftVsN5E+/vGujTRIFtwuLbNsVUe7TO6zYPDR1O6nFwvwhIKEKSrl6dZchmYBITazxKoUYOjdtjlRg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "ajv": "^6.14.0",+ "debug": "^4.3.2",+ "espree": "^10.0.1",+ "globals": "^14.0.0",+ "ignore": "^5.2.0",+ "import-fresh": "^3.2.1",+ "js-yaml": "^4.1.1",+ "minimatch": "^3.1.5",+ "strip-json-comments": "^3.1.1"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ }+ },+ "node_modules/@eslint/js": {+ "version": "9.39.4",+ "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.39.4.tgz",+ "integrity": "sha512-nE7DEIchvtiFTwBw4Lfbu59PG+kCofhjsKaCWzxTpt4lfRjRMqG6uMBzKXuEcyXhOHoUp9riAm7/aWYGhXZ9cw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "url": "https://eslint.org/donate"+ }+ },+ "node_modules/@eslint/object-schema": {+ "version": "2.1.7",+ "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.7.tgz",+ "integrity": "sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ }+ },+ "node_modules/@eslint/plugin-kit": {+ "version": "0.4.1",+ "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.4.1.tgz",+ "integrity": "sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "@eslint/core": "^0.17.0",+ "levn": "^0.4.1"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ }+ },+ "node_modules/@humanfs/core": {+ "version": "0.19.1",+ "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz",+ "integrity": "sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=18.18.0"+ }+ },+ "node_modules/@humanfs/node": {+ "version": "0.16.7",+ "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.7.tgz",+ "integrity": "sha512-/zUx+yOsIrG4Y43Eh2peDeKCxlRt/gET6aHfaKpuq267qXdYDFViVHfMaLyygZOnl0kGWxFIgsBy8QFuTLUXEQ==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "@humanfs/core": "^0.19.1",+ "@humanwhocodes/retry": "^0.4.0"+ },+ "engines": {+ "node": ">=18.18.0"+ }+ },+ "node_modules/@humanwhocodes/module-importer": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz",+ "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=12.22"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/nzakas"+ }+ },+ "node_modules/@humanwhocodes/retry": {+ "version": "0.4.3",+ "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz",+ "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=18.18"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/nzakas"+ }+ },+ "node_modules/@img/colour": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz",+ "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==",+ "license": "MIT",+ "optional": true,+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@img/sharp-darwin-arm64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.34.5.tgz",+ "integrity": "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==",+ "cpu": [+ "arm64"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-darwin-arm64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-darwin-x64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.34.5.tgz",+ "integrity": "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==",+ "cpu": [+ "x64"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-darwin-x64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-libvips-darwin-arm64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.2.4.tgz",+ "integrity": "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==",+ "cpu": [+ "arm64"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "darwin"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-darwin-x64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.2.4.tgz",+ "integrity": "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==",+ "cpu": [+ "x64"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "darwin"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-arm": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.2.4.tgz",+ "integrity": "sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==",+ "cpu": [+ "arm"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-arm64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.2.4.tgz",+ "integrity": "sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==",+ "cpu": [+ "arm64"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-ppc64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.2.4.tgz",+ "integrity": "sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==",+ "cpu": [+ "ppc64"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-riscv64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.2.4.tgz",+ "integrity": "sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==",+ "cpu": [+ "riscv64"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-s390x": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.2.4.tgz",+ "integrity": "sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==",+ "cpu": [+ "s390x"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-x64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.2.4.tgz",+ "integrity": "sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==",+ "cpu": [+ "x64"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linuxmusl-arm64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.2.4.tgz",+ "integrity": "sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==",+ "cpu": [+ "arm64"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linuxmusl-x64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.2.4.tgz",+ "integrity": "sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==",+ "cpu": [+ "x64"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-linux-arm": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.34.5.tgz",+ "integrity": "sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==",+ "cpu": [+ "arm"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-arm": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linux-arm64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.34.5.tgz",+ "integrity": "sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==",+ "cpu": [+ "arm64"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-arm64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linux-ppc64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.34.5.tgz",+ "integrity": "sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==",+ "cpu": [+ "ppc64"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-ppc64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linux-riscv64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.34.5.tgz",+ "integrity": "sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==",+ "cpu": [+ "riscv64"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-riscv64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linux-s390x": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.34.5.tgz",+ "integrity": "sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==",+ "cpu": [+ "s390x"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-s390x": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linux-x64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.5.tgz",+ "integrity": "sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==",+ "cpu": [+ "x64"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-x64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linuxmusl-arm64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.34.5.tgz",+ "integrity": "sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==",+ "cpu": [+ "arm64"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linuxmusl-arm64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linuxmusl-x64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.34.5.tgz",+ "integrity": "sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==",+ "cpu": [+ "x64"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linuxmusl-x64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-wasm32": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.34.5.tgz",+ "integrity": "sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==",+ "cpu": [+ "wasm32"+ ],+ "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",+ "optional": true,+ "dependencies": {+ "@emnapi/runtime": "^1.7.0"+ },+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-win32-arm64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.34.5.tgz",+ "integrity": "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==",+ "cpu": [+ "arm64"+ ],+ "license": "Apache-2.0 AND LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-win32-ia32": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.34.5.tgz",+ "integrity": "sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==",+ "cpu": [+ "ia32"+ ],+ "license": "Apache-2.0 AND LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-win32-x64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.5.tgz",+ "integrity": "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==",+ "cpu": [+ "x64"+ ],+ "license": "Apache-2.0 AND LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@jridgewell/gen-mapping": {+ "version": "0.3.13",+ "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",+ "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/sourcemap-codec": "^1.5.0",+ "@jridgewell/trace-mapping": "^0.3.24"+ }+ },+ "node_modules/@jridgewell/remapping": {+ "version": "2.3.5",+ "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz",+ "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/gen-mapping": "^0.3.5",+ "@jridgewell/trace-mapping": "^0.3.24"+ }+ },+ "node_modules/@jridgewell/resolve-uri": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",+ "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/@jridgewell/sourcemap-codec": {+ "version": "1.5.5",+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",+ "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@jridgewell/trace-mapping": {+ "version": "0.3.31",+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",+ "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/resolve-uri": "^3.1.0",+ "@jridgewell/sourcemap-codec": "^1.4.14"+ }+ },+ "node_modules/@napi-rs/wasm-runtime": {+ "version": "0.2.12",+ "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-0.2.12.tgz",+ "integrity": "sha512-ZVWUcfwY4E/yPitQJl481FjFo3K22D6qF0DuFH6Y/nbnE11GY5uguDxZMGXPQ8WQ0128MXQD7TnfHyK4oWoIJQ==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@emnapi/core": "^1.4.3",+ "@emnapi/runtime": "^1.4.3",+ "@tybys/wasm-util": "^0.10.0"+ }+ },+ "node_modules/@next/env": {+ "version": "16.2.3",+ "resolved": "https://registry.npmjs.org/@next/env/-/env-16.2.3.tgz",+ "integrity": "sha512-ZWXyj4uNu4GCWQw9cjRxWlbD+33mcDszIo9iQxFnBX3Wmgq9ulaSJcl6VhuWx5pCWqqD+9W6Wfz7N0lM5lYPMA==",+ "license": "MIT"+ },+ "node_modules/@next/eslint-plugin-next": {+ "version": "16.2.3",+ "resolved": "https://registry.npmjs.org/@next/eslint-plugin-next/-/eslint-plugin-next-16.2.3.tgz",+ "integrity": "sha512-nE/b9mht28XJxjTwKs/yk7w4XTaU3t40UHVAky6cjiijdP/SEy3hGsnQMPxmXPTpC7W4/97okm6fngKnvCqVaA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "fast-glob": "3.3.1"+ }+ },+ "node_modules/@next/swc-darwin-arm64": {+ "version": "16.2.3",+ "resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-16.2.3.tgz",+ "integrity": "sha512-u37KDKTKQ+OQLvY+z7SNXixwo4Q2/IAJFDzU1fYe66IbCE51aDSAzkNDkWmLN0yjTUh4BKBd+hb69jYn6qqqSg==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@next/swc-darwin-x64": {+ "version": "16.2.3",+ "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-16.2.3.tgz",+ "integrity": "sha512-gHjL/qy6Q6CG3176FWbAKyKh9IfntKZTB3RY/YOJdDFpHGsUDXVH38U4mMNpHVGXmeYW4wj22dMp1lTfmu/bTQ==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@next/swc-linux-arm64-gnu": {+ "version": "16.2.3",+ "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.2.3.tgz",+ "integrity": "sha512-U6vtblPtU/P14Y/b/n9ZY0GOxbbIhTFuaFR7F4/uMBidCi2nSdaOFhA0Go81L61Zd6527+yvuX44T4ksnf8T+Q==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@next/swc-linux-arm64-musl": {+ "version": "16.2.3",+ "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.2.3.tgz",+ "integrity": "sha512-/YV0LgjHUmfhQpn9bVoGc4x4nan64pkhWR5wyEV8yCOfwwrH630KpvRg86olQHTwHIn1z59uh6JwKvHq1h4QEw==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@next/swc-linux-x64-gnu": {+ "version": "16.2.3",+ "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.2.3.tgz",+ "integrity": "sha512-/HiWEcp+WMZ7VajuiMEFGZ6cg0+aYZPqCJD3YJEfpVWQsKYSjXQG06vJP6F1rdA03COD9Fef4aODs3YxKx+RDQ==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@next/swc-linux-x64-musl": {+ "version": "16.2.3",+ "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.2.3.tgz",+ "integrity": "sha512-Kt44hGJfZSefebhk/7nIdivoDr3Ugp5+oNz9VvF3GUtfxutucUIHfIO0ZYO8QlOPDQloUVQn4NVC/9JvHRk9hw==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@next/swc-win32-arm64-msvc": {+ "version": "16.2.3",+ "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.2.3.tgz",+ "integrity": "sha512-O2NZ9ie3Tq6xj5Z5CSwBT3+aWAMW2PIZ4egUi9MaWLkwaehgtB7YZjPm+UpcNpKOme0IQuqDcor7BsW6QBiQBw==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@next/swc-win32-x64-msvc": {+ "version": "16.2.3",+ "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.2.3.tgz",+ "integrity": "sha512-Ibm29/GgB/ab5n7XKqlStkm54qqZE8v2FnijUPBgrd67FWrac45o/RsNlaOWjme/B5UqeWt/8KM4aWBwA1D2Kw==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@nodelib/fs.scandir": {+ "version": "2.1.5",+ "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",+ "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@nodelib/fs.stat": "2.0.5",+ "run-parallel": "^1.1.9"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/@nodelib/fs.stat": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz",+ "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/@nodelib/fs.walk": {+ "version": "1.2.8",+ "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz",+ "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@nodelib/fs.scandir": "2.1.5",+ "fastq": "^1.6.0"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/@nolyfill/is-core-module": {+ "version": "1.0.39",+ "resolved": "https://registry.npmjs.org/@nolyfill/is-core-module/-/is-core-module-1.0.39.tgz",+ "integrity": "sha512-nn5ozdjYQpUCZlWGuxcJY/KpxkWQs4DcbMCmKojjyrYDEAGy4Ce19NN4v5MduafTwJlbKc99UA8YhSVqq9yPZA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12.4.0"+ }+ },+ "node_modules/@rtsao/scc": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@rtsao/scc/-/scc-1.1.0.tgz",+ "integrity": "sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@swc/helpers": {+ "version": "0.5.15",+ "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.15.tgz",+ "integrity": "sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g==",+ "license": "Apache-2.0",+ "dependencies": {+ "tslib": "^2.8.0"+ }+ },+ "node_modules/@tailwindcss/node": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.2.2.tgz",+ "integrity": "sha512-pXS+wJ2gZpVXqFaUEjojq7jzMpTGf8rU6ipJz5ovJV6PUGmlJ+jvIwGrzdHdQ80Sg+wmQxUFuoW1UAAwHNEdFA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/remapping": "^2.3.5",+ "enhanced-resolve": "^5.19.0",+ "jiti": "^2.6.1",+ "lightningcss": "1.32.0",+ "magic-string": "^0.30.21",+ "source-map-js": "^1.2.1",+ "tailwindcss": "4.2.2"+ }+ },+ "node_modules/@tailwindcss/oxide": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.2.2.tgz",+ "integrity": "sha512-qEUA07+E5kehxYp9BVMpq9E8vnJuBHfJEC0vPC5e7iL/hw7HR61aDKoVoKzrG+QKp56vhNZe4qwkRmMC0zDLvg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 20"+ },+ "optionalDependencies": {+ "@tailwindcss/oxide-android-arm64": "4.2.2",+ "@tailwindcss/oxide-darwin-arm64": "4.2.2",+ "@tailwindcss/oxide-darwin-x64": "4.2.2",+ "@tailwindcss/oxide-freebsd-x64": "4.2.2",+ "@tailwindcss/oxide-linux-arm-gnueabihf": "4.2.2",+ "@tailwindcss/oxide-linux-arm64-gnu": "4.2.2",+ "@tailwindcss/oxide-linux-arm64-musl": "4.2.2",+ "@tailwindcss/oxide-linux-x64-gnu": "4.2.2",+ "@tailwindcss/oxide-linux-x64-musl": "4.2.2",+ "@tailwindcss/oxide-wasm32-wasi": "4.2.2",+ "@tailwindcss/oxide-win32-arm64-msvc": "4.2.2",+ "@tailwindcss/oxide-win32-x64-msvc": "4.2.2"+ }+ },+ "node_modules/@tailwindcss/oxide-android-arm64": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.2.2.tgz",+ "integrity": "sha512-dXGR1n+P3B6748jZO/SvHZq7qBOqqzQ+yFrXpoOWWALWndF9MoSKAT3Q0fYgAzYzGhxNYOoysRvYlpixRBBoDg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/oxide-darwin-arm64": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.2.2.tgz",+ "integrity": "sha512-iq9Qjr6knfMpZHj55/37ouZeykwbDqF21gPFtfnhCCKGDcPI/21FKC9XdMO/XyBM7qKORx6UIhGgg6jLl7BZlg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/oxide-darwin-x64": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.2.2.tgz",+ "integrity": "sha512-BlR+2c3nzc8f2G639LpL89YY4bdcIdUmiOOkv2GQv4/4M0vJlpXEa0JXNHhCHU7VWOKWT/CjqHdTP8aUuDJkuw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/oxide-freebsd-x64": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.2.2.tgz",+ "integrity": "sha512-YUqUgrGMSu2CDO82hzlQ5qSb5xmx3RUrke/QgnoEx7KvmRJHQuZHZmZTLSuuHwFf0DJPybFMXMYf+WJdxHy/nQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.2.2.tgz",+ "integrity": "sha512-FPdhvsW6g06T9BWT0qTwiVZYE2WIFo2dY5aCSpjG/S/u1tby+wXoslXS0kl3/KXnULlLr1E3NPRRw0g7t2kgaQ==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/oxide-linux-arm64-gnu": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.2.2.tgz",+ "integrity": "sha512-4og1V+ftEPXGttOO7eCmW7VICmzzJWgMx+QXAJRAhjrSjumCwWqMfkDrNu1LXEQzNAwz28NCUpucgQPrR4S2yw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/oxide-linux-arm64-musl": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.2.2.tgz",+ "integrity": "sha512-oCfG/mS+/+XRlwNjnsNLVwnMWYH7tn/kYPsNPh+JSOMlnt93mYNCKHYzylRhI51X+TbR+ufNhhKKzm6QkqX8ag==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/oxide-linux-x64-gnu": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.2.2.tgz",+ "integrity": "sha512-rTAGAkDgqbXHNp/xW0iugLVmX62wOp2PoE39BTCGKjv3Iocf6AFbRP/wZT/kuCxC9QBh9Pu8XPkv/zCZB2mcMg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/oxide-linux-x64-musl": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.2.2.tgz",+ "integrity": "sha512-XW3t3qwbIwiSyRCggeO2zxe3KWaEbM0/kW9e8+0XpBgyKU4ATYzcVSMKteZJ1iukJ3HgHBjbg9P5YPRCVUxlnQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/oxide-wasm32-wasi": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.2.2.tgz",+ "integrity": "sha512-eKSztKsmEsn1O5lJ4ZAfyn41NfG7vzCg496YiGtMDV86jz1q/irhms5O0VrY6ZwTUkFy/EKG3RfWgxSI3VbZ8Q==",+ "bundleDependencies": [+ "@napi-rs/wasm-runtime",+ "@emnapi/core",+ "@emnapi/runtime",+ "@tybys/wasm-util",+ "@emnapi/wasi-threads",+ "tslib"+ ],+ "cpu": [+ "wasm32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@emnapi/core": "^1.8.1",+ "@emnapi/runtime": "^1.8.1",+ "@emnapi/wasi-threads": "^1.1.0",+ "@napi-rs/wasm-runtime": "^1.1.1",+ "@tybys/wasm-util": "^0.10.1",+ "tslib": "^2.8.1"+ },+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/@tailwindcss/oxide-win32-arm64-msvc": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.2.2.tgz",+ "integrity": "sha512-qPmaQM4iKu5mxpsrWZMOZRgZv1tOZpUm+zdhhQP0VhJfyGGO3aUKdbh3gDZc/dPLQwW4eSqWGrrcWNBZWUWaXQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/oxide-win32-x64-msvc": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.2.2.tgz",+ "integrity": "sha512-1T/37VvI7WyH66b+vqHj/cLwnCxt7Qt3WFu5Q8hk65aOvlwAhs7rAp1VkulBJw/N4tMirXjVnylTR72uI0HGcA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/postcss": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/postcss/-/postcss-4.2.2.tgz",+ "integrity": "sha512-n4goKQbW8RVXIbNKRB/45LzyUqN451deQK0nzIeauVEqjlI49slUlgKYJM2QyUzap/PcpnS7kzSUmPb1sCRvYQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@alloc/quick-lru": "^5.2.0",+ "@tailwindcss/node": "4.2.2",+ "@tailwindcss/oxide": "4.2.2",+ "postcss": "^8.5.6",+ "tailwindcss": "4.2.2"+ }+ },+ "node_modules/@tybys/wasm-util": {+ "version": "0.10.1",+ "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.1.tgz",+ "integrity": "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "tslib": "^2.4.0"+ }+ },+ "node_modules/@types/estree": {+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",+ "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/json-schema": {+ "version": "7.0.15",+ "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",+ "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/json5": {+ "version": "0.0.29",+ "resolved": "https://registry.npmjs.org/@types/json5/-/json5-0.0.29.tgz",+ "integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/node": {+ "version": "20.19.39",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.39.tgz",+ "integrity": "sha512-orrrD74MBUyK8jOAD/r0+lfa1I2MO6I+vAkmAWzMYbCcgrN4lCrmK52gRFQq/JRxfYPfonkr4b0jcY7Olqdqbw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "undici-types": "~6.21.0"+ }+ },+ "node_modules/@types/react": {+ "version": "19.2.14",+ "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.14.tgz",+ "integrity": "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "csstype": "^3.2.2"+ }+ },+ "node_modules/@types/react-dom": {+ "version": "19.2.3",+ "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz",+ "integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==",+ "dev": true,+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "^19.2.0"+ }+ },+ "node_modules/@typescript-eslint/eslint-plugin": {+ "version": "8.58.1",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.58.1.tgz",+ "integrity": "sha512-eSkwoemjo76bdXl2MYqtxg51HNwUSkWfODUOQ3PaTLZGh9uIWWFZIjyjaJnex7wXDu+TRx+ATsnSxdN9YWfRTQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@eslint-community/regexpp": "^4.12.2",+ "@typescript-eslint/scope-manager": "8.58.1",+ "@typescript-eslint/type-utils": "8.58.1",+ "@typescript-eslint/utils": "8.58.1",+ "@typescript-eslint/visitor-keys": "8.58.1",+ "ignore": "^7.0.5",+ "natural-compare": "^1.4.0",+ "ts-api-utils": "^2.5.0"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ },+ "peerDependencies": {+ "@typescript-eslint/parser": "^8.58.1",+ "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",+ "typescript": ">=4.8.4 <6.1.0"+ }+ },+ "node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": {+ "version": "7.0.5",+ "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz",+ "integrity": "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 4"+ }+ },+ "node_modules/@typescript-eslint/parser": {+ "version": "8.58.1",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.58.1.tgz",+ "integrity": "sha512-gGkiNMPqerb2cJSVcruigx9eHBlLG14fSdPdqMoOcBfh+vvn4iCq2C8MzUB89PrxOXk0y3GZ1yIWb9aOzL93bw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@typescript-eslint/scope-manager": "8.58.1",+ "@typescript-eslint/types": "8.58.1",+ "@typescript-eslint/typescript-estree": "8.58.1",+ "@typescript-eslint/visitor-keys": "8.58.1",+ "debug": "^4.4.3"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ },+ "peerDependencies": {+ "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",+ "typescript": ">=4.8.4 <6.1.0"+ }+ },+ "node_modules/@typescript-eslint/project-service": {+ "version": "8.58.1",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.58.1.tgz",+ "integrity": "sha512-gfQ8fk6cxhtptek+/8ZIqw8YrRW5048Gug8Ts5IYcMLCw18iUgrZAEY/D7s4hkI0FxEfGakKuPK/XUMPzPxi5g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@typescript-eslint/tsconfig-utils": "^8.58.1",+ "@typescript-eslint/types": "^8.58.1",+ "debug": "^4.4.3"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ },+ "peerDependencies": {+ "typescript": ">=4.8.4 <6.1.0"+ }+ },+ "node_modules/@typescript-eslint/scope-manager": {+ "version": "8.58.1",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.58.1.tgz",+ "integrity": "sha512-TPYUEqJK6avLcEjumWsIuTpuYODTTDAtoMdt8ZZa93uWMTX13Nb8L5leSje1NluammvU+oI3QRr5lLXPgihX3w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@typescript-eslint/types": "8.58.1",+ "@typescript-eslint/visitor-keys": "8.58.1"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ }+ },+ "node_modules/@typescript-eslint/tsconfig-utils": {+ "version": "8.58.1",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.58.1.tgz",+ "integrity": "sha512-JAr2hOIct2Q+qk3G+8YFfqkqi7sC86uNryT+2i5HzMa2MPjw4qNFvtjnw1IiA1rP7QhNKVe21mSSLaSjwA1Olw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ },+ "peerDependencies": {+ "typescript": ">=4.8.4 <6.1.0"+ }+ },+ "node_modules/@typescript-eslint/type-utils": {+ "version": "8.58.1",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.58.1.tgz",+ "integrity": "sha512-HUFxvTJVroT+0rXVJC7eD5zol6ID+Sn5npVPWoFuHGg9Ncq5Q4EYstqR+UOqaNRFXi5TYkpXXkLhoCHe3G0+7w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@typescript-eslint/types": "8.58.1",+ "@typescript-eslint/typescript-estree": "8.58.1",+ "@typescript-eslint/utils": "8.58.1",+ "debug": "^4.4.3",+ "ts-api-utils": "^2.5.0"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ },+ "peerDependencies": {+ "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",+ "typescript": ">=4.8.4 <6.1.0"+ }+ },+ "node_modules/@typescript-eslint/types": {+ "version": "8.58.1",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.58.1.tgz",+ "integrity": "sha512-io/dV5Aw5ezwzfPBBWLoT+5QfVtP8O7q4Kftjn5azJ88bYyp/ZMCsyW1lpKK46EXJcaYMZ1JtYj+s/7TdzmQMw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ }+ },+ "node_modules/@typescript-eslint/typescript-estree": {+ "version": "8.58.1",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.58.1.tgz",+ "integrity": "sha512-w4w7WR7GHOjqqPnvAYbazq+Y5oS68b9CzasGtnd6jIeOIeKUzYzupGTB2T4LTPSv4d+WPeccbxuneTFHYgAAWg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@typescript-eslint/project-service": "8.58.1",+ "@typescript-eslint/tsconfig-utils": "8.58.1",+ "@typescript-eslint/types": "8.58.1",+ "@typescript-eslint/visitor-keys": "8.58.1",+ "debug": "^4.4.3",+ "minimatch": "^10.2.2",+ "semver": "^7.7.3",+ "tinyglobby": "^0.2.15",+ "ts-api-utils": "^2.5.0"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ },+ "peerDependencies": {+ "typescript": ">=4.8.4 <6.1.0"+ }+ },+ "node_modules/@typescript-eslint/typescript-estree/node_modules/balanced-match": {+ "version": "4.0.4",+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",+ "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "18 || 20 || >=22"+ }+ },+ "node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": {+ "version": "5.0.5",+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.5.tgz",+ "integrity": "sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "balanced-match": "^4.0.2"+ },+ "engines": {+ "node": "18 || 20 || >=22"+ }+ },+ "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": {+ "version": "10.2.5",+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz",+ "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==",+ "dev": true,+ "license": "BlueOak-1.0.0",+ "dependencies": {+ "brace-expansion": "^5.0.5"+ },+ "engines": {+ "node": "18 || 20 || >=22"+ },+ "funding": {+ "url": "https://github.com/sponsors/isaacs"+ }+ },+ "node_modules/@typescript-eslint/typescript-estree/node_modules/semver": {+ "version": "7.7.4",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",+ "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",+ "dev": true,+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/@typescript-eslint/utils": {+ "version": "8.58.1",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.58.1.tgz",+ "integrity": "sha512-Ln8R0tmWC7pTtLOzgJzYTXSCjJ9rDNHAqTaVONF4FEi2qwce8mD9iSOxOpLFFvWp/wBFlew0mjM1L1ihYWfBdQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@eslint-community/eslint-utils": "^4.9.1",+ "@typescript-eslint/scope-manager": "8.58.1",+ "@typescript-eslint/types": "8.58.1",+ "@typescript-eslint/typescript-estree": "8.58.1"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ },+ "peerDependencies": {+ "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",+ "typescript": ">=4.8.4 <6.1.0"+ }+ },+ "node_modules/@typescript-eslint/visitor-keys": {+ "version": "8.58.1",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.58.1.tgz",+ "integrity": "sha512-y+vH7QE8ycjoa0bWciFg7OpFcipUuem1ujhrdLtq1gByKwfbC7bPeKsiny9e0urg93DqwGcHey+bGRKCnF1nZQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@typescript-eslint/types": "8.58.1",+ "eslint-visitor-keys": "^5.0.0"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ }+ },+ "node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz",+ "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": "^20.19.0 || ^22.13.0 || >=24"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ }+ },+ "node_modules/@unrs/resolver-binding-android-arm-eabi": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-android-arm-eabi/-/resolver-binding-android-arm-eabi-1.11.1.tgz",+ "integrity": "sha512-ppLRUgHVaGRWUx0R0Ut06Mjo9gBaBkg3v/8AxusGLhsIotbBLuRk51rAzqLC8gq6NyyAojEXglNjzf6R948DNw==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ]+ },+ "node_modules/@unrs/resolver-binding-android-arm64": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-android-arm64/-/resolver-binding-android-arm64-1.11.1.tgz",+ "integrity": "sha512-lCxkVtb4wp1v+EoN+HjIG9cIIzPkX5OtM03pQYkG+U5O/wL53LC4QbIeazgiKqluGeVEeBlZahHalCaBvU1a2g==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ]+ },+ "node_modules/@unrs/resolver-binding-darwin-arm64": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-darwin-arm64/-/resolver-binding-darwin-arm64-1.11.1.tgz",+ "integrity": "sha512-gPVA1UjRu1Y/IsB/dQEsp2V1pm44Of6+LWvbLc9SDk1c2KhhDRDBUkQCYVWe6f26uJb3fOK8saWMgtX8IrMk3g==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@unrs/resolver-binding-darwin-x64": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-darwin-x64/-/resolver-binding-darwin-x64-1.11.1.tgz",+ "integrity": "sha512-cFzP7rWKd3lZaCsDze07QX1SC24lO8mPty9vdP+YVa3MGdVgPmFc59317b2ioXtgCMKGiCLxJ4HQs62oz6GfRQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@unrs/resolver-binding-freebsd-x64": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-freebsd-x64/-/resolver-binding-freebsd-x64-1.11.1.tgz",+ "integrity": "sha512-fqtGgak3zX4DCB6PFpsH5+Kmt/8CIi4Bry4rb1ho6Av2QHTREM+47y282Uqiu3ZRF5IQioJQ5qWRV6jduA+iGw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ]+ },+ "node_modules/@unrs/resolver-binding-linux-arm-gnueabihf": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm-gnueabihf/-/resolver-binding-linux-arm-gnueabihf-1.11.1.tgz",+ "integrity": "sha512-u92mvlcYtp9MRKmP+ZvMmtPN34+/3lMHlyMj7wXJDeXxuM0Vgzz0+PPJNsro1m3IZPYChIkn944wW8TYgGKFHw==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@unrs/resolver-binding-linux-arm-musleabihf": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm-musleabihf/-/resolver-binding-linux-arm-musleabihf-1.11.1.tgz",+ "integrity": "sha512-cINaoY2z7LVCrfHkIcmvj7osTOtm6VVT16b5oQdS4beibX2SYBwgYLmqhBjA1t51CarSaBuX5YNsWLjsqfW5Cw==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@unrs/resolver-binding-linux-arm64-gnu": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm64-gnu/-/resolver-binding-linux-arm64-gnu-1.11.1.tgz",+ "integrity": "sha512-34gw7PjDGB9JgePJEmhEqBhWvCiiWCuXsL9hYphDF7crW7UgI05gyBAi6MF58uGcMOiOqSJ2ybEeCvHcq0BCmQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@unrs/resolver-binding-linux-arm64-musl": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm64-musl/-/resolver-binding-linux-arm64-musl-1.11.1.tgz",+ "integrity": "sha512-RyMIx6Uf53hhOtJDIamSbTskA99sPHS96wxVE/bJtePJJtpdKGXO1wY90oRdXuYOGOTuqjT8ACccMc4K6QmT3w==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@unrs/resolver-binding-linux-ppc64-gnu": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-ppc64-gnu/-/resolver-binding-linux-ppc64-gnu-1.11.1.tgz",+ "integrity": "sha512-D8Vae74A4/a+mZH0FbOkFJL9DSK2R6TFPC9M+jCWYia/q2einCubX10pecpDiTmkJVUH+y8K3BZClycD8nCShA==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@unrs/resolver-binding-linux-riscv64-gnu": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-riscv64-gnu/-/resolver-binding-linux-riscv64-gnu-1.11.1.tgz",+ "integrity": "sha512-frxL4OrzOWVVsOc96+V3aqTIQl1O2TjgExV4EKgRY09AJ9leZpEg8Ak9phadbuX0BA4k8U5qtvMSQQGGmaJqcQ==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@unrs/resolver-binding-linux-riscv64-musl": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-riscv64-musl/-/resolver-binding-linux-riscv64-musl-1.11.1.tgz",+ "integrity": "sha512-mJ5vuDaIZ+l/acv01sHoXfpnyrNKOk/3aDoEdLO/Xtn9HuZlDD6jKxHlkN8ZhWyLJsRBxfv9GYM2utQ1SChKew==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@unrs/resolver-binding-linux-s390x-gnu": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-s390x-gnu/-/resolver-binding-linux-s390x-gnu-1.11.1.tgz",+ "integrity": "sha512-kELo8ebBVtb9sA7rMe1Cph4QHreByhaZ2QEADd9NzIQsYNQpt9UkM9iqr2lhGr5afh885d/cB5QeTXSbZHTYPg==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@unrs/resolver-binding-linux-x64-gnu": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-x64-gnu/-/resolver-binding-linux-x64-gnu-1.11.1.tgz",+ "integrity": "sha512-C3ZAHugKgovV5YvAMsxhq0gtXuwESUKc5MhEtjBpLoHPLYM+iuwSj3lflFwK3DPm68660rZ7G8BMcwSro7hD5w==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@unrs/resolver-binding-linux-x64-musl": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-x64-musl/-/resolver-binding-linux-x64-musl-1.11.1.tgz",+ "integrity": "sha512-rV0YSoyhK2nZ4vEswT/QwqzqQXw5I6CjoaYMOX0TqBlWhojUf8P94mvI7nuJTeaCkkds3QE4+zS8Ko+GdXuZtA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@unrs/resolver-binding-wasm32-wasi": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-wasm32-wasi/-/resolver-binding-wasm32-wasi-1.11.1.tgz",+ "integrity": "sha512-5u4RkfxJm+Ng7IWgkzi3qrFOvLvQYnPBmjmZQ8+szTK/b31fQCnleNl1GgEt7nIsZRIf5PLhPwT0WM+q45x/UQ==",+ "cpu": [+ "wasm32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@napi-rs/wasm-runtime": "^0.2.11"+ },+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/@unrs/resolver-binding-win32-arm64-msvc": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-arm64-msvc/-/resolver-binding-win32-arm64-msvc-1.11.1.tgz",+ "integrity": "sha512-nRcz5Il4ln0kMhfL8S3hLkxI85BXs3o8EYoattsJNdsX4YUU89iOkVn7g0VHSRxFuVMdM4Q1jEpIId1Ihim/Uw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@unrs/resolver-binding-win32-ia32-msvc": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-ia32-msvc/-/resolver-binding-win32-ia32-msvc-1.11.1.tgz",+ "integrity": "sha512-DCEI6t5i1NmAZp6pFonpD5m7i6aFrpofcp4LA2i8IIq60Jyo28hamKBxNrZcyOwVOZkgsRp9O2sXWBWP8MnvIQ==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@unrs/resolver-binding-win32-x64-msvc": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-x64-msvc/-/resolver-binding-win32-x64-msvc-1.11.1.tgz",+ "integrity": "sha512-lrW200hZdbfRtztbygyaq/6jP6AKE8qQN2KvPcJ+x7wiD038YtnYtZ82IMNJ69GJibV7bwL3y9FgK+5w/pYt6g==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/acorn": {+ "version": "8.16.0",+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz",+ "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==",+ "dev": true,+ "license": "MIT",+ "bin": {+ "acorn": "bin/acorn"+ },+ "engines": {+ "node": ">=0.4.0"+ }+ },+ "node_modules/acorn-jsx": {+ "version": "5.3.2",+ "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz",+ "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==",+ "dev": true,+ "license": "MIT",+ "peerDependencies": {+ "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"+ }+ },+ "node_modules/ajv": {+ "version": "6.14.0",+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz",+ "integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "fast-deep-equal": "^3.1.1",+ "fast-json-stable-stringify": "^2.0.0",+ "json-schema-traverse": "^0.4.1",+ "uri-js": "^4.2.2"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/epoberezkin"+ }+ },+ "node_modules/ansi-styles": {+ "version": "4.3.0",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",+ "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "color-convert": "^2.0.1"+ },+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"+ }+ },+ "node_modules/argparse": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",+ "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",+ "dev": true,+ "license": "Python-2.0"+ },+ "node_modules/aria-query": {+ "version": "5.3.2",+ "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.2.tgz",+ "integrity": "sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/array-buffer-byte-length": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/array-buffer-byte-length/-/array-buffer-byte-length-1.0.2.tgz",+ "integrity": "sha512-LHE+8BuR7RYGDKvnrmcuSq3tDcKv9OFEXQt/HpbZhY7V6h0zlUXutnAD82GiFx9rdieCMjkvtcsPqBwgUl1Iiw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.3",+ "is-array-buffer": "^3.0.5"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/array-includes": {+ "version": "3.1.9",+ "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.9.tgz",+ "integrity": "sha512-FmeCCAenzH0KH381SPT5FZmiA/TmpndpcaShhfgEN9eCVjnFBqq3l1xrI42y8+PPLI6hypzou4GXw00WHmPBLQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "call-bound": "^1.0.4",+ "define-properties": "^1.2.1",+ "es-abstract": "^1.24.0",+ "es-object-atoms": "^1.1.1",+ "get-intrinsic": "^1.3.0",+ "is-string": "^1.1.1",+ "math-intrinsics": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/array.prototype.findlast": {+ "version": "1.2.5",+ "resolved": "https://registry.npmjs.org/array.prototype.findlast/-/array.prototype.findlast-1.2.5.tgz",+ "integrity": "sha512-CVvd6FHg1Z3POpBLxO6E6zr+rSKEQ9L6rZHAaY7lLfhKsWYUBBOuMs0e9o24oopj6H+geRCX0YJ+TJLBK2eHyQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.7",+ "define-properties": "^1.2.1",+ "es-abstract": "^1.23.2",+ "es-errors": "^1.3.0",+ "es-object-atoms": "^1.0.0",+ "es-shim-unscopables": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/array.prototype.findlastindex": {+ "version": "1.2.6",+ "resolved": "https://registry.npmjs.org/array.prototype.findlastindex/-/array.prototype.findlastindex-1.2.6.tgz",+ "integrity": "sha512-F/TKATkzseUExPlfvmwQKGITM3DGTK+vkAsCZoDc5daVygbJBnjEUCbgkAvVFsgfXfX4YIqZ/27G3k3tdXrTxQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "call-bound": "^1.0.4",+ "define-properties": "^1.2.1",+ "es-abstract": "^1.23.9",+ "es-errors": "^1.3.0",+ "es-object-atoms": "^1.1.1",+ "es-shim-unscopables": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/array.prototype.flat": {+ "version": "1.3.3",+ "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.3.3.tgz",+ "integrity": "sha512-rwG/ja1neyLqCuGZ5YYrznA62D4mZXg0i1cIskIUKSiqF3Cje9/wXAls9B9s1Wa2fomMsIv8czB8jZcPmxCXFg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "define-properties": "^1.2.1",+ "es-abstract": "^1.23.5",+ "es-shim-unscopables": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/array.prototype.flatmap": {+ "version": "1.3.3",+ "resolved": "https://registry.npmjs.org/array.prototype.flatmap/-/array.prototype.flatmap-1.3.3.tgz",+ "integrity": "sha512-Y7Wt51eKJSyi80hFrJCePGGNo5ktJCslFuboqJsbf57CCPcm5zztluPlc4/aD8sWsKvlwatezpV4U1efk8kpjg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "define-properties": "^1.2.1",+ "es-abstract": "^1.23.5",+ "es-shim-unscopables": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/array.prototype.tosorted": {+ "version": "1.1.4",+ "resolved": "https://registry.npmjs.org/array.prototype.tosorted/-/array.prototype.tosorted-1.1.4.tgz",+ "integrity": "sha512-p6Fx8B7b7ZhL/gmUsAy0D15WhvDccw3mnGNbZpi3pmeJdxtWsj2jEaI4Y6oo3XiHfzuSgPwKc04MYt6KgvC/wA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.7",+ "define-properties": "^1.2.1",+ "es-abstract": "^1.23.3",+ "es-errors": "^1.3.0",+ "es-shim-unscopables": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/arraybuffer.prototype.slice": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/arraybuffer.prototype.slice/-/arraybuffer.prototype.slice-1.0.4.tgz",+ "integrity": "sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "array-buffer-byte-length": "^1.0.1",+ "call-bind": "^1.0.8",+ "define-properties": "^1.2.1",+ "es-abstract": "^1.23.5",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.6",+ "is-array-buffer": "^3.0.4"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/ast-types-flow": {+ "version": "0.0.8",+ "resolved": "https://registry.npmjs.org/ast-types-flow/-/ast-types-flow-0.0.8.tgz",+ "integrity": "sha512-OH/2E5Fg20h2aPrbe+QL8JZQFko0YZaF+j4mnQ7BGhfavO7OpSLa8a0y9sBwomHdSbkhTS8TQNayBfnW5DwbvQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/async-function": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/async-function/-/async-function-1.0.0.tgz",+ "integrity": "sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/available-typed-arrays": {+ "version": "1.0.7",+ "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz",+ "integrity": "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "possible-typed-array-names": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/axe-core": {+ "version": "4.11.2",+ "resolved": "https://registry.npmjs.org/axe-core/-/axe-core-4.11.2.tgz",+ "integrity": "sha512-byD6KPdvo72y/wj2T/4zGEvvlis+PsZsn/yPS3pEO+sFpcrqRpX/TJCxvVaEsNeMrfQbCr7w163YqoD9IYwHXw==",+ "dev": true,+ "license": "MPL-2.0",+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/axobject-query": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz",+ "integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/balanced-match": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",+ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/baseline-browser-mapping": {+ "version": "2.10.18",+ "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.18.tgz",+ "integrity": "sha512-VSnGQAOLtP5mib/DPyg2/t+Tlv65NTBz83BJBJvmLVHHuKJVaDOBvJJykiT5TR++em5nfAySPccDZDa4oSrn8A==",+ "license": "Apache-2.0",+ "bin": {+ "baseline-browser-mapping": "dist/cli.cjs"+ },+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/brace-expansion": {+ "version": "1.1.14",+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.14.tgz",+ "integrity": "sha512-MWPGfDxnyzKU7rNOW9SP/c50vi3xrmrua/+6hfPbCS2ABNWfx24vPidzvC7krjU/RTo235sV776ymlsMtGKj8g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "balanced-match": "^1.0.0",+ "concat-map": "0.0.1"+ }+ },+ "node_modules/braces": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz",+ "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "fill-range": "^7.1.1"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/browserslist": {+ "version": "4.28.2",+ "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.2.tgz",+ "integrity": "sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg==",+ "dev": true,+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/browserslist"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/browserslist"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "baseline-browser-mapping": "^2.10.12",+ "caniuse-lite": "^1.0.30001782",+ "electron-to-chromium": "^1.5.328",+ "node-releases": "^2.0.36",+ "update-browserslist-db": "^1.2.3"+ },+ "bin": {+ "browserslist": "cli.js"+ },+ "engines": {+ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"+ }+ },+ "node_modules/call-bind": {+ "version": "1.0.9",+ "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.9.tgz",+ "integrity": "sha512-a/hy+pNsFUTR+Iz8TCJvXudKVLAnz/DyeSUo10I5yvFDQJBFU2s9uqQpoSrJlroHUKoKqzg+epxyP9lqFdzfBQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.2",+ "es-define-property": "^1.0.1",+ "get-intrinsic": "^1.3.0",+ "set-function-length": "^1.2.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/call-bind-apply-helpers": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/call-bound": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",+ "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.2",+ "get-intrinsic": "^1.3.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/callsites": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz",+ "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/caniuse-lite": {+ "version": "1.0.30001787",+ "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001787.tgz",+ "integrity": "sha512-mNcrMN9KeI68u7muanUpEejSLghOKlVhRqS/Za2IeyGllJ9I9otGpR9g3nsw7n4W378TE/LyIteA0+/FOZm4Kg==",+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/browserslist"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/caniuse-lite"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "CC-BY-4.0"+ },+ "node_modules/chalk": {+ "version": "4.1.2",+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",+ "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "ansi-styles": "^4.1.0",+ "supports-color": "^7.1.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/chalk/chalk?sponsor=1"+ }+ },+ "node_modules/client-only": {+ "version": "0.0.1",+ "resolved": "https://registry.npmjs.org/client-only/-/client-only-0.0.1.tgz",+ "integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==",+ "license": "MIT"+ },+ "node_modules/color-convert": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",+ "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "color-name": "~1.1.4"+ },+ "engines": {+ "node": ">=7.0.0"+ }+ },+ "node_modules/color-name": {+ "version": "1.1.4",+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",+ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/concat-map": {+ "version": "0.0.1",+ "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",+ "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/convert-source-map": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",+ "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/cross-spawn": {+ "version": "7.0.6",+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "path-key": "^3.1.0",+ "shebang-command": "^2.0.0",+ "which": "^2.0.1"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/csstype": {+ "version": "3.2.3",+ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",+ "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/damerau-levenshtein": {+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/damerau-levenshtein/-/damerau-levenshtein-1.0.8.tgz",+ "integrity": "sha512-sdQSFB7+llfUcQHUQO3+B8ERRj0Oa4w9POWMI/puGtuf7gFywGmkaLCElnudfTiKZV+NvHqL0ifzdrI8Ro7ESA==",+ "dev": true,+ "license": "BSD-2-Clause"+ },+ "node_modules/data-view-buffer": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.2.tgz",+ "integrity": "sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.3",+ "es-errors": "^1.3.0",+ "is-data-view": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/data-view-byte-length": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/data-view-byte-length/-/data-view-byte-length-1.0.2.tgz",+ "integrity": "sha512-tuhGbE6CfTM9+5ANGf+oQb72Ky/0+s3xKUpHvShfiz2RxMFgFPjsXuRLBVMtvMs15awe45SRb83D6wH4ew6wlQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.3",+ "es-errors": "^1.3.0",+ "is-data-view": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/inspect-js"+ }+ },+ "node_modules/data-view-byte-offset": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/data-view-byte-offset/-/data-view-byte-offset-1.0.1.tgz",+ "integrity": "sha512-BS8PfmtDGnrgYdOonGZQdLZslWIeCGFP9tpan0hi1Co2Zr2NKADsvGYA8XxuG/4UWgJ6Cjtv+YJnB6MM69QGlQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "is-data-view": "^1.0.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/debug": {+ "version": "4.4.3",+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "ms": "^2.1.3"+ },+ "engines": {+ "node": ">=6.0"+ },+ "peerDependenciesMeta": {+ "supports-color": {+ "optional": true+ }+ }+ },+ "node_modules/deep-is": {+ "version": "0.1.4",+ "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz",+ "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/define-data-property": {+ "version": "1.1.4",+ "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz",+ "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "es-define-property": "^1.0.0",+ "es-errors": "^1.3.0",+ "gopd": "^1.0.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/define-properties": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz",+ "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "define-data-property": "^1.0.1",+ "has-property-descriptors": "^1.0.0",+ "object-keys": "^1.1.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/detect-libc": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",+ "devOptional": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/doctrine": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz",+ "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "esutils": "^2.0.2"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/dunder-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.1",+ "es-errors": "^1.3.0",+ "gopd": "^1.2.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/electron-to-chromium": {+ "version": "1.5.335",+ "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.335.tgz",+ "integrity": "sha512-q9n5T4BR4Xwa2cwbrwcsDJtHD/enpQ5S1xF1IAtdqf5AAgqDFmR/aakqH3ChFdqd/QXJhS3rnnXFtexU7rax6Q==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/emoji-regex": {+ "version": "9.2.2",+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",+ "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/enhanced-resolve": {+ "version": "5.20.1",+ "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.20.1.tgz",+ "integrity": "sha512-Qohcme7V1inbAfvjItgw0EaxVX5q2rdVEZHRBrEQdRZTssLDGsL8Lwrznl8oQ/6kuTJONLaDcGjkNP247XEhcA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "graceful-fs": "^4.2.4",+ "tapable": "^2.3.0"+ },+ "engines": {+ "node": ">=10.13.0"+ }+ },+ "node_modules/es-abstract": {+ "version": "1.24.2",+ "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.24.2.tgz",+ "integrity": "sha512-2FpH9Q5i2RRwyEP1AylXe6nYLR5OhaJTZwmlcP0dL/+JCbgg7yyEo/sEK6HeGZRf3dFpWwThaRHVApXSkW3xeg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "array-buffer-byte-length": "^1.0.2",+ "arraybuffer.prototype.slice": "^1.0.4",+ "available-typed-arrays": "^1.0.7",+ "call-bind": "^1.0.8",+ "call-bound": "^1.0.4",+ "data-view-buffer": "^1.0.2",+ "data-view-byte-length": "^1.0.2",+ "data-view-byte-offset": "^1.0.1",+ "es-define-property": "^1.0.1",+ "es-errors": "^1.3.0",+ "es-object-atoms": "^1.1.1",+ "es-set-tostringtag": "^2.1.0",+ "es-to-primitive": "^1.3.0",+ "function.prototype.name": "^1.1.8",+ "get-intrinsic": "^1.3.0",+ "get-proto": "^1.0.1",+ "get-symbol-description": "^1.1.0",+ "globalthis": "^1.0.4",+ "gopd": "^1.2.0",+ "has-property-descriptors": "^1.0.2",+ "has-proto": "^1.2.0",+ "has-symbols": "^1.1.0",+ "hasown": "^2.0.2",+ "internal-slot": "^1.1.0",+ "is-array-buffer": "^3.0.5",+ "is-callable": "^1.2.7",+ "is-data-view": "^1.0.2",+ "is-negative-zero": "^2.0.3",+ "is-regex": "^1.2.1",+ "is-set": "^2.0.3",+ "is-shared-array-buffer": "^1.0.4",+ "is-string": "^1.1.1",+ "is-typed-array": "^1.1.15",+ "is-weakref": "^1.1.1",+ "math-intrinsics": "^1.1.0",+ "object-inspect": "^1.13.4",+ "object-keys": "^1.1.1",+ "object.assign": "^4.1.7",+ "own-keys": "^1.0.1",+ "regexp.prototype.flags": "^1.5.4",+ "safe-array-concat": "^1.1.3",+ "safe-push-apply": "^1.0.0",+ "safe-regex-test": "^1.1.0",+ "set-proto": "^1.0.0",+ "stop-iteration-iterator": "^1.1.0",+ "string.prototype.trim": "^1.2.10",+ "string.prototype.trimend": "^1.0.9",+ "string.prototype.trimstart": "^1.0.8",+ "typed-array-buffer": "^1.0.3",+ "typed-array-byte-length": "^1.0.3",+ "typed-array-byte-offset": "^1.0.4",+ "typed-array-length": "^1.0.7",+ "unbox-primitive": "^1.1.0",+ "which-typed-array": "^1.1.19"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/es-define-property": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-errors": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-iterator-helpers": {+ "version": "1.3.2",+ "resolved": "https://registry.npmjs.org/es-iterator-helpers/-/es-iterator-helpers-1.3.2.tgz",+ "integrity": "sha512-HVLACW1TppGYjJ8H6/jqH/pqOtKRw6wMlrB23xfExmFWxFquAIWCmwoLsOyN96K4a5KbmOf5At9ZUO3GZbetAw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.9",+ "call-bound": "^1.0.4",+ "define-properties": "^1.2.1",+ "es-abstract": "^1.24.2",+ "es-errors": "^1.3.0",+ "es-set-tostringtag": "^2.1.0",+ "function-bind": "^1.1.2",+ "get-intrinsic": "^1.3.0",+ "globalthis": "^1.0.4",+ "gopd": "^1.2.0",+ "has-property-descriptors": "^1.0.2",+ "has-proto": "^1.2.0",+ "has-symbols": "^1.1.0",+ "internal-slot": "^1.1.0",+ "iterator.prototype": "^1.1.5",+ "math-intrinsics": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-object-atoms": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",+ "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-set-tostringtag": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",+ "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.6",+ "has-tostringtag": "^1.0.2",+ "hasown": "^2.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-shim-unscopables": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/es-shim-unscopables/-/es-shim-unscopables-1.1.0.tgz",+ "integrity": "sha512-d9T8ucsEhh8Bi1woXCf+TIKDIROLG5WCkxg8geBCbvk22kzwC5G2OnXVMO6FUsvQlgUUXQ2itephWDLqDzbeCw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "hasown": "^2.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-to-primitive": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.3.0.tgz",+ "integrity": "sha512-w+5mJ3GuFL+NjVtJlvydShqE1eN3h3PbI7/5LAsYJP/2qtuMXjfL2LpHSRqo4b4eSF5K/DH1JXKUAHSB2UW50g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "is-callable": "^1.2.7",+ "is-date-object": "^1.0.5",+ "is-symbol": "^1.0.4"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/escalade": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",+ "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/escape-string-regexp": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz",+ "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/eslint": {+ "version": "9.39.4",+ "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.39.4.tgz",+ "integrity": "sha512-XoMjdBOwe/esVgEvLmNsD3IRHkm7fbKIUGvrleloJXUZgDHig2IPWNniv+GwjyJXzuNqVjlr5+4yVUZjycJwfQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@eslint-community/eslint-utils": "^4.8.0",+ "@eslint-community/regexpp": "^4.12.1",+ "@eslint/config-array": "^0.21.2",+ "@eslint/config-helpers": "^0.4.2",+ "@eslint/core": "^0.17.0",+ "@eslint/eslintrc": "^3.3.5",+ "@eslint/js": "9.39.4",+ "@eslint/plugin-kit": "^0.4.1",+ "@humanfs/node": "^0.16.6",+ "@humanwhocodes/module-importer": "^1.0.1",+ "@humanwhocodes/retry": "^0.4.2",+ "@types/estree": "^1.0.6",+ "ajv": "^6.14.0",+ "chalk": "^4.0.0",+ "cross-spawn": "^7.0.6",+ "debug": "^4.3.2",+ "escape-string-regexp": "^4.0.0",+ "eslint-scope": "^8.4.0",+ "eslint-visitor-keys": "^4.2.1",+ "espree": "^10.4.0",+ "esquery": "^1.5.0",+ "esutils": "^2.0.2",+ "fast-deep-equal": "^3.1.3",+ "file-entry-cache": "^8.0.0",+ "find-up": "^5.0.0",+ "glob-parent": "^6.0.2",+ "ignore": "^5.2.0",+ "imurmurhash": "^0.1.4",+ "is-glob": "^4.0.0",+ "json-stable-stringify-without-jsonify": "^1.0.1",+ "lodash.merge": "^4.6.2",+ "minimatch": "^3.1.5",+ "natural-compare": "^1.4.0",+ "optionator": "^0.9.3"+ },+ "bin": {+ "eslint": "bin/eslint.js"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "url": "https://eslint.org/donate"+ },+ "peerDependencies": {+ "jiti": "*"+ },+ "peerDependenciesMeta": {+ "jiti": {+ "optional": true+ }+ }+ },+ "node_modules/eslint-config-next": {+ "version": "16.2.3",+ "resolved": "https://registry.npmjs.org/eslint-config-next/-/eslint-config-next-16.2.3.tgz",+ "integrity": "sha512-Dnkrylzjof/Az7iNoIQJqD18zTxQZcngir19KJaiRsMnnjpQSVoa6aEg/1Q4hQC+cW90uTlgQYadwL1CYNwFWA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@next/eslint-plugin-next": "16.2.3",+ "eslint-import-resolver-node": "^0.3.6",+ "eslint-import-resolver-typescript": "^3.5.2",+ "eslint-plugin-import": "^2.32.0",+ "eslint-plugin-jsx-a11y": "^6.10.0",+ "eslint-plugin-react": "^7.37.0",+ "eslint-plugin-react-hooks": "^7.0.0",+ "globals": "16.4.0",+ "typescript-eslint": "^8.46.0"+ },+ "peerDependencies": {+ "eslint": ">=9.0.0",+ "typescript": ">=3.3.1"+ },+ "peerDependenciesMeta": {+ "typescript": {+ "optional": true+ }+ }+ },+ "node_modules/eslint-config-next/node_modules/globals": {+ "version": "16.4.0",+ "resolved": "https://registry.npmjs.org/globals/-/globals-16.4.0.tgz",+ "integrity": "sha512-ob/2LcVVaVGCYN+r14cnwnoDPUufjiYgSqRhiFD0Q1iI4Odora5RE8Iv1D24hAz5oMophRGkGz+yuvQmmUMnMw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/eslint-import-resolver-node": {+ "version": "0.3.10",+ "resolved": "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.10.tgz",+ "integrity": "sha512-tRrKqFyCaKict5hOd244sL6EQFNycnMQnBe+j8uqGNXYzsImGbGUU4ibtoaBmv5FLwJwcFJNeg1GeVjQfbMrDQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "debug": "^3.2.7",+ "is-core-module": "^2.16.1",+ "resolve": "^2.0.0-next.6"+ }+ },+ "node_modules/eslint-import-resolver-node/node_modules/debug": {+ "version": "3.2.7",+ "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz",+ "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "ms": "^2.1.1"+ }+ },+ "node_modules/eslint-import-resolver-typescript": {+ "version": "3.10.1",+ "resolved": "https://registry.npmjs.org/eslint-import-resolver-typescript/-/eslint-import-resolver-typescript-3.10.1.tgz",+ "integrity": "sha512-A1rHYb06zjMGAxdLSkN2fXPBwuSaQ0iO5M/hdyS0Ajj1VBaRp0sPD3dn1FhME3c/JluGFbwSxyCfqdSbtQLAHQ==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "@nolyfill/is-core-module": "1.0.39",+ "debug": "^4.4.0",+ "get-tsconfig": "^4.10.0",+ "is-bun-module": "^2.0.0",+ "stable-hash": "^0.0.5",+ "tinyglobby": "^0.2.13",+ "unrs-resolver": "^1.6.2"+ },+ "engines": {+ "node": "^14.18.0 || >=16.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/eslint-import-resolver-typescript"+ },+ "peerDependencies": {+ "eslint": "*",+ "eslint-plugin-import": "*",+ "eslint-plugin-import-x": "*"+ },+ "peerDependenciesMeta": {+ "eslint-plugin-import": {+ "optional": true+ },+ "eslint-plugin-import-x": {+ "optional": true+ }+ }+ },+ "node_modules/eslint-module-utils": {+ "version": "2.12.1",+ "resolved": "https://registry.npmjs.org/eslint-module-utils/-/eslint-module-utils-2.12.1.tgz",+ "integrity": "sha512-L8jSWTze7K2mTg0vos/RuLRS5soomksDPoJLXIslC7c8Wmut3bx7CPpJijDcBZtxQ5lrbUdM+s0OlNbz0DCDNw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "debug": "^3.2.7"+ },+ "engines": {+ "node": ">=4"+ },+ "peerDependenciesMeta": {+ "eslint": {+ "optional": true+ }+ }+ },+ "node_modules/eslint-module-utils/node_modules/debug": {+ "version": "3.2.7",+ "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz",+ "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "ms": "^2.1.1"+ }+ },+ "node_modules/eslint-plugin-import": {+ "version": "2.32.0",+ "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.32.0.tgz",+ "integrity": "sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@rtsao/scc": "^1.1.0",+ "array-includes": "^3.1.9",+ "array.prototype.findlastindex": "^1.2.6",+ "array.prototype.flat": "^1.3.3",+ "array.prototype.flatmap": "^1.3.3",+ "debug": "^3.2.7",+ "doctrine": "^2.1.0",+ "eslint-import-resolver-node": "^0.3.9",+ "eslint-module-utils": "^2.12.1",+ "hasown": "^2.0.2",+ "is-core-module": "^2.16.1",+ "is-glob": "^4.0.3",+ "minimatch": "^3.1.2",+ "object.fromentries": "^2.0.8",+ "object.groupby": "^1.0.3",+ "object.values": "^1.2.1",+ "semver": "^6.3.1",+ "string.prototype.trimend": "^1.0.9",+ "tsconfig-paths": "^3.15.0"+ },+ "engines": {+ "node": ">=4"+ },+ "peerDependencies": {+ "eslint": "^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0 || ^8 || ^9"+ }+ },+ "node_modules/eslint-plugin-import/node_modules/debug": {+ "version": "3.2.7",+ "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz",+ "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "ms": "^2.1.1"+ }+ },+ "node_modules/eslint-plugin-jsx-a11y": {+ "version": "6.10.2",+ "resolved": "https://registry.npmjs.org/eslint-plugin-jsx-a11y/-/eslint-plugin-jsx-a11y-6.10.2.tgz",+ "integrity": "sha512-scB3nz4WmG75pV8+3eRUQOHZlNSUhFNq37xnpgRkCCELU3XMvXAxLk1eqWWyE22Ki4Q01Fnsw9BA3cJHDPgn2Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "aria-query": "^5.3.2",+ "array-includes": "^3.1.8",+ "array.prototype.flatmap": "^1.3.2",+ "ast-types-flow": "^0.0.8",+ "axe-core": "^4.10.0",+ "axobject-query": "^4.1.0",+ "damerau-levenshtein": "^1.0.8",+ "emoji-regex": "^9.2.2",+ "hasown": "^2.0.2",+ "jsx-ast-utils": "^3.3.5",+ "language-tags": "^1.0.9",+ "minimatch": "^3.1.2",+ "object.fromentries": "^2.0.8",+ "safe-regex-test": "^1.0.3",+ "string.prototype.includes": "^2.0.1"+ },+ "engines": {+ "node": ">=4.0"+ },+ "peerDependencies": {+ "eslint": "^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9"+ }+ },+ "node_modules/eslint-plugin-react": {+ "version": "7.37.5",+ "resolved": "https://registry.npmjs.org/eslint-plugin-react/-/eslint-plugin-react-7.37.5.tgz",+ "integrity": "sha512-Qteup0SqU15kdocexFNAJMvCJEfa2xUKNV4CC1xsVMrIIqEy3SQ/rqyxCWNzfrd3/ldy6HMlD2e0JDVpDg2qIA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "array-includes": "^3.1.8",+ "array.prototype.findlast": "^1.2.5",+ "array.prototype.flatmap": "^1.3.3",+ "array.prototype.tosorted": "^1.1.4",+ "doctrine": "^2.1.0",+ "es-iterator-helpers": "^1.2.1",+ "estraverse": "^5.3.0",+ "hasown": "^2.0.2",+ "jsx-ast-utils": "^2.4.1 || ^3.0.0",+ "minimatch": "^3.1.2",+ "object.entries": "^1.1.9",+ "object.fromentries": "^2.0.8",+ "object.values": "^1.2.1",+ "prop-types": "^15.8.1",+ "resolve": "^2.0.0-next.5",+ "semver": "^6.3.1",+ "string.prototype.matchall": "^4.0.12",+ "string.prototype.repeat": "^1.0.0"+ },+ "engines": {+ "node": ">=4"+ },+ "peerDependencies": {+ "eslint": "^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9.7"+ }+ },+ "node_modules/eslint-plugin-react-hooks": {+ "version": "7.0.1",+ "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-7.0.1.tgz",+ "integrity": "sha512-O0d0m04evaNzEPoSW+59Mezf8Qt0InfgGIBJnpC0h3NH/WjUAR7BIKUfysC6todmtiZ/A0oUVS8Gce0WhBrHsA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/core": "^7.24.4",+ "@babel/parser": "^7.24.4",+ "hermes-parser": "^0.25.1",+ "zod": "^3.25.0 || ^4.0.0",+ "zod-validation-error": "^3.5.0 || ^4.0.0"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0"+ }+ },+ "node_modules/eslint-scope": {+ "version": "8.4.0",+ "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.4.0.tgz",+ "integrity": "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==",+ "dev": true,+ "license": "BSD-2-Clause",+ "dependencies": {+ "esrecurse": "^4.3.0",+ "estraverse": "^5.2.0"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ }+ },+ "node_modules/eslint-visitor-keys": {+ "version": "4.2.1",+ "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz",+ "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ }+ },+ "node_modules/espree": {+ "version": "10.4.0",+ "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz",+ "integrity": "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==",+ "dev": true,+ "license": "BSD-2-Clause",+ "dependencies": {+ "acorn": "^8.15.0",+ "acorn-jsx": "^5.3.2",+ "eslint-visitor-keys": "^4.2.1"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ }+ },+ "node_modules/esquery": {+ "version": "1.7.0",+ "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz",+ "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==",+ "dev": true,+ "license": "BSD-3-Clause",+ "dependencies": {+ "estraverse": "^5.1.0"+ },+ "engines": {+ "node": ">=0.10"+ }+ },+ "node_modules/esrecurse": {+ "version": "4.3.0",+ "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz",+ "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==",+ "dev": true,+ "license": "BSD-2-Clause",+ "dependencies": {+ "estraverse": "^5.2.0"+ },+ "engines": {+ "node": ">=4.0"+ }+ },+ "node_modules/estraverse": {+ "version": "5.3.0",+ "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz",+ "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=4.0"+ }+ },+ "node_modules/esutils": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz",+ "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/fast-deep-equal": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/fast-glob": {+ "version": "3.3.1",+ "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.1.tgz",+ "integrity": "sha512-kNFPyjhh5cKjrUltxs+wFx+ZkbRaxxmZ+X0ZU31SOsxCEtP9VPgtq2teZw1DebupL5GmDaNQ6yKMMVcM41iqDg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@nodelib/fs.stat": "^2.0.2",+ "@nodelib/fs.walk": "^1.2.3",+ "glob-parent": "^5.1.2",+ "merge2": "^1.3.0",+ "micromatch": "^4.0.4"+ },+ "engines": {+ "node": ">=8.6.0"+ }+ },+ "node_modules/fast-glob/node_modules/glob-parent": {+ "version": "5.1.2",+ "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",+ "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "is-glob": "^4.0.1"+ },+ "engines": {+ "node": ">= 6"+ }+ },+ "node_modules/fast-json-stable-stringify": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",+ "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/fast-levenshtein": {+ "version": "2.0.6",+ "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz",+ "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/fastq": {+ "version": "1.20.1",+ "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz",+ "integrity": "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "reusify": "^1.0.4"+ }+ },+ "node_modules/file-entry-cache": {+ "version": "8.0.0",+ "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz",+ "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "flat-cache": "^4.0.0"+ },+ "engines": {+ "node": ">=16.0.0"+ }+ },+ "node_modules/fill-range": {+ "version": "7.1.1",+ "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",+ "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "to-regex-range": "^5.0.1"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/find-up": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz",+ "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "locate-path": "^6.0.0",+ "path-exists": "^4.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/flat-cache": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz",+ "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "flatted": "^3.2.9",+ "keyv": "^4.5.4"+ },+ "engines": {+ "node": ">=16"+ }+ },+ "node_modules/flatted": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.2.tgz",+ "integrity": "sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/for-each": {+ "version": "0.3.5",+ "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.5.tgz",+ "integrity": "sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "is-callable": "^1.2.7"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/function-bind": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/function.prototype.name": {+ "version": "1.1.8",+ "resolved": "https://registry.npmjs.org/function.prototype.name/-/function.prototype.name-1.1.8.tgz",+ "integrity": "sha512-e5iwyodOHhbMr/yNrc7fDYG4qlbIvI5gajyzPnb5TCwyhjApznQh1BMFou9b30SevY43gCJKXycoCBjMbsuW0Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "call-bound": "^1.0.3",+ "define-properties": "^1.2.1",+ "functions-have-names": "^1.2.3",+ "hasown": "^2.0.2",+ "is-callable": "^1.2.7"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/functions-have-names": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz",+ "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/generator-function": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/generator-function/-/generator-function-2.0.1.tgz",+ "integrity": "sha512-SFdFmIJi+ybC0vjlHN0ZGVGHc3lgE0DxPAT0djjVg+kjOnSqclqmj0KQ7ykTOLP6YxoqOvuAODGdcHJn+43q3g==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/gensync": {+ "version": "1.0.0-beta.2",+ "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz",+ "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/get-intrinsic": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.2",+ "es-define-property": "^1.0.1",+ "es-errors": "^1.3.0",+ "es-object-atoms": "^1.1.1",+ "function-bind": "^1.1.2",+ "get-proto": "^1.0.1",+ "gopd": "^1.2.0",+ "has-symbols": "^1.1.0",+ "hasown": "^2.0.2",+ "math-intrinsics": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/get-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "dunder-proto": "^1.0.1",+ "es-object-atoms": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/get-symbol-description": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.1.0.tgz",+ "integrity": "sha512-w9UMqWwJxHNOvoNzSJ2oPF5wvYcvP7jUvYzhp67yEhTi17ZDBBC1z9pTdGuzjD+EFIqLSYRweZjqfiPzQ06Ebg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.3",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.6"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/get-tsconfig": {+ "version": "4.13.7",+ "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.7.tgz",+ "integrity": "sha512-7tN6rFgBlMgpBML5j8typ92BKFi2sFQvIdpAqLA2beia5avZDrMs0FLZiM5etShWq5irVyGcGMEA1jcDaK7A/Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "resolve-pkg-maps": "^1.0.0"+ },+ "funding": {+ "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1"+ }+ },+ "node_modules/glob-parent": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz",+ "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "is-glob": "^4.0.3"+ },+ "engines": {+ "node": ">=10.13.0"+ }+ },+ "node_modules/globals": {+ "version": "14.0.0",+ "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz",+ "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/globalthis": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz",+ "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "define-properties": "^1.2.1",+ "gopd": "^1.0.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/gopd": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/graceful-fs": {+ "version": "4.2.11",+ "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",+ "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/has-bigints": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.1.0.tgz",+ "integrity": "sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/has-flag": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",+ "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/has-property-descriptors": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz",+ "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "es-define-property": "^1.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/has-proto": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.2.0.tgz",+ "integrity": "sha512-KIL7eQPfHQRC8+XluaIw7BHUwwqL19bQn4hzNgdr+1wXoU0KKj6rufu47lhY7KbJR2C6T6+PfyN0Ea7wkSS+qQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "dunder-proto": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/has-symbols": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/has-tostringtag": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",+ "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "has-symbols": "^1.0.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/hasown": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",+ "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/hermes-estree": {+ "version": "0.25.1",+ "resolved": "https://registry.npmjs.org/hermes-estree/-/hermes-estree-0.25.1.tgz",+ "integrity": "sha512-0wUoCcLp+5Ev5pDW2OriHC2MJCbwLwuRx+gAqMTOkGKJJiBCLjtrvy4PWUGn6MIVefecRpzoOZ/UV6iGdOr+Cw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/hermes-parser": {+ "version": "0.25.1",+ "resolved": "https://registry.npmjs.org/hermes-parser/-/hermes-parser-0.25.1.tgz",+ "integrity": "sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "hermes-estree": "0.25.1"+ }+ },+ "node_modules/ignore": {+ "version": "5.3.2",+ "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",+ "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 4"+ }+ },+ "node_modules/import-fresh": {+ "version": "3.3.1",+ "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz",+ "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "parent-module": "^1.0.0",+ "resolve-from": "^4.0.0"+ },+ "engines": {+ "node": ">=6"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/imurmurhash": {+ "version": "0.1.4",+ "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz",+ "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.8.19"+ }+ },+ "node_modules/internal-slot": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.1.0.tgz",+ "integrity": "sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "hasown": "^2.0.2",+ "side-channel": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/is-array-buffer": {+ "version": "3.0.5",+ "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.5.tgz",+ "integrity": "sha512-DDfANUiiG2wC1qawP66qlTugJeL5HyzMpfr8lLK+jMQirGzNod0B12cFB/9q838Ru27sBwfw78/rdoU7RERz6A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "call-bound": "^1.0.3",+ "get-intrinsic": "^1.2.6"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-async-function": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/is-async-function/-/is-async-function-2.1.1.tgz",+ "integrity": "sha512-9dgM/cZBnNvjzaMYHVoxxfPj2QXt22Ev7SuuPrs+xav0ukGB0S6d4ydZdEiM48kLx5kDV+QBPrpVnFyefL8kkQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "async-function": "^1.0.0",+ "call-bound": "^1.0.3",+ "get-proto": "^1.0.1",+ "has-tostringtag": "^1.0.2",+ "safe-regex-test": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-bigint": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.1.0.tgz",+ "integrity": "sha512-n4ZT37wG78iz03xPRKJrHTdZbe3IicyucEtdRsV5yglwc3GyUfbAfpSeD0FJ41NbUNSt5wbhqfp1fS+BgnvDFQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "has-bigints": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-boolean-object": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.2.2.tgz",+ "integrity": "sha512-wa56o2/ElJMYqjCjGkXri7it5FbebW5usLw/nPmCMs5DeZ7eziSYZhSmPRn0txqeW4LnAmQQU7FgqLpsEFKM4A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.3",+ "has-tostringtag": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-bun-module": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/is-bun-module/-/is-bun-module-2.0.0.tgz",+ "integrity": "sha512-gNCGbnnnnFAUGKeZ9PdbyeGYJqewpmc2aKHUEMO5nQPWU9lOmv7jcmQIv+qHD8fXW6W7qfuCwX4rY9LNRjXrkQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "semver": "^7.7.1"+ }+ },+ "node_modules/is-bun-module/node_modules/semver": {+ "version": "7.7.4",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",+ "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",+ "dev": true,+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/is-callable": {+ "version": "1.2.7",+ "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz",+ "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-core-module": {+ "version": "2.16.1",+ "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz",+ "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "hasown": "^2.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-data-view": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/is-data-view/-/is-data-view-1.0.2.tgz",+ "integrity": "sha512-RKtWF8pGmS87i2D6gqQu/l7EYRlVdfzemCJN/P3UOs//x1QE7mfhvzHIApBTRf7axvT6DMGwSwBXYCT0nfB9xw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "get-intrinsic": "^1.2.6",+ "is-typed-array": "^1.1.13"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-date-object": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.1.0.tgz",+ "integrity": "sha512-PwwhEakHVKTdRNVOw+/Gyh0+MzlCl4R6qKvkhuvLtPMggI1WAHt9sOwZxQLSGpUaDnrdyDsomoRgNnCfKNSXXg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "has-tostringtag": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-extglob": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",+ "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/is-finalizationregistry": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/is-finalizationregistry/-/is-finalizationregistry-1.1.1.tgz",+ "integrity": "sha512-1pC6N8qWJbWoPtEjgcL2xyhQOP491EQjeUo3qTKcmV8YSDDJrOepfG8pcC7h/QgnQHYSv0mJ3Z/ZWxmatVrysg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-generator-function": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.1.2.tgz",+ "integrity": "sha512-upqt1SkGkODW9tsGNG5mtXTXtECizwtS2kA161M+gJPc1xdb/Ax629af6YrTwcOeQHbewrPNlE5Dx7kzvXTizA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.4",+ "generator-function": "^2.0.0",+ "get-proto": "^1.0.1",+ "has-tostringtag": "^1.0.2",+ "safe-regex-test": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-glob": {+ "version": "4.0.3",+ "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",+ "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "is-extglob": "^2.1.1"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/is-map": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/is-map/-/is-map-2.0.3.tgz",+ "integrity": "sha512-1Qed0/Hr2m+YqxnM09CjA2d/i6YZNfF6R2oRAOj36eUdS6qIV/huPJNSEpKbupewFs+ZsJlxsjjPbc0/afW6Lw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-negative-zero": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.3.tgz",+ "integrity": "sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-number": {+ "version": "7.0.0",+ "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz",+ "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.12.0"+ }+ },+ "node_modules/is-number-object": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.1.1.tgz",+ "integrity": "sha512-lZhclumE1G6VYD8VHe35wFaIif+CTy5SJIi5+3y4psDgWu4wPDoBhF8NxUOinEc7pHgiTsT6MaBb92rKhhD+Xw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.3",+ "has-tostringtag": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-regex": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.2.1.tgz",+ "integrity": "sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "gopd": "^1.2.0",+ "has-tostringtag": "^1.0.2",+ "hasown": "^2.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-set": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/is-set/-/is-set-2.0.3.tgz",+ "integrity": "sha512-iPAjerrse27/ygGLxw+EBR9agv9Y6uLeYVJMu+QNCoouJ1/1ri0mGrcWpfCqFZuzzx3WjtwxG098X+n4OuRkPg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-shared-array-buffer": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.4.tgz",+ "integrity": "sha512-ISWac8drv4ZGfwKl5slpHG9OwPNty4jOWPRIhBpxOoD+hqITiwuipOQ2bNthAzwA3B4fIjO4Nln74N0S9byq8A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-string": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.1.1.tgz",+ "integrity": "sha512-BtEeSsoaQjlSPBemMQIrY1MY0uM6vnS1g5fmufYOtnxLGUZM2178PKbhsk7Ffv58IX+ZtcvoGwccYsh0PglkAA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.3",+ "has-tostringtag": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-symbol": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.1.1.tgz",+ "integrity": "sha512-9gGx6GTtCQM73BgmHQXfDmLtfjjTUDSyoxTCbp5WtoixAhfgsDirWIcVQ/IHpvI5Vgd5i/J5F7B9cN/WlVbC/w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "has-symbols": "^1.1.0",+ "safe-regex-test": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-typed-array": {+ "version": "1.1.15",+ "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.15.tgz",+ "integrity": "sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "which-typed-array": "^1.1.16"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-weakmap": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/is-weakmap/-/is-weakmap-2.0.2.tgz",+ "integrity": "sha512-K5pXYOm9wqY1RgjpL3YTkF39tni1XajUIkawTLUo9EZEVUFga5gSQJF8nNS7ZwJQ02y+1YCNYcMh+HIf1ZqE+w==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-weakref": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/is-weakref/-/is-weakref-1.1.1.tgz",+ "integrity": "sha512-6i9mGWSlqzNMEqpCp93KwRS1uUOodk2OJ6b+sq7ZPDSy2WuI5NFIxp/254TytR8ftefexkWn5xNiHUNpPOfSew==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-weakset": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/is-weakset/-/is-weakset-2.0.4.tgz",+ "integrity": "sha512-mfcwb6IzQyOKTs84CQMrOwW4gQcaTOAWJ0zzJCl2WSPDrWk/OzDaImWFH3djXhb24g4eudZfLRozAvPGw4d9hQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.3",+ "get-intrinsic": "^1.2.6"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/isarray": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz",+ "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/isexe": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/iterator.prototype": {+ "version": "1.1.5",+ "resolved": "https://registry.npmjs.org/iterator.prototype/-/iterator.prototype-1.1.5.tgz",+ "integrity": "sha512-H0dkQoCa3b2VEeKQBOxFph+JAbcrQdE7KC0UkqwpLmv2EC4P41QXP+rqo9wYodACiG5/WM5s9oDApTU8utwj9g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "define-data-property": "^1.1.4",+ "es-object-atoms": "^1.0.0",+ "get-intrinsic": "^1.2.6",+ "get-proto": "^1.0.0",+ "has-symbols": "^1.1.0",+ "set-function-name": "^2.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/jiti": {+ "version": "2.6.1",+ "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.6.1.tgz",+ "integrity": "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==",+ "dev": true,+ "license": "MIT",+ "bin": {+ "jiti": "lib/jiti-cli.mjs"+ }+ },+ "node_modules/js-tokens": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",+ "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/js-yaml": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",+ "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "argparse": "^2.0.1"+ },+ "bin": {+ "js-yaml": "bin/js-yaml.js"+ }+ },+ "node_modules/jsesc": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz",+ "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==",+ "dev": true,+ "license": "MIT",+ "bin": {+ "jsesc": "bin/jsesc"+ },+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/json-buffer": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz",+ "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/json-schema-traverse": {+ "version": "0.4.1",+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",+ "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/json-stable-stringify-without-jsonify": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz",+ "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/json5": {+ "version": "2.2.3",+ "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",+ "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==",+ "dev": true,+ "license": "MIT",+ "bin": {+ "json5": "lib/cli.js"+ },+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/jsx-ast-utils": {+ "version": "3.3.5",+ "resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-3.3.5.tgz",+ "integrity": "sha512-ZZow9HBI5O6EPgSJLUb8n2NKgmVWTwCvHGwFuJlMjvLFqlGG6pjirPhtdsseaLZjSibD8eegzmYpUZwoIlj2cQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "array-includes": "^3.1.6",+ "array.prototype.flat": "^1.3.1",+ "object.assign": "^4.1.4",+ "object.values": "^1.1.6"+ },+ "engines": {+ "node": ">=4.0"+ }+ },+ "node_modules/keyv": {+ "version": "4.5.4",+ "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",+ "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "json-buffer": "3.0.1"+ }+ },+ "node_modules/language-subtag-registry": {+ "version": "0.3.23",+ "resolved": "https://registry.npmjs.org/language-subtag-registry/-/language-subtag-registry-0.3.23.tgz",+ "integrity": "sha512-0K65Lea881pHotoGEa5gDlMxt3pctLi2RplBb7Ezh4rRdLEOtgi7n4EwK9lamnUCkKBqaeKRVebTq6BAxSkpXQ==",+ "dev": true,+ "license": "CC0-1.0"+ },+ "node_modules/language-tags": {+ "version": "1.0.9",+ "resolved": "https://registry.npmjs.org/language-tags/-/language-tags-1.0.9.tgz",+ "integrity": "sha512-MbjN408fEndfiQXbFQ1vnd+1NoLDsnQW41410oQBXiyXDMYH5z505juWa4KUE1LqxRC7DgOgZDbKLxHIwm27hA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "language-subtag-registry": "^0.3.20"+ },+ "engines": {+ "node": ">=0.10"+ }+ },+ "node_modules/levn": {+ "version": "0.4.1",+ "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz",+ "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "prelude-ls": "^1.2.1",+ "type-check": "~0.4.0"+ },+ "engines": {+ "node": ">= 0.8.0"+ }+ },+ "node_modules/lightningcss": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz",+ "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==",+ "dev": true,+ "license": "MPL-2.0",+ "dependencies": {+ "detect-libc": "^2.0.3"+ },+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ },+ "optionalDependencies": {+ "lightningcss-android-arm64": "1.32.0",+ "lightningcss-darwin-arm64": "1.32.0",+ "lightningcss-darwin-x64": "1.32.0",+ "lightningcss-freebsd-x64": "1.32.0",+ "lightningcss-linux-arm-gnueabihf": "1.32.0",+ "lightningcss-linux-arm64-gnu": "1.32.0",+ "lightningcss-linux-arm64-musl": "1.32.0",+ "lightningcss-linux-x64-gnu": "1.32.0",+ "lightningcss-linux-x64-musl": "1.32.0",+ "lightningcss-win32-arm64-msvc": "1.32.0",+ "lightningcss-win32-x64-msvc": "1.32.0"+ }+ },+ "node_modules/lightningcss-android-arm64": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz",+ "integrity": "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-darwin-arm64": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz",+ "integrity": "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-darwin-x64": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.32.0.tgz",+ "integrity": "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-freebsd-x64": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz",+ "integrity": "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-arm-gnueabihf": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz",+ "integrity": "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-arm64-gnu": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz",+ "integrity": "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-arm64-musl": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz",+ "integrity": "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-x64-gnu": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz",+ "integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-x64-musl": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz",+ "integrity": "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-win32-arm64-msvc": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz",+ "integrity": "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-win32-x64-msvc": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz",+ "integrity": "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/locate-path": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz",+ "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "p-locate": "^5.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/lodash.merge": {+ "version": "4.6.2",+ "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz",+ "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/loose-envify": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",+ "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "js-tokens": "^3.0.0 || ^4.0.0"+ },+ "bin": {+ "loose-envify": "cli.js"+ }+ },+ "node_modules/lru-cache": {+ "version": "5.1.1",+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",+ "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "yallist": "^3.0.2"+ }+ },+ "node_modules/magic-string": {+ "version": "0.30.21",+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",+ "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/sourcemap-codec": "^1.5.5"+ }+ },+ "node_modules/math-intrinsics": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/merge2": {+ "version": "1.4.1",+ "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz",+ "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/micromatch": {+ "version": "4.0.8",+ "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",+ "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "braces": "^3.0.3",+ "picomatch": "^2.3.1"+ },+ "engines": {+ "node": ">=8.6"+ }+ },+ "node_modules/minimatch": {+ "version": "3.1.5",+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",+ "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "brace-expansion": "^1.1.7"+ },+ "engines": {+ "node": "*"+ }+ },+ "node_modules/minimist": {+ "version": "1.2.8",+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",+ "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/ms": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/nanoid": {+ "version": "3.3.11",+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",+ "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "bin": {+ "nanoid": "bin/nanoid.cjs"+ },+ "engines": {+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"+ }+ },+ "node_modules/napi-postinstall": {+ "version": "0.3.4",+ "resolved": "https://registry.npmjs.org/napi-postinstall/-/napi-postinstall-0.3.4.tgz",+ "integrity": "sha512-PHI5f1O0EP5xJ9gQmFGMS6IZcrVvTjpXjz7Na41gTE7eE2hK11lg04CECCYEEjdc17EV4DO+fkGEtt7TpTaTiQ==",+ "dev": true,+ "license": "MIT",+ "bin": {+ "napi-postinstall": "lib/cli.js"+ },+ "engines": {+ "node": "^12.20.0 || ^14.18.0 || >=16.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/napi-postinstall"+ }+ },+ "node_modules/natural-compare": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz",+ "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/next": {+ "version": "16.2.3",+ "resolved": "https://registry.npmjs.org/next/-/next-16.2.3.tgz",+ "integrity": "sha512-9V3zV4oZFza3PVev5/poB9g0dEafVcgNyQ8eTRop8GvxZjV2G15FC5ARuG1eFD42QgeYkzJBJzHghNP8Ad9xtA==",+ "license": "MIT",+ "dependencies": {+ "@next/env": "16.2.3",+ "@swc/helpers": "0.5.15",+ "baseline-browser-mapping": "^2.9.19",+ "caniuse-lite": "^1.0.30001579",+ "postcss": "8.4.31",+ "styled-jsx": "5.1.6"+ },+ "bin": {+ "next": "dist/bin/next"+ },+ "engines": {+ "node": ">=20.9.0"+ },+ "optionalDependencies": {+ "@next/swc-darwin-arm64": "16.2.3",+ "@next/swc-darwin-x64": "16.2.3",+ "@next/swc-linux-arm64-gnu": "16.2.3",+ "@next/swc-linux-arm64-musl": "16.2.3",+ "@next/swc-linux-x64-gnu": "16.2.3",+ "@next/swc-linux-x64-musl": "16.2.3",+ "@next/swc-win32-arm64-msvc": "16.2.3",+ "@next/swc-win32-x64-msvc": "16.2.3",+ "sharp": "^0.34.5"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.1.0",+ "@playwright/test": "^1.51.1",+ "babel-plugin-react-compiler": "*",+ "react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0",+ "react-dom": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0",+ "sass": "^1.3.0"+ },+ "peerDependenciesMeta": {+ "@opentelemetry/api": {+ "optional": true+ },+ "@playwright/test": {+ "optional": true+ },+ "babel-plugin-react-compiler": {+ "optional": true+ },+ "sass": {+ "optional": true+ }+ }+ },+ "node_modules/next/node_modules/postcss": {+ "version": "8.4.31",+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.31.tgz",+ "integrity": "sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ==",+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/postcss/"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/postcss"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "nanoid": "^3.3.6",+ "picocolors": "^1.0.0",+ "source-map-js": "^1.0.2"+ },+ "engines": {+ "node": "^10 || ^12 || >=14"+ }+ },+ "node_modules/node-exports-info": {+ "version": "1.6.0",+ "resolved": "https://registry.npmjs.org/node-exports-info/-/node-exports-info-1.6.0.tgz",+ "integrity": "sha512-pyFS63ptit/P5WqUkt+UUfe+4oevH+bFeIiPPdfb0pFeYEu/1ELnJu5l+5EcTKYL5M7zaAa7S8ddywgXypqKCw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "array.prototype.flatmap": "^1.3.3",+ "es-errors": "^1.3.0",+ "object.entries": "^1.1.9",+ "semver": "^6.3.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/node-releases": {+ "version": "2.0.37",+ "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.37.tgz",+ "integrity": "sha512-1h5gKZCF+pO/o3Iqt5Jp7wc9rH3eJJ0+nh/CIoiRwjRxde/hAHyLPXYN4V3CqKAbiZPSeJFSWHmJsbkicta0Eg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/object-assign": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/object-inspect": {+ "version": "1.13.4",+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",+ "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/object-keys": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz",+ "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/object.assign": {+ "version": "4.1.7",+ "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.7.tgz",+ "integrity": "sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "call-bound": "^1.0.3",+ "define-properties": "^1.2.1",+ "es-object-atoms": "^1.0.0",+ "has-symbols": "^1.1.0",+ "object-keys": "^1.1.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/object.entries": {+ "version": "1.1.9",+ "resolved": "https://registry.npmjs.org/object.entries/-/object.entries-1.1.9.tgz",+ "integrity": "sha512-8u/hfXFRBD1O0hPUjioLhoWFHRmt6tKA4/vZPyckBr18l1KE9uHrFaFaUi8MDRTpi4uak2goyPTSNJLXX2k2Hw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "call-bound": "^1.0.4",+ "define-properties": "^1.2.1",+ "es-object-atoms": "^1.1.1"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/object.fromentries": {+ "version": "2.0.8",+ "resolved": "https://registry.npmjs.org/object.fromentries/-/object.fromentries-2.0.8.tgz",+ "integrity": "sha512-k6E21FzySsSK5a21KRADBd/NGneRegFO5pLHfdQLpRDETUNJueLXs3WCzyQ3tFRDYgbq3KHGXfTbi2bs8WQ6rQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.7",+ "define-properties": "^1.2.1",+ "es-abstract": "^1.23.2",+ "es-object-atoms": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/object.groupby": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/object.groupby/-/object.groupby-1.0.3.tgz",+ "integrity": "sha512-+Lhy3TQTuzXI5hevh8sBGqbmurHbbIjAi0Z4S63nthVLmLxfbj4T54a4CfZrXIrt9iP4mVAPYMo/v99taj3wjQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.7",+ "define-properties": "^1.2.1",+ "es-abstract": "^1.23.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/object.values": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.2.1.tgz",+ "integrity": "sha512-gXah6aZrcUxjWg2zR2MwouP2eHlCBzdV4pygudehaKXSGW4v2AsRQUK+lwwXhii6KFZcunEnmSUoYp5CXibxtA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "call-bound": "^1.0.3",+ "define-properties": "^1.2.1",+ "es-object-atoms": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/optionator": {+ "version": "0.9.4",+ "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",+ "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "deep-is": "^0.1.3",+ "fast-levenshtein": "^2.0.6",+ "levn": "^0.4.1",+ "prelude-ls": "^1.2.1",+ "type-check": "^0.4.0",+ "word-wrap": "^1.2.5"+ },+ "engines": {+ "node": ">= 0.8.0"+ }+ },+ "node_modules/own-keys": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/own-keys/-/own-keys-1.0.1.tgz",+ "integrity": "sha512-qFOyK5PjiWZd+QQIh+1jhdb9LpxTF0qs7Pm8o5QHYZ0M3vKqSqzsZaEB6oWlxZ+q2sJBMI/Ktgd2N5ZwQoRHfg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "get-intrinsic": "^1.2.6",+ "object-keys": "^1.1.1",+ "safe-push-apply": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/p-limit": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz",+ "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "yocto-queue": "^0.1.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/p-locate": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz",+ "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "p-limit": "^3.0.2"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/parent-module": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz",+ "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "callsites": "^3.0.0"+ },+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/path-exists": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",+ "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/path-key": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/path-parse": {+ "version": "1.0.7",+ "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz",+ "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/picocolors": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",+ "license": "ISC"+ },+ "node_modules/picomatch": {+ "version": "2.3.2",+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz",+ "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8.6"+ },+ "funding": {+ "url": "https://github.com/sponsors/jonschlinkert"+ }+ },+ "node_modules/possible-typed-array-names": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",+ "integrity": "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/postcss": {+ "version": "8.5.9",+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.9.tgz",+ "integrity": "sha512-7a70Nsot+EMX9fFU3064K/kdHWZqGVY+BADLyXc8Dfv+mTLLVl6JzJpPaCZ2kQL9gIJvKXSLMHhqdRRjwQeFtw==",+ "dev": true,+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/postcss/"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/postcss"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "nanoid": "^3.3.11",+ "picocolors": "^1.1.1",+ "source-map-js": "^1.2.1"+ },+ "engines": {+ "node": "^10 || ^12 || >=14"+ }+ },+ "node_modules/prelude-ls": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",+ "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.8.0"+ }+ },+ "node_modules/prop-types": {+ "version": "15.8.1",+ "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",+ "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "loose-envify": "^1.4.0",+ "object-assign": "^4.1.1",+ "react-is": "^16.13.1"+ }+ },+ "node_modules/punycode": {+ "version": "2.3.1",+ "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",+ "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/queue-microtask": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",+ "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT"+ },+ "node_modules/react": {+ "version": "19.2.4",+ "resolved": "https://registry.npmjs.org/react/-/react-19.2.4.tgz",+ "integrity": "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/react-dom": {+ "version": "19.2.4",+ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.4.tgz",+ "integrity": "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ==",+ "license": "MIT",+ "dependencies": {+ "scheduler": "^0.27.0"+ },+ "peerDependencies": {+ "react": "^19.2.4"+ }+ },+ "node_modules/react-icons": {+ "version": "5.6.0",+ "resolved": "https://registry.npmjs.org/react-icons/-/react-icons-5.6.0.tgz",+ "integrity": "sha512-RH93p5ki6LfOiIt0UtDyNg/cee+HLVR6cHHtW3wALfo+eOHTp8RnU2kRkI6E+H19zMIs03DyxUG/GfZMOGvmiA==",+ "license": "MIT",+ "peerDependencies": {+ "react": "*"+ }+ },+ "node_modules/react-is": {+ "version": "16.13.1",+ "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",+ "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/reflect.getprototypeof": {+ "version": "1.0.10",+ "resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz",+ "integrity": "sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "define-properties": "^1.2.1",+ "es-abstract": "^1.23.9",+ "es-errors": "^1.3.0",+ "es-object-atoms": "^1.0.0",+ "get-intrinsic": "^1.2.7",+ "get-proto": "^1.0.1",+ "which-builtin-type": "^1.2.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/regexp.prototype.flags": {+ "version": "1.5.4",+ "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.4.tgz",+ "integrity": "sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "define-properties": "^1.2.1",+ "es-errors": "^1.3.0",+ "get-proto": "^1.0.1",+ "gopd": "^1.2.0",+ "set-function-name": "^2.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/resolve": {+ "version": "2.0.0-next.6",+ "resolved": "https://registry.npmjs.org/resolve/-/resolve-2.0.0-next.6.tgz",+ "integrity": "sha512-3JmVl5hMGtJ3kMmB3zi3DL25KfkCEyy3Tw7Gmw7z5w8M9WlwoPFnIvwChzu1+cF3iaK3sp18hhPz8ANeimdJfA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "is-core-module": "^2.16.1",+ "node-exports-info": "^1.6.0",+ "object-keys": "^1.1.1",+ "path-parse": "^1.0.7",+ "supports-preserve-symlinks-flag": "^1.0.0"+ },+ "bin": {+ "resolve": "bin/resolve"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/resolve-from": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz",+ "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/resolve-pkg-maps": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz",+ "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1"+ }+ },+ "node_modules/reusify": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz",+ "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "iojs": ">=1.0.0",+ "node": ">=0.10.0"+ }+ },+ "node_modules/run-parallel": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz",+ "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "queue-microtask": "^1.2.2"+ }+ },+ "node_modules/safe-array-concat": {+ "version": "1.1.3",+ "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.1.3.tgz",+ "integrity": "sha512-AURm5f0jYEOydBj7VQlVvDrjeFgthDdEF5H1dP+6mNpoXOMo1quQqJ4wvJDyRZ9+pO3kGWoOdmV08cSv2aJV6Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "call-bound": "^1.0.2",+ "get-intrinsic": "^1.2.6",+ "has-symbols": "^1.1.0",+ "isarray": "^2.0.5"+ },+ "engines": {+ "node": ">=0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/safe-push-apply": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/safe-push-apply/-/safe-push-apply-1.0.0.tgz",+ "integrity": "sha512-iKE9w/Z7xCzUMIZqdBsp6pEQvwuEebH4vdpjcDWnyzaI6yl6O9FHvVpmGelvEHNsoY6wGblkxR6Zty/h00WiSA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "isarray": "^2.0.5"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/safe-regex-test": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/safe-regex-test/-/safe-regex-test-1.1.0.tgz",+ "integrity": "sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "is-regex": "^1.2.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/scheduler": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",+ "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==",+ "license": "MIT"+ },+ "node_modules/semver": {+ "version": "6.3.1",+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",+ "dev": true,+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ }+ },+ "node_modules/set-function-length": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz",+ "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "define-data-property": "^1.1.4",+ "es-errors": "^1.3.0",+ "function-bind": "^1.1.2",+ "get-intrinsic": "^1.2.4",+ "gopd": "^1.0.1",+ "has-property-descriptors": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/set-function-name": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/set-function-name/-/set-function-name-2.0.2.tgz",+ "integrity": "sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "define-data-property": "^1.1.4",+ "es-errors": "^1.3.0",+ "functions-have-names": "^1.2.3",+ "has-property-descriptors": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/set-proto": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/set-proto/-/set-proto-1.0.0.tgz",+ "integrity": "sha512-RJRdvCo6IAnPdsvP/7m6bsQqNnn1FCBX5ZNtFL98MmFF/4xAIJTIg1YbHW5DC2W5SKZanrC6i4HsJqlajw/dZw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "dunder-proto": "^1.0.1",+ "es-errors": "^1.3.0",+ "es-object-atoms": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/sharp": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.5.tgz",+ "integrity": "sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==",+ "hasInstallScript": true,+ "license": "Apache-2.0",+ "optional": true,+ "dependencies": {+ "@img/colour": "^1.0.0",+ "detect-libc": "^2.1.2",+ "semver": "^7.7.3"+ },+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-darwin-arm64": "0.34.5",+ "@img/sharp-darwin-x64": "0.34.5",+ "@img/sharp-libvips-darwin-arm64": "1.2.4",+ "@img/sharp-libvips-darwin-x64": "1.2.4",+ "@img/sharp-libvips-linux-arm": "1.2.4",+ "@img/sharp-libvips-linux-arm64": "1.2.4",+ "@img/sharp-libvips-linux-ppc64": "1.2.4",+ "@img/sharp-libvips-linux-riscv64": "1.2.4",+ "@img/sharp-libvips-linux-s390x": "1.2.4",+ "@img/sharp-libvips-linux-x64": "1.2.4",+ "@img/sharp-libvips-linuxmusl-arm64": "1.2.4",+ "@img/sharp-libvips-linuxmusl-x64": "1.2.4",+ "@img/sharp-linux-arm": "0.34.5",+ "@img/sharp-linux-arm64": "0.34.5",+ "@img/sharp-linux-ppc64": "0.34.5",+ "@img/sharp-linux-riscv64": "0.34.5",+ "@img/sharp-linux-s390x": "0.34.5",+ "@img/sharp-linux-x64": "0.34.5",+ "@img/sharp-linuxmusl-arm64": "0.34.5",+ "@img/sharp-linuxmusl-x64": "0.34.5",+ "@img/sharp-wasm32": "0.34.5",+ "@img/sharp-win32-arm64": "0.34.5",+ "@img/sharp-win32-ia32": "0.34.5",+ "@img/sharp-win32-x64": "0.34.5"+ }+ },+ "node_modules/sharp/node_modules/semver": {+ "version": "7.7.4",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",+ "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",+ "license": "ISC",+ "optional": true,+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/shebang-command": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "shebang-regex": "^3.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/shebang-regex": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/side-channel": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz",+ "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "object-inspect": "^1.13.3",+ "side-channel-list": "^1.0.0",+ "side-channel-map": "^1.0.1",+ "side-channel-weakmap": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-list": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz",+ "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "object-inspect": "^1.13.4"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-map": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",+ "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.5",+ "object-inspect": "^1.13.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-weakmap": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",+ "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.5",+ "object-inspect": "^1.13.3",+ "side-channel-map": "^1.0.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/source-map-js": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/stable-hash": {+ "version": "0.0.5",+ "resolved": "https://registry.npmjs.org/stable-hash/-/stable-hash-0.0.5.tgz",+ "integrity": "sha512-+L3ccpzibovGXFK+Ap/f8LOS0ahMrHTf3xu7mMLSpEGU0EO9ucaysSylKo9eRDFNhWve/y275iPmIZ4z39a9iA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/stop-iteration-iterator": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/stop-iteration-iterator/-/stop-iteration-iterator-1.1.0.tgz",+ "integrity": "sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "internal-slot": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/string.prototype.includes": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/string.prototype.includes/-/string.prototype.includes-2.0.1.tgz",+ "integrity": "sha512-o7+c9bW6zpAdJHTtujeePODAhkuicdAryFsfVKwA+wGw89wJ4GTY484WTucM9hLtDEOpOvI+aHnzqnC5lHp4Rg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.7",+ "define-properties": "^1.2.1",+ "es-abstract": "^1.23.3"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/string.prototype.matchall": {+ "version": "4.0.12",+ "resolved": "https://registry.npmjs.org/string.prototype.matchall/-/string.prototype.matchall-4.0.12.tgz",+ "integrity": "sha512-6CC9uyBL+/48dYizRf7H7VAYCMCNTBeM78x/VTUe9bFEaxBepPJDa1Ow99LqI/1yF7kuy7Q3cQsYMrcjGUcskA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "call-bound": "^1.0.3",+ "define-properties": "^1.2.1",+ "es-abstract": "^1.23.6",+ "es-errors": "^1.3.0",+ "es-object-atoms": "^1.0.0",+ "get-intrinsic": "^1.2.6",+ "gopd": "^1.2.0",+ "has-symbols": "^1.1.0",+ "internal-slot": "^1.1.0",+ "regexp.prototype.flags": "^1.5.3",+ "set-function-name": "^2.0.2",+ "side-channel": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/string.prototype.repeat": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/string.prototype.repeat/-/string.prototype.repeat-1.0.0.tgz",+ "integrity": "sha512-0u/TldDbKD8bFCQ/4f5+mNRrXwZ8hg2w7ZR8wa16e8z9XpePWl3eGEcUD0OXpEH/VJH/2G3gjUtR3ZOiBe2S/w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "define-properties": "^1.1.3",+ "es-abstract": "^1.17.5"+ }+ },+ "node_modules/string.prototype.trim": {+ "version": "1.2.10",+ "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.2.10.tgz",+ "integrity": "sha512-Rs66F0P/1kedk5lyYyH9uBzuiI/kNRmwJAR9quK6VOtIpZ2G+hMZd+HQbbv25MgCA6gEffoMZYxlTod4WcdrKA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "call-bound": "^1.0.2",+ "define-data-property": "^1.1.4",+ "define-properties": "^1.2.1",+ "es-abstract": "^1.23.5",+ "es-object-atoms": "^1.0.0",+ "has-property-descriptors": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/string.prototype.trimend": {+ "version": "1.0.9",+ "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.9.tgz",+ "integrity": "sha512-G7Ok5C6E/j4SGfyLCloXTrngQIQU3PWtXGst3yM7Bea9FRURf1S42ZHlZZtsNque2FN2PoUhfZXYLNWwEr4dLQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "call-bound": "^1.0.2",+ "define-properties": "^1.2.1",+ "es-object-atoms": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/string.prototype.trimstart": {+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.8.tgz",+ "integrity": "sha512-UXSH262CSZY1tfu3G3Secr6uGLCFVPMhIqHjlgCUtCCcgihYc/xKs9djMTMUOb2j1mVSeU8EU6NWc/iQKU6Gfg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.7",+ "define-properties": "^1.2.1",+ "es-object-atoms": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/strip-bom": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz",+ "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/strip-json-comments": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz",+ "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/styled-jsx": {+ "version": "5.1.6",+ "resolved": "https://registry.npmjs.org/styled-jsx/-/styled-jsx-5.1.6.tgz",+ "integrity": "sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA==",+ "license": "MIT",+ "dependencies": {+ "client-only": "0.0.1"+ },+ "engines": {+ "node": ">= 12.0.0"+ },+ "peerDependencies": {+ "react": ">= 16.8.0 || 17.x.x || ^18.0.0-0 || ^19.0.0-0"+ },+ "peerDependenciesMeta": {+ "@babel/core": {+ "optional": true+ },+ "babel-plugin-macros": {+ "optional": true+ }+ }+ },+ "node_modules/supports-color": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",+ "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "has-flag": "^4.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/supports-preserve-symlinks-flag": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz",+ "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/tailwindcss": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.2.2.tgz",+ "integrity": "sha512-KWBIxs1Xb6NoLdMVqhbhgwZf2PGBpPEiwOqgI4pFIYbNTfBXiKYyWoTsXgBQ9WFg/OlhnvHaY+AEpW7wSmFo2Q==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/tapable": {+ "version": "2.3.2",+ "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.2.tgz",+ "integrity": "sha512-1MOpMXuhGzGL5TTCZFItxCc0AARf1EZFQkGqMm7ERKj8+Hgr5oLvJOVFcC+lRmR8hCe2S3jC4T5D7Vg/d7/fhA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/webpack"+ }+ },+ "node_modules/tinyglobby": {+ "version": "0.2.16",+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.16.tgz",+ "integrity": "sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "fdir": "^6.5.0",+ "picomatch": "^4.0.4"+ },+ "engines": {+ "node": ">=12.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/SuperchupuDev"+ }+ },+ "node_modules/tinyglobby/node_modules/fdir": {+ "version": "6.5.0",+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12.0.0"+ },+ "peerDependencies": {+ "picomatch": "^3 || ^4"+ },+ "peerDependenciesMeta": {+ "picomatch": {+ "optional": true+ }+ }+ },+ "node_modules/tinyglobby/node_modules/picomatch": {+ "version": "4.0.4",+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",+ "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/sponsors/jonschlinkert"+ }+ },+ "node_modules/to-regex-range": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",+ "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "is-number": "^7.0.0"+ },+ "engines": {+ "node": ">=8.0"+ }+ },+ "node_modules/ts-api-utils": {+ "version": "2.5.0",+ "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz",+ "integrity": "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18.12"+ },+ "peerDependencies": {+ "typescript": ">=4.8.4"+ }+ },+ "node_modules/tsconfig-paths": {+ "version": "3.15.0",+ "resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-3.15.0.tgz",+ "integrity": "sha512-2Ac2RgzDe/cn48GvOe3M+o82pEFewD3UPbyoUHHdKasHwJKjds4fLXWf/Ux5kATBKN20oaFGu+jbElp1pos0mg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/json5": "^0.0.29",+ "json5": "^1.0.2",+ "minimist": "^1.2.6",+ "strip-bom": "^3.0.0"+ }+ },+ "node_modules/tsconfig-paths/node_modules/json5": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.2.tgz",+ "integrity": "sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "minimist": "^1.2.0"+ },+ "bin": {+ "json5": "lib/cli.js"+ }+ },+ "node_modules/tslib": {+ "version": "2.8.1",+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",+ "license": "0BSD"+ },+ "node_modules/type-check": {+ "version": "0.4.0",+ "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",+ "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "prelude-ls": "^1.2.1"+ },+ "engines": {+ "node": ">= 0.8.0"+ }+ },+ "node_modules/typed-array-buffer": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/typed-array-buffer/-/typed-array-buffer-1.0.3.tgz",+ "integrity": "sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.3",+ "es-errors": "^1.3.0",+ "is-typed-array": "^1.1.14"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/typed-array-byte-length": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/typed-array-byte-length/-/typed-array-byte-length-1.0.3.tgz",+ "integrity": "sha512-BaXgOuIxz8n8pIq3e7Atg/7s+DpiYrxn4vdot3w9KbnBhcRQq6o3xemQdIfynqSeXeDrF32x+WvfzmOjPiY9lg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "for-each": "^0.3.3",+ "gopd": "^1.2.0",+ "has-proto": "^1.2.0",+ "is-typed-array": "^1.1.14"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/typed-array-byte-offset": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/typed-array-byte-offset/-/typed-array-byte-offset-1.0.4.tgz",+ "integrity": "sha512-bTlAFB/FBYMcuX81gbL4OcpH5PmlFHqlCCpAl8AlEzMz5k53oNDvN8p1PNOWLEmI2x4orp3raOFB51tv9X+MFQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "available-typed-arrays": "^1.0.7",+ "call-bind": "^1.0.8",+ "for-each": "^0.3.3",+ "gopd": "^1.2.0",+ "has-proto": "^1.2.0",+ "is-typed-array": "^1.1.15",+ "reflect.getprototypeof": "^1.0.9"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/typed-array-length": {+ "version": "1.0.7",+ "resolved": "https://registry.npmjs.org/typed-array-length/-/typed-array-length-1.0.7.tgz",+ "integrity": "sha512-3KS2b+kL7fsuk/eJZ7EQdnEmQoaho/r6KUef7hxvltNA5DR8NAUM+8wJMbJyZ4G9/7i3v5zPBIMN5aybAh2/Jg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.7",+ "for-each": "^0.3.3",+ "gopd": "^1.0.1",+ "is-typed-array": "^1.1.13",+ "possible-typed-array-names": "^1.0.0",+ "reflect.getprototypeof": "^1.0.6"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/typescript": {+ "version": "5.9.3",+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "tsc": "bin/tsc",+ "tsserver": "bin/tsserver"+ },+ "engines": {+ "node": ">=14.17"+ }+ },+ "node_modules/typescript-eslint": {+ "version": "8.58.1",+ "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.58.1.tgz",+ "integrity": "sha512-gf6/oHChByg9HJvhMO1iBexJh12AqqTfnuxscMDOVqfJW3htsdRJI/GfPpHTTcyeB8cSTUY2JcZmVgoyPqcrDg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@typescript-eslint/eslint-plugin": "8.58.1",+ "@typescript-eslint/parser": "8.58.1",+ "@typescript-eslint/typescript-estree": "8.58.1",+ "@typescript-eslint/utils": "8.58.1"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ },+ "peerDependencies": {+ "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",+ "typescript": ">=4.8.4 <6.1.0"+ }+ },+ "node_modules/unbox-primitive": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.1.0.tgz",+ "integrity": "sha512-nWJ91DjeOkej/TA8pXQ3myruKpKEYgqvpw9lz4OPHj/NWFNluYrjbz9j01CJ8yKQd2g4jFoOkINCTW2I5LEEyw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.3",+ "has-bigints": "^1.0.2",+ "has-symbols": "^1.1.0",+ "which-boxed-primitive": "^1.1.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/undici-types": {+ "version": "6.21.0",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/unrs-resolver": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/unrs-resolver/-/unrs-resolver-1.11.1.tgz",+ "integrity": "sha512-bSjt9pjaEBnNiGgc9rUiHGKv5l4/TGzDmYw3RhnkJGtLhbnnA/5qJj7x3dNDCRx/PJxu774LlH8lCOlB4hEfKg==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "dependencies": {+ "napi-postinstall": "^0.3.0"+ },+ "funding": {+ "url": "https://opencollective.com/unrs-resolver"+ },+ "optionalDependencies": {+ "@unrs/resolver-binding-android-arm-eabi": "1.11.1",+ "@unrs/resolver-binding-android-arm64": "1.11.1",+ "@unrs/resolver-binding-darwin-arm64": "1.11.1",+ "@unrs/resolver-binding-darwin-x64": "1.11.1",+ "@unrs/resolver-binding-freebsd-x64": "1.11.1",+ "@unrs/resolver-binding-linux-arm-gnueabihf": "1.11.1",+ "@unrs/resolver-binding-linux-arm-musleabihf": "1.11.1",+ "@unrs/resolver-binding-linux-arm64-gnu": "1.11.1",+ "@unrs/resolver-binding-linux-arm64-musl": "1.11.1",+ "@unrs/resolver-binding-linux-ppc64-gnu": "1.11.1",+ "@unrs/resolver-binding-linux-riscv64-gnu": "1.11.1",+ "@unrs/resolver-binding-linux-riscv64-musl": "1.11.1",+ "@unrs/resolver-binding-linux-s390x-gnu": "1.11.1",+ "@unrs/resolver-binding-linux-x64-gnu": "1.11.1",+ "@unrs/resolver-binding-linux-x64-musl": "1.11.1",+ "@unrs/resolver-binding-wasm32-wasi": "1.11.1",+ "@unrs/resolver-binding-win32-arm64-msvc": "1.11.1",+ "@unrs/resolver-binding-win32-ia32-msvc": "1.11.1",+ "@unrs/resolver-binding-win32-x64-msvc": "1.11.1"+ }+ },+ "node_modules/update-browserslist-db": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz",+ "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==",+ "dev": true,+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/browserslist"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/browserslist"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "escalade": "^3.2.0",+ "picocolors": "^1.1.1"+ },+ "bin": {+ "update-browserslist-db": "cli.js"+ },+ "peerDependencies": {+ "browserslist": ">= 4.21.0"+ }+ },+ "node_modules/uri-js": {+ "version": "4.4.1",+ "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",+ "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==",+ "dev": true,+ "license": "BSD-2-Clause",+ "dependencies": {+ "punycode": "^2.1.0"+ }+ },+ "node_modules/which": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "isexe": "^2.0.0"+ },+ "bin": {+ "node-which": "bin/node-which"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/which-boxed-primitive": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.1.1.tgz",+ "integrity": "sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "is-bigint": "^1.1.0",+ "is-boolean-object": "^1.2.1",+ "is-number-object": "^1.1.1",+ "is-string": "^1.1.1",+ "is-symbol": "^1.1.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/which-builtin-type": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/which-builtin-type/-/which-builtin-type-1.2.1.tgz",+ "integrity": "sha512-6iBczoX+kDQ7a3+YJBnh3T+KZRxM/iYNPXicqk66/Qfm1b93iu+yOImkg0zHbj5LNOcNv1TEADiZ0xa34B4q6Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "function.prototype.name": "^1.1.6",+ "has-tostringtag": "^1.0.2",+ "is-async-function": "^2.0.0",+ "is-date-object": "^1.1.0",+ "is-finalizationregistry": "^1.1.0",+ "is-generator-function": "^1.0.10",+ "is-regex": "^1.2.1",+ "is-weakref": "^1.0.2",+ "isarray": "^2.0.5",+ "which-boxed-primitive": "^1.1.0",+ "which-collection": "^1.0.2",+ "which-typed-array": "^1.1.16"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/which-collection": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/which-collection/-/which-collection-1.0.2.tgz",+ "integrity": "sha512-K4jVyjnBdgvc86Y6BkaLZEN933SwYOuBFkdmBu9ZfkcAbdVbpITnDmjvZ/aQjRXQrv5EPkTnD1s39GiiqbngCw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "is-map": "^2.0.3",+ "is-set": "^2.0.3",+ "is-weakmap": "^2.0.2",+ "is-weakset": "^2.0.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/which-typed-array": {+ "version": "1.1.20",+ "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.20.tgz",+ "integrity": "sha512-LYfpUkmqwl0h9A2HL09Mms427Q1RZWuOHsukfVcKRq9q95iQxdw0ix1JQrqbcDR9PH1QDwf5Qo8OZb5lksZ8Xg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "available-typed-arrays": "^1.0.7",+ "call-bind": "^1.0.8",+ "call-bound": "^1.0.4",+ "for-each": "^0.3.5",+ "get-proto": "^1.0.1",+ "gopd": "^1.2.0",+ "has-tostringtag": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/word-wrap": {+ "version": "1.2.5",+ "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz",+ "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/yallist": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",+ "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/yocto-queue": {+ "version": "0.1.0",+ "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",+ "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/zod": {+ "version": "4.3.6",+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz",+ "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ },+ "node_modules/zod-validation-error": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/zod-validation-error/-/zod-validation-error-4.0.2.tgz",+ "integrity": "sha512-Q6/nZLe6jxuU80qb/4uJ4t5v2VEZ44lzQjPDhYJNztRQ4wyWc6VF3D3Kb/fAuPetZQnhS3hnajCf9CsWesghLQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18.0.0"+ },+ "peerDependencies": {+ "zod": "^3.25.0 || ^4.0.0"+ }+ }+ }+}diff --git a/landing/package.json b/landing/package.jsonnew file mode 100644index 0000000..6420050--- /dev/null+++ b/landing/package.json@@ -0,0 +1,27 @@+{+ "name": "landing",+ "version": "0.1.0",+ "private": true,+ "scripts": {+ "dev": "next dev",+ "build": "next build",+ "start": "next start",+ "lint": "eslint"+ },+ "dependencies": {+ "next": "16.2.3",+ "react": "19.2.4",+ "react-dom": "19.2.4",+ "react-icons": "^5.6.0"+ },+ "devDependencies": {+ "@tailwindcss/postcss": "^4",+ "@types/node": "^20",+ "@types/react": "^19",+ "@types/react-dom": "^19",+ "eslint": "^9",+ "eslint-config-next": "16.2.3",+ "tailwindcss": "^4",+ "typescript": "^5"+ }+}diff --git a/landing/postcss.config.mjs b/landing/postcss.config.mjsnew file mode 100644index 0000000..61e3684--- /dev/null+++ b/landing/postcss.config.mjs@@ -0,0 +1,7 @@+const config = {+ plugins: {+ "@tailwindcss/postcss": {},+ },+};++export default config;diff --git a/landing/public/file.svg b/landing/public/file.svgnew file mode 100644index 0000000..004145c--- /dev/null+++ b/landing/public/file.svg@@ -0,0 +1 @@+<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>\ No newline at end of filediff --git a/landing/public/globe.svg b/landing/public/globe.svgnew file mode 100644index 0000000..567f17b--- /dev/null+++ b/landing/public/globe.svg@@ -0,0 +1 @@+<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>\ No newline at end of filediff --git a/landing/public/icon-192.png b/landing/public/icon-192.pngnew file mode 100644index 0000000..6249abdBinary files /dev/null and b/landing/public/icon-192.png differdiff --git a/landing/public/icon-512.png b/landing/public/icon-512.pngnew file mode 100644index 0000000..3a5e3fcBinary files /dev/null and b/landing/public/icon-512.png differdiff --git a/landing/public/logo.png b/landing/public/logo.pngnew file mode 100644index 0000000..cc8608eBinary files /dev/null and b/landing/public/logo.png differdiff --git a/landing/public/next.svg b/landing/public/next.svgnew file mode 100644index 0000000..5174b28--- /dev/null+++ b/landing/public/next.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>\ No newline at end of filediff --git a/landing/public/vercel.svg b/landing/public/vercel.svgnew file mode 100644index 0000000..7705396--- /dev/null+++ b/landing/public/vercel.svg@@ -0,0 +1 @@+<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>\ No newline at end of filediff --git a/landing/public/window.svg b/landing/public/window.svgnew file mode 100644index 0000000..b2b2a44--- /dev/null+++ b/landing/public/window.svg@@ -0,0 +1 @@+<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>\ No newline at end of filediff --git a/landing/src/app/apple-icon.png b/landing/src/app/apple-icon.pngnew file mode 100644index 0000000..e0526d8Binary files /dev/null and b/landing/src/app/apple-icon.png differdiff --git a/landing/src/app/components/CTA.tsx b/landing/src/app/components/CTA.tsxnew file mode 100644index 0000000..19ee607--- /dev/null+++ b/landing/src/app/components/CTA.tsx@@ -0,0 +1,52 @@+"use client";++import { useReveal } from "../hooks/useReveal";++export default function CTA() {+ const ref = useReveal();++ return (+ <section className="py-20 md:py-28 relative overflow-hidden">+ {/* Background glow */}+ <div className="absolute inset-0 pointer-events-none">+ <div className="absolute bottom-0 left-1/2 -translate-x-1/2 w-[800px] h-[400px] rounded-full bg-gradient-to-t from-phoenix/10 via-flame/5 to-transparent blur-[100px]" />+ </div>++ <div ref={ref} className="relative mx-auto max-w-2xl px-6 text-center">+ <div className="reveal">+ <h2 className="text-3xl md:text-4xl font-bold tracking-tight text-foreground mb-4">+ Ready to try <span className="gradient-text">Gridex</span>?+ </h2>+ <p className="text-muted mb-10 max-w-md mx-auto">+ Free to download. No account required.+ <br />+ Available for macOS and Windows.+ </p>+ </div>++ <div className="reveal reveal-delay-1 flex flex-col sm:flex-row items-center justify-center gap-3">+ <a+ href="/download"+ className="w-full sm:w-auto gradient-primary text-white font-medium px-8 py-3.5 rounded-xl hover:opacity-90 transition-all shadow-lg shadow-phoenix/20 flex items-center justify-center gap-2.5"+ >+ <svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">+ <path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3" />+ </svg>+ Download Gridex+ </a>+ <a+ href="https://github.com"+ target="_blank"+ rel="noopener noreferrer"+ className="w-full sm:w-auto text-foreground font-medium px-8 py-3.5 rounded-xl border border-border hover:bg-black/[0.03] dark:hover:bg-white/[0.03] transition-colors flex items-center justify-center gap-2.5"+ >+ <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">+ <path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12" />+ </svg>+ Star on GitHub+ </a>+ </div>+ </div>+ </section>+ );+}diff --git a/landing/src/app/components/Comparison.tsx b/landing/src/app/components/Comparison.tsxnew file mode 100644index 0000000..b78a243--- /dev/null+++ b/landing/src/app/components/Comparison.tsx@@ -0,0 +1,106 @@+"use client";++import { useReveal } from "../hooks/useReveal";++const rows = [+ { feature: "Native macOS", gridex: true, tableplus: true, dbeaver: "Java" },+ { feature: "AI Chat", gridex: true, tableplus: false, dbeaver: false },+ { feature: "Local AI (Ollama)", gridex: true, tableplus: false, dbeaver: false },+ { feature: "Multi-DB", gridex: true, tableplus: true, dbeaver: true },+ { feature: "SSH Tunnel", gridex: true, tableplus: true, dbeaver: true },+ { feature: "Free tier", gridex: true, tableplus: "Limited", dbeaver: true },+];++function Check() {+ return (+ <div className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-emerald-500/10">+ <svg className="w-3.5 h-3.5 text-emerald-500" fill="none" stroke="currentColor" strokeWidth={2.5} viewBox="0 0 24 24">+ <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />+ </svg>+ </div>+ );+}++function Cross() {+ return (+ <div className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-black/5 dark:bg-white/5">+ <svg className="w-3.5 h-3.5 text-muted-foreground" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">+ <path strokeLinecap="round" strokeLinejoin="round" d="M18 12H6" />+ </svg>+ </div>+ );+}++function Cell({ value }: { value: boolean | string }) {+ if (value === true) return <Check />;+ if (value === false) return <Cross />;+ return <span className="text-xs font-medium text-muted-foreground bg-black/5 dark:bg-white/5 px-2 py-0.5 rounded">{value}</span>;+}++export default function Comparison() {+ const ref = useReveal();++ return (+ <section id="comparison" className="py-20 md:py-28">+ <div ref={ref} className="mx-auto max-w-3xl px-6">+ <div className="reveal text-center mb-12">+ <p className="text-xs font-medium text-phoenix uppercase tracking-[0.2em] mb-3">+ Compare+ </p>+ <h2 className="text-3xl md:text-4xl font-bold tracking-tight text-foreground mb-4">+ Why choose <span className="gradient-text">Gridex</span>?+ </h2>+ <p className="text-muted max-w-md mx-auto">+ A fast, native database IDE with AI built right in.+ </p>+ </div>++ <div className="reveal reveal-delay-1 rounded-2xl border border-border overflow-hidden bg-card">+ <table className="w-full text-sm">+ <thead>+ <tr className="border-b border-border bg-black/[0.02] dark:bg-white/[0.02]">+ <th className="text-left px-5 py-3.5 font-medium text-muted text-xs uppercase tracking-wider">+ Feature+ </th>+ <th className="px-5 py-3.5 text-center">+ <span className="font-semibold text-phoenix text-xs uppercase tracking-wider">+ Gridex+ </span>+ </th>+ <th className="px-5 py-3.5 font-medium text-muted-foreground text-xs uppercase tracking-wider text-center">+ TablePlus+ </th>+ <th className="px-5 py-3.5 font-medium text-muted-foreground text-xs uppercase tracking-wider text-center">+ DBeaver+ </th>+ </tr>+ </thead>+ <tbody>+ {rows.map((row, i) => (+ <tr+ key={row.feature}+ className={`border-b border-border last:border-0 ${+ i % 2 === 0 ? "" : "bg-black/[0.01] dark:bg-white/[0.01]"+ }`}+ >+ <td className="px-5 py-3.5 font-medium text-foreground text-sm">+ {row.feature}+ </td>+ <td className="px-5 py-3.5 text-center">+ <Cell value={row.gridex} />+ </td>+ <td className="px-5 py-3.5 text-center">+ <Cell value={row.tableplus} />+ </td>+ <td className="px-5 py-3.5 text-center">+ <Cell value={row.dbeaver} />+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </div>+ </section>+ );+}diff --git a/landing/src/app/components/Databases.tsx b/landing/src/app/components/Databases.tsxnew file mode 100644index 0000000..862686b--- /dev/null+++ b/landing/src/app/components/Databases.tsx@@ -0,0 +1,48 @@+"use client";++import {+ SiPostgresql,+ SiMysql,+ SiSqlite,+ SiRedis,+ SiMongodb,+} from "react-icons/si";+import { DiMsqlServer } from "react-icons/di";+import type { IconType } from "react-icons";+import { useReveal } from "../hooks/useReveal";++const databases: { name: string; Icon: IconType }[] = [+ { name: "PostgreSQL", Icon: SiPostgresql },+ { name: "MySQL", Icon: SiMysql },+ { name: "SQLite", Icon: SiSqlite },+ { name: "Redis", Icon: SiRedis },+ { name: "MongoDB", Icon: SiMongodb },+ { name: "SQL Server", Icon: DiMsqlServer },+];++export default function Databases() {+ const ref = useReveal();++ return (+ <section className="py-14 border-y border-border">+ <div ref={ref} className="mx-auto max-w-6xl px-6">+ <p className="reveal text-center text-xs font-medium text-muted-foreground uppercase tracking-[0.2em] mb-10">+ Connect to all your databases+ </p>+ <div className="reveal reveal-delay-1 grid grid-cols-3 md:grid-cols-6 gap-4">+ {databases.map(({ name, Icon }) => (+ <div+ key={name}+ className="flex flex-col items-center gap-3 py-4 px-2 rounded-xl hover:bg-black/[0.03] dark:hover:bg-white/[0.03] transition-colors cursor-default"+ >+ <div className="text-muted-foreground opacity-60 hover:opacity-100 transition-opacity">+ <Icon className="w-8 h-8" />+ </div>+ <span className="text-xs font-medium text-muted">{name}</span>+ </div>+ ))}+ </div>+ </div>+ </section>+ );+}diff --git a/landing/src/app/components/Features.tsx b/landing/src/app/components/Features.tsxnew file mode 100644index 0000000..e6f3ded--- /dev/null+++ b/landing/src/app/components/Features.tsx@@ -0,0 +1,117 @@+"use client";++import { useReveal } from "../hooks/useReveal";++const features = [+ {+ title: "AI Chat Built-in",+ description:+ "Describe what you need in plain language. AI writes the query for you. Supports Claude, GPT, and local Ollama.",+ icon: (+ <svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">+ <path strokeLinecap="round" strokeLinejoin="round" d="M9.813 15.904L9 18.75l-.813-2.846a4.5 4.5 0 00-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 003.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 003.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 00-3.09 3.09zM18.259 8.715L18 9.75l-.259-1.035a3.375 3.375 0 00-2.455-2.456L14.25 6l1.036-.259a3.375 3.375 0 002.455-2.456L18 2.25l.259 1.035a3.375 3.375 0 002.455 2.456L21.75 6l-1.036.259a3.375 3.375 0 00-2.455 2.456z" />+ </svg>+ ),+ gradient: "from-purple-500/10 to-pink-500/10 dark:from-purple-500/5 dark:to-pink-500/5",+ iconBg: "bg-purple-500/10 text-purple-600 dark:text-purple-400",+ },+ {+ title: "Query Editor",+ description:+ "Multi-tab editor with autocomplete, syntax highlighting, query history. Export results to CSV, JSON, or SQL.",+ icon: (+ <svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">+ <path strokeLinecap="round" strokeLinejoin="round" d="M17.25 6.75L22.5 12l-5.25 5.25m-10.5 0L1.5 12l5.25-5.25m7.5-3l-4.5 16.5" />+ </svg>+ ),+ gradient: "from-emerald-500/10 to-teal-500/10 dark:from-emerald-500/5 dark:to-teal-500/5",+ iconBg: "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",+ },+ {+ title: "Table Editor",+ description:+ "Edit data visually like a spreadsheet. Inline editing, filtering, sorting. JSON document editor for MongoDB.",+ icon: (+ <svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">+ <path strokeLinecap="round" strokeLinejoin="round" d="M3.375 19.5h17.25m-17.25 0a1.125 1.125 0 01-1.125-1.125M3.375 19.5h7.5c.621 0 1.125-.504 1.125-1.125m-9.75 0V5.625m0 12.75v-1.5c0-.621.504-1.125 1.125-1.125m18.375 2.625V5.625m0 12.75c0 .621-.504 1.125-1.125 1.125m1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125m0 3.75h-7.5A1.125 1.125 0 0112 18.375m9.75-12.75c0-.621-.504-1.125-1.125-1.125H3.375c-.621 0-1.125.504-1.125 1.125m19.5 0v1.5c0 .621-.504 1.125-1.125 1.125M2.25 5.625v1.5c0 .621.504 1.125 1.125 1.125m0 0h17.25m-17.25 0h7.5c.621 0 1.125.504 1.125 1.125M3.375 8.25c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125m17.25-3.75h-7.5c-.621 0-1.125.504-1.125 1.125m8.625-1.125c.621 0 1.125.504 1.125 1.125v1.5c0 .621-.504 1.125-1.125 1.125m-17.25 0h7.5m-7.5 0c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125M12 10.875v-1.5m0 1.5c0 .621-.504 1.125-1.125 1.125M12 10.875c0 .621.504 1.125 1.125 1.125m-2.25 0c.621 0 1.125.504 1.125 1.125M10.875 12c-.621 0-1.125.504-1.125 1.125M12 12c.621 0 1.125.504 1.125 1.125m0 0v1.5c0 .621-.504 1.125-1.125 1.125M12 15.375c-.621 0-1.125-.504-1.125-1.125" />+ </svg>+ ),+ gradient: "from-orange-500/10 to-amber-500/10 dark:from-orange-500/5 dark:to-amber-500/5",+ iconBg: "bg-orange-500/10 text-orange-600 dark:text-orange-400",+ },+ {+ title: "SSH Tunnel",+ description:+ "Connect to production databases securely. Password and key authentication. Credentials in macOS Keychain.",+ icon: (+ <svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">+ <path strokeLinecap="round" strokeLinejoin="round" d="M16.5 10.5V6.75a4.5 4.5 0 10-9 0v3.75m-.75 11.25h10.5a2.25 2.25 0 002.25-2.25v-6.75a2.25 2.25 0 00-2.25-2.25H6.75a2.25 2.25 0 00-2.25 2.25v6.75a2.25 2.25 0 002.25 2.25z" />+ </svg>+ ),+ gradient: "from-rose-500/10 to-red-500/10 dark:from-rose-500/5 dark:to-red-500/5",+ iconBg: "bg-rose-500/10 text-rose-600 dark:text-rose-400",+ },+ {+ title: "Import & Export",+ description:+ "Import from CSV, JSON, SQL. Export query results or entire tables. Backup and restore with a few clicks.",+ icon: (+ <svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">+ <path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5" />+ </svg>+ ),+ gradient: "from-indigo-500/10 to-violet-500/10 dark:from-indigo-500/5 dark:to-violet-500/5",+ iconBg: "bg-indigo-500/10 text-indigo-600 dark:text-indigo-400",+ },+];++export default function Features() {+ const ref = useReveal();++ return (+ <section id="features" className="py-20 md:py-28">+ <div ref={ref} className="mx-auto max-w-6xl px-6">+ <div className="reveal text-center mb-16">+ <p className="text-xs font-medium text-phoenix uppercase tracking-[0.2em] mb-3">+ Features+ </p>+ <h2 className="text-3xl md:text-4xl font-bold tracking-tight text-foreground mb-4">+ Everything you need,{" "}+ <span className="gradient-text">nothing you don't</span>+ </h2>+ <p className="text-muted max-w-lg mx-auto">+ A fast, intelligent database tool built for developers who value simplicity and power.+ </p>+ </div>++ <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-4">+ {features.map((f, i) => (+ <div+ key={f.title}+ className={`reveal reveal-delay-${Math.min(i + 1, 5)} group relative rounded-2xl border border-border p-6 bg-card hover:bg-card-hover transition-all duration-300 hover:border-border hover:shadow-lg hover:shadow-black/5 dark:hover:shadow-black/20`}+ >+ {/* Gradient bg on hover */}+ <div+ className={`absolute inset-0 rounded-2xl bg-gradient-to-br ${f.gradient} opacity-0 group-hover:opacity-100 transition-opacity duration-300`}+ />++ <div className="relative">+ <div+ className={`w-10 h-10 rounded-xl ${f.iconBg} flex items-center justify-center mb-4`}+ >+ {f.icon}+ </div>+ <h3 className="text-base font-semibold text-foreground mb-2">+ {f.title}+ </h3>+ <p className="text-sm text-muted leading-relaxed">+ {f.description}+ </p>+ </div>+ </div>+ ))}+ </div>+ </div>+ </section>+ );+}diff --git a/landing/src/app/components/Footer.tsx b/landing/src/app/components/Footer.tsxnew file mode 100644index 0000000..88a488a--- /dev/null+++ b/landing/src/app/components/Footer.tsx@@ -0,0 +1,95 @@+import Image from "next/image";++const groups = [+ {+ title: "Product",+ links: [+ { label: "Features", href: "/#features" },+ { label: "Download", href: "/download" },+ { label: "Compare", href: "/#comparison" },+ { label: "Changelog", href: "#" },+ ],+ },+ {+ title: "Resources",+ links: [+ { label: "Documentation", href: "#" },+ { label: "Blog", href: "#" },+ { label: "Support", href: "#" },+ ],+ },+ {+ title: "Company",+ links: [+ { label: "About", href: "#" },+ { label: "GitHub", href: "#" },+ { label: "Twitter", href: "#" },+ { label: "Discord", href: "#" },+ ],+ },+];++export default function Footer() {+ return (+ <footer className="border-t border-border">+ <div className="mx-auto max-w-6xl px-6 py-12 md:py-16">+ <div className="grid grid-cols-2 md:grid-cols-5 gap-8">+ {/* Brand */}+ <div className="col-span-2">+ <a href="#" className="flex items-center gap-2 mb-4">+ <Image+ src="/logo.png"+ alt="Gridex"+ width={24}+ height={24}+ className="rounded-md"+ />+ <span className="font-semibold text-foreground text-sm">Gridex</span>+ </a>+ <p className="text-sm text-muted-foreground leading-relaxed max-w-xs">+ AI-Native Database IDE for macOS.+ <br />+ Built in Vietnam.+ </p>+ </div>++ {/* Link groups */}+ {groups.map((g) => (+ <div key={g.title}>+ <h4 className="text-xs font-semibold text-foreground uppercase tracking-wider mb-4">+ {g.title}+ </h4>+ <ul className="space-y-2.5">+ {g.links.map((link) => (+ <li key={link.label}>+ <a+ href={link.href}+ className="text-sm text-muted-foreground hover:text-foreground transition-colors"+ >+ {link.label}+ </a>+ </li>+ ))}+ </ul>+ </div>+ ))}+ </div>++ {/* Bottom */}+ <div className="mt-12 pt-8 border-t border-border flex flex-col sm:flex-row items-center justify-between gap-4">+ <p className="text-xs text-muted-foreground">+ © {new Date().getFullYear()} Gridex. All rights reserved.+ </p>+ <div className="flex items-center gap-4">+ <a href="#" className="text-xs text-muted-foreground hover:text-foreground transition-colors">+ Privacy+ </a>+ <a href="#" className="text-xs text-muted-foreground hover:text-foreground transition-colors">+ Terms+ </a>+ </div>+ </div>+ </div>+ </footer>+ );+}diff --git a/landing/src/app/components/Hero.tsx b/landing/src/app/components/Hero.tsxnew file mode 100644index 0000000..4af912b--- /dev/null+++ b/landing/src/app/components/Hero.tsx@@ -0,0 +1,127 @@+"use client";++import Image from "next/image";+import { SiApple, SiIntel } from "react-icons/si";+import { BsWindows } from "react-icons/bs";+import type { IconType } from "react-icons";+import { useReveal } from "../hooks/useReveal";+import { useDetectedBuild } from "../hooks/useDetectedBuild";+import { BUILD_LABELS, type BuildId } from "../lib/platform";++const BUILD_ICONS: Record<BuildId, IconType> = {+ "mac-arm": SiApple,+ "mac-x64": SiIntel,+ windows: BsWindows,+};++export default function Hero() {+ const ref = useReveal();+ const detected = useDetectedBuild();+ const DetectedIcon = detected ? BUILD_ICONS[detected] : null;+ const downloadLabel = detected ? BUILD_LABELS[detected] : "Download Gridex";++ return (+ <section className="relative pt-28 pb-16 md:pt-40 md:pb-24 overflow-hidden">+ {/* Background effects */}+ <div className="absolute inset-0 pointer-events-none">+ {/* Radial glow */}+ <div className="absolute top-[-20%] left-1/2 -translate-x-1/2 w-[1000px] h-[600px] rounded-full bg-gradient-to-b from-phoenix/15 via-flame/8 to-transparent blur-[100px] dark:from-phoenix/10 dark:via-flame/5" />+ {/* Grid */}+ <div className="absolute inset-0 grid-bg" />+ {/* Fade bottom */}+ <div className="absolute bottom-0 left-0 right-0 h-40 bg-gradient-to-t from-background to-transparent" />+ </div>++ <div ref={ref} className="relative mx-auto max-w-4xl px-6 text-center">+ {/* Logo */}+ <div className="reveal flex justify-center mb-8">+ <div className="relative">+ <Image+ src="/logo.png"+ alt="Gridex"+ width={80}+ height={80}+ className="rounded-2xl"+ priority+ />+ <div className="absolute inset-0 rounded-2xl glow-phoenix" />+ </div>+ </div>++ {/* Badge */}+ <div className="reveal reveal-delay-1 flex justify-center mb-6">+ <div className="inline-flex items-center gap-2 px-3.5 py-1.5 rounded-full border border-phoenix/20 bg-phoenix/5 dark:bg-phoenix/10">+ <span className="relative flex h-2 w-2">+ <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-phoenix opacity-75" />+ <span className="relative inline-flex rounded-full h-2 w-2 bg-phoenix" />+ </span>+ <span className="text-xs font-medium text-phoenix tracking-wide uppercase">+ Now with MongoDB & SQL Server+ </span>+ </div>+ </div>++ {/* Headline */}+ <h1 className="reveal reveal-delay-2 text-4xl sm:text-5xl md:text-6xl lg:text-[4.25rem] font-bold tracking-tight leading-[1.1] mb-6">+ The database IDE{" "}+ <br className="hidden sm:block" />+ <span className="gradient-text">powered by AI</span>+ </h1>++ {/* Subheadline */}+ <p className="reveal reveal-delay-3 text-base md:text-lg text-muted max-w-xl mx-auto mb-10 leading-relaxed">+ Query, explore, and manage all your databases from one native macOS app.+ With built-in AI chat powered by Claude, GPT, or local Ollama.+ </p>++ {/* CTAs */}+ <div className="reveal reveal-delay-4 flex flex-col sm:flex-row items-center justify-center gap-3">+ <a+ href="/download"+ className="w-full sm:w-auto gradient-primary text-white font-medium px-7 py-3 rounded-xl hover:opacity-90 transition-all shadow-lg shadow-phoenix/20 hover:shadow-phoenix/30 flex items-center justify-center gap-2.5"+ >+ {DetectedIcon ? (+ <DetectedIcon className="w-5 h-5" />+ ) : (+ <svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">+ <path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3" />+ </svg>+ )}+ {downloadLabel}+ </a>+ <a+ href="/#features"+ className="w-full sm:w-auto text-foreground font-medium px-7 py-3 rounded-xl border border-border hover:bg-black/5 dark:hover:bg-white/5 transition-colors flex items-center justify-center gap-2"+ >+ See features+ <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">+ <path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />+ </svg>+ </a>+ </div>++ {/* Social proof */}+ <div className="reveal reveal-delay-5 mt-12 flex flex-wrap items-center justify-center gap-6 text-xs text-muted-foreground">+ <div className="flex items-center gap-1.5">+ <svg className="w-4 h-4 text-emerald-500" fill="currentColor" viewBox="0 0 20 20">+ <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />+ </svg>+ Free to use+ </div>+ <div className="flex items-center gap-1.5">+ <svg className="w-4 h-4 text-emerald-500" fill="currentColor" viewBox="0 0 20 20">+ <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />+ </svg>+ 6 databases supported+ </div>+ <div className="flex items-center gap-1.5">+ <svg className="w-4 h-4 text-emerald-500" fill="currentColor" viewBox="0 0 20 20">+ <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />+ </svg>+ Native macOS+ </div>+ </div>+ </div>+ </section>+ );+}diff --git a/landing/src/app/components/Navbar.tsx b/landing/src/app/components/Navbar.tsxnew file mode 100644index 0000000..d8882fa--- /dev/null+++ b/landing/src/app/components/Navbar.tsx@@ -0,0 +1,139 @@+"use client";++import { useTheme } from "./ThemeProvider";+import Image from "next/image";+import { useState, useEffect } from "react";++export default function Navbar() {+ const { theme, toggleTheme } = useTheme();+ const [mobileOpen, setMobileOpen] = useState(false);+ const [scrolled, setScrolled] = useState(false);++ useEffect(() => {+ const onScroll = () => setScrolled(window.scrollY > 20);+ window.addEventListener("scroll", onScroll, { passive: true });+ return () => window.removeEventListener("scroll", onScroll);+ }, []);++ const links = [+ { href: "/#features", label: "Features" },+ { href: "/#comparison", label: "Compare" },+ { href: "/download", label: "Download" },+ ];++ return (+ <header+ className={`fixed top-0 left-0 right-0 z-50 transition-all duration-300 ${+ scrolled+ ? "bg-white/70 dark:bg-[#09090B]/70 backdrop-blur-xl border-b border-border shadow-sm"+ : "bg-transparent"+ }`}+ >+ <nav className="mx-auto max-w-6xl flex items-center justify-between px-6 h-16">+ {/* Logo */}+ <a href="#" className="flex items-center gap-2.5 group">+ <Image+ src="/logo.png"+ alt="Gridex"+ width={30}+ height={30}+ className="rounded-lg transition-transform group-hover:scale-105"+ />+ <span className="text-lg font-semibold tracking-tight text-foreground">+ Gridex+ </span>+ </a>++ {/* Desktop nav */}+ <div className="hidden md:flex items-center gap-1">+ {links.map((l) => (+ <a+ key={l.href}+ href={l.href}+ className="px-4 py-2 text-sm text-muted hover:text-foreground rounded-lg hover:bg-black/5 dark:hover:bg-white/5 transition-colors"+ >+ {l.label}+ </a>+ ))}+ </div>++ {/* Actions */}+ <div className="flex items-center gap-2">+ <button+ onClick={toggleTheme}+ className="p-2 rounded-lg text-muted hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5 transition-colors"+ aria-label="Toggle theme"+ >+ {theme === "dark" ? (+ <svg className="w-[18px] h-[18px]" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">+ <circle cx="12" cy="12" r="5" />+ <path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42" />+ </svg>+ ) : (+ <svg className="w-[18px] h-[18px]" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">+ <path d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z" />+ </svg>+ )}+ </button>++ <a+ href="https://github.com"+ target="_blank"+ rel="noopener noreferrer"+ className="hidden sm:flex p-2 rounded-lg text-muted hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5 transition-colors"+ aria-label="GitHub"+ >+ <svg className="w-[18px] h-[18px]" fill="currentColor" viewBox="0 0 24 24">+ <path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12" />+ </svg>+ </a>++ <a+ href="/download"+ className="hidden md:inline-flex items-center gap-2 gradient-primary text-white text-sm font-medium px-4 py-2 rounded-lg hover:opacity-90 transition-opacity"+ >+ Download+ </a>++ {/* Mobile toggle */}+ <button+ className="md:hidden p-2 rounded-lg text-muted hover:text-foreground"+ onClick={() => setMobileOpen(!mobileOpen)}+ aria-label="Menu"+ >+ <svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">+ {mobileOpen ? (+ <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />+ ) : (+ <path strokeLinecap="round" strokeLinejoin="round" d="M4 6h16M4 12h16M4 18h16" />+ )}+ </svg>+ </button>+ </div>+ </nav>++ {/* Mobile menu */}+ {mobileOpen && (+ <div className="md:hidden border-t border-border bg-white/90 dark:bg-[#09090B]/90 backdrop-blur-xl px-6 py-4 space-y-1">+ {links.map((l) => (+ <a+ key={l.href}+ href={l.href}+ onClick={() => setMobileOpen(false)}+ className="block px-3 py-2.5 text-sm text-muted hover:text-foreground rounded-lg hover:bg-black/5 dark:hover:bg-white/5"+ >+ {l.label}+ </a>+ ))}+ <a+ href="/download"+ onClick={() => setMobileOpen(false)}+ className="block gradient-primary text-white text-sm font-medium px-3 py-2.5 rounded-lg text-center mt-2"+ >+ Download+ </a>+ </div>+ )}+ </header>+ );+}diff --git a/landing/src/app/components/ThemeProvider.tsx b/landing/src/app/components/ThemeProvider.tsxnew file mode 100644index 0000000..860daad--- /dev/null+++ b/landing/src/app/components/ThemeProvider.tsx@@ -0,0 +1,46 @@+"use client";++import { createContext, useContext, useEffect, useState } from "react";++type Theme = "light" | "dark";++const ThemeContext = createContext<{+ theme: Theme;+ toggleTheme: () => void;+}>({+ theme: "dark",+ toggleTheme: () => {},+});++export function useTheme() {+ return useContext(ThemeContext);+}++export function ThemeProvider({ children }: { children: React.ReactNode }) {+ const [theme, setTheme] = useState<Theme>("dark");+ const [mounted, setMounted] = useState(false);++ useEffect(() => {+ const saved = localStorage.getItem("gridex-theme") as Theme | null;+ if (saved) {+ setTheme(saved);+ } else if (window.matchMedia("(prefers-color-scheme: light)").matches) {+ setTheme("light");+ }+ setMounted(true);+ }, []);++ useEffect(() => {+ if (!mounted) return;+ document.documentElement.classList.toggle("dark", theme === "dark");+ localStorage.setItem("gridex-theme", theme);+ }, [theme, mounted]);++ const toggleTheme = () => setTheme((t) => (t === "dark" ? "light" : "dark"));++ return (+ <ThemeContext.Provider value={{ theme, toggleTheme }}>+ <div style={{ visibility: mounted ? "visible" : "hidden" }}>{children}</div>+ </ThemeContext.Provider>+ );+}diff --git a/landing/src/app/download/DownloadContent.tsx b/landing/src/app/download/DownloadContent.tsxnew file mode 100644index 0000000..78433fe--- /dev/null+++ b/landing/src/app/download/DownloadContent.tsx@@ -0,0 +1,335 @@+"use client";++import Navbar from "../components/Navbar";+import Footer from "../components/Footer";+import { SiApple, SiIntel } from "react-icons/si";+import { BsWindows } from "react-icons/bs";+import type { IconType } from "react-icons";+import { useReveal } from "../hooks/useReveal";+import { useDetectedBuild } from "../hooks/useDetectedBuild";+import type { BuildId } from "../lib/platform";++type Build = {+ id: BuildId;+ platform: string;+ arch: string;+ Icon: IconType;+ archIcon?: IconType;+ description: string;+ fileFormat: string;+ size: string;+ href: string;+};++const APP_VERSION = "0.1.0";++const builds: Build[] = [+ {+ id: "mac-arm",+ platform: "macOS",+ arch: "Apple Silicon",+ Icon: SiApple,+ archIcon: SiApple,+ description: "For Mac with M1, M2, M3, or M4 chip.",+ fileFormat: "Universal .dmg",+ size: "~48 MB",+ href:+ process.env.NEXT_PUBLIC_DOWNLOAD_MAC_ARM64 ??+ `/downloads/Gridex-${APP_VERSION}-arm64.dmg`,+ },+ {+ id: "mac-x64",+ platform: "macOS",+ arch: "Intel",+ Icon: SiApple,+ archIcon: SiIntel,+ description: "For Mac with Intel processor (2015 – 2020).",+ fileFormat: ".dmg",+ size: "~52 MB",+ href:+ process.env.NEXT_PUBLIC_DOWNLOAD_MAC_X64 ??+ `/downloads/Gridex-${APP_VERSION}-x64.dmg`,+ },+ {+ id: "windows",+ platform: "Windows",+ arch: "x64",+ Icon: BsWindows,+ description: "For Windows 10 and Windows 11 (64-bit).",+ fileFormat: ".exe installer",+ size: "~62 MB",+ href:+ process.env.NEXT_PUBLIC_DOWNLOAD_WIN_X64 ??+ `/downloads/Gridex-${APP_VERSION}-setup.exe`,+ },+];+++function DownloadHero() {+ const ref = useReveal();+ return (+ <section className="relative pt-32 pb-10 md:pt-40 md:pb-14 overflow-hidden">+ <div className="absolute inset-0 pointer-events-none">+ <div className="absolute top-[-10%] left-1/2 -translate-x-1/2 w-[800px] h-[400px] rounded-full bg-gradient-to-b from-phoenix/10 via-flame/5 to-transparent blur-[100px]" />+ </div>+ <div ref={ref} className="relative mx-auto max-w-3xl px-6 text-center">+ <div className="reveal flex justify-center mb-5">+ <div className="inline-flex items-center gap-2 px-3.5 py-1.5 rounded-full border border-phoenix/20 bg-phoenix/5 dark:bg-phoenix/10">+ <svg className="w-3.5 h-3.5 text-phoenix" fill="currentColor" viewBox="0 0 24 24">+ <path d="M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z" />+ </svg>+ <span className="text-xs font-semibold text-phoenix tracking-wide uppercase">+ Community Edition+ </span>+ </div>+ </div>++ <p className="reveal reveal-delay-1 text-xs font-medium text-phoenix uppercase tracking-[0.2em] mb-3">+ Download+ </p>+ <h1 className="reveal reveal-delay-2 text-4xl md:text-5xl font-bold tracking-tight text-foreground mb-4">+ Get <span className="gradient-text">Gridex</span> for your platform+ </h1>+ <p className="reveal reveal-delay-3 text-muted max-w-lg mx-auto">+ Free and open for the community. No account, no license key, no+ usage limits — choose the build that matches your hardware.+ </p>+ <div className="reveal reveal-delay-4 mt-6 inline-flex items-center gap-2 text-xs text-muted-foreground">+ <span className="px-2 py-1 rounded-md bg-black/[0.04] dark:bg-white/[0.06] font-mono">+ Community v{APP_VERSION}+ </span>+ <span>·</span>+ <a href="#" className="hover:text-foreground transition-colors">+ View changelog+ </a>+ </div>+ </div>+ </section>+ );+}++function DownloadCard({+ build,+ index,+ recommended,+}: {+ build: Build;+ index: number;+ recommended: boolean;+}) {+ const { platform, arch, Icon, archIcon: ArchIcon, description, fileFormat, size, href } = build;+ const delayClass = `reveal-delay-${Math.min(index + 1, 5)}`;++ return (+ <div+ className={`reveal ${delayClass} relative flex flex-col rounded-2xl p-7 transition-all ${+ recommended+ ? "border-2 border-phoenix/30 bg-card shadow-xl shadow-phoenix/5"+ : "border border-border bg-card hover:border-border"+ }`}+ >+ {recommended && (+ <div className="absolute -top-3 left-1/2 -translate-x-1/2">+ <span className="gradient-primary text-white text-[10px] font-semibold uppercase tracking-wider px-3 py-1 rounded-full whitespace-nowrap">+ Recommended for you+ </span>+ </div>+ )}++ <div className="flex items-center gap-3 mb-5">+ <div className="w-12 h-12 rounded-xl bg-black/[0.04] dark:bg-white/[0.06] flex items-center justify-center text-foreground">+ <Icon className="w-6 h-6" />+ </div>+ <div>+ <div className="text-lg font-semibold text-foreground leading-tight">+ {platform}+ </div>+ <div className="flex items-center gap-1.5 text-xs text-muted mt-0.5">+ {ArchIcon && <ArchIcon className="w-3.5 h-3.5" />}+ <span>{arch}</span>+ </div>+ </div>+ </div>++ <p className="text-sm text-muted leading-relaxed mb-5">{description}</p>++ <div className="flex items-center gap-3 text-xs text-muted-foreground mb-6 pb-6 border-b border-border">+ <span className="font-mono">{fileFormat}</span>+ <span>·</span>+ <span>{size}</span>+ </div>++ <a+ href={href}+ download+ className={`mt-auto block w-full text-center font-medium py-2.5 rounded-xl text-sm transition-all ${+ recommended+ ? "gradient-primary text-white hover:opacity-90 shadow-lg shadow-phoenix/15"+ : "border border-border text-foreground hover:bg-black/[0.03] dark:hover:bg-white/[0.03]"+ }`}+ >+ Download for {platform}+ </a>+ </div>+ );+}++function DownloadGrid({ recommendedId }: { recommendedId: BuildId | null }) {+ const ref = useReveal();+ return (+ <section className="py-8 md:py-12">+ <div ref={ref} className="mx-auto max-w-5xl px-6">+ <div className="grid md:grid-cols-3 gap-6">+ {builds.map((b, i) => (+ <DownloadCard+ key={b.id}+ build={b}+ index={i}+ recommended={b.id === recommendedId}+ />+ ))}+ </div>+ </div>+ </section>+ );+}++function SystemRequirements() {+ const ref = useReveal();+ return (+ <section className="py-16 md:py-20 border-t border-border mt-12">+ <div ref={ref} className="mx-auto max-w-5xl px-6">+ <div className="reveal text-center mb-12">+ <h2 className="text-2xl md:text-3xl font-bold tracking-tight text-foreground mb-3">+ System requirements+ </h2>+ <p className="text-muted max-w-md mx-auto">+ Gridex is native on every platform — small binary, fast startup,+ low memory.+ </p>+ </div>++ <div className="reveal reveal-delay-1 grid md:grid-cols-3 gap-4">+ <div className="rounded-xl border border-border bg-card p-5">+ <div className="flex items-center gap-2 mb-3">+ <SiApple className="w-4 h-4 text-foreground" />+ <span className="text-sm font-semibold text-foreground">+ macOS Apple Silicon+ </span>+ </div>+ <ul className="text-sm text-muted space-y-1.5">+ <li>macOS 14 Sonoma or later</li>+ <li>M1 / M2 / M3 / M4</li>+ <li>150 MB disk space</li>+ </ul>+ </div>++ <div className="rounded-xl border border-border bg-card p-5">+ <div className="flex items-center gap-2 mb-3">+ <SiIntel className="w-4 h-4 text-foreground" />+ <span className="text-sm font-semibold text-foreground">+ macOS Intel+ </span>+ </div>+ <ul className="text-sm text-muted space-y-1.5">+ <li>macOS 14 Sonoma or later</li>+ <li>Intel Core i5 or later</li>+ <li>150 MB disk space</li>+ </ul>+ </div>++ <div className="rounded-xl border border-border bg-card p-5">+ <div className="flex items-center gap-2 mb-3">+ <BsWindows className="w-4 h-4 text-foreground" />+ <span className="text-sm font-semibold text-foreground">+ Windows+ </span>+ </div>+ <ul className="text-sm text-muted space-y-1.5">+ <li>Windows 10 / 11 (64-bit)</li>+ <li>.NET 8 runtime (bundled)</li>+ <li>200 MB disk space</li>+ </ul>+ </div>+ </div>+ </div>+ </section>+ );+}++function HowToInstall() {+ const ref = useReveal();+ return (+ <section className="py-16 md:py-20 border-t border-border">+ <div ref={ref} className="mx-auto max-w-3xl px-6">+ <div className="reveal text-center mb-10">+ <h2 className="text-2xl md:text-3xl font-bold tracking-tight text-foreground mb-3">+ How to install+ </h2>+ </div>+ <div className="reveal reveal-delay-1 space-y-5">+ <div className="flex gap-4">+ <div className="shrink-0 w-7 h-7 rounded-full bg-phoenix/10 text-phoenix text-sm font-semibold flex items-center justify-center">+ 1+ </div>+ <div>+ <div className="text-sm font-semibold text-foreground mb-1">+ Download the build for your platform+ </div>+ <div className="text-sm text-muted">+ Not sure which Mac you have? Click{" "}+ <span className="text-foreground font-medium">Apple menu → About This Mac</span>{" "}+ to check your chip.+ </div>+ </div>+ </div>+ <div className="flex gap-4">+ <div className="shrink-0 w-7 h-7 rounded-full bg-phoenix/10 text-phoenix text-sm font-semibold flex items-center justify-center">+ 2+ </div>+ <div>+ <div className="text-sm font-semibold text-foreground mb-1">+ Open the installer+ </div>+ <div className="text-sm text-muted">+ macOS: open the .dmg and drag Gridex into Applications.+ Windows: run the .exe and follow the setup wizard.+ </div>+ </div>+ </div>+ <div className="flex gap-4">+ <div className="shrink-0 w-7 h-7 rounded-full bg-phoenix/10 text-phoenix text-sm font-semibold flex items-center justify-center">+ 3+ </div>+ <div>+ <div className="text-sm font-semibold text-foreground mb-1">+ Launch Gridex+ </div>+ <div className="text-sm text-muted">+ Add your first connection and start querying. Your credentials+ stay on your machine.+ </div>+ </div>+ </div>+ </div>+ </div>+ </section>+ );+}++export default function DownloadContent() {+ const recommendedId = useDetectedBuild();++ return (+ <>+ <Navbar />+ <main className="flex-1">+ <DownloadHero />+ <DownloadGrid recommendedId={recommendedId} />+ <SystemRequirements />+ <HowToInstall />+ </main>+ <Footer />+ </>+ );+}diff --git a/landing/src/app/download/page.tsx b/landing/src/app/download/page.tsxnew file mode 100644index 0000000..cdbf6b3--- /dev/null+++ b/landing/src/app/download/page.tsx@@ -0,0 +1,20 @@+import type { Metadata } from "next";+import DownloadContent from "./DownloadContent";++export const metadata: Metadata = {+ title: "Download",+ description:+ "Download Gridex for macOS (Apple Silicon / Intel) or Windows. Free, native, and privacy-first — no account required.",+ alternates: { canonical: "/download" },+ openGraph: {+ title: "Download Gridex — AI-Native Database IDE",+ description:+ "Get Gridex for macOS (Apple Silicon / Intel) or Windows. Free and native.",+ url: "/download",+ type: "website",+ },+};++export default function DownloadPage() {+ return <DownloadContent />;+}diff --git a/landing/src/app/globals.css b/landing/src/app/globals.cssnew file mode 100644index 0000000..8d73ce0--- /dev/null+++ b/landing/src/app/globals.css@@ -0,0 +1,126 @@+@import "tailwindcss";++@custom-variant dark (&:where(.dark, .dark *));++@theme inline {+ --color-background: var(--background);+ --color-foreground: var(--foreground);+ --color-muted: var(--muted);+ --color-muted-foreground: var(--muted-foreground);+ --color-border: var(--border);+ --color-card: var(--card);+ --color-card-hover: var(--card-hover);+ --font-sans: var(--font-geist-sans);+ --font-mono: var(--font-geist-mono);++ /* Brand */+ --color-crimson: #D42020;+ --color-phoenix: #E83A1C;+ --color-flame: #F06525;+ --color-amber-brand: #F58B2C;+ --color-light-amber: #F9A83A;+ --color-navy: #0A0A12;+ --color-deep-blue: #16213E;+}++:root {+ --background: #FFFFFF;+ --foreground: #0F172A;+ --muted: #64748B;+ --muted-foreground: #94A3B8;+ --border: #E2E8F0;+ --card: #FFFFFF;+ --card-hover: #F8FAFC;+}++.dark {+ --background: #131316;+ --foreground: #FAFAFA;+ --muted: #A1A1AA;+ --muted-foreground: #8B8B93;+ --border: #27272C;+ --card: #1A1A1E;+ --card-hover: #212126;+}++/* Reset */+*,+*::before,+*::after {+ border-color: var(--border);+}++body {+ background: var(--background);+ color: var(--foreground);+ font-family: var(--font-sans), system-ui, -apple-system, sans-serif;+ -webkit-font-smoothing: antialiased;+ -moz-osx-font-smoothing: grayscale;+}++html {+ scroll-behavior: smooth;+}++/* Gradient utilities */+.gradient-text {+ background: linear-gradient(135deg, #E83A1C 0%, #F06525 40%, #F9A83A 100%);+ -webkit-background-clip: text;+ -webkit-text-fill-color: transparent;+ background-clip: text;+}++.gradient-primary {+ background: linear-gradient(135deg, #D42020 0%, #F06525 50%, #F9A83A 100%);+}++.gradient-primary-hover {+ background: linear-gradient(135deg, #C01C1C 0%, #E05A20 50%, #E89530 100%);+}++/* Glow effects */+.glow-phoenix {+ box-shadow: 0 0 40px rgba(232, 58, 28, 0.15), 0 0 80px rgba(240, 101, 37, 0.08);+}++.dark .glow-phoenix {+ box-shadow: 0 0 40px rgba(232, 58, 28, 0.25), 0 0 80px rgba(240, 101, 37, 0.12);+}++/* Reveal animations */+.reveal {+ opacity: 0;+ transform: translateY(24px);+ transition: opacity 0.7s cubic-bezier(0.16, 1, 0.3, 1),+ transform 0.7s cubic-bezier(0.16, 1, 0.3, 1);+}++.reveal.visible {+ opacity: 1;+ transform: translateY(0);+}++.reveal-delay-1 { transition-delay: 0.1s; }+.reveal-delay-2 { transition-delay: 0.2s; }+.reveal-delay-3 { transition-delay: 0.3s; }+.reveal-delay-4 { transition-delay: 0.4s; }+.reveal-delay-5 { transition-delay: 0.5s; }++/* Noise texture overlay */+.noise::before {+ content: "";+ position: absolute;+ inset: 0;+ background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)' opacity='0.03'/%3E%3C/svg%3E");+ pointer-events: none;+ z-index: 0;+}++/* Subtle grid bg */+.grid-bg {+ background-size: 60px 60px;+ background-image:+ linear-gradient(to right, var(--border) 1px, transparent 1px),+ linear-gradient(to bottom, var(--border) 1px, transparent 1px);+ opacity: 0.4;+}diff --git a/landing/src/app/hooks/useDetectedBuild.ts b/landing/src/app/hooks/useDetectedBuild.tsnew file mode 100644index 0000000..f0d02ad--- /dev/null+++ b/landing/src/app/hooks/useDetectedBuild.ts@@ -0,0 +1,20 @@+"use client";++import { useEffect, useState } from "react";+import { detectBuild, type BuildId } from "../lib/platform";++export function useDetectedBuild(): BuildId | null {+ const [id, setId] = useState<BuildId | null>(null);++ useEffect(() => {+ let cancelled = false;+ detectBuild().then((result) => {+ if (!cancelled) setId(result);+ });+ return () => {+ cancelled = true;+ };+ }, []);++ return id;+}diff --git a/landing/src/app/hooks/useReveal.ts b/landing/src/app/hooks/useReveal.tsnew file mode 100644index 0000000..11e30a3--- /dev/null+++ b/landing/src/app/hooks/useReveal.ts@@ -0,0 +1,33 @@+"use client";++import { useEffect, useRef } from "react";++export function useReveal() {+ const ref = useRef<HTMLDivElement>(null);++ useEffect(() => {+ const el = ref.current;+ if (!el) return;++ const observer = new IntersectionObserver(+ (entries) => {+ entries.forEach((entry) => {+ if (entry.isIntersecting) {+ entry.target.classList.add("visible");+ observer.unobserve(entry.target);+ }+ });+ },+ { threshold: 0.1, rootMargin: "0px 0px -40px 0px" }+ );++ // Observe the container and all reveal children+ const children = el.querySelectorAll(".reveal");+ children.forEach((child) => observer.observe(child));+ if (el.classList.contains("reveal")) observer.observe(el);++ return () => observer.disconnect();+ }, []);++ return ref;+}diff --git a/landing/src/app/icon.png b/landing/src/app/icon.pngnew file mode 100644index 0000000..3a45e46Binary files /dev/null and b/landing/src/app/icon.png differdiff --git a/landing/src/app/layout.tsx b/landing/src/app/layout.tsxnew file mode 100644index 0000000..c9445dd--- /dev/null+++ b/landing/src/app/layout.tsx@@ -0,0 +1,127 @@+import type { Metadata, Viewport } from "next";+import { Geist, Geist_Mono } from "next/font/google";+import { ThemeProvider } from "./components/ThemeProvider";+import "./globals.css";++const geistSans = Geist({+ variable: "--font-geist-sans",+ subsets: ["latin"],+});++const geistMono = Geist_Mono({+ variable: "--font-geist-mono",+ subsets: ["latin"],+});++const siteUrl = process.env.NEXT_PUBLIC_SITE_URL ?? "https://gridex.app";+const title = "Gridex — AI-Native Database IDE for macOS";+const description =+ "Gridex is the native macOS database IDE with built-in AI chat. Query PostgreSQL, MySQL, SQLite, Redis, MongoDB, and SQL Server faster with Claude, GPT, or local Ollama.";++export const metadata: Metadata = {+ metadataBase: new URL(siteUrl),+ title: {+ default: title,+ template: "%s — Gridex",+ },+ description,+ applicationName: "Gridex",+ authors: [{ name: "Gridex" }],+ creator: "Gridex",+ publisher: "Gridex",+ keywords: [+ "database IDE",+ "macOS database client",+ "AI SQL editor",+ "PostgreSQL client",+ "MySQL client",+ "SQLite client",+ "Redis GUI",+ "MongoDB GUI",+ "SQL Server client",+ "TablePlus alternative",+ "DBeaver alternative",+ "Claude SQL",+ "Ollama SQL",+ "native Mac app",+ ],+ category: "developer tools",+ alternates: {+ canonical: "/",+ },+ openGraph: {+ type: "website",+ url: siteUrl,+ siteName: "Gridex",+ title,+ description,+ locale: "en_US",+ },+ twitter: {+ card: "summary_large_image",+ title,+ description,+ creator: "@gridexapp",+ },+ robots: {+ index: true,+ follow: true,+ googleBot: {+ index: true,+ follow: true,+ "max-image-preview": "large",+ "max-snippet": -1,+ "max-video-preview": -1,+ },+ },+ formatDetection: {+ telephone: false,+ email: false,+ address: false,+ },+};++export const viewport: Viewport = {+ themeColor: [+ { media: "(prefers-color-scheme: light)", color: "#FFFFFF" },+ { media: "(prefers-color-scheme: dark)", color: "#131316" },+ ],+ colorScheme: "light dark",+};++export default function RootLayout({+ children,+}: Readonly<{+ children: React.ReactNode;+}>) {+ const jsonLd = {+ "@context": "https://schema.org",+ "@type": "SoftwareApplication",+ name: "Gridex",+ applicationCategory: "DeveloperApplication",+ operatingSystem: "macOS",+ description,+ url: siteUrl,+ offers: {+ "@type": "Offer",+ price: "0",+ priceCurrency: "USD",+ },+ };++ return (+ <html+ lang="en"+ className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}+ suppressHydrationWarning+ >+ <body className="min-h-full flex flex-col">+ <ThemeProvider>{children}</ThemeProvider>+ <script+ type="application/ld+json"+ dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}+ />+ </body>+ </html>+ );+}diff --git a/landing/src/app/lib/platform.ts b/landing/src/app/lib/platform.tsnew file mode 100644index 0000000..5cc9fb4--- /dev/null+++ b/landing/src/app/lib/platform.ts@@ -0,0 +1,55 @@+export type BuildId = "mac-arm" | "mac-x64" | "windows";++type NavigatorUAData = {+ platform: string;+ getHighEntropyValues: (hints: string[]) => Promise<{ architecture?: string }>;+};++export async function detectBuild(): Promise<BuildId | null> {+ if (typeof navigator === "undefined") return null;++ const uaData = (navigator as unknown as { userAgentData?: NavigatorUAData })+ .userAgentData;+ const ua = navigator.userAgent;++ const isWindows = uaData?.platform === "Windows" || /Windows/i.test(ua);+ if (isWindows) return "windows";++ const isMac = uaData?.platform === "macOS" || /Mac/i.test(ua);+ if (!isMac) return null;++ if (uaData?.getHighEntropyValues) {+ try {+ const data = await uaData.getHighEntropyValues(["architecture"]);+ if (data.architecture === "arm") return "mac-arm";+ if (data.architecture === "x86") return "mac-x64";+ } catch {+ // fall through+ }+ }++ try {+ const canvas = document.createElement("canvas");+ const gl =+ canvas.getContext("webgl") ?? canvas.getContext("experimental-webgl");+ const dbg =+ gl && (gl as WebGLRenderingContext).getExtension("WEBGL_debug_renderer_info");+ if (dbg && gl) {+ const renderer = (gl as WebGLRenderingContext).getParameter(+ (dbg as { UNMASKED_RENDERER_WEBGL: number }).UNMASKED_RENDERER_WEBGL,+ ) as string;+ if (/Apple (M\d|GPU)/i.test(renderer)) return "mac-arm";+ if (/Intel/i.test(renderer)) return "mac-x64";+ }+ } catch {+ // ignore+ }++ return "mac-arm";+}++export const BUILD_LABELS: Record<BuildId, string> = {+ "mac-arm": "Download for Mac (Apple Silicon)",+ "mac-x64": "Download for Mac (Intel)",+ windows: "Download for Windows",+};diff --git a/landing/src/app/manifest.ts b/landing/src/app/manifest.tsnew file mode 100644index 0000000..ff72d5a--- /dev/null+++ b/landing/src/app/manifest.ts@@ -0,0 +1,26 @@+import type { MetadataRoute } from "next";++export default function manifest(): MetadataRoute.Manifest {+ return {+ name: "Gridex — AI-Native Database IDE",+ short_name: "Gridex",+ description:+ "Native macOS database IDE with built-in AI chat.",+ start_url: "/",+ display: "standalone",+ background_color: "#131316",+ theme_color: "#131316",+ icons: [+ {+ src: "/icon-192.png",+ sizes: "192x192",+ type: "image/png",+ },+ {+ src: "/icon-512.png",+ sizes: "512x512",+ type: "image/png",+ },+ ],+ };+}diff --git a/landing/src/app/opengraph-image.tsx b/landing/src/app/opengraph-image.tsxnew file mode 100644index 0000000..58ca3e1--- /dev/null+++ b/landing/src/app/opengraph-image.tsx@@ -0,0 +1,97 @@+import { ImageResponse } from "next/og";+import { readFile } from "node:fs/promises";+import { join } from "node:path";++export const alt = "Gridex — AI-Native Database IDE for macOS";+export const size = { width: 1200, height: 630 };+export const contentType = "image/png";++export default async function OpengraphImage() {+ const logo = await readFile(join(process.cwd(), "public/logo.png"));+ const logoSrc = `data:image/png;base64,${logo.toString("base64")}`;++ return new ImageResponse(+ (+ <div+ style={{+ width: "100%",+ height: "100%",+ display: "flex",+ flexDirection: "column",+ justifyContent: "space-between",+ padding: "80px",+ background:+ "linear-gradient(135deg, #0F0F12 0%, #1A1318 45%, #2A1410 100%)",+ color: "#FAFAFA",+ fontFamily: "sans-serif",+ }}+ >+ <div style={{ display: "flex", alignItems: "center", gap: 24 }}>+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img src={logoSrc} width={96} height={96} alt="" />+ <div style={{ fontSize: 44, fontWeight: 700, letterSpacing: -1 }}>+ Gridex+ </div>+ </div>++ <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>+ <div+ style={{+ display: "flex",+ flexDirection: "column",+ fontSize: 72,+ fontWeight: 700,+ lineHeight: 1.05,+ letterSpacing: -2,+ maxWidth: 1000,+ }}+ >+ <div style={{ display: "flex" }}>The AI-Native Database IDE</div>+ <div+ style={{+ display: "flex",+ background:+ "linear-gradient(135deg, #E83A1C 0%, #F06525 50%, #F9A83A 100%)",+ backgroundClip: "text",+ color: "transparent",+ }}+ >+ for macOS+ </div>+ </div>+ <div+ style={{+ fontSize: 28,+ color: "#A1A1AA",+ maxWidth: 900,+ lineHeight: 1.35,+ }}+ >+ Query PostgreSQL, MySQL, SQLite, Redis, MongoDB, and SQL Server+ with built-in AI chat.+ </div>+ </div>++ <div+ style={{+ display: "flex",+ justifyContent: "space-between",+ alignItems: "center",+ fontSize: 20,+ color: "#71717A",+ }}+ >+ <div style={{ display: "flex", gap: 24 }}>+ <span>Claude</span>+ <span>·</span>+ <span>GPT</span>+ <span>·</span>+ <span>Ollama</span>+ </div>+ <div>gridex.app</div>+ </div>+ </div>+ ),+ { ...size },+ );+}diff --git a/landing/src/app/page.tsx b/landing/src/app/page.tsxnew file mode 100644index 0000000..32ecee4--- /dev/null+++ b/landing/src/app/page.tsx@@ -0,0 +1,23 @@+import Navbar from "./components/Navbar";+import Hero from "./components/Hero";+import Databases from "./components/Databases";+import Features from "./components/Features";+import Comparison from "./components/Comparison";+import CTA from "./components/CTA";+import Footer from "./components/Footer";++export default function Home() {+ return (+ <>+ <Navbar />+ <main className="flex-1">+ <Hero />+ <Databases />+ <Features />+ <Comparison />+ <CTA />+ </main>+ <Footer />+ </>+ );+}diff --git a/landing/src/app/robots.ts b/landing/src/app/robots.tsnew file mode 100644index 0000000..0b73321--- /dev/null+++ b/landing/src/app/robots.ts@@ -0,0 +1,14 @@+import type { MetadataRoute } from "next";++const siteUrl = process.env.NEXT_PUBLIC_SITE_URL ?? "https://gridex.app";++export default function robots(): MetadataRoute.Robots {+ return {+ rules: {+ userAgent: "*",+ allow: "/",+ },+ sitemap: `${siteUrl}/sitemap.xml`,+ host: siteUrl,+ };+}diff --git a/landing/src/app/sitemap.ts b/landing/src/app/sitemap.tsnew file mode 100644index 0000000..3ed0022--- /dev/null+++ b/landing/src/app/sitemap.ts@@ -0,0 +1,20 @@+import type { MetadataRoute } from "next";++const siteUrl = process.env.NEXT_PUBLIC_SITE_URL ?? "https://gridex.app";++export default function sitemap(): MetadataRoute.Sitemap {+ return [+ {+ url: siteUrl,+ lastModified: new Date(),+ changeFrequency: "weekly",+ priority: 1,+ },+ {+ url: `${siteUrl}/download`,+ lastModified: new Date(),+ changeFrequency: "weekly",+ priority: 0.9,+ },+ ];+}diff --git a/landing/src/app/twitter-image.tsx b/landing/src/app/twitter-image.tsxnew file mode 100644index 0000000..76d5636--- /dev/null+++ b/landing/src/app/twitter-image.tsx@@ -0,0 +1 @@+export { default, alt, size, contentType } from "./opengraph-image";diff --git a/landing/tsconfig.json b/landing/tsconfig.jsonnew file mode 100644index 0000000..cf9c65d--- /dev/null+++ b/landing/tsconfig.json@@ -0,0 +1,34 @@+{+ "compilerOptions": {+ "target": "ES2017",+ "lib": ["dom", "dom.iterable", "esnext"],+ "allowJs": true,+ "skipLibCheck": true,+ "strict": true,+ "noEmit": true,+ "esModuleInterop": true,+ "module": "esnext",+ "moduleResolution": "bundler",+ "resolveJsonModule": true,+ "isolatedModules": true,+ "jsx": "react-jsx",+ "incremental": true,+ "plugins": [+ {+ "name": "next"+ }+ ],+ "paths": {+ "@/*": ["./src/*"]+ }+ },+ "include": [+ "next-env.d.ts",+ "**/*.ts",+ "**/*.tsx",+ ".next/types/**/*.ts",+ ".next/dev/types/**/*.ts",+ "**/*.mts"+ ],+ "exclude": ["node_modules"]+}diff --git a/logo.png b/logo.pngnew file mode 100644index 0000000..cc8608eBinary files /dev/null and b/logo.png differdiff --git a/macos/App/Configuration/AppConstants.swift b/macos/App/Configuration/AppConstants.swiftnew file mode 100644index 0000000..bb90c5b--- /dev/null+++ b/macos/App/Configuration/AppConstants.swift@@ -0,0 +1,36 @@+// AppConstants.swift+// Gridex++import Foundation++enum AppConstants {+ static let appName = "Gridex"+ static let bundleIdentifier = "com.gridex.app"++ enum Defaults {+ static let pageSize = 500+ static let sidebarWidth: Double = 240+ static let aiPanelWidth: Double = 320+ static let schemaRefreshInterval: TimeInterval = 300 // 5 minutes+ static let maxQueryTimeout: TimeInterval = 30+ }++ enum AI {+ static let defaultModel = "claude-sonnet-4-6"+ static let defaultProvider = "anthropic"+ static let defaultMaxTokens = 4096+ static let defaultTemperature = 0.3+ static let maxContextTokens = 100000+ }++ enum UI {+ static let minWindowWidth: CGFloat = 900+ static let minWindowHeight: CGFloat = 500+ static let defaultWindowWidth: CGFloat = 1200+ static let defaultWindowHeight: CGFloat = 700+ static let rowHeight: CGFloat = 28+ static let headerHeight: CGFloat = 32+ static let statusBarHeight: CGFloat = 24+ static let tabBarHeight: CGFloat = 32+ }+}diff --git a/macos/App/DependencyInjection/DependencyContainer.swift b/macos/App/DependencyInjection/DependencyContainer.swiftnew file mode 100644index 0000000..11e2233--- /dev/null+++ b/macos/App/DependencyInjection/DependencyContainer.swift@@ -0,0 +1,64 @@+// DependencyContainer.swift+// Gridex+//+// Central dependency injection container.++import Foundation+import SwiftData++@MainActor+final class DependencyContainer {++ /// Shared instance — ensures SwiftData ModelContainer is created only once,+ /// even when multiple windows each own their own AppState.+ static let shared = DependencyContainer()++ // MARK: - SwiftData++ lazy var modelContainer: ModelContainer = {+ let schema = Schema([+ SavedConnectionEntity.self,+ QueryHistoryEntity.self,+ ])+ let config = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)+ do {+ return try ModelContainer(for: schema, configurations: [config])+ } catch {+ fatalError("Failed to create ModelContainer: \(error)")+ }+ }()++ // MARK: - Core Services++ lazy var keychainService: KeychainServiceProtocol = KeychainService()+ lazy var schemaCache = SchemaCache()+ lazy var connectionManager = ConnectionManager()++ // MARK: - Repositories++ lazy var connectionRepository: any ConnectionRepository = SwiftDataConnectionRepository(modelContainer: modelContainer)+ lazy var queryHistoryRepository: any QueryHistoryRepository = SwiftDataQueryHistoryRepository(modelContainer: modelContainer)++ // MARK: - Services++ lazy var queryEngine: QueryEngine = {+ QueryEngine(connectionManager: connectionManager, historyRepository: queryHistoryRepository)+ }()++ lazy var schemaInspector = SchemaInspectorService(cache: schemaCache, connectionManager: connectionManager)+ lazy var aiContextEngine = AIContextEngine(schemaCache: schemaCache)+ lazy var sshTunnelService = SSHTunnelService()+ lazy var exportService = ExportService()++ // MARK: - AI++ func makeLLMService(provider: String, apiKey: String, baseURL: String? = nil) -> any LLMService {+ switch provider {+ case "anthropic": return AnthropicProvider(apiKey: apiKey)+ case "openai": return OpenAIProvider(apiKey: apiKey)+ case "ollama": return OllamaProvider()+ case "gemini": return GeminiProvider(apiKey: apiKey, baseURL: baseURL ?? "https://generativelanguage.googleapis.com/v1beta/openai")+ default: return AnthropicProvider(apiKey: apiKey)+ }+ }+}diff --git a/macos/App/Lifecycle/AppDelegate.swift b/macos/App/Lifecycle/AppDelegate.swiftnew file mode 100644index 0000000..367ea88--- /dev/null+++ b/macos/App/Lifecycle/AppDelegate.swift@@ -0,0 +1,117 @@+// AppDelegate.swift+// Gridex+//+// Legacy AppDelegate — kept for applicationWillTerminate cleanup.+// The @main entry point is now GridexApp.swift.++import AppKit++final class AppDelegate: NSObject, NSApplicationDelegate {++ func applicationWillFinishLaunching(_ notification: Notification) {+ // Register bundle identifier for SPM builds (fixes "missing main bundle identifier" warning)+ if Bundle.main.bundleIdentifier == nil {+ UserDefaults.standard.set("com.gridex.app", forKey: "CFBundleIdentifier")+ }+ }++ func applicationDidFinishLaunching(_ notification: Notification) {+ // Ensure app activates and shows window when launched from terminal/SPM+ NSApplication.shared.setActivationPolicy(.regular)+ NSApplication.shared.activate(ignoringOtherApps: true)++ // Thin scrollbars app-wide; horizontal always visible+ UserDefaults.standard.set("Always", forKey: "AppleShowScrollBars")++ NotificationCenter.default.addObserver(+ forName: NSView.frameDidChangeNotification,+ object: nil,+ queue: .main+ ) { notification in+ guard let scrollView = notification.object as? NSScrollView else { return }+ // Mini control size for thin scrollbars+ if let vScroller = scrollView.verticalScroller, vScroller.controlSize != .mini {+ vScroller.controlSize = .mini+ }+ scrollView.hasHorizontalScroller = true+ if let hScroller = scrollView.horizontalScroller, hScroller.controlSize != .mini {+ hScroller.controlSize = .mini+ }+ }++ // Make sure the main window is visible and set up close interception+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {+ self.installCloseInterceptor()+ }++ // Also observe new windows in case SwiftUI recreates the window.+ // Only install on the primary main window — skip NSPanel (e.g. ConnectionFormPanel)+ // and any auxiliary windows, otherwise closing them would route through+ // WindowCloseInterceptor and terminate the app.+ NotificationCenter.default.addObserver(+ forName: NSWindow.didBecomeKeyNotification,+ object: nil,+ queue: .main+ ) { [weak self] notification in+ guard let window = notification.object as? NSWindow,+ window.delegate !== WindowCloseInterceptor.shared,+ !(window is NSPanel),+ window.canBecomeMain else { return }+ self?.installCloseInterceptor(for: window)+ }+ }++ private func installCloseInterceptor(for window: NSWindow? = nil) {+ let win = window ?? NSApplication.shared.windows.first+ guard let win else { return }+ win.makeKeyAndOrderFront(nil)+ win.delegate = WindowCloseInterceptor.shared+ }++ func applicationWillTerminate(_ notification: Notification) {+ // Cleanup: disconnect all active database connections+ }++ func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {+ true+ }++ func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {+ if !flag {+ for window in sender.windows {+ window.makeKeyAndOrderFront(nil)+ }+ }+ return true+ }++ func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {+ true+ }+}++// Intercepts the window close button for multi-window support.+// - Multiple windows open: close the window normally (MainView.onDisappear cleans up).+// - Last window: disconnect and show Home instead of closing (preserves single-window UX).+final class WindowCloseInterceptor: NSObject, NSWindowDelegate {+ static let shared = WindowCloseInterceptor()++ func windowShouldClose(_ sender: NSWindow) -> Bool {+ let otherMainWindows = NSApp.windows.filter {+ $0 !== sender && $0.canBecomeMain && !($0 is NSPanel) && $0.isVisible+ }++ if otherMainWindows.isEmpty {+ // Last window — keep it open, just disconnect+ NotificationCenter.default.post(name: .windowCloseRequested, object: sender)+ return false+ } else {+ // Other windows exist — close this one+ return true+ }+ }+}++extension Notification.Name {+ static let windowCloseRequested = Notification.Name("Gridex.windowCloseRequested")+}diff --git a/macos/App/Lifecycle/GridexApp.swift b/macos/App/Lifecycle/GridexApp.swiftnew file mode 100644index 0000000..2550bf0--- /dev/null+++ b/macos/App/Lifecycle/GridexApp.swift@@ -0,0 +1,138 @@+// GridexApp.swift+// Gridex+//+// SwiftUI application entry point.++import SwiftUI+import SwiftData++@main+struct GridexApp: App {+ @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate+ @FocusedObject private var focusedAppState: AppState?++ private var currentAppState: AppState? { focusedAppState ?? AppState.active }++ var body: some Scene {+ WindowGroup {+ WindowRoot()+ .frame(minWidth: 900, minHeight: 500)+ }+ .defaultSize(width: 900, height: 500)+ .windowToolbarStyle(.unified(showsTitle: false))+ .commands {+ CommandGroup(replacing: .appSettings) {+ Button("Settings...") {+ currentAppState?.showSettings = true+ }+ .keyboardShortcut(",", modifiers: .command)+ }++ CommandGroup(after: .newItem) {+ // Cmd+N → default WindowGroup "New Window" (opens a fresh connection picker)++ Button("New Query") {+ currentAppState?.openNewQueryTab()+ }+ .keyboardShortcut("n", modifiers: [.command, .shift])+ .disabled(currentAppState?.activeAdapter == nil)++ Button("New Connection") {+ currentAppState?.showConnectionForm = true+ }+ .keyboardShortcut("t", modifiers: .command)++ Divider()++ Button("Close Tab") {+ currentAppState?.closeActiveTab()+ }+ .keyboardShortcut("w", modifiers: .command)++ Button("Disconnect") {+ currentAppState?.disconnect()+ }+ .keyboardShortcut("d", modifiers: [.command, .shift])+ .disabled(currentAppState?.activeAdapter == nil)+ }++ CommandGroup(after: .sidebar) {+ Button("Toggle Sidebar") {+ currentAppState?.sidebarVisible.toggle()+ }+ .keyboardShortcut("\\", modifiers: .command)++ Button("Toggle AI Panel") {+ currentAppState?.aiPanelVisible.toggle()+ }+ .keyboardShortcut("a", modifiers: [.command, .shift])+ }++ CommandMenu("Database") {+ Button("Open Database...") {+ currentAppState?.showDatabaseSwitcher = true+ }+ .keyboardShortcut("k", modifiers: .command)+ .disabled(currentAppState?.activeAdapter == nil)++ Button("New Table...") {+ currentAppState?.showNewTableSheet = true+ }+ .disabled(currentAppState?.activeAdapter == nil)+ }++ CommandMenu("Data") {+ Button("Commit Changes") {+ NotificationCenter.default.post(name: .commitChanges, object: nil)+ }+ .keyboardShortcut("s", modifiers: .command)++ Button("Reload Data") {+ NotificationCenter.default.post(name: .reloadData, object: nil)+ }+ .keyboardShortcut("r", modifiers: .command)++ Divider()++ Button("Toggle Filters") {+ NotificationCenter.default.post(name: .toggleFilterBar, object: nil)+ }+ .keyboardShortcut("f", modifiers: .command)+ }++ CommandMenu("Query") {+ Button("Execute") {+ NotificationCenter.default.post(name: .executeQuery, object: nil)+ }+ .keyboardShortcut("r", modifiers: [.command, .shift])++ Button("Explain") {+ NotificationCenter.default.post(name: .explainQuery, object: nil)+ }+ .keyboardShortcut("e", modifiers: .command)++ Divider()++ Button("Format SQL") {+ NotificationCenter.default.post(name: .formatSQL, object: nil)+ }+ .keyboardShortcut("b", modifiers: [.command, .shift])+ }+ }++ Settings {+ SettingsView()+ }+ }+}++extension Notification.Name {+ static let executeQuery = Notification.Name("Gridex.executeQuery")+ static let executeSelection = Notification.Name("Gridex.executeSelection")+ static let explainQuery = Notification.Name("Gridex.explainQuery")+ static let formatSQL = Notification.Name("Gridex.formatSQL")+ static let deleteSelectedRows = Notification.Name("Gridex.deleteSelectedRows")+ static let commitChanges = Notification.Name("Gridex.commitChanges")+ static let reloadData = Notification.Name("Gridex.reloadData")+ static let toggleFilterBar = Notification.Name("Gridex.toggleFilterBar")+}diff --git a/macos/App/State/AppState.swift b/macos/App/State/AppState.swiftnew file mode 100644index 0000000..2bf6736--- /dev/null+++ b/macos/App/State/AppState.swift@@ -0,0 +1,735 @@+// AppState.swift+// Gridex+//+// Central application state for SwiftUI. Replaces AppCoordinator.++import SwiftUI+import Combine++@MainActor+final class AppState: ObservableObject {++ /// The AppState of the currently focused window. Updated by WindowRoot+ /// when a window appears or gains focus. Used as a fallback for menu commands.+ static weak var active: AppState?++ // MARK: - Dependencies++ /// Shared across all windows so SwiftData ModelContainer is a singleton.+ let container = DependencyContainer.shared++ // MARK: - Navigation State++ @Published var sidebarVisible = true+ @Published var detailsPanelVisible = true+ /// Persisted width of the details panel so toggling doesn't reset it.+ @Published var detailsPanelWidth: CGFloat = 320++ /// Tables the user has marked for deletion in the sidebar.+ /// They are NOT dropped until the user clicks the commit button in the sidebar header.+ /// Key is the table name (per active connection / schema).+ @Published var pendingTableDeletions: [String: PendingTableDeletion] = [:]+ @Published var pendingTableTruncations: Set<String> = []++ struct PendingTableDeletion {+ var tableName: String+ var cascade: Bool+ var ignoreForeignKeys: Bool+ }+ /// Chat messages per connection (keyed by connectionId). In-memory only.+ var aiChatMessages: [UUID: [ChatDisplayMessage]] = [:]+ @Published var aiPanelVisible = false+ @Published var showDBTypePicker = false+ @Published var showConnectionForm = false+ @Published var showSettings = false+ @Published var showDatabaseSwitcher = false+ @Published var showNewTableSheet = false+ @Published var selectedDBType: DatabaseType?+ @Published var selectedSidebarItem: SidebarItemType?++ // MARK: - Home State++ @Published var savedConnections: [ConnectionConfig] = []+ @Published var connectionSearchText = ""+ @Published var connectionGroups: Set<String> = [] {+ didSet {+ UserDefaults.standard.set(Array(connectionGroups), forKey: "connectionGroups")+ }+ }++ // MARK: - Connection State++ @Published var activeConnectionId: UUID?+ @Published var activeAdapter: (any DatabaseAdapter)?+ @Published var activeConfig: ConnectionConfig?+ @Published var sidebarItems: [SidebarItem] = []+ @Published var connectionTitle: String = "Gridex"+ @Published var isConnecting: Bool = false+ @Published var connectionError: String?+ @Published var serverVersion: String?+ @Published var sslInfo: String?++ // MARK: - Tab State++ @Published var tabs: [ContentTab] = []+ @Published var activeTabId: UUID? {+ didSet { syncSidebarFromActiveTab() }+ }++ // Cache DataGridViewState per tab to avoid reloading when switching tabs+ var dataGridCache: [UUID: DataGridViewState] = [:]++ func cachedDataGridState(for tabId: UUID) -> DataGridViewState {+ if let existing = dataGridCache[tabId] { return existing }+ let state = DataGridViewState()+ dataGridCache[tabId] = state+ return state+ }++ // Persist SQL editor text per tab so switching tabs doesn't lose work+ var queryEditorText: [UUID: String] = [:]++ // MARK: - Database List+ @Published var availableDatabases: [String] = []++ // MARK: - Status Bar++ @Published var statusConnection: String?+ @Published var statusSchema: String?+ @Published var statusRowCount: Int?+ @Published var statusQueryTime: TimeInterval?++ // MARK: - Redis State+ @Published var redisDBSize: Int?+ @Published var showFlushDBConfirm = false+ @Published var showRedisAddKey = false++ // MARK: - Query Log (global, shared across all tables)+ @Published var queryLog: [QueryLogEntry] = []+ @Published var showQueryLog: Bool = false++ /// Log a query to the in-memory SQL log panel. Used by all query sources+ /// (data grid loads, structure changes, user queries) for the bottom log panel.+ func logQuery(sql: String, duration: TimeInterval?) {+ let entry = QueryLogEntry(sql: sql, timestamp: Date(), duration: duration)+ queryLog.append(entry)+ }++ /// Counter that increments whenever a query is recorded to history.+ /// Observed by QueryHistoryTab to trigger reload.+ @Published var queryHistoryVersion: Int = 0++ /// Persist a user-executed SQL query to the sidebar History (SwiftData).+ /// Called ONLY from the SQL query editor — not from data grid loads,+ /// structure inspections, or internal DML. Survives app restarts.+ func recordQueryHistory(sql: String, duration: TimeInterval?, rowCount: Int? = nil, error: String? = nil) {+ guard let connectionId = activeConnectionId else { return }+ let database = currentDatabaseName ?? ""+ let historyEntry = QueryHistoryEntry(+ id: UUID(),+ connectionId: connectionId,+ database: database,+ sql: sql,+ executedAt: Date(),+ duration: duration ?? 0,+ rowCount: rowCount,+ status: error == nil ? .success : .error,+ errorMessage: error,+ isFavorite: false+ )+ let repo = container.queryHistoryRepository+ Task {+ try? await repo.save(entry: historyEntry)+ await MainActor.run { self.queryHistoryVersion += 1 }+ }+ }++ func clearQueryLog() {+ queryLog.removeAll()+ }++ // MARK: - Selected Row Details+ @Published var selectedRowDetails: [(column: String, value: String)]?+ var onDetailFieldEdit: ((_ colIndex: Int, _ newValue: String) -> Void)?++ // MARK: - Tab Types++ struct ContentTab: Identifiable {+ let id: UUID+ let type: TabState.TabType+ var title: String+ let tableName: String?+ let schema: String?+ var databaseName: String?+ var initialViewMode: String? // "data" or "structure"+ }++ struct TabGroup: Identifiable {+ let id: String // keyed by databaseName+ let databaseName: String+ var displayName: String?+ var color: ColorTag+ var isCollapsed: Bool++ var label: String { displayName ?? databaseName }+ }++ // MARK: - Tab Group State++ @Published var tabGroups: [String: TabGroup] = [:]+ @Published var currentDatabaseName: String?++ private static let groupColors: [ColorTag] = [.blue, .green, .purple, .orange, .red, .gray]++ /// Whether tabs should display as groups (2+ databases open)+ var isMultiDatabase: Bool {+ Set(tabs.compactMap(\.databaseName)).count > 1+ }++ /// Tabs grouped by database. Returns flat list when single database.+ var groupedTabs: [(group: TabGroup?, tabs: [ContentTab])] {+ let uniqueDatabases = Set(tabs.compactMap(\.databaseName))++ if uniqueDatabases.count <= 1 {+ return [(group: nil, tabs: tabs)]+ }++ var seen: [String] = []+ var grouped: [String: [ContentTab]] = [:]+ for tab in tabs {+ let key = tab.databaseName ?? "Ungrouped"+ if !seen.contains(key) { seen.append(key) }+ grouped[key, default: []].append(tab)+ }++ return seen.map { key in+ let group = tabGroups[key] ?? TabGroup(+ id: key, databaseName: key, displayName: nil,+ color: autoColor(for: key), isCollapsed: false+ )+ return (group: group, tabs: grouped[key] ?? [])+ }+ }++ private func autoColor(for databaseName: String) -> ColorTag {+ let allNames = Set(tabs.compactMap(\.databaseName)).sorted()+ let index = allNames.firstIndex(of: databaseName) ?? 0+ return Self.groupColors[index % Self.groupColors.count]+ }++ func renameTab(id: UUID, newTitle: String) {+ guard let index = tabs.firstIndex(where: { $0.id == id }) else { return }+ tabs[index].title = newTitle+ }++ // MARK: - Connection++ func connect(config: ConnectionConfig, password: String, sshPassword: String? = nil) async {+ isConnecting = true+ connectionError = nil++ // If the caller didn't provide an SSH password but the config needs one,+ // try to load it from the Keychain.+ let effectiveSSHPassword: String? = {+ if let explicit = sshPassword, !explicit.isEmpty { return explicit }+ guard config.sshConfig != nil else { return nil }+ return try? container.keychainService.load(+ key: "ssh.password.\(config.id.uuidString)")+ }()++ do {+ // Race the connection attempt against a 20s timeout so the UI never+ // stays stuck "Connecting…" forever (e.g. when the server is unreachable+ // or the network stack blocks indefinitely).+ let connectionManager = container.connectionManager+ let connection = try await withThrowingTaskGroup(of: ActiveConnection.self) { group in+ group.addTask {+ try await connectionManager.connect(+ config: config, password: password, sshPassword: effectiveSSHPassword+ )+ }+ group.addTask {+ try await Task.sleep(nanoseconds: 10_000_000_000) // 10s+ throw NSError(+ domain: "Gridex.Connection",+ code: -1001,+ userInfo: [NSLocalizedDescriptionKey: "Connection timed out after 10 seconds. Check host, port, and network."]+ )+ }+ guard let result = try await group.next() else {+ throw NSError(domain: "Gridex.Connection", code: -1002,+ userInfo: [NSLocalizedDescriptionKey: "Connection failed unexpectedly."])+ }+ group.cancelAll()+ return result+ }+ activeConnectionId = config.id+ activeAdapter = connection.adapter+ activeConfig = config+ connectionTitle = "Gridex — \(config.name)"+ statusConnection = config.displayHost+ isConnecting = false++ // Load sidebar immediately (most important for user)+ await loadSidebar(config: config, adapter: connection.adapter)++ // Fetch metadata in background — all parallel+ Task { [weak self] in+ guard let self else { return }+ let adapter = connection.adapter++ await withTaskGroup(of: Void.self) { group in+ // SSL info+ group.addTask {+ if config.sslEnabled {+ if let sslResult = try? await adapter.executeRaw(sql: "SHOW ssl"),+ let sslOn = sslResult.rows.first?.first?.stringValue, sslOn == "on" {+ if let verResult = try? await adapter.executeRaw(sql: "SELECT ssl_version FROM pg_stat_ssl WHERE pid = pg_backend_pid()"),+ let tlsVer = verResult.rows.first?.first?.stringValue {+ await MainActor.run { self.sslInfo = tlsVer }+ } else {+ await MainActor.run { self.sslInfo = "TLS" }+ }+ } else {+ await MainActor.run { self.sslInfo = "SSL" }+ }+ }+ }++ // Server version+ group.addTask {+ if let fullVersion = try? await adapter.serverVersion() {+ let parts = fullVersion.split(separator: " ")+ if parts.count >= 2, let ver = parts.first(where: { $0.first?.isNumber == true }) {+ await MainActor.run { self.serverVersion = String(ver).trimmingCharacters(in: .punctuationCharacters) }+ } else {+ await MainActor.run { self.serverVersion = fullVersion }+ }+ }+ }++ // Current database + available databases+ group.addTask {+ let dbName = try? await adapter.currentDatabase()+ let databases = (try? await adapter.listDatabases()) ?? []+ await MainActor.run {+ self.currentDatabaseName = dbName ?? config.database ?? config.name+ self.availableDatabases = databases+ }+ }++ // Redis DBSIZE+ if config.databaseType == .redis, let redis = adapter as? RedisAdapter {+ group.addTask {+ let size = try? await redis.dbSize()+ await MainActor.run { self.redisDBSize = size }+ }+ }+ }+ }+ } catch {+ isConnecting = false+ connectionError = error.localizedDescription+ print("Connection failed: \(error)")+ }+ }++ func loadSidebar(config: ConnectionConfig, adapter: any DatabaseAdapter) async {+ do {+ // Run all queries in parallel instead of sequential+ async let tablesTask = adapter.listTables(schema: nil)+ async let viewsTask = adapter.listViews(schema: nil)+ async let functionsTask = adapter.listFunctions(schema: nil)+ async let proceduresTask = adapter.listProcedures(schema: nil)++ let tables = try await tablesTask+ let views = try await viewsTask+ let functions = try await functionsTask+ let procedures = (try? await proceduresTask) ?? []++ let tableItems = tables.map { t in+ SidebarItem(title: t.name, type: .table(t.name), iconName: "")+ }+ let viewItems = views.map { v in+ SidebarItem(title: v.name, type: .view(v.name), iconName: "")+ }+ let functionItems = functions.map { f in+ SidebarItem(title: f, type: .function(f), iconName: "")+ }+ let procedureItems = procedures.map { p in+ SidebarItem(title: p, type: .procedure(p), iconName: "")+ }++ var items: [SidebarItem] = []++ if !functionItems.isEmpty {+ items.append(SidebarItem(title: "Functions", type: .group("functions"), iconName: "", children: functionItems))+ }++ if !procedureItems.isEmpty {+ items.append(SidebarItem(title: "Procedures", type: .group("procedures"), iconName: "", children: procedureItems))+ }++ items.append(SidebarItem(title: "Tables", type: .group("tables"), iconName: "", children: tableItems))++ if !viewItems.isEmpty {+ items.append(SidebarItem(title: "Views", type: .group("views"), iconName: "", children: viewItems))+ }++ sidebarItems = items+ } catch {+ print("Sidebar load error: \(error)")+ }+ }++ // MARK: - Tab Management++ private func syncSidebarFromActiveTab() {+ guard let activeId = activeTabId,+ let tab = tabs.first(where: { $0.id == activeId }),+ let name = tab.tableName else { return }+ switch tab.type {+ case .functionDetail:+ if tab.initialViewMode == "procedure" {+ selectedSidebarItem = .procedure(name)+ } else {+ selectedSidebarItem = .function(name)+ }+ default:+ selectedSidebarItem = .table(name)+ }+ }++ func openTable(name: String, schema: String?) {+ if let existing = tabs.first(where: { $0.type == .dataGrid && $0.tableName == name && $0.schema == schema }) {+ activeTabId = existing.id+ return+ }+ let tab = ContentTab(id: UUID(), type: .dataGrid, title: name, tableName: name, schema: schema, databaseName: currentDatabaseName)+ tabs.append(tab)+ activeTabId = tab.id+ if let db = currentDatabaseName { ensureTabGroup(for: db) }+ }++ func openTableStructure(name: String, schema: String?) {+ if let existing = tabs.first(where: { $0.type == .dataGrid && $0.tableName == name && $0.schema == schema }) {+ activeTabId = existing.id+ } else {+ let tab = ContentTab(id: UUID(), type: .dataGrid, title: name, tableName: name, schema: schema, databaseName: currentDatabaseName, initialViewMode: "structure")+ tabs.append(tab)+ activeTabId = tab.id+ if let db = currentDatabaseName { ensureTabGroup(for: db) }+ }+ // Post notification for already-open tabs to switch mode+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {+ NotificationCenter.default.post(name: .init("switchToStructure"), object: name)+ }+ }++ func openTableWithFilter(name: String, schema: String?, filterColumn: String, filterValue: String) {+ // Always open a new tab (don't reuse existing — different filter context)+ let tab = ContentTab(id: UUID(), type: .dataGrid, title: name, tableName: name, schema: schema, databaseName: currentDatabaseName)+ tabs.append(tab)+ activeTabId = tab.id+ if let db = currentDatabaseName { ensureTabGroup(for: db) }++ // Pre-configure the cached DataGridViewState with filter+ let state = cachedDataGridState(for: tab.id)+ let filter = FilterExpression(+ conditions: [FilterCondition(column: filterColumn, op: .equal, value: .string(filterValue))],+ combinator: .and+ )+ state.activeFilter = filter+ state.showFilterBar = true+ }++ func openTableList(schema: String?) {+ let schemaName = schema ?? "public"+ let title = "Tables.\(schemaName)"+ if let existing = tabs.first(where: { $0.type == .tableList && $0.schema == schema }) {+ activeTabId = existing.id+ return+ }+ let tab = ContentTab(id: UUID(), type: .tableList, title: title, tableName: nil, schema: schema, databaseName: currentDatabaseName)+ tabs.append(tab)+ activeTabId = tab.id+ if let db = currentDatabaseName { ensureTabGroup(for: db) }+ }++ func openFunction(name: String, schema: String?) {+ if let existing = tabs.first(where: { $0.type == .functionDetail && $0.tableName == name && $0.schema == schema && $0.initialViewMode != "procedure" }) {+ activeTabId = existing.id+ return+ }+ let tab = ContentTab(id: UUID(), type: .functionDetail, title: name, tableName: name, schema: schema, databaseName: currentDatabaseName)+ tabs.append(tab)+ activeTabId = tab.id+ if let db = currentDatabaseName { ensureTabGroup(for: db) }+ }++ func openProcedure(name: String, schema: String?) {+ if let existing = tabs.first(where: { $0.type == .functionDetail && $0.tableName == name && $0.schema == schema && $0.initialViewMode == "procedure" }) {+ activeTabId = existing.id+ return+ }+ let tab = ContentTab(id: UUID(), type: .functionDetail, title: name, tableName: name, schema: schema, databaseName: currentDatabaseName, initialViewMode: "procedure")+ tabs.append(tab)+ activeTabId = tab.id+ if let db = currentDatabaseName { ensureTabGroup(for: db) }+ }++ func openCreateTable(schema: String?) {+ let tab = ContentTab(id: UUID(), type: .createTable, title: "New Table", tableName: nil, schema: schema, databaseName: currentDatabaseName)+ tabs.append(tab)+ activeTabId = tab.id+ if let db = currentDatabaseName { ensureTabGroup(for: db) }+ }++ func openERDiagram(schema: String?) {+ let title = "ER Diagram"+ if let existing = tabs.first(where: { $0.type == .erDiagram && $0.schema == schema }) {+ activeTabId = existing.id+ return+ }+ let tab = ContentTab(id: UUID(), type: .erDiagram, title: title, tableName: nil, schema: schema, databaseName: currentDatabaseName)+ tabs.append(tab)+ activeTabId = tab.id+ if let db = currentDatabaseName { ensureTabGroup(for: db) }+ }++ // MARK: - Redis Tabs++ func openRedisKeyDetail(key: String) {+ if let existing = tabs.first(where: { $0.type == .redisKeyDetail && $0.tableName == key }) {+ activeTabId = existing.id+ return+ }+ let tab = ContentTab(id: UUID(), type: .redisKeyDetail, title: key, tableName: key, schema: nil, databaseName: currentDatabaseName)+ tabs.append(tab)+ activeTabId = tab.id+ if let db = currentDatabaseName { ensureTabGroup(for: db) }+ }++ func openRedisServerInfo() {+ if let existing = tabs.first(where: { $0.type == .redisServerInfo }) {+ activeTabId = existing.id+ return+ }+ let tab = ContentTab(id: UUID(), type: .redisServerInfo, title: "Server Info", tableName: nil, schema: nil, databaseName: currentDatabaseName)+ tabs.append(tab)+ activeTabId = tab.id+ if let db = currentDatabaseName { ensureTabGroup(for: db) }+ }++ func openRedisSlowLog() {+ if let existing = tabs.first(where: { $0.type == .redisSlowLog }) {+ activeTabId = existing.id+ return+ }+ let tab = ContentTab(id: UUID(), type: .redisSlowLog, title: "Slow Log", tableName: nil, schema: nil, databaseName: currentDatabaseName)+ tabs.append(tab)+ activeTabId = tab.id+ if let db = currentDatabaseName { ensureTabGroup(for: db) }+ }++ func openNewQueryTab() {+ let number = tabs.filter { $0.type == .queryEditor }.count + 1+ let tab = ContentTab(id: UUID(), type: .queryEditor, title: "Query \(number)", tableName: nil, schema: nil, databaseName: currentDatabaseName)+ tabs.append(tab)+ activeTabId = tab.id+ if let db = currentDatabaseName { ensureTabGroup(for: db) }+ }++ func closeTab(id: UUID) {+ tabs.removeAll { $0.id == id }+ if let state = dataGridCache.removeValue(forKey: id) {+ state.rows = []+ state.displayCache = []+ state.columns = []+ }+ if activeTabId == id {+ activeTabId = tabs.last?.id+ }+ }++ func closeActiveTab() {+ guard let id = activeTabId else { return }+ closeTab(id: id)+ }++ func closeOtherTabs(except id: UUID) {+ let closedIds = tabs.filter { $0.id != id }.map(\.id)+ tabs.removeAll { $0.id != id }+ for cid in closedIds {+ if let state = dataGridCache.removeValue(forKey: cid) {+ state.rows = []; state.displayCache = []; state.columns = []+ }+ }+ activeTabId = id+ }++ func closeTabsToTheRight(of id: UUID) {+ guard let index = tabs.firstIndex(where: { $0.id == id }) else { return }+ let closedIds = tabs[(index + 1)...].map(\.id)+ tabs.removeSubrange((index + 1)...)+ for cid in closedIds {+ if let state = dataGridCache.removeValue(forKey: cid) {+ state.rows = []; state.displayCache = []; state.columns = []+ }+ }+ if let activeId = activeTabId, !tabs.contains(where: { $0.id == activeId }) {+ activeTabId = id+ }+ }++ func closeAllTabs() {+ tabs.removeAll()+ for state in dataGridCache.values {+ state.rows = []; state.displayCache = []; state.columns = []+ }+ dataGridCache.removeAll()+ queryEditorText.removeAll()+ activeTabId = nil+ }++ /// Switch to a different database on the same connection.+ /// PostgreSQL requires a full reconnect; MySQL/SQLite can use USE.+ func switchDatabase(_ databaseName: String) async {+ guard let adapter = activeAdapter, var config = activeConfig else { return }++ do {+ switch config.databaseType {+ case .mysql:+ // MySQL supports USE to switch database in-place+ _ = try await adapter.executeRaw(sql: "USE `\(databaseName)`")+ currentDatabaseName = databaseName++ case .mssql:+ // SQL Server supports USE to switch database in-place+ _ = try await adapter.executeRaw(sql: "USE [\(databaseName.replacingOccurrences(of: "]", with: "]]"))]")+ currentDatabaseName = databaseName++ case .postgresql:+ // PostgreSQL: each connection is tied to one database — must reconnect+ try await adapter.disconnect()+ config.database = databaseName+ let pw = (try? container.keychainService.load(key: "db.password.\(config.id.uuidString)")) ?? ""+ let sshPw = config.sshConfig != nil+ ? (try? container.keychainService.load(key: "ssh.password.\(config.id.uuidString)"))+ : nil+ let connection = try await container.connectionManager.connect(config: config, password: pw, sshPassword: sshPw ?? nil)+ activeAdapter = connection.adapter+ activeConfig = config+ currentDatabaseName = databaseName++ case .redis:+ // Redis: SELECT <db_number>+ let dbNum = databaseName.replacingOccurrences(of: "db", with: "")+ _ = try await adapter.executeRaw(sql: "SELECT \(dbNum)")+ currentDatabaseName = databaseName++ case .mongodb:+ // MongoDB: reconnect to the new database+ try await adapter.disconnect()+ config.database = databaseName+ let pw = (try? container.keychainService.load(key: "db.password.\(config.id.uuidString)")) ?? ""+ let sshPw = config.sshConfig != nil+ ? (try? container.keychainService.load(key: "ssh.password.\(config.id.uuidString)"))+ : nil+ let connection = try await container.connectionManager.connect(config: config, password: pw, sshPassword: sshPw ?? nil)+ activeAdapter = connection.adapter+ activeConfig = config+ currentDatabaseName = databaseName++ default:+ currentDatabaseName = databaseName+ }++ ensureTabGroup(for: databaseName)++ // Reload sidebar for the new database+ if let cfg = activeConfig, let adp = activeAdapter {+ await loadSidebar(config: cfg, adapter: adp)+ }+ } catch {+ print("Switch database failed: \(error)")+ connectionError = "Failed to switch to \(databaseName): \(error.localizedDescription)"+ }+ }++ // MARK: - Tab Group Management++ func ensureTabGroup(for databaseName: String) {+ guard tabGroups[databaseName] == nil else { return }+ tabGroups[databaseName] = TabGroup(+ id: databaseName, databaseName: databaseName, displayName: nil,+ color: autoColor(for: databaseName), isCollapsed: false+ )+ }++ func toggleGroupCollapsed(_ groupId: String) {+ tabGroups[groupId]?.isCollapsed.toggle()+ }++ func closeGroup(_ groupId: String) {+ let idsToRemove = Set(tabs.filter { $0.databaseName == groupId }.map(\.id))+ tabs.removeAll { idsToRemove.contains($0.id) }+ tabGroups.removeValue(forKey: groupId)+ if let activeId = activeTabId, idsToRemove.contains(activeId) {+ activeTabId = tabs.last?.id+ }+ }++ func renameGroup(_ groupId: String, newName: String) {+ tabGroups[groupId]?.displayName = newName+ }++ func changeGroupColor(_ groupId: String, color: ColorTag) {+ tabGroups[groupId]?.color = color+ }++ func disconnect() {+ if let adapter = activeAdapter {+ Task { try? await adapter.disconnect() }+ }+ if let connId = activeConnectionId {+ aiChatMessages.removeValue(forKey: connId)+ }+ activeAdapter = nil+ activeConfig = nil+ activeConnectionId = nil+ tabs.removeAll()+ activeTabId = nil+ tabGroups.removeAll()+ currentDatabaseName = nil+ availableDatabases.removeAll()+ sidebarItems.removeAll()+ selectedSidebarItem = nil+ selectedRowDetails = nil+ onDetailFieldEdit = nil+ serverVersion = nil+ sslInfo = nil+ statusConnection = nil+ statusSchema = nil+ statusRowCount = nil+ statusQueryTime = nil+ connectionTitle = "Gridex"+ redisDBSize = nil+ }++ func refreshSidebar() {+ guard let adapter = activeAdapter, let config = activeConfig else { return }+ Task { await loadSidebar(config: config, adapter: adapter) }+ }++ func loadSavedConnections() async {+ do {+ savedConnections = try await container.connectionRepository.fetchAll()+ let stored = Set(UserDefaults.standard.stringArray(forKey: "connectionGroups") ?? [])+ let fromConnections = Set(savedConnections.compactMap { $0.group })+ connectionGroups = stored.union(fromConnections)+ } catch {+ print("Failed to load saved connections: \(error)")+ }+ }+}diff --git a/macos/Core/Enums/ColorTag.swift b/macos/Core/Enums/ColorTag.swiftnew file mode 100644index 0000000..a07c7f2--- /dev/null+++ b/macos/Core/Enums/ColorTag.swift@@ -0,0 +1,40 @@+// ColorTag.swift+// Gridex++import AppKit+import SwiftUI++enum ColorTag: String, Codable, Sendable, CaseIterable {+ case red+ case orange+ case green+ case blue+ case purple+ case gray++ var nsColor: NSColor {+ switch self {+ case .red: return NSColor(calibratedRed: 0.886, green: 0.294, blue: 0.290, alpha: 1.0)+ case .orange: return NSColor(calibratedRed: 0.937, green: 0.624, blue: 0.153, alpha: 1.0)+ case .green: return NSColor(calibratedRed: 0.388, green: 0.600, blue: 0.133, alpha: 1.0)+ case .blue: return NSColor(calibratedRed: 0.216, green: 0.541, blue: 0.867, alpha: 1.0)+ case .purple: return NSColor(calibratedRed: 0.325, green: 0.290, blue: 0.718, alpha: 1.0)+ case .gray: return NSColor.secondaryLabelColor+ }+ }++ var swiftUIColor: Color {+ Color(nsColor: nsColor)+ }++ var environmentHint: String {+ switch self {+ case .red: return "Production"+ case .orange: return "Staging"+ case .green: return "Development"+ case .blue: return "Local"+ case .purple: return "Custom"+ case .gray: return "Other"+ }+ }+}diff --git a/macos/Core/Enums/DatabaseType.swift b/macos/Core/Enums/DatabaseType.swiftnew file mode 100644index 0000000..bd140c2--- /dev/null+++ b/macos/Core/Enums/DatabaseType.swift@@ -0,0 +1,74 @@+// DatabaseType.swift+// Gridex++import Foundation++enum DatabaseType: String, Codable, Sendable, CaseIterable, Identifiable {+ case postgresql = "postgresql"+ case mysql = "mysql"+ case sqlite = "sqlite"+ case redis = "redis"+ case mongodb = "mongodb"+ case mssql = "mssql"++ var id: String { rawValue }++ var displayName: String {+ switch self {+ case .postgresql: return "PostgreSQL"+ case .mysql: return "MySQL"+ case .sqlite: return "SQLite"+ case .redis: return "Redis"+ case .mongodb: return "MongoDB"+ case .mssql: return "SQL Server"+ }+ }++ var defaultPort: Int {+ switch self {+ case .postgresql: return 5432+ case .mysql: return 3306+ case .sqlite: return 0+ case .redis: return 6379+ case .mongodb: return 27017+ case .mssql: return 1433+ }+ }++ var iconName: String {+ switch self {+ case .postgresql: return "server.rack"+ case .mysql: return "externaldrive.connected.to.line.below"+ case .sqlite: return "doc"+ case .redis: return "key.fill"+ case .mongodb: return "leaf.fill"+ case .mssql: return "cylinder.split.1x2.fill"+ }+ }++ var sqlDialect: SQLDialect {+ switch self {+ case .postgresql: return .postgresql+ case .mysql: return .mysql+ case .sqlite: return .sqlite+ case .redis: return .redis+ case .mongodb: return .mongodb+ case .mssql: return .mssql+ }+ }++ /// Whether this database type uses SQL as its query language.+ var isSQL: Bool {+ switch self {+ case .postgresql, .mysql, .sqlite, .mssql: return true+ case .redis, .mongodb: return false+ }+ }++ var supportsSchemas: Bool {+ switch self {+ case .postgresql, .mssql: return true+ case .mysql, .sqlite, .redis, .mongodb: return false+ }+ }+}diff --git a/macos/Core/Enums/SQLDialect.swift b/macos/Core/Enums/SQLDialect.swiftnew file mode 100644index 0000000..54dd2e3--- /dev/null+++ b/macos/Core/Enums/SQLDialect.swift@@ -0,0 +1,45 @@+// SQLDialect.swift+// Gridex++import Foundation++enum SQLDialect: Sendable {+ case postgresql+ case mysql+ case sqlite+ case redis+ case mongodb+ case mssql++ func quoteIdentifier(_ identifier: String) -> String {+ switch self {+ case .postgresql, .sqlite:+ return "\"\(identifier.replacingOccurrences(of: "\"", with: "\"\""))\""+ case .mysql:+ return "`\(identifier.replacingOccurrences(of: "`", with: "``"))`"+ case .mssql:+ return "[\(identifier.replacingOccurrences(of: "]", with: "]]"))]"+ case .redis, .mongodb:+ return identifier // No quoting for non-SQL databases+ }+ }++ var limitClause: String {+ "LIMIT"+ }++ var offsetClause: String {+ "OFFSET"+ }++ var parameterPlaceholder: (Int) -> String {+ switch self {+ case .postgresql:+ return { "$\($0)" }+ case .mssql:+ return { "@p\($0)" }+ case .mysql, .sqlite, .redis, .mongodb:+ return { _ in "?" }+ }+ }+}diff --git a/macos/Core/Enums/SSHAuthMethod.swift b/macos/Core/Enums/SSHAuthMethod.swiftnew file mode 100644index 0000000..e0ad9f6--- /dev/null+++ b/macos/Core/Enums/SSHAuthMethod.swift@@ -0,0 +1,10 @@+// SSHAuthMethod.swift+// Gridex++import Foundation++enum SSHAuthMethod: String, Codable, Sendable {+ case password+ case privateKey+ case keyWithPassphrase+}diff --git a/macos/Core/Enums/SSLMode.swift b/macos/Core/Enums/SSLMode.swiftnew file mode 100644index 0000000..e0ea77a--- /dev/null+++ b/macos/Core/Enums/SSLMode.swift@@ -0,0 +1,22 @@+// SSLMode.swift+// Gridex++import Foundation++enum SSLMode: String, Codable, Sendable, CaseIterable {+ case preferred = "PREFERRED"+ case disabled = "DISABLED"+ case required = "REQUIRED"+ case verifyCA = "VERIFY_CA"+ case verifyIdentity = "VERIFY_IDENTITY"++ var displayName: String {+ switch self {+ case .preferred: return "PREFERRED"+ case .disabled: return "DISABLED"+ case .required: return "REQUIRED"+ case .verifyCA: return "VERIFY CA"+ case .verifyIdentity: return "VERIFY IDENTITY"+ }+ }+}diff --git a/macos/Core/Errors/GridexError.swift b/macos/Core/Errors/GridexError.swiftnew file mode 100644index 0000000..7ba4c0f--- /dev/null+++ b/macos/Core/Errors/GridexError.swift@@ -0,0 +1,79 @@+// GridexError.swift+// Gridex+//+// Centralized error types for the entire application.++import Foundation++enum GridexError: LocalizedError, Sendable, Equatable {+ static func == (lhs: GridexError, rhs: GridexError) -> Bool {+ lhs.errorDescription == rhs.errorDescription+ }++ // Connection+ case connectionFailed(underlying: any Error & Sendable)+ case connectionTimeout+ case authenticationFailed+ case sslRequired+ case databaseNotFound(String)++ // Query+ case queryExecutionFailed(String)+ case queryCancelled+ case queryTimeout+ case invalidSQL(String)++ // SSH+ case sshConnectionFailed(underlying: any Error & Sendable)+ case sshAuthenticationFailed+ case sshTunnelFailed++ // Schema+ case schemaLoadFailed(String)+ case tableNotFound(String)++ // AI+ case aiProviderError(String)+ case aiAPIKeyMissing+ case aiTokenLimitExceeded+ case aiStreamingError(String)++ // Data+ case keychainError(String)+ case persistenceError(String)+ case importError(String)+ case exportError(String)++ // General+ case unsupportedOperation(String)+ case internalError(String)++ var errorDescription: String? {+ switch self {+ case .connectionFailed(let error): return "Connection failed: \(error.localizedDescription)"+ case .connectionTimeout: return "Connection timed out"+ case .authenticationFailed: return "Authentication failed. Check your credentials."+ case .sslRequired: return "SSL connection is required by the server"+ case .databaseNotFound(let name): return "Database '\(name)' not found"+ case .queryExecutionFailed(let msg): return "Query failed: \(msg)"+ case .queryCancelled: return "Query was cancelled"+ case .queryTimeout: return "Query timed out"+ case .invalidSQL(let msg): return "Invalid SQL: \(msg)"+ case .sshConnectionFailed(let error): return "SSH connection failed: \(error.localizedDescription)"+ case .sshAuthenticationFailed: return "SSH authentication failed"+ case .sshTunnelFailed: return "SSH tunnel could not be established"+ case .schemaLoadFailed(let msg): return "Failed to load schema: \(msg)"+ case .tableNotFound(let name): return "Table '\(name)' not found"+ case .aiProviderError(let msg): return "AI provider error: \(msg)"+ case .aiAPIKeyMissing: return "AI API key is not configured"+ case .aiTokenLimitExceeded: return "Token limit exceeded for AI context"+ case .aiStreamingError(let msg): return "AI streaming error: \(msg)"+ case .keychainError(let msg): return "Keychain error: \(msg)"+ case .persistenceError(let msg): return "Data persistence error: \(msg)"+ case .importError(let msg): return "Import error: \(msg)"+ case .exportError(let msg): return "Export error: \(msg)"+ case .unsupportedOperation(let msg): return "Unsupported operation: \(msg)"+ case .internalError(let msg): return "Internal error: \(msg)"+ }+ }+}diff --git a/macos/Core/Extensions/NSColor+Gridex.swift b/macos/Core/Extensions/NSColor+Gridex.swiftnew file mode 100644index 0000000..0961a63--- /dev/null+++ b/macos/Core/Extensions/NSColor+Gridex.swift@@ -0,0 +1,60 @@+// Color+Gridex.swift+// Gridex+//+// App-specific color constants with dark mode support.++import SwiftUI+import AppKit++extension Color {+ enum Gridex {+ // Syntax highlighting+ static let syntaxKeyword = Color(red: 0.325, green: 0.290, blue: 0.718)+ static let syntaxString = Color(red: 0.388, green: 0.600, blue: 0.133)+ static let syntaxNumber = Color(red: 0.847, green: 0.353, blue: 0.188)+ static let syntaxComment = Color(red: 0.533, green: 0.533, blue: 0.502)+ static let syntaxFunction = Color(red: 0.216, green: 0.541, blue: 0.867)+ static let syntaxOperator = Color(red: 0.831, green: 0.325, blue: 0.494)++ // Data grid (adaptive)+ static let cellModified = Color(nsColor: NSColor.Gridex.cellModified)+ static let cellNew = Color(nsColor: NSColor.Gridex.cellNew)+ static let cellDeleted = Color(nsColor: NSColor.Gridex.cellDeleted)+ static let cellNull = Color(red: 0.533, green: 0.533, blue: 0.502)+ }+}++// NSColor bridge — appearance-aware data grid colors+extension NSColor {+ enum Gridex {+ static let syntaxKeyword = NSColor(calibratedRed: 0.325, green: 0.290, blue: 0.718, alpha: 1.0)+ static let syntaxString = NSColor(calibratedRed: 0.388, green: 0.600, blue: 0.133, alpha: 1.0)+ static let syntaxNumber = NSColor(calibratedRed: 0.847, green: 0.353, blue: 0.188, alpha: 1.0)+ static let syntaxComment = NSColor(calibratedRed: 0.533, green: 0.533, blue: 0.502, alpha: 1.0)+ static let syntaxFunction = NSColor(calibratedRed: 0.216, green: 0.541, blue: 0.867, alpha: 1.0)+ static let syntaxOperator = NSColor(calibratedRed: 0.831, green: 0.325, blue: 0.494, alpha: 1.0)++ // Light: light beige | Dark: dark amber-brown+ static let cellModified = NSColor(name: "cellModified") { appearance in+ appearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua+ ? NSColor(calibratedRed: 0.25, green: 0.20, blue: 0.10, alpha: 1.0)+ : NSColor(calibratedRed: 0.980, green: 0.933, blue: 0.855, alpha: 1.0)+ }++ // Light: light green | Dark: dark green+ static let cellNew = NSColor(name: "cellNew") { appearance in+ appearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua+ ? NSColor(calibratedRed: 0.10, green: 0.20, blue: 0.10, alpha: 1.0)+ : NSColor(calibratedRed: 0.918, green: 0.953, blue: 0.871, alpha: 1.0)+ }++ // Light: light red | Dark: dark red+ static let cellDeleted = NSColor(name: "cellDeleted") { appearance in+ appearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua+ ? NSColor(calibratedRed: 0.25, green: 0.10, blue: 0.10, alpha: 1.0)+ : NSColor(calibratedRed: 0.988, green: 0.922, blue: 0.922, alpha: 1.0)+ }++ static let cellNull = NSColor(calibratedRed: 0.533, green: 0.533, blue: 0.502, alpha: 1.0)+ }+}diff --git a/macos/Core/Models/AI/AIModels.swift b/macos/Core/Models/AI/AIModels.swiftnew file mode 100644index 0000000..75a6d41--- /dev/null+++ b/macos/Core/Models/AI/AIModels.swift@@ -0,0 +1,73 @@+// AIModels.swift+// Gridex+//+// Models for AI chat and LLM integration.++import Foundation++struct LLMMessage: Codable, Sendable {+ let role: MessageRole+ let content: String++ enum MessageRole: String, Codable, Sendable {+ case user+ case assistant+ case system+ }+}++struct LLMModel: Sendable, Identifiable {+ let id: String+ let name: String+ let provider: String+ let contextWindow: Int+ let supportsStreaming: Bool+}++struct AIContext: Sendable {+ let relevantTables: [TableDescription]+ let schemaSQL: String+ let sampleData: [String: [[RowValue]]]+ let statistics: [String: [ColumnStatistics]]+ let tokenCount: Int+}++struct ChatMessage: Codable, Sendable, Identifiable {+ let id: UUID+ let role: LLMMessage.MessageRole+ let content: String+ let timestamp: Date+ let sqlBlocks: [SQLBlock]?+ let queryResults: [InlinedQueryResult]?++ init(id: UUID = UUID(), role: LLMMessage.MessageRole, content: String, timestamp: Date = Date(), sqlBlocks: [SQLBlock]? = nil, queryResults: [InlinedQueryResult]? = nil) {+ self.id = id+ self.role = role+ self.content = content+ self.timestamp = timestamp+ self.sqlBlocks = sqlBlocks+ self.queryResults = queryResults+ }+}++struct SQLBlock: Codable, Sendable, Identifiable {+ let id: UUID+ let sql: String+ var wasExecuted: Bool+ var executionResult: InlinedQueryResult?++ init(id: UUID = UUID(), sql: String, wasExecuted: Bool = false, executionResult: InlinedQueryResult? = nil) {+ self.id = id+ self.sql = sql+ self.wasExecuted = wasExecuted+ self.executionResult = executionResult+ }+}++struct InlinedQueryResult: Codable, Sendable {+ let columnNames: [String]+ let rows: [[String]]+ let rowCount: Int+ let executionTime: TimeInterval+ let error: String?+}diff --git a/macos/Core/Models/Database/ConnectionConfig.swift b/macos/Core/Models/Database/ConnectionConfig.swiftnew file mode 100644index 0000000..ebe4536--- /dev/null+++ b/macos/Core/Models/Database/ConnectionConfig.swift@@ -0,0 +1,76 @@+// ConnectionConfig.swift+// Gridex+//+// Configuration needed to establish a database connection.++import Foundation++struct ConnectionConfig: Codable, Sendable, Hashable, Identifiable {+ let id: UUID+ var name: String+ var databaseType: DatabaseType+ var host: String?+ var port: Int?+ var database: String?+ var username: String?+ var sslEnabled: Bool+ var colorTag: ColorTag?+ var group: String?++ // SQLite-specific+ var filePath: String?++ // SSH Tunnel+ var sshConfig: SSHTunnelConfig?++ init(+ id: UUID = UUID(),+ name: String,+ databaseType: DatabaseType,+ host: String? = nil,+ port: Int? = nil,+ database: String? = nil,+ username: String? = nil,+ sslEnabled: Bool = false,+ colorTag: ColorTag? = nil,+ group: String? = nil,+ filePath: String? = nil,+ sshConfig: SSHTunnelConfig? = nil+ ) {+ self.id = id+ self.name = name+ self.databaseType = databaseType+ self.host = host+ self.port = port+ self.database = database+ self.username = username+ self.sslEnabled = sslEnabled+ self.colorTag = colorTag+ self.group = group+ self.filePath = filePath+ self.sshConfig = sshConfig+ }++ var displayHost: String {+ if databaseType == .sqlite {+ return filePath ?? "Unknown"+ }+ return "\(host ?? "localhost"):\(port ?? databaseType.defaultPort)"+ }+}++struct SSHTunnelConfig: Codable, Sendable, Hashable {+ var host: String+ var port: Int+ var username: String+ var authMethod: SSHAuthMethod+ var keyPath: String?++ init(host: String, port: Int = 22, username: String, authMethod: SSHAuthMethod = .password, keyPath: String? = nil) {+ self.host = host+ self.port = port+ self.username = username+ self.authMethod = authMethod+ self.keyPath = keyPath+ }+}diff --git a/macos/Core/Models/Database/RowValue.swift b/macos/Core/Models/Database/RowValue.swiftnew file mode 100644index 0000000..9d03dbc--- /dev/null+++ b/macos/Core/Models/Database/RowValue.swift@@ -0,0 +1,102 @@+// RowValue.swift+// Gridex+//+// Unified value type for all database cell values.+// Abstracts away database-specific types into a common representation.++import Foundation++private let _sharedDateFormatter: DateFormatter = {+ let fmt = DateFormatter()+ fmt.dateFormat = "yyyy-MM-dd HH:mm:ss"+ fmt.timeZone = TimeZone(identifier: "UTC")+ return fmt+}()++enum RowValue: Codable, Sendable, Hashable, CustomStringConvertible {+ case null+ case string(String)+ case integer(Int64)+ case double(Double)+ case boolean(Bool)+ case date(Date)+ case data(Data)+ case json(String)+ case uuid(UUID)+ case array([RowValue])++ var isNull: Bool {+ if case .null = self { return true }+ return false+ }++ var isNumeric: Bool {+ switch self {+ case .integer, .double: return true+ default: return false+ }+ }++ var stringValue: String? {+ switch self {+ case .null: return nil+ case .string(let v): return v+ case .integer(let v): return String(v)+ case .double(let v): return String(v)+ case .boolean(let v): return v ? "true" : "false"+ case .date(let v):+ return _sharedDateFormatter.string(from: v)+ case .data(let v): return v.base64EncodedString()+ case .json(let v): return v+ case .uuid(let v): return v.uuidString+ case .array(let v): return v.map(\.description).joined(separator: ", ")+ }+ }++ var intValue: Int? {+ switch self {+ case .integer(let v): return Int(v)+ case .double(let v): return Int(v)+ case .string(let v): return Int(v)+ case .boolean(let v): return v ? 1 : 0+ default: return nil+ }+ }++ var doubleValue: Double? {+ switch self {+ case .double(let v): return v+ case .integer(let v): return Double(v)+ case .string(let v): return Double(v)+ default: return nil+ }+ }++ var description: String {+ stringValue ?? "NULL"+ }++ /// Truncated version for display in grid cells. Avoids expensive+ /// full base64 encoding for blobs and caps long strings.+ var displayString: String {+ switch self {+ case .null: return "NULL"+ case .data(let v):+ if v.count > 100 {+ return "(BLOB \(v.count) bytes)"+ }+ return v.base64EncodedString()+ case .json(let v):+ if v.count > 300 { return String(v.prefix(300)) + "…" }+ return v+ case .string(let v):+ if v.count > 500 { return String(v.prefix(500)) + "…" }+ return v+ case .array(let v):+ let joined = v.prefix(20).map(\.description).joined(separator: ", ")+ if v.count > 20 { return joined + "… (\(v.count) items)" }+ return joined+ default: return description+ }+ }+}diff --git a/macos/Core/Models/Query/FilterExpression.swift b/macos/Core/Models/Query/FilterExpression.swiftnew file mode 100644index 0000000..32edb4e--- /dev/null+++ b/macos/Core/Models/Query/FilterExpression.swift@@ -0,0 +1,83 @@+// FilterExpression.swift+// Gridex+//+// Filter expressions for data grid filtering.++import Foundation++struct FilterExpression: Sendable {+ let conditions: [FilterCondition]+ let combinator: FilterCombinator++ func toSQL(dialect: SQLDialect) -> String {+ let clauses = conditions.map { $0.toSQL(dialect: dialect) }+ let separator = combinator == .and ? " AND " : " OR "+ return clauses.joined(separator: separator)+ }+}++struct FilterCondition: Sendable {+ let column: String+ let op: FilterOperator+ let value: RowValue++ func toSQL(dialect: SQLDialect) -> String {+ let quotedColumn = dialect.quoteIdentifier(column)+ let escapedValue = escapeValue(value)+ switch op {+ case .equal: return "\(quotedColumn) = \(escapedValue)"+ case .notEqual: return "\(quotedColumn) != \(escapedValue)"+ case .greaterThan: return "\(quotedColumn) > \(escapedValue)"+ case .lessThan: return "\(quotedColumn) < \(escapedValue)"+ case .greaterOrEqual: return "\(quotedColumn) >= \(escapedValue)"+ case .lessOrEqual: return "\(quotedColumn) <= \(escapedValue)"+ case .like: return "\(quotedColumn) LIKE \(escapedValue)"+ case .notLike: return "\(quotedColumn) NOT LIKE \(escapedValue)"+ case .isNull: return "\(quotedColumn) IS NULL"+ case .isNotNull: return "\(quotedColumn) IS NOT NULL"+ case .in_: return "\(quotedColumn) IN (\(escapedValue))"+ }+ }++ private func escapeValue(_ value: RowValue) -> String {+ switch value {+ case .null: return "NULL"+ case .string(let v):+ // Try to detect numeric values and pass them unquoted+ if let _ = Int(v) { return v }+ if let _ = Double(v) { return v }+ return "'\(v.replacingOccurrences(of: "'", with: "''"))'"+ case .integer(let v): return "\(v)"+ case .double(let v): return "\(v)"+ case .boolean(let v): return v ? "TRUE" : "FALSE"+ case .date(let v):+ let fmt = DateFormatter()+ fmt.dateFormat = "yyyy-MM-dd HH:mm:ss"+ fmt.timeZone = TimeZone(identifier: "UTC")+ return "'\(fmt.string(from: v))'"+ case .uuid(let v): return "'\(v.uuidString)'"+ case .json(let v): return "'\(v.replacingOccurrences(of: "'", with: "''"))'"+ case .data: return "NULL"+ case .array: return "NULL"+ }+ }+}++enum FilterOperator: String, CaseIterable, Sendable {+ case equal = "="+ case notEqual = "!="+ case greaterThan = ">"+ case lessThan = "<"+ case greaterOrEqual = ">="+ case lessOrEqual = "<="+ case like = "LIKE"+ case notLike = "NOT LIKE"+ case isNull = "IS NULL"+ case isNotNull = "IS NOT NULL"+ case in_ = "IN"+}++enum FilterCombinator: String, Sendable {+ case and = "AND"+ case or = "OR"+}diff --git a/macos/Core/Models/Query/QueryParameter.swift b/macos/Core/Models/Query/QueryParameter.swiftnew file mode 100644index 0000000..aa535f3--- /dev/null+++ b/macos/Core/Models/Query/QueryParameter.swift@@ -0,0 +1,14 @@+// QueryParameter.swift+// Gridex++import Foundation++struct QueryParameter: Sendable {+ let value: RowValue+ let type: String?++ init(_ value: RowValue, type: String? = nil) {+ self.value = value+ self.type = type+ }+}diff --git a/macos/Core/Models/Query/QueryResult.swift b/macos/Core/Models/Query/QueryResult.swiftnew file mode 100644index 0000000..855dbe7--- /dev/null+++ b/macos/Core/Models/Query/QueryResult.swift@@ -0,0 +1,40 @@+// QueryResult.swift+// Gridex+//+// Result of a database query execution.++import Foundation++struct QueryResult: Sendable {+ let columns: [ColumnHeader]+ let rows: [[RowValue]]+ let rowsAffected: Int+ let executionTime: TimeInterval+ let queryType: QueryType++ var rowCount: Int { rows.count }+ var isEmpty: Bool { rows.isEmpty }+}++struct ColumnHeader: Sendable, Hashable {+ let name: String+ let dataType: String+ let isNullable: Bool+ let tableName: String?++ init(name: String, dataType: String = "unknown", isNullable: Bool = true, tableName: String? = nil) {+ self.name = name+ self.dataType = dataType+ self.isNullable = isNullable+ self.tableName = tableName+ }+}++enum QueryType: String, Sendable {+ case select+ case insert+ case update+ case delete+ case ddl+ case other+}diff --git a/macos/Core/Models/Query/SortDescriptor.swift b/macos/Core/Models/Query/SortDescriptor.swiftnew file mode 100644index 0000000..c0776e3--- /dev/null+++ b/macos/Core/Models/Query/SortDescriptor.swift@@ -0,0 +1,22 @@+// SortDescriptor.swift+// Gridex++import Foundation++struct QuerySortDescriptor: Sendable, Hashable {+ let column: String+ let direction: SortDirection++ func toSQL(dialect: SQLDialect) -> String {+ "\(dialect.quoteIdentifier(column)) \(direction.rawValue)"+ }+}++enum SortDirection: String, Sendable {+ case ascending = "ASC"+ case descending = "DESC"++ mutating func toggle() {+ self = self == .ascending ? .descending : .ascending+ }+}diff --git a/macos/Core/Models/Schema/SchemaSnapshot.swift b/macos/Core/Models/Schema/SchemaSnapshot.swiftnew file mode 100644index 0000000..5207daa--- /dev/null+++ b/macos/Core/Models/Schema/SchemaSnapshot.swift@@ -0,0 +1,165 @@+// SchemaSnapshot.swift+// Gridex+//+// Complete snapshot of a database schema for AI context.++import Foundation++struct SchemaSnapshot: Codable, Sendable {+ let databaseName: String+ let databaseType: DatabaseType+ let schemas: [SchemaInfo]+ let capturedAt: Date++ var allTables: [TableDescription] {+ schemas.flatMap(\.tables)+ }++ var totalTableCount: Int {+ schemas.reduce(0) { $0 + $1.tables.count }+ }+}++struct SchemaInfo: Codable, Sendable {+ let name: String+ let tables: [TableDescription]+ let views: [ViewInfo]+ let functions: [FunctionInfo]+ let enums: [EnumInfo]+}++struct TableDescription: Codable, Sendable, Equatable {+ let name: String+ let schema: String?+ let columns: [ColumnInfo]+ let indexes: [IndexInfo]+ let foreignKeys: [ForeignKeyInfo]+ let constraints: [ConstraintInfo]+ let comment: String?+ let estimatedRowCount: Int?++ var primaryKeyColumns: [ColumnInfo] {+ columns.filter(\.isPrimaryKey)+ }++ func toDDL(dialect: SQLDialect) -> String {+ var ddl = "CREATE TABLE \(dialect.quoteIdentifier(name)) (\n"+ ddl += columns.map { " \($0.name) \($0.dataType)\($0.isNullable ? "" : " NOT NULL")\($0.defaultValue.map { " DEFAULT \($0)" } ?? "")" }.joined(separator: ",\n")+ ddl += "\n);"+ return ddl+ }+}++struct ColumnInfo: Codable, Sendable, Hashable, Identifiable {+ var id: String { name }+ let name: String+ let dataType: String+ let isNullable: Bool+ let defaultValue: String?+ let isPrimaryKey: Bool+ let isAutoIncrement: Bool+ let comment: String?+ let ordinalPosition: Int+ let characterMaxLength: Int?+ var checkConstraint: String?+}++struct IndexInfo: Codable, Sendable, Identifiable, Equatable {+ var id: String { name }+ let name: String+ let columns: [String]+ let isUnique: Bool+ let type: String?+ let tableName: String?+ var condition: String?+ var include: String?+ var comment: String?+}++struct ForeignKeyInfo: Codable, Sendable, Identifiable, Equatable {+ var id: String { "\(columns.joined())->\(referencedTable)" }+ let name: String?+ var columns: [String]+ let referencedTable: String+ var referencedColumns: [String]+ let onDelete: ForeignKeyAction+ let onUpdate: ForeignKeyAction++ var column: String { columns.joined(separator: ", ") }+ var referencedColumn: String { referencedColumns.joined(separator: ", ") }+}++enum ForeignKeyAction: String, Codable, Sendable {+ case cascade = "CASCADE"+ case setNull = "SET NULL"+ case setDefault = "SET DEFAULT"+ case restrict = "RESTRICT"+ case noAction = "NO ACTION"+}++struct ConstraintInfo: Codable, Sendable, Equatable {+ let name: String+ let type: ConstraintType+ let columns: [String]+ let definition: String?+}++enum ConstraintType: String, Codable, Sendable {+ case primaryKey = "PRIMARY KEY"+ case unique = "UNIQUE"+ case check = "CHECK"+ case exclusion = "EXCLUSION"+}++struct TableInfo: Codable, Sendable {+ let name: String+ let schema: String?+ let type: TableKind+ let estimatedRowCount: Int?+}++enum TableKind: String, Codable, Sendable {+ case table+ case view+ case materializedView+ case foreignTable+}++struct ViewInfo: Codable, Sendable {+ let name: String+ let schema: String?+ let definition: String?+ let isMaterialized: Bool+}++struct FunctionInfo: Codable, Sendable {+ let name: String+ let schema: String?+ let returnType: String+ let parameters: String?+ let language: String?+}++struct EnumInfo: Codable, Sendable {+ let name: String+ let schema: String?+ let values: [String]+}++struct ColumnStatistics: Codable, Sendable {+ let columnName: String+ let distinctCount: Int?+ let nullRatio: Double?+ let topValues: [String]?+ let minValue: String?+ let maxValue: String?+}++struct QueryStatisticsEntry: Codable, Sendable {+ let query: String+ let callCount: Int+ let totalTime: TimeInterval+ let meanTime: TimeInterval+ let minTime: TimeInterval+ let maxTime: TimeInterval+}diff --git a/macos/Core/Protocols/AI/AIContextProvider.swift b/macos/Core/Protocols/AI/AIContextProvider.swiftnew file mode 100644index 0000000..ebbb197--- /dev/null+++ b/macos/Core/Protocols/AI/AIContextProvider.swift@@ -0,0 +1,21 @@+// AIContextProvider.swift+// Gridex+//+// Protocol for building AI context from database schema.+// Manages token budgeting and smart context selection.++import Foundation++protocol AIContextProvider: Sendable {+ func buildContext(+ for question: String,+ schema: SchemaSnapshot,+ tokenBudget: Int+ ) async throws -> AIContext++ func buildSystemPrompt(+ databaseType: DatabaseType,+ connectionInfo: String,+ context: AIContext+ ) -> String+}diff --git a/macos/Core/Protocols/AI/LLMService.swift b/macos/Core/Protocols/AI/LLMService.swiftnew file mode 100644index 0000000..c90deff--- /dev/null+++ b/macos/Core/Protocols/AI/LLMService.swift@@ -0,0 +1,22 @@+// LLMService.swift+// Gridex+//+// Protocol for LLM provider integration.+// Supports streaming responses from Anthropic, OpenAI, and Ollama.++import Foundation++protocol LLMService: Sendable {+ var providerName: String { get }++ func stream(+ messages: [LLMMessage],+ systemPrompt: String,+ model: String,+ maxTokens: Int,+ temperature: Double+ ) -> AsyncThrowingStream<String, Error>++ func availableModels() async throws -> [LLMModel]+ func validateAPIKey() async throws -> Bool+}diff --git a/macos/Core/Protocols/Database/DatabaseAdapter.swift b/macos/Core/Protocols/Database/DatabaseAdapter.swiftnew file mode 100644index 0000000..33a5f3d--- /dev/null+++ b/macos/Core/Protocols/Database/DatabaseAdapter.swift@@ -0,0 +1,132 @@+// DatabaseAdapter.swift+// Gridex+//+// Core protocol that all database adapters must conform to.+// Each supported database (SQLite, PostgreSQL, MySQL) implements this.++import Foundation++protocol DatabaseAdapter: AnyObject, Sendable {+ var databaseType: DatabaseType { get }+ var isConnected: Bool { get }++ // Connection lifecycle+ func connect(config: ConnectionConfig, password: String?) async throws+ func disconnect() async throws+ func testConnection(config: ConnectionConfig, password: String?) async throws -> Bool++ // Query execution+ func execute(query: String, parameters: [QueryParameter]?) async throws -> QueryResult+ func executeRaw(sql: String) async throws -> QueryResult++ /// Execute a parameterized SQL statement with RowValue parameters.+ /// Uses native driver bindings where available. Placeholders are dialect-specific+ /// ($1, $2... for PostgreSQL; ? for MySQL/SQLite).+ func executeWithRowValues(sql: String, parameters: [RowValue]) async throws -> QueryResult++ // Schema inspection+ func listDatabases() async throws -> [String]+ func listSchemas(database: String?) async throws -> [String]+ func listTables(schema: String?) async throws -> [TableInfo]+ func listViews(schema: String?) async throws -> [ViewInfo]+ func describeTable(name: String, schema: String?) async throws -> TableDescription+ func listIndexes(table: String, schema: String?) async throws -> [IndexInfo]+ func listForeignKeys(table: String, schema: String?) async throws -> [ForeignKeyInfo]+ func listFunctions(schema: String?) async throws -> [String]+ func getFunctionSource(name: String, schema: String?) async throws -> String++ /// List stored procedures. Returns empty by default — only MSSQL implements+ /// native stored procedures; PostgreSQL/MySQL blur the line with listFunctions.+ func listProcedures(schema: String?) async throws -> [String]+ /// Get stored procedure source. Returns empty by default.+ func getProcedureSource(name: String, schema: String?) async throws -> String+ /// Get stored procedure parameter signature (name, type, mode).+ /// Returns empty by default. Each item is a formatted string like "@id INT INPUT".+ func listProcedureParameters(name: String, schema: String?) async throws -> [String]++ // Data manipulation+ func insertRow(table: String, schema: String?, values: [String: RowValue]) async throws -> QueryResult+ func updateRow(table: String, schema: String?, set: [String: RowValue], where: [String: RowValue]) async throws -> QueryResult+ func deleteRow(table: String, schema: String?, where: [String: RowValue]) async throws -> QueryResult++ // Transaction support+ func beginTransaction() async throws+ func commitTransaction() async throws+ func rollbackTransaction() async throws++ // Pagination+ func fetchRows(+ table: String,+ schema: String?,+ columns: [String]?,+ where: FilterExpression?,+ orderBy: [QuerySortDescriptor]?,+ limit: Int,+ offset: Int+ ) async throws -> QueryResult++ // Database management+ func createDatabase(name: String) async throws+ func dropDatabase(name: String) async throws++ // Database-specific+ func serverVersion() async throws -> String+ func currentDatabase() async throws -> String?+}++extension DatabaseAdapter {+ func createDatabase(name: String) async throws {+ let quoted = databaseType.sqlDialect.quoteIdentifier(name)+ _ = try await executeRaw(sql: "CREATE DATABASE \(quoted)")+ }++ func dropDatabase(name: String) async throws {+ let quoted = databaseType.sqlDialect.quoteIdentifier(name)+ _ = try await executeRaw(sql: "DROP DATABASE \(quoted)")+ }++ // Default: no native stored procedures. Override in MSSQL (and later PG if needed).+ func listProcedures(schema: String?) async throws -> [String] { [] }+ func getProcedureSource(name: String, schema: String?) async throws -> String { "" }+ func listProcedureParameters(name: String, schema: String?) async throws -> [String] { [] }++ /// Default implementation: inlines parameters into the SQL string.+ /// Adapters should override this with native parameter binding.+ func executeWithRowValues(sql: String, parameters: [RowValue]) async throws -> QueryResult {+ var result = sql+ // Replace placeholders with inline values, handling both $N and ? styles+ if sql.contains("$1") {+ // PostgreSQL-style: replace $N in reverse order to avoid $1 matching in $10+ for i in stride(from: parameters.count, through: 1, by: -1) {+ result = result.replacingOccurrences(of: "$\(i)", with: inlineRowValue(parameters[i - 1]))+ }+ } else {+ // MySQL/SQLite-style: replace ? one by one+ for param in parameters {+ if let range = result.range(of: "?") {+ result = result.replacingCharacters(in: range, with: inlineRowValue(param))+ }+ }+ }+ return try await executeRaw(sql: result)+ }++ private func inlineRowValue(_ value: RowValue) -> String {+ switch value {+ case .null: return "NULL"+ case .string(let v): return "'\(v.replacingOccurrences(of: "'", with: "''"))'"+ case .integer(let v): return "\(v)"+ case .double(let v): return "\(v)"+ case .boolean(let v): return v ? "1" : "0"+ case .date(let v):+ let fmt = DateFormatter()+ fmt.dateFormat = "yyyy-MM-dd HH:mm:ss"+ fmt.timeZone = TimeZone(identifier: "UTC")+ return "'\(fmt.string(from: v))'"+ case .uuid(let v): return "'\(v.uuidString)'"+ case .json(let v): return "'\(v.replacingOccurrences(of: "'", with: "''"))'"+ case .data: return "NULL"+ case .array: return "NULL"+ }+ }+}diff --git a/macos/Core/Protocols/Database/SchemaInspectable.swift b/macos/Core/Protocols/Database/SchemaInspectable.swiftnew file mode 100644index 0000000..4a6e9a4--- /dev/null+++ b/macos/Core/Protocols/Database/SchemaInspectable.swift@@ -0,0 +1,16 @@+// SchemaInspectable.swift+// Gridex+//+// Protocol for inspecting database schema in detail.+// Used by AI Context Engine to build schema snapshots.++import Foundation++protocol SchemaInspectable: Sendable {+ func fullSchemaSnapshot(database: String?) async throws -> SchemaSnapshot+ func columnStatistics(table: String, schema: String?, sampleSize: Int) async throws -> [ColumnStatistics]+ func tableRowCount(table: String, schema: String?) async throws -> Int+ func tableSizeBytes(table: String, schema: String?) async throws -> Int64?+ func queryStatistics() async throws -> [QueryStatisticsEntry]+ func primaryKeyColumns(table: String, schema: String?) async throws -> [String]+}diff --git a/macos/Core/Types/TypeAliases.swift b/macos/Core/Types/TypeAliases.swiftnew file mode 100644index 0000000..1e6d840--- /dev/null+++ b/macos/Core/Types/TypeAliases.swift@@ -0,0 +1,12 @@+// TypeAliases.swift+// Gridex+//+// Common type aliases used across the project.++import Foundation++typealias Row = [RowValue]+typealias RowDictionary = [String: RowValue]+typealias ConnectionID = UUID+typealias TableName = String+typealias SchemaName = Stringdiff --git a/macos/Data/Adapters/MSSQL/MSSQLAdapter.swift b/macos/Data/Adapters/MSSQL/MSSQLAdapter.swiftnew file mode 100644index 0000000..4f78b2c--- /dev/null+++ b/macos/Data/Adapters/MSSQL/MSSQLAdapter.swift@@ -0,0 +1,693 @@+// MSSQLAdapter.swift+// Gridex+//+// Microsoft SQL Server adapter using CosmoMSSQL (TDS 7.4, pure Swift NIO).+// Compatible with SQL Server 2014+ and Azure SQL Edge / Azure SQL Database.++import Foundation+import CosmoMSSQL+import CosmoSQLCore+import NIOCore++final class MSSQLAdapter: DatabaseAdapter, @unchecked Sendable {++ // MARK: - Properties++ let databaseType: DatabaseType = .mssql+ private(set) var isConnected: Bool = false++ private var pool: MSSQLConnectionPool?+ private var connectionConfig: ConnectionConfig?+ /// Tracks the database name when USE statements switch context. Required because+ /// each pooled connection initially uses the configured database, so explicit+ /// USE on each acquired connection is necessary.+ private var currentDB: String?+ /// Single connection used for transactions (to ensure all commands run on the same conn)+ private var txConnection: MSSQLConnection?++ // MARK: - Connection Lifecycle++ func connect(config: ConnectionConfig, password: String?) async throws {+ let host = config.host ?? "localhost"+ let port = config.port ?? 1433+ let database = config.database ?? "master"+ let username = config.username ?? "sa"++ // SQL Server SSL handling:+ // - sslEnabled=false → .disable (no TLS attempt)+ // - sslEnabled=true → .prefer (try TLS, fall back to plaintext if server rejects)+ // We avoid .require because dev/Docker SQL Server often has no valid cert.+ let tlsMode: SQLTLSConfiguration = config.sslEnabled ? .prefer : .disable++ var mssqlConfig = MSSQLConnection.Configuration(+ host: host,+ port: port,+ database: database,+ username: username,+ password: password ?? "",+ tls: tlsMode,+ trustServerCertificate: true, // Skip cert verification (common for dev/Docker)+ connectTimeout: 15+ )+ mssqlConfig.queryTimeout = 60++ let newPool = MSSQLConnectionPool(configuration: mssqlConfig, maxConnections: 5)++ do {+ // Verify connection works by acquiring + releasing a connection+ try await newPool.withConnection { conn in+ _ = try await conn.query("SELECT 1", [])+ }+ self.pool = newPool+ self.connectionConfig = config+ self.currentDB = database+ self.isConnected = true+ } catch {+ try? await newPool.close()+ let nsErr = NSError(+ domain: "MSSQL",+ code: -1,+ userInfo: [NSLocalizedDescriptionKey: "MSSQL connect failed: \(error)"]+ )+ throw GridexError.connectionFailed(underlying: nsErr)+ }+ }++ func disconnect() async throws {+ if let txConn = txConnection {+ try? await txConn.close()+ txConnection = nil+ }+ if let pool = pool {+ try? await pool.close()+ }+ pool = nil+ connectionConfig = nil+ currentDB = nil+ isConnected = false+ }++ func testConnection(config: ConnectionConfig, password: String?) async throws -> Bool {+ let adapter = MSSQLAdapter()+ do {+ try await adapter.connect(config: config, password: password)+ _ = try await adapter.serverVersion()+ try await adapter.disconnect()+ return true+ } catch {+ try? await adapter.disconnect()+ throw error+ }+ }++ // MARK: - Helpers++ private func requirePool() throws -> MSSQLConnectionPool {+ guard let pool = pool else {+ throw GridexError.connectionFailed(underlying: NSError(+ domain: "MSSQL", code: -1,+ userInfo: [NSLocalizedDescriptionKey: "Not connected to SQL Server"]))+ }+ return pool+ }++ /// A dedicated connection for script execution — lets multi-batch scripts+ /// (CREATE DATABASE + USE + CREATE TABLE ...) share session state.+ private var scriptConnection: MSSQLConnection?++ /// Begin a multi-batch script session. All subsequent executeRaw calls will+ /// reuse the same connection until `endScript()` is called, so USE statements+ /// persist across batches. Not reentrant.+ func beginScript() async throws {+ let pool = try requirePool()+ let conn = try await pool.acquire()+ if let dbName = currentDB {+ let safeName = dbName.replacingOccurrences(of: "]", with: "]]")+ _ = try? await conn.execute("USE [\(safeName)]", [])+ }+ scriptConnection = conn+ }++ /// End a script session, releasing the dedicated connection back to the pool.+ func endScript() async {+ guard let conn = scriptConnection, let pool = pool else {+ scriptConnection = nil+ return+ }+ await pool.release(conn)+ scriptConnection = nil+ }++ /// Run a closure with a pooled connection. Priority order:+ /// 1. Transaction connection (if in transaction)+ /// 2. Script connection (if inside a script session)+ /// 3. Fresh pooled connection with auto-USE to currentDB+ ///+ /// Pass `skipUSE: true` for statements that manage databases themselves+ /// (CREATE DATABASE, DROP DATABASE, USE) to avoid interfering with them.+ private func withConnection<T: Sendable>(skipUSE: Bool = false, _ work: @Sendable (MSSQLConnection) async throws -> T) async throws -> T {+ if let txConn = txConnection {+ return try await work(txConn)+ }+ if let scriptConn = scriptConnection {+ // Script session: reuse same connection so USE persists across batches+ return try await work(scriptConn)+ }+ let pool = try requirePool()+ return try await pool.withConnection { conn in+ // Switch to current database (USE) since pooled connections may be on a different DB+ if !skipUSE, let dbName = self.currentDB {+ let safeName = dbName.replacingOccurrences(of: "]", with: "]]")+ _ = try? await conn.execute("USE [\(safeName)]", [])+ }+ return try await work(conn)+ }+ }++ /// Convert a SQLValue (CosmoSQL) into a Gridex RowValue.+ private func sqlValueToRowValue(_ value: SQLValue) -> RowValue {+ switch value {+ case .null: return .null+ case .bool(let b): return .boolean(b)+ case .int(let i): return .integer(Int64(i))+ case .int8(let i): return .integer(Int64(i))+ case .int16(let i): return .integer(Int64(i))+ case .int32(let i): return .integer(Int64(i))+ case .int64(let i): return .integer(i)+ case .float(let f): return .double(Double(f))+ case .double(let d): return .double(d)+ case .decimal(let d): return .string("\(d)")+ case .string(let s): return .string(s)+ case .bytes(let bytes): return .data(Data(bytes))+ case .uuid(let u): return .uuid(u)+ case .date(let d): return .date(d)+ }+ }++ /// Convert a Gridex RowValue into a CosmoSQL SQLValue.+ private func rowValueToSQLValue(_ value: RowValue) -> SQLValue {+ switch value {+ case .null: return .null+ case .string(let s): return .string(s)+ case .integer(let i): return .int64(i)+ case .double(let d): return .double(d)+ case .boolean(let b): return .bool(b)+ case .date(let d): return .date(d)+ case .data(let d): return .bytes([UInt8](d))+ case .json(let s): return .string(s)+ case .uuid(let u): return .uuid(u)+ case .array(let arr): return .string(arr.map(\.description).joined(separator: ", "))+ }+ }++ // MARK: - Query Execution++ func execute(query: String, parameters: [QueryParameter]?) async throws -> QueryResult {+ try await executeRaw(sql: query)+ }++ func executeRaw(sql: String) async throws -> QueryResult {+ let start = CFAbsoluteTimeGetCurrent()+ let upper = sql.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()+ let qType = detectQueryType(upper)+ // SQL Server doesn't support PostgreSQL-style SHOW. Reject these queries early+ // to avoid sending PostgreSQL-specific commands (e.g. "SHOW ssl") to MSSQL.+ if upper.hasPrefix("SHOW ") {+ throw GridexError.queryExecutionFailed("SHOW statements are not supported in SQL Server")+ }+ let isSelect = qType == .select || upper.hasPrefix("EXPLAIN") || upper.hasPrefix("WITH")++ // Statements that manage database context themselves — don't inject USE before them+ let isDBContextStmt = upper.hasPrefix("USE ")+ || upper.hasPrefix("CREATE DATABASE")+ || upper.hasPrefix("DROP DATABASE")+ || upper.hasPrefix("ALTER DATABASE")++ // Detect USE [dbname] / USE dbname statement to track current DB across pooled connections+ if upper.hasPrefix("USE ") {+ let after = String(sql.dropFirst(4)).trimmingCharacters(in: .whitespacesAndNewlines)+ let dbName = after.trimmingCharacters(in: CharacterSet(charactersIn: "[]\"`'; "))+ if !dbName.isEmpty {+ self.currentDB = dbName+ }+ }++ return try await withConnection(skipUSE: isDBContextStmt) { conn in+ do {+ if isSelect {+ // Use queryMulti to get SQLResultSet with columns even when result has 0 rows+ let sets = try await conn.queryMulti(sql, [])+ let elapsed = CFAbsoluteTimeGetCurrent() - start+ guard let first = sets.first else {+ return QueryResult(columns: [], rows: [], rowsAffected: 0, executionTime: elapsed, queryType: .select)+ }+ let columns = first.columns.map { col in+ ColumnHeader(+ name: col.name,+ dataType: col.dataTypeID.map(String.init) ?? "unknown",+ isNullable: true,+ tableName: col.table+ )+ }+ let resultRows: [[RowValue]] = first.rows.map { row in+ row.values.map { self.sqlValueToRowValue($0) }+ }+ return QueryResult(columns: columns, rows: resultRows, rowsAffected: 0, executionTime: elapsed, queryType: .select)+ } else {+ let affected = try await conn.execute(sql, [])+ let elapsed = CFAbsoluteTimeGetCurrent() - start+ return QueryResult(columns: [], rows: [], rowsAffected: affected, executionTime: elapsed, queryType: qType)+ }+ } catch {+ print("[MSSQL] Query failed: \(sql.prefix(200)) — \(error)")+ // Rewrap SQLError to preserve rich description (enum errors lose detail+ // through default NSError bridging, appearing as "error 0")+ throw GridexError.queryExecutionFailed(String(describing: error))+ }+ }+ }++ func executeWithRowValues(sql: String, parameters: [RowValue]) async throws -> QueryResult {+ // CosmoMSSQL's RPC (sp_executesql) path hardcodes the transaction descriptor to 0,+ // so parameterized queries inside explicit transactions fail with error 3989+ // ("New request is not allowed to start because it should come with valid+ // transaction descriptor"). Work around by inlining @pN placeholders into SQL+ // and routing through executeRaw (SQL_BATCH, which correctly carries the descriptor).+ let inlined = inlinePlaceholders(sql: sql, parameters: parameters)+ return try await executeRaw(sql: inlined)+ }++ /// Replace @p1, @p2, ... placeholders with literal values (with proper escaping).+ /// Processed in reverse order so @p1 doesn't match inside @p10, @p11, etc.+ private func inlinePlaceholders(sql: String, parameters: [RowValue]) -> String {+ var result = sql+ for i in stride(from: parameters.count, through: 1, by: -1) {+ let placeholder = "@p\(i)"+ let literal = mssqlLiteral(parameters[i - 1])+ result = result.replacingOccurrences(of: placeholder, with: literal)+ }+ return result+ }++ private func mssqlLiteral(_ value: RowValue) -> String {+ switch value {+ case .null: return "NULL"+ case .string(let s): return "N'\(s.replacingOccurrences(of: "'", with: "''"))'"+ case .integer(let i): return "\(i)"+ case .double(let d): return "\(d)"+ case .boolean(let b): return b ? "1" : "0"+ case .date(let d):+ let fmt = DateFormatter()+ fmt.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"+ fmt.timeZone = TimeZone(identifier: "UTC")+ return "'\(fmt.string(from: d))'"+ case .uuid(let u): return "'\(u.uuidString)'"+ case .json(let s): return "N'\(s.replacingOccurrences(of: "'", with: "''"))'"+ case .data(let d):+ let hex = d.map { String(format: "%02X", $0) }.joined()+ return "0x\(hex)"+ case .array: return "NULL"+ }+ }++ private func detectQueryType(_ upper: String) -> QueryType {+ if upper.hasPrefix("SELECT") { return .select }+ if upper.hasPrefix("INSERT") { return .insert }+ if upper.hasPrefix("UPDATE") { return .update }+ if upper.hasPrefix("DELETE") { return .delete }+ if upper.hasPrefix("CREATE") || upper.hasPrefix("ALTER") || upper.hasPrefix("DROP") || upper.hasPrefix("TRUNCATE") { return .ddl }+ return .other+ }++ // MARK: - Schema Inspection++ func listDatabases() async throws -> [String] {+ let result = try await executeRaw(sql: """+ SELECT name FROM sys.databases+ WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb')+ ORDER BY name+ """)+ return result.rows.compactMap { $0.first?.stringValue }+ }++ func listSchemas(database: String?) async throws -> [String] {+ let result = try await executeRaw(sql: """+ SELECT SCHEMA_NAME+ FROM INFORMATION_SCHEMA.SCHEMATA+ WHERE SCHEMA_NAME NOT IN ('sys', 'INFORMATION_SCHEMA', 'guest', 'db_owner', 'db_accessadmin',+ 'db_securityadmin', 'db_ddladmin', 'db_backupoperator', 'db_datareader',+ 'db_datawriter', 'db_denydatareader', 'db_denydatawriter')+ ORDER BY SCHEMA_NAME+ """)+ return result.rows.compactMap { $0.first?.stringValue }+ }++ func listTables(schema: String?) async throws -> [TableInfo] {+ let schemaName = schema ?? "dbo"+ // Use INFORMATION_SCHEMA.TABLES for portability across SQL Server / Azure SQL Edge+ let result = try await executeRaw(sql: """+ SELECT TABLE_NAME+ FROM INFORMATION_SCHEMA.TABLES+ WHERE TABLE_SCHEMA = '\(schemaName)' AND TABLE_TYPE = 'BASE TABLE'+ ORDER BY TABLE_NAME+ """)+ return result.rows.compactMap { row -> TableInfo? in+ guard let name = row.first?.stringValue else { return nil }+ return TableInfo(name: name, schema: schemaName, type: .table, estimatedRowCount: nil)+ }+ }++ func listViews(schema: String?) async throws -> [ViewInfo] {+ let schemaName = schema ?? "dbo"+ let result = try await executeRaw(sql: """+ SELECT TABLE_NAME+ FROM INFORMATION_SCHEMA.VIEWS+ WHERE TABLE_SCHEMA = '\(schemaName)'+ ORDER BY TABLE_NAME+ """)+ return result.rows.compactMap { row -> ViewInfo? in+ guard let name = row.first?.stringValue else { return nil }+ return ViewInfo(name: name, schema: schemaName, definition: nil, isMaterialized: false)+ }+ }++ func describeTable(name: String, schema: String?) async throws -> TableDescription {+ let schemaName = schema ?? "dbo"++ // Get primary key columns first via INFORMATION_SCHEMA+ let pkResult = try? await executeRaw(sql: """+ SELECT kcu.COLUMN_NAME+ FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc+ INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu+ ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME AND tc.TABLE_SCHEMA = kcu.TABLE_SCHEMA+ WHERE tc.CONSTRAINT_TYPE = 'PRIMARY KEY'+ AND tc.TABLE_SCHEMA = '\(schemaName)'+ AND tc.TABLE_NAME = '\(name)'+ """)+ let pkColumns: Set<String> = Set((pkResult?.rows ?? []).compactMap { $0.first?.stringValue })++ // Columns via INFORMATION_SCHEMA+ let colResult = try await executeRaw(sql: """+ SELECT+ COLUMN_NAME,+ DATA_TYPE,+ IS_NULLABLE,+ COLUMN_DEFAULT,+ ORDINAL_POSITION,+ CHARACTER_MAXIMUM_LENGTH,+ COLUMNPROPERTY(OBJECT_ID('\(schemaName).\(name)'), COLUMN_NAME, 'IsIdentity') AS is_identity+ FROM INFORMATION_SCHEMA.COLUMNS+ WHERE TABLE_SCHEMA = '\(schemaName)' AND TABLE_NAME = '\(name)'+ ORDER BY ORDINAL_POSITION+ """)++ let columns: [ColumnInfo] = colResult.rows.enumerated().compactMap { (idx, row) in+ guard let colName = row[0].stringValue,+ let dataType = row[1].stringValue else { return nil }+ return ColumnInfo(+ name: colName,+ dataType: dataType,+ isNullable: (row[2].stringValue ?? "YES") == "YES",+ defaultValue: row[3].stringValue,+ isPrimaryKey: pkColumns.contains(colName),+ isAutoIncrement: row[6].intValue == 1,+ comment: nil,+ ordinalPosition: idx + 1,+ characterMaxLength: row[5].intValue+ )+ }++ // Indexes — empty for now (requires sys.* views; add later if needed)+ let indexes: [IndexInfo] = []++ // Foreign keys via INFORMATION_SCHEMA+ let fkResult = try? await executeRaw(sql: """+ SELECT+ rc.CONSTRAINT_NAME,+ kcu.COLUMN_NAME,+ rkcu.TABLE_NAME AS REF_TABLE,+ rkcu.COLUMN_NAME AS REF_COLUMN+ FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc+ INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu+ ON rc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME+ INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE rkcu+ ON rc.UNIQUE_CONSTRAINT_NAME = rkcu.CONSTRAINT_NAME+ AND kcu.ORDINAL_POSITION = rkcu.ORDINAL_POSITION+ WHERE kcu.TABLE_SCHEMA = '\(schemaName)' AND kcu.TABLE_NAME = '\(name)'+ """)++ let foreignKeys: [ForeignKeyInfo] = (fkResult?.rows ?? []).compactMap { row in+ guard let fkName = row[0].stringValue,+ let column = row[1].stringValue,+ let refTable = row[2].stringValue,+ let refCol = row[3].stringValue else { return nil }+ return ForeignKeyInfo(+ name: fkName,+ columns: [column],+ referencedTable: refTable,+ referencedColumns: [refCol],+ onDelete: .noAction,+ onUpdate: .noAction+ )+ }++ // Row count: skip for now (would require COUNT(*) which is slow)+ let rowCount: Int? = nil++ return TableDescription(+ name: name,+ schema: schemaName,+ columns: columns,+ indexes: indexes,+ foreignKeys: foreignKeys,+ constraints: [],+ comment: nil,+ estimatedRowCount: rowCount+ )+ }++ func listIndexes(table: String, schema: String?) async throws -> [IndexInfo] {+ try await describeTable(name: table, schema: schema).indexes+ }++ func listForeignKeys(table: String, schema: String?) async throws -> [ForeignKeyInfo] {+ try await describeTable(name: table, schema: schema).foreignKeys+ }++ func listFunctions(schema: String?) async throws -> [String] {+ let schemaName = schema ?? "dbo"+ let result = try await executeRaw(sql: """+ SELECT ROUTINE_NAME+ FROM INFORMATION_SCHEMA.ROUTINES+ WHERE ROUTINE_SCHEMA = '\(schemaName)' AND ROUTINE_TYPE = 'FUNCTION'+ ORDER BY ROUTINE_NAME+ """)+ return result.rows.compactMap { $0.first?.stringValue }+ }++ func getFunctionSource(name: String, schema: String?) async throws -> String {+ let schemaName = schema ?? "dbo"+ let result = try await executeRaw(sql: """+ SELECT ROUTINE_DEFINITION+ FROM INFORMATION_SCHEMA.ROUTINES+ WHERE ROUTINE_SCHEMA = '\(schemaName)' AND ROUTINE_NAME = '\(name)'+ """)+ return result.rows.first?.first?.stringValue ?? ""+ }++ func listProcedures(schema: String?) async throws -> [String] {+ let schemaName = schema ?? "dbo"+ let result = try await executeRaw(sql: """+ SELECT ROUTINE_NAME+ FROM INFORMATION_SCHEMA.ROUTINES+ WHERE ROUTINE_SCHEMA = '\(schemaName)' AND ROUTINE_TYPE = 'PROCEDURE'+ ORDER BY ROUTINE_NAME+ """)+ return result.rows.compactMap { $0.first?.stringValue }+ }++ func getProcedureSource(name: String, schema: String?) async throws -> String {+ // Same as getFunctionSource since INFORMATION_SCHEMA.ROUTINES stores both.+ try await getFunctionSource(name: name, schema: schema)+ }++ func listProcedureParameters(name: String, schema: String?) async throws -> [String] {+ let schemaName = schema ?? "dbo"+ let result = try await executeRaw(sql: """+ SELECT+ PARAMETER_NAME,+ DATA_TYPE,+ CHARACTER_MAXIMUM_LENGTH,+ NUMERIC_PRECISION,+ NUMERIC_SCALE,+ PARAMETER_MODE+ FROM INFORMATION_SCHEMA.PARAMETERS+ WHERE SPECIFIC_SCHEMA = '\(schemaName)' AND SPECIFIC_NAME = '\(name)'+ ORDER BY ORDINAL_POSITION+ """)+ return result.rows.compactMap { row -> String? in+ guard let paramName = row[0].stringValue, !paramName.isEmpty else { return nil }+ let dataType = row[1].stringValue ?? "UNKNOWN"+ let mode = (row[5].stringValue ?? "IN").uppercased()+ // Build typed signature: VARCHAR(255), DECIMAL(18,2), etc.+ var typeStr = dataType.uppercased()+ if let maxLen = row[2].intValue, maxLen > 0 {+ typeStr += "(\(maxLen))"+ } else if let precision = row[3].intValue, precision > 0 {+ if let scale = row[4].intValue, scale > 0 {+ typeStr += "(\(precision),\(scale))"+ } else {+ typeStr += "(\(precision))"+ }+ }+ // Mode: IN (default) / INOUT / OUT+ let modeLabel: String+ switch mode {+ case "INOUT", "IN OUT": modeLabel = " INOUT"+ case "OUT": modeLabel = " OUTPUT"+ default: modeLabel = "" // IN is implicit+ }+ return "\(paramName) \(typeStr)\(modeLabel)"+ }+ }++ // MARK: - Data Manipulation++ func insertRow(table: String, schema: String?, values: [String: RowValue]) async throws -> QueryResult {+ let d = SQLDialect.mssql+ let schemaPrefix = schema.map { d.quoteIdentifier($0) + "." } ?? ""+ let qualified = "\(schemaPrefix)\(d.quoteIdentifier(table))"+ let cols = values.keys.sorted()+ let colList = cols.map { d.quoteIdentifier($0) }.joined(separator: ", ")+ let placeholders = (1...cols.count).map { "@p\($0)" }.joined(separator: ", ")+ let sql = "INSERT INTO \(qualified) (\(colList)) VALUES (\(placeholders))"+ let params = cols.map { values[$0] ?? .null }+ return try await executeWithRowValues(sql: sql, parameters: params)+ }++ func updateRow(table: String, schema: String?, set: [String: RowValue], where whereClause: [String: RowValue]) async throws -> QueryResult {+ let d = SQLDialect.mssql+ let schemaPrefix = schema.map { d.quoteIdentifier($0) + "." } ?? ""+ let qualified = "\(schemaPrefix)\(d.quoteIdentifier(table))"++ let setKeys = set.keys.sorted()+ let whereKeys = whereClause.keys.sorted()+ var idx = 1+ let setClauses = setKeys.map { col -> String in+ defer { idx += 1 }+ return "\(d.quoteIdentifier(col)) = @p\(idx)"+ }.joined(separator: ", ")+ let whereClauses = whereKeys.map { col -> String in+ defer { idx += 1 }+ return "\(d.quoteIdentifier(col)) = @p\(idx)"+ }.joined(separator: " AND ")++ let sql = "UPDATE \(qualified) SET \(setClauses) WHERE \(whereClauses)"+ let params = setKeys.map { set[$0] ?? .null } + whereKeys.map { whereClause[$0] ?? .null }+ return try await executeWithRowValues(sql: sql, parameters: params)+ }++ func deleteRow(table: String, schema: String?, where whereClause: [String: RowValue]) async throws -> QueryResult {+ let d = SQLDialect.mssql+ let schemaPrefix = schema.map { d.quoteIdentifier($0) + "." } ?? ""+ let qualified = "\(schemaPrefix)\(d.quoteIdentifier(table))"+ let whereKeys = whereClause.keys.sorted()+ let clauses = whereKeys.enumerated().map { (i, col) in+ "\(d.quoteIdentifier(col)) = @p\(i + 1)"+ }.joined(separator: " AND ")+ let sql = "DELETE FROM \(qualified) WHERE \(clauses)"+ let params = whereKeys.map { whereClause[$0] ?? .null }+ return try await executeWithRowValues(sql: sql, parameters: params)+ }++ // MARK: - Transactions++ func beginTransaction() async throws {+ // Acquire a dedicated connection for the transaction so all subsequent+ // executeRaw / executeWithRowValues calls run on the same session.+ let pool = try requirePool()+ let conn = try await pool.acquire()+ if let dbName = currentDB {+ let safeName = dbName.replacingOccurrences(of: "]", with: "]]")+ _ = try? await conn.execute("USE [\(safeName)]", [])+ }+ try await conn.beginTransaction()+ txConnection = conn+ }++ func commitTransaction() async throws {+ guard let conn = txConnection else { return }+ try await conn.commitTransaction()+ if let pool = pool {+ await pool.release(conn)+ }+ txConnection = nil+ }++ func rollbackTransaction() async throws {+ guard let conn = txConnection else { return }+ try await conn.rollbackTransaction()+ if let pool = pool {+ await pool.release(conn)+ }+ txConnection = nil+ }++ // MARK: - Pagination++ func fetchRows(+ table: String,+ schema: String?,+ columns: [String]?,+ where filter: FilterExpression?,+ orderBy: [QuerySortDescriptor]?,+ limit: Int,+ offset: Int+ ) async throws -> QueryResult {+ let d = SQLDialect.mssql+ let schemaPrefix = schema.map { d.quoteIdentifier($0) + "." } ?? d.quoteIdentifier("dbo") + "."+ let qualified = "\(schemaPrefix)\(d.quoteIdentifier(table))"+ let colList = columns?.map { d.quoteIdentifier($0) }.joined(separator: ", ") ?? "*"++ var sql = "SELECT \(colList) FROM \(qualified)"+ if let filter, !filter.conditions.isEmpty {+ sql += " WHERE \(filter.toSQL(dialect: d))"+ }+ // SQL Server requires ORDER BY for OFFSET/FETCH+ if let orderBy, !orderBy.isEmpty {+ sql += " ORDER BY " + orderBy.map { $0.toSQL(dialect: d) }.joined(separator: ", ")+ } else {+ sql += " ORDER BY (SELECT NULL)"+ }+ sql += " OFFSET \(offset) ROWS FETCH NEXT \(limit) ROWS ONLY"+ return try await executeRaw(sql: sql)+ }++ // MARK: - Database Management++ func createDatabase(name: String) async throws {+ let d = SQLDialect.mssql+ _ = try await executeRaw(sql: "CREATE DATABASE \(d.quoteIdentifier(name))")+ }++ func dropDatabase(name: String) async throws {+ let d = SQLDialect.mssql+ // Force-disconnect users by setting SINGLE_USER first+ _ = try? await executeRaw(sql: "ALTER DATABASE \(d.quoteIdentifier(name)) SET SINGLE_USER WITH ROLLBACK IMMEDIATE")+ _ = try await executeRaw(sql: "DROP DATABASE \(d.quoteIdentifier(name))")+ }++ // MARK: - Database Info++ func serverVersion() async throws -> String {+ // Use SERVERPROPERTY which is safer and works on all SQL Server variants+ // (including Azure SQL Edge / Azure SQL Database).+ let r = try await executeRaw(sql: "SELECT CAST(SERVERPROPERTY('ProductVersion') AS NVARCHAR(128))")+ return r.rows.first?.first?.stringValue ?? "SQL Server"+ }++ func currentDatabase() async throws -> String? {+ let r = try await executeRaw(sql: "SELECT DB_NAME()")+ return r.rows.first?.first?.stringValue+ }+}diff --git a/macos/Data/Adapters/MongoDB/MongoDBAdapter.swift b/macos/Data/Adapters/MongoDB/MongoDBAdapter.swiftnew file mode 100644index 0000000..94a2572--- /dev/null+++ b/macos/Data/Adapters/MongoDB/MongoDBAdapter.swift@@ -0,0 +1,859 @@+// MongoDBAdapter.swift+// Gridex+//+// MongoDB adapter — maps document collections into Gridex's relational model.+//+// Mapping:+// • Each MongoDB collection appears as a "table" in the sidebar+// • Documents are flattened: each top-level field becomes a column+// • Nested objects/arrays are rendered as JSON strings+// • executeRaw accepts a JSON command body that gets sent via runCommand()++import Foundation+import MongoKitten+import NIOCore++final class MongoDBAdapter: DatabaseAdapter, @unchecked Sendable {++ // MARK: - Properties++ let databaseType: DatabaseType = .mongodb+ private(set) var isConnected: Bool = false++ private var database: MongoDatabase?+ private var connectionConfig: ConnectionConfig?++ // MARK: - Connection Lifecycle++ func connect(config: ConnectionConfig, password: String?) async throws {+ let uri = buildURI(config: config, password: password)++ do {+ self.database = try await MongoDatabase.connect(to: uri)+ self.connectionConfig = config+ self.isConnected = true+ } catch {+ throw GridexError.connectionFailed(underlying: error)+ }+ }++ /// Build a MongoDB URI from a ConnectionConfig.+ /// If the host field already contains a full mongodb:// or mongodb+srv:// URI,+ /// it is used as-is, but the database segment is overridden when config.database is set.+ private func buildURI(config: ConnectionConfig, password: String?) -> String {+ let hostField = config.host ?? "localhost"++ // If user pasted a raw URI in host field, use it (with database override if set)+ if hostField.hasPrefix("mongodb://") || hostField.hasPrefix("mongodb+srv://") {+ return overrideDatabase(in: hostField, with: config.database)+ }++ let port = config.port ?? 27017+ let dbName = config.database ?? "admin"++ var uri = "mongodb://"+ if let user = config.username, !user.isEmpty {+ uri += user.addingPercentEncoding(withAllowedCharacters: .urlUserAllowed) ?? user+ if let pw = password, !pw.isEmpty {+ uri += ":" + (pw.addingPercentEncoding(withAllowedCharacters: .urlPasswordAllowed) ?? pw)+ }+ uri += "@"+ }+ uri += "\(hostField):\(port)/\(dbName)"+ if config.sslEnabled {+ uri += "?tls=true"+ }+ return uri+ }++ /// Replace the /database segment of a mongodb URI with a new database name.+ /// Preserves user:pass@host[:port] and any ?query string after the database.+ private func overrideDatabase(in uri: String, with newDB: String?) -> String {+ guard let newDB = newDB, !newDB.isEmpty else { return uri }++ let prefix: String+ let rest: String+ if uri.hasPrefix("mongodb+srv://") {+ prefix = "mongodb+srv://"+ rest = String(uri.dropFirst(prefix.count))+ } else if uri.hasPrefix("mongodb://") {+ prefix = "mongodb://"+ rest = String(uri.dropFirst(prefix.count))+ } else {+ return uri+ }++ // Split off query string+ var pathPart = rest+ var query = ""+ if let qIdx = rest.firstIndex(of: "?") {+ pathPart = String(rest[..<qIdx])+ query = String(rest[qIdx...])+ }++ // Find the / that separates host from database (skip past credentials @)+ let searchStart: String.Index+ if let atIdx = pathPart.lastIndex(of: "@") {+ searchStart = pathPart.index(after: atIdx)+ } else {+ searchStart = pathPart.startIndex+ }++ if let slashIdx = pathPart[searchStart...].firstIndex(of: "/") {+ // Replace existing database segment+ let hostPart = String(pathPart[..<slashIdx])+ return prefix + hostPart + "/" + newDB + query+ } else {+ // No database in URI — append it+ return prefix + pathPart + "/" + newDB + query+ }+ }++ func disconnect() async throws {+ // MongoKitten cleans up via deinit; just clear references+ database = nil+ connectionConfig = nil+ isConnected = false+ }++ func testConnection(config: ConnectionConfig, password: String?) async throws -> Bool {+ try await connect(config: config, password: password)+ // Run a ping command to verify+ do {+ let _ = try await listCollectionNames()+ try await disconnect()+ return true+ } catch {+ try? await disconnect()+ throw error+ }+ }++ // MARK: - Helpers++ private func requireDatabase() throws -> MongoDatabase {+ guard let db = database else {+ throw GridexError.connectionFailed(underlying: NSError(+ domain: "MongoDB", code: -1,+ userInfo: [NSLocalizedDescriptionKey: "Not connected to MongoDB"]))+ }+ return db+ }++ private func listCollectionNames() async throws -> [String] {+ let db = try requireDatabase()+ let collections = try await db.listCollections()+ return collections.map(\.name).sorted()+ }++ // Convert a BSON Primitive into Gridex's RowValue+ private func primitiveToRowValue(_ value: Primitive?) -> RowValue {+ guard let value = value else { return .null }+ if value is Null { return .null }+ if let s = value as? String { return .string(s) }+ if let i = value as? Int32 { return .integer(Int64(i)) }+ if let i = value as? Int64 { return .integer(i) }+ if let i = value as? Int { return .integer(Int64(i)) }+ if let d = value as? Double { return .double(d) }+ if let b = value as? Bool { return .boolean(b) }+ if let date = value as? Date { return .date(date) }+ if let oid = value as? ObjectId { return .string(oid.hexString) }+ if let doc = value as? Document {+ // Render nested document as JSON+ return .json(documentToJSONString(doc))+ }+ // Arrays are also Documents in BSON; fall back to string+ return .string(String(describing: value))+ }++ private func documentToJSONString(_ doc: Document) -> String {+ // Best-effort JSON representation. BSON has more types than JSON,+ // so this is lossy but readable.+ // Use keys/subscript instead of for-in to sidestep any iterator quirks+ // when sub-documents have unusual encodings.+ if doc.isArray {+ var items: [String] = []+ for key in doc.keys {+ items.append(primitiveToJSON(doc[key]))+ }+ return "[" + items.joined(separator: ",") + "]"+ }+ var pairs: [String] = []+ for key in doc.keys {+ let escapedKey = "\"\(key)\""+ let val = primitiveToJSON(doc[key])+ pairs.append("\(escapedKey):\(val)")+ }+ return "{" + pairs.joined(separator: ",") + "}"+ }++ private func primitiveToJSON(_ value: Primitive?) -> String {+ guard let value = value else { return "null" }+ if value is Null { return "null" }+ if let s = value as? String { return "\"\(s.replacingOccurrences(of: "\"", with: "\\\""))\"" }+ if let i = value as? Int32 { return String(i) }+ if let i = value as? Int64 { return String(i) }+ if let i = value as? Int { return String(i) }+ if let d = value as? Double { return String(d) }+ if let b = value as? Bool { return b ? "true" : "false" }+ if let oid = value as? ObjectId { return "\"\(oid.hexString)\"" }+ if let date = value as? Date {+ let fmt = ISO8601DateFormatter()+ return "\"\(fmt.string(from: date))\""+ }+ if let doc = value as? Document { return documentToJSONString(doc) }+ return "\"\(String(describing: value).replacingOccurrences(of: "\"", with: "\\\""))\""+ }++ // MARK: - DatabaseAdapter — Query Execution++ func execute(query: String, parameters: [QueryParameter]?) async throws -> QueryResult {+ try await executeRaw(sql: query)+ }++ func executeRaw(sql: String) async throws -> QueryResult {+ // Accept raw shell-like syntax: "collection.find()" or JSON command body+ // For MVP: parse "collectionName.find()" / "collectionName.count()"+ let start = CFAbsoluteTimeGetCurrent()+ let trimmed = sql.trimmingCharacters(in: .whitespacesAndNewlines)++ // Match patterns like: collectionName.find() or collectionName.count()+ if let match = trimmed.range(of: #"^(\w+)\.(\w+)\(\s*\)$"#, options: .regularExpression) {+ let parts = trimmed[match].split(separator: ".")+ guard parts.count >= 2 else {+ throw GridexError.queryExecutionFailed("Invalid query syntax. Use: collectionName.find() or collectionName.count()")+ }+ let coll = String(parts[0])+ let op = String(parts[1].dropLast(2)) // strip "()"++ switch op {+ case "find":+ let result = try await fetchRows(table: coll, schema: nil, columns: nil, where: nil, orderBy: nil, limit: 100, offset: 0)+ return QueryResult(+ columns: result.columns,+ rows: result.rows,+ rowsAffected: 0,+ executionTime: CFAbsoluteTimeGetCurrent() - start,+ queryType: .select+ )+ case "count":+ let db = try requireDatabase()+ let count = try await db[coll].count()+ return QueryResult(+ columns: [ColumnHeader(name: "count", dataType: "integer", isNullable: false)],+ rows: [[.integer(Int64(count))]],+ rowsAffected: 0,+ executionTime: CFAbsoluteTimeGetCurrent() - start,+ queryType: .select+ )+ default:+ throw GridexError.queryExecutionFailed("Unsupported operation: \(op). Try collectionName.find() or .count()")+ }+ }++ throw GridexError.queryExecutionFailed("Use the syntax: collectionName.find() or collectionName.count()")+ }++ func executeWithRowValues(sql: String, parameters: [RowValue]) async throws -> QueryResult {+ try await executeRaw(sql: sql)+ }++ // MARK: - Schema Inspection++ func listDatabases() async throws -> [String] {+ let db = try requireDatabase()+ let dbs = try await db.pool.listDatabases()+ return dbs.map { $0.name }.sorted()+ }++ func listSchemas(database: String?) async throws -> [String] { [] }++ func listTables(schema: String?) async throws -> [TableInfo] {+ let names = try await listCollectionNames()+ var infos: [TableInfo] = []+ let db = try requireDatabase()+ for name in names {+ let count = try? await db[name].count()+ infos.append(TableInfo(name: name, schema: nil, type: .table, estimatedRowCount: count))+ }+ return infos+ }++ func listViews(schema: String?) async throws -> [ViewInfo] { [] }++ func describeTable(name: String, schema: String?) async throws -> TableDescription {+ let db = try requireDatabase()+ let collection = db[name]++ // Sample up to 10 documents to infer the schema (including nested fields).+ let samples = try await collection.find().limit(10).drain()++ var fieldOrder: [String] = []+ var fieldTypes: [String: String] = [:]+ for doc in samples {+ collectFieldPaths(doc, prefix: "", order: &fieldOrder, types: &fieldTypes)+ }++ // Always ensure _id appears first+ if let idx = fieldOrder.firstIndex(of: "_id"), idx != 0 {+ fieldOrder.remove(at: idx)+ fieldOrder.insert("_id", at: 0)+ } else if !fieldOrder.contains("_id") {+ fieldOrder.insert("_id", at: 0)+ fieldTypes["_id"] = "objectId"+ }++ let columns = fieldOrder.enumerated().map { (idx, name) in+ ColumnInfo(+ name: name,+ dataType: fieldTypes[name] ?? "any",+ isNullable: name != "_id",+ defaultValue: nil,+ isPrimaryKey: name == "_id",+ isAutoIncrement: false,+ comment: nil,+ ordinalPosition: idx + 1,+ characterMaxLength: nil+ )+ }++ let count = try? await collection.count()++ return TableDescription(+ name: name,+ schema: nil,+ columns: columns,+ indexes: [],+ foreignKeys: [],+ constraints: [],+ comment: nil,+ estimatedRowCount: count+ )+ }++ /// Recursively collect field paths from a BSON Document, flattening nested+ /// objects into dot-notation paths (e.g. "address.city"). Arrays and primitive+ /// fields are recorded at their parent level. The top-level field is also+ /// recorded so users can filter on the parent (e.g. `address` for object equality+ /// or `tags` for array contains).+ /// Limited recursion depth to avoid pathological docs and stack overflow.+ private func collectFieldPaths(_ doc: Document, prefix: String, order: inout [String], types: inout [String: String], depth: Int = 0) {+ guard depth < 10 else { return } // safety: cap nesting depth++ // Use keys/subscript instead of for-in to avoid any iterator quirks+ // with deeply nested or unusual BSON encodings.+ for key in doc.keys {+ let value = doc[key]+ let path = prefix.isEmpty ? key : "\(prefix).\(key)"++ if !types.keys.contains(path) {+ order.append(path)+ types[path] = inferType(value)+ }++ // Recurse only into nested object documents (NOT arrays — they have+ // numeric string keys "0", "1", "2" which would create paths like+ // "tags.0" that aren't useful for filtering most cases).+ if let nested = value as? Document, !nested.isArray {+ collectFieldPaths(nested, prefix: path, order: &order, types: &types, depth: depth + 1)+ }+ }+ }++ /// Look up a value in a Document by dot-notation path (e.g. "address.city").+ /// Returns nil if any segment is missing or hits a non-document.+ /// Skips array documents to avoid weird numeric-key traversal.+ private func valueAtPath(_ doc: Document, path: String) -> Primitive? {+ let segments = path.split(separator: ".").map(String.init)+ guard !segments.isEmpty else { return nil }+ var current: Primitive? = doc+ for seg in segments {+ guard let cur = current else { return nil }+ guard let curDoc = cur as? Document else { return nil }+ // Don't traverse into arrays via dot path+ if curDoc.isArray { return nil }+ current = curDoc[seg]+ }+ return current+ }++ private func inferType(_ value: Primitive?) -> String {+ guard let value = value else { return "null" }+ if value is Null { return "null" }+ if value is String { return "string" }+ if value is Int32 || value is Int64 || value is Int { return "integer" }+ if value is Double { return "double" }+ if value is Bool { return "boolean" }+ if value is Date { return "date" }+ if value is ObjectId { return "objectId" }+ if let doc = value as? Document {+ return doc.isArray ? "array" : "document"+ }+ return "any"+ }++ func listIndexes(table: String, schema: String?) async throws -> [IndexInfo] { [] }+ func listForeignKeys(table: String, schema: String?) async throws -> [ForeignKeyInfo] { [] }+ func listFunctions(schema: String?) async throws -> [String] { [] }+ func getFunctionSource(name: String, schema: String?) async throws -> String { "" }++ // MARK: - Data Manipulation++ func insertRow(table: String, schema: String?, values: [String: RowValue]) async throws -> QueryResult {+ let db = try requireDatabase()+ let collection = db[table]+ var doc = Document()+ for (key, value) in values {+ doc[key] = rowValueToPrimitive(value)+ }+ let reply = try await collection.insert(doc)+ return QueryResult(+ columns: [],+ rows: [],+ rowsAffected: reply.insertCount,+ executionTime: 0,+ queryType: .insert+ )+ }++ func updateRow(table: String, schema: String?, set: [String: RowValue], where whereClause: [String: RowValue]) async throws -> QueryResult {+ let db = try requireDatabase()+ let collection = db[table]++ var filter = Document()+ for (key, value) in whereClause {+ filter[key] = rowValueToPrimitive(value)+ }+ var setDoc = Document()+ for (key, value) in set {+ setDoc[key] = rowValueToPrimitive(value)+ }+ let reply = try await collection.updateOne(where: filter, to: ["$set": setDoc])+ return QueryResult(+ columns: [],+ rows: [],+ rowsAffected: reply.updatedCount ?? 0,+ executionTime: 0,+ queryType: .update+ )+ }++ func deleteRow(table: String, schema: String?, where whereClause: [String: RowValue]) async throws -> QueryResult {+ let db = try requireDatabase()+ let collection = db[table]+ var filter = Document()+ for (key, value) in whereClause {+ filter[key] = rowValueToPrimitive(value)+ }+ let reply = try await collection.deleteOne(where: filter)+ return QueryResult(+ columns: [],+ rows: [],+ rowsAffected: reply.deletes,+ executionTime: 0,+ queryType: .delete+ )+ }++ /// Convert a Gridex FilterExpression into a BSON Document for MongoDB find().+ /// Returns an empty Document (matches everything) when filter is nil or empty.+ private func buildMongoFilter(from expr: FilterExpression?) -> Document {+ guard let expr = expr, !expr.conditions.isEmpty else { return Document() }++ let conditionDocs: [Document] = expr.conditions.compactMap { condition in+ buildConditionDoc(condition)+ }++ if conditionDocs.isEmpty { return Document() }+ if conditionDocs.count == 1 { return conditionDocs[0] }++ // Combine multiple conditions with $and / $or+ var combined = Document()+ let combinator = expr.combinator == .and ? "$and" : "$or"+ var array = Document(isArray: true)+ for (idx, doc) in conditionDocs.enumerated() {+ array[String(idx)] = doc+ }+ combined[combinator] = array+ return combined+ }++ private func buildConditionDoc(_ condition: FilterCondition) -> Document? {+ let column = condition.column+ let value = mongoValueFromRowValue(condition.value, fieldName: column)+ var doc = Document()++ switch condition.op {+ case .equal:+ doc[column] = value+ case .notEqual:+ var inner = Document()+ inner["$ne"] = value+ doc[column] = inner+ case .greaterThan:+ var inner = Document()+ inner["$gt"] = value+ doc[column] = inner+ case .lessThan:+ var inner = Document()+ inner["$lt"] = value+ doc[column] = inner+ case .greaterOrEqual:+ var inner = Document()+ inner["$gte"] = value+ doc[column] = inner+ case .lessOrEqual:+ var inner = Document()+ inner["$lte"] = value+ doc[column] = inner+ case .like, .notLike:+ // Convert SQL LIKE pattern to MongoDB regex+ // % → .* _ → .+ let pattern: String = {+ if let s = condition.value.stringValue {+ let escaped = NSRegularExpression.escapedPattern(for: s)+ .replacingOccurrences(of: "%", with: ".*")+ .replacingOccurrences(of: "_", with: ".")+ return "^" + escaped + "$"+ }+ return ".*"+ }()+ var inner = Document()+ inner["$regex"] = pattern+ inner["$options"] = "i"+ if condition.op == .notLike {+ var notDoc = Document()+ notDoc["$not"] = inner+ doc[column] = notDoc+ } else {+ doc[column] = inner+ }+ case .isNull:+ var inner = Document()+ inner["$eq"] = Null()+ doc[column] = inner+ case .isNotNull:+ var inner = Document()+ inner["$ne"] = Null()+ doc[column] = inner+ case .in_:+ // Parse comma-separated values from string+ if let s = condition.value.stringValue {+ let parts = s.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }+ var array = Document(isArray: true)+ for (idx, part) in parts.enumerated() {+ array[String(idx)] = parseScalar(part)+ }+ var inner = Document()+ inner["$in"] = array+ doc[column] = inner+ }+ }+ return doc+ }++ /// Convert a Gridex RowValue to a BSON primitive for use in queries.+ /// Special-cased for the _id field: 24-char hex strings auto-convert to ObjectId.+ private func mongoValueFromRowValue(_ value: RowValue, fieldName: String) -> Primitive {+ if fieldName == "_id", case .string(let s) = value, s.count == 24,+ s.allSatisfy({ $0.isHexDigit }), let oid = try? ObjectId(s) {+ return oid+ }+ return rowValueToPrimitive(value)+ }++ /// Best-effort parse of a string into a typed BSON primitive (used for IN clauses).+ private func parseScalar(_ s: String) -> Primitive {+ let trimmed = s.trimmingCharacters(in: CharacterSet(charactersIn: "'\""))+ if let i = Int(trimmed) { return i }+ if let d = Double(trimmed) { return d }+ if trimmed.lowercased() == "true" { return true }+ if trimmed.lowercased() == "false" { return false }+ if trimmed.lowercased() == "null" { return Null() }+ if trimmed.count == 24, trimmed.allSatisfy({ $0.isHexDigit }), let oid = try? ObjectId(trimmed) {+ return oid+ }+ return trimmed+ }++ private func rowValueToPrimitive(_ value: RowValue) -> Primitive {+ switch value {+ case .null: return Null()+ case .string(let s):+ // Auto-detect ObjectId hex strings (24 hex chars)+ if s.count == 24, s.allSatisfy({ $0.isHexDigit }), let oid = try? ObjectId(s) {+ return oid+ }+ return s+ case .integer(let i): return Int(i)+ case .double(let d): return d+ case .boolean(let b): return b+ case .date(let d): return d+ case .data(let d): return d.base64EncodedString()+ case .json(let s): return s+ case .uuid(let u): return u.uuidString+ case .array(let arr): return arr.map { String(describing: $0) }.joined(separator: ", ")+ }+ }++ // MARK: - Transactions++ func beginTransaction() async throws {+ // MongoKitten supports startTransaction on the database instance.+ // For MVP we no-op since most operations are atomic at document level.+ }++ func commitTransaction() async throws {}+ func rollbackTransaction() async throws {}++ // MARK: - Pagination++ func fetchRows(+ table: String,+ schema: String?,+ columns: [String]?,+ where whereExpr: FilterExpression?,+ orderBy: [QuerySortDescriptor]?,+ limit: Int,+ offset: Int+ ) async throws -> QueryResult {+ let start = CFAbsoluteTimeGetCurrent()+ let db = try requireDatabase()+ let collection = db[table]++ // Build BSON filter from FilterExpression+ let filter = buildMongoFilter(from: whereExpr)+ var query = collection.find(filter)++ // Apply sort if provided — _id ASC is the natural default+ if let orderBy, !orderBy.isEmpty {+ var sortDoc = Document()+ for desc in orderBy {+ sortDoc[desc.column] = desc.direction == .ascending ? Int32(1) : Int32(-1)+ }+ query = query.sort(sortDoc)+ }++ query = query.skip(offset).limit(limit)++ let documents = try await query.drain()++ // Build flat field paths from the returned documents (includes nested+ // dot-notation paths like "address.city").+ var fieldOrder: [String] = []+ var fieldTypes: [String: String] = [:]+ // Always show _id first+ if !documents.isEmpty {+ fieldOrder.append("_id")+ fieldTypes["_id"] = "objectId"+ for doc in documents {+ collectFieldPaths(doc, prefix: "", order: &fieldOrder, types: &fieldTypes)+ }+ }++ let cols = fieldOrder.map { name in+ ColumnHeader(+ name: name,+ dataType: fieldTypes[name] ?? "any",+ isNullable: name != "_id",+ tableName: table+ )+ }++ let rows: [[RowValue]] = documents.map { doc in+ fieldOrder.map { path in+ if path.contains(".") {+ return primitiveToRowValue(valueAtPath(doc, path: path))+ } else {+ return primitiveToRowValue(doc[path])+ }+ }+ }++ return QueryResult(+ columns: cols,+ rows: rows,+ rowsAffected: 0,+ executionTime: CFAbsoluteTimeGetCurrent() - start,+ queryType: .select+ )+ }++ // MARK: - Database Management++ func createDatabase(name: String) async throws {+ // MongoDB creates databases lazily when first collection is created.+ // Use the existing connection's pool to access the new database namespace,+ // then materialize it by inserting + dropping a placeholder document.+ let db = try requireDatabase()+ let newDb = db.pool[name]+ _ = try await newDb["__gridex_init__"].insert(["_id": ObjectId()])+ try await newDb["__gridex_init__"].drop()+ }++ /// Create an empty collection in the current database. MongoDB collections are+ /// schemaless, so no column definitions are needed.+ func createCollection(name: String) async throws {+ let db = try requireDatabase()+ let collection = db[name]+ // Materialize the collection by inserting a sentinel doc, then deleting it+ let sentinelId = ObjectId()+ _ = try await collection.insert(["_id": sentinelId])+ _ = try await collection.deleteOne(where: ["_id": sentinelId])+ }++ // MARK: - Backup / Restore++ /// Stream all collections and documents for backup. Calls `onBatch` for each+ /// batch of documents with the collection name. Progress callback receives+ /// cumulative document count + elapsed time.+ func backupStream(+ onBatch: @escaping (String, [Document]) async throws -> Void,+ onProgress: ((Int64, TimeInterval) -> Void)? = nil+ ) async throws {+ let db = try requireDatabase()+ let collectionNames = try await listCollectionNames()+ let start = CFAbsoluteTimeGetCurrent()+ var totalDocs: Int64 = 0+ let batchSize = 500++ for name in collectionNames {+ let collection = db[name]+ var skip = 0+ while true {+ let batch = try await collection.find().skip(skip).limit(batchSize).drain()+ if batch.isEmpty { break }+ try await onBatch(name, batch)+ totalDocs += Int64(batch.count)+ onProgress?(totalDocs, CFAbsoluteTimeGetCurrent() - start)+ if batch.count < batchSize { break }+ skip += batchSize+ }+ }+ }++ /// Insert a batch of documents into a collection (used by restore).+ func insertBatch(collection: String, documents: [Document]) async throws {+ guard !documents.isEmpty else { return }+ let db = try requireDatabase()+ let coll = db[collection]+ for doc in documents {+ _ = try? await coll.insert(doc)+ }+ }++ /// Convert a BSON Document to a JSON string for NDJSON export.+ func documentToJSON(_ doc: Document) -> String {+ documentToJSONString(doc)+ }++ /// Parse a single JSON line into a BSON Document for NDJSON restore.+ func jsonLineToDocument(_ line: String) -> Document? {+ guard let data = line.data(using: .utf8),+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {+ return nil+ }+ return jsonObjectToDocument(json)+ }++ /// Insert a single document from a raw JSON string into a collection.+ /// Supports MongoDB extended JSON shortcuts: {"$oid": "..."} for ObjectId,+ /// {"$date": "..."} for Date.+ func insertJSONDocument(into collection: String, json: String) async throws {+ let db = try requireDatabase()+ guard let data = json.data(using: .utf8) else {+ throw GridexError.queryExecutionFailed("Invalid UTF-8 in JSON")+ }+ let jsonObject: Any+ do {+ jsonObject = try JSONSerialization.jsonObject(with: data, options: [.allowFragments])+ } catch {+ throw GridexError.queryExecutionFailed("Invalid JSON: \(error.localizedDescription)")+ }+ guard let dict = jsonObject as? [String: Any] else {+ throw GridexError.queryExecutionFailed("JSON must be a single document object")+ }+ let doc = jsonObjectToDocument(dict)+ _ = try await db[collection].insert(doc)+ }++ /// Convert a JSON dictionary into a BSON Document, handling extended JSON shortcuts.+ private func jsonObjectToDocument(_ dict: [String: Any]) -> Document {+ var doc = Document()+ for (key, value) in dict {+ doc[key] = jsonValueToBSON(value)+ }+ return doc+ }++ private func jsonValueToBSON(_ value: Any) -> Primitive? {+ if value is NSNull { return Null() }+ if let str = value as? String {+ // Auto-detect ObjectId hex strings+ if str.count == 24, str.allSatisfy({ $0.isHexDigit }), let oid = try? ObjectId(str) {+ return oid+ }+ return str+ }+ if let num = value as? NSNumber {+ // Distinguish bool / int / double+ let typeChar = String(cString: num.objCType)+ if typeChar == "c" || typeChar == "B" { return num.boolValue }+ if typeChar == "d" || typeChar == "f" { return num.doubleValue }+ return Int(truncating: num)+ }+ if let arr = value as? [Any] {+ // Convert to BSON array (Document with isArray)+ var doc = Document(isArray: true)+ for (idx, item) in arr.enumerated() {+ doc[String(idx)] = jsonValueToBSON(item)+ }+ return doc+ }+ if let dict = value as? [String: Any] {+ // Extended JSON shortcuts+ if let oidStr = dict["$oid"] as? String, let oid = try? ObjectId(oidStr) {+ return oid+ }+ if let dateStr = dict["$date"] as? String {+ let fmt = ISO8601DateFormatter()+ fmt.formatOptions = [.withInternetDateTime, .withFractionalSeconds]+ if let date = fmt.date(from: dateStr) {+ return date+ }+ fmt.formatOptions = [.withInternetDateTime]+ if let date = fmt.date(from: dateStr) {+ return date+ }+ }+ return jsonObjectToDocument(dict)+ }+ return nil+ }++ func dropDatabase(name: String) async throws {+ let db = try requireDatabase()+ let target = db.pool[name]+ try await target.drop()+ }++ // MARK: - Database Info++ func serverVersion() async throws -> String {+ // MongoKitten doesn't expose server version directly without runCommand;+ // return generic label for now.+ return "MongoDB"+ }++ func currentDatabase() async throws -> String? {+ connectionConfig?.database+ }+}++// MARK: - Character helper++private extension Character {+ var isHexDigit: Bool {+ return ("0"..."9").contains(self) || ("a"..."f").contains(self) || ("A"..."F").contains(self)+ }+}diff --git a/macos/Data/Adapters/MySQL/MySQLAdapter.swift b/macos/Data/Adapters/MySQL/MySQLAdapter.swiftnew file mode 100644index 0000000..c054bd5--- /dev/null+++ b/macos/Data/Adapters/MySQL/MySQLAdapter.swift@@ -0,0 +1,662 @@+// MySQLAdapter.swift+// Gridex+//+// MySQL database adapter using MySQLNIO.++import Foundation+import MySQLNIO+import NIOCore+import NIOPosix+import NIOSSL+import Logging++final class MySQLAdapter: DatabaseAdapter, SchemaInspectable, @unchecked Sendable {+ let databaseType: DatabaseType = .mysql+ private(set) var isConnected: Bool = false+ private var connection: MySQLConnection?+ private let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 2)+ private let logger = Logger(label: "com.gridex.mysql")+ private var cachedDatabase: String?++ // Stored credentials for auto-reconnect (in-memory only, cleared on disconnect)+ private var storedConfig: ConnectionConfig?+ private var storedPassword: String?++ // Reconnect coordination — prevents concurrent reconnect attempts+ private let stateLock = NSLock()+ private var reconnectTask: Task<Void, Error>?+ private var keepaliveTask: Task<Void, Never>?++ /// Keepalive interval. 30s is well under MySQL's default wait_timeout (28800s)+ /// but low enough to fit under aggressive SSH/firewall idle timeouts (often 60-300s).+ private static let keepaliveInterval: Duration = .seconds(30)++ deinit {+ keepaliveTask?.cancel()+ if let connection, !connection.isClosed {+ _ = connection.close()+ }+ try? eventLoopGroup.syncShutdownGracefully()+ }++ // MARK: - Connection++ func connect(config: ConnectionConfig, password: String?) async throws {+ try await openConnection(config: config, password: password)+ self.storedConfig = config+ self.storedPassword = password+ startKeepalive()+ }++ func disconnect() async throws {+ keepaliveTask?.cancel()+ keepaliveTask = nil+ storedConfig = nil+ storedPassword = nil++ if let connection, !connection.isClosed {+ _ = try await connection.close().get()+ }+ connection = nil+ isConnected = false+ cachedDatabase = nil+ }++ /// Opens a new MySQL connection using the given config. Does not mutate stored+ /// credentials — callers manage those (so reconnect doesn't overwrite them).+ private func openConnection(config: ConnectionConfig, password: String?) async throws {+ let host = config.host ?? "localhost"+ let port = config.port ?? 3306+ let username = config.username ?? "root"+ let database = config.database ?? ""++ let address: SocketAddress+ do {+ address = try SocketAddress.makeAddressResolvingHost(host, port: port)+ } catch {+ throw GridexError.connectionFailed(underlying: error)+ }++ let tlsConfig: TLSConfiguration? = config.sslEnabled ? .makeClientConfiguration() : nil++ do {+ let conn = try await MySQLConnection.connect(+ to: address,+ username: username,+ database: database,+ password: password,+ tlsConfiguration: tlsConfig,+ serverHostname: host,+ logger: logger,+ on: eventLoopGroup.next()+ ).get()+ self.connection = conn+ self.isConnected = true+ self.cachedDatabase = nil+ } catch {+ throw GridexError.connectionFailed(underlying: error)+ }+ }++ func testConnection(config: ConnectionConfig, password: String?) async throws -> Bool {+ let adapter = MySQLAdapter()+ do {+ try await adapter.connect(config: config, password: password)+ try await adapter.disconnect()+ return true+ } catch {+ try? await adapter.disconnect()+ throw error+ }+ }++ // MARK: - Query Execution++ func execute(query: String, parameters: [QueryParameter]?) async throws -> QueryResult {+ try await ensureLive()+ let startTime = CFAbsoluteTimeGetCurrent()+ let upper = query.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()+ let queryType = detectQueryType(upper)++ guard let connection else { throw GridexError.queryExecutionFailed("Not connected to MySQL") }++ let rows: [MySQLRow]+ do {+ rows = try await connection.simpleQuery(query).get()+ } catch {+ // Connection may have died mid-query (e.g. server idle timeout after our+ // ensureLive check). Try to reconnect once and re-run the query.+ if isConnectionDrop(error) {+ logger.info("MySQL query failed with connection drop; reconnecting and retrying")+ try await forceReconnect()+ guard let live = self.connection else {+ throw GridexError.queryExecutionFailed("Not connected to MySQL")+ }+ rows = try await live.simpleQuery(query).get()+ } else {+ throw error+ }+ }+ let duration = CFAbsoluteTimeGetCurrent() - startTime++ if queryType == .select || !rows.isEmpty {+ let columns: [ColumnHeader]+ if let first = rows.first {+ columns = first.columnDefinitions.map { col in+ ColumnHeader(name: col.name, dataType: mysqlDataTypeName(col.columnType))+ }+ } else {+ columns = []+ }++ let resultRows: [[RowValue]] = rows.map { row in+ row.columnDefinitions.enumerated().map { idx, col in+ let data = MySQLData(+ type: col.columnType,+ format: row.format,+ buffer: row.values[idx],+ isUnsigned: col.flags.contains(.COLUMN_UNSIGNED)+ )+ return decodeData(data, columnType: col.columnType)+ }+ }++ return QueryResult(columns: columns, rows: resultRows, rowsAffected: resultRows.count, executionTime: duration, queryType: queryType)+ } else {+ return QueryResult(columns: [], rows: [], rowsAffected: 0, executionTime: duration, queryType: queryType)+ }+ }++ func executeRaw(sql: String) async throws -> QueryResult {+ try await execute(query: sql, parameters: nil)+ }++ // MARK: - Schema Inspection++ func listDatabases() async throws -> [String] {+ let result = try await executeRaw(sql: "SHOW DATABASES")+ return result.rows.compactMap { $0.first?.stringValue }+ }++ func listSchemas(database: String?) async throws -> [String] {+ try await listDatabases()+ }++ func listTables(schema: String?) async throws -> [TableInfo] {+ let db = try await resolveDB(schema)+ let result = try await executeRaw(sql: """+ SELECT TABLE_NAME, TABLE_ROWS+ FROM information_schema.TABLES+ WHERE TABLE_SCHEMA = '\(escapeSQL(db))' AND TABLE_TYPE = 'BASE TABLE'+ ORDER BY TABLE_NAME+ """)+ return result.rows.compactMap { row -> TableInfo? in+ guard let name = row.first?.stringValue else { return nil }+ let count = row.count > 1 ? row[1].intValue : nil+ return TableInfo(name: name, schema: db, type: .table, estimatedRowCount: count)+ }+ }++ func listViews(schema: String?) async throws -> [ViewInfo] {+ let db = try await resolveDB(schema)+ let result = try await executeRaw(sql: """+ SELECT TABLE_NAME, VIEW_DEFINITION+ FROM information_schema.VIEWS+ WHERE TABLE_SCHEMA = '\(escapeSQL(db))'+ ORDER BY TABLE_NAME+ """)+ return result.rows.compactMap { row -> ViewInfo? in+ guard let name = row.first?.stringValue else { return nil }+ let def = row.count > 1 ? row[1].stringValue : nil+ return ViewInfo(name: name, schema: db, definition: def, isMaterialized: false)+ }+ }++ func describeTable(name: String, schema: String?) async throws -> TableDescription {+ let db = try await resolveDB(schema)++ // Run column/index/FK queries in parallel+ async let columnsTask = describeColumns(table: name, schema: db)+ async let indexesTask = listIndexes(table: name, schema: db)+ async let fksTask = listForeignKeys(table: name, schema: db)++ // Get row count + comment in one query from information_schema.TABLES+ let metaResult = try await executeRaw(sql: """+ SELECT TABLE_ROWS, TABLE_COMMENT FROM information_schema.TABLES+ WHERE TABLE_SCHEMA = '\(escapeSQL(db))' AND TABLE_NAME = '\(escapeSQL(name))'+ """)+ let count = metaResult.rows.first?[0].intValue+ let comment = metaResult.rows.first?[1].stringValue++ let columns = try await columnsTask+ let indexes = try await indexesTask+ let fks = try await fksTask++ return TableDescription(name: name, schema: db, columns: columns, indexes: indexes, foreignKeys: fks, constraints: [], comment: comment, estimatedRowCount: count)+ }++ private func describeColumns(table: String, schema: String) async throws -> [ColumnInfo] {+ let result = try await executeRaw(sql: """+ SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_DEFAULT,+ ORDINAL_POSITION, CHARACTER_MAXIMUM_LENGTH, COLUMN_KEY, EXTRA, COLUMN_COMMENT+ FROM information_schema.COLUMNS+ WHERE TABLE_SCHEMA = '\(escapeSQL(schema))' AND TABLE_NAME = '\(escapeSQL(table))'+ ORDER BY ORDINAL_POSITION+ """)++ return result.rows.map { row in+ let name = row[0].stringValue ?? ""+ let dataType = row[1].stringValue ?? "varchar"+ let nullable = row[2].stringValue == "YES"+ let defVal = row[3].stringValue+ let ordinal = row[4].intValue ?? 0+ let maxLen = row[5].intValue+ let columnKey = row[6].stringValue ?? ""+ let extra = row[7].stringValue ?? ""+ let comment = row[8].stringValue++ return ColumnInfo(+ name: name, dataType: dataType, isNullable: nullable, defaultValue: defVal,+ isPrimaryKey: columnKey == "PRI",+ isAutoIncrement: extra.contains("auto_increment"),+ comment: comment?.isEmpty == true ? nil : comment,+ ordinalPosition: ordinal, characterMaxLength: maxLen+ )+ }+ }++ func listIndexes(table: String, schema: String?) async throws -> [IndexInfo] {+ let db = try await resolveDB(schema)+ let result = try await executeRaw(sql: """+ SELECT INDEX_NAME, GROUP_CONCAT(COLUMN_NAME ORDER BY SEQ_IN_INDEX), NON_UNIQUE, INDEX_TYPE+ FROM information_schema.STATISTICS+ WHERE TABLE_SCHEMA = '\(escapeSQL(db))' AND TABLE_NAME = '\(escapeSQL(table))'+ GROUP BY INDEX_NAME, NON_UNIQUE, INDEX_TYPE+ ORDER BY INDEX_NAME+ """)++ return result.rows.compactMap { row -> IndexInfo? in+ guard let name = row[0].stringValue else { return nil }+ let cols = row[1].stringValue?.split(separator: ",").map(String.init) ?? []+ let nonUnique = row[2].stringValue == "1" || row[2].intValue == 1+ let type = row[3].stringValue+ return IndexInfo(name: name, columns: cols, isUnique: !nonUnique, type: type, tableName: table)+ }+ }++ func listForeignKeys(table: String, schema: String?) async throws -> [ForeignKeyInfo] {+ let db = try await resolveDB(schema)+ let result = try await executeRaw(sql: """+ SELECT kcu.CONSTRAINT_NAME, kcu.COLUMN_NAME, kcu.REFERENCED_TABLE_NAME, kcu.REFERENCED_COLUMN_NAME,+ rc.DELETE_RULE, rc.UPDATE_RULE+ FROM information_schema.KEY_COLUMN_USAGE kcu+ JOIN information_schema.REFERENTIAL_CONSTRAINTS rc+ ON rc.CONSTRAINT_SCHEMA = kcu.TABLE_SCHEMA AND rc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME+ WHERE kcu.TABLE_SCHEMA = '\(escapeSQL(db))' AND kcu.TABLE_NAME = '\(escapeSQL(table))'+ AND kcu.REFERENCED_TABLE_NAME IS NOT NULL+ ORDER BY kcu.CONSTRAINT_NAME+ """)++ return result.rows.compactMap { row -> ForeignKeyInfo? in+ let name = row[0].stringValue+ guard let col = row[1].stringValue,+ let refTable = row[2].stringValue,+ let refCol = row[3].stringValue else { return nil }+ let onDelete = ForeignKeyAction(rawValue: row[4].stringValue ?? "NO ACTION") ?? .noAction+ let onUpdate = ForeignKeyAction(rawValue: row[5].stringValue ?? "NO ACTION") ?? .noAction+ return ForeignKeyInfo(name: name, columns: [col], referencedTable: refTable, referencedColumns: [refCol], onDelete: onDelete, onUpdate: onUpdate)+ }+ }++ func listFunctions(schema: String?) async throws -> [String] {+ let db = try await resolveDB(schema)+ let result = try await executeRaw(sql: """+ SELECT ROUTINE_NAME FROM information_schema.ROUTINES+ WHERE ROUTINE_SCHEMA = '\(escapeSQL(db))'+ ORDER BY ROUTINE_NAME+ """)+ return result.rows.compactMap { $0[0].stringValue }+ }++ func getFunctionSource(name: String, schema: String?) async throws -> String {+ let result = try await executeRaw(sql: "SHOW CREATE FUNCTION \(quoteIdentifier(name))")+ guard let source = result.rows.first?[2].stringValue else {+ throw GridexError.queryExecutionFailed("Function '\(name)' not found")+ }+ return source+ }++ // MARK: - Data Manipulation++ func insertRow(table: String, schema: String?, values: [String: RowValue]) async throws -> QueryResult {+ let d = SQLDialect.mysql+ let cols = values.keys.map { d.quoteIdentifier($0) }.joined(separator: ", ")+ let vals = values.values.map { inlineValue($0) }.joined(separator: ", ")+ return try await executeRaw(sql: "INSERT INTO \(d.quoteIdentifier(table)) (\(cols)) VALUES (\(vals))")+ }++ func updateRow(table: String, schema: String?, set values: [String: RowValue], where conditions: [String: RowValue]) async throws -> QueryResult {+ let d = SQLDialect.mysql+ let setClauses = values.map { "\(d.quoteIdentifier($0.key)) = \(inlineValue($0.value))" }.joined(separator: ", ")+ let whereClauses = conditions.map { "\(d.quoteIdentifier($0.key)) = \(inlineValue($0.value))" }.joined(separator: " AND ")+ return try await executeRaw(sql: "UPDATE \(d.quoteIdentifier(table)) SET \(setClauses) WHERE \(whereClauses)")+ }++ func deleteRow(table: String, schema: String?, where conditions: [String: RowValue]) async throws -> QueryResult {+ let d = SQLDialect.mysql+ let whereClauses = conditions.map { "\(d.quoteIdentifier($0.key)) = \(inlineValue($0.value))" }.joined(separator: " AND ")+ return try await executeRaw(sql: "DELETE FROM \(d.quoteIdentifier(table)) WHERE \(whereClauses)")+ }++ func beginTransaction() async throws { _ = try await executeRaw(sql: "START TRANSACTION") }+ func commitTransaction() async throws { _ = try await executeRaw(sql: "COMMIT") }+ func rollbackTransaction() async throws { _ = try await executeRaw(sql: "ROLLBACK") }++ // MARK: - Pagination++ func fetchRows(table: String, schema: String?, columns: [String]?, where filter: FilterExpression?, orderBy: [QuerySortDescriptor]?, limit: Int, offset: Int) async throws -> QueryResult {+ let d = SQLDialect.mysql+ let colList = columns?.map { d.quoteIdentifier($0) }.joined(separator: ", ") ?? "*"+ var sql = "SELECT \(colList) FROM \(d.quoteIdentifier(table))"+ if let filter, !filter.conditions.isEmpty {+ sql += " WHERE \(filter.toSQL(dialect: d))"+ }+ if let orderBy, !orderBy.isEmpty {+ sql += " ORDER BY " + orderBy.map { $0.toSQL(dialect: d) }.joined(separator: ", ")+ }+ sql += " LIMIT \(limit) OFFSET \(offset)"+ return try await executeRaw(sql: sql)+ }++ func serverVersion() async throws -> String {+ let r = try await executeRaw(sql: "SELECT VERSION()")+ return r.rows.first?.first?.stringValue ?? "MySQL"+ }++ func currentDatabase() async throws -> String? {+ if let cached = cachedDatabase { return cached }+ let r = try await executeRaw(sql: "SELECT DATABASE()")+ let db = r.rows.first?.first?.stringValue+ cachedDatabase = db+ return db+ }++ /// Resolve the effective database name, using cached value to avoid extra query+ private func resolveDB(_ schema: String?) async throws -> String {+ if let schema, !schema.isEmpty { return schema }+ return try await currentDatabase() ?? ""+ }++ // MARK: - SchemaInspectable++ func fullSchemaSnapshot(database: String?) async throws -> SchemaSnapshot {+ let currentDB = try await currentDatabase()+ let dbName = database ?? currentDB ?? "mysql"+ let tables = try await listTables(schema: dbName)+ let descs: [TableDescription] = try await withThrowingTaskGroup(of: TableDescription.self) { group in+ for t in tables {+ let name = t.name+ group.addTask { try await self.describeTable(name: name, schema: dbName) }+ }+ var results: [TableDescription] = []+ for try await desc in group { results.append(desc) }+ return results+ }+ let views = try await listViews(schema: dbName)+ let schemaInfo = SchemaInfo(name: dbName, tables: descs, views: views, functions: [], enums: [])+ return SchemaSnapshot(databaseName: dbName, databaseType: .mysql, schemas: [schemaInfo], capturedAt: Date())+ }++ func columnStatistics(table: String, schema: String?, sampleSize: Int) async throws -> [ColumnStatistics] {+ let db = try await resolveDB(schema)+ let cols = try await describeColumns(table: table, schema: db)+ var stats: [ColumnStatistics] = []+ let d = SQLDialect.mysql+ for col in cols {+ let q = d.quoteIdentifier(col.name)+ let tbl = d.quoteIdentifier(table)+ let r = try await executeRaw(sql: """+ SELECT COUNT(DISTINCT \(q)),+ SUM(CASE WHEN \(q) IS NULL THEN 1 ELSE 0 END) / GREATEST(COUNT(*), 1),+ MIN(\(q)), MAX(\(q))+ FROM (SELECT \(q) FROM \(tbl) LIMIT \(sampleSize)) AS sample+ """)+ if let row = r.rows.first {+ stats.append(ColumnStatistics(+ columnName: col.name,+ distinctCount: row[0].intValue,+ nullRatio: row[1].doubleValue,+ topValues: nil,+ minValue: row[2].stringValue,+ maxValue: row[3].stringValue+ ))+ }+ }+ return stats+ }++ func tableRowCount(table: String, schema: String?) async throws -> Int {+ // Use fast estimated count from InnoDB stats instead of slow COUNT(*)+ let db = try await resolveDB(schema)+ let r = try await executeRaw(sql: """+ SELECT TABLE_ROWS FROM information_schema.TABLES+ WHERE TABLE_SCHEMA = '\(escapeSQL(db))' AND TABLE_NAME = '\(escapeSQL(table))'+ """)+ return r.rows.first?.first?.intValue ?? 0+ }++ func tableSizeBytes(table: String, schema: String?) async throws -> Int64? {+ let db = try await resolveDB(schema)+ let r = try await executeRaw(sql: """+ SELECT DATA_LENGTH + INDEX_LENGTH FROM information_schema.TABLES+ WHERE TABLE_SCHEMA = '\(escapeSQL(db))' AND TABLE_NAME = '\(escapeSQL(table))'+ """)+ if let val = r.rows.first?.first?.intValue { return Int64(val) }+ return nil+ }++ func queryStatistics() async throws -> [QueryStatisticsEntry] { [] }++ func primaryKeyColumns(table: String, schema: String?) async throws -> [String] {+ let db = try await resolveDB(schema)+ let r = try await executeRaw(sql: """+ SELECT COLUMN_NAME FROM information_schema.KEY_COLUMN_USAGE+ WHERE TABLE_SCHEMA = '\(escapeSQL(db))' AND TABLE_NAME = '\(escapeSQL(table))'+ AND CONSTRAINT_NAME = 'PRIMARY'+ ORDER BY ORDINAL_POSITION+ """)+ return r.rows.compactMap { $0.first?.stringValue }+ }++ // MARK: - Resilience (keepalive + auto-reconnect)++ /// Ensures the MySQL connection is alive. If closed, attempts to re-open using+ /// stored credentials. Concurrent callers coalesce onto a single reconnect task.+ private func ensureLive() async throws {+ stateLock.lock()+ let needsReconnect = connection == nil || connection?.isClosed == true || !isConnected+ if !needsReconnect {+ stateLock.unlock()+ return+ }++ guard let config = storedConfig else {+ stateLock.unlock()+ throw GridexError.queryExecutionFailed("Not connected to MySQL")+ }++ if let existing = reconnectTask {+ stateLock.unlock()+ try await existing.value+ return+ }++ let password = storedPassword+ let task: Task<Void, Error> = Task { [weak self] in+ guard let self else { return }+ try await self.openConnection(config: config, password: password)+ }+ reconnectTask = task+ stateLock.unlock()++ defer {+ stateLock.lock()+ if self.reconnectTask == task { self.reconnectTask = nil }+ stateLock.unlock()+ }+ try await task.value+ }++ /// Forces a reconnect regardless of current state. Used after a mid-query failure.+ private func forceReconnect() async throws {+ stateLock.lock()+ // Tear down the existing connection so ensureLive sees it as dead+ if let conn = connection, !conn.isClosed {+ _ = try? await conn.close().get()+ }+ connection = nil+ isConnected = false+ stateLock.unlock()+ try await ensureLive()+ }++ private func isConnectionDrop(_ error: Error) -> Bool {+ // MySQLNIO surfaces connection drops as various NIO/Channel errors. Also+ // treat any error as a drop if the connection object is now closed.+ if let conn = connection, conn.isClosed { return true }+ let desc = String(describing: error).lowercased()+ return desc.contains("closed")+ || desc.contains("ioerror")+ || desc.contains("connection")+ || desc.contains("channel")+ }++ private func startKeepalive() {+ keepaliveTask?.cancel()+ keepaliveTask = Task { [weak self] in+ while !Task.isCancelled {+ try? await Task.sleep(for: MySQLAdapter.keepaliveInterval)+ guard let self, !Task.isCancelled else { return }+ // If connection died, proactively heal so the next user query is fast.+ if let conn = self.connection, !conn.isClosed {+ _ = try? await conn.simpleQuery("SELECT 1").get()+ } else if self.storedConfig != nil {+ try? await self.ensureLive()+ }+ }+ }+ }++ // MARK: - Helpers++ private func detectQueryType(_ upper: String) -> QueryType {+ if upper.hasPrefix("SELECT") || upper.hasPrefix("EXPLAIN") || upper.hasPrefix("SHOW") || upper.hasPrefix("DESCRIBE") || upper.hasPrefix("WITH") { return .select }+ if upper.hasPrefix("INSERT") { return .insert }+ if upper.hasPrefix("UPDATE") { return .update }+ if upper.hasPrefix("DELETE") { return .delete }+ if upper.hasPrefix("CREATE") || upper.hasPrefix("ALTER") || upper.hasPrefix("DROP") { return .ddl }+ return .other+ }++ private func decodeData(_ data: MySQLData, columnType: MySQLProtocol.DataType) -> RowValue {+ if data.buffer == nil { return .null }++ switch columnType {+ case .tiny:+ if let v = data.bool { return .boolean(v) }+ if let v = data.int64 { return .integer(v) }+ return data.string.map { .string($0) } ?? .null+ case .short, .long, .longlong, .int24:+ if let v = data.int64 { return .integer(v) }+ if data.isUnsigned, let v = data.uint64 { return .integer(Int64(bitPattern: v)) }+ return data.string.map { .string($0) } ?? .null+ case .float, .double, .decimal, .newdecimal:+ if let v = data.double { return .double(v) }+ return data.string.map { .string($0) } ?? .null+ case .date, .datetime, .timestamp:+ if let v = data.date { return .date(v) }+ return data.string.map { .string($0) } ?? .null+ case .time, .year:+ return data.string.map { .string($0) } ?? .null+ case .json:+ return data.string.map { .json($0) } ?? .null+ case .blob, .tinyBlob, .mediumBlob, .longBlob:+ if let buf = data.buffer {+ return .data(Data(buf.readableBytesView))+ }+ return .null+ case .varchar, .varString, .string, .enum, .set:+ return data.string.map { .string($0) } ?? .null+ default:+ return data.string.map { .string($0) } ?? .null+ }+ }++ private func mysqlDataTypeName(_ type: MySQLProtocol.DataType) -> String {+ switch type {+ case .tiny: return "TINYINT"+ case .short: return "SMALLINT"+ case .long: return "INT"+ case .longlong: return "BIGINT"+ case .int24: return "MEDIUMINT"+ case .float: return "FLOAT"+ case .double: return "DOUBLE"+ case .decimal, .newdecimal: return "DECIMAL"+ case .varchar, .varString: return "VARCHAR"+ case .string: return "CHAR"+ case .blob: return "BLOB"+ case .tinyBlob: return "TINYBLOB"+ case .mediumBlob: return "MEDIUMBLOB"+ case .longBlob: return "LONGBLOB"+ case .date: return "DATE"+ case .datetime: return "DATETIME"+ case .timestamp: return "TIMESTAMP"+ case .time: return "TIME"+ case .year: return "YEAR"+ case .json: return "JSON"+ case .enum: return "ENUM"+ case .set: return "SET"+ default: return "UNKNOWN"+ }+ }++ private func inlineValue(_ value: RowValue) -> String {+ switch value {+ case .null: return "NULL"+ case .string(let v): return "'\(escapeSQL(v))'"+ case .integer(let v): return "\(v)"+ case .double(let v): return "\(v)"+ case .boolean(let v): return v ? "1" : "0"+ case .date(let v): return "'\(ISO8601DateFormatter().string(from: v))'"+ case .uuid(let v): return "'\(v.uuidString)'"+ case .json(let v): return "'\(escapeSQL(v))'"+ case .data: return "NULL"+ case .array: return "NULL"+ }+ }++ /// Escape a string value for safe inclusion in a single-quoted SQL literal.+ /// Handles all special characters that MySQL interprets within string literals.+ private func escapeSQL(_ str: String) -> String {+ var result = ""+ result.reserveCapacity(str.count)+ for char in str {+ switch char {+ case "\0": result += "\\0"+ case "\n": result += "\\n"+ case "\r": result += "\\r"+ case "\\": result += "\\\\"+ case "'": result += "''"+ case "\"": result += "\\\""+ case "\u{1a}": result += "\\Z" // Ctrl+Z / SUB+ default: result.append(char)+ }+ }+ return result+ }++ /// Quote an identifier (table, column, schema name) using backticks with proper escaping.+ private func quoteIdentifier(_ name: String) -> String {+ "`\(name.replacingOccurrences(of: "`", with: "``"))`"+ }+}diff --git a/macos/Data/Adapters/PostgreSQL/PostgreSQLAdapter.swift b/macos/Data/Adapters/PostgreSQL/PostgreSQLAdapter.swiftnew file mode 100644index 0000000..a501003--- /dev/null+++ b/macos/Data/Adapters/PostgreSQL/PostgreSQLAdapter.swift@@ -0,0 +1,861 @@+// PostgreSQLAdapter.swift+// Gridex+//+// PostgreSQL database adapter using PostgresNIO.++import Foundation+import PostgresNIO+import NIOCore+import NIOPosix+import NIOSSL++final class PostgreSQLAdapter: DatabaseAdapter, SchemaInspectable, @unchecked Sendable {+ let databaseType: DatabaseType = .postgresql+ private(set) var isConnected: Bool = false+ private var client: PostgresClient?+ private var clientTask: Task<Void, Never>?+ private let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 2)++ deinit {+ clientTask?.cancel()+ }++ // MARK: - Connection++ func connect(config: ConnectionConfig, password: String?) async throws {+ let host = config.host ?? "localhost"+ let port = config.port ?? 5432+ let username = config.username ?? "postgres"+ let database = config.database ?? username++ let tlsConfig: PostgresClient.Configuration.TLS+ if config.sslEnabled {+ var tls = TLSConfiguration.makeClientConfiguration()+ tls.certificateVerification = .none+ tlsConfig = .prefer(tls)+ } else {+ tlsConfig = .disable+ }++ let pgConfig = PostgresClient.Configuration(+ host: host,+ port: port,+ username: username,+ password: password,+ database: database,+ tls: tlsConfig+ )++ let newClient = PostgresClient(configuration: pgConfig)+ self.client = newClient++ // PostgresClient requires run() in a background task+ self.clientTask = Task { await newClient.run() }++ // Verify the connection works+ _ = try await newClient.query("SELECT 1")+ isConnected = true+ }++ func disconnect() async throws {+ clientTask?.cancel()+ clientTask = nil+ client = nil+ isConnected = false+ }++ func testConnection(config: ConnectionConfig, password: String?) async throws -> Bool {+ let adapter = PostgreSQLAdapter()+ do {+ try await adapter.connect(config: config, password: password)+ try await adapter.disconnect()+ return true+ } catch {+ try? await adapter.disconnect()+ throw error+ }+ }++ // MARK: - Query Execution++ func execute(query: String, parameters: [QueryParameter]?) async throws -> QueryResult {+ try ensureConnected()+ let startTime = CFAbsoluteTimeGetCurrent()+ let upper = query.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()+ let queryType = detectQueryType(upper)+ let isSelect = queryType == .select || upper.hasPrefix("SHOW") || upper.hasPrefix("EXPLAIN")++ guard let client else { throw GridexError.queryExecutionFailed("No connection") }++ do {+ let pgQuery = PostgresQuery(unsafeSQL: query)+ let rows = try await client.query(pgQuery)+ let columns = rows.columns.map { col in+ ColumnHeader(name: col.name, dataType: col.dataType.description)+ }++ if isSelect {+ var resultRows: [[RowValue]] = []+ for try await row in rows {+ var rowValues: [RowValue] = []+ for (cell, meta) in zip(row, rows.columns) {+ rowValues.append(decodeCell(cell, dataType: meta.dataType))+ }+ resultRows.append(rowValues)+ }+ let duration = CFAbsoluteTimeGetCurrent() - startTime+ return QueryResult(columns: columns, rows: resultRows, rowsAffected: resultRows.count, executionTime: duration, queryType: queryType)+ } else {+ var count = 0+ for try await _ in rows { count += 1 }+ let duration = CFAbsoluteTimeGetCurrent() - startTime+ return QueryResult(columns: columns, rows: [], rowsAffected: count, executionTime: duration, queryType: queryType)+ }+ } catch {+ throw GridexError.queryExecutionFailed(Self.formatPostgresError(error))+ }+ }++ /// Extract a human-readable message from a PSQLError (which doesn't implement LocalizedError well).+ static func formatPostgresError(_ error: Error) -> String {+ if let pgError = error as? PSQLError {+ var parts: [String] = []+ if let msg = pgError.serverInfo?[.message] {+ parts.append(msg)+ }+ if let detail = pgError.serverInfo?[.detail] {+ parts.append("Detail: \(detail)")+ }+ if let hint = pgError.serverInfo?[.hint] {+ parts.append("Hint: \(hint)")+ }+ if let position = pgError.serverInfo?[.position] {+ parts.append("Position: \(position)")+ }+ if let sqlState = pgError.serverInfo?[.sqlState] {+ parts.append("SQLSTATE: \(sqlState)")+ }+ if !parts.isEmpty {+ return parts.joined(separator: "\n")+ }+ return String(describing: pgError)+ }+ return error.localizedDescription+ }++ func executeRaw(sql: String) async throws -> QueryResult {+ try await execute(query: sql, parameters: nil)+ }++ func executeWithRowValues(sql: String, parameters: [RowValue]) async throws -> QueryResult {+ try ensureConnected()+ guard let client else { throw GridexError.queryExecutionFailed("No connection") }++ let startTime = CFAbsoluteTimeGetCurrent()+ let upper = sql.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()+ let queryType = detectQueryType(upper)++ var bindings = PostgresBindings(capacity: parameters.count)+ for param in parameters {+ appendBinding(param, to: &bindings)+ }++ let pgQuery = PostgresQuery(unsafeSQL: sql, binds: bindings)+ let rows = try await client.query(pgQuery)+ let columns = rows.columns.map { col in+ ColumnHeader(name: col.name, dataType: col.dataType.description)+ }++ var resultRows: [[RowValue]] = []+ for try await row in rows {+ var rowValues: [RowValue] = []+ for (cell, meta) in zip(row, rows.columns) {+ rowValues.append(decodeCell(cell, dataType: meta.dataType))+ }+ resultRows.append(rowValues)+ }++ let duration = CFAbsoluteTimeGetCurrent() - startTime+ return QueryResult(columns: columns, rows: resultRows, rowsAffected: resultRows.count, executionTime: duration, queryType: queryType)+ }++ private func appendBinding(_ value: RowValue, to bindings: inout PostgresBindings) {+ switch value {+ case .null:+ bindings.appendNull()+ case .string(let v):+ bindings.append(v)+ case .integer(let v):+ bindings.append(v)+ case .double(let v):+ bindings.append(v)+ case .boolean(let v):+ bindings.append(v)+ case .date(let v):+ bindings.append(v)+ case .uuid(let v):+ bindings.append(v)+ case .json(let v):+ bindings.append(v)+ case .data(let v):+ var buf = ByteBuffer()+ buf.writeBytes(v)+ bindings.append(buf)+ case .array(let v):+ bindings.append(v.map(\.description).joined(separator: ","))+ }+ }++ // MARK: - Schema Inspection++ func listDatabases() async throws -> [String] {+ let result = try await executeRaw(sql: "SELECT datname FROM pg_database WHERE datistemplate = false ORDER BY datname")+ return result.rows.compactMap { $0.first?.stringValue }+ }++ func listSchemas(database: String?) async throws -> [String] {+ let result = try await executeRaw(sql: """+ SELECT schema_name FROM information_schema.schemata+ WHERE schema_name NOT IN ('pg_catalog', 'information_schema', 'pg_toast')+ ORDER BY schema_name+ """)+ return result.rows.compactMap { $0.first?.stringValue }+ }++ func listTables(schema: String?) async throws -> [TableInfo] {+ let schemaFilter = schema ?? "public"+ let result = try await executeParameterized(sql: """+ SELECT t.table_name,+ (SELECT reltuples::bigint FROM pg_class c+ JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE c.relname = t.table_name AND n.nspname = $1)+ FROM information_schema.tables t+ WHERE t.table_schema = $1 AND t.table_type = 'BASE TABLE'+ ORDER BY t.table_name+ """, params: [schemaFilter])+ return result.rows.compactMap { row -> TableInfo? in+ guard let name = row.first?.stringValue else { return nil }+ let count = row.count > 1 ? row[1].intValue : nil+ return TableInfo(name: name, schema: schemaFilter, type: .table, estimatedRowCount: count)+ }+ }++ func listViews(schema: String?) async throws -> [ViewInfo] {+ let schemaFilter = schema ?? "public"+ let result = try await executeParameterized(sql: """+ SELECT table_name, view_definition, false AS is_materialized+ FROM information_schema.views+ WHERE table_schema = $1+ UNION ALL+ SELECT matviewname, definition, true+ FROM pg_matviews+ WHERE schemaname = $1+ ORDER BY table_name+ """, params: [schemaFilter])++ return result.rows.compactMap { row -> ViewInfo? in+ guard let name = row[0].stringValue else { return nil }+ let def = row[1].stringValue+ let isMat = row[2].stringValue == "true" || row[2].stringValue == "t"+ return ViewInfo(name: name, schema: schemaFilter, definition: def, isMaterialized: isMat)+ }+ }++ func describeTable(name: String, schema: String?) async throws -> TableDescription {+ let schemaFilter = schema ?? "public"++ async let colsTask = describeColumns(table: name, schema: schemaFilter)+ async let constraintsTask = listAllConstraints(table: name, schema: schemaFilter)+ async let indexesTask = listIndexes(table: name, schema: schemaFilter)++ let cols = try await colsTask+ let constraints = try await constraintsTask+ let indexes = try await indexesTask++ // Merge check constraints into columns+ var columns = cols.columns+ for (colName, checkExpr) in constraints.checks {+ if let idx = columns.firstIndex(where: { $0.name == colName }) {+ columns[idx].checkConstraint = checkExpr+ }+ }++ return TableDescription(+ name: name, schema: schemaFilter, columns: columns,+ indexes: indexes, foreignKeys: constraints.foreignKeys, constraints: [],+ comment: cols.tableComment, estimatedRowCount: cols.estimatedRowCount+ )+ }++ static func shortenPgType(_ raw: String) -> String {+ switch raw {+ case "timestamp without time zone": return "timestamp"+ case "timestamp with time zone": return "timestamptz"+ case "time without time zone": return "time"+ case "time with time zone": return "timetz"+ case "integer": return "int4"+ case "smallint": return "int2"+ case "bigint": return "int8"+ case "real": return "float4"+ case "double precision": return "float8"+ case "boolean": return "bool"+ default: break+ }+ if raw.hasPrefix("character varying") {+ return raw.replacingOccurrences(of: "character varying", with: "varchar")+ }+ if raw.hasPrefix("character") {+ return raw.replacingOccurrences(of: "character", with: "char")+ }+ return raw+ }++ // MARK: - Query 1: Columns + PK + defaults + comments + meta (no FK/check joins)++ private func describeColumns(table: String, schema: String) async throws -> (columns: [ColumnInfo], tableComment: String?, estimatedRowCount: Int?) {+ let result = try await executeParameterized(sql: """+ SELECT a.attname,+ format_type(a.atttypid, a.atttypmod),+ NOT a.attnotnull,+ pg_get_expr(d.adbin, d.adrelid),+ a.attnum,+ CASE WHEN a.atttypid IN (1042, 1043) AND a.atttypmod > 0 THEN a.atttypmod - 4 END,+ CASE WHEN pk.conkey @> ARRAY[a.attnum] THEN true ELSE false END,+ col_description(cls.oid, a.attnum),+ cls.reltuples::bigint,+ obj_description(cls.oid)+ FROM pg_attribute a+ JOIN pg_class cls ON cls.oid = a.attrelid+ JOIN pg_namespace ns ON ns.oid = cls.relnamespace+ LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum+ LEFT JOIN pg_constraint pk ON pk.conrelid = cls.oid AND pk.contype = 'p'+ WHERE cls.relname = $1 AND ns.nspname = $2+ AND a.attnum > 0 AND NOT a.attisdropped+ ORDER BY a.attnum+ """, params: [table, schema])++ var columns: [ColumnInfo] = []+ var rowCount: Int?+ var tableComment: String?++ for row in result.rows {+ let colName = row[0].stringValue ?? ""+ if columns.contains(where: { $0.name == colName }) { continue }++ let dataType = Self.shortenPgType(row[1].stringValue ?? "text")+ let nullable = row[2].stringValue == "t" || row[2].stringValue == "true"+ let defVal = row[3].stringValue+ let ordinal = row[4].intValue ?? 0+ let maxLen = row[5].intValue+ let isPK = row[6].stringValue == "t" || row[6].stringValue == "true"+ let comment = row[7].stringValue++ columns.append(ColumnInfo(+ name: colName, dataType: dataType, isNullable: nullable, defaultValue: defVal,+ isPrimaryKey: isPK, isAutoIncrement: defVal?.hasPrefix("nextval(") == true,+ comment: comment, ordinalPosition: ordinal, characterMaxLength: maxLen+ ))++ if rowCount == nil { rowCount = row[8].intValue }+ if tableComment == nil { tableComment = row[9].stringValue }+ }++ return (columns, tableComment, rowCount)+ }++ // MARK: - Query 2: All constraints (FK + check) in one simple query++ private func listAllConstraints(table: String, schema: String) async throws -> (foreignKeys: [ForeignKeyInfo], checks: [(String, String)]) {+ let result = try await executeParameterized(sql: """+ SELECT con.contype,+ con.conname,+ con.conkey,+ pg_get_constraintdef(con.oid),+ ref_cls.relname,+ (SELECT string_agg(a.attname, ',' ORDER BY array_position(con.confkey, a.attnum))+ FROM pg_attribute a WHERE a.attrelid = con.confrelid AND a.attnum = ANY(con.confkey)),+ (SELECT string_agg(a.attname, ',' ORDER BY array_position(con.conkey, a.attnum))+ FROM pg_attribute a WHERE a.attrelid = con.conrelid AND a.attnum = ANY(con.conkey)),+ con.confdeltype,+ con.confupdtype+ FROM pg_constraint con+ JOIN pg_class cls ON cls.oid = con.conrelid+ JOIN pg_namespace ns ON ns.oid = cls.relnamespace+ LEFT JOIN pg_class ref_cls ON ref_cls.oid = con.confrelid+ WHERE cls.relname = $1 AND ns.nspname = $2+ AND con.contype IN ('f', 'c')+ ORDER BY con.conname+ """, params: [table, schema])++ var fks: [ForeignKeyInfo] = []+ var checks: [(String, String)] = []++ for row in result.rows {+ let contype = row[0].stringValue ?? ""+ let conname = row[1].stringValue ?? ""++ if contype == "f" {+ let refTable = row[4].stringValue ?? ""+ let refCols = splitCols(row[5].stringValue)+ let localCols = splitCols(row[6].stringValue)+ let onDelete = pgFKAction(row[7].stringValue)+ let onUpdate = pgFKAction(row[8].stringValue)+ fks.append(ForeignKeyInfo(name: conname, columns: localCols, referencedTable: refTable, referencedColumns: refCols, onDelete: onDelete, onUpdate: onUpdate))+ } else if contype == "c" {+ let conDef = row[3].stringValue ?? ""+ let localCols = splitCols(row[6].stringValue)+ // Strip "CHECK (...)" wrapper+ let expr: String+ if conDef.hasPrefix("CHECK (") && conDef.hasSuffix(")") {+ expr = String(conDef.dropFirst(7).dropLast(1))+ } else {+ expr = conDef+ }+ for col in localCols {+ checks.append((col, expr))+ }+ }+ }++ return (fks, checks)+ }++ /// Parse PostgreSQL array string like "{a,b,c}" into [String]+ private func parseArrayString(_ raw: String?) -> [String] {+ guard let raw, raw.hasPrefix("{") && raw.hasSuffix("}") else {+ return raw?.split(separator: ",").map(String.init) ?? []+ }+ return String(raw.dropFirst().dropLast()).split(separator: ",").map { String($0) }+ }++ /// Split comma-separated column names from string_agg result+ private func splitCols(_ raw: String?) -> [String] {+ guard let raw, !raw.isEmpty else { return [] }+ return raw.split(separator: ",").map { String($0).trimmingCharacters(in: .whitespaces) }+ }++ func listIndexes(table: String, schema: String?) async throws -> [IndexInfo] {+ let schemaFilter = schema ?? "public"+ // Use pg_get_indexdef + regex parsing (faster, no subqueries)+ let result = try await executeParameterized(sql: """+ SELECT ix.relname,+ upper(am.amname),+ i.indisunique,+ pg_get_indexdef(i.indexrelid),+ obj_description(ix.oid)+ FROM pg_index i+ JOIN pg_class t ON t.oid = i.indrelid+ JOIN pg_class ix ON ix.oid = i.indexrelid+ JOIN pg_namespace n ON t.relnamespace = n.oid+ JOIN pg_am am ON ix.relam = am.oid+ WHERE t.relname = $1 AND n.nspname = $2+ ORDER BY ix.relname+ """, params: [table, schemaFilter])++ return result.rows.compactMap { row -> IndexInfo? in+ guard let name = row[0].stringValue else { return nil }+ let type = row[1].stringValue+ let unique = row[2].stringValue == "t" || row[2].stringValue == "true"+ let indexDef = row[3].stringValue ?? ""+ let comment = row[4].stringValue++ // Parse columns from indexdef: "CREATE INDEX ... ON ... USING btree (col1, col2)"+ let cols: [String]+ if let openParen = indexDef.range(of: "("),+ let closeParen = indexDef.range(of: ")", options: .backwards) {+ let colStr = indexDef[openParen.upperBound..<closeParen.lowerBound]+ cols = colStr.split(separator: ",").map { String($0.trimmingCharacters(in: .whitespaces)) }+ } else {+ cols = []+ }++ // Parse WHERE condition+ let condition: String?+ if let whereRange = indexDef.range(of: " WHERE ", options: .caseInsensitive) {+ condition = String(indexDef[whereRange.upperBound...])+ } else {+ condition = nil+ }++ // Parse INCLUDE+ let include: String?+ if let includeRange = indexDef.range(of: " INCLUDE ", options: .caseInsensitive) {+ let afterInclude = indexDef[includeRange.upperBound...]+ if let iParen = afterInclude.range(of: "("),+ let iClose = afterInclude.range(of: ")") {+ include = String(afterInclude[iParen.upperBound..<iClose.lowerBound])+ } else {+ include = nil+ }+ } else {+ include = nil+ }++ return IndexInfo(name: name, columns: cols, isUnique: unique, type: type, tableName: table, condition: condition, include: include, comment: comment)+ }+ }++ func listForeignKeys(table: String, schema: String?) async throws -> [ForeignKeyInfo] {+ let schemaFilter = schema ?? "public"+ let result = try await executeParameterized(sql: """+ SELECT con.conname,+ att.attname AS column_name,+ ref_cls.relname AS foreign_table,+ ref_att.attname AS foreign_column,+ con.confdeltype,+ con.confupdtype+ FROM pg_constraint con+ JOIN pg_class cls ON cls.oid = con.conrelid+ JOIN pg_namespace ns ON ns.oid = cls.relnamespace+ JOIN pg_attribute att ON att.attrelid = con.conrelid AND att.attnum = ANY(con.conkey)+ JOIN pg_class ref_cls ON ref_cls.oid = con.confrelid+ JOIN pg_attribute ref_att ON ref_att.attrelid = con.confrelid AND ref_att.attnum = ANY(con.confkey)+ WHERE con.contype = 'f'+ AND ns.nspname = $1 AND cls.relname = $2+ ORDER BY con.conname+ """, params: [schemaFilter, table])++ return result.rows.compactMap { row -> ForeignKeyInfo? in+ let name = row[0].stringValue+ guard let col = row[1].stringValue,+ let refTable = row[2].stringValue,+ let refCol = row[3].stringValue else { return nil }+ let onDelete = pgFKAction(row[4].stringValue)+ let onUpdate = pgFKAction(row[5].stringValue)+ return ForeignKeyInfo(name: name, columns: [col], referencedTable: refTable, referencedColumns: [refCol], onDelete: onDelete, onUpdate: onUpdate)+ }+ }++ private func pgFKAction(_ code: String?) -> ForeignKeyAction {+ switch code {+ case "c": return .cascade+ case "n": return .setNull+ case "d": return .setDefault+ case "r": return .restrict+ default: return .noAction+ }+ }++ func listFunctions(schema: String?) async throws -> [String] {+ let schemaFilter = schema ?? "public"+ let result = try await executeParameterized(sql: """+ SELECT p.proname || '(' || pg_get_function_identity_arguments(p.oid) || ')'+ FROM pg_proc p+ JOIN pg_namespace n ON p.pronamespace = n.oid+ WHERE n.nspname = $1+ AND p.prokind IN ('f', 'p')+ ORDER BY p.proname+ """, params: [schemaFilter])+ return result.rows.compactMap { $0[0].stringValue }+ }++ func getFunctionSource(name: String, schema: String?) async throws -> String {+ let schemaFilter = schema ?? "public"+ // name may be "funcname(arg_types)" or just "funcname"+ let result: QueryResult+ if name.contains("(") {+ // Match exact overload by full signature+ result = try await executeParameterized(sql: """+ SELECT pg_get_functiondef(p.oid)+ FROM pg_proc p+ JOIN pg_namespace n ON p.pronamespace = n.oid+ WHERE n.nspname = $1+ AND p.proname || '(' || pg_get_function_identity_arguments(p.oid) || ')' = $2+ LIMIT 1+ """, params: [schemaFilter, name])+ } else {+ result = try await executeParameterized(sql: """+ SELECT pg_get_functiondef(p.oid)+ FROM pg_proc p+ JOIN pg_namespace n ON p.pronamespace = n.oid+ WHERE n.nspname = $1 AND p.proname = $2+ LIMIT 1+ """, params: [schemaFilter, name])+ }+ guard let source = result.rows.first?[0].stringValue else {+ throw GridexError.queryExecutionFailed("Function '\(name)' not found")+ }+ return source+ }++ // MARK: - Data Manipulation++ func insertRow(table: String, schema: String?, values: [String: RowValue]) async throws -> QueryResult {+ let d = SQLDialect.postgresql+ let schemaPrefix = schema.map { d.quoteIdentifier($0) + "." } ?? ""+ let cols = values.keys.map { d.quoteIdentifier($0) }.joined(separator: ", ")+ let placeholders = (1...values.count).map { "$\($0)" }.joined(separator: ", ")+ let sql = "INSERT INTO \(schemaPrefix)\(d.quoteIdentifier(table)) (\(cols)) VALUES (\(placeholders))"+ return try await executeRaw(sql: buildInlineSQL(sql: sql, values: Array(values.values)))+ }++ func updateRow(table: String, schema: String?, set values: [String: RowValue], where conditions: [String: RowValue]) async throws -> QueryResult {+ let d = SQLDialect.postgresql+ let schemaPrefix = schema.map { d.quoteIdentifier($0) + "." } ?? ""+ let setClauses = values.compactMap { k, v in "\(d.quoteIdentifier(k)) = \(inlineValue(k, v))" }.joined(separator: ", ")+ let whereClauses = conditions.compactMap { k, v in "\(d.quoteIdentifier(k)) = \(inlineValue(k, v))" }.joined(separator: " AND ")+ return try await executeRaw(sql: "UPDATE \(schemaPrefix)\(d.quoteIdentifier(table)) SET \(setClauses) WHERE \(whereClauses)")+ }++ func deleteRow(table: String, schema: String?, where conditions: [String: RowValue]) async throws -> QueryResult {+ let d = SQLDialect.postgresql+ let schemaPrefix = schema.map { d.quoteIdentifier($0) + "." } ?? ""+ let whereClauses = conditions.compactMap { k, v in "\(d.quoteIdentifier(k)) = \(inlineValue(k, v))" }.joined(separator: " AND ")+ return try await executeRaw(sql: "DELETE FROM \(schemaPrefix)\(d.quoteIdentifier(table)) WHERE \(whereClauses)")+ }++ func beginTransaction() async throws { _ = try await executeRaw(sql: "BEGIN") }+ func commitTransaction() async throws { _ = try await executeRaw(sql: "COMMIT") }+ func rollbackTransaction() async throws { _ = try await executeRaw(sql: "ROLLBACK") }++ // MARK: - Pagination++ func fetchRows(table: String, schema: String?, columns: [String]?, where filter: FilterExpression?, orderBy: [QuerySortDescriptor]?, limit: Int, offset: Int) async throws -> QueryResult {+ let d = SQLDialect.postgresql+ let schemaPrefix = schema.map { d.quoteIdentifier($0) + "." } ?? ""+ let colList = columns?.map { d.quoteIdentifier($0) }.joined(separator: ", ") ?? "*"+ var sql = "SELECT \(colList) FROM \(schemaPrefix)\(d.quoteIdentifier(table))"+ if let filter, !filter.conditions.isEmpty {+ sql += " WHERE \(filter.toSQL(dialect: d))"+ }+ if let orderBy, !orderBy.isEmpty {+ sql += " ORDER BY " + orderBy.map { $0.toSQL(dialect: d) }.joined(separator: ", ")+ }+ sql += " LIMIT \(limit) OFFSET \(offset)"+ return try await executeRaw(sql: sql)+ }++ func serverVersion() async throws -> String {+ let r = try await executeRaw(sql: "SELECT version()")+ return r.rows.first?.first?.stringValue ?? "PostgreSQL"+ }++ func currentDatabase() async throws -> String? {+ let r = try await executeRaw(sql: "SELECT current_database()")+ return r.rows.first?.first?.stringValue+ }++ // MARK: - SchemaInspectable++ func fullSchemaSnapshot(database: String?) async throws -> SchemaSnapshot {+ let schemas = try await listSchemas(database: database)+ var schemaInfos: [SchemaInfo] = []+ for schemaName in schemas {+ let tables = try await listTables(schema: schemaName)+ let descs: [TableDescription] = try await withThrowingTaskGroup(of: TableDescription.self) { group in+ for t in tables {+ let name = t.name+ group.addTask { try await self.describeTable(name: name, schema: schemaName) }+ }+ var results: [TableDescription] = []+ for try await desc in group { results.append(desc) }+ return results+ }+ let views = try await listViews(schema: schemaName)+ schemaInfos.append(SchemaInfo(name: schemaName, tables: descs, views: views, functions: [], enums: []))+ }+ let dbName = try await currentDatabase() ?? "postgres"+ return SchemaSnapshot(databaseName: dbName, databaseType: .postgresql, schemas: schemaInfos, capturedAt: Date())+ }++ func columnStatistics(table: String, schema: String?, sampleSize: Int) async throws -> [ColumnStatistics] {+ let schemaFilter = schema ?? "public"+ let colResult = try await describeColumns(table: table, schema: schemaFilter)+ let cols = colResult.columns+ var stats: [ColumnStatistics] = []+ for col in cols {+ let q = SQLDialect.postgresql.quoteIdentifier(col.name)+ let tbl = "\(SQLDialect.postgresql.quoteIdentifier(schemaFilter)).\(SQLDialect.postgresql.quoteIdentifier(table))"+ let r = try await executeRaw(sql: """+ SELECT COUNT(DISTINCT \(q)),+ CAST(SUM(CASE WHEN \(q) IS NULL THEN 1 ELSE 0 END) AS DOUBLE PRECISION) / GREATEST(COUNT(*), 1),+ MIN(\(q)::text), MAX(\(q)::text)+ FROM \(tbl)+ """)+ if let row = r.rows.first {+ stats.append(ColumnStatistics(+ columnName: col.name,+ distinctCount: row[0].intValue,+ nullRatio: row[1].doubleValue,+ topValues: nil,+ minValue: row[2].stringValue,+ maxValue: row[3].stringValue+ ))+ }+ }+ return stats+ }++ func tableRowCount(table: String, schema: String?) async throws -> Int {+ let schemaFilter = schema ?? "public"+ // Use fast estimated count from pg_class instead of slow COUNT(*)+ let r = try await executeParameterized(sql: """+ SELECT reltuples::bigint FROM pg_class c+ JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE c.relname = $1 AND n.nspname = $2+ """, params: [table, schemaFilter])+ return r.rows.first?.first?.intValue ?? 0+ }++ func tableSizeBytes(table: String, schema: String?) async throws -> Int64? {+ let schemaFilter = schema ?? "public"+ let d = SQLDialect.postgresql+ let qualifiedName = "\(d.quoteIdentifier(schemaFilter)).\(d.quoteIdentifier(table))"+ let r = try await executeParameterized(sql: "SELECT pg_total_relation_size($1)", params: [qualifiedName])+ if let val = r.rows.first?.first?.intValue { return Int64(val) }+ return nil+ }++ func queryStatistics() async throws -> [QueryStatisticsEntry] { [] }++ func primaryKeyColumns(table: String, schema: String?) async throws -> [String] {+ let schemaFilter = schema ?? "public"+ let result = try await executeParameterized(sql: """+ SELECT kcu.column_name+ FROM information_schema.table_constraints tc+ JOIN information_schema.key_column_usage kcu+ ON tc.constraint_name = kcu.constraint_name AND tc.table_schema = kcu.table_schema+ WHERE tc.constraint_type = 'PRIMARY KEY'+ AND tc.table_schema = $1 AND tc.table_name = $2+ ORDER BY kcu.ordinal_position+ """, params: [schemaFilter, table])+ return result.rows.compactMap { $0.first?.stringValue }+ }++ // MARK: - Helpers++ /// Execute a parameterized query with `$1, $2, ...` placeholders and String bindings.+ /// Use this for metadata queries where values come from user input.+ private func executeParameterized(sql: String, params: [String]) async throws -> QueryResult {+ try ensureConnected()+ guard let client else { throw GridexError.queryExecutionFailed("No connection") }++ let startTime = CFAbsoluteTimeGetCurrent()+ var bindings = PostgresBindings(capacity: params.count)+ for param in params {+ bindings.append(param)+ }+ let pgQuery = PostgresQuery(unsafeSQL: sql, binds: bindings)+ let rows = try await client.query(pgQuery)+ let columns = rows.columns.map { col in+ ColumnHeader(name: col.name, dataType: col.dataType.description)+ }+ var resultRows: [[RowValue]] = []+ for try await row in rows {+ var rowValues: [RowValue] = []+ for (cell, meta) in zip(row, rows.columns) {+ rowValues.append(decodeCell(cell, dataType: meta.dataType))+ }+ resultRows.append(rowValues)+ }+ let duration = CFAbsoluteTimeGetCurrent() - startTime+ return QueryResult(columns: columns, rows: resultRows, rowsAffected: resultRows.count, executionTime: duration, queryType: .select)+ }++ private func ensureConnected() throws {+ guard isConnected, client != nil else {+ throw GridexError.queryExecutionFailed("Not connected to PostgreSQL")+ }+ }++ private func detectQueryType(_ upper: String) -> QueryType {+ if upper.hasPrefix("SELECT") || upper.hasPrefix("EXPLAIN") || upper.hasPrefix("WITH") { return .select }+ if upper.hasPrefix("INSERT") { return .insert }+ if upper.hasPrefix("UPDATE") { return .update }+ if upper.hasPrefix("DELETE") { return .delete }+ if upper.hasPrefix("CREATE") || upper.hasPrefix("ALTER") || upper.hasPrefix("DROP") { return .ddl }+ return .other+ }++ private func decodeCell(_ cell: PostgresCell, dataType: PostgresDataType) -> RowValue {+ if cell.bytes == nil { return .null }+ do {+ switch dataType {+ case .bool:+ return .boolean(try cell.decode(Bool.self))+ case .int2:+ return .integer(Int64(try cell.decode(Int16.self)))+ case .int4:+ return .integer(Int64(try cell.decode(Int32.self)))+ case .int8:+ return .integer(try cell.decode(Int64.self))+ case .float4:+ return .double(Double(try cell.decode(Float.self)))+ case .float8:+ return .double(try cell.decode(Double.self))+ case .numeric:+ // numeric binary format requires Decimal decoder, not String+ let decimal = try cell.decode(Decimal.self)+ let str = "\(decimal)"+ if let d = Double(str) { return .double(d) }+ return .string(str)+ case .money:+ // money is stored as Int64 (cents) in binary protocol+ if var bytes = cell.bytes, bytes.readableBytes == 8,+ let cents = bytes.readInteger(as: Int64.self) {+ return .double(Double(cents) / 100.0)+ }+ return .null+ case .text, .varchar, .bpchar, .name:+ return .string(try cell.decode(String.self))+ case .bytea:+ var buf = try cell.decode(ByteBuffer.self)+ let data = buf.readData(length: buf.readableBytes) ?? Data()+ return .data(data)+ case .timestamp, .timestamptz, .date:+ return .date(try cell.decode(Date.self))+ case .time:+ // time/timetz: decode as String via text representation+ if let s = try? cell.decode(String.self) { return .string(s) }+ return .null+ case .interval:+ if let s = try? cell.decode(String.self) { return .string(s) }+ return .null+ case .uuid:+ return .uuid(try cell.decode(UUID.self))+ case .json, .jsonb:+ return .json(try cell.decode(String.self))+ default:+ // Try String decoding, but validate it's not binary garbage+ if let s = try? cell.decode(String.self),+ !s.unicodeScalars.contains(where: { $0.value == 0xFFFD }) {+ return .string(s)+ }+ return .null+ }+ } catch {+ if let s = try? cell.decode(String.self),+ !s.unicodeScalars.contains(where: { $0.value == 0xFFFD }) {+ return .string(s)+ }+ return .null+ }+ }++ private func inlineValue(_ key: String, _ value: RowValue) -> String {+ switch value {+ case .null: return "NULL"+ case .string(let v): return "'\(v.replacingOccurrences(of: "'", with: "''"))'"+ case .integer(let v): return "\(v)"+ case .double(let v): return "\(v)"+ case .boolean(let v): return v ? "TRUE" : "FALSE"+ case .date(let v):+ let fmt = DateFormatter()+ fmt.dateFormat = "yyyy-MM-dd HH:mm:ss"+ fmt.timeZone = TimeZone(identifier: "UTC")+ return "'\(fmt.string(from: v))'"+ case .uuid(let v): return "'\(v.uuidString)'"+ case .json(let v): return "'\(v.replacingOccurrences(of: "'", with: "''"))'::jsonb"+ case .data: return "NULL"+ case .array: return "NULL"+ }+ }++ private func buildInlineSQL(sql: String, values: [RowValue]) -> String {+ var result = sql+ for (i, value) in values.enumerated() {+ result = result.replacingOccurrences(of: "$\(i + 1)", with: inlineValue("", value))+ }+ return result+ }+}diff --git a/macos/Data/Adapters/Redis/RedisAdapter.swift b/macos/Data/Adapters/Redis/RedisAdapter.swiftnew file mode 100644index 0000000..e9200b2--- /dev/null+++ b/macos/Data/Adapters/Redis/RedisAdapter.swift@@ -0,0 +1,938 @@+// RedisAdapter.swift+// Gridex+//+// Redis adapter — maps the key-value store into Gridex's relational model.+//+// Virtual schema:+// • "Keys" table with columns: key, type, value, ttl+// • SCAN-based pagination for fetchRows+// • executeRaw accepts raw Redis commands (space-separated)++import Foundation+import NIOCore+import NIOPosix+import NIOSSL+import RediStack++final class RedisAdapter: DatabaseAdapter, @unchecked Sendable {++ // MARK: - Properties++ let databaseType: DatabaseType = .redis+ private(set) var isConnected: Bool = false++ private var connection: RedisConnection?+ private let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)+ private var currentDB: Int = 0++ // MARK: - Connection Lifecycle++ func connect(config: ConnectionConfig, password: String?) async throws {+ let host = config.host ?? "localhost"+ let port = config.port ?? 6379+ let eventLoop = eventLoopGroup.next()++ let redisConfig = try RedisConnection.Configuration(+ hostname: host,+ port: port,+ password: (password?.isEmpty == false) ? password : nil,+ initialDatabase: config.database.flatMap { Int($0) },+ defaultLogger: .init(label: "com.gridex.redis")+ )++ // Build a ClientBootstrap — add TLS handler if sslEnabled (e.g. Upstash, rediss://)+ let bootstrap: ClientBootstrap+ if config.sslEnabled {+ let tlsConfig = TLSConfiguration.makeClientConfiguration()+ let sslContext = try NIOSSLContext(configuration: tlsConfig)+ bootstrap = ClientBootstrap(group: eventLoop)+ .channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)+ .channelInitializer { channel in+ do {+ let sslHandler = try NIOSSLClientHandler(context: sslContext, serverHostname: host)+ return channel.pipeline.addHandler(sslHandler).flatMap {+ channel.pipeline.addBaseRedisHandlers()+ }+ } catch {+ return channel.eventLoop.makeFailedFuture(error)+ }+ }+ } else {+ bootstrap = ClientBootstrap.makeRedisTCPClient(group: eventLoop)+ }++ let conn = try await RedisConnection.make(+ configuration: redisConfig,+ boundEventLoop: eventLoop,+ configuredTCPClient: bootstrap+ ).get()++ self.connection = conn+ self.currentDB = config.database.flatMap { Int($0) } ?? 0+ self.isConnected = true+ }++ func disconnect() async throws {+ connection?.close()+ isConnected = false+ connection = nil+ }++ func testConnection(config: ConnectionConfig, password: String?) async throws -> Bool {+ try await connect(config: config, password: password)+ let pong = try await sendCommand("PING")+ try await disconnect()+ return pong.string == "PONG"+ }++ // MARK: - Command Execution++ @discardableResult+ private func sendCommand(_ command: String, args: [String] = []) async throws -> RESPValue {+ guard let conn = connection else {+ throw GridexError.connectionFailed(underlying: NSError(+ domain: "Redis", code: -1,+ userInfo: [NSLocalizedDescriptionKey: "Not connected to Redis"]))+ }+ let respArgs = args.map { RESPValue(from: $0) }+ return try await conn.send(command: command, with: respArgs).get()+ }++ /// Parse a space-separated Redis command string (respecting quoted strings).+ private func parseCommand(_ raw: String) -> [String] {+ var tokens: [String] = []+ var current = ""+ var inQuote: Character?++ for ch in raw {+ if let q = inQuote {+ if ch == q { inQuote = nil } else { current.append(ch) }+ } else if ch == "\"" || ch == "'" {+ inQuote = ch+ } else if ch == " " {+ if !current.isEmpty { tokens.append(current); current = "" }+ } else {+ current.append(ch)+ }+ }+ if !current.isEmpty { tokens.append(current) }+ return tokens+ }++ // MARK: - DatabaseAdapter — Query Execution++ func execute(query: String, parameters: [QueryParameter]?) async throws -> QueryResult {+ try await executeRaw(sql: query)+ }++ func executeRaw(sql: String) async throws -> QueryResult {+ let start = CFAbsoluteTimeGetCurrent()+ let tokens = parseCommand(sql.trimmingCharacters(in: .whitespacesAndNewlines))+ guard let keyword = tokens.first?.uppercased() else {+ throw GridexError.queryExecutionFailed("Empty command")+ }+ let args = Array(tokens.dropFirst())+ let resp = try await sendCommand(keyword, args: args)+ let elapsed = CFAbsoluteTimeGetCurrent() - start++ let (columns, rows, affected) = formatRESP(resp, keyword: keyword)+ return QueryResult(+ columns: columns,+ rows: rows,+ rowsAffected: affected,+ executionTime: elapsed,+ queryType: redisQueryType(keyword)+ )+ }++ func executeWithRowValues(sql: String, parameters: [RowValue]) async throws -> QueryResult {+ try await executeRaw(sql: sql)+ }++ // MARK: - RESP → QueryResult Formatting++ private func formatRESP(_ value: RESPValue, keyword: String) -> ([ColumnHeader], [[RowValue]], Int) {+ switch value {+ case .simpleString(let buf):+ let str = buf.getString(at: 0, length: buf.readableBytes) ?? ""+ return (+ [ColumnHeader(name: "result", dataType: "string", isNullable: false, tableName: nil)],+ [[.string(str)]],+ 0+ )++ case .bulkString(let buf):+ if let buf {+ let str = buf.getString(at: 0, length: buf.readableBytes) ?? ""+ return (+ [ColumnHeader(name: "value", dataType: "string", isNullable: true, tableName: nil)],+ [[.string(str)]],+ 0+ )+ }+ return (+ [ColumnHeader(name: "value", dataType: "string", isNullable: true, tableName: nil)],+ [[.null]],+ 0+ )++ case .integer(let n):+ return (+ [ColumnHeader(name: "result", dataType: "integer", isNullable: false, tableName: nil)],+ [[.integer(Int64(n))]],+ Int(n)+ )++ case .array(let items):+ return formatArrayResponse(items, keyword: keyword)++ case .error(let err):+ return (+ [ColumnHeader(name: "error", dataType: "string", isNullable: false, tableName: nil)],+ [[.string(err.message)]],+ 0+ )++ case .null:+ return (+ [ColumnHeader(name: "value", dataType: "string", isNullable: true, tableName: nil)],+ [[.null]],+ 0+ )+ }+ }++ private func formatArrayResponse(_ items: [RESPValue], keyword: String) -> ([ColumnHeader], [[RowValue]], Int) {+ // HGETALL / CONFIG GET: alternating key-value pairs+ if ["HGETALL", "CONFIG"].contains(keyword) && items.count % 2 == 0 && !items.isEmpty {+ let cols = [+ ColumnHeader(name: "field", dataType: "string", isNullable: false, tableName: nil),+ ColumnHeader(name: "value", dataType: "string", isNullable: true, tableName: nil),+ ]+ var rows: [[RowValue]] = []+ for i in stride(from: 0, to: items.count, by: 2) {+ rows.append([respToRowValue(items[i]), respToRowValue(items[i + 1])])+ }+ return (cols, rows, 0)+ }++ // Generic array+ let cols = [+ ColumnHeader(name: "#", dataType: "integer", isNullable: false, tableName: nil),+ ColumnHeader(name: "value", dataType: "string", isNullable: true, tableName: nil),+ ]+ let rows = items.enumerated().map { (i, item) -> [RowValue] in+ [.integer(Int64(i + 1)), respToRowValue(item)]+ }+ return (cols, rows, 0)+ }++ private func respToRowValue(_ value: RESPValue) -> RowValue {+ switch value {+ case .simpleString(let buf):+ return .string(buf.getString(at: 0, length: buf.readableBytes) ?? "")+ case .bulkString(let buf):+ guard let buf else { return .null }+ return .string(buf.getString(at: 0, length: buf.readableBytes) ?? "")+ case .integer(let n):+ return .integer(Int64(n))+ case .array(let arr):+ return .string(arr.map { respToRowValue($0).stringValue ?? "" }.joined(separator: ", "))+ case .error(let err):+ return .string("ERR: \(err.message)")+ case .null:+ return .null+ }+ }++ private func redisQueryType(_ keyword: String) -> QueryType {+ switch keyword {+ case "SET", "MSET", "HSET", "LPUSH", "RPUSH", "SADD", "ZADD":+ return .insert+ case "DEL", "HDEL", "LREM", "SREM", "ZREM", "UNLINK":+ return .delete+ case "GET", "MGET", "HGETALL", "HGET", "LRANGE", "SMEMBERS", "ZRANGE",+ "KEYS", "SCAN", "INFO", "DBSIZE", "TYPE", "TTL", "PTTL":+ return .select+ default:+ return .other+ }+ }++ // MARK: - Schema Inspection (virtual)++ func listDatabases() async throws -> [String] {+ // CONFIG GET is blocked on many cloud providers (Upstash, ElastiCache).+ // Fall back to default 16 databases on error.+ do {+ let resp = try await sendCommand("CONFIG", args: ["GET", "databases"])+ if case .array(let items) = resp, items.count >= 2,+ let str = respToRowValue(items[1]).stringValue, let n = Int(str) {+ return (0..<n).map { "db\($0)" }+ }+ } catch {}+ return (0..<16).map { "db\($0)" }+ }++ func listSchemas(database: String?) async throws -> [String] { [] }++ func listTables(schema: String?) async throws -> [TableInfo] {+ [TableInfo(name: "Keys", schema: nil, type: .table, estimatedRowCount: nil)]+ }++ func listViews(schema: String?) async throws -> [ViewInfo] { [] }++ func describeTable(name: String, schema: String?) async throws -> TableDescription {+ TableDescription(+ name: "Keys",+ schema: nil,+ columns: [+ ColumnInfo(name: "key", dataType: "string", isNullable: false, defaultValue: nil,+ isPrimaryKey: true, isAutoIncrement: false, comment: nil, ordinalPosition: 1, characterMaxLength: nil),+ ColumnInfo(name: "type", dataType: "string", isNullable: false, defaultValue: nil,+ isPrimaryKey: false, isAutoIncrement: false, comment: nil, ordinalPosition: 2, characterMaxLength: nil),+ ColumnInfo(name: "value", dataType: "string", isNullable: true, defaultValue: nil,+ isPrimaryKey: false, isAutoIncrement: false, comment: nil, ordinalPosition: 3, characterMaxLength: nil),+ ColumnInfo(name: "ttl", dataType: "integer", isNullable: true, defaultValue: nil,+ isPrimaryKey: false, isAutoIncrement: false, comment: nil, ordinalPosition: 4, characterMaxLength: nil),+ ],+ indexes: [],+ foreignKeys: [],+ constraints: [],+ comment: nil,+ estimatedRowCount: nil+ )+ }++ func listIndexes(table: String, schema: String?) async throws -> [IndexInfo] { [] }+ func listForeignKeys(table: String, schema: String?) async throws -> [ForeignKeyInfo] { [] }+ func listFunctions(schema: String?) async throws -> [String] { [] }+ func getFunctionSource(name: String, schema: String?) async throws -> String { "" }++ // MARK: - Data Manipulation++ func insertRow(table: String, schema: String?, values: [String: RowValue]) async throws -> QueryResult {+ guard let key = values["key"]?.stringValue else {+ throw GridexError.queryExecutionFailed("Missing 'key' field")+ }+ let val = values["value"]?.stringValue ?? ""+ let start = CFAbsoluteTimeGetCurrent()+ try await sendCommand("SET", args: [key, val])+ return QueryResult(columns: [], rows: [], rowsAffected: 1,+ executionTime: CFAbsoluteTimeGetCurrent() - start, queryType: .insert)+ }++ func updateRow(table: String, schema: String?, set: [String: RowValue], where: [String: RowValue]) async throws -> QueryResult {+ guard let key = `where`["key"]?.stringValue else {+ throw GridexError.queryExecutionFailed("Missing 'key' in WHERE clause")+ }+ let start = CFAbsoluteTimeGetCurrent()+ if let newVal = set["value"]?.stringValue {+ try await sendCommand("SET", args: [key, newVal])+ } else if let ttl = set["ttl"]?.intValue {+ if ttl < 0 {+ try await sendCommand("PERSIST", args: [key])+ } else {+ try await sendCommand("EXPIRE", args: [key, String(ttl)])+ }+ } else {+ throw GridexError.queryExecutionFailed("Nothing to update")+ }+ return QueryResult(columns: [], rows: [], rowsAffected: 1,+ executionTime: CFAbsoluteTimeGetCurrent() - start, queryType: .update)+ }++ func deleteRow(table: String, schema: String?, where: [String: RowValue]) async throws -> QueryResult {+ guard let key = `where`["key"]?.stringValue else {+ throw GridexError.queryExecutionFailed("Missing 'key' in WHERE clause")+ }+ let start = CFAbsoluteTimeGetCurrent()+ try await sendCommand("DEL", args: [key])+ return QueryResult(columns: [], rows: [], rowsAffected: 1,+ executionTime: CFAbsoluteTimeGetCurrent() - start, queryType: .delete)+ }++ // MARK: - Transactions++ func beginTransaction() async throws {+ try await sendCommand("MULTI")+ }++ func commitTransaction() async throws {+ try await sendCommand("EXEC")+ }++ func rollbackTransaction() async throws {+ try await sendCommand("DISCARD")+ }++ // MARK: - Pagination (SCAN-based)++ func fetchRows(+ table: String,+ schema: String?,+ columns: [String]?,+ where filter: FilterExpression?,+ orderBy: [QuerySortDescriptor]?,+ limit: Int,+ offset: Int+ ) async throws -> QueryResult {+ let start = CFAbsoluteTimeGetCurrent()+ let pattern = extractPattern(from: filter) ?? "*"++ // Collect keys using SCAN (capped at 100k keys for safety)+ var cursor = 0+ var allKeys: [String] = []+ var scanIterations = 0+ repeat {+ guard connection?.isConnected == true else {+ throw GridexError.queryExecutionFailed("Connection lost during SCAN")+ }+ let resp = try await sendCommand("SCAN", args: [String(cursor), "MATCH", pattern, "COUNT", "500"])+ if case .array(let parts) = resp, parts.count == 2 {+ cursor = Int(respToRowValue(parts[0]).stringValue ?? "0") ?? 0+ if case .array(let keys) = parts[1] {+ allKeys.append(contentsOf: keys.compactMap { respToRowValue($0).stringValue })+ }+ } else { break }+ scanIterations += 1+ if allKeys.count >= 100_000 || scanIterations >= 500 { break }+ } while cursor != 0++ allKeys.sort()+ let paged = Array(allKeys.dropFirst(offset).prefix(limit))++ // Fire TYPE and TTL for all keys concurrently via NIO futures (single round-trip batch)+ guard let conn = connection else {+ throw GridexError.connectionFailed(underlying: NSError(+ domain: "Redis", code: -1, userInfo: [NSLocalizedDescriptionKey: "Not connected"]))+ }++ // Phase 1: TYPE + TTL for all keys (2 commands per key, all pipelined)+ let typeFutures = paged.map { conn.send(command: "TYPE", with: [RESPValue(from: $0)]) }+ let ttlFutures = paged.map { conn.send(command: "TTL", with: [RESPValue(from: $0)]) }++ let types = try await withCheckedThrowingContinuation { (cont: CheckedContinuation<[RESPValue], Error>) in+ EventLoopFuture.whenAllSucceed(typeFutures, on: conn.eventLoop).whenComplete {+ switch $0 {+ case .success(let v): cont.resume(returning: v)+ case .failure(let e): cont.resume(throwing: e)+ }+ }+ }+ let ttls = try await withCheckedThrowingContinuation { (cont: CheckedContinuation<[RESPValue], Error>) in+ EventLoopFuture.whenAllSucceed(ttlFutures, on: conn.eventLoop).whenComplete {+ switch $0 {+ case .success(let v): cont.resume(returning: v)+ case .failure(let e): cont.resume(throwing: e)+ }+ }+ }++ // Phase 2: fetch values based on type (pipelined)+ var valueFutures: [EventLoopFuture<RESPValue>] = []+ for (i, key) in paged.enumerated() {+ let typeStr = respToRowValue(types[i]).stringValue ?? "unknown"+ let keyResp = RESPValue(from: key)+ switch typeStr {+ case "string":+ valueFutures.append(conn.send(command: "GET", with: [keyResp]))+ case "list":+ valueFutures.append(conn.send(command: "LRANGE", with: [keyResp, RESPValue(from: "0"), RESPValue(from: "99")]))+ case "set":+ valueFutures.append(conn.send(command: "SMEMBERS", with: [keyResp]))+ case "zset":+ valueFutures.append(conn.send(command: "ZRANGE", with: [keyResp, RESPValue(from: "0"), RESPValue(from: "99"), RESPValue(from: "WITHSCORES")]))+ case "hash":+ valueFutures.append(conn.send(command: "HGETALL", with: [keyResp]))+ default:+ valueFutures.append(conn.eventLoop.makeSucceededFuture(.simpleString(ByteBuffer(string: "(\(typeStr))"))))+ }+ }++ let values = try await withCheckedThrowingContinuation { (cont: CheckedContinuation<[RESPValue], Error>) in+ EventLoopFuture.whenAllSucceed(valueFutures, on: conn.eventLoop).whenComplete {+ switch $0 {+ case .success(let v): cont.resume(returning: v)+ case .failure(let e): cont.resume(throwing: e)+ }+ }+ }++ // Assemble rows+ var rows: [[RowValue]] = []+ for (i, key) in paged.enumerated() {+ let typeStr = respToRowValue(types[i]).stringValue ?? "unknown"+ let ttlVal: RowValue = {+ if case .integer(let n) = ttls[i] { return n < 0 ? .null : .integer(Int64(n)) }+ return .null+ }()++ let value: String+ switch typeStr {+ case "string":+ value = respToRowValue(values[i]).stringValue ?? ""+ case "list", "set", "zset":+ value = formatListValue(values[i])+ case "hash":+ value = formatHashValue(values[i])+ default:+ value = respToRowValue(values[i]).stringValue ?? "(unknown)"+ }++ rows.append([.string(key), .string(typeStr), .string(value), ttlVal])+ }++ let elapsed = CFAbsoluteTimeGetCurrent() - start+ return QueryResult(+ columns: [+ ColumnHeader(name: "key", dataType: "string", isNullable: false, tableName: "Keys"),+ ColumnHeader(name: "type", dataType: "string", isNullable: false, tableName: "Keys"),+ ColumnHeader(name: "value", dataType: "string", isNullable: true, tableName: "Keys"),+ ColumnHeader(name: "ttl", dataType: "integer", isNullable: true, tableName: "Keys"),+ ],+ rows: rows,+ rowsAffected: 0,+ executionTime: elapsed,+ queryType: .select+ )+ }++ // MARK: - Database Info++ func serverVersion() async throws -> String {+ let resp = try await sendCommand("INFO", args: ["server"])+ if let info = respToRowValue(resp).stringValue,+ let line = info.split(separator: "\n").first(where: { $0.hasPrefix("redis_version:") }) {+ return String(line.split(separator: ":").last ?? "unknown")+ }+ return "unknown"+ }++ func currentDatabase() async throws -> String? {+ "db\(currentDB)"+ }++ // MARK: - Helpers++ private func extractPattern(from filter: FilterExpression?) -> String? {+ guard let filter else { return nil }+ for cond in filter.conditions {+ if cond.column == "key" {+ switch cond.op {+ case .equal:+ return cond.value.stringValue+ case .like:+ return cond.value.stringValue?+ .replacingOccurrences(of: "%", with: "*")+ .replacingOccurrences(of: "_", with: "?")+ default:+ continue+ }+ }+ }+ return nil+ }++ private func formatListValue(_ resp: RESPValue) -> String {+ if case .array(let items) = resp {+ let values = items.map { respToRowValue($0).stringValue ?? "" }+ return "[\(values.joined(separator: ", "))]"+ }+ return "[]"+ }++ private func formatHashValue(_ resp: RESPValue) -> String {+ if case .array(let items) = resp, items.count % 2 == 0 {+ var pairs: [String] = []+ for i in stride(from: 0, to: items.count, by: 2) {+ let k = respToRowValue(items[i]).stringValue ?? ""+ let v = respToRowValue(items[i + 1]).stringValue ?? ""+ pairs.append("\(k): \(v)")+ }+ return "{\(pairs.joined(separator: ", "))}"+ }+ return "{}"+ }++ // MARK: - Redis-Specific Operations++ /// Create a key with a specific Redis data type.+ func redisInsertTyped(key: String, type: RedisKeyType, data: RedisKeyData, ttl: Int? = nil) async throws {+ switch data {+ case .string(let value):+ try await sendCommand("SET", args: [key, value])+ case .hash(let fields):+ var args = [key]+ for f in fields { args.append(contentsOf: [f.field, f.value]) }+ try await sendCommand("HSET", args: args)+ case .list(let items):+ try await sendCommand("RPUSH", args: [key] + items)+ case .set(let members):+ try await sendCommand("SADD", args: [key] + members)+ case .zset(let members):+ var args = [key]+ for m in members { args.append(contentsOf: [String(m.score), m.member]) }+ try await sendCommand("ZADD", args: args)+ }+ if let ttl, ttl > 0 {+ try await sendCommand("EXPIRE", args: [key, String(ttl)])+ }+ }++ /// Fetch detailed data for a single key.+ func fetchKeyDetail(key: String) async throws -> RedisKeyDetail {+ let typeStr = try await respToRowValue(sendCommand("TYPE", args: [key])).stringValue ?? "none"+ let ttlVal = try await sendCommand("TTL", args: [key])+ let ttl: Int? = {+ if case .integer(let n) = ttlVal { return n < 0 ? nil : Int(n) }+ return nil+ }()++ let memoryBytes: Int?+ do {+ let mem = try await sendCommand("MEMORY", args: ["USAGE", key])+ if case .integer(let n) = mem { memoryBytes = Int(n) } else { memoryBytes = nil }+ } catch { memoryBytes = nil }++ let keyType = RedisKeyType(rawValue: typeStr) ?? .string+ let data: RedisKeyData+ switch keyType {+ case .string:+ let v = try await respToRowValue(sendCommand("GET", args: [key])).stringValue ?? ""+ data = .string(value: v)+ case .hash:+ let resp = try await sendCommand("HGETALL", args: [key])+ var fields: [(field: String, value: String)] = []+ if case .array(let items) = resp, items.count >= 2 {+ for i in stride(from: 0, to: items.count, by: 2) {+ fields.append((+ field: respToRowValue(items[i]).stringValue ?? "",+ value: respToRowValue(items[i + 1]).stringValue ?? ""+ ))+ }+ }+ data = .hash(fields: fields)+ case .list:+ // Cap at 10,000 items to prevent OOM+ let resp = try await sendCommand("LRANGE", args: [key, "0", "9999"])+ let items: [String] = {+ if case .array(let arr) = resp { return arr.map { respToRowValue($0).stringValue ?? "" } }+ return []+ }()+ data = .list(items: items)+ case .set:+ // SSCAN with limit to prevent OOM on huge sets+ var members: [String] = []+ var setCursor = 0+ repeat {+ let resp = try await sendCommand("SSCAN", args: [key, String(setCursor), "COUNT", "1000"])+ if case .array(let parts) = resp, parts.count == 2 {+ setCursor = Int(respToRowValue(parts[0]).stringValue ?? "0") ?? 0+ if case .array(let items) = parts[1] {+ members.append(contentsOf: items.compactMap { respToRowValue($0).stringValue })+ }+ } else { break }+ if members.count >= 10000 { break }+ } while setCursor != 0+ data = .set(members: members.sorted())+ case .zset:+ let resp = try await sendCommand("ZRANGE", args: [key, "0", "9999", "WITHSCORES"])+ var members: [(member: String, score: Double)] = []+ if case .array(let arr) = resp, arr.count >= 2 {+ for i in stride(from: 0, to: arr.count, by: 2) {+ let m = respToRowValue(arr[i]).stringValue ?? ""+ let s = Double(respToRowValue(arr[i + 1]).stringValue ?? "0") ?? 0+ members.append((member: m, score: s))+ }+ }+ data = .zset(members: members)+ }++ return RedisKeyDetail(key: key, type: keyType, ttl: ttl, data: data, memoryBytes: memoryBytes)+ }++ // Hash field operations+ func updateHashField(key: String, field: String, value: String) async throws {+ try await sendCommand("HSET", args: [key, field, value])+ }+ func deleteHashField(key: String, field: String) async throws {+ try await sendCommand("HDEL", args: [key, field])+ }++ // List operations+ func updateListItem(key: String, index: Int, value: String) async throws {+ try await sendCommand("LSET", args: [key, String(index), value])+ }++ // Set operations+ func addSetMember(key: String, member: String) async throws {+ try await sendCommand("SADD", args: [key, member])+ }+ func removeSetMember(key: String, member: String) async throws {+ try await sendCommand("SREM", args: [key, member])+ }++ // Sorted set operations+ func addZSetMember(key: String, member: String, score: Double) async throws {+ try await sendCommand("ZADD", args: [key, String(score), member])+ }+ func removeZSetMember(key: String, member: String) async throws {+ try await sendCommand("ZREM", args: [key, member])+ }++ // TTL management+ func setTTL(key: String, seconds: Int) async throws {+ try await sendCommand("EXPIRE", args: [key, String(seconds)])+ }+ func removeTTL(key: String) async throws {+ try await sendCommand("PERSIST", args: [key])+ }++ // Key management+ func renameKey(oldName: String, newName: String) async throws {+ try await sendCommand("RENAME", args: [oldName, newName])+ }+ func duplicateKey(source: String, destination: String) async throws {+ // Try COPY first (Redis 6.2+), fall back to type-aware copy+ do {+ try await sendCommand("COPY", args: [source, destination])+ } catch {+ let detail = try await fetchKeyDetail(key: source)+ try await redisInsertTyped(key: destination, type: detail.type, data: detail.data, ttl: detail.ttl)+ }+ }++ // Server info+ func serverInfoSections() async throws -> [RedisInfoSection] {+ let resp = try await sendCommand("INFO")+ guard let raw = respToRowValue(resp).stringValue else { return [] }+ var sections: [RedisInfoSection] = []+ var currentName = "Server"+ var currentEntries: [(key: String, value: String)] = []+ // Redis INFO uses \r\n line endings+ for line in raw.components(separatedBy: .newlines) {+ let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)+ if trimmed.isEmpty { continue }+ if trimmed.hasPrefix("# ") {+ if !currentEntries.isEmpty {+ sections.append(RedisInfoSection(name: currentName, entries: currentEntries))+ currentEntries = []+ }+ currentName = String(trimmed.dropFirst(2))+ } else if let colonIdx = trimmed.firstIndex(of: ":") {+ let k = String(trimmed[trimmed.startIndex..<colonIdx])+ let v = String(trimmed[trimmed.index(after: colonIdx)...])+ currentEntries.append((key: k, value: v))+ }+ }+ if !currentEntries.isEmpty {+ sections.append(RedisInfoSection(name: currentName, entries: currentEntries))+ }+ return sections+ }++ // DBSIZE+ func dbSize() async throws -> Int {+ let resp = try await sendCommand("DBSIZE")+ if case .integer(let n) = resp { return Int(n) }+ return 0+ }++ // Flush+ func flushDB() async throws {+ try await sendCommand("FLUSHDB")+ }++ // Memory usage+ func memoryUsage(key: String) async throws -> Int? {+ do {+ let resp = try await sendCommand("MEMORY", args: ["USAGE", key])+ if case .integer(let n) = resp { return Int(n) }+ } catch {}+ return nil+ }++ // Slow log+ func slowLog(count: Int = 50) async throws -> [RedisSlowLogEntry] {+ let resp = try await sendCommand("SLOWLOG", args: ["GET", String(count)])+ guard case .array(let entries) = resp else { return [] }+ return entries.compactMap { entry -> RedisSlowLogEntry? in+ guard case .array(let parts) = entry, parts.count >= 4 else { return nil }+ let id = { if case .integer(let n) = parts[0] { return Int(n) }; return 0 }()+ let ts = { if case .integer(let n) = parts[1] { return Date(timeIntervalSince1970: Double(n)) }; return Date() }()+ let dur = { if case .integer(let n) = parts[2] { return Int(n) }; return 0 }()+ let cmd: String = {+ if case .array(let args) = parts[3] {+ return args.map { respToRowValue($0).stringValue ?? "" }.joined(separator: " ")+ }+ return ""+ }()+ let client = parts.count > 4 ? (respToRowValue(parts[4]).stringValue ?? "") : ""+ return RedisSlowLogEntry(id: id, timestamp: ts, durationMicros: dur, command: cmd, clientInfo: client)+ }+ }++ // MARK: - Backup / Restore++ /// A single Redis key entry for backup. Value is type-specific:+ /// - string: `.string(String)`+ /// - list: `.list([String])`+ /// - set: `.set([String])`+ /// - zset: `.zset([(String, Double)])` — member + score+ /// - hash: `.hash([String: String])`+ struct RedisKeyEntry {+ let key: String+ let type: String+ let ttl: Int?+ let value: Value++ enum Value {+ case string(String)+ case list([String])+ case set([String])+ case zset([(String, Double)])+ case hash([String: String])+ }+ }++ /// Iterate all keys using SCAN and yield batches for backup.+ func backupScanAll(batchSize: Int = 100, onBatch: @escaping ([RedisKeyEntry]) async throws -> Void, onProgress: ((Int64, TimeInterval) -> Void)? = nil) async throws {+ let start = CFAbsoluteTimeGetCurrent()+ var cursor = "0"+ var totalKeys: Int64 = 0+ var batch: [RedisKeyEntry] = []++ repeat {+ let scanResp = try await sendCommand("SCAN", args: [cursor, "COUNT", String(batchSize)])+ guard case .array(let scanArr) = scanResp, scanArr.count >= 2,+ let newCursor = respToRowValue(scanArr[0]).stringValue else {+ break+ }+ cursor = newCursor+ guard case .array(let keys) = scanArr[1] else { continue }++ for keyResp in keys {+ guard let key = respToRowValue(keyResp).stringValue else { continue }+ if let entry = try? await fetchKeyEntry(key: key) {+ batch.append(entry)+ }+ totalKeys += 1+ if batch.count >= batchSize {+ try await onBatch(batch)+ batch = []+ }+ onProgress?(totalKeys, CFAbsoluteTimeGetCurrent() - start)+ }+ } while cursor != "0"++ if !batch.isEmpty {+ try await onBatch(batch)+ }+ }++ /// Fetch a single key with its type-specific value + TTL.+ private func fetchKeyEntry(key: String) async throws -> RedisKeyEntry? {+ let typeResp = try await sendCommand("TYPE", args: [key])+ guard let type = typeResp.string else { return nil }++ let ttlResp = try await sendCommand("TTL", args: [key])+ let ttl: Int? = {+ if case .integer(let n) = ttlResp, n > 0 { return Int(n) }+ return nil+ }()++ let value: RedisKeyEntry.Value+ switch type {+ case "string":+ let resp = try await sendCommand("GET", args: [key])+ value = .string(respToRowValue(resp).stringValue ?? "")+ case "list":+ let resp = try await sendCommand("LRANGE", args: [key, "0", "-1"])+ if case .array(let items) = resp {+ value = .list(items.compactMap { respToRowValue($0).stringValue })+ } else { value = .list([]) }+ case "set":+ let resp = try await sendCommand("SMEMBERS", args: [key])+ if case .array(let items) = resp {+ value = .set(items.compactMap { respToRowValue($0).stringValue })+ } else { value = .set([]) }+ case "zset":+ let resp = try await sendCommand("ZRANGE", args: [key, "0", "-1", "WITHSCORES"])+ if case .array(let items) = resp {+ var pairs: [(String, Double)] = []+ var i = 0+ while i + 1 < items.count {+ let member = respToRowValue(items[i]).stringValue ?? ""+ let score = Double(respToRowValue(items[i + 1]).stringValue ?? "0") ?? 0+ pairs.append((member, score))+ i += 2+ }+ value = .zset(pairs)+ } else { value = .zset([]) }+ case "hash":+ let resp = try await sendCommand("HGETALL", args: [key])+ if case .array(let items) = resp {+ var dict: [String: String] = [:]+ var i = 0+ while i + 1 < items.count {+ let k = respToRowValue(items[i]).stringValue ?? ""+ let v = respToRowValue(items[i + 1]).stringValue ?? ""+ dict[k] = v+ i += 2+ }+ value = .hash(dict)+ } else { value = .hash([:]) }+ default:+ return nil+ }++ return RedisKeyEntry(key: key, type: type, ttl: ttl, value: value)+ }++ /// Restore a single key entry.+ func restoreKeyEntry(_ entry: RedisKeyEntry) async throws {+ // Delete any existing key first to ensure clean restore+ _ = try? await sendCommand("DEL", args: [entry.key])++ switch entry.value {+ case .string(let s):+ _ = try await sendCommand("SET", args: [entry.key, s])+ case .list(let items):+ if !items.isEmpty {+ _ = try await sendCommand("RPUSH", args: [entry.key] + items)+ }+ case .set(let members):+ if !members.isEmpty {+ _ = try await sendCommand("SADD", args: [entry.key] + members)+ }+ case .zset(let pairs):+ var args = [entry.key]+ for (member, score) in pairs {+ args.append(String(score))+ args.append(member)+ }+ if pairs.count > 0 {+ _ = try await sendCommand("ZADD", args: args)+ }+ case .hash(let dict):+ var args = [entry.key]+ for (k, v) in dict {+ args.append(k)+ args.append(v)+ }+ if !dict.isEmpty {+ _ = try await sendCommand("HSET", args: args)+ }+ }++ if let ttl = entry.ttl {+ _ = try await sendCommand("EXPIRE", args: [entry.key, String(ttl)])+ }+ }++ deinit {+ connection?.close()+ try? eventLoopGroup.syncShutdownGracefully()+ }+}diff --git a/macos/Data/Adapters/Redis/RedisModels.swift b/macos/Data/Adapters/Redis/RedisModels.swiftnew file mode 100644index 0000000..b08dea8--- /dev/null+++ b/macos/Data/Adapters/Redis/RedisModels.swift@@ -0,0 +1,39 @@+// RedisModels.swift+// Gridex+//+// Supporting types for Redis-specific features.++import Foundation++enum RedisKeyType: String, CaseIterable, Sendable {+ case string, hash, list, set, zset+}++enum RedisKeyData: Sendable {+ case string(value: String)+ case hash(fields: [(field: String, value: String)])+ case list(items: [String])+ case set(members: [String])+ case zset(members: [(member: String, score: Double)])+}++struct RedisKeyDetail: Sendable {+ let key: String+ let type: RedisKeyType+ let ttl: Int? // nil = no expiry+ let data: RedisKeyData+ let memoryBytes: Int?+}++struct RedisInfoSection: Sendable {+ let name: String+ let entries: [(key: String, value: String)]+}++struct RedisSlowLogEntry: Identifiable, Sendable {+ let id: Int+ let timestamp: Date+ let durationMicros: Int+ let command: String+ let clientInfo: String+}diff --git a/macos/Data/Adapters/SQLite/SQLiteAdapter.swift b/macos/Data/Adapters/SQLite/SQLiteAdapter.swiftnew file mode 100644index 0000000..9cbbd50--- /dev/null+++ b/macos/Data/Adapters/SQLite/SQLiteAdapter.swift@@ -0,0 +1,404 @@+// SQLiteAdapter.swift+// Gridex+//+// SQLite database adapter using the sqlite3 C API.+// Thread-safe via serial DispatchQueue.++import Foundation+import SQLite3++final class SQLiteAdapter: DatabaseAdapter, SchemaInspectable, @unchecked Sendable {+ let databaseType: DatabaseType = .sqlite+ private(set) var isConnected: Bool = false+ private var db: OpaquePointer?+ private var filePath: String?+ private let queue = DispatchQueue(label: "com.gridex.sqlite", qos: .userInitiated)++ deinit {+ if let db { sqlite3_close_v2(db) }+ }++ // MARK: - Connection++ func connect(config: ConnectionConfig, password: String?) async throws {+ guard let path = config.filePath else {+ throw GridexError.connectionFailed(underlying: NSError(domain: "SQLite", code: -1, userInfo: [NSLocalizedDescriptionKey: "No file path"]))+ }+ try await withCheckedThrowingContinuation { (cont: CheckedContinuation<Void, Error>) in+ queue.async {+ let flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX+ var dbPointer: OpaquePointer?+ let rc = sqlite3_open_v2(path, &dbPointer, flags, nil)+ if rc != SQLITE_OK {+ let msg = dbPointer.flatMap { String(cString: sqlite3_errmsg($0)) } ?? "Unknown"+ sqlite3_close_v2(dbPointer)+ cont.resume(throwing: GridexError.connectionFailed(underlying: NSError(domain: "SQLite", code: Int(rc), userInfo: [NSLocalizedDescriptionKey: msg])))+ return+ }+ self.db = dbPointer+ self.filePath = path+ self.isConnected = true+ sqlite3_exec(dbPointer, "PRAGMA journal_mode=WAL", nil, nil, nil)+ sqlite3_exec(dbPointer, "PRAGMA foreign_keys=ON", nil, nil, nil)+ cont.resume()+ }+ }+ }++ func disconnect() async throws {+ try await withCheckedThrowingContinuation { (cont: CheckedContinuation<Void, Error>) in+ queue.async {+ if let db = self.db {+ sqlite3_close_v2(db)+ self.db = nil+ }+ self.isConnected = false+ cont.resume()+ }+ }+ }++ func testConnection(config: ConnectionConfig, password: String?) async throws -> Bool {+ guard let path = config.filePath else {+ throw GridexError.connectionFailed(underlying: NSError(domain: "Gridex", code: -1, userInfo: [NSLocalizedDescriptionKey: "No file path specified"]))+ }+ var testDb: OpaquePointer?+ let rc = sqlite3_open_v2(path, &testDb, SQLITE_OPEN_READONLY, nil)+ defer { sqlite3_close_v2(testDb) }+ if rc != SQLITE_OK {+ let msg = testDb.flatMap { String(cString: sqlite3_errmsg($0)) } ?? "Unknown SQLite error"+ throw GridexError.connectionFailed(underlying: NSError(domain: "SQLite", code: Int(rc), userInfo: [NSLocalizedDescriptionKey: msg]))+ }+ return true+ }++ // MARK: - Query Execution++ func execute(query: String, parameters: [QueryParameter]?) async throws -> QueryResult {+ try ensureConnected()+ let startTime = CFAbsoluteTimeGetCurrent()++ return try await withCheckedThrowingContinuation { cont in+ queue.async {+ do {+ let result = try self.executeSync(sql: query, parameters: parameters, startTime: startTime)+ cont.resume(returning: result)+ } catch {+ cont.resume(throwing: error)+ }+ }+ }+ }++ func executeRaw(sql: String) async throws -> QueryResult {+ try await execute(query: sql, parameters: nil)+ }++ private func executeSync(sql: String, parameters: [QueryParameter]?, startTime: CFAbsoluteTime) throws -> QueryResult {+ guard let db else { throw GridexError.queryExecutionFailed("No database connection") }++ var stmt: OpaquePointer?+ guard sqlite3_prepare_v2(db, sql, -1, &stmt, nil) == SQLITE_OK, let stmt else {+ let msg = String(cString: sqlite3_errmsg(db))+ throw GridexError.queryExecutionFailed(msg)+ }+ defer { sqlite3_finalize(stmt) }++ // Bind parameters+ if let parameters {+ for (i, param) in parameters.enumerated() {+ bindValue(param.value, to: stmt, at: Int32(i + 1))+ }+ }++ // Detect query type+ let upper = sql.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()+ let queryType: QueryType =+ upper.hasPrefix("SELECT") || upper.hasPrefix("PRAGMA") || upper.hasPrefix("EXPLAIN") ? .select :+ upper.hasPrefix("INSERT") ? .insert :+ upper.hasPrefix("UPDATE") ? .update :+ upper.hasPrefix("DELETE") ? .delete :+ upper.hasPrefix("CREATE") || upper.hasPrefix("ALTER") || upper.hasPrefix("DROP") ? .ddl : .other++ // SELECT-like: read all rows+ if queryType == .select {+ let colCount = sqlite3_column_count(stmt)+ var columns: [ColumnHeader] = []+ for i in 0..<colCount {+ let name = String(cString: sqlite3_column_name(stmt, i))+ let declType = sqlite3_column_decltype(stmt, i).map { String(cString: $0) } ?? "TEXT"+ columns.append(ColumnHeader(name: name, dataType: declType))+ }++ var rows: [[RowValue]] = []+ while sqlite3_step(stmt) == SQLITE_ROW {+ var row: [RowValue] = []+ for i in 0..<colCount {+ row.append(readColumn(stmt: stmt, index: i))+ }+ rows.append(row)+ }++ let duration = CFAbsoluteTimeGetCurrent() - startTime+ return QueryResult(columns: columns, rows: rows, rowsAffected: rows.count, executionTime: duration, queryType: queryType)+ }++ // Non-SELECT: execute and return affected count+ let stepResult = sqlite3_step(stmt)+ guard stepResult == SQLITE_DONE else {+ throw GridexError.queryExecutionFailed(String(cString: sqlite3_errmsg(db)))+ }++ let duration = CFAbsoluteTimeGetCurrent() - startTime+ return QueryResult(columns: [], rows: [], rowsAffected: Int(sqlite3_changes(db)), executionTime: duration, queryType: queryType)+ }++ private func readColumn(stmt: OpaquePointer, index: Int32) -> RowValue {+ switch sqlite3_column_type(stmt, index) {+ case SQLITE_NULL: return .null+ case SQLITE_INTEGER: return .integer(sqlite3_column_int64(stmt, index))+ case SQLITE_FLOAT: return .double(sqlite3_column_double(stmt, index))+ case SQLITE_TEXT: return .string(String(cString: sqlite3_column_text(stmt, index)))+ case SQLITE_BLOB:+ let n = sqlite3_column_bytes(stmt, index)+ if let ptr = sqlite3_column_blob(stmt, index) {+ return .data(Data(bytes: ptr, count: Int(n)))+ }+ return .null+ default: return .null+ }+ }++ private func bindValue(_ value: RowValue, to stmt: OpaquePointer, at idx: Int32) {+ let TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)+ switch value {+ case .null: sqlite3_bind_null(stmt, idx)+ case .string(let v): sqlite3_bind_text(stmt, idx, v, -1, TRANSIENT)+ case .integer(let v):sqlite3_bind_int64(stmt, idx, v)+ case .double(let v): sqlite3_bind_double(stmt, idx, v)+ case .boolean(let v):sqlite3_bind_int(stmt, idx, v ? 1 : 0)+ case .date(let v): sqlite3_bind_text(stmt, idx, ISO8601DateFormatter().string(from: v), -1, TRANSIENT)+ case .data(let v): _ = v.withUnsafeBytes { sqlite3_bind_blob(stmt, idx, $0.baseAddress, Int32(v.count), TRANSIENT) }+ case .json(let v): sqlite3_bind_text(stmt, idx, v, -1, TRANSIENT)+ case .uuid(let v): sqlite3_bind_text(stmt, idx, v.uuidString, -1, TRANSIENT)+ case .array: sqlite3_bind_text(stmt, idx, value.description, -1, TRANSIENT)+ }+ }++ // MARK: - Schema Inspection++ func listDatabases() async throws -> [String] {+ [filePath.map { URL(fileURLWithPath: $0).lastPathComponent } ?? "main"]+ }++ func listSchemas(database: String?) async throws -> [String] { ["main"] }++ func listTables(schema: String?) async throws -> [TableInfo] {+ let result = try await executeRaw(sql: """+ SELECT name FROM sqlite_master+ WHERE type='table' AND name NOT LIKE 'sqlite_%'+ ORDER BY name+ """)+ var tables: [TableInfo] = []+ for row in result.rows {+ guard case .string(let name) = row.first else { continue }+ let count = try? await tableRowCount(table: name, schema: nil)+ tables.append(TableInfo(name: name, schema: nil, type: .table, estimatedRowCount: count))+ }+ return tables+ }++ func listViews(schema: String?) async throws -> [ViewInfo] {+ let result = try await executeRaw(sql: """+ SELECT name, sql FROM sqlite_master WHERE type='view' ORDER BY name+ """)+ return result.rows.compactMap { row in+ guard case .string(let name) = row.first else { return nil }+ return ViewInfo(name: name, schema: nil, definition: row.count > 1 ? row[1].stringValue : nil, isMaterialized: false)+ }+ }++ func describeTable(name: String, schema: String?) async throws -> TableDescription {+ let columns = try await describeColumns(table: name)+ let indexes = try await listIndexes(table: name, schema: nil)+ let fks = try await listForeignKeys(table: name, schema: nil)+ let count = try? await tableRowCount(table: name, schema: nil)+ return TableDescription(name: name, schema: nil, columns: columns, indexes: indexes, foreignKeys: fks, constraints: [], comment: nil, estimatedRowCount: count)+ }++ private func describeColumns(table: String) async throws -> [ColumnInfo] {+ let result = try await executeRaw(sql: "PRAGMA table_info(\(q(table)))")+ return result.rows.enumerated().map { idx, row in+ let cid = row[0].stringValue ?? "\(idx)"+ let name = row[1].stringValue ?? ""+ let type = row[2].stringValue ?? "TEXT"+ let notNull = row[3].stringValue == "1"+ let defVal = row[4].isNull ? nil : row[4].stringValue+ let pk = row[5].stringValue != "0"+ return ColumnInfo(+ name: name, dataType: type, isNullable: !notNull, defaultValue: defVal,+ isPrimaryKey: pk, isAutoIncrement: pk && type.uppercased() == "INTEGER",+ comment: nil, ordinalPosition: Int(cid) ?? idx, characterMaxLength: nil+ )+ }+ }++ func listIndexes(table: String, schema: String?) async throws -> [IndexInfo] {+ let escapedTable = table.replacingOccurrences(of: "'", with: "''")+ let sql = """+ SELECT il.name, il.\"unique\", GROUP_CONCAT(ii.name) AS columns+ FROM pragma_index_list('\(escapedTable)') il+ JOIN pragma_index_info(il.name) ii+ GROUP BY il.name, il.\"unique\"+ ORDER BY il.name, ii.seqno+ """+ let result = try await executeRaw(sql: sql)+ return result.rows.map { row in+ let name = row[0].stringValue ?? ""+ let unique = row[1].stringValue == "1"+ let cols = (row[2].stringValue ?? "").split(separator: ",").map(String.init)+ return IndexInfo(name: name, columns: cols, isUnique: unique, type: "btree", tableName: table)+ }+ }++ func listForeignKeys(table: String, schema: String?) async throws -> [ForeignKeyInfo] {+ let result = try await executeRaw(sql: "PRAGMA foreign_key_list(\(q(table)))")+ return result.rows.map { row in+ ForeignKeyInfo(+ name: nil,+ columns: [row[3].stringValue ?? ""],+ referencedTable: row[2].stringValue ?? "",+ referencedColumns: [row[4].stringValue ?? ""],+ onDelete: ForeignKeyAction(rawValue: row[6].stringValue ?? "NO ACTION") ?? .noAction,+ onUpdate: ForeignKeyAction(rawValue: row[5].stringValue ?? "NO ACTION") ?? .noAction+ )+ }+ }++ func listFunctions(schema: String?) async throws -> [String] {+ return []+ }++ func getFunctionSource(name: String, schema: String?) async throws -> String {+ throw GridexError.queryExecutionFailed("SQLite does not support stored functions")+ }++ // MARK: - Data Manipulation++ func insertRow(table: String, schema: String?, values: [String: RowValue]) async throws -> QueryResult {+ let cols = values.keys.map { q($0) }.joined(separator: ", ")+ let placeholders = values.keys.map { _ in "?" }.joined(separator: ", ")+ return try await execute(query: "INSERT INTO \(q(table)) (\(cols)) VALUES (\(placeholders))",+ parameters: values.values.map { QueryParameter($0) })+ }++ func updateRow(table: String, schema: String?, set values: [String: RowValue], where conditions: [String: RowValue]) async throws -> QueryResult {+ let setClauses = values.keys.map { "\(q($0)) = ?" }.joined(separator: ", ")+ let whereClauses = conditions.keys.map { "\(q($0)) = ?" }.joined(separator: " AND ")+ let params = (Array(values.values) + Array(conditions.values)).map { QueryParameter($0) }+ return try await execute(query: "UPDATE \(q(table)) SET \(setClauses) WHERE \(whereClauses)", parameters: params)+ }++ func deleteRow(table: String, schema: String?, where conditions: [String: RowValue]) async throws -> QueryResult {+ let whereClauses = conditions.keys.map { "\(q($0)) = ?" }.joined(separator: " AND ")+ return try await execute(query: "DELETE FROM \(q(table)) WHERE \(whereClauses)",+ parameters: conditions.values.map { QueryParameter($0) })+ }++ func beginTransaction() async throws { _ = try await executeRaw(sql: "BEGIN TRANSACTION") }+ func commitTransaction() async throws { _ = try await executeRaw(sql: "COMMIT") }+ func rollbackTransaction() async throws { _ = try await executeRaw(sql: "ROLLBACK") }++ // MARK: - Pagination++ func fetchRows(table: String, schema: String?, columns: [String]?, where filter: FilterExpression?, orderBy: [QuerySortDescriptor]?, limit: Int, offset: Int) async throws -> QueryResult {+ let d = SQLDialect.sqlite+ let colList = columns?.map { d.quoteIdentifier($0) }.joined(separator: ", ") ?? "*"+ var sql = "SELECT \(colList) FROM \(d.quoteIdentifier(table))"+ if let filter, !filter.conditions.isEmpty {+ sql += " WHERE \(filter.toSQL(dialect: d))"+ }+ if let orderBy, !orderBy.isEmpty {+ sql += " ORDER BY " + orderBy.map { $0.toSQL(dialect: d) }.joined(separator: ", ")+ }+ sql += " LIMIT \(limit) OFFSET \(offset)"+ return try await executeRaw(sql: sql)+ }++ func serverVersion() async throws -> String {+ let r = try await executeRaw(sql: "SELECT sqlite_version()")+ return "SQLite " + (r.rows.first?.first?.stringValue ?? "")+ }++ func currentDatabase() async throws -> String? { filePath }++ // MARK: - SchemaInspectable++ func fullSchemaSnapshot(database: String?) async throws -> SchemaSnapshot {+ let tables = try await listTables(schema: nil)+ var descs: [TableDescription] = []+ for t in tables { descs.append(try await describeTable(name: t.name, schema: nil)) }+ let views = try await listViews(schema: nil)+ return SchemaSnapshot(+ databaseName: filePath.map { URL(fileURLWithPath: $0).lastPathComponent } ?? "main",+ databaseType: .sqlite,+ schemas: [SchemaInfo(name: "main", tables: descs, views: views, functions: [], enums: [])],+ capturedAt: Date()+ )+ }++ func columnStatistics(table: String, schema: String?, sampleSize: Int) async throws -> [ColumnStatistics] {+ let cols = try await describeColumns(table: table)+ var stats: [ColumnStatistics] = []+ for col in cols {+ let r = try await executeRaw(sql: """+ SELECT COUNT(DISTINCT \(q(col.name))),+ CAST(SUM(CASE WHEN \(q(col.name)) IS NULL THEN 1 ELSE 0 END) AS REAL) / MAX(COUNT(*), 1),+ MIN(\(q(col.name))), MAX(\(q(col.name)))+ FROM \(q(table))+ """)+ if let row = r.rows.first {+ stats.append(ColumnStatistics(+ columnName: col.name,+ distinctCount: row[0].stringValue.flatMap(Int.init),+ nullRatio: row[1].stringValue.flatMap(Double.init),+ topValues: nil,+ minValue: row[2].stringValue,+ maxValue: row[3].stringValue+ ))+ }+ }+ return stats+ }++ func tableRowCount(table: String, schema: String?) async throws -> Int {+ let r = try await executeRaw(sql: "SELECT COUNT(*) FROM \(q(table))")+ guard let row = r.rows.first, case .integer(let n) = row.first else { return 0 }+ return Int(n)+ }++ func tableSizeBytes(table: String, schema: String?) async throws -> Int64? { nil }+ func queryStatistics() async throws -> [QueryStatisticsEntry] { [] }++ func primaryKeyColumns(table: String, schema: String?) async throws -> [String] {+ let r = try await executeRaw(sql: "PRAGMA table_info(\(q(table)))")+ // PRAGMA table_info columns: cid, name, type, notnull, dflt_value, pk+ return r.rows.compactMap { row in+ guard row.count >= 6, let pk = row[5].intValue, pk > 0 else { return nil }+ return row[1].stringValue+ }+ }++ // MARK: - Helpers++ private func ensureConnected() throws {+ guard isConnected, db != nil else {+ throw GridexError.queryExecutionFailed("Not connected to database")+ }+ }++ /// Shorthand for quoting identifiers+ private func q(_ name: String) -> String {+ "\"\(name.replacingOccurrences(of: "\"", with: "\"\""))\""+ }+}diff --git a/macos/Data/Cache/SchemaCache.swift b/macos/Data/Cache/SchemaCache.swiftnew file mode 100644index 0000000..7dc66c5--- /dev/null+++ b/macos/Data/Cache/SchemaCache.swift@@ -0,0 +1,45 @@+// SchemaCache.swift+// Gridex+//+// In-memory cache for database schemas with TTL.++import Foundation++actor SchemaCache {+ private var cache: [UUID: CachedSchema] = [:]+ private let defaultTTL: TimeInterval = 300 // 5 minutes++ struct CachedSchema {+ let snapshot: SchemaSnapshot+ let cachedAt: Date+ let ttl: TimeInterval++ var isExpired: Bool {+ Date().timeIntervalSince(cachedAt) > ttl+ }+ }++ func get(connectionId: UUID) -> SchemaSnapshot? {+ guard let cached = cache[connectionId], !cached.isExpired else {+ cache[connectionId] = nil+ return nil+ }+ return cached.snapshot+ }++ func set(connectionId: UUID, snapshot: SchemaSnapshot, ttl: TimeInterval? = nil) {+ cache[connectionId] = CachedSchema(+ snapshot: snapshot,+ cachedAt: Date(),+ ttl: ttl ?? defaultTTL+ )+ }++ func invalidate(connectionId: UUID) {+ cache[connectionId] = nil+ }++ func invalidateAll() {+ cache.removeAll()+ }+}diff --git a/macos/Data/Keychain/KeychainService.swift b/macos/Data/Keychain/KeychainService.swiftnew file mode 100644index 0000000..0ac93b0--- /dev/null+++ b/macos/Data/Keychain/KeychainService.swift@@ -0,0 +1,210 @@+// KeychainService.swift+// Gridex+//+// Wrapper around macOS Keychain Services.+// Prefers the Data Protection Keychain (iOS-style, no ACL prompts).+// Falls back to the standard file-based Keychain for unsigned/dev builds.++import Foundation+import Security++protocol KeychainServiceProtocol: Sendable {+ func save(key: String, value: String) throws+ func load(key: String) throws -> String?+ func delete(key: String) throws+ func update(key: String, value: String) throws+}++final class KeychainService: KeychainServiceProtocol, Sendable {+ private let serviceName = "com.gridex.credentials"++ /// Whether the Data Protection Keychain is available (requires code signing + entitlements).+ private let useDataProtection: Bool++ init() {+ // Probe: try a save+delete with Data Protection to see if it works.+ let probeKey = "__keychain_probe__"+ let probeQuery: [String: Any] = [+ kSecClass as String: kSecClassGenericPassword,+ kSecAttrService as String: "com.gridex.probe",+ kSecAttrAccount as String: probeKey,+ kSecUseDataProtectionKeychain as String: true,+ kSecValueData as String: Data("probe".utf8),+ ]+ let status = SecItemAdd(probeQuery as CFDictionary, nil)+ if status == errSecSuccess || status == errSecDuplicateItem {+ // Cleanup probe+ let deleteQuery: [String: Any] = [+ kSecClass as String: kSecClassGenericPassword,+ kSecAttrService as String: "com.gridex.probe",+ kSecAttrAccount as String: probeKey,+ kSecUseDataProtectionKeychain as String: true,+ ]+ SecItemDelete(deleteQuery as CFDictionary)+ useDataProtection = true+ } else {+ useDataProtection = false+ }+ }++ // MARK: - Core Operations++ func save(key: String, value: String) throws {+ guard let data = value.data(using: .utf8) else { return }++ var query = baseQuery(key: key)+ query[kSecValueData as String] = data+ if useDataProtection {+ query[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock+ } else {+ // For the file-based Keychain, create a SecAccess that trusts the+ // current application so macOS won't show a password prompt on access.+ if let access = createTrustedAccess() {+ query[kSecAttrAccess as String] = access+ }+ }++ let status = SecItemAdd(query as CFDictionary, nil)++ if status == errSecDuplicateItem {+ try update(key: key, value: value)+ } else if status != errSecSuccess {+ throw GridexError.keychainError("Save failed (OSStatus \(status))")+ }+ }++ func load(key: String) throws -> String? {+ var query = baseQuery(key: key)+ query[kSecReturnData as String] = true+ query[kSecMatchLimit as String] = kSecMatchLimitOne++ var result: AnyObject?+ let status = SecItemCopyMatching(query as CFDictionary, &result)++ if status == errSecSuccess,+ let data = result as? Data,+ let value = String(data: data, encoding: .utf8) {+ // For file-based Keychain: re-save with trusted access so future reads+ // won't prompt. Each rebuild changes the binary hash, invalidating the+ // old ACL. Delete the old item and re-create with current app's trust.+ if !useDataProtection {+ let deleteQuery = baseQuery(key: key)+ SecItemDelete(deleteQuery as CFDictionary)+ try? save(key: key, value: value)+ }+ return value+ }++ // Try the other keychain variant (migration between Data Protection ↔ standard)+ var altQuery = baseQuery(key: key, forceDataProtection: !useDataProtection)+ altQuery[kSecReturnData as String] = true+ altQuery[kSecMatchLimit as String] = kSecMatchLimitOne++ var altResult: AnyObject?+ let altStatus = SecItemCopyMatching(altQuery as CFDictionary, &altResult)++ if altStatus == errSecSuccess,+ let data = altResult as? Data,+ let value = String(data: data, encoding: .utf8) {+ // Migrate to preferred keychain+ try? save(key: key, value: value)+ SecItemDelete(altQuery as CFDictionary)+ return value+ }++ // Migrate from legacy UserDefaults Base64 storage (used by older versions)+ if let base64 = UserDefaults.standard.string(forKey: "kc.fallback.\(key)"),+ let data = Data(base64Encoded: base64),+ let value = String(data: data, encoding: .utf8) {+ // Migrate to real Keychain and clean up UserDefaults+ try? save(key: key, value: value)+ UserDefaults.standard.removeObject(forKey: "kc.fallback.\(key)")+ return value+ }++ return nil+ }++ func delete(key: String) throws {+ let query = baseQuery(key: key)+ SecItemDelete(query as CFDictionary)++ // Also clean up from the other keychain variant+ let altQuery = baseQuery(key: key, forceDataProtection: !useDataProtection)+ SecItemDelete(altQuery as CFDictionary)+ }++ func update(key: String, value: String) throws {+ guard let data = value.data(using: .utf8) else { return }++ let query = baseQuery(key: key)+ let attributes: [String: Any] = [kSecValueData as String: data]++ let status = SecItemUpdate(query as CFDictionary, attributes as CFDictionary)+ if status != errSecSuccess {+ throw GridexError.keychainError("Update failed (OSStatus \(status))")+ }+ }++ // MARK: - Access Control++ /// Creates a SecAccess that trusts the current application, allowing Keychain+ /// access without macOS showing a password/permission prompt to the user.+ /// Only needed for the file-based Keychain (not Data Protection Keychain).+ private func createTrustedAccess() -> SecAccess? {+ var trustedApp: SecTrustedApplication?+ // nil path = current application+ let appStatus = SecTrustedApplicationCreateFromPath(nil, &trustedApp)+ guard appStatus == errSecSuccess, let app = trustedApp else { return nil }++ var access: SecAccess?+ let accessStatus = SecAccessCreate(+ "Gridex Credentials" as CFString,+ [app] as CFArray,+ &access+ )+ guard accessStatus == errSecSuccess else { return nil }+ return access+ }++ // MARK: - Query Builder++ private func baseQuery(key: String, forceDataProtection: Bool? = nil) -> [String: Any] {+ let dp = forceDataProtection ?? useDataProtection+ var query: [String: Any] = [+ kSecClass as String: kSecClassGenericPassword,+ kSecAttrService as String: serviceName,+ kSecAttrAccount as String: key,+ ]+ if dp {+ query[kSecUseDataProtectionKeychain as String] = true+ }+ return query+ }++ // MARK: - Convenience++ func savePassword(connectionId: UUID, password: String) throws {+ try save(key: "db.password.\(connectionId.uuidString)", value: password)+ }++ func loadPassword(connectionId: UUID) throws -> String? {+ try load(key: "db.password.\(connectionId.uuidString)")+ }++ func saveSSHPassword(connectionId: UUID, password: String) throws {+ try save(key: "ssh.password.\(connectionId.uuidString)", value: password)+ }++ func loadSSHPassword(connectionId: UUID) throws -> String? {+ try load(key: "ssh.password.\(connectionId.uuidString)")+ }++ func saveAPIKey(provider: String, key: String) throws {+ try save(key: "ai.apikey.\(provider)", value: key)+ }++ func loadAPIKey(provider: String) throws -> String? {+ try load(key: "ai.apikey.\(provider)")+ }+}diff --git a/macos/Data/Persistence/Models/QueryHistoryEntity.swift b/macos/Data/Persistence/Models/QueryHistoryEntity.swiftnew file mode 100644index 0000000..98f8035--- /dev/null+++ b/macos/Data/Persistence/Models/QueryHistoryEntity.swift@@ -0,0 +1,43 @@+// QueryHistoryEntity.swift+// Gridex++import Foundation+import SwiftData++@Model+final class QueryHistoryEntity {+ @Attribute(.unique) var id: UUID+ var connectionId: UUID+ var database: String+ var sql: String+ var executedAt: Date+ var duration: TimeInterval+ var rowCount: Int?+ var status: String+ var errorMessage: String?+ var isFavorite: Bool++ init(+ id: UUID = UUID(),+ connectionId: UUID,+ database: String,+ sql: String,+ executedAt: Date = Date(),+ duration: TimeInterval,+ rowCount: Int? = nil,+ status: String = "success",+ errorMessage: String? = nil,+ isFavorite: Bool = false+ ) {+ self.id = id+ self.connectionId = connectionId+ self.database = database+ self.sql = sql+ self.executedAt = executedAt+ self.duration = duration+ self.rowCount = rowCount+ self.status = status+ self.errorMessage = errorMessage+ self.isFavorite = isFavorite+ }+}diff --git a/macos/Data/Persistence/Models/SavedConnectionEntity.swift b/macos/Data/Persistence/Models/SavedConnectionEntity.swiftnew file mode 100644index 0000000..f7c1c68--- /dev/null+++ b/macos/Data/Persistence/Models/SavedConnectionEntity.swift@@ -0,0 +1,103 @@+// SavedConnectionEntity.swift+// Gridex+//+// SwiftData model for persisted connections.++import Foundation+import SwiftData++@Model+final class SavedConnectionEntity {+ @Attribute(.unique) var id: UUID+ var name: String+ var databaseType: String+ var host: String?+ var port: Int?+ var database: String?+ var username: String?+ var sslEnabled: Bool+ var sshEnabled: Bool+ var sshHost: String?+ var sshPort: Int?+ var sshUsername: String?+ var sshAuthMethod: String?+ var sshKeyPath: String?+ var colorTag: String?+ var group: String?+ var sortOrder: Int+ var lastConnectedAt: Date?+ var createdAt: Date+ var filePath: String?++ init(+ id: UUID = UUID(),+ name: String,+ databaseType: String,+ host: String? = nil,+ port: Int? = nil,+ database: String? = nil,+ username: String? = nil,+ sslEnabled: Bool = false,+ sshEnabled: Bool = false,+ sshHost: String? = nil,+ sshPort: Int? = nil,+ sshUsername: String? = nil,+ sshAuthMethod: String? = nil,+ sshKeyPath: String? = nil,+ colorTag: String? = nil,+ group: String? = nil,+ sortOrder: Int = 0,+ lastConnectedAt: Date? = nil,+ createdAt: Date = Date(),+ filePath: String? = nil+ ) {+ self.id = id+ self.name = name+ self.databaseType = databaseType+ self.host = host+ self.port = port+ self.database = database+ self.username = username+ self.sslEnabled = sslEnabled+ self.sshEnabled = sshEnabled+ self.sshHost = sshHost+ self.sshPort = sshPort+ self.sshUsername = sshUsername+ self.sshAuthMethod = sshAuthMethod+ self.sshKeyPath = sshKeyPath+ self.colorTag = colorTag+ self.group = group+ self.sortOrder = sortOrder+ self.lastConnectedAt = lastConnectedAt+ self.createdAt = createdAt+ self.filePath = filePath+ }++ func toConfig() -> ConnectionConfig {+ var sshConfig: SSHTunnelConfig?+ if sshEnabled, let sshHost, let sshUsername {+ sshConfig = SSHTunnelConfig(+ host: sshHost,+ port: sshPort ?? 22,+ username: sshUsername,+ authMethod: SSHAuthMethod(rawValue: sshAuthMethod ?? "password") ?? .password,+ keyPath: sshKeyPath+ )+ }++ return ConnectionConfig(+ id: id,+ name: name,+ databaseType: DatabaseType(rawValue: databaseType) ?? .sqlite,+ host: host,+ port: port,+ database: database,+ username: username,+ sslEnabled: sslEnabled,+ colorTag: colorTag.flatMap { ColorTag(rawValue: $0) },+ group: group,+ filePath: filePath,+ sshConfig: sshConfig+ )+ }+}diff --git a/macos/Data/Persistence/Repositories/SwiftDataConnectionRepository.swift b/macos/Data/Persistence/Repositories/SwiftDataConnectionRepository.swiftnew file mode 100644index 0000000..cfd7e65--- /dev/null+++ b/macos/Data/Persistence/Repositories/SwiftDataConnectionRepository.swift@@ -0,0 +1,131 @@+// SwiftDataConnectionRepository.swift+// Gridex+//+// SwiftData implementation of ConnectionRepository.++import Foundation+import SwiftData++final class SwiftDataConnectionRepository: ConnectionRepository, @unchecked Sendable {+ private let modelContainer: ModelContainer++ init(modelContainer: ModelContainer) {+ self.modelContainer = modelContainer+ }++ @MainActor+ func fetchAll() async throws -> [ConnectionConfig] {+ let context = modelContainer.mainContext+ let descriptor = FetchDescriptor<SavedConnectionEntity>(+ sortBy: [SortDescriptor(\.sortOrder)]+ )+ let entities = try context.fetch(descriptor)+ return entities.map { $0.toConfig() }+ }++ @MainActor+ func fetchByID(_ id: UUID) async throws -> ConnectionConfig? {+ let context = modelContainer.mainContext+ var descriptor = FetchDescriptor<SavedConnectionEntity>(+ predicate: #Predicate { $0.id == id }+ )+ descriptor.fetchLimit = 1+ return try context.fetch(descriptor).first?.toConfig()+ }++ @MainActor+ func fetchByGroup(_ group: String) async throws -> [ConnectionConfig] {+ let context = modelContainer.mainContext+ let descriptor = FetchDescriptor<SavedConnectionEntity>(+ predicate: #Predicate { $0.group == group },+ sortBy: [SortDescriptor(\.sortOrder)]+ )+ return try context.fetch(descriptor).map { $0.toConfig() }+ }++ @MainActor+ func save(_ config: ConnectionConfig) async throws {+ let context = modelContainer.mainContext+ let entity = SavedConnectionEntity(+ id: config.id,+ name: config.name,+ databaseType: config.databaseType.rawValue,+ host: config.host,+ port: config.port,+ database: config.database,+ username: config.username,+ sslEnabled: config.sslEnabled,+ sshEnabled: config.sshConfig != nil,+ sshHost: config.sshConfig?.host,+ sshPort: config.sshConfig?.port,+ sshUsername: config.sshConfig?.username,+ sshAuthMethod: config.sshConfig?.authMethod.rawValue,+ sshKeyPath: config.sshConfig?.keyPath,+ colorTag: config.colorTag?.rawValue,+ group: config.group,+ filePath: config.filePath+ )+ context.insert(entity)+ try context.save()+ }++ @MainActor+ func update(_ config: ConnectionConfig) async throws {+ let context = modelContainer.mainContext+ let id = config.id+ var descriptor = FetchDescriptor<SavedConnectionEntity>(+ predicate: #Predicate { $0.id == id }+ )+ descriptor.fetchLimit = 1+ guard let entity = try context.fetch(descriptor).first else { return }++ entity.name = config.name+ entity.databaseType = config.databaseType.rawValue+ entity.host = config.host+ entity.port = config.port+ entity.database = config.database+ entity.username = config.username+ entity.sslEnabled = config.sslEnabled+ entity.colorTag = config.colorTag?.rawValue+ entity.group = config.group+ entity.filePath = config.filePath+ entity.sshEnabled = config.sshConfig != nil+ entity.sshHost = config.sshConfig?.host+ entity.sshPort = config.sshConfig?.port+ entity.sshUsername = config.sshConfig?.username+ entity.sshAuthMethod = config.sshConfig?.authMethod.rawValue+ entity.sshKeyPath = config.sshConfig?.keyPath++ try context.save()+ }++ @MainActor+ func delete(_ id: UUID) async throws {+ let context = modelContainer.mainContext+ let descriptor = FetchDescriptor<SavedConnectionEntity>(+ predicate: #Predicate { $0.id == id }+ )+ if let entity = try context.fetch(descriptor).first {+ context.delete(entity)+ try context.save()+ }+ }++ @MainActor+ func updateLastConnected(_ id: UUID, date: Date) async throws {+ let context = modelContainer.mainContext+ var descriptor = FetchDescriptor<SavedConnectionEntity>(+ predicate: #Predicate { $0.id == id }+ )+ descriptor.fetchLimit = 1+ if let entity = try context.fetch(descriptor).first {+ entity.lastConnectedAt = date+ try context.save()+ }+ }++ @MainActor+ func reorder(ids: [UUID]) async throws {+ // TODO: Update sortOrder for each entity+ }+}diff --git a/macos/Data/Persistence/Repositories/SwiftDataQueryHistoryRepository.swift b/macos/Data/Persistence/Repositories/SwiftDataQueryHistoryRepository.swiftnew file mode 100644index 0000000..ff47240--- /dev/null+++ b/macos/Data/Persistence/Repositories/SwiftDataQueryHistoryRepository.swift@@ -0,0 +1,114 @@+// SwiftDataQueryHistoryRepository.swift+// Gridex++import Foundation+import SwiftData++final class SwiftDataQueryHistoryRepository: QueryHistoryRepository, @unchecked Sendable {+ private let modelContainer: ModelContainer++ init(modelContainer: ModelContainer) {+ self.modelContainer = modelContainer+ }++ @MainActor+ func save(entry: QueryHistoryEntry) async throws {+ let context = modelContainer.mainContext+ let entity = QueryHistoryEntity(+ id: entry.id,+ connectionId: entry.connectionId,+ database: entry.database,+ sql: entry.sql,+ executedAt: entry.executedAt,+ duration: entry.duration,+ rowCount: entry.rowCount,+ status: entry.status.rawValue,+ errorMessage: entry.errorMessage,+ isFavorite: entry.isFavorite+ )+ context.insert(entity)+ try context.save()+ }++ @MainActor+ func fetchRecent(connectionId: UUID, limit: Int) async throws -> [QueryHistoryEntry] {+ let context = modelContainer.mainContext+ var descriptor = FetchDescriptor<QueryHistoryEntity>(+ predicate: #Predicate { $0.connectionId == connectionId },+ sortBy: [SortDescriptor(\.executedAt, order: .reverse)]+ )+ descriptor.fetchLimit = limit+ return try context.fetch(descriptor).map { toEntry($0) }+ }++ @MainActor+ func search(query: String, connectionId: UUID?) async throws -> [QueryHistoryEntry] {+ let context = modelContainer.mainContext+ var descriptor: FetchDescriptor<QueryHistoryEntity>+ if let connectionId {+ descriptor = FetchDescriptor<QueryHistoryEntity>(+ predicate: #Predicate { $0.connectionId == connectionId && $0.sql.contains(query) },+ sortBy: [SortDescriptor(\.executedAt, order: .reverse)]+ )+ } else {+ descriptor = FetchDescriptor<QueryHistoryEntity>(+ predicate: #Predicate { $0.sql.contains(query) },+ sortBy: [SortDescriptor(\.executedAt, order: .reverse)]+ )+ }+ descriptor.fetchLimit = 100+ return try context.fetch(descriptor).map { toEntry($0) }+ }++ @MainActor+ func toggleFavorite(id: UUID) async throws {+ let context = modelContainer.mainContext+ var descriptor = FetchDescriptor<QueryHistoryEntity>(+ predicate: #Predicate { $0.id == id }+ )+ descriptor.fetchLimit = 1+ if let entity = try context.fetch(descriptor).first {+ entity.isFavorite.toggle()+ try context.save()+ }+ }++ @MainActor+ func delete(id: UUID) async throws {+ let context = modelContainer.mainContext+ let descriptor = FetchDescriptor<QueryHistoryEntity>(+ predicate: #Predicate { $0.id == id }+ )+ if let entity = try context.fetch(descriptor).first {+ context.delete(entity)+ try context.save()+ }+ }++ @MainActor+ func deleteAll(connectionId: UUID) async throws {+ let context = modelContainer.mainContext+ let descriptor = FetchDescriptor<QueryHistoryEntity>(+ predicate: #Predicate { $0.connectionId == connectionId }+ )+ for entity in try context.fetch(descriptor) {+ context.delete(entity)+ }+ try context.save()+ }++ private func toEntry(_ entity: QueryHistoryEntity) -> QueryHistoryEntry {+ QueryHistoryEntry(+ id: entity.id,+ connectionId: entity.connectionId,+ database: entity.database,+ sql: entity.sql,+ executedAt: entity.executedAt,+ duration: entity.duration,+ rowCount: entity.rowCount,+ status: QueryHistoryEntry.QueryStatus(rawValue: entity.status) ?? .success,+ errorMessage: entity.errorMessage,+ isFavorite: entity.isFavorite+ )+ }+}diff --git a/macos/Domain/Repositories/AIConversationRepository.swift b/macos/Domain/Repositories/AIConversationRepository.swiftnew file mode 100644index 0000000..619c67f--- /dev/null+++ b/macos/Domain/Repositories/AIConversationRepository.swift@@ -0,0 +1,20 @@+// AIConversationRepository.swift+// Gridex++import Foundation++protocol AIConversationRepository: Sendable {+ func save(conversation: AIConversation) async throws+ func fetch(connectionId: UUID) async throws -> [AIConversation]+ func fetchByID(_ id: UUID) async throws -> AIConversation?+ func update(_ conversation: AIConversation) async throws+ func delete(_ id: UUID) async throws+}++struct AIConversation: Sendable, Identifiable {+ let id: UUID+ let connectionId: UUID+ var messages: [ChatMessage]+ let createdAt: Date+ var updatedAt: Date+}diff --git a/macos/Domain/Repositories/ConnectionRepository.swift b/macos/Domain/Repositories/ConnectionRepository.swiftnew file mode 100644index 0000000..002988e--- /dev/null+++ b/macos/Domain/Repositories/ConnectionRepository.swift@@ -0,0 +1,17 @@+// ConnectionRepository.swift+// Gridex+//+// Repository protocol for managing saved connections.++import Foundation++protocol ConnectionRepository: Sendable {+ func fetchAll() async throws -> [ConnectionConfig]+ func fetchByID(_ id: UUID) async throws -> ConnectionConfig?+ func fetchByGroup(_ group: String) async throws -> [ConnectionConfig]+ func save(_ config: ConnectionConfig) async throws+ func update(_ config: ConnectionConfig) async throws+ func delete(_ id: UUID) async throws+ func updateLastConnected(_ id: UUID, date: Date) async throws+ func reorder(ids: [UUID]) async throws+}diff --git a/macos/Domain/Repositories/QueryHistoryRepository.swift b/macos/Domain/Repositories/QueryHistoryRepository.swiftnew file mode 100644index 0000000..0b52a9c--- /dev/null+++ b/macos/Domain/Repositories/QueryHistoryRepository.swift@@ -0,0 +1,31 @@+// QueryHistoryRepository.swift+// Gridex++import Foundation++protocol QueryHistoryRepository: Sendable {+ func save(entry: QueryHistoryEntry) async throws+ func fetchRecent(connectionId: UUID, limit: Int) async throws -> [QueryHistoryEntry]+ func search(query: String, connectionId: UUID?) async throws -> [QueryHistoryEntry]+ func toggleFavorite(id: UUID) async throws+ func delete(id: UUID) async throws+ func deleteAll(connectionId: UUID) async throws+}++struct QueryHistoryEntry: Sendable, Identifiable {+ let id: UUID+ let connectionId: UUID+ let database: String+ let sql: String+ let executedAt: Date+ let duration: TimeInterval+ let rowCount: Int?+ let status: QueryStatus+ let errorMessage: String?+ var isFavorite: Bool++ enum QueryStatus: String, Sendable {+ case success+ case error+ }+}diff --git a/macos/Domain/Repositories/WorkspaceRepository.swift b/macos/Domain/Repositories/WorkspaceRepository.swiftnew file mode 100644index 0000000..b8c363b--- /dev/null+++ b/macos/Domain/Repositories/WorkspaceRepository.swift@@ -0,0 +1,45 @@+// WorkspaceRepository.swift+// Gridex++import Foundation++protocol WorkspaceRepository: Sendable {+ func save(state: WorkspaceState) async throws+ func fetch(connectionId: UUID) async throws -> WorkspaceState?+ func update(_ state: WorkspaceState) async throws+ func delete(connectionId: UUID) async throws+}++struct WorkspaceState: Sendable {+ let id: UUID+ let connectionId: UUID+ var openTabs: [TabState]+ var activeTabIndex: Int+ var sidebarWidth: Double+ var aiPanelVisible: Bool+ var aiPanelWidth: Double+ var lastOpenedAt: Date+}++struct TabState: Codable, Sendable {+ let id: UUID+ let type: TabType+ let title: String+ let tableName: String?+ let schema: String?+ let query: String?++ enum TabType: String, Codable, Sendable {+ case dataGrid+ case queryEditor+ case tableStructure+ case tableList+ case functionDetail+ case createTable+ case erDiagram+ // Redis-specific+ case redisKeyDetail+ case redisServerInfo+ case redisSlowLog+ }+}diff --git a/macos/Domain/UseCases/AI/AIChatUseCase.swift b/macos/Domain/UseCases/AI/AIChatUseCase.swiftnew file mode 100644index 0000000..4ca8963--- /dev/null+++ b/macos/Domain/UseCases/AI/AIChatUseCase.swift@@ -0,0 +1,15 @@+// AIChatUseCase.swift+// Gridex++import Foundation++protocol AIChatUseCase: Sendable {+ func sendMessage(+ _ message: String,+ conversation: AIConversation,+ schema: SchemaSnapshot,+ connectionInfo: ConnectionConfig+ ) -> AsyncThrowingStream<String, Error>++ func suggestQuestions(for schema: SchemaSnapshot) async throws -> [String]+}diff --git a/macos/Domain/UseCases/Connection/ConnectDatabaseUseCase.swift b/macos/Domain/UseCases/Connection/ConnectDatabaseUseCase.swiftnew file mode 100644index 0000000..7138453--- /dev/null+++ b/macos/Domain/UseCases/Connection/ConnectDatabaseUseCase.swift@@ -0,0 +1,22 @@+// ConnectDatabaseUseCase.swift+// Gridex+//+// Orchestrates the full connection flow:+// 1. Resolve SSH tunnel if needed+// 2. Create appropriate adapter+// 3. Establish connection+// 4. Load initial schema++import Foundation++protocol ConnectDatabaseUseCase: Sendable {+ func execute(config: ConnectionConfig, password: String?, sshPassword: String?) async throws -> ActiveConnection+}++struct ActiveConnection: Sendable {+ let id: UUID+ let config: ConnectionConfig+ let adapter: any DatabaseAdapter+ let initialSchema: SchemaSnapshot?+ let connectedAt: Date+}diff --git a/macos/Domain/UseCases/Connection/TestConnectionUseCase.swift b/macos/Domain/UseCases/Connection/TestConnectionUseCase.swiftnew file mode 100644index 0000000..29a5c2f--- /dev/null+++ b/macos/Domain/UseCases/Connection/TestConnectionUseCase.swift@@ -0,0 +1,15 @@+// TestConnectionUseCase.swift+// Gridex++import Foundation++protocol TestConnectionUseCase: Sendable {+ func execute(config: ConnectionConfig, password: String?, sshPassword: String?) async throws -> ConnectionTestResult+}++struct ConnectionTestResult: Sendable {+ let success: Bool+ let serverVersion: String?+ let latency: TimeInterval+ let errorMessage: String?+}diff --git a/macos/Domain/UseCases/DataGrid/ChangeTracker.swift b/macos/Domain/UseCases/DataGrid/ChangeTracker.swiftnew file mode 100644index 0000000..40a7a8b--- /dev/null+++ b/macos/Domain/UseCases/DataGrid/ChangeTracker.swift@@ -0,0 +1,47 @@+// ChangeTracker.swift+// Gridex+//+// Tracks inline edits in the data grid before committing.++import Foundation++protocol ChangeTracker: AnyObject, Sendable {+ var pendingChanges: [CellEdit] { get }+ var hasChanges: Bool { get }++ func trackEdit(row: Int, column: String, oldValue: RowValue, newValue: RowValue, primaryKey: RowDictionary?)+ func trackInsert(values: RowDictionary)+ func trackDelete(row: Int, primaryKey: RowDictionary)+ func removeInserts()+ func discardChange(at index: Int)+ func discardAll()+ func generateSQL(table: String, schema: String?, dialect: SQLDialect) -> [(sql: String, parameters: [RowValue])]+}++struct CellEdit: Sendable, Identifiable {+ let id: UUID+ let editType: EditType+ let row: Int+ let column: String?+ let oldValue: RowValue?+ let newValue: RowValue?+ let primaryKey: RowDictionary?+ let timestamp: Date++ enum EditType: Sendable {+ case update+ case insert+ case delete+ }++ init(id: UUID = UUID(), editType: EditType, row: Int, column: String? = nil, oldValue: RowValue? = nil, newValue: RowValue? = nil, primaryKey: RowDictionary? = nil) {+ self.id = id+ self.editType = editType+ self.row = row+ self.column = column+ self.oldValue = oldValue+ self.newValue = newValue+ self.primaryKey = primaryKey+ self.timestamp = Date()+ }+}diff --git a/macos/Domain/UseCases/DataGrid/DefaultChangeTracker.swift b/macos/Domain/UseCases/DataGrid/DefaultChangeTracker.swiftnew file mode 100644index 0000000..27e26be--- /dev/null+++ b/macos/Domain/UseCases/DataGrid/DefaultChangeTracker.swift@@ -0,0 +1,144 @@+// DefaultChangeTracker.swift+// Gridex+//+// Concrete implementation of ChangeTracker.+// Tracks cell edits, inserts, and deletes; generates commit SQL.++import Foundation++final class DefaultChangeTracker: ChangeTracker, @unchecked Sendable {+ private let lock = NSLock()+ private var _changes: [CellEdit] = []++ var pendingChanges: [CellEdit] {+ lock.lock()+ defer { lock.unlock() }+ return _changes+ }++ var hasChanges: Bool {+ lock.lock()+ defer { lock.unlock() }+ return !_changes.isEmpty+ }++ func trackEdit(row: Int, column: String, oldValue: RowValue, newValue: RowValue, primaryKey: RowDictionary? = nil) {+ guard oldValue != newValue else { return }+ lock.lock()+ defer { lock.unlock() }++ // If there's already an edit for the same row+column, update it+ if let idx = _changes.firstIndex(where: { $0.row == row && $0.column == column && $0.editType == .update }) {+ let existing = _changes[idx]+ // If reverting to original, remove the change+ if existing.oldValue == newValue {+ _changes.remove(at: idx)+ return+ }+ _changes[idx] = CellEdit(editType: .update, row: row, column: column, oldValue: existing.oldValue, newValue: newValue, primaryKey: existing.primaryKey ?? primaryKey)+ } else {+ _changes.append(CellEdit(editType: .update, row: row, column: column, oldValue: oldValue, newValue: newValue, primaryKey: primaryKey))+ }+ }++ func trackInsert(values: RowDictionary) {+ lock.lock()+ defer { lock.unlock() }+ _changes.append(CellEdit(editType: .insert, row: -1, newValue: nil, primaryKey: values))+ }++ func trackDelete(row: Int, primaryKey: RowDictionary) {+ lock.lock()+ defer { lock.unlock() }++ // Remove any pending edits for this row+ _changes.removeAll { $0.row == row && $0.editType == .update }+ _changes.append(CellEdit(editType: .delete, row: row, primaryKey: primaryKey))+ }++ func removeInserts() {+ lock.lock()+ defer { lock.unlock() }+ _changes.removeAll { $0.editType == .insert }+ }++ func discardChange(at index: Int) {+ lock.lock()+ defer { lock.unlock() }+ guard _changes.indices.contains(index) else { return }+ _changes.remove(at: index)+ }++ func discardAll() {+ lock.lock()+ defer { lock.unlock() }+ _changes.removeAll()+ }++ func generateSQL(table: String, schema: String?, dialect: SQLDialect) -> [(sql: String, parameters: [RowValue])] {+ lock.lock()+ let changes = _changes+ lock.unlock()++ let qt: String+ if let schema, !schema.isEmpty {+ qt = "\(dialect.quoteIdentifier(schema)).\(dialect.quoteIdentifier(table))"+ } else {+ qt = dialect.quoteIdentifier(table)+ }+ var statements: [(sql: String, parameters: [RowValue])] = []++ for edit in changes {+ switch edit.editType {+ case .update:+ guard let column = edit.column, let newValue = edit.newValue, let pk = edit.primaryKey else { continue }+ var params: [RowValue] = []+ var paramIndex = 1+ let setClause = "\(dialect.quoteIdentifier(column)) = \(placeholder(dialect: dialect, index: ¶mIndex))"+ params.append(newValue)+ let whereClause = pk.map { key, value -> String in+ whereCondition(key, value, dialect: dialect, params: ¶ms, paramIndex: ¶mIndex)+ }.joined(separator: " AND ")+ statements.append((sql: "UPDATE \(qt) SET \(setClause) WHERE \(whereClause);", parameters: params))++ case .insert:+ guard let pk = edit.primaryKey else { continue }+ var params: [RowValue] = []+ var paramIndex = 1+ let entries = Array(pk)+ let cols = entries.map { dialect.quoteIdentifier($0.key) }.joined(separator: ", ")+ let placeholders = entries.map { entry -> String in+ params.append(entry.value)+ return placeholder(dialect: dialect, index: ¶mIndex)+ }.joined(separator: ", ")+ statements.append((sql: "INSERT INTO \(qt) (\(cols)) VALUES (\(placeholders));", parameters: params))++ case .delete:+ guard let pk = edit.primaryKey else { continue }+ var params: [RowValue] = []+ var paramIndex = 1+ let whereClause = pk.map { key, value -> String in+ whereCondition(key, value, dialect: dialect, params: ¶ms, paramIndex: ¶mIndex)+ }.joined(separator: " AND ")+ statements.append((sql: "DELETE FROM \(qt) WHERE \(whereClause);", parameters: params))+ }+ }++ return statements+ }++ private func placeholder(dialect: SQLDialect, index: inout Int) -> String {+ let p = dialect.parameterPlaceholder(index)+ index += 1+ return p+ }++ private func whereCondition(_ key: String, _ value: RowValue, dialect: SQLDialect, params: inout [RowValue], paramIndex: inout Int) -> String {+ if case .null = value {+ return "\(dialect.quoteIdentifier(key)) IS NULL"+ }+ let p = placeholder(dialect: dialect, index: ¶mIndex)+ params.append(value)+ return "\(dialect.quoteIdentifier(key)) = \(p)"+ }+}diff --git a/macos/Domain/UseCases/Export/ExportDataUseCase.swift b/macos/Domain/UseCases/Export/ExportDataUseCase.swiftnew file mode 100644index 0000000..5c1f0a2--- /dev/null+++ b/macos/Domain/UseCases/Export/ExportDataUseCase.swift@@ -0,0 +1,12 @@+// ExportDataUseCase.swift+// Gridex++import Foundation++protocol ExportDataUseCase: Sendable {+ func exportCSV(data: QueryResult, to url: URL) async throws+ func exportJSON(data: QueryResult, to url: URL) async throws+ func exportSQL(data: QueryResult, table: String, to url: URL) async throws+ func exportExcel(data: QueryResult, to url: URL) async throws+ func exportSchemaDDL(schema: SchemaSnapshot, to url: URL) async throws+}diff --git a/macos/Domain/UseCases/Query/ExecuteQueryUseCase.swift b/macos/Domain/UseCases/Query/ExecuteQueryUseCase.swiftnew file mode 100644index 0000000..8b02f6c--- /dev/null+++ b/macos/Domain/UseCases/Query/ExecuteQueryUseCase.swift@@ -0,0 +1,9 @@+// ExecuteQueryUseCase.swift+// Gridex++import Foundation++protocol ExecuteQueryUseCase: Sendable {+ func execute(sql: String, connectionId: UUID, parameters: [QueryParameter]?) async throws -> QueryResult+ func cancel() async+}diff --git a/macos/Domain/UseCases/Schema/InspectSchemaUseCase.swift b/macos/Domain/UseCases/Schema/InspectSchemaUseCase.swiftnew file mode 100644index 0000000..1bd3806--- /dev/null+++ b/macos/Domain/UseCases/Schema/InspectSchemaUseCase.swift@@ -0,0 +1,10 @@+// InspectSchemaUseCase.swift+// Gridex++import Foundation++protocol InspectSchemaUseCase: Sendable {+ func loadFullSchema(connectionId: UUID) async throws -> SchemaSnapshot+ func refreshSchema(connectionId: UUID) async throws -> SchemaSnapshot+ func describeTable(name: String, schema: String?, connectionId: UUID) async throws -> TableDescription+}diff --git a/macos/Presentation/ViewModels/AIChatViewModel.swift b/macos/Presentation/ViewModels/AIChatViewModel.swiftnew file mode 100644index 0000000..8df8b1c--- /dev/null+++ b/macos/Presentation/ViewModels/AIChatViewModel.swift@@ -0,0 +1,96 @@+// AIChatViewModel.swift+// Gridex++import Foundation++@MainActor+final class AIChatViewModel: ObservableObject {+ @Published var messages: [ChatMessage] = []+ @Published var isStreaming: Bool = false+ @Published var suggestedQuestions: [String] = []+ @Published var errorMessage: String?++ private let chatUseCase: any AIChatUseCase+ private let queryEngine: QueryEngine+ private var currentStreamTask: Task<Void, Never>?+ private var connectionId: UUID+ private var schema: SchemaSnapshot?+ private var connectionConfig: ConnectionConfig?++ init(chatUseCase: any AIChatUseCase, queryEngine: QueryEngine, connectionId: UUID) {+ self.chatUseCase = chatUseCase+ self.queryEngine = queryEngine+ self.connectionId = connectionId+ }++ deinit {+ currentStreamTask?.cancel()+ }++ func configure(schema: SchemaSnapshot, config: ConnectionConfig) {+ self.schema = schema+ self.connectionConfig = config+ }++ func sendMessage(_ text: String) {+ guard let schema, let config = connectionConfig else { return }++ let userMessage = ChatMessage(role: .user, content: text)+ messages.append(userMessage)++ let conversation = AIConversation(+ id: UUID(),+ connectionId: connectionId,+ messages: messages,+ createdAt: Date(),+ updatedAt: Date()+ )++ isStreaming = true++ currentStreamTask = Task { [weak self] in+ guard let self else { return }+ var assistantContent = ""+ do {+ let stream = chatUseCase.sendMessage(text, conversation: conversation, schema: schema, connectionInfo: config)+ for try await token in stream {+ assistantContent += token+ // Update last message in real-time+ if self.messages.last?.role == .assistant {+ self.messages[self.messages.count - 1] = ChatMessage(role: .assistant, content: assistantContent)+ } else {+ self.messages.append(ChatMessage(role: .assistant, content: assistantContent))+ }+ }+ } catch {+ self.errorMessage = error.localizedDescription+ self.messages.append(ChatMessage(role: .assistant, content: "Error: \(error.localizedDescription)"))+ }+ self.isStreaming = false+ }+ }++ func stopStreaming() {+ currentStreamTask?.cancel()+ currentStreamTask = nil+ isStreaming = false+ }++ func dismissError() {+ errorMessage = nil+ }++ func clearChat() {+ messages.removeAll()+ }++ func executeSQL(_ sql: String) async {+ do {+ let result = try await queryEngine.execute(sql: sql, connectionId: connectionId)+ let resultMessage = "Query executed successfully. \(result.rowCount) rows returned in \(Int(result.executionTime * 1000))ms."+ messages.append(ChatMessage(role: .assistant, content: resultMessage))+ } catch {+ messages.append(ChatMessage(role: .assistant, content: "Query error: \(error.localizedDescription)"))+ }+ }+}diff --git a/macos/Presentation/ViewModels/ConnectionListViewModel.swift b/macos/Presentation/ViewModels/ConnectionListViewModel.swiftnew file mode 100644index 0000000..349fbe2--- /dev/null+++ b/macos/Presentation/ViewModels/ConnectionListViewModel.swift@@ -0,0 +1,63 @@+// ConnectionListViewModel.swift+// Gridex++import Foundation++@MainActor+final class ConnectionListViewModel: ObservableObject {+ @Published var connections: [ConnectionConfig] = []+ @Published var activeConnectionIds: Set<UUID> = []+ @Published var isLoading = false+ @Published var error: String?++ private let repository: any ConnectionRepository+ private let connectionManager: ConnectionManager+ private let keychainService: KeychainServiceProtocol++ init(+ repository: any ConnectionRepository,+ connectionManager: ConnectionManager,+ keychainService: KeychainServiceProtocol+ ) {+ self.repository = repository+ self.connectionManager = connectionManager+ self.keychainService = keychainService+ }++ func loadConnections() async {+ isLoading = true+ defer { isLoading = false }++ do {+ connections = try await repository.fetchAll()+ } catch {+ self.error = error.localizedDescription+ }+ }++ func connect(config: ConnectionConfig, password: String) async throws {+ let sshPassword: String? = config.sshConfig != nil+ ? (try? keychainService.load(key: "ssh.password.\(config.id.uuidString)")) ?? nil+ : nil+ let _ = try await connectionManager.connect(config: config, password: password, sshPassword: sshPassword)+ activeConnectionIds.insert(config.id)+ try await repository.updateLastConnected(config.id, date: Date())+ }++ func disconnect(connectionId: UUID) async throws {+ try await connectionManager.disconnect(connectionId: connectionId)+ activeConnectionIds.remove(connectionId)+ }++ func saveConnection(_ config: ConnectionConfig, password: String) async throws {+ try await repository.save(config)+ try keychainService.save(key: "db.password.\(config.id.uuidString)", value: password)+ await loadConnections()+ }++ func deleteConnection(_ id: UUID) async throws {+ try await repository.delete(id)+ try keychainService.delete(key: "db.password.\(id.uuidString)")+ await loadConnections()+ }+}diff --git a/macos/Presentation/ViewModels/DataGridViewModel.swift b/macos/Presentation/ViewModels/DataGridViewModel.swiftnew file mode 100644index 0000000..8600650--- /dev/null+++ b/macos/Presentation/ViewModels/DataGridViewModel.swift@@ -0,0 +1,70 @@+// DataGridViewModel.swift+// Gridex++import Foundation++@MainActor+final class DataGridViewModel: ObservableObject {+ @Published var columns: [ColumnHeader] = []+ @Published var rows: [[RowValue]] = []+ @Published var totalRows: Int = 0+ @Published var currentPage: Int = 0+ @Published var isLoading: Bool = false+ @Published var executionTime: TimeInterval = 0+ @Published var pendingChangesCount: Int = 0+ @Published var errorMessage: String?++ private let queryEngine: QueryEngine+ private let connectionId: UUID+ private let pageSize: Int++ var tableName: String = ""+ var schema: String?++ init(queryEngine: QueryEngine, connectionId: UUID, pageSize: Int = 500) {+ self.queryEngine = queryEngine+ self.connectionId = connectionId+ self.pageSize = pageSize+ }++ func loadTable(name: String, schema: String? = nil) async {+ self.tableName = name+ self.schema = schema+ await loadPage(0)+ }++ func loadPage(_ page: Int) async {+ isLoading = true+ defer { isLoading = false }++ let offset = page * pageSize+ let sql = "SELECT * FROM \(tableName) LIMIT \(pageSize) OFFSET \(offset)"++ do {+ let result = try await queryEngine.execute(sql: sql, connectionId: connectionId)+ self.columns = result.columns+ self.rows = result.rows+ self.executionTime = result.executionTime+ self.currentPage = page+ } catch {+ errorMessage = error.localizedDescription+ }+ }++ func nextPage() async {+ await loadPage(currentPage + 1)+ }++ func previousPage() async {+ guard currentPage > 0 else { return }+ await loadPage(currentPage - 1)+ }++ func refresh() async {+ await loadPage(currentPage)+ }++ func dismissError() {+ errorMessage = nil+ }+}diff --git a/macos/Presentation/Views/AIChat/AIChatView.swift b/macos/Presentation/Views/AIChat/AIChatView.swiftnew file mode 100644index 0000000..040a8d6--- /dev/null+++ b/macos/Presentation/Views/AIChat/AIChatView.swift@@ -0,0 +1,927 @@+// AIChatView.swift+// Gridex+//+// SwiftUI AI chat panel with streaming responses.++import SwiftUI++// Observable message class — mutations don't trigger ForEach diffing+final class ChatDisplayMessage: ObservableObject, Identifiable {+ let id: UUID+ let role: ChatRole+ @Published var content: String++ enum ChatRole {+ case user, assistant+ }++ init(role: ChatRole, content: String) {+ self.id = UUID()+ self.role = role+ self.content = content+ }+}++struct AIChatView: View {+ @EnvironmentObject private var appState: AppState+ @AppStorage("ai.provider") private var providerType = "gemini"+ @AppStorage("ai.provider.baseURL") private var baseURL = "https://generativelanguage.googleapis.com/v1beta/openai"+ @AppStorage("ai.provider.enabled") private var isEnabled = true+ @AppStorage("ai.provider.model") private var selectedModel = "gemini-2.5-flash"+ @State private var inputText = ""+ @State private var isStreaming = false+ @State private var errorMessage: String?+ @State private var apiKeyLoaded = false+ @State private var attachedTables: Set<String> = []+ @State private var showTablePicker = false++ private var messages: [ChatDisplayMessage] {+ get {+ guard let connId = appState.activeConnectionId else { return [] }+ return appState.aiChatMessages[connId] ?? []+ }+ }++ private func appendMessage(_ msg: ChatDisplayMessage) {+ guard let connId = appState.activeConnectionId else { return }+ if appState.aiChatMessages[connId] == nil {+ appState.aiChatMessages[connId] = []+ }+ appState.aiChatMessages[connId]!.append(msg)+ appState.objectWillChange.send()+ }++ private func clearMessages() {+ guard let connId = appState.activeConnectionId else { return }+ appState.aiChatMessages[connId] = []+ appState.objectWillChange.send()+ }++ var body: some View {+ VStack(spacing: 0) {+ header++ if !apiKeyLoaded {+ setupPrompt+ } else if messages.isEmpty {+ welcomeScreen+ } else {+ messageList+ }++ inputBar+ }+ .background(Color(nsColor: .windowBackgroundColor))+ .alert("Error", isPresented: Binding(+ get: { errorMessage != nil },+ set: { if !$0 { errorMessage = nil } }+ )) {+ Button("OK", role: .cancel) {}+ } message: {+ Text(errorMessage ?? "")+ }+ .onAppear { refreshAPIKeyState() }+ .onChange(of: providerType) { _, _ in refreshAPIKeyState() }+ .onChange(of: isEnabled) { _, _ in refreshAPIKeyState() }+ }++ // MARK: - Subviews++ private var header: some View {+ HStack(spacing: 10) {+ // Animated brand icon with gradient+ ZStack {+ LinearGradient(+ colors: [Color.purple, Color.blue],+ startPoint: .topLeading,+ endPoint: .bottomTrailing+ )+ .frame(width: 26, height: 26)+ .clipShape(RoundedRectangle(cornerRadius: 7, style: .continuous))+ Image(systemName: "sparkles")+ .font(.system(size: 12, weight: .semibold))+ .foregroundStyle(.white)+ }++ VStack(alignment: .leading, spacing: 1) {+ Text("AI Assistant")+ .font(.system(size: 13, weight: .semibold))+ HStack(spacing: 4) {+ Circle()+ .fill(apiKeyLoaded ? Color.green : Color.orange)+ .frame(width: 6, height: 6)+ Text(apiKeyLoaded ? selectedModel : "Not configured")+ .font(.system(size: 10))+ .foregroundStyle(.secondary)+ .lineLimit(1)+ }+ }++ Spacer()++ if !messages.isEmpty {+ Button(action: clearMessages) {+ Image(systemName: "arrow.counterclockwise")+ .font(.system(size: 11, weight: .medium))+ .foregroundStyle(.secondary)+ .frame(width: 26, height: 26)+ .background(Color.primary.opacity(0.06))+ .clipShape(Circle())+ }+ .buttonStyle(.plain)+ .help("New chat")+ }+ SettingsLink {+ Image(systemName: "gearshape")+ .font(.system(size: 11, weight: .medium))+ .foregroundStyle(.secondary)+ .frame(width: 26, height: 26)+ .background(Color.primary.opacity(0.06))+ .clipShape(Circle())+ }+ .buttonStyle(.plain)+ .help("AI Settings")+ }+ .padding(.horizontal, 14)+ .padding(.vertical, 10)+ .background(Color(nsColor: .windowBackgroundColor))+ .overlay(alignment: .bottom) {+ Divider().opacity(0.5)+ }+ }++ private var setupPrompt: some View {+ VStack(spacing: 16) {+ Spacer()+ ZStack {+ LinearGradient(+ colors: [Color.purple.opacity(0.2), Color.blue.opacity(0.2)],+ startPoint: .topLeading,+ endPoint: .bottomTrailing+ )+ .frame(width: 72, height: 72)+ .clipShape(Circle())+ Image(systemName: "sparkles")+ .font(.system(size: 30, weight: .medium))+ .foregroundStyle(+ LinearGradient(+ colors: [.purple, .blue],+ startPoint: .topLeading,+ endPoint: .bottomTrailing+ )+ )+ }+ VStack(spacing: 6) {+ Text("Welcome to AI Assistant")+ .font(.system(size: 15, weight: .semibold))+ Text("Connect an AI provider to start chatting\nwith your database.")+ .font(.system(size: 12))+ .foregroundStyle(.secondary)+ .multilineTextAlignment(.center)+ }+ SettingsLink {+ HStack(spacing: 6) {+ Image(systemName: "gearshape.fill")+ .font(.system(size: 11))+ Text("Configure AI Settings")+ .font(.system(size: 12, weight: .medium))+ }+ .padding(.horizontal, 14)+ .padding(.vertical, 8)+ .background(+ LinearGradient(+ colors: [.purple, .blue],+ startPoint: .leading,+ endPoint: .trailing+ )+ )+ .foregroundStyle(.white)+ .clipShape(Capsule())+ }+ .buttonStyle(.plain)+ Spacer()+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ .padding()+ }++ /// Welcome screen with suggested prompts shown when chat is empty+ private var welcomeScreen: some View {+ ScrollView {+ VStack(spacing: 18) {+ Spacer().frame(height: 30)+ ZStack {+ LinearGradient(+ colors: [Color.purple.opacity(0.18), Color.blue.opacity(0.18)],+ startPoint: .topLeading,+ endPoint: .bottomTrailing+ )+ .frame(width: 64, height: 64)+ .clipShape(Circle())+ Image(systemName: "sparkles")+ .font(.system(size: 26, weight: .medium))+ .foregroundStyle(+ LinearGradient(+ colors: [.purple, .blue],+ startPoint: .topLeading,+ endPoint: .bottomTrailing+ )+ )+ }++ VStack(spacing: 4) {+ Text("How can I help you?")+ .font(.system(size: 16, weight: .semibold))+ Text("Ask me anything about your database")+ .font(.system(size: 12))+ .foregroundStyle(.secondary)+ }++ // Suggested prompts+ VStack(spacing: 8) {+ ForEach(suggestedPrompts, id: \.0) { prompt in+ Button {+ inputText = prompt.1+ } label: {+ HStack(spacing: 10) {+ Image(systemName: prompt.0)+ .font(.system(size: 12))+ .foregroundStyle(.purple)+ .frame(width: 22, height: 22)+ .background(Color.purple.opacity(0.12))+ .clipShape(RoundedRectangle(cornerRadius: 6, style: .continuous))+ Text(prompt.1)+ .font(.system(size: 12))+ .foregroundStyle(.primary)+ .multilineTextAlignment(.leading)+ Spacer()+ Image(systemName: "arrow.up.right")+ .font(.system(size: 9))+ .foregroundStyle(.tertiary)+ }+ .padding(.horizontal, 12)+ .padding(.vertical, 10)+ .background(Color.primary.opacity(0.04))+ .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))+ .overlay {+ RoundedRectangle(cornerRadius: 10, style: .continuous)+ .stroke(Color.primary.opacity(0.06), lineWidth: 1)+ }+ }+ .buttonStyle(.plain)+ }+ }+ .padding(.horizontal, 14)+ .padding(.top, 4)+ Spacer()+ }+ }+ }++ private var suggestedPrompts: [(String, String)] {+ [+ ("doc.text.magnifyingglass", "Show me the schema of all tables"),+ ("chart.bar.fill", "Find the top 10 records by date"),+ ("text.alignleft", "Generate a SQL query to count rows"),+ ("lightbulb.fill", "Explain the relationships between tables"),+ ]+ }++ private var messageList: some View {+ ScrollViewReader { proxy in+ ScrollView {+ LazyVStack(alignment: .leading, spacing: 14) {+ ForEach(messages) { message in+ MessageBubble(message: message)+ .id(message.id)+ .transition(.asymmetric(+ insertion: .opacity.combined(with: .offset(y: 8)),+ removal: .opacity+ ))+ }++ if isStreaming, let last = messages.last, last.role == .assistant, last.content.isEmpty {+ TypingIndicator()+ .padding(.leading, 38)+ }+ }+ .padding(.horizontal, 14)+ .padding(.vertical, 16)+ }+ .onChange(of: messages.count) { _, _ in+ withAnimation(.spring(response: 0.4, dampingFraction: 0.8)) {+ if let last = messages.last {+ proxy.scrollTo(last.id, anchor: .bottom)+ }+ }+ }+ }+ }++ private var inputBar: some View {+ VStack(spacing: 0) {+ Divider().opacity(0.5)++ VStack(spacing: 6) {+ // Attached tables chips+ if !attachedTables.isEmpty {+ ScrollView(.horizontal, showsIndicators: false) {+ HStack(spacing: 6) {+ ForEach(Array(attachedTables).sorted(), id: \.self) { table in+ HStack(spacing: 4) {+ Image(systemName: "tablecells.fill")+ .font(.system(size: 9))+ .foregroundStyle(.purple)+ Text(table)+ .font(.system(size: 11, weight: .medium))+ Button {+ attachedTables.remove(table)+ } label: {+ Image(systemName: "xmark")+ .font(.system(size: 8, weight: .bold))+ .foregroundStyle(.secondary)+ }+ .buttonStyle(.plain)+ }+ .padding(.horizontal, 8)+ .padding(.vertical, 4)+ .background(Color.purple.opacity(0.12))+ .clipShape(Capsule())+ }+ }+ .padding(.horizontal, 14)+ }+ .padding(.top, 10)+ }++ // Input capsule+ HStack(spacing: 6) {+ // Attach button+ Button { showTablePicker.toggle() } label: {+ Image(systemName: "plus")+ .font(.system(size: 14, weight: .medium))+ .foregroundStyle(.secondary)+ .frame(width: 28, height: 28)+ .background(Color.primary.opacity(0.06))+ .clipShape(Circle())+ }+ .buttonStyle(.plain)+ .help("Attach tables for context")+ .popover(isPresented: $showTablePicker, arrowEdge: .top) {+ tablePickerPopover+ }++ TextField("Ask anything...", text: $inputText, axis: .vertical)+ .textFieldStyle(.plain)+ .font(.system(size: 13))+ .lineLimit(1...5)+ .onSubmit { sendMessage() }+ .padding(.horizontal, 4)++ // Send button — gradient when ready+ Button(action: sendMessage) {+ ZStack {+ if canSend {+ LinearGradient(+ colors: [.purple, .blue],+ startPoint: .topLeading,+ endPoint: .bottomTrailing+ )+ } else {+ Color.primary.opacity(0.08)+ }+ Image(systemName: "arrow.up")+ .font(.system(size: 13, weight: .bold))+ .foregroundStyle(canSend ? .white : .secondary)+ }+ .frame(width: 28, height: 28)+ .clipShape(Circle())+ }+ .buttonStyle(.plain)+ .disabled(!canSend)+ .animation(.easeInOut(duration: 0.15), value: canSend)+ }+ .padding(.horizontal, 8)+ .padding(.vertical, 6)+ .background(Color.primary.opacity(0.04))+ .clipShape(RoundedRectangle(cornerRadius: 18, style: .continuous))+ .overlay {+ RoundedRectangle(cornerRadius: 18, style: .continuous)+ .stroke(Color.primary.opacity(0.08), lineWidth: 1)+ }+ .padding(.horizontal, 12)+ .padding(.top, attachedTables.isEmpty ? 10 : 4)+ .padding(.bottom, 12)+ }+ }+ }++ private var canSend: Bool {+ apiKeyLoaded && !inputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && !isStreaming+ }++ private var tablePickerPopover: some View {+ let tables = availableTableNames+ return VStack(spacing: 0) {+ HStack(spacing: 6) {+ Image(systemName: "tablecells.fill")+ .font(.system(size: 11))+ .foregroundStyle(.purple)+ Text("Attach Tables")+ .font(.system(size: 12, weight: .semibold))+ Spacer()+ if !attachedTables.isEmpty {+ Text("\(attachedTables.count)")+ .font(.system(size: 10, weight: .semibold))+ .foregroundStyle(.purple)+ .padding(.horizontal, 6)+ .padding(.vertical, 1)+ .background(Color.purple.opacity(0.15))+ .clipShape(Capsule())+ }+ }+ .padding(.horizontal, 12)+ .padding(.vertical, 10)++ Divider().opacity(0.5)++ if tables.isEmpty {+ VStack(spacing: 6) {+ Image(systemName: "tray")+ .font(.system(size: 20))+ .foregroundStyle(.tertiary)+ Text("No tables available")+ .font(.system(size: 11))+ .foregroundStyle(.secondary)+ }+ .frame(maxWidth: .infinity)+ .padding(20)+ } else {+ ScrollView {+ VStack(alignment: .leading, spacing: 1) {+ ForEach(tables, id: \.self) { name in+ let isSelected = attachedTables.contains(name)+ Button {+ if isSelected {+ attachedTables.remove(name)+ } else {+ attachedTables.insert(name)+ }+ } label: {+ HStack(spacing: 8) {+ Image(systemName: isSelected ? "checkmark.circle.fill" : "circle")+ .font(.system(size: 13))+ .foregroundStyle(isSelected ? Color.purple : Color.secondary)+ Image(systemName: "tablecells")+ .font(.system(size: 10))+ .foregroundStyle(.secondary)+ Text(name)+ .font(.system(size: 12))+ .foregroundStyle(.primary)+ Spacer()+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 6)+ .background(isSelected ? Color.purple.opacity(0.08) : Color.clear)+ .clipShape(RoundedRectangle(cornerRadius: 6, style: .continuous))+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ }+ }+ .padding(6)+ }+ .frame(maxHeight: 280)+ }+ }+ .frame(width: 240)+ }++ private var availableTableNames: [String] {+ appState.sidebarItems.flatMap { item -> [String] in+ item.children.compactMap { child in+ switch child.type {+ case .table(let name): return name+ case .view(let name): return name+ default: return nil+ }+ }+ }.sorted()+ }++ // MARK: - Logic++ private func refreshAPIKeyState() {+ guard isEnabled else { apiKeyLoaded = false; return }+ let key = try? DependencyContainer.shared.keychainService.load(key: "ai.apikey.\(providerType)")+ apiKeyLoaded = key != nil && !key!.isEmpty+ }++ private func sendMessage() {+ let text = inputText.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !text.isEmpty else { return }++ let userMsg = ChatDisplayMessage(role: .user, content: text)+ appendMessage(userMsg)+ inputText = ""+ isStreaming = true++ // Capture attached tables for this message+ let currentAttached = attachedTables++ Task {+ guard let apiKey = try? DependencyContainer.shared.keychainService.load(key: "ai.apikey.\(providerType)"),+ !apiKey.isEmpty else {+ errorMessage = "API key not configured"+ isStreaming = false+ return+ }++ let service = DependencyContainer.shared.makeLLMService(+ provider: providerType,+ apiKey: apiKey,+ baseURL: baseURL+ )++ // Build system prompt — general rules only+ var systemPrompt = "You are a helpful database assistant. Answer concisely."+ if let connectionId = appState.activeConnectionId,+ let config = appState.activeConfig {+ let contextEngine = DependencyContainer.shared.aiContextEngine+ if let schema = await DependencyContainer.shared.schemaCache.get(connectionId: connectionId) {+ let context = try? await contextEngine.buildContext(for: text, schema: schema, tokenBudget: 8000)+ if let context {+ systemPrompt = contextEngine.buildSystemPrompt(+ databaseType: config.databaseType,+ connectionInfo: "\(config.host ?? "localhost"):\(config.port)",+ context: context+ )+ }+ }+ }++ // Build user message content — attach table schemas inline+ var userContent = ""+ if !currentAttached.isEmpty, let adapter = appState.activeAdapter {+ var schemaLines: [String] = []+ for tableName in currentAttached.sorted() {+ if let desc = try? await adapter.describeTable(name: tableName, schema: nil) {+ let cols = desc.columns.map {+ "\($0.name) \($0.dataType)\($0.isPrimaryKey ? " PK" : "")\($0.isNullable ? "" : " NOT NULL")"+ }.joined(separator: ", ")+ schemaLines.append(" \(tableName) (\(cols))")+ }+ }+ if !schemaLines.isEmpty {+ userContent += "--- Schema Context ---\n" + schemaLines.joined(separator: "\n") + "\n\n"+ }+ }+ userContent += "--- Question ---\n" + text++ // Build conversation history for API+ // Previous messages go as-is, last user message replaced with enriched content+ var llmMessages: [LLMMessage] = []+ let allMessages = messages+ for (i, msg) in allMessages.enumerated() {+ if i == allMessages.count - 1 && msg.role == .user {+ // Last user message — use enriched content with schema+ llmMessages.append(LLMMessage(role: .user, content: userContent))+ } else {+ llmMessages.append(LLMMessage(+ role: msg.role == .user ? .user : .assistant,+ content: msg.content+ ))+ }+ }++ // Stream response+ let assistantMsg = ChatDisplayMessage(role: .assistant, content: "")+ appendMessage(assistantMsg)++ do {+ let stream = service.stream(+ messages: llmMessages,+ systemPrompt: systemPrompt,+ model: selectedModel,+ maxTokens: AppConstants.AI.defaultMaxTokens,+ temperature: AppConstants.AI.defaultTemperature+ )+ for try await token in stream {+ assistantMsg.content += token+ }+ } catch {+ if assistantMsg.content.isEmpty {+ assistantMsg.content = "Error: \(error.localizedDescription)"+ }+ }+ isStreaming = false+ }+ }+}++// MARK: - Message Bubble++struct MessageBubble: View {+ @ObservedObject var message: ChatDisplayMessage++ var body: some View {+ HStack(alignment: .top, spacing: 10) {+ if message.role == .assistant {+ avatar+ } else {+ Spacer(minLength: 40)+ }++ VStack(alignment: message.role == .user ? .trailing : .leading, spacing: 3) {+ // Sender label+ Text(message.role == .user ? "You" : "Assistant")+ .font(.system(size: 10, weight: .semibold))+ .foregroundStyle(.tertiary)+ .padding(.horizontal, 2)++ // Bubble content — either plain text or parsed markdown (with code blocks)+ MessageContent(text: message.content.isEmpty ? " " : message.content, role: message.role)+ }++ if message.role == .user {+ avatar+ } else {+ Spacer(minLength: 40)+ }+ }+ }++ @ViewBuilder+ private var avatar: some View {+ if message.role == .assistant {+ ZStack {+ LinearGradient(+ colors: [.purple, .blue],+ startPoint: .topLeading,+ endPoint: .bottomTrailing+ )+ .frame(width: 28, height: 28)+ .clipShape(Circle())+ Image(systemName: "sparkles")+ .font(.system(size: 12, weight: .semibold))+ .foregroundStyle(.white)+ }+ } else {+ ZStack {+ Color.primary.opacity(0.1)+ .frame(width: 28, height: 28)+ .clipShape(Circle())+ Image(systemName: "person.fill")+ .font(.system(size: 12, weight: .semibold))+ .foregroundStyle(.secondary)+ }+ }+ }+}++// MARK: - Message Content (parses markdown code fences)++/// A message content view that parses markdown fenced code blocks (```lang ... ```)+/// and renders them as styled code blocks with language label and copy button.+/// Regular text is rendered as a normal bubble.+struct MessageContent: View {+ let text: String+ let role: ChatDisplayMessage.ChatRole++ var body: some View {+ let segments = parseSegments(text)+ VStack(alignment: role == .user ? .trailing : .leading, spacing: 6) {+ ForEach(Array(segments.enumerated()), id: \.offset) { _, segment in+ switch segment {+ case .text(let content):+ textBubble(content)+ case .code(let language, let code):+ CodeBlockView(language: language, code: code)+ }+ }+ }+ }++ @ViewBuilder+ private func textBubble(_ content: String) -> some View {+ Text(content)+ .font(.system(size: 13))+ .lineSpacing(2)+ .textSelection(.enabled)+ .multilineTextAlignment(.leading)+ .padding(.horizontal, 12)+ .padding(.vertical, 9)+ .background(textBubbleBackground)+ .clipShape(textBubbleShape)+ .overlay {+ textBubbleShape+ .stroke(role == .user ? Color.clear : Color.primary.opacity(0.06), lineWidth: 1)+ }+ .foregroundStyle(role == .user ? Color.white : Color.primary)+ }++ private var textBubbleShape: some Shape {+ UnevenRoundedRectangle(+ cornerRadii: .init(+ topLeading: 14,+ bottomLeading: role == .user ? 14 : 4,+ bottomTrailing: role == .user ? 4 : 14,+ topTrailing: 14+ ),+ style: .continuous+ )+ }++ @ViewBuilder+ private var textBubbleBackground: some View {+ if role == .user {+ LinearGradient(+ colors: [.purple, .blue],+ startPoint: .topLeading,+ endPoint: .bottomTrailing+ )+ } else {+ Color.primary.opacity(0.05)+ }+ }++ // MARK: - Parser++ enum Segment {+ case text(String)+ case code(language: String, code: String)+ }++ /// Parse the input for markdown fenced code blocks (```lang\ncode\n```).+ /// Returns alternating text/code segments, skipping empty text segments.+ private func parseSegments(_ input: String) -> [Segment] {+ var segments: [Segment] = []+ let lines = input.components(separatedBy: "\n")+ var i = 0+ var currentText: [String] = []++ func flushText() {+ let joined = currentText.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines)+ if !joined.isEmpty {+ segments.append(.text(joined))+ }+ currentText = []+ }++ while i < lines.count {+ let line = lines[i]+ let trimmed = line.trimmingCharacters(in: .whitespaces)+ // Detect opening fence: ``` or ```lang+ if trimmed.hasPrefix("```") {+ let lang = String(trimmed.dropFirst(3)).trimmingCharacters(in: .whitespaces)+ flushText()+ // Scan until closing fence+ var codeLines: [String] = []+ i += 1+ while i < lines.count {+ let codeLine = lines[i]+ if codeLine.trimmingCharacters(in: .whitespaces) == "```" {+ break+ }+ codeLines.append(codeLine)+ i += 1+ }+ segments.append(.code(language: lang.isEmpty ? "plain" : lang, code: codeLines.joined(separator: "\n")))+ i += 1+ continue+ }+ currentText.append(line)+ i += 1+ }+ flushText()+ return segments+ }+}++// MARK: - Code Block View++struct CodeBlockView: View {+ let language: String+ let code: String+ @State private var copied = false++ var body: some View {+ VStack(alignment: .leading, spacing: 0) {+ // Header: language label + copy button+ HStack(spacing: 6) {+ Image(systemName: languageIcon)+ .font(.system(size: 10))+ .foregroundStyle(.secondary)+ Text(language.uppercased())+ .font(.system(size: 10, weight: .semibold, design: .monospaced))+ .foregroundStyle(.secondary)+ Spacer()+ Button(action: copyCode) {+ HStack(spacing: 4) {+ Image(systemName: copied ? "checkmark" : "doc.on.doc")+ .font(.system(size: 10))+ Text(copied ? "Copied" : "Copy")+ .font(.system(size: 10, weight: .medium))+ }+ .foregroundStyle(copied ? .green : .secondary)+ }+ .buttonStyle(.plain)+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 6)+ .background(Color.primary.opacity(0.06))++ Divider().opacity(0.3)++ // Code content+ ScrollView(.horizontal, showsIndicators: false) {+ Text(code)+ .font(.system(size: 12, design: .monospaced))+ .textSelection(.enabled)+ .lineSpacing(2)+ .padding(.horizontal, 12)+ .padding(.vertical, 10)+ .frame(maxWidth: .infinity, alignment: .leading)+ }+ .background(Color(nsColor: .textBackgroundColor).opacity(0.5))+ }+ .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))+ .overlay {+ RoundedRectangle(cornerRadius: 10, style: .continuous)+ .stroke(Color.primary.opacity(0.1), lineWidth: 1)+ }+ }++ private var languageIcon: String {+ let lang = language.lowercased()+ if lang == "sql" || lang == "mysql" || lang == "postgresql" || lang == "mssql" {+ return "cylinder.split.1x2"+ }+ if lang == "json" || lang == "javascript" || lang == "js" || lang == "typescript" || lang == "ts" {+ return "curlybraces"+ }+ if lang == "python" || lang == "py" || lang == "swift" || lang == "rust" || lang == "go" {+ return "chevron.left.forwardslash.chevron.right"+ }+ return "text.alignleft"+ }++ private func copyCode() {+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(code, forType: .string)+ copied = true+ Task {+ try? await Task.sleep(nanoseconds: 2_000_000_000)+ copied = false+ }+ }+}++// MARK: - Typing Indicator (animated dots)++struct TypingIndicator: View {+ @State private var phase: CGFloat = 0++ var body: some View {+ HStack(spacing: 4) {+ ForEach(0..<3) { i in+ Circle()+ .fill(Color.secondary)+ .frame(width: 6, height: 6)+ .scaleEffect(scaleForDot(at: i))+ .opacity(opacityForDot(at: i))+ }+ }+ .padding(.horizontal, 12)+ .padding(.vertical, 10)+ .background(Color.primary.opacity(0.05))+ .clipShape(+ UnevenRoundedRectangle(+ cornerRadii: .init(+ topLeading: 14,+ bottomLeading: 4,+ bottomTrailing: 14,+ topTrailing: 14+ ),+ style: .continuous+ )+ )+ .onAppear {+ withAnimation(.easeInOut(duration: 0.9).repeatForever(autoreverses: false)) {+ phase = 1+ }+ }+ }++ private func scaleForDot(at index: Int) -> CGFloat {+ let offset = CGFloat(index) * 0.2+ let progress = (phase + offset).truncatingRemainder(dividingBy: 1)+ return 0.7 + 0.5 * sin(progress * .pi)+ }++ private func opacityForDot(at index: Int) -> CGFloat {+ let offset = CGFloat(index) * 0.2+ let progress = (phase + offset).truncatingRemainder(dividingBy: 1)+ return 0.4 + 0.6 * sin(progress * .pi)+ }+}diff --git a/macos/Presentation/Views/ConnectionForm/ConnectionFormPanel.swift b/macos/Presentation/Views/ConnectionForm/ConnectionFormPanel.swiftnew file mode 100644index 0000000..0d0baab--- /dev/null+++ b/macos/Presentation/Views/ConnectionForm/ConnectionFormPanel.swift@@ -0,0 +1,212 @@+// ConnectionFormPanel.swift+// Gridex+//+// Opens ConnectionFormView as a native NSPanel with traffic-light buttons.++import SwiftUI+import AppKit++@MainActor+final class ConnectionFormPanel {++ private static var current: NSPanel?++ // MARK: - Open++ static func open(+ databaseType: DatabaseType,+ existingConfig: ConnectionConfig? = nil,+ existingPassword: String = "",+ existingSSHPassword: String = "",+ appState: AppState+ ) {+ current?.close()+ current = nil++ let isEditing = existingConfig != nil++ let formView = ConnectionFormView(+ databaseType: databaseType,+ existingConfig: existingConfig,+ existingPassword: existingPassword,+ existingSSHPassword: existingSSHPassword,+ onConnect: { config, pw, sshPw in+ Task { @MainActor in+ do {+ if isEditing {+ try await appState.container.connectionRepository.update(config)+ } else {+ try await appState.container.connectionRepository.save(config)+ }+ } catch { appState.connectionError = "Save failed: \(error.localizedDescription)" }+ persistCredentials(config: config, dbPassword: pw, sshPassword: sshPw, appState: appState)+ ConnectionFormPanel.close()+ await appState.connect(config: config, password: pw, sshPassword: sshPw)+ }+ },+ onTest: { config, pw, sshPw in+ await runTest(config: config, dbPassword: pw, sshPassword: sshPw, appState: appState)+ },+ onSave: { config, pw, sshPw in+ Task { @MainActor in+ do {+ if isEditing {+ try await appState.container.connectionRepository.update(config)+ } else {+ try await appState.container.connectionRepository.save(config)+ }+ } catch { appState.connectionError = "Save failed: \(error.localizedDescription)" }+ persistCredentials(config: config, dbPassword: pw, sshPassword: sshPw, appState: appState)+ ConnectionFormPanel.close()+ await appState.loadSavedConnections()+ }+ },+ onCancel: {+ ConnectionFormPanel.close()+ }+ )+ .environmentObject(appState)++ let controller = NSHostingController(rootView: formView)++ let panel = NSPanel(+ contentRect: NSRect(x: 0, y: 0, width: 580, height: 520),+ styleMask: [.titled, .closable, .miniaturizable, .resizable],+ backing: .buffered,+ defer: false+ )+ panel.title = "\(databaseType.displayName) Connection"+ panel.contentViewController = controller+ panel.layoutIfNeeded()++ // Center the panel over the main app window (not the screen).+ // Done after layout so panel.frame.size reflects the actual size.+ let parentWindow = NSApp.mainWindow+ ?? NSApp.windows.first(where: { $0.canBecomeMain && !($0 is NSPanel) && $0.isVisible })+ if let parent = parentWindow {+ let parentFrame = parent.frame+ let panelSize = panel.frame.size+ let origin = NSPoint(+ x: parentFrame.midX - panelSize.width / 2,+ y: parentFrame.midY - panelSize.height / 2+ )+ panel.setFrameOrigin(origin)+ } else {+ panel.center()+ }++ panel.makeKeyAndOrderFront(nil)++ current = panel+ }++ // MARK: - Close++ static func close() {+ current?.close()+ current = nil+ }++ // MARK: - Helpers++ @MainActor+ private static func persistCredentials(+ config: ConnectionConfig,+ dbPassword: String,+ sshPassword: String,+ appState: AppState+ ) {+ let keychain = appState.container.keychainService+ let dbKey = "db.password.\(config.id.uuidString)"+ let sshKey = "ssh.password.\(config.id.uuidString)"++ do {+ if dbPassword.isEmpty {+ try? keychain.delete(key: dbKey)+ } else {+ try keychain.save(key: dbKey, value: dbPassword)+ }+ if config.sshConfig != nil, !sshPassword.isEmpty {+ try keychain.save(key: sshKey, value: sshPassword)+ } else {+ try? keychain.delete(key: sshKey)+ }+ } catch {+ appState.connectionError = "Keychain error: \(error.localizedDescription)"+ }+ }++ private static func runTest(+ config: ConnectionConfig,+ dbPassword: String,+ sshPassword: String,+ appState: AppState+ ) async -> ConnectionTestResult {+ let adapter: any DatabaseAdapter = switch config.databaseType {+ case .sqlite: SQLiteAdapter()+ case .postgresql: PostgreSQLAdapter()+ case .mysql: MySQLAdapter()+ case .redis: RedisAdapter()+ case .mongodb: MongoDBAdapter()+ case .mssql: MSSQLAdapter()+ }++ let sshService = appState.container.sshTunnelService+ let testConnectionId = UUID()++ let start = CFAbsoluteTimeGetCurrent()+ var effectiveConfig = config++ // Establish SSH tunnel for the duration of the test so the adapter connects+ // to 127.0.0.1:<localPort> instead of the remote host.+ if let ssh = config.sshConfig {+ do {+ let remoteHost = config.host ?? "127.0.0.1"+ let remotePort = config.port ?? config.databaseType.defaultPort+ let localPort = try await sshService.establish(+ connectionId: testConnectionId,+ config: ssh,+ remoteHost: remoteHost,+ remotePort: remotePort,+ password: sshPassword+ )+ effectiveConfig.host = "127.0.0.1"+ effectiveConfig.port = Int(localPort)+ } catch {+ return ConnectionTestResult(+ success: false, serverVersion: nil,+ latency: CFAbsoluteTimeGetCurrent() - start,+ errorMessage: "SSH tunnel failed: \(friendlyError(error))"+ )+ }+ }++ do {+ try await adapter.connect(config: effectiveConfig, password: dbPassword)+ let ver = try? await adapter.serverVersion()+ let latency = CFAbsoluteTimeGetCurrent() - start+ try? await adapter.disconnect()+ await sshService.disconnect(connectionId: testConnectionId)+ return ConnectionTestResult(success: true, serverVersion: ver,+ latency: latency, errorMessage: nil)+ } catch {+ try? await adapter.disconnect()+ await sshService.disconnect(connectionId: testConnectionId)+ return ConnectionTestResult(+ success: false, serverVersion: nil,+ latency: CFAbsoluteTimeGetCurrent() - start,+ errorMessage: friendlyError(error)+ )+ }+ }++ /// Maps low-level NIO/network errors to readable messages.+ private static func friendlyError(_ error: Error) -> String {+ let ns = error as NSError+ let desc = error.localizedDescription+ if desc.contains("NIOCore.IOError") || ns.domain.contains("NIO") {+ return "Cannot reach host — check hostname, port, and firewall."+ }+ return desc+ }+}diff --git a/macos/Presentation/Views/ConnectionForm/ConnectionFormView.swift b/macos/Presentation/Views/ConnectionForm/ConnectionFormView.swiftnew file mode 100644index 0000000..ee4a09a--- /dev/null+++ b/macos/Presentation/Views/ConnectionForm/ConnectionFormView.swift@@ -0,0 +1,665 @@+// ConnectionFormView.swift+// Gridex+//+// SwiftUI form for creating/editing database connections (Gridex-style layout).++import SwiftUI+import AppKit++struct ConnectionFormView: View {+ let databaseType: DatabaseType+ var existingConfig: ConnectionConfig?+ var existingPassword: String = ""+ var existingSSHPassword: String = ""++ @State private var name: String = ""+ @State private var host: String = "localhost"+ @State private var port: String = ""+ @State private var database: String = ""+ @State private var username: String = ""+ @State private var password: String = ""+ @State private var sqliteFilePath: String = ""+ @State private var connectionString: String = ""+ @State private var connStringError: String?++ // Tag+ @State private var colorTag: ColorTag = .blue++ // SSL+ @State private var sslMode: SSLMode = .preferred+ @State private var sslKeyPath: String = ""+ @State private var sslCertPath: String = ""+ @State private var sslCACertPath: String = ""++ // SSH+ @State private var sshEnabled: Bool = false+ @State private var sshHost: String = ""+ @State private var sshPort: String = "22"+ @State private var sshUsername: String = ""+ @State private var sshPassword: String = ""+ @State private var sshAuthMethod: SSHAuthMethod = .password+ @State private var sshKeyPath: String = ""++ // Password storage+ @State private var storeInKeychain: Bool = true++ // Test+ @State private var isTesting: Bool = false+ @State private var testResult: ConnectionTestResult?++ var onConnect: ((ConnectionConfig, String, String) -> Void)?+ var onTest: ((ConnectionConfig, String, String) async -> ConnectionTestResult)?+ var onSave: ((ConnectionConfig, String, String) -> Void)?+ var onCancel: (() -> Void)?++ private var isEditing: Bool { existingConfig != nil }+ private let labelWidth: CGFloat = 110++ var body: some View {+ VStack(spacing: 0) {+ // Form fields+ VStack(spacing: 16) {+ // Name+ TPRow(label: "Name", labelWidth: labelWidth) {+ TPTextField(placeholder: "Connection name", text: $name)+ }++ // Status color + Tag+ TPRow(label: "Status color", labelWidth: labelWidth) {+ HStack(spacing: 0) {+ HStack(spacing: 6) {+ ForEach(ColorTag.allCases, id: \.self) { tag in+ RoundedRectangle(cornerRadius: 3)+ .fill(tag.swiftUIColor)+ .frame(width: 28, height: 20)+ .overlay(+ RoundedRectangle(cornerRadius: 3)+ .stroke(Color.white, lineWidth: colorTag == tag ? 2 : 0)+ )+ .onTapGesture { colorTag = tag }+ }+ }++ Spacer()++ // Tag dropdown+ HStack(spacing: 4) {+ Text("Tag")+ .font(.system(size: 13))+ .foregroundStyle(.secondary)+ .frame(width: 30, alignment: .trailing)++ Picker("", selection: $colorTag) {+ ForEach(ColorTag.allCases, id: \.self) { tag in+ Text(tag.environmentHint).tag(tag)+ }+ }+ .labelsHidden()+ .pickerStyle(.menu)+ .frame(width: 120)+ }+ }+ }++ // MongoDB: connection string field (paste full URI to auto-fill)+ if databaseType == .mongodb {+ TPRow(label: "URI", labelWidth: labelWidth) {+ HStack(spacing: 8) {+ TPTextField(placeholder: "mongodb://user:pass@host:27017/db or mongodb+srv://...", text: $connectionString)+ Button("Parse") { parseMongoConnectionString() }+ .disabled(connectionString.isEmpty)+ }+ }+ if let err = connStringError {+ TPRow(label: "", labelWidth: labelWidth) {+ Text(err)+ .font(.system(size: 11))+ .foregroundStyle(.red)+ }+ }+ }++ if databaseType == .sqlite {+ // SQLite file+ TPRow(label: "File", labelWidth: labelWidth) {+ HStack(spacing: 8) {+ TPTextField(placeholder: "path/to/database.db", text: $sqliteFilePath)+ Button("Browse...") { pickSQLiteFile() }+ }+ }+ } else {+ // Host/Socket + Port+ HStack(spacing: 0) {+ TPRow(label: "Host/Socket", labelWidth: labelWidth) {+ TPTextField(placeholder: "127.0.0.1", text: $host)+ }++ HStack(spacing: 8) {+ Text("Port")+ .font(.system(size: 13))+ .foregroundStyle(.secondary)+ TPTextField(placeholder: String(databaseType.defaultPort), text: $port)+ .frame(width: 72)+ }+ }++ if databaseType != .redis {+ // User + Other options (not needed for Redis)+ TPRow(label: "User", labelWidth: labelWidth) {+ HStack(spacing: 0) {+ TPTextField(placeholder: "user name", text: $username)+ Spacer().frame(width: 12)+ TPButton(title: "Other options") {}+ .frame(width: 130)+ }+ }+ }++ // Password + Store in keychain+ TPRow(label: "Password", labelWidth: labelWidth) {+ HStack(spacing: 0) {+ ZStack(alignment: .trailing) {+ TPTextField(placeholder: databaseType == .redis ? "optional" : "password", text: $password, isSecure: true)+ if !password.isEmpty {+ Text("\(password.count)")+ .font(.system(size: 10, weight: .medium, design: .monospaced))+ .foregroundStyle(.tertiary)+ .padding(.trailing, 6)+ .allowsHitTesting(false)+ }+ }+ Spacer().frame(width: 12)+ Picker("", selection: $storeInKeychain) {+ Text("Store in keychain").tag(true)+ Text("Don't store").tag(false)+ }+ .labelsHidden()+ .pickerStyle(.menu)+ .frame(width: 170)+ }+ }++ if databaseType == .redis {+ // Redis: database number + TLS toggle+ TPRow(label: "Database", labelWidth: labelWidth) {+ HStack(spacing: 0) {+ TPTextField(placeholder: "0 (default)", text: $database)+ Spacer().frame(width: 12)+ Toggle("TLS (rediss://)", isOn: Binding(+ get: { sslMode != .disabled },+ set: { sslMode = $0 ? .required : .disabled }+ ))+ .toggleStyle(.checkbox)+ .font(.system(size: 12))+ }+ }+ } else {+ // Database + SSL mode+ TPRow(label: "Database", labelWidth: labelWidth) {+ HStack(spacing: 0) {+ TPTextField(placeholder: "database name", text: $database)+ Spacer().frame(width: 12)+ HStack(spacing: 4) {+ Text("SSL mode")+ .font(.system(size: 13))+ .foregroundStyle(.secondary)+ Picker("", selection: $sslMode) {+ ForEach(SSLMode.allCases, id: \.self) { mode in+ Text(mode.displayName).tag(mode)+ }+ }+ .labelsHidden()+ .pickerStyle(.menu)+ .frame(width: 120)+ }+ }+ }+ }++ // SSL keys (not applicable to non-SQL databases)+ if databaseType != .redis && databaseType != .mongodb {+ TPRow(label: "SSL keys", labelWidth: labelWidth) {+ HStack(spacing: 6) {+ TPFileButton(title: "Key...", path: $sslKeyPath)+ TPFileButton(title: "Cert...", path: $sslCertPath)+ TPFileButton(title: "CA Cert...", path: $sslCACertPath)++ Button {+ sslKeyPath = ""+ sslCertPath = ""+ sslCACertPath = ""+ } label: {+ Image(systemName: "minus")+ .font(.system(size: 11, weight: .medium))+ .frame(width: 24, height: 24)+ }+ }+ }+ } // end if !redis++ // SSH section (expanded)+ if sshEnabled {+ Divider()+ .padding(.vertical, 2)++ // SSH Host + Port+ HStack(spacing: 0) {+ TPRow(label: "SSH Host", labelWidth: labelWidth) {+ TPTextField(placeholder: "ssh.example.com", text: $sshHost)+ }++ HStack(spacing: 8) {+ Text("Port")+ .font(.system(size: 13))+ .foregroundStyle(.secondary)+ TPTextField(placeholder: "22", text: $sshPort)+ .frame(width: 72)+ }+ }++ // SSH User+ TPRow(label: "SSH User", labelWidth: labelWidth) {+ HStack(spacing: 0) {+ TPTextField(placeholder: "username", text: $sshUsername)+ Spacer().frame(width: 12)+ Picker("", selection: $sshAuthMethod) {+ Text("Password").tag(SSHAuthMethod.password)+ Text("Private Key").tag(SSHAuthMethod.privateKey)+ Text("Key + Passphrase").tag(SSHAuthMethod.keyWithPassphrase)+ }+ .labelsHidden()+ .pickerStyle(.menu)+ .frame(width: 150)+ }+ }++ // SSH Password+ if sshAuthMethod == .password || sshAuthMethod == .keyWithPassphrase {+ TPRow(label: "SSH Password", labelWidth: labelWidth) {+ TPTextField(placeholder: "password", text: $sshPassword, isSecure: true)+ }+ }++ // SSH Key+ if sshAuthMethod == .privateKey || sshAuthMethod == .keyWithPassphrase {+ TPRow(label: "SSH Key", labelWidth: labelWidth) {+ HStack(spacing: 8) {+ TPTextField(placeholder: "~/.ssh/id_rsa", text: $sshKeyPath)+ Button("Browse...") { pickSSHKey() }+ }+ }+ }+ }+ }+ }+ .padding(.horizontal, 24)+ .padding(.vertical, 20)++ // Test result+ if let result = testResult {+ HStack(spacing: 6) {+ Image(systemName: result.success ? "checkmark.circle.fill" : "xmark.circle.fill")+ Text(result.success+ ? "Connected! \(result.serverVersion ?? "") (\(Int(result.latency * 1000))ms)"+ : result.errorMessage ?? "Connection failed")+ .font(.system(size: 12))+ Spacer()+ }+ .foregroundColor(result.success ? .green : .red)+ .padding(.horizontal, 24)+ .padding(.bottom, 10)+ }++ Divider()++ // Bottom bar — Gridex style+ HStack(spacing: 8) {+ if databaseType != .sqlite {+ Button {+ withAnimation(.spring(response: 0.25, dampingFraction: 0.9)) {+ sshEnabled.toggle()+ }+ } label: {+ Text(sshEnabled ? "Close SSH" : "Over SSH")+ .font(.system(size: 13))+ }+ }++ Spacer()++ Button("Save") { save() }+ .disabled(name.isEmpty)++ Button {+ Task { await testConnection() }+ } label: {+ if isTesting {+ ProgressView()+ .controlSize(.small)+ .scaleEffect(0.7)+ .frame(width: 40)+ } else {+ Text("Test")+ }+ }+ .disabled(isTesting || !isFormValid)++ Button("Connect") { connectAction() }+ .buttonStyle(.borderedProminent)+ .disabled(!isFormValid)+ .keyboardShortcut(.defaultAction)+ }+ .padding(.horizontal, 24)+ .padding(.vertical, 12)+ }+ .frame(width: 580)+ .onAppear {+ if let config = existingConfig {+ populateFromConfig(config)+ password = existingPassword+ sshPassword = existingSSHPassword+ } else {+ port = String(databaseType.defaultPort)+ }+ }+ }++ // MARK: - Populate from existing config (edit mode)++ private func populateFromConfig(_ config: ConnectionConfig) {+ name = config.name+ host = config.host ?? "localhost"+ port = String(config.port ?? databaseType.defaultPort)+ database = config.database ?? ""+ username = config.username ?? ""+ sslMode = config.sslEnabled ? .required : .preferred+ colorTag = config.colorTag ?? .blue+ sqliteFilePath = config.filePath ?? ""++ if let ssh = config.sshConfig {+ sshEnabled = true+ sshHost = ssh.host+ sshPort = String(ssh.port)+ sshUsername = ssh.username+ sshAuthMethod = ssh.authMethod+ sshKeyPath = ssh.keyPath ?? ""+ }+ }++ // MARK: - Validation++ private var isFormValid: Bool {+ if databaseType == .sqlite {+ return !sqliteFilePath.isEmpty+ }+ return !host.isEmpty+ }++ // MARK: - Actions++ private func buildConfig() -> ConnectionConfig {+ var sshConfig: SSHTunnelConfig?+ if sshEnabled && databaseType != .sqlite {+ sshConfig = SSHTunnelConfig(+ host: sshHost,+ port: Int(sshPort) ?? 22,+ username: sshUsername,+ authMethod: sshAuthMethod,+ keyPath: sshAuthMethod != .password ? sshKeyPath : nil+ )+ }++ let sslEnabled = sslMode != .disabled++ let isFileDB = databaseType == .sqlite++ // For MongoDB: if a connection string was provided, store it in host so the+ // adapter can pass it through to MongoKitten unchanged (preserves SRV lookup,+ // replica set hosts, query options, etc.)+ let isMongoURI = databaseType == .mongodb+ && (connectionString.hasPrefix("mongodb://") || connectionString.hasPrefix("mongodb+srv://"))+ let effectiveHost: String? = {+ if isFileDB { return nil }+ if isMongoURI { return connectionString.trimmingCharacters(in: .whitespacesAndNewlines) }+ return host+ }()++ return ConnectionConfig(+ id: existingConfig?.id ?? UUID(),+ name: name.isEmpty ? (isFileDB ? "SQLite" : host) : name,+ databaseType: databaseType,+ host: effectiveHost,+ port: isFileDB ? nil : (Int(port) ?? databaseType.defaultPort),+ database: isFileDB ? nil : (database.isEmpty ? nil : database),+ username: (isFileDB || databaseType == .redis) ? nil : username,+ sslEnabled: isFileDB ? false : sslEnabled,+ colorTag: colorTag,+ group: existingConfig?.group,+ filePath: databaseType == .sqlite ? sqliteFilePath : nil,+ sshConfig: sshConfig+ )+ }++ private func connectAction() {+ onConnect?(buildConfig(), password, sshPassword)+ }++ private func save() {+ onSave?(buildConfig(), password, sshPassword)+ }++ private func testConnection() async {+ isTesting = true+ testResult = nil+ defer { isTesting = false }+ testResult = await onTest?(buildConfig(), password, sshPassword) ?? ConnectionTestResult(+ success: false, serverVersion: nil, latency: 0, errorMessage: "No handler"+ )+ }++ /// Parse a MongoDB connection string and populate the form fields.+ /// Supports both `mongodb://` and `mongodb+srv://` formats.+ private func parseMongoConnectionString() {+ connStringError = nil+ let trimmed = connectionString.trimmingCharacters(in: .whitespacesAndNewlines)++ guard trimmed.hasPrefix("mongodb://") || trimmed.hasPrefix("mongodb+srv://") else {+ connStringError = "URI must start with mongodb:// or mongodb+srv://"+ return+ }++ let isSrv = trimmed.hasPrefix("mongodb+srv://")+ let prefixLength = isSrv ? "mongodb+srv://".count : "mongodb://".count+ var rest = String(trimmed.dropFirst(prefixLength))++ // Strip query string and parse for tls/ssl flag+ var hasTLS = isSrv // SRV implies TLS by default+ if let qIdx = rest.firstIndex(of: "?") {+ let query = String(rest[rest.index(after: qIdx)...])+ rest = String(rest[..<qIdx])+ for param in query.split(separator: "&") {+ let parts = param.split(separator: "=", maxSplits: 1)+ if parts.count == 2 {+ let key = String(parts[0]).lowercased()+ let value = String(parts[1]).lowercased()+ if (key == "tls" || key == "ssl") && (value == "true" || value == "1") {+ hasTLS = true+ }+ }+ }+ }++ // Extract database (path component after host)+ var dbName: String?+ if let slashIdx = rest.firstIndex(of: "/") {+ let dbPart = String(rest[rest.index(after: slashIdx)...])+ if !dbPart.isEmpty { dbName = dbPart }+ rest = String(rest[..<slashIdx])+ }++ // Extract user:password (before @)+ var user: String?+ var pass: String?+ if let atIdx = rest.lastIndex(of: "@") {+ let credPart = String(rest[..<atIdx])+ rest = String(rest[rest.index(after: atIdx)...])+ if let colonIdx = credPart.firstIndex(of: ":") {+ user = String(credPart[..<colonIdx]).removingPercentEncoding ?? String(credPart[..<colonIdx])+ pass = String(credPart[credPart.index(after: colonIdx)...]).removingPercentEncoding ?? String(credPart[credPart.index(after: colonIdx)...])+ } else {+ user = credPart.removingPercentEncoding ?? credPart+ }+ }++ // Extract host:port (rest may contain comma-separated hosts for replica sets — take first)+ let firstHost = rest.split(separator: ",").first.map(String.init) ?? rest+ var hostName = firstHost+ var portNum: String?+ if let colonIdx = firstHost.firstIndex(of: ":") {+ hostName = String(firstHost[..<colonIdx])+ portNum = String(firstHost[firstHost.index(after: colonIdx)...])+ }++ guard !hostName.isEmpty else {+ connStringError = "Could not parse host from URI"+ return+ }++ // Apply parsed values to form+ host = hostName+ port = portNum ?? (isSrv ? "" : "27017")+ if let dbName = dbName { database = dbName }+ if let user = user { username = user }+ if let pass = pass { password = pass }+ if hasTLS {+ sslMode = .required+ }+ if name.isEmpty {+ name = hostName+ }+ }++ private func pickSQLiteFile() {+ let panel = NSOpenPanel()+ panel.allowedContentTypes = [.database, .data]+ panel.allowsOtherFileTypes = true+ panel.canChooseFiles = true+ panel.canChooseDirectories = false+ panel.message = "Select a SQLite database file"+ panel.prompt = "Open"+ if panel.runModal() == .OK, let url = panel.url {+ sqliteFilePath = url.path+ if name.isEmpty {+ name = url.deletingPathExtension().lastPathComponent+ }+ }+ }++ private func pickSSHKey() {+ let panel = NSOpenPanel()+ panel.canChooseFiles = true+ panel.canChooseDirectories = false+ panel.allowsMultipleSelection = false+ panel.directoryURL = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".ssh")+ panel.message = "Select SSH private key"+ panel.prompt = "Select"+ if panel.runModal() == .OK, let url = panel.url {+ sshKeyPath = url.path+ }+ }+}++// MARK: - Gridex-style Row (label left, content right)++struct TPRow<Content: View>: View {+ let label: String+ var labelWidth: CGFloat = 110+ @ViewBuilder let content: Content++ var body: some View {+ HStack(spacing: 12) {+ Text(label)+ .font(.system(size: 13))+ .foregroundStyle(.secondary)+ .frame(width: labelWidth, alignment: .trailing)+ content+ }+ }+}++// MARK: - Gridex-style flat button++struct TPButton: View {+ let title: String+ let action: () -> Void++ var body: some View {+ Button(action: action) {+ Text(title)+ .font(.system(size: 12))+ .frame(maxWidth: .infinity)+ }+ }+}++// MARK: - No-flicker TextField (no focus ring animation)++struct TPTextField: NSViewRepresentable {+ var placeholder: String+ @Binding var text: String+ var isSecure: Bool = false++ func makeNSView(context: Context) -> NSTextField {+ let field = isSecure ? NSSecureTextField() : NSTextField()+ field.placeholderString = placeholder+ field.focusRingType = .none+ field.bezelStyle = .roundedBezel+ field.font = .systemFont(ofSize: 13)+ field.delegate = context.coordinator+ return field+ }++ func updateNSView(_ nsView: NSTextField, context: Context) {+ if nsView.stringValue != text {+ nsView.stringValue = text+ }+ }++ func makeCoordinator() -> Coordinator { Coordinator(text: $text) }++ class Coordinator: NSObject, NSTextFieldDelegate {+ @Binding var text: String+ init(text: Binding<String>) { _text = text }+ func controlTextDidChange(_ obj: Notification) {+ if let field = obj.object as? NSTextField {+ text = field.stringValue+ }+ }+ }+}++// MARK: - Gridex-style file picker button++struct TPFileButton: View {+ let title: String+ @Binding var path: String++ var body: some View {+ Button {+ let panel = NSOpenPanel()+ panel.canChooseFiles = true+ panel.canChooseDirectories = false+ panel.allowsMultipleSelection = false+ panel.message = "Select \(title.replacingOccurrences(of: "...", with: "")) file"+ panel.prompt = "Select"+ if panel.runModal() == .OK, let url = panel.url {+ path = url.path+ }+ } label: {+ Text(path.isEmpty ? title : URL(fileURLWithPath: path).lastPathComponent)+ .font(.system(size: 12))+ .lineLimit(1)+ .frame(maxWidth: .infinity)+ }+ }+}diff --git a/macos/Presentation/Views/DataGrid/AppKitDataGrid.swift b/macos/Presentation/Views/DataGrid/AppKitDataGrid.swiftnew file mode 100644index 0000000..4b46376--- /dev/null+++ b/macos/Presentation/Views/DataGrid/AppKitDataGrid.swift@@ -0,0 +1,1386 @@+// AppKitDataGrid.swift+// Gridex+//+// High-performance NSTableView wrapper for the data grid.+// The Coordinator observes the viewModel directly via Combine,+// bypassing SwiftUI's update cycle to avoid unnecessary reloadData() calls.++import SwiftUI+import AppKit+import Combine+import ObjectiveC++struct AppKitDataGrid: NSViewRepresentable {+ let viewModel: DataGridViewState+ let onSelectRows: (Set<Int>) -> Void+ var onFKClick: ((_ refTable: String, _ refColumn: String, _ value: String) -> Void)?++ func makeNSView(context: Context) -> NSScrollView {+ let scrollView = NSScrollView()+ scrollView.hasVerticalScroller = true+ scrollView.hasHorizontalScroller = true+ scrollView.autohidesScrollers = false+ scrollView.borderType = .noBorder++ let tableView = DataGridTableView()+ tableView.style = .plain+ tableView.usesAlternatingRowBackgroundColors = true+ tableView.allowsMultipleSelection = true+ tableView.allowsColumnReordering = false+ tableView.allowsColumnResizing = true+ tableView.columnAutoresizingStyle = .noColumnAutoresizing+ tableView.intercellSpacing = NSSize(width: 0, height: 0)+ tableView.rowHeight = 28+ tableView.headerView = NSTableHeaderView()+ tableView.gridStyleMask = [.solidVerticalGridLineMask, .solidHorizontalGridLineMask]+ tableView.gridColor = NSColor.separatorColor.withAlphaComponent(0.3)+ tableView.selectionHighlightStyle = .regular+ tableView.doubleAction = #selector(context.coordinator.tableViewDoubleClick(_:))+ tableView.target = context.coordinator++ let menu = NSMenu()+ let copyRowItem = NSMenuItem(title: "Copy Row", action: #selector(context.coordinator.copyRow(_:)), keyEquivalent: "")+ copyRowItem.target = context.coordinator+ let copyCellItem = NSMenuItem(title: "Copy Cell", action: #selector(context.coordinator.copyCell(_:)), keyEquivalent: "")+ copyCellItem.target = context.coordinator+ let deleteItem = NSMenuItem(title: "Delete Row(s)", action: #selector(context.coordinator.deleteRows(_:)), keyEquivalent: "")+ deleteItem.target = context.coordinator+ menu.addItem(copyRowItem)+ menu.addItem(copyCellItem)+ menu.addItem(NSMenuItem.separator())+ menu.addItem(deleteItem)+ tableView.menu = menu++ scrollView.documentView = tableView+ tableView.dataSource = context.coordinator+ tableView.delegate = context.coordinator++ context.coordinator.tableView = tableView+ context.coordinator.onSelectRows = onSelectRows+ tableView.gridCoordinator = context.coordinator+ context.coordinator.bind(to: viewModel)++ return scrollView+ }++ func updateNSView(_ scrollView: NSScrollView, context: Context) {+ context.coordinator.onSelectRows = onSelectRows+ context.coordinator.onFKClick = onFKClick+ }++ func makeCoordinator() -> Coordinator {+ Coordinator()+ }++ // MARK: - Coordinator++ @MainActor+ class Coordinator: NSObject, NSTableViewDataSource, NSTableViewDelegate, NSTextFieldDelegate {+ weak var tableView: NSTableView?+ var onSelectRows: ((Set<Int>) -> Void)?+ var onFKClick: ((_ refTable: String, _ refColumn: String, _ value: String) -> Void)?++ private(set) var columns: [ColumnHeader] = []+ private(set) var rows: [[RowValue]] = []+ private(set) var columnWidths: [String: CGFloat] = [:]+ private(set) var pendingChanges: [CellEdit] = []+ private(set) var insertedRowIndices: Set<Int> = []+ private(set) var foreignKeyColumns: [String: String] = [:]+ private(set) var foreignKeyRefColumns: [String: String] = [:]+ private(set) var columnDefaults: [String: String] = [:]+ private(set) var columnEnumValues: [String: [String]] = [:]++ private weak var viewModel: DataGridViewState?+ private var cancellables = Set<AnyCancellable>()+ private var isUpdating = false+ private var isEditing = false+ private var justFinishedEditing = false+ private var previousColumnNames: [String] = []+ private var previousRowCount = 0++ // Cached lookups for O(1) access+ private var deletedRows: Set<Int> = []+ private var modifiedCells: Set<String> = [] // "row:colName"+ private var columnNameToIndex: [String: Int] = [:]+ private var dateColumnIndices: Set<Int> = []+ private var boolColumnIndices: Set<Int> = []++ private func rebuildPendingChangeCaches() {+ deletedRows = []+ modifiedCells = []+ for change in pendingChanges {+ if change.editType == .delete {+ deletedRows.insert(change.row)+ } else if change.editType == .update {+ if let col = change.column {+ modifiedCells.insert("\(change.row):\(col)")+ }+ }+ }+ }++ private func rebuildColumnCaches() {+ columnNameToIndex = [:]+ dateColumnIndices = []+ boolColumnIndices = []+ for (idx, col) in columns.enumerated() {+ columnNameToIndex[col.name] = idx+ let dt = col.dataType.lowercased()+ if dt.contains("date") || dt.contains("time") || dt.contains("timestamp") {+ dateColumnIndices.insert(idx)+ }+ if dt == "boolean" || dt == "bool" || dt == "tinyint(1)" {+ boolColumnIndices.insert(idx)+ }+ }+ }++ static let cellFont = NSFont.monospacedSystemFont(ofSize: 12, weight: .regular)+ static let nullFont: NSFont = {+ let descriptor = cellFont.fontDescriptor.withSymbolicTraits(.italic)+ return NSFont(descriptor: descriptor, size: 12) ?? cellFont+ }()++ // MARK: - ViewModel Binding++ nonisolated func bind(to viewModel: DataGridViewState) {+ MainActor.assumeIsolated {+ self.viewModel = viewModel+ self.cancellables.removeAll()+ self.snapshotFromViewModel()+ self.rebuildColumns()++ viewModel.objectWillChange+ .receive(on: RunLoop.main)+ .debounce(for: .milliseconds(100), scheduler: RunLoop.main)+ .sink { [weak self, weak viewModel] _ in+ MainActor.assumeIsolated {+ guard viewModel != nil else { return }+ self?.handleViewModelUpdate()+ }+ }+ .store(in: &self.cancellables)+ }+ }++ func releaseData() {+ cancellables.removeAll()+ rows = []+ columns = []+ viewModel = nil+ }++ private func snapshotFromViewModel() {+ guard let vm = viewModel else { return }+ columns = vm.columns+ rows = vm.rows+ columnWidths = vm.columnWidths+ pendingChanges = vm.changeTracker.pendingChanges+ insertedRowIndices = vm.insertedRowIndices+ foreignKeyColumns = vm.foreignKeyColumns+ foreignKeyRefColumns = vm.foreignKeyRefColumns+ columnDefaults = vm.columnDefaults+ columnEnumValues = vm.columnEnumValues+ rebuildColumnCaches()+ rebuildPendingChangeCaches()+ }++ private func handleViewModelUpdate() {+ guard let tableView, let vm = viewModel else { return }++ let newColumnNames = vm.columns.map(\.name)+ let newRowCount = vm.rows.count+ let columnsChanged = newColumnNames != previousColumnNames+ let rowsChanged = vm.rows.count != rows.count+ || (vm.rows.first != rows.first)+ columns = vm.columns+ rows = vm.rows+ columnWidths = vm.columnWidths+ foreignKeyColumns = vm.foreignKeyColumns+ foreignKeyRefColumns = vm.foreignKeyRefColumns+ columnDefaults = vm.columnDefaults+ columnEnumValues = vm.columnEnumValues++ // Always sync pending changes — edits to the same cell change content but not count+ let newPending = vm.changeTracker.pendingChanges+ let newInserted = vm.insertedRowIndices+ let pendingChanged = newPending.count != pendingChanges.count+ || newInserted != insertedRowIndices+ || newPending.map(\.column) != pendingChanges.map(\.column)+ pendingChanges = newPending+ insertedRowIndices = newInserted+ if pendingChanged {+ rebuildPendingChangeCaches()+ }+ if columnsChanged {+ rebuildColumnCaches()+ }++ guard !isEditing else {+ previousRowCount = newRowCount+ previousColumnNames = newColumnNames+ return+ }++ if justFinishedEditing {+ justFinishedEditing = false+ previousRowCount = newRowCount+ previousColumnNames = newColumnNames+ // Must rebuild caches since pending changes updated during edit+ pendingChanges = vm.changeTracker.pendingChanges+ insertedRowIndices = vm.insertedRowIndices+ rebuildPendingChangeCaches()+ // Force redraw all visible cells — cells may have been blanked+ // while the floating editor was active+ let visibleRange = tableView.rows(in: tableView.visibleRect)+ guard visibleRange.length > 0 else { return }+ for row in visibleRange.location..<(visibleRange.location + visibleRange.length) {+ for colIdx in 0..<tableView.numberOfColumns {+ if let cell = tableView.view(atColumn: colIdx, row: row, makeIfNecessary: false) as? DataGridCellView {+ cell.isEditingActive = false+ configureCell(cell, row: row, col: colIdx)+ cell.needsDisplay = true+ }+ }+ }+ return+ }++ if columnsChanged {+ previousColumnNames = newColumnNames+ previousRowCount = newRowCount+ rebuildColumns()+ isUpdating = true+ tableView.reloadData()+ isUpdating = false+ return+ }++ if newRowCount != previousRowCount {+ let wasInsert = newRowCount == previousRowCount + 1 && vm.insertedRowIndices.contains(newRowCount - 1)+ previousRowCount = newRowCount+ isUpdating = true+ tableView.reloadData()+ isUpdating = false+ if wasInsert, newRowCount > 0 {+ tableView.scrollRowToVisible(newRowCount - 1)+ }+ return+ }++ // Only refresh visible cells if data or pending changes actually changed+ guard rowsChanged || pendingChanged else { return }++ let visibleRange = tableView.rows(in: tableView.visibleRect)+ guard visibleRange.length > 0 else { return }+ for row in visibleRange.location..<(visibleRange.location + visibleRange.length) {+ refreshRow(row, in: tableView)+ }+ }++ private func rebuildColumns() {+ guard let tableView, let vm = viewModel else { return }++ for col in tableView.tableColumns.reversed() {+ tableView.removeTableColumn(col)+ }+ for colHeader in vm.columns {+ let col = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(colHeader.name))+ col.title = colHeader.name+ col.width = vm.columnWidths[colHeader.name] ?? 120+ col.minWidth = 50+ col.maxWidth = 2000+ col.headerCell = SortableHeaderCell(textCell: colHeader.name)+ col.sortDescriptorPrototype = NSSortDescriptor(key: colHeader.name, ascending: true)+ tableView.addTableColumn(col)+ }+ previousColumnNames = vm.columns.map(\.name)+ }++ // MARK: - Cell Configuration++ private func configureCell(_ cell: DataGridCellView, row: Int, col: Int) {+ let value = col < rows[row].count ? rows[row][col] : .null+ let isInserted = insertedRowIndices.contains(row)+ var dirty = false++ let newText: String+ let newFont: NSFont+ let newColor: NSColor+ if value.isNull && isInserted {+ newText = "DEFAULT"+ newFont = Self.cellFont+ newColor = NSColor.secondaryLabelColor+ } else if value.isNull {+ newText = "NULL"+ newFont = Self.nullFont+ newColor = NSColor.Gridex.cellNull+ } else {+ // Use pre-computed display cache when available+ if let vm = viewModel,+ row < vm.displayCache.count,+ col < vm.displayCache[row].count {+ newText = vm.displayCache[row][col]+ } else {+ newText = value.displayString+ }+ newFont = Self.cellFont+ newColor = .labelColor+ }++ if cell.text != newText {+ cell.text = newText+ cell.toolTip = newText.count > 30 ? (newText.count > 200 ? String(newText.prefix(200)) + "…" : newText) : nil+ dirty = true+ }+ if cell.textFont != newFont { cell.textFont = newFont; dirty = true }+ if cell.textColor != newColor { cell.textColor = newColor; dirty = true }++ let newAlignment: NSTextAlignment = value.isNumeric ? .right : .left+ if cell.textAlignment != newAlignment { cell.textAlignment = newAlignment; dirty = true }+ cell.isDateColumn = isDateColumn(col)+ cell.isBooleanColumn = isBoolColumn(col)++ let colName = col < columns.count ? columns[col].name : ""+ cell.foreignKeyTarget = foreignKeyColumns[colName]+ cell.foreignKeyRefColumn = foreignKeyRefColumns[colName]+ cell.cellValue = value == .null ? "" : newText+ cell.onFKClick = onFKClick+ cell.hasDefaultValue = columnDefaults[colName] != nil+ cell.hasEnumValues = columnEnumValues[colName] != nil++ let isModified = modifiedCells.contains("\(row):\(colName)")+ let newBg = isModified ? NSColor.Gridex.cellModified : nil+ if cell.cellBackgroundColor != newBg { cell.cellBackgroundColor = newBg; dirty = true }+ if dirty { cell.needsDisplay = true }+ }++ private func refreshRow(_ row: Int, in tableView: NSTableView) {+ guard row < rows.count else { return }++ // Update row view background (deleted = red, inserted = blue)+ if let rowView = tableView.rowView(atRow: row, makeIfNecessary: false) as? DataGridRowView {+ let isDeleted = deletedRows.contains(row)+ let isInserted = insertedRowIndices.contains(row)+ if isDeleted {+ rowView.overrideBackgroundColor = NSColor.Gridex.cellDeleted+ } else if isInserted {+ rowView.overrideBackgroundColor = NSColor.systemBlue.withAlphaComponent(0.12)+ } else {+ rowView.overrideBackgroundColor = nil+ }+ rowView.needsDisplay = true+ }++ for colIdx in 0..<tableView.numberOfColumns {+ guard let cell = tableView.view(atColumn: colIdx, row: row, makeIfNecessary: false) as? DataGridCellView,+ !cell.isEditingActive else { continue }+ configureCell(cell, row: row, col: colIdx)+ }+ }++ // MARK: - DataSource++ nonisolated func numberOfRows(in tableView: NSTableView) -> Int {+ MainActor.assumeIsolated { rows.count }+ }++ nonisolated func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {+ MainActor.assumeIsolated {+ guard let tableColumn,+ let colIdx = columnNameToIndex[tableColumn.identifier.rawValue],+ row < rows.count else { return nil }++ let cellId = NSUserInterfaceItemIdentifier("DataCell")+ let cell: DataGridCellView+ if let reused = tableView.makeView(withIdentifier: cellId, owner: self) as? DataGridCellView {+ cell = reused+ cell.isEditingActive = false+ } else {+ cell = DataGridCellView()+ cell.identifier = cellId+ }++ configureCell(cell, row: row, col: colIdx)+ return cell+ }+ }++ nonisolated func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {+ MainActor.assumeIsolated {+ let rowId = NSUserInterfaceItemIdentifier("DataGridRow")+ let rowView = (tableView.makeView(withIdentifier: rowId, owner: self) as? DataGridRowView) ?? DataGridRowView()+ rowView.identifier = rowId+ let isDeleted = deletedRows.contains(row)+ let isInserted = insertedRowIndices.contains(row)+ if isDeleted {+ rowView.overrideBackgroundColor = NSColor.Gridex.cellDeleted+ } else if isInserted {+ rowView.overrideBackgroundColor = NSColor.systemBlue.withAlphaComponent(0.12)+ } else {+ rowView.overrideBackgroundColor = nil+ }+ return rowView+ }+ }++ // MARK: - Delegate++ nonisolated func tableViewSelectionDidChange(_ notification: Notification) {+ MainActor.assumeIsolated {+ guard !isUpdating, let tableView else { return }+ onSelectRows?(Set(tableView.selectedRowIndexes.map { $0 }))+ }+ }++ nonisolated func tableView(_ tableView: NSTableView, didClick tableColumn: NSTableColumn) {+ MainActor.assumeIsolated {+ guard let vm = viewModel else { return }+ let colName = tableColumn.identifier.rawValue+ if vm.sortColumn == colName {+ vm.sortAscending.toggle()+ } else {+ vm.sortColumn = colName+ vm.sortAscending = true+ }+ }+ }++ nonisolated func tableViewColumnDidResize(_ notification: Notification) {+ MainActor.assumeIsolated {+ guard let col = notification.userInfo?["NSTableColumn"] as? NSTableColumn else { return }+ // Update local cache only — don't fire objectWillChange to avoid full refresh+ columnWidths[col.identifier.rawValue] = col.width+ }+ }++ /// Sync column widths back to view model (called on resize end or when needed)+ private func syncColumnWidthsToViewModel() {+ viewModel?.columnWidths = columnWidths+ }++ // MARK: - Inline Editing++ @objc nonisolated func tableViewDoubleClick(_ sender: Any?) {+ MainActor.assumeIsolated {+ guard let tableView else { return }+ let row = tableView.clickedRow+ let col = tableView.clickedColumn+ guard row >= 0, col >= 0 else { return }+ beginEditing(row: row, col: col)+ }+ }++ private func isDateColumn(_ col: Int) -> Bool {+ dateColumnIndices.contains(col)+ }++ private func isBoolColumn(_ col: Int) -> Bool {+ boolColumnIndices.contains(col)+ }++ func beginEditing(row: Int, col: Int) {+ guard let tableView, col < columns.count, row < rows.count else { return }+ if tableView.subviews.contains(where: { $0 is EditContainerView }) { return }++ // Boolean columns show True/False picker+ if isBoolColumn(col) {+ showBooleanMenu(row: row, col: col)+ return+ }++ // Date/time columns show a popup menu instead of a text field+ if isDateColumn(col) {+ showDateMenu(row: row, col: col)+ return+ }++ // Enum columns show a popup menu with enum values+ let colName = columns[col].name+ if columnEnumValues[colName] != nil {+ showEnumMenu(row: row, col: col)+ return+ }++ beginTextEditing(row: row, col: col)+ }++ private func beginTextEditing(row: Int, col: Int) {+ guard let tableView, col < columns.count, row < rows.count else { return }++ isEditing = true++ let value = col < rows[row].count ? rows[row][col] : .null+ let initialText = value.isNull ? "" : value.description++ // Hide the cell's drawn text while editing+ if let cellView = tableView.view(atColumn: col, row: row, makeIfNecessary: false) as? DataGridCellView {+ cellView.isEditingActive = true+ cellView.needsDisplay = true+ }++ // Place editor as a direct child of the table view (not the cell)+ // to prevent first responder changes from disrupting the cell hierarchy.+ let cellRect = tableView.frameOfCell(atColumn: col, row: row)++ let container = EditContainerView()+ container.frame = cellRect+ container.wantsLayer = true+ container.layer?.borderColor = NSColor.controlAccentColor.cgColor+ container.layer?.borderWidth = 2+ container.layer?.cornerRadius = 2+ container.layer?.backgroundColor = NSColor.textBackgroundColor.cgColor++ let editor = NSTextField(string: initialText)+ editor.font = Self.cellFont+ editor.isEditable = true+ editor.isBordered = false+ editor.isBezeled = false+ editor.focusRingType = .none+ editor.textColor = .textColor+ editor.backgroundColor = .textBackgroundColor+ editor.drawsBackground = true+ editor.frame = CGRect(x: 4, y: 0, width: cellRect.width - 8, height: cellRect.height)+ editor.autoresizingMask = [.width, .height]+ editor.delegate = self++ let info = EditInfo(row: row, col: col)+ objc_setAssociatedObject(editor, &Self.editInfoKey, info, .OBJC_ASSOCIATION_RETAIN)++ container.addSubview(editor)+ tableView.addSubview(container)+ tableView.window?.makeFirstResponder(editor)+ }++ // MARK: - Date Column Menu++ private var pendingDateEdit: (row: Int, col: Int)?++ private func showDateMenu(row: Int, col: Int) {+ guard let tableView else { return }+ pendingDateEdit = (row, col)++ let menu = NSMenu()+ menu.autoenablesItems = false++ let nullItem = NSMenuItem(title: "NULL", action: #selector(dateMenuNull(_:)), keyEquivalent: "")+ nullItem.target = self+ menu.addItem(nullItem)++ if insertedRowIndices.contains(row) {+ let defaultItem = NSMenuItem(title: "DEFAULT", action: #selector(dateMenuDefault(_:)), keyEquivalent: "")+ defaultItem.target = self+ menu.addItem(defaultItem)+ }++ menu.addItem(NSMenuItem.separator())++ let nowItem = NSMenuItem(title: "NOW()", action: #selector(dateMenuNow(_:)), keyEquivalent: "")+ nowItem.target = self+ menu.addItem(nowItem)++ menu.addItem(NSMenuItem.separator())++ let pickerItem = NSMenuItem(title: "Date Picker...", action: #selector(dateMenuPicker(_:)), keyEquivalent: "")+ pickerItem.target = self+ menu.addItem(pickerItem)++ let manualItem = NSMenuItem(title: "Manual input...", action: #selector(dateMenuManual(_:)), keyEquivalent: "")+ manualItem.target = self+ menu.addItem(manualItem)++ let cellRect = tableView.frameOfCell(atColumn: col, row: row)+ let menuOrigin = NSPoint(x: cellRect.minX, y: cellRect.maxY)+ menu.popUp(positioning: nil, at: menuOrigin, in: tableView)+ }++ @objc nonisolated func dateMenuNull(_ sender: Any?) {+ MainActor.assumeIsolated {+ commitDateValue(.null)+ }+ }++ @objc nonisolated func dateMenuDefault(_ sender: Any?) {+ MainActor.assumeIsolated {+ // For new rows, NULL means let DB handle default+ commitDateValue(.null)+ }+ }++ @objc nonisolated func dateMenuNow(_ sender: Any?) {+ MainActor.assumeIsolated {+ commitDateValue(.date(Date()))+ }+ }++ @objc nonisolated func dateMenuManual(_ sender: Any?) {+ MainActor.assumeIsolated {+ guard let edit = pendingDateEdit else { return }+ pendingDateEdit = nil+ beginTextEditing(row: edit.row, col: edit.col)+ }+ }++ @objc nonisolated func dateMenuPicker(_ sender: Any?) {+ MainActor.assumeIsolated {+ guard let edit = pendingDateEdit, let tableView else {+ pendingDateEdit = nil+ return+ }++ let cellRect = tableView.frameOfCell(atColumn: edit.col, row: edit.row)+ let screenRect = tableView.convert(cellRect, to: nil)+ let windowRect = tableView.window?.convertToScreen(screenRect) ?? .zero++ // Current value as initial date+ var initialDate = Date()+ if edit.row < rows.count, edit.col < rows[edit.row].count {+ if case .date(let d) = rows[edit.row][edit.col] {+ initialDate = d+ }+ }++ let panel = DatePickerPanel(date: initialDate) { [weak self] selectedDate in+ self?.commitDateValue(.date(selectedDate))+ }+ panel.show(relativeTo: windowRect)+ }+ }++ private func commitDateValue(_ value: RowValue) {+ guard let edit = pendingDateEdit else { return }+ pendingDateEdit = nil++ guard edit.row < rows.count, edit.col < columns.count else { return }++ let oldValue = rows[edit.row][edit.col]+ guard oldValue != value else { return }++ if insertedRowIndices.contains(edit.row) {+ viewModel?.commitDateEdit(rowIndex: edit.row, colIdx: edit.col, newValue: value)+ } else {+ viewModel?.commitDateEdit(rowIndex: edit.row, colIdx: edit.col, newValue: value)+ }++ if let vm = viewModel {+ rows = vm.rows+ pendingChanges = vm.changeTracker.pendingChanges+ }++ // Update cell appearance+ if let tableView,+ let cellView = tableView.view(atColumn: edit.col, row: edit.row, makeIfNecessary: false) as? DataGridCellView {+ configureCell(cellView, row: edit.row, col: edit.col)+ if oldValue != value {+ cellView.cellBackgroundColor = NSColor.Gridex.cellModified+ cellView.needsDisplay = true+ }+ }+ }++ // MARK: - Default Value Column Menu++ private var pendingDefaultEdit: (row: Int, col: Int)?++ private func showDefaultMenu(row: Int, col: Int) {+ guard let tableView else { return }+ pendingDefaultEdit = (row, col)++ let colName = columns[col].name+ let defaultExpr = columnDefaults[colName] ?? ""++ let menu = NSMenu()+ menu.autoenablesItems = false++ let nullItem = NSMenuItem(title: "NULL", action: #selector(defaultMenuNull(_:)), keyEquivalent: "")+ nullItem.target = self+ menu.addItem(nullItem)++ if insertedRowIndices.contains(row) {+ let defaultItem = NSMenuItem(title: "DEFAULT (\(defaultExpr))", action: #selector(defaultMenuDefault(_:)), keyEquivalent: "")+ defaultItem.target = self+ menu.addItem(defaultItem)+ }++ menu.addItem(NSMenuItem.separator())++ let manualItem = NSMenuItem(title: "Manual input...", action: #selector(defaultMenuManual(_:)), keyEquivalent: "")+ manualItem.target = self+ menu.addItem(manualItem)++ let cellRect = tableView.frameOfCell(atColumn: col, row: row)+ let menuOrigin = NSPoint(x: cellRect.minX, y: cellRect.maxY)+ menu.popUp(positioning: nil, at: menuOrigin, in: tableView)+ }++ @objc nonisolated func defaultMenuNull(_ sender: Any?) {+ MainActor.assumeIsolated {+ guard let edit = pendingDefaultEdit else { return }+ pendingDefaultEdit = nil+ commitDefaultValue(.null, edit: edit)+ }+ }++ @objc nonisolated func defaultMenuDefault(_ sender: Any?) {+ MainActor.assumeIsolated {+ guard let edit = pendingDefaultEdit else { return }+ pendingDefaultEdit = nil+ // NULL for inserted rows = let DB handle the default+ commitDefaultValue(.null, edit: edit)+ }+ }++ @objc nonisolated func defaultMenuManual(_ sender: Any?) {+ MainActor.assumeIsolated {+ guard let edit = pendingDefaultEdit else { return }+ pendingDefaultEdit = nil+ beginTextEditing(row: edit.row, col: edit.col)+ }+ }++ private func commitDefaultValue(_ value: RowValue, edit: (row: Int, col: Int)) {+ guard edit.row < rows.count, edit.col < columns.count else { return }++ let oldValue = rows[edit.row][edit.col]+ guard oldValue != value else { return }++ if insertedRowIndices.contains(edit.row) {+ viewModel?.commitNewRowEdit(rowIndex: edit.row, colIdx: edit.col, newText: value.isNull ? "NULL" : value.description)+ } else {+ viewModel?.commitCellEdit(rowIndex: edit.row, colIdx: edit.col, newText: value.isNull ? "NULL" : value.description)+ }++ if let vm = viewModel {+ rows = vm.rows+ pendingChanges = vm.changeTracker.pendingChanges+ }++ if let tableView,+ let cellView = tableView.view(atColumn: edit.col, row: edit.row, makeIfNecessary: false) as? DataGridCellView {+ configureCell(cellView, row: edit.row, col: edit.col)+ if oldValue != value {+ cellView.cellBackgroundColor = NSColor.Gridex.cellModified+ cellView.needsDisplay = true+ }+ }+ }++ // MARK: - Enum Column Menu++ private var pendingEnumEdit: (row: Int, col: Int)?++ private func showEnumMenu(row: Int, col: Int) {+ guard let tableView else { return }+ pendingEnumEdit = (row, col)++ let colName = columns[col].name+ guard let values = columnEnumValues[colName] else { return }++ let menu = NSMenu()+ menu.autoenablesItems = false++ let nullItem = NSMenuItem(title: "NULL", action: #selector(enumMenuNull(_:)), keyEquivalent: "")+ nullItem.target = self+ menu.addItem(nullItem)++ menu.addItem(NSMenuItem.separator())++ for value in values {+ let item = NSMenuItem(title: value, action: #selector(enumMenuSelect(_:)), keyEquivalent: "")+ item.target = self+ item.representedObject = value+ // Check-mark the current value+ let currentValue = rows[row][col]+ if case .string(let s) = currentValue, s == value {+ item.state = .on+ }+ menu.addItem(item)+ }++ menu.addItem(NSMenuItem.separator())++ let manualItem = NSMenuItem(title: "Manual input...", action: #selector(enumMenuManual(_:)), keyEquivalent: "")+ manualItem.target = self+ menu.addItem(manualItem)++ let cellRect = tableView.frameOfCell(atColumn: col, row: row)+ let menuOrigin = NSPoint(x: cellRect.minX, y: cellRect.maxY)+ menu.popUp(positioning: nil, at: menuOrigin, in: tableView)+ }++ @objc nonisolated func enumMenuNull(_ sender: Any?) {+ MainActor.assumeIsolated {+ guard let edit = pendingEnumEdit else { return }+ pendingEnumEdit = nil+ commitEnumValue(.null, edit: edit)+ }+ }++ @objc nonisolated func enumMenuSelect(_ sender: Any?) {+ MainActor.assumeIsolated {+ guard let edit = pendingEnumEdit,+ let item = sender as? NSMenuItem,+ let value = item.representedObject as? String else { return }+ pendingEnumEdit = nil+ commitEnumValue(.string(value), edit: edit)+ }+ }++ @objc nonisolated func enumMenuManual(_ sender: Any?) {+ MainActor.assumeIsolated {+ guard let edit = pendingEnumEdit else { return }+ pendingEnumEdit = nil+ beginTextEditing(row: edit.row, col: edit.col)+ }+ }++ private func commitEnumValue(_ value: RowValue, edit: (row: Int, col: Int)) {+ guard edit.row < rows.count, edit.col < columns.count else { return }++ let oldValue = rows[edit.row][edit.col]+ guard oldValue != value else { return }++ if insertedRowIndices.contains(edit.row) {+ viewModel?.commitNewRowEdit(rowIndex: edit.row, colIdx: edit.col, newText: value.isNull ? "NULL" : value.description)+ } else {+ viewModel?.commitCellEdit(rowIndex: edit.row, colIdx: edit.col, newText: value.isNull ? "NULL" : value.description)+ }++ if let vm = viewModel {+ rows = vm.rows+ pendingChanges = vm.changeTracker.pendingChanges+ }++ if let tableView,+ let cellView = tableView.view(atColumn: edit.col, row: edit.row, makeIfNecessary: false) as? DataGridCellView {+ configureCell(cellView, row: edit.row, col: edit.col)+ if oldValue != value {+ cellView.cellBackgroundColor = NSColor.Gridex.cellModified+ cellView.needsDisplay = true+ }+ }+ }++ // MARK: - Boolean Column Menu++ private var pendingBoolEdit: (row: Int, col: Int)?++ private func showBooleanMenu(row: Int, col: Int) {+ guard let tableView else { return }+ pendingBoolEdit = (row, col)++ let currentValue = rows[row][col]+ let menu = NSMenu()+ menu.autoenablesItems = false++ let nullItem = NSMenuItem(title: "NULL", action: #selector(boolMenuNull(_:)), keyEquivalent: "")+ nullItem.target = self+ if currentValue.isNull { nullItem.state = .on }+ menu.addItem(nullItem)++ menu.addItem(NSMenuItem.separator())++ let trueItem = NSMenuItem(title: "true", action: #selector(boolMenuTrue(_:)), keyEquivalent: "")+ trueItem.target = self+ if case .boolean(true) = currentValue { trueItem.state = .on }+ else if case .string(let s) = currentValue, s.lowercased() == "true" || s == "t" { trueItem.state = .on }+ menu.addItem(trueItem)++ let falseItem = NSMenuItem(title: "false", action: #selector(boolMenuFalse(_:)), keyEquivalent: "")+ falseItem.target = self+ if case .boolean(false) = currentValue { falseItem.state = .on }+ else if case .string(let s) = currentValue, s.lowercased() == "false" || s == "f" { falseItem.state = .on }+ menu.addItem(falseItem)++ let cellRect = tableView.frameOfCell(atColumn: col, row: row)+ let menuOrigin = NSPoint(x: cellRect.minX, y: cellRect.maxY)+ menu.popUp(positioning: nil, at: menuOrigin, in: tableView)+ }++ @objc nonisolated func boolMenuNull(_ sender: Any?) {+ MainActor.assumeIsolated {+ guard let edit = pendingBoolEdit else { return }+ pendingBoolEdit = nil+ commitBoolValue(.null, edit: edit)+ }+ }++ @objc nonisolated func boolMenuTrue(_ sender: Any?) {+ MainActor.assumeIsolated {+ guard let edit = pendingBoolEdit else { return }+ pendingBoolEdit = nil+ commitBoolValue(.boolean(true), edit: edit)+ }+ }++ @objc nonisolated func boolMenuFalse(_ sender: Any?) {+ MainActor.assumeIsolated {+ guard let edit = pendingBoolEdit else { return }+ pendingBoolEdit = nil+ commitBoolValue(.boolean(false), edit: edit)+ }+ }++ private func commitBoolValue(_ value: RowValue, edit: (row: Int, col: Int)) {+ guard edit.row < rows.count, edit.col < columns.count else { return }++ let oldValue = rows[edit.row][edit.col]+ guard oldValue != value else { return }++ let text: String+ switch value {+ case .null: text = "NULL"+ case .boolean(let b): text = b ? "true" : "false"+ default: text = value.description+ }++ if insertedRowIndices.contains(edit.row) {+ viewModel?.commitNewRowEdit(rowIndex: edit.row, colIdx: edit.col, newText: text)+ } else {+ viewModel?.commitCellEdit(rowIndex: edit.row, colIdx: edit.col, newText: text)+ }++ if let vm = viewModel {+ rows = vm.rows+ pendingChanges = vm.changeTracker.pendingChanges+ }++ if let tableView,+ let cellView = tableView.view(atColumn: edit.col, row: edit.row, makeIfNecessary: false) as? DataGridCellView {+ configureCell(cellView, row: edit.row, col: edit.col)+ if oldValue != value {+ cellView.cellBackgroundColor = NSColor.Gridex.cellModified+ cellView.needsDisplay = true+ }+ }+ }++ private static var editInfoKey: UInt8 = 0++ private struct EditInfo {+ let row: Int+ let col: Int+ }++ private func finishEditing(_ editor: NSTextField, commit: Bool, nextCol: Bool = false) {+ guard let info = objc_getAssociatedObject(editor, &Self.editInfoKey) as? EditInfo else { return }+ objc_setAssociatedObject(editor, &Self.editInfoKey, nil, .OBJC_ASSOCIATION_RETAIN)++ // Save scroll position before any changes — removing the editor+ // and changing first responder can cause NSTableView to auto-scroll.+ let savedContentOffset = tableView?.enclosingScrollView?.contentView.bounds.origin++ if commit {+ if insertedRowIndices.contains(info.row) {+ viewModel?.commitNewRowEdit(rowIndex: info.row, colIdx: info.col, newText: editor.stringValue)+ } else {+ viewModel?.commitCellEdit(rowIndex: info.row, colIdx: info.col, newText: editor.stringValue)+ }+ }++ // Remove the floating editor from the table view+ (editor.superview as? EditContainerView)?.removeFromSuperview()++ // Restore the cell underneath and update its content+ if let tableView,+ let cellView = tableView.view(atColumn: info.col, row: info.row, makeIfNecessary: false) as? DataGridCellView {+ cellView.isEditingActive = false+ if commit, let vm = viewModel {+ rows = vm.rows+ pendingChanges = vm.changeTracker.pendingChanges+ rebuildPendingChangeCaches()+ }+ configureCell(cellView, row: info.row, col: info.col)+ cellView.needsDisplay = true+ }++ // Restore scroll position using the enclosing scroll view directly.+ // Deferred to ensure it runs after any pending layout triggered by+ // removing the editor or changing first responder.+ if let scrollView = tableView?.enclosingScrollView, let offset = savedContentOffset {+ scrollView.contentView.scroll(to: offset)+ scrollView.reflectScrolledClipView(scrollView.contentView)+ }++ justFinishedEditing = true+ isEditing = false++ // Tab → open next column for editing+ if nextCol, commit {+ let nextColIdx = info.col + 1+ if nextColIdx < columns.count {+ beginEditing(row: info.row, col: nextColIdx)+ }+ }+ }++ nonisolated func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {+ MainActor.assumeIsolated {+ guard let editor = control as? NSTextField else { return false }++ if commandSelector == #selector(NSResponder.insertNewline(_:)) {+ finishEditing(editor, commit: true)+ return true+ } else if commandSelector == #selector(NSResponder.insertTab(_:)) {+ finishEditing(editor, commit: true, nextCol: true)+ return true+ } else if commandSelector == #selector(NSResponder.cancelOperation(_:)) {+ finishEditing(editor, commit: false)+ return true+ }+ return false+ }+ }++ nonisolated func controlTextDidEndEditing(_ obj: Notification) {+ MainActor.assumeIsolated {+ guard let editor = obj.object as? NSTextField else { return }+ finishEditing(editor, commit: true)+ }+ }++ // MARK: - Copy++ @objc nonisolated func copyRow(_ sender: Any?) {+ MainActor.assumeIsolated {+ guard let tableView else { return }+ let row = tableView.clickedRow+ guard row >= 0, row < rows.count else { return }+ let text = rows[row].map { $0.isNull ? "NULL" : $0.description }.joined(separator: "\t")+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(text, forType: .string)+ }+ }++ @objc nonisolated func copyCell(_ sender: Any?) {+ MainActor.assumeIsolated {+ guard let tableView else { return }+ let row = tableView.clickedRow+ let col = tableView.clickedColumn+ guard row >= 0, col >= 0, col < columns.count, row < rows.count else { return }+ let value = col < rows[row].count ? rows[row][col] : .null+ let text = value.isNull ? "NULL" : value.description+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(text, forType: .string)+ }+ }++ @objc nonisolated func deleteRows(_ sender: Any?) {+ MainActor.assumeIsolated {+ guard let vm = viewModel, let tableView else { return }+ // If right-clicked row is not in selection, delete just that row+ let clickedRow = tableView.clickedRow+ if clickedRow >= 0, !tableView.selectedRowIndexes.contains(clickedRow) {+ vm.selectedRows = [clickedRow]+ }+ vm.deleteSelectedRows()+ }+ }+ }+}++// MARK: - Key-aware Table View (Delete key support)++private class DataGridTableView: NSTableView {+ weak var gridCoordinator: AppKitDataGrid.Coordinator?++ override func keyDown(with event: NSEvent) {+ let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask)++ switch event.keyCode {+ case 51, 117: // Delete, Forward Delete+ gridCoordinator?.deleteRows(nil)+ case 36: // Enter → edit selected cell+ if selectedRow >= 0, selectedColumn >= 0 {+ gridCoordinator?.beginEditing(row: selectedRow, col: selectedColumn)+ } else if selectedRow >= 0 {+ gridCoordinator?.beginEditing(row: selectedRow, col: 0)+ }+ case 8 where flags == .command: // ⌘C → copy+ gridCoordinator?.copyCell(nil)+ default:+ super.keyDown(with: event)+ }+ }+}++// MARK: - Custom Row View++private class DataGridRowView: NSTableRowView {+ var overrideBackgroundColor: NSColor?++ override func drawBackground(in dirtyRect: NSRect) {+ if let color = overrideBackgroundColor {+ color.setFill()+ bounds.fill()+ } else {+ super.drawBackground(in: dirtyRect)+ }+ }+}++// MARK: - Cell View (Direct Text Drawing)++private class DataGridCellView: NSView {+ var cellBackgroundColor: NSColor?+ var textFont: NSFont = AppKitDataGrid.Coordinator.cellFont+ var textColor: NSColor = .labelColor+ var textAlignment: NSTextAlignment = .left+ var isEditingActive: Bool = false+ var isDateColumn: Bool = false+ var hasDefaultValue: Bool = false+ var hasEnumValues: Bool = false+ var foreignKeyTarget: String? = nil // referenced table name+ var foreignKeyRefColumn: String? = nil // referenced column name+ var cellValue: String = "" // current cell value (for FK click)+ var onFKClick: ((_ refTable: String, _ refColumn: String, _ value: String) -> Void)?+ var isBooleanColumn: Bool = false++ // Text with cached attributed string — invalidated on change+ private var _text: String = ""+ private var _cachedAttrString: NSAttributedString?+ private var _cacheFont: NSFont?+ private var _cacheColor: NSColor?+ private var _cacheAlignment: NSTextAlignment?++ var text: String {+ get { _text }+ set {+ if _text != newValue {+ _text = newValue+ _cachedAttrString = nil+ }+ }+ }++ var showChevron: Bool { isDateColumn || hasEnumValues || isBooleanColumn }++ // Cached objects — avoid allocations in draw()+ private static let fkArrowAttrs: [NSAttributedString.Key: Any] = [+ .font: NSFont.systemFont(ofSize: 10, weight: .medium),+ .foregroundColor: NSColor.secondaryLabelColor+ ]+ private static let fkArrow = NSAttributedString(string: "→", attributes: fkArrowAttrs)+ private static let fkArrowSize = fkArrow.size()++ private static let chevronImage: NSImage? = {+ guard let img = NSImage(systemSymbolName: "chevron.up.chevron.down", accessibilityDescription: nil) else { return nil }+ let config = NSImage.SymbolConfiguration(pointSize: 10, weight: .regular)+ .applying(.init(paletteColors: [.secondaryLabelColor]))+ return img.withSymbolConfiguration(config) ?? img+ }()++ private let paragraphStyle: NSMutableParagraphStyle = {+ let ps = NSMutableParagraphStyle()+ ps.lineBreakMode = .byTruncatingTail+ return ps+ }()++ private func cachedAttributedString() -> NSAttributedString {+ if let cached = _cachedAttrString,+ _cacheFont === textFont,+ _cacheColor == textColor,+ _cacheAlignment == textAlignment {+ return cached+ }+ paragraphStyle.alignment = textAlignment+ // Pre-truncate long strings — cell can only show ~200 chars max at any width+ let drawText = _text.count > 300 ? String(_text.prefix(300)) + "…" : _text+ let str = NSAttributedString(string: drawText, attributes: [+ .font: textFont,+ .foregroundColor: textColor,+ .paragraphStyle: paragraphStyle+ ])+ _cachedAttrString = str+ _cacheFont = textFont+ _cacheColor = textColor+ _cacheAlignment = textAlignment+ return str+ }++ override init(frame frameRect: NSRect) {+ super.init(frame: frameRect)+ wantsLayer = true+ layerContentsRedrawPolicy = .onSetNeedsDisplay+ canDrawSubviewsIntoLayer = true+ }++ required init?(coder: NSCoder) { fatalError() }++ override var isFlipped: Bool { true }++ override func draw(_ dirtyRect: NSRect) {+ if let color = cellBackgroundColor {+ color.setFill()+ bounds.fill()+ }++ guard !isEditingActive else { return }++ let hasFK = foreignKeyTarget != nil+ let chevronWidth: CGFloat = showChevron ? 18 : 0+ let fkWidth: CGFloat = hasFK ? 16 : 0+ let rightIconWidth = chevronWidth + fkWidth++ let attrStr = cachedAttributedString()++ var textRect = bounds.insetBy(dx: 6, dy: 0)+ textRect.size.width -= rightIconWidth+ let textHeight = textFont.ascender - textFont.descender + textFont.leading+ textRect.origin.y = max(0, (bounds.height - textHeight) / 2)+ textRect.size.height = textHeight + 2+ attrStr.draw(with: textRect, options: [.truncatesLastVisibleLine, .usesLineFragmentOrigin], context: nil)++ // FK arrow on the right (before chevron)+ if hasFK {+ let s = Self.fkArrowSize+ let fkX = bounds.maxX - chevronWidth - s.width - 3+ let fkY = (bounds.height - s.height) / 2+ Self.fkArrow.draw(at: NSPoint(x: fkX, y: fkY))+ }++ // Chevron icon on the far right+ if showChevron, let img = Self.chevronImage {+ let iconSize = img.size+ let iconX = bounds.maxX - iconSize.width - 5+ let iconY = (bounds.height - iconSize.height) / 2+ img.draw(in: NSRect(x: iconX, y: iconY, width: iconSize.width, height: iconSize.height))+ }+ }++ override func mouseDown(with event: NSEvent) {+ guard let fkTable = foreignKeyTarget, let fkCol = foreignKeyRefColumn, !cellValue.isEmpty else {+ super.mouseDown(with: event)+ return+ }+ let loc = convert(event.locationInWindow, from: nil)+ let chevronWidth: CGFloat = showChevron ? 18 : 0+ let fkHitX = bounds.maxX - chevronWidth - Self.fkArrowSize.width - 6+ if loc.x >= fkHitX && loc.x <= bounds.maxX - chevronWidth {+ onFKClick?(fkTable, fkCol, cellValue)+ } else {+ super.mouseDown(with: event)+ }+ }++ override func prepareForReuse() {+ super.prepareForReuse()+ cellBackgroundColor = nil+ text = ""+ textColor = .labelColor+ textAlignment = .left+ isEditingActive = false+ isDateColumn = false+ hasDefaultValue = false+ hasEnumValues = false+ isBooleanColumn = false+ foreignKeyTarget = nil+ foreignKeyRefColumn = nil+ cellValue = ""+ onFKClick = nil+ }+}++// MARK: - Edit Container (marker class for type detection)++private class EditContainerView: NSView {}++// MARK: - Sortable Header Cell++private class SortableHeaderCell: NSTableHeaderCell {+ override func drawInterior(withFrame cellFrame: NSRect, in controlView: NSView) {+ let attrs: [NSAttributedString.Key: Any] = [+ .font: NSFont.systemFont(ofSize: 12, weight: .medium),+ .foregroundColor: NSColor.secondaryLabelColor+ ]+ let str = NSAttributedString(string: stringValue, attributes: attrs)+ let rect = cellFrame.insetBy(dx: 6, dy: 0)+ str.draw(with: rect, options: [.truncatesLastVisibleLine, .usesLineFragmentOrigin], context: nil)+ }+}++// MARK: - Date Picker Panel++@MainActor+private class DatePickerPanel: NSObject {+ private let panel: NSPanel+ private let datePicker: NSDatePicker+ private let onSelect: (Date) -> Void++ init(date: Date, onSelect: @escaping (Date) -> Void) {+ self.onSelect = onSelect++ panel = NSPanel(+ contentRect: NSRect(x: 0, y: 0, width: 240, height: 180),+ styleMask: [.titled, .closable, .fullSizeContentView],+ backing: .buffered,+ defer: false+ )+ panel.isFloatingPanel = true+ panel.level = .floating+ panel.titlebarAppearsTransparent = true+ panel.titleVisibility = .hidden+ panel.isMovableByWindowBackground = true+ panel.hasShadow = true+ panel.becomesKeyOnlyIfNeeded = false++ datePicker = NSDatePicker()+ datePicker.datePickerStyle = .clockAndCalendar+ datePicker.datePickerElements = [.yearMonthDay, .hourMinuteSecond]+ datePicker.dateValue = date+ datePicker.timeZone = TimeZone(identifier: "UTC")++ super.init()++ let contentView = NSView(frame: NSRect(x: 0, y: 0, width: 240, height: 180))++ datePicker.translatesAutoresizingMaskIntoConstraints = false+ contentView.addSubview(datePicker)++ let okButton = NSButton(title: "OK", target: self, action: #selector(confirmDate(_:)))+ okButton.bezelStyle = .rounded+ okButton.keyEquivalent = "\r"+ okButton.translatesAutoresizingMaskIntoConstraints = false+ contentView.addSubview(okButton)++ let cancelButton = NSButton(title: "Cancel", target: self, action: #selector(cancelDate(_:)))+ cancelButton.bezelStyle = .rounded+ cancelButton.keyEquivalent = "\u{1b}"+ cancelButton.translatesAutoresizingMaskIntoConstraints = false+ contentView.addSubview(cancelButton)++ NSLayoutConstraint.activate([+ datePicker.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 12),+ datePicker.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),++ okButton.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -12),+ okButton.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -12),+ okButton.widthAnchor.constraint(greaterThanOrEqualToConstant: 60),++ cancelButton.trailingAnchor.constraint(equalTo: okButton.leadingAnchor, constant: -8),+ cancelButton.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -12),+ cancelButton.widthAnchor.constraint(greaterThanOrEqualToConstant: 60),+ ])++ panel.contentView = contentView+ }++ func show(relativeTo rect: NSRect) {+ let x = rect.minX+ let y = rect.minY - panel.frame.height - 4+ panel.setFrameOrigin(NSPoint(x: x, y: y))+ panel.makeKeyAndOrderFront(nil)+ // Keep self alive while panel is visible+ objc_setAssociatedObject(panel, "datePickerOwner", self, .OBJC_ASSOCIATION_RETAIN)+ }++ @objc private func confirmDate(_ sender: Any?) {+ let date = datePicker.dateValue+ panel.close()+ onSelect(date)+ }++ @objc private func cancelDate(_ sender: Any?) {+ panel.close()+ }+}diff --git a/macos/Presentation/Views/DataGrid/CreateTableView.swift b/macos/Presentation/Views/DataGrid/CreateTableView.swiftnew file mode 100644index 0000000..a4c6cf5--- /dev/null+++ b/macos/Presentation/Views/DataGrid/CreateTableView.swift@@ -0,0 +1,913 @@+// CreateTableView.swift+// Gridex+//+// View for creating a new database table with columns, primary key, indexes.+// UI matches the Structure editor (columns: #, name, type, nullable, check,+// foreign_key, default, comment; indexes: name, algorithm, unique, columns,+// condition, include, comment).++import SwiftUI++struct CreateTableView: View {+ let schema: String?++ @EnvironmentObject private var appState: AppState+ @State private var tableName: String = "new_table"+ @State private var columns: [NewColumn] = [+ NewColumn(name: "id", dataType: "int4", isPrimaryKey: true, isNullable: false, defaultValue: ""),+ ]+ @State private var indexes: [NewIndex] = []+ @State private var isCreating = false+ @State private var errorMessage: String?+ @State private var cachedDataTypes: [String] = []++ enum ColumnField: Hashable {+ case name(UUID), dataType(UUID), comment(UUID)+ }+ @FocusState private var focusedField: ColumnField?+ @State private var selectedColumnId: UUID?+ @State private var selectedIndexId: UUID?++ // FK editor state+ @State private var fkEditColumnId: UUID?+ @State private var fkRefTable: String = ""+ @State private var fkRefColumn: String = ""+ @State private var availableTables: [String] = []++ // Default value editor state+ @State private var defaultEditColumnId: UUID?+ @State private var defaultTab: DefaultTab = .string+ @State private var defaultStringValue: String = ""+ @State private var defaultExpressionValue: String = ""++ enum DefaultTab: String, CaseIterable { case string = "String", expression = "Expression" }++ private var isMongoDB: Bool {+ appState.activeAdapter?.databaseType == .mongodb+ }++ private var defaultSchema: String {+ switch appState.activeAdapter?.databaseType {+ case .mssql: return "dbo"+ default: return "public"+ }+ }++ var body: some View {+ VStack(spacing: 0) {+ toolbar+ Divider()+ if isMongoDB {+ mongoCollectionInfo+ } else {+ VSplitView {+ columnsSection+ indexesSection+ }+ }+ }+ .onAppear {+ rebuildDataTypes()+ // Fix default column data type for current adapter (the @State initializer+ // defaults to "int4" which is PostgreSQL-specific).+ if !isMongoDB, let adapter = appState.activeAdapter {+ let idType: String+ switch adapter.databaseType {+ case .postgresql: idType = "int4"+ case .mysql: idType = "int"+ case .sqlite: idType = "INTEGER"+ case .mssql: idType = "INT"+ default: idType = "int"+ }+ if columns.count == 1 && columns[0].dataType == "int4" {+ columns[0].dataType = idType+ }+ }+ // Select the first column so it's immediately editable+ if isMongoDB {+ tableName = "new_collection"+ } else if selectedColumnId == nil, let first = columns.first {+ selectedColumnId = first.id+ }+ }+ }++ private var mongoCollectionInfo: some View {+ VStack(spacing: 16) {+ Spacer()+ Image(systemName: "doc.text.below.ecg")+ .font(.system(size: 48))+ .foregroundStyle(.secondary)+ Text("MongoDB Collection")+ .font(.system(size: 16, weight: .semibold))+ Text("MongoDB collections are schemaless — no column definitions are needed.\nClick \"Create\" to add the collection. Documents can be inserted later with any structure.")+ .font(.system(size: 12))+ .foregroundStyle(.secondary)+ .multilineTextAlignment(.center)+ .padding(.horizontal, 40)+ Spacer()+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ }++ // MARK: - Toolbar++ private var toolbar: some View {+ HStack(spacing: 12) {+ Image(systemName: isMongoDB ? "doc.text" : "tablecells")+ .foregroundStyle(.secondary)+ TextField(isMongoDB ? "Collection name" : "Table name", text: $tableName)+ .textFieldStyle(.squareBorder)+ .frame(maxWidth: 250)++ if !isMongoDB {+ Text("Schema: \(schema ?? defaultSchema)")+ .font(.system(size: 12))+ .foregroundStyle(.secondary)+ } else {+ Text("MongoDB · \(appState.currentDatabaseName ?? "")")+ .font(.system(size: 12))+ .foregroundStyle(.secondary)+ }++ Spacer()++ if let errorMessage {+ Text(errorMessage)+ .font(.system(size: 11))+ .foregroundStyle(.red)+ .lineLimit(2)+ .frame(maxWidth: 300, alignment: .trailing)+ }++ Button {+ Task { await createTable() }+ } label: {+ HStack(spacing: 3) {+ if isCreating {+ ProgressView().controlSize(.small)+ }+ Image(systemName: "checkmark").font(.system(size: 10, weight: .semibold))+ Text("Create").font(.system(size: 11, weight: .medium))+ }+ }+ .buttonStyle(.borderedProminent)+ .pointerCursor()+ .disabled(tableName.isEmpty || (!isMongoDB && columns.isEmpty) || isCreating)+ }+ .padding(.horizontal, 12)+ .padding(.vertical, 8)+ }++ // MARK: - Columns Section (matches Structure editor)++ private var columnsSection: some View {+ VStack(spacing: 0) {+ Table($columns, selection: $selectedColumnId) {+ TableColumn("#") { $col in+ Text("\((columns.firstIndex(where: { $0.id == col.id }) ?? 0) + 1)")+ .foregroundStyle(.secondary)+ }+ .width(30)++ TableColumn("column_name") { $col in+ columnNameCell(col: $col)+ }++ TableColumn("data_type") { $col in+ dataTypeCell(col: $col)+ }++ TableColumn("is_nullable") { $col in+ nullableCell(col: $col)+ }+ .width(80)++ TableColumn("check") { $col in+ if selectedColumnId == col.id {+ TextField("", text: $col.checkConstraint)+ .textFieldStyle(.squareBorder)+ } else {+ Text(col.checkConstraint.isEmpty ? "" : col.checkConstraint)+ .foregroundStyle(.secondary)+ .lineLimit(1)+ .help(col.checkConstraint)+ }+ }++ TableColumn("foreign_key") { $col in+ fkCell(col: $col)+ }++ TableColumn("column_default") { $col in+ defaultCell(col: $col)+ }++ TableColumn("comment") { $col in+ commentCell(col: $col)+ }+ }+ .contextMenu(forSelectionType: UUID.self) { ids in+ if let id = ids.first {+ if let col = columns.first(where: { $0.id == id }) {+ Button(col.isPrimaryKey ? "Unset Primary Key" : "Set as Primary Key") {+ togglePrimaryKey(id)+ }+ Divider()+ }+ Button("Delete Column", role: .destructive) {+ columns.removeAll { $0.id == id }+ }+ }+ } primaryAction: { _ in }+ .onChange(of: selectedColumnId) { _, _ in+ focusedField = nil+ }+ .environment(\.defaultMinListRowHeight, 34)++ // Inline "+ New column" button (matches Structure editor)+ HStack {+ Button { addNewColumn() } label: {+ HStack(spacing: 4) {+ Image(systemName: "plus").font(.system(size: 9))+ Text("New column").font(.system(size: 11))+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 6)+ }+ .buttonStyle(.plain)+ .pointerCursor()+ .foregroundStyle(.tertiary)+ Spacer()+ }+ .padding(.leading, 8)+ .padding(.top, 4)+ }+ .frame(minHeight: 120)+ }++ // MARK: - Column Cell Views (mirrors Structure editor)++ @ViewBuilder+ private func columnNameCell(col: Binding<NewColumn>) -> some View {+ let c = col.wrappedValue+ if selectedColumnId == c.id {+ HStack(spacing: 4) {+ if c.isPrimaryKey {+ Image(systemName: "key.fill").font(.system(size: 9)).foregroundStyle(.yellow)+ }+ TextField("name", text: col.name)+ .textFieldStyle(.squareBorder)+ .fontWeight(c.isPrimaryKey ? .medium : .regular)+ .focused($focusedField, equals: .name(c.id))+ }+ } else {+ HStack(spacing: 4) {+ if c.isPrimaryKey {+ Image(systemName: "key.fill").font(.system(size: 9)).foregroundStyle(.yellow)+ }+ Text(c.name)+ .fontWeight(c.isPrimaryKey ? .medium : .regular)+ .lineLimit(1)+ }+ }+ }++ @ViewBuilder+ private func dataTypeCell(col: Binding<NewColumn>) -> some View {+ let c = col.wrappedValue+ if selectedColumnId == c.id {+ HStack(spacing: 2) {+ TextField("type", text: col.dataType)+ .textFieldStyle(.squareBorder)+ .focused($focusedField, equals: .dataType(c.id))+ Menu {+ ForEach(cachedDataTypes, id: \.self) { t in+ Button(t) { col.wrappedValue.dataType = t }+ }+ } label: {+ Image(systemName: "chevron.down")+ .font(.system(size: 8, weight: .semibold))+ .foregroundStyle(.secondary)+ }+ .menuStyle(.borderlessButton)+ .menuIndicator(.hidden)+ .fixedSize()+ }+ } else {+ Text(c.dataType).lineLimit(1)+ }+ }++ @ViewBuilder+ private func nullableCell(col: Binding<NewColumn>) -> some View {+ let c = col.wrappedValue+ if selectedColumnId == c.id {+ Picker("", selection: col.isNullable) {+ Text("NO").tag(false)+ Text("YES").tag(true)+ }+ .pickerStyle(.menu)+ .labelsHidden()+ .focusable(false)+ } else {+ Text(c.isNullable ? "YES" : "NO")+ .foregroundStyle(c.isNullable ? .primary : .secondary)+ .lineLimit(1)+ }+ }++ @ViewBuilder+ private func fkCell(col: Binding<NewColumn>) -> some View {+ let c = col.wrappedValue+ HStack(spacing: 4) {+ Text(c.foreignKey.isEmpty ? "EMPTY" : c.foreignKey)+ .foregroundStyle(c.foreignKey.isEmpty ? .tertiary : .primary)+ .lineLimit(1)+ Spacer()+ Image(systemName: "arrow.right")+ .font(.system(size: 9))+ .foregroundStyle(.tertiary)+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ .contentShape(Rectangle())+ .pointerCursor()+ .onTapGesture { openFKEditor(c) }+ .popover(isPresented: Binding(+ get: { fkEditColumnId == c.id },+ set: { if !$0 { fkEditColumnId = nil } }+ )) {+ foreignKeyPopover(c)+ }+ }++ @ViewBuilder+ private func defaultCell(col: Binding<NewColumn>) -> some View {+ let c = col.wrappedValue+ HStack(spacing: 4) {+ Text(c.defaultValue.isEmpty ? "NULL" : c.defaultValue)+ .foregroundStyle(c.defaultValue.isEmpty ? .tertiary : .primary)+ .lineLimit(1)+ Image(systemName: "chevron.down")+ .font(.system(size: 8))+ .foregroundStyle(selectedColumnId == c.id ? Color.gray.opacity(0.4) : Color.clear)+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ .contentShape(Rectangle())+ .pointerCursor()+ .onTapGesture { openDefaultEditor(c) }+ .popover(isPresented: Binding(+ get: { defaultEditColumnId == c.id },+ set: { if !$0 { defaultEditColumnId = nil } }+ )) {+ defaultValuePopover(c)+ }+ }++ @ViewBuilder+ private func commentCell(col: Binding<NewColumn>) -> some View {+ let c = col.wrappedValue+ if selectedColumnId == c.id {+ TextField("NULL", text: col.comment)+ .textFieldStyle(.squareBorder)+ .focused($focusedField, equals: .comment(c.id))+ } else {+ Text(c.comment.isEmpty ? "NULL" : c.comment)+ .foregroundStyle(c.comment.isEmpty ? .tertiary : .primary)+ .lineLimit(1)+ }+ }++ // MARK: - Indexes Section (matches Structure editor)++ private var indexesSection: some View {+ VStack(spacing: 0) {+ Rectangle()+ .fill(Color.accentColor.opacity(0.6))+ .frame(height: 2)++ if indexes.isEmpty {+ VStack {+ Text("No indexes")+ .foregroundStyle(.secondary)+ HStack {+ Button { addNewIndex() } label: {+ HStack(spacing: 4) {+ Image(systemName: "plus").font(.system(size: 9))+ Text("New index").font(.system(size: 11))+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 6)+ }+ .buttonStyle(.plain)+ .pointerCursor()+ .foregroundStyle(.tertiary)+ }+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ } else {+ Table($indexes, selection: $selectedIndexId) {+ TableColumn("index_name") { $idx in+ if selectedIndexId == idx.id {+ TextField("name", text: $idx.name)+ .textFieldStyle(.squareBorder)+ } else {+ Text(idx.name).lineLimit(1)+ }+ }++ TableColumn("index_algorithm") { $idx in+ if selectedIndexId == idx.id {+ Picker("", selection: $idx.algorithm) {+ Text("BTREE").tag("BTREE")+ Text("HASH").tag("HASH")+ Text("GIST").tag("GIST")+ Text("SPGIST").tag("SPGIST")+ Text("GIN").tag("GIN")+ Text("BRIN").tag("BRIN")+ }+ .pickerStyle(.menu)+ .labelsHidden()+ } else {+ Text(idx.algorithm).lineLimit(1)+ }+ }.width(120)++ TableColumn("is_unique") { $idx in+ if selectedIndexId == idx.id {+ Picker("", selection: $idx.isUnique) {+ Text("FALSE").tag(false)+ Text("TRUE").tag(true)+ }+ .pickerStyle(.menu)+ .labelsHidden()+ } else {+ Text(idx.isUnique ? "TRUE" : "FALSE")+ .foregroundStyle(idx.isUnique ? .primary : .secondary)+ }+ }.width(80)++ TableColumn("column_name") { $idx in+ if selectedIndexId == idx.id {+ TextField("col1, col2", text: $idx.columns)+ .textFieldStyle(.squareBorder)+ } else {+ Text(idx.columns).lineLimit(1)+ }+ }++ TableColumn("condition") { $idx in+ if selectedIndexId == idx.id {+ TextField("EMPTY", text: $idx.condition)+ .textFieldStyle(.squareBorder)+ } else {+ Text(idx.condition.isEmpty ? "EMPTY" : idx.condition)+ .foregroundStyle(idx.condition.isEmpty ? .tertiary : .secondary)+ .lineLimit(1)+ }+ }++ TableColumn("include") { $idx in+ if selectedIndexId == idx.id {+ TextField("EMPTY", text: $idx.include)+ .textFieldStyle(.squareBorder)+ } else {+ Text(idx.include.isEmpty ? "EMPTY" : idx.include)+ .foregroundStyle(idx.include.isEmpty ? .tertiary : .secondary)+ .lineLimit(1)+ }+ }++ TableColumn("comment") { $idx in+ if selectedIndexId == idx.id {+ TextField("NULL", text: $idx.comment)+ .textFieldStyle(.squareBorder)+ } else {+ Text(idx.comment.isEmpty ? "NULL" : idx.comment)+ .foregroundStyle(idx.comment.isEmpty ? .tertiary : .secondary)+ .lineLimit(1)+ }+ }+ }+ .contextMenu(forSelectionType: UUID.self) { ids in+ if let id = ids.first {+ Button("Delete Index", role: .destructive) {+ indexes.removeAll { $0.id == id }+ }+ }+ } primaryAction: { _ in }+ .environment(\.defaultMinListRowHeight, 34)++ // Inline "+ New index" button+ HStack {+ Button { addNewIndex() } label: {+ HStack(spacing: 4) {+ Image(systemName: "plus").font(.system(size: 9))+ Text("New index").font(.system(size: 11))+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 6)+ }+ .buttonStyle(.plain)+ .pointerCursor()+ .foregroundStyle(.tertiary)+ Spacer()+ }+ .padding(.leading, 8)+ .padding(.top, 4)+ }+ }+ .frame(minHeight: 120)+ }++ // MARK: - Foreign Key Editor++ private func openFKEditor(_ col: NewColumn) {+ // Parse existing "table(col)" format+ let fk = col.foreignKey+ if let parenIdx = fk.firstIndex(of: "(") {+ fkRefTable = String(fk[..<parenIdx])+ let rest = fk[fk.index(after: parenIdx)...]+ fkRefColumn = String(rest.dropLast()) // drop closing ')'+ } else {+ fkRefTable = ""+ fkRefColumn = ""+ }+ fkEditColumnId = col.id+ // Load available tables+ if availableTables.isEmpty, let adapter = appState.activeAdapter {+ Task {+ if let tables = try? await adapter.listTables(schema: schema) {+ availableTables = tables.filter { $0.type == .table }.map(\.name).sorted()+ }+ }+ }+ }++ private func saveForeignKey(_ col: NewColumn) {+ guard let idx = columns.firstIndex(where: { $0.id == col.id }) else { return }+ columns[idx].foreignKey = "\(fkRefTable)(\(fkRefColumn))"+ fkEditColumnId = nil+ }++ private func clearForeignKey(_ col: NewColumn) {+ guard let idx = columns.firstIndex(where: { $0.id == col.id }) else { return }+ columns[idx].foreignKey = ""+ fkEditColumnId = nil+ }++ @ViewBuilder+ private func foreignKeyPopover(_ col: NewColumn) -> some View {+ VStack(spacing: 12) {+ HStack {+ Text("Column").frame(width: 130, alignment: .trailing).foregroundStyle(.secondary)+ Text(col.name)+ .padding(.horizontal, 8).padding(.vertical, 4)+ .background(Color.accentColor.opacity(0.2))+ .cornerRadius(4)+ .frame(maxWidth: .infinity, alignment: .leading)+ }++ HStack {+ Text("Referenced Table").frame(width: 130, alignment: .trailing).foregroundStyle(.secondary)+ Picker("", selection: $fkRefTable) {+ Text("Select a table...").tag("")+ ForEach(availableTables, id: \.self) { t in+ Text(t).tag(t)+ }+ }+ .labelsHidden()+ }++ HStack {+ Text("Referenced Column").frame(width: 130, alignment: .trailing).foregroundStyle(.secondary)+ TextField("Column name...", text: $fkRefColumn)+ .textFieldStyle(.roundedBorder)+ }++ Divider()++ HStack {+ if !col.foreignKey.isEmpty {+ Button("Clear", role: .destructive) { clearForeignKey(col) }+ }+ Spacer()+ Button("Cancel") { fkEditColumnId = nil }+ Button("OK") { saveForeignKey(col) }+ .disabled(fkRefTable.isEmpty || fkRefColumn.isEmpty)+ .buttonStyle(.borderedProminent)+ }+ }+ .padding(16)+ .frame(width: 380)+ }++ // MARK: - Default Value Editor++ private func openDefaultEditor(_ col: NewColumn) {+ let current = col.defaultValue+ if current.contains("(") || current == "CURRENT_TIMESTAMP" || current == "NOW()" ||+ current == "true" || current == "false" || current == "gen_random_uuid()" {+ defaultTab = .expression+ defaultExpressionValue = current+ defaultStringValue = ""+ } else {+ defaultTab = .string+ var str = current+ if str.hasPrefix("'") && str.hasSuffix("'") && str.count >= 2 {+ str = String(str.dropFirst().dropLast())+ }+ defaultStringValue = str+ defaultExpressionValue = ""+ }+ defaultEditColumnId = col.id+ }++ private func saveDefaultValue(_ col: NewColumn) {+ guard let idx = columns.firstIndex(where: { $0.id == col.id }) else { return }+ switch defaultTab {+ case .string:+ columns[idx].defaultValue = defaultStringValue.isEmpty+ ? ""+ : "'\(defaultStringValue.replacingOccurrences(of: "'", with: "''"))'"+ case .expression:+ columns[idx].defaultValue = defaultExpressionValue+ }+ defaultEditColumnId = nil+ }++ @ViewBuilder+ private func defaultValuePopover(_ col: NewColumn) -> some View {+ VStack(spacing: 12) {+ Picker("", selection: $defaultTab) {+ ForEach(DefaultTab.allCases, id: \.self) { tab in+ Text(tab.rawValue).tag(tab)+ }+ }+ .pickerStyle(.segmented)+ .labelsHidden()++ switch defaultTab {+ case .string:+ VStack(alignment: .leading, spacing: 6) {+ Text("String value").font(.caption).foregroundStyle(.secondary)+ TextField("Enter string value...", text: $defaultStringValue)+ .textFieldStyle(.roundedBorder)+ }+ case .expression:+ VStack(alignment: .leading, spacing: 6) {+ Text("SQL expression").font(.caption).foregroundStyle(.secondary)+ TextField("e.g. CURRENT_TIMESTAMP, gen_random_uuid()", text: $defaultExpressionValue)+ .textFieldStyle(.roundedBorder)+ HStack(spacing: 4) {+ ForEach(["CURRENT_TIMESTAMP", "NOW()", "gen_random_uuid()", "true", "false"], id: \.self) { expr in+ Button(expr) { defaultExpressionValue = expr }+ .buttonStyle(.plain)+ .font(.system(size: 10, design: .monospaced))+ .padding(.horizontal, 6)+ .padding(.vertical, 2)+ .background(Color(nsColor: .controlBackgroundColor))+ .cornerRadius(4)+ }+ }+ }+ }++ Divider()++ HStack {+ if !col.defaultValue.isEmpty {+ Button("Clear", role: .destructive) {+ guard let idx = columns.firstIndex(where: { $0.id == col.id }) else { return }+ columns[idx].defaultValue = ""+ defaultEditColumnId = nil+ }+ }+ Spacer()+ Button("Cancel") { defaultEditColumnId = nil }+ Button("OK") { saveDefaultValue(col) }+ .buttonStyle(.borderedProminent)+ }+ }+ .padding(16)+ .frame(width: 360)+ }++ // MARK: - Actions++ private func addNewColumn() {+ let newCol = NewColumn(+ name: "column_\(columns.count + 1)",+ dataType: defaultDataType,+ isPrimaryKey: false,+ isNullable: true,+ defaultValue: ""+ )+ columns.append(newCol)+ selectedColumnId = newCol.id+ }++ private func addNewIndex() {+ let newIdx = NewIndex(+ name: "idx_\(tableName.isEmpty ? "table" : tableName)_\(indexes.count + 1)",+ columns: "",+ isUnique: false+ )+ indexes.append(newIdx)+ selectedIndexId = newIdx.id+ }++ private func togglePrimaryKey(_ id: UUID) {+ if let idx = columns.firstIndex(where: { $0.id == id }) {+ columns[idx].isPrimaryKey.toggle()+ }+ }++ // MARK: - SQL Generation & Execution++ private func createTable() async {+ guard let adapter = appState.activeAdapter else { return }+ isCreating = true+ errorMessage = nil+ defer { isCreating = false }++ // MongoDB: schemaless collection creation+ if let mongo = adapter as? MongoDBAdapter {+ do {+ try await mongo.createCollection(name: tableName)+ } catch {+ errorMessage = "Failed: \(DataGridViewState.detailedErrorMessage(error))"+ return+ }+ let createdName = tableName+ let createTabId = appState.tabs.first(where: {+ $0.type == .createTable && $0.id == appState.activeTabId+ })?.id+ appState.refreshSidebar()+ appState.openTable(name: createdName, schema: schema)+ if let createTabId {+ appState.closeTab(id: createTabId)+ }+ return+ }++ let d = adapter.databaseType.sqlDialect+ let schemaName = schema ?? defaultSchema+ let qualifiedTable = adapter.databaseType == .sqlite+ ? d.quoteIdentifier(tableName)+ : "\(d.quoteIdentifier(schemaName)).\(d.quoteIdentifier(tableName))"++ // Build CREATE TABLE+ var colDefs: [String] = []+ var pkCols: [String] = []++ for col in columns {+ var def = "\(d.quoteIdentifier(col.name)) \(col.dataType)"+ if !col.isNullable { def += " NOT NULL" }+ if !col.defaultValue.isEmpty { def += " DEFAULT \(col.defaultValue)" }+ if !col.checkConstraint.isEmpty { def += " CHECK (\(col.checkConstraint))" }+ colDefs.append(def)+ if col.isPrimaryKey { pkCols.append(d.quoteIdentifier(col.name)) }+ }++ if !pkCols.isEmpty {+ colDefs.append("PRIMARY KEY (\(pkCols.joined(separator: ", ")))")+ }++ // Foreign keys (basic support: "referenced_table(col)")+ for col in columns where !col.foreignKey.isEmpty {+ colDefs.append("FOREIGN KEY (\(d.quoteIdentifier(col.name))) REFERENCES \(col.foreignKey)")+ }++ let createSQL = "CREATE TABLE \(qualifiedTable) (\n \(colDefs.joined(separator: ",\n "))\n)"++ do {+ _ = try await adapter.executeRaw(sql: createSQL)+ } catch {+ errorMessage = "Failed: \(DataGridViewState.detailedErrorMessage(error))"+ return+ }++ // Create indexes+ for idx in indexes where !idx.columns.isEmpty {+ let uniqueStr = idx.isUnique ? "UNIQUE " : ""+ var idxSQL: String+ if adapter.databaseType == .postgresql {+ idxSQL = "CREATE \(uniqueStr)INDEX \(d.quoteIdentifier(idx.name)) ON \(qualifiedTable) USING \(idx.algorithm.lowercased()) (\(idx.columns))"+ } else {+ idxSQL = "CREATE \(uniqueStr)INDEX \(d.quoteIdentifier(idx.name)) ON \(qualifiedTable) (\(idx.columns))"+ }+ if !idx.include.isEmpty && adapter.databaseType == .postgresql {+ idxSQL += " INCLUDE (\(idx.include))"+ }+ if !idx.condition.isEmpty {+ idxSQL += " WHERE \(idx.condition)"+ }+ do {+ _ = try await adapter.executeRaw(sql: idxSQL)+ } catch {+ errorMessage = "Table created, but index failed: \(DataGridViewState.detailedErrorMessage(error))"+ return+ }+ }++ // Add comments (PostgreSQL only)+ if adapter.databaseType == .postgresql {+ for col in columns where !col.comment.isEmpty {+ let commentSQL = "COMMENT ON COLUMN \(qualifiedTable).\(d.quoteIdentifier(col.name)) IS '\(col.comment.replacingOccurrences(of: "'", with: "''"))'"+ _ = try? await adapter.executeRaw(sql: commentSQL)+ }+ }++ // Success — refresh sidebar, close this Create Table tab, open the new table+ let createdName = tableName+ let createTabId = appState.tabs.first(where: {+ $0.type == .createTable && $0.id == appState.activeTabId+ })?.id+ appState.refreshSidebar()+ appState.openTable(name: createdName, schema: schema)+ if let createTabId {+ appState.closeTab(id: createTabId)+ }+ }++ // MARK: - Helpers++ private var defaultDataType: String {+ guard let adapter = appState.activeAdapter else { return "text" }+ switch adapter.databaseType {+ case .postgresql: return "text"+ case .mysql: return "varchar(255)"+ case .sqlite: return "TEXT"+ case .mssql: return "NVARCHAR(255)"+ case .redis: return "string"+ case .mongodb: return "string"+ }+ }++ private func rebuildDataTypes() {+ guard let adapter = appState.activeAdapter else {+ cachedDataTypes = postgresDataTypes+ return+ }+ switch adapter.databaseType {+ case .postgresql: cachedDataTypes = postgresDataTypes+ case .mysql: cachedDataTypes = mysqlDataTypes+ case .sqlite: cachedDataTypes = sqliteDataTypes+ case .mssql: cachedDataTypes = mssqlDataTypes+ case .redis: cachedDataTypes = ["string", "list", "set", "zset", "hash", "stream"]+ case .mongodb: cachedDataTypes = ["string", "integer", "double", "boolean", "date", "objectId", "document", "array"]+ }+ }++ /// SQL Server data types ordered by category (exact numerics → approximate+ /// numerics → date/time → char strings → unicode strings → binary → other).+ /// Modern variants (VARCHAR(MAX), NVARCHAR(MAX), VARBINARY(MAX)) replace+ /// the deprecated TEXT/NTEXT/IMAGE types but those are kept for compatibility.+ /// Source: https://learn.microsoft.com/sql/t-sql/data-types/data-types-transact-sql+ private var mssqlDataTypes: [String] {+ [+ // Exact numerics+ "INT", "BIGINT", "SMALLINT", "TINYINT", "BIT",+ "DECIMAL", "NUMERIC", "MONEY", "SMALLMONEY",+ // Approximate numerics+ "FLOAT", "REAL",+ // Date and time+ "DATE", "TIME", "DATETIME", "DATETIME2", "DATETIMEOFFSET", "SMALLDATETIME",+ // Character strings+ "CHAR", "VARCHAR", "VARCHAR(MAX)", "TEXT",+ // Unicode character strings+ "NCHAR", "NVARCHAR", "NVARCHAR(MAX)", "NTEXT",+ // Binary strings+ "BINARY", "VARBINARY", "VARBINARY(MAX)", "IMAGE",+ // Other+ "UNIQUEIDENTIFIER", "XML", "JSON", "ROWVERSION", "HIERARCHYID",+ "GEOGRAPHY", "GEOMETRY", "SQL_VARIANT",+ ]+ }+}++// MARK: - Models++struct NewColumn: Identifiable {+ let id = UUID()+ var name: String+ var dataType: String+ var isPrimaryKey: Bool+ var isNullable: Bool+ var defaultValue: String+ var comment: String = ""+ var checkConstraint: String = ""+ var foreignKey: String = "" // "referenced_table(referenced_col)"+}++struct NewIndex: Identifiable {+ let id = UUID()+ var name: String+ var columns: String+ var isUnique: Bool+ var algorithm: String = "BTREE"+ var condition: String = ""+ var include: String = ""+ var comment: String = ""+}diff --git a/macos/Presentation/Views/DataGrid/DataGridView.swift b/macos/Presentation/Views/DataGrid/DataGridView.swiftnew file mode 100644index 0000000..b484439--- /dev/null+++ b/macos/Presentation/Views/DataGrid/DataGridView.swift@@ -0,0 +1,3664 @@+// DataGridView.swift+// Gridex+//+// SwiftUI data grid with pagination, inline editing, column resize, and visual diff.+// Styled after professional database GUIs (professional database GUI).++import SwiftUI+import AppKit++enum DataGridViewMode: String {+ case data+ case structure+}++struct DataGridView: View {+ let tableName: String+ let schema: String?+ let tabId: UUID+ var initialViewMode: String?++ @EnvironmentObject private var appState: AppState+ @State private var showDiscardWarning = false+ @State private var viewMode: DataGridViewMode = .data++ var body: some View {+ let viewModel = appState.cachedDataGridState(for: tabId)+ DataGridContentView(+ tableName: tableName,+ schema: schema,+ viewModel: viewModel,+ showDiscardWarning: $showDiscardWarning,+ viewMode: $viewMode+ )+ .onAppear {+ if initialViewMode == "structure" {+ viewMode = .structure+ }+ }+ .onReceive(NotificationCenter.default.publisher(for: .init("switchToStructure"))) { notif in+ if let name = notif.object as? String, name == tableName {+ viewMode = .structure+ }+ }+ }+}++private struct DataGridContentView: View {+ let tableName: String+ let schema: String?+ @ObservedObject var viewModel: DataGridViewState+ @Binding var showDiscardWarning: Bool+ @Binding var viewMode: DataGridViewMode+ @State private var showAddIndex = false+ @EnvironmentObject private var appState: AppState++ var body: some View {+ VStack(spacing: 0) {+ if viewMode == .data {+ // Toolbar+ DataGridToolbar(viewModel: viewModel)++ // Filter bar — Redis uses pattern-based filter, SQL uses column filter+ if viewModel.showFilterBar {+ if appState.activeConfig?.databaseType == .redis {+ RedisFilterBar(+ initialFilter: viewModel.activeFilter,+ onApply: { filter in+ viewModel.activeFilter = filter+ Task { await viewModel.applyFilter() }+ },+ onClear: {+ viewModel.activeFilter = nil+ Task { await viewModel.applyFilter() }+ },+ onDismiss: {+ viewModel.showFilterBar = false+ }+ )+ } else {+ FilterBarSwiftUIView(+ columns: viewModel.columns,+ initialFilter: viewModel.activeFilter,+ onApply: { filter in+ viewModel.activeFilter = filter+ Task { await viewModel.applyFilter() }+ },+ onClear: {+ viewModel.activeFilter = nil+ Task { await viewModel.applyFilter() }+ },+ onDismiss: {+ viewModel.showFilterBar = false+ }+ )+ }+ }++ // Data grid+ if viewModel.isLoading && viewModel.rows.isEmpty {+ ProgressView("Loading...")+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ } else if viewModel.columns.isEmpty {+ Text("No data")+ .foregroundStyle(.secondary)+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ } else {+ AppKitDataGrid(+ viewModel: viewModel,+ onSelectRows: { rows in+ viewModel.editingCell = nil+ viewModel.selectedRows = rows+ updateSelectedRowDetails()+ },+ onFKClick: { refTable, refColumn, value in+ appState.openTableWithFilter(+ name: refTable,+ schema: schema,+ filterColumn: refColumn,+ filterValue: value+ )+ }+ )+ }+ } else {+ // Structure view+ InlineStructureView(+ tableDescription: viewModel.tableDescription,+ isLoading: viewModel.tableDescription == nil && viewModel.isLoading,+ tableName: tableName,+ schema: schema,+ adapter: appState.activeAdapter,+ onStructureChanged: {+ await viewModel.reloadAfterStructureChange()+ return viewModel.tableDescription+ },+ onSelectColumn: { details in+ appState.selectedRowDetails = details+ appState.onDetailFieldEdit = nil+ },+ showAddIndex: $showAddIndex+ )+ }++ // Bottom bar with Data/Structure tabs + pagination+ BottomTabBar(+ viewMode: $viewMode,+ viewModel: viewModel,+ onAddColumn: { NotificationCenter.default.post(name: .init("structureAddColumn"), object: nil) },+ showAddIndex: $showAddIndex+ )++ // Query log panel+ if appState.showQueryLog {+ QueryLogPanel(appState: appState)+ }+ }+ .task {+ viewModel.appState = appState+ // Skip reload if already loaded (cached from previous tab switch)+ guard viewModel.columns.isEmpty else { return }+ await viewModel.load(+ tableName: tableName,+ schema: schema,+ adapter: appState.activeAdapter+ )+ }+ .onChange(of: viewModel.statusRowCount) { _, count in+ appState.statusRowCount = count+ }+ .onChange(of: viewModel.executionTime) { _, time in+ appState.statusQueryTime = time+ }+ .onChange(of: viewModel.sortColumn) { _, _ in+ Task { await viewModel.loadPage(0) }+ }+ .onChange(of: viewModel.sortAscending) { _, _ in+ Task { await viewModel.loadPage(0) }+ }+ .sheet(isPresented: $viewModel.showCommitPreview) {+ CommitPreviewSheet(viewModel: viewModel)+ }+ .alert("Warning", isPresented: $showDiscardWarning) {+ Button("Cancel", role: .cancel) {}+ Button("Discard", role: .destructive) {+ viewModel.discardAllChanges()+ Task { await viewModel.loadPage(viewModel.currentPage) }+ }+ } message: {+ Text("Discard all changes?\nTips: You can commit the changes by\n1. Command + S.\n2. Use the top left segment control.")+ }+ .alert("Error", isPresented: .constant(viewModel.errorMessage != nil)) {+ Button("OK") { viewModel.dismissError() }+ } message: {+ Text(viewModel.errorMessage ?? "")+ }+ // Cmd+S: commit changes+ .onReceive(NotificationCenter.default.publisher(for: .commitChanges)) { _ in+ if viewModel.hasPendingChanges {+ viewModel.prepareCommit()+ }+ }+ // Delete selected rows+ .onReceive(NotificationCenter.default.publisher(for: .deleteSelectedRows)) { _ in+ viewModel.deleteSelectedRows()+ }+ // Cmd+R: reload (with warning if pending changes)+ .onReceive(NotificationCenter.default.publisher(for: .reloadData)) { _ in+ if viewModel.hasPendingChanges {+ showDiscardWarning = true+ } else {+ Task { await viewModel.loadPage(viewModel.currentPage) }+ }+ }+ // Cmd+F: toggle filter bar+ .onReceive(NotificationCenter.default.publisher(for: .toggleFilterBar)) { _ in+ viewModel.showFilterBar.toggle()+ }+ }++ private func updateSelectedRowDetails() {+ guard viewModel.selectedRows.count == 1,+ let rowIndex = viewModel.selectedRows.first,+ rowIndex < viewModel.rows.count else {+ appState.selectedRowDetails = nil+ appState.onDetailFieldEdit = nil+ return+ }+ let row = viewModel.rows[rowIndex]+ appState.selectedRowDetails = viewModel.columns.enumerated().map { idx, col in+ let value = idx < row.count ? row[idx].displayString : ""+ return (column: col.name, value: value)+ }+ appState.onDetailFieldEdit = { [weak viewModel] colIdx, newValue in+ guard let viewModel else { return }+ viewModel.commitCellEdit(rowIndex: rowIndex, colIdx: colIdx, newText: newValue)+ // Update the details panel to reflect the edit+ if colIdx < viewModel.columns.count {+ self.appState.selectedRowDetails?[colIdx].value = newValue+ }+ }+ }++}++// MARK: - DataGrid View State++// MARK: - Query Log Entry++struct QueryLogEntry: Identifiable {+ let id = UUID()+ let sql: String+ let timestamp: Date+ let duration: TimeInterval?+ /// Pre-computed highlighted SQL (with syntax coloring)+ let highlightedColored: AttributedString+ /// Pre-computed highlighted SQL (plain, no coloring)+ let highlightedPlain: AttributedString++ init(sql: String, timestamp: Date, duration: TimeInterval?) {+ self.sql = sql+ self.timestamp = timestamp+ self.duration = duration+ self.highlightedColored = Self.buildHighlightedSQL(sql, colored: true)+ self.highlightedPlain = Self.buildHighlightedSQL(sql, colored: false)+ }++ static func buildHighlightedSQL(_ sql: String, colored: Bool) -> AttributedString {+ let fullStr = sql + ";"+ var result = AttributedString(fullStr)+ result.font = .system(size: 12, design: .monospaced)+ result.foregroundColor = .primary++ guard colored else { return result }++ let keywords = [+ "SELECT", "FROM", "WHERE", "ORDER BY", "LIMIT", "OFFSET",+ "INSERT", "UPDATE", "DELETE", "SET", "INTO", "VALUES",+ "JOIN", "LEFT", "RIGHT", "INNER", "OUTER", "ON",+ "GROUP BY", "HAVING", "AS", "AND", "OR", "NOT", "IN",+ "COUNT", "SUM", "AVG", "MIN", "MAX", "DISTINCT",+ "ASC", "DESC", "NULL", "IS", "LIKE", "BETWEEN",+ "CREATE", "ALTER", "DROP", "TABLE", "INDEX",+ "BEGIN", "COMMIT", "ROLLBACK"+ ]++ let charCount = fullStr.count+ var coloredFlags = [Bool](repeating: false, count: charCount)+ let chars = Array(fullStr.unicodeScalars)+ let upperChars = Array(fullStr.uppercased().unicodeScalars)++ func applyColor(_ color: Color, startOffset: Int, length: Int) {+ let startIdx = result.index(result.startIndex, offsetByCharacters: startOffset)+ let endIdx = result.index(startIdx, offsetByCharacters: length)+ result[startIdx..<endIdx].foregroundColor = color+ for i in startOffset..<min(startOffset + length, charCount) {+ coloredFlags[i] = true+ }+ }++ for keyword in keywords {+ let kwChars = Array(keyword.unicodeScalars)+ let kwLen = kwChars.count+ var i = 0+ while i <= charCount - kwLen {+ var match = true+ for j in 0..<kwLen {+ if upperChars[i + j] != kwChars[j] {+ match = false+ break+ }+ }+ if match {+ let before = i == 0 || !CharacterSet.letters.contains(chars[i - 1])+ let after = (i + kwLen) >= charCount || !CharacterSet.letters.contains(chars[i + kwLen])+ if before && after {+ applyColor(Color(nsColor: .systemBlue), startOffset: i, length: kwLen)+ i += kwLen+ continue+ }+ }+ i += 1+ }+ }++ var i = 0+ while i < charCount {+ if chars[i] == "\"" {+ if let closeIdx = (i + 1..<charCount).first(where: { chars[$0] == "\"" }) {+ let len = closeIdx - i + 1+ applyColor(Color(nsColor: .systemGreen), startOffset: i, length: len)+ i = closeIdx + 1+ continue+ }+ }+ i += 1+ }++ i = 0+ while i < charCount {+ if !coloredFlags[i] && chars[i].properties.numericType != nil {+ var end = i + 1+ while end < charCount && chars[end].properties.numericType != nil { end += 1 }+ let before = i == 0 || !CharacterSet.letters.contains(chars[i - 1])+ let after = end >= charCount || !CharacterSet.letters.contains(chars[end])+ if before && after {+ applyColor(Color(nsColor: .systemOrange), startOffset: i, length: end - i)+ }+ i = end+ } else {+ i += 1+ }+ }++ return result+ }+}++@MainActor+final class DataGridViewState: ObservableObject {+ @Published var columns: [ColumnHeader] = []+ @Published var rows: [[RowValue]] = []+ @Published var totalRows: Int = 0+ @Published var currentPage: Int = 0+ @Published var isLoading = false+ @Published var executionTime: TimeInterval = 0+ @Published var sortColumn: String?+ @Published var sortAscending = true+ @Published var showFilterBar = false+ @Published var activeFilter: FilterExpression?+ @Published var primaryKeyColumns: [String] = []+ @Published var showCommitPreview = false+ @Published var commitSQL: [(sql: String, parameters: [RowValue])] = []+ @Published var commitError: String?+ @Published var isCommitting = false+ @Published var errorMessage: String?+ @Published var tableDescription: TableDescription?++ // Non-published: high-frequency changes that only the coordinator observes via Combine.+ // Removing @Published avoids SwiftUI body re-evaluation on every click/resize/edit.+ var columnWidths: [String: CGFloat] = [:]+ var editingCell: CellID?+ var selectedRows: Set<Int> = []+ var insertedRowIndices: Set<Int> = []++ // Column metadata for UI indicators+ var foreignKeyColumns: [String: String] = [:] // column -> "referenced_table"+ var foreignKeyRefColumns: [String: String] = [:] // column -> "referenced_column"+ var columnDefaults: [String: String] = [:] // column -> default expression+ var columnEnumValues: [String: [String]] = [:] // column -> enum labels (for USER-DEFINED enum types)++ let changeTracker = DefaultChangeTracker()+ let pageSize = 300++ /// Pre-computed display strings for the current page — avoids repeated+ /// `displayString` computation during cell rendering and scrolling.+ var displayCache: [[String]] = []++ func rebuildDisplayCache() {+ displayCache = rows.map { row in+ row.map { $0.displayString }+ }+ }++ func updateDisplayCache(row: Int, col: Int) {+ guard row < displayCache.count, col < displayCache[row].count, row < rows.count, col < rows[row].count else { return }+ displayCache[row][col] = rows[row][col].displayString+ }++ var statusRowCount: Int? { totalRows > 0 ? totalRows : nil }++ private(set) var adapter: (any DatabaseAdapter)?+ private(set) var tableName: String = ""+ private(set) var schema: String?+ weak var appState: AppState?++ // MARK: - Schema metadata cache (survives tab switches)++ private struct TableMetadataCache {+ var primaryKeyColumns: [String]+ var foreignKeyColumns: [String: String]+ var foreignKeyRefColumns: [String: String]+ var columnDefaults: [String: String]+ var columnEnumValues: [String: [String]]+ var estimatedRowCount: Int?+ var tableDescription: TableDescription?+ }++ private static var metadataCache: [String: TableMetadataCache] = [:]++ private var cacheKey: String {+ "\(schema ?? "public").\(tableName)"+ }++ static func clearMetadataCache() {+ metadataCache.removeAll()+ }++ struct CellID: Equatable {+ let row: Int+ let col: Int+ }++ func load(tableName: String, schema: String?, adapter: (any DatabaseAdapter)?) async {+ guard let adapter else { return }+ self.adapter = adapter+ self.tableName = tableName+ self.schema = schema++ isLoading = true++ // Apply cache immediately if available (before any query)+ let hasCachedMeta: Bool+ if let cached = Self.metadataCache[cacheKey] {+ self.primaryKeyColumns = cached.primaryKeyColumns+ self.foreignKeyColumns = cached.foreignKeyColumns+ self.foreignKeyRefColumns = cached.foreignKeyRefColumns+ self.columnDefaults = cached.columnDefaults+ self.columnEnumValues = cached.columnEnumValues+ self.tableDescription = cached.tableDescription+ if let count = cached.estimatedRowCount, count > 0 {+ self.totalRows = count+ }+ hasCachedMeta = true+ } else {+ hasCachedMeta = false+ }++ let schemaFilter = schema ?? "public"+ let d = adapter.databaseType.sqlDialect+ let qualifiedTable = "\(d.quoteIdentifier(schemaFilter)).\(d.quoteIdentifier(tableName))"++ // Fetch rows first, load metadata in background (non-blocking)+ let fetchSQL = buildFetchSQL(orderBy: nil, limit: pageSize, offset: 0)++ // 1. Fetch rows — show data ASAP+ do {+ let start = Date()+ let result = try await adapter.fetchRows(table: tableName, schema: schema, columns: nil, where: activeFilter, orderBy: nil, limit: pageSize, offset: 0)+ let duration = Date().timeIntervalSince(start)+ logQuery(sql: fetchSQL, duration: duration)++ self.columns = result.columns+ self.rows = result.rows+ rebuildDisplayCache()+ if self.totalRows == 0 { self.totalRows = result.rowCount }+ self.executionTime = result.executionTime+ computeColumnWidths(columns: result.columns, rows: result.rows)+ } catch {+ errorMessage = Self.detailedErrorMessage(error)+ isLoading = false+ return+ }++ isLoading = false++ // 2. Load metadata in background (FK icons, structure) — doesn't block row display+ if hasCachedMeta {+ Task {+ if let desc = try? await adapter.describeTable(name: tableName, schema: schema) {+ self.tableDescription = desc+ Self.metadataCache[self.cacheKey]?.tableDescription = desc+ self.objectWillChange.send()+ }+ }+ return+ }++ let start = Date()+ async let descTask = adapter.describeTable(name: tableName, schema: schema)+ async let enumTask: [String: [String]] = {+ guard adapter.databaseType == .postgresql else { return [:] }+ let sql = """+ SELECT a.attname, e.enumlabel+ FROM pg_attribute a+ JOIN pg_class cls ON cls.oid = a.attrelid+ JOIN pg_namespace ns ON ns.oid = cls.relnamespace+ JOIN pg_type t ON t.oid = a.atttypid+ JOIN pg_enum e ON e.enumtypid = t.oid+ WHERE cls.relname = $1 AND ns.nspname = $2+ AND a.attnum > 0 AND NOT a.attisdropped+ ORDER BY a.attname, e.enumsortorder+ """+ guard let result = try? await adapter.executeWithRowValues(sql: sql, parameters: [.string(tableName), .string(schemaFilter)]) else { return [:] }+ var enums: [String: [String]] = [:]+ for row in result.rows {+ if let colName = row[0].stringValue, let label = row[1].stringValue {+ enums[colName, default: []].append(label)+ }+ }+ return enums+ }()++ if let desc = try? await descTask {+ let dur = Date().timeIntervalSince(start)+ self.primaryKeyColumns = desc.columns.filter { $0.isPrimaryKey }.map { $0.name }+ for col in desc.columns {+ if let def = col.defaultValue, !col.isAutoIncrement {+ self.columnDefaults[col.name] = def+ }+ }+ for fk in desc.foreignKeys {+ for (i, col) in fk.columns.enumerated() {+ self.foreignKeyColumns[col] = fk.referencedTable+ if i < fk.referencedColumns.count {+ self.foreignKeyRefColumns[col] = fk.referencedColumns[i]+ }+ }+ }+ if let count = desc.estimatedRowCount, count > 0 {+ self.totalRows = count+ }+ self.tableDescription = desc+ self.logQuery(sql: "-- describeTable(\(qualifiedTable)) → \(desc.columns.count) cols, \(desc.indexes.count) idx, \(desc.foreignKeys.count) fks", duration: dur)+ }++ self.columnEnumValues = await enumTask++ // Save to cache+ Self.metadataCache[self.cacheKey] = TableMetadataCache(+ primaryKeyColumns: self.primaryKeyColumns,+ foreignKeyColumns: self.foreignKeyColumns,+ foreignKeyRefColumns: self.foreignKeyRefColumns,+ columnDefaults: self.columnDefaults,+ columnEnumValues: self.columnEnumValues,+ estimatedRowCount: self.totalRows,+ tableDescription: self.tableDescription+ )+ self.objectWillChange.send()+ }++ func reloadStructure() async {+ guard let adapter else { return }+ do {+ tableDescription = try await adapter.describeTable(name: tableName, schema: schema)+ } catch {+ // Structure reload error — silently ignore+ }+ }++ /// Invalidate cache and reload everything (after structure changes like ADD COLUMN)+ func reloadAfterStructureChange() async {+ Self.metadataCache.removeValue(forKey: cacheKey)+ guard let adapter else { return }+ await load(tableName: tableName, schema: schema, adapter: adapter)+ }++ func loadPage(_ page: Int) async {+ guard let adapter else { return }+ isLoading = true+ defer { isLoading = false }++ do {+ let offset = page * pageSize+ // Use explicit sort if set, otherwise fall back to primary key for stable ordering+ let sort: [QuerySortDescriptor]? = if let col = sortColumn {+ [QuerySortDescriptor(column: col, direction: sortAscending ? .ascending : .descending)]+ } else if let pk = primaryKeyColumns.first {+ [QuerySortDescriptor(column: pk, direction: .ascending)]+ } else {+ nil+ }+ let sql = buildFetchSQL(orderBy: sort, limit: pageSize, offset: offset)+ let start = Date()+ let result = try await adapter.fetchRows(table: tableName, schema: schema, columns: nil, where: activeFilter, orderBy: sort, limit: pageSize, offset: offset)+ let duration = Date().timeIntervalSince(start)+ logQuery(sql: sql, duration: duration)+ self.rows = result.rows+ rebuildDisplayCache()+ self.currentPage = page+ self.executionTime = result.executionTime+ // Update row count when filter is active via a proper COUNT query+ if activeFilter != nil {+ let countSQL = buildCountSQL()+ if let countResult = try? await adapter.executeRaw(sql: countSQL),+ let firstRow = countResult.rows.first,+ let firstVal = firstRow.first {+ switch firstVal {+ case .integer(let n): self.totalRows = Int(n)+ case .string(let s): self.totalRows = Int(s) ?? (result.rows.count + offset)+ default: self.totalRows = result.rows.count + offset+ }+ }+ }+ } catch {+ errorMessage = Self.detailedErrorMessage(error)+ }+ }++ func applyFilter() async {+ await loadPage(0)+ }++ func nextPage() async {+ await loadPage(currentPage + 1)+ }++ func previousPage() async {+ guard currentPage > 0 else { return }+ await loadPage(currentPage - 1)+ }++ func dismissError() {+ errorMessage = nil+ }++ // MARK: - Error Formatting++ static func detailedErrorMessage(_ error: Error) -> String {+ // PSQLError intentionally hides details in String(describing:).+ // String(reflecting:) includes the full debug info (server message, detail, hint).+ let debug = String(reflecting: error)+ let describing = String(describing: error)++ // If reflecting gives us substantially more info than describing, prefer it+ if debug.count > describing.count + 20 {+ return debug+ }+ // If describing is informative enough, use it+ if describing.count > 40, !describing.contains("prevent accidental leakage") {+ return describing+ }+ // Fall back to localizedDescription+ let localized = error.localizedDescription+ if localized.count > 20, !localized.contains("error 1") {+ return localized+ }+ return debug+ }++ // MARK: - Query Log++ private func logQuery(sql: String, duration: TimeInterval?) {+ appState?.logQuery(sql: sql, duration: duration)+ }++ private func buildFetchSQL(orderBy: [QuerySortDescriptor]?, limit: Int, offset: Int) -> String {+ guard let adapter else { return "" }+ let d = adapter.databaseType.sqlDialect+ let schemaPrefix = schema.map { d.quoteIdentifier($0) + "." } ?? ""+ var sql = "SELECT * FROM \(schemaPrefix)\(d.quoteIdentifier(tableName))"+ if let filter = activeFilter {+ sql += " WHERE " + filter.toSQL(dialect: d)+ }+ if let orderBy, !orderBy.isEmpty {+ sql += " ORDER BY " + orderBy.map { $0.toSQL(dialect: d) }.joined(separator: ", ")+ }+ sql += " LIMIT \(limit) OFFSET \(offset)"+ return sql+ }++ private func buildCountSQL() -> String {+ guard let adapter else { return "" }+ let d = adapter.databaseType.sqlDialect+ let schemaPrefix = schema.map { d.quoteIdentifier($0) + "." } ?? ""+ var sql = "SELECT COUNT(*) FROM \(schemaPrefix)\(d.quoteIdentifier(tableName))"+ if let filter = activeFilter {+ sql += " WHERE " + filter.toSQL(dialect: d)+ }+ return sql+ }++ // MARK: - Column Auto-sizing++ private func computeColumnWidths(columns: [ColumnHeader], rows: [[RowValue]]) {+ let font = NSFont.monospacedSystemFont(ofSize: 12, weight: .regular)+ let attrs: [NSAttributedString.Key: Any] = [.font: font]+ let headerFont = NSFont.systemFont(ofSize: 12, weight: .medium)+ let headerAttrs: [NSAttributedString.Key: Any] = [.font: headerFont]++ for (colIdx, col) in columns.enumerated() {+ // Already manually resized? Keep it.+ if columnWidths[col.name] != nil { continue }++ // Measure header+ let headerWidth = (col.name as NSString).size(withAttributes: headerAttrs).width++ // Measure sample of row data (first 50 rows for performance)+ var maxDataWidth: CGFloat = 0+ let sampleCount = min(rows.count, 50)+ for rowIdx in 0..<sampleCount {+ if colIdx < rows[rowIdx].count {+ let raw: String+ if rowIdx < displayCache.count, colIdx < displayCache[rowIdx].count {+ raw = displayCache[rowIdx][colIdx]+ } else {+ raw = rows[rowIdx][colIdx].displayString+ }+ let text = raw.count > 100 ? String(raw.prefix(100)) : raw+ let w = (text as NSString).size(withAttributes: attrs).width+ maxDataWidth = max(maxDataWidth, w)+ }+ }++ let contentWidth = max(headerWidth, maxDataWidth)+ // Add padding (12px each side) and clamp+ let width = min(max(contentWidth + 24, 70), 500)+ columnWidths[col.name] = ceil(width)+ }+ }++ // MARK: - Inline Editing++ func commitCellEdit(rowIndex: Int, colIdx: Int, newText: String) {+ guard colIdx < columns.count, rowIndex < rows.count else { return }+ let col = columns[colIdx]+ let oldValue = rows[rowIndex][colIdx]+ let newValue = parseRowValue(from: newText, oldValue: oldValue)++ guard oldValue != newValue else {+ editingCell = nil+ return+ }++ let pk = buildPrimaryKey(forRow: rowIndex)+ changeTracker.trackEdit(row: rowIndex, column: col.name, oldValue: oldValue, newValue: newValue, primaryKey: pk)+ rows[rowIndex][colIdx] = newValue+ updateDisplayCache(row: rowIndex, col: colIdx)+ editingCell = nil+ }++ func commitDateEdit(rowIndex: Int, colIdx: Int, newValue: RowValue) {+ guard colIdx < columns.count, rowIndex < rows.count else { return }+ let col = columns[colIdx]+ let oldValue = rows[rowIndex][colIdx]+ guard oldValue != newValue else { return }++ if insertedRowIndices.contains(rowIndex) {+ rows[rowIndex][colIdx] = newValue+ } else {+ let pk = buildPrimaryKey(forRow: rowIndex)+ changeTracker.trackEdit(row: rowIndex, column: col.name, oldValue: oldValue, newValue: newValue, primaryKey: pk)+ rows[rowIndex][colIdx] = newValue+ }+ updateDisplayCache(row: rowIndex, col: colIdx)+ editingCell = nil+ }++ private func buildPrimaryKey(forRow rowIndex: Int) -> RowDictionary? {+ guard rowIndex < rows.count else { return nil }++ // Use primary key columns if available+ if !primaryKeyColumns.isEmpty {+ var pk: RowDictionary = [:]+ for pkCol in primaryKeyColumns {+ if let colIdx = columns.firstIndex(where: { $0.name == pkCol }) {+ pk[pkCol] = rows[rowIndex][colIdx]+ }+ }+ if !pk.isEmpty { return pk }+ }++ // Fallback: use only safe-to-compare columns (integer, string, boolean, uuid)+ var safeCols: RowDictionary = [:]+ for (colIdx, col) in columns.enumerated() {+ guard colIdx < rows[rowIndex].count else { continue }+ let value = rows[rowIndex][colIdx]+ switch value {+ case .integer, .string, .boolean, .uuid:+ safeCols[col.name] = value+ case .null, .double, .date, .data, .json, .array:+ continue // Skip types that can cause comparison issues+ }+ }+ return safeCols.isEmpty ? nil : safeCols+ }++ private func parseRowValue(from text: String, oldValue: RowValue) -> RowValue {+ let trimmed = text.trimmingCharacters(in: .whitespaces)+ if trimmed.uppercased() == "NULL" { return .null }++ switch oldValue {+ case .integer:+ if let v = Int64(trimmed) { return .integer(v) }+ case .double:+ if let v = Double(trimmed) { return .double(v) }+ case .boolean:+ let lower = trimmed.lowercased()+ if lower == "true" || lower == "1" { return .boolean(true) }+ if lower == "false" || lower == "0" { return .boolean(false) }+ case .date:+ if let d = Self.parseDate(trimmed) { return .date(d) }+ case .uuid:+ if let u = UUID(uuidString: trimmed) { return .uuid(u) }+ default:+ break+ }+ return .string(trimmed)+ }++ private static let dateFormatters: [DateFormatter] = {+ let formats = [+ "yyyy-MM-dd HH:mm:ss",+ "yyyy-MM-dd",+ "yyyy-MM-dd'T'HH:mm:ss",+ "yyyy-MM-dd'T'HH:mm:ssZ",+ "yyyy-MM-dd HH:mm:ss.SSS",+ "dd/MM/yyyy",+ "MM/dd/yyyy"+ ]+ return formats.map { fmt in+ let f = DateFormatter()+ f.dateFormat = fmt+ f.timeZone = TimeZone(identifier: "UTC")+ f.locale = Locale(identifier: "en_US_POSIX")+ return f+ }+ }()++ private static func parseDate(_ text: String) -> Date? {+ for formatter in dateFormatters {+ if let date = formatter.date(from: text) { return date }+ }+ return nil+ }++ private func parseRowValue(from text: String, columnType: String) -> RowValue {+ let trimmed = text.trimmingCharacters(in: .whitespaces)+ if trimmed.uppercased() == "NULL" { return .null }++ let lower = columnType.lowercased()++ if lower.contains("int") || lower.contains("serial") {+ if let v = Int64(trimmed) { return .integer(v) }+ }+ if lower.contains("float") || lower.contains("double") || lower.contains("real") || lower.contains("numeric") || lower.contains("decimal") {+ if let v = Double(trimmed) { return .double(v) }+ }+ if lower.contains("bool") {+ let l = trimmed.lowercased()+ if l == "true" || l == "1" { return .boolean(true) }+ if l == "false" || l == "0" { return .boolean(false) }+ }+ if lower.contains("date") || lower.contains("time") {+ if let d = Self.parseDate(trimmed) { return .date(d) }+ }+ if lower.contains("uuid") {+ if let u = UUID(uuidString: trimmed) { return .uuid(u) }+ }+ if lower.contains("json") {+ return .json(trimmed)+ }+ return .string(trimmed)+ }++ var hasPendingChanges: Bool {+ changeTracker.hasChanges || !insertedRowIndices.isEmpty+ }++ func discardAllChanges() {+ // Remove inserted rows from end (reverse order to preserve indices)+ for rowIndex in insertedRowIndices.sorted().reversed() {+ if rowIndex < rows.count {+ rows.remove(at: rowIndex)+ if rowIndex < displayCache.count { displayCache.remove(at: rowIndex) }+ totalRows -= 1+ }+ }+ insertedRowIndices.removeAll()+ changeTracker.discardAll()+ rebuildDisplayCache()+ objectWillChange.send()+ }++ // MARK: - Add New Row++ func addNewRow() {+ let newRow: [RowValue] = columns.map { col in+ if let def = defaultValueFor(column: col) {+ return def+ }+ return .null+ }+ let rowIndex = rows.count+ rows.append(newRow)+ displayCache.append(newRow.map { $0.displayString })+ insertedRowIndices.insert(rowIndex)+ totalRows += 1+ objectWillChange.send()+ }++ private func defaultValueFor(column: ColumnHeader) -> RowValue? {+ // Auto-increment / serial columns get NULL (server-generated)+ nil+ }++ func commitNewRowEdit(rowIndex: Int, colIdx: Int, newText: String) {+ guard colIdx < columns.count, rowIndex < rows.count else { return }+ // Always use column dataType for inserted rows to ensure correct binding types+ let newValue = parseRowValue(from: newText, columnType: columns[colIdx].dataType)+ rows[rowIndex][colIdx] = newValue+ updateDisplayCache(row: rowIndex, col: colIdx)+ editingCell = nil+ }++ func buildInsertValues(forRow rowIndex: Int) -> RowDictionary {+ var values: RowDictionary = [:]+ for (colIdx, col) in columns.enumerated() {+ guard colIdx < rows[rowIndex].count else { continue }+ let value = rows[rowIndex][colIdx]+ if case .null = value { continue } // Skip NULL — let DB handle defaults+ values[col.name] = value+ }+ return values+ }++ // MARK: - Delete Rows++ func deleteSelectedRows() {+ guard !selectedRows.isEmpty else { return }+ for rowIndex in selectedRows.sorted().reversed() {+ guard rowIndex < rows.count else { continue }+ // Skip if already marked for deletion+ if changeTracker.pendingChanges.contains(where: { $0.row == rowIndex && $0.editType == .delete }) { continue }+ guard let pk = buildPrimaryKey(forRow: rowIndex) else { continue }+ changeTracker.trackDelete(row: rowIndex, primaryKey: pk)+ }+ objectWillChange.send()+ }++ func undoDeleteRow(_ rowIndex: Int) {+ let changes = changeTracker.pendingChanges+ if let idx = changes.firstIndex(where: { $0.row == rowIndex && $0.editType == .delete }) {+ changeTracker.discardChange(at: idx)+ objectWillChange.send()+ }+ }++ // MARK: - Commit Flow++ func prepareCommit() {+ guard let adapter else { return }++ // MongoDB: skip SQL generation and preview, commit directly+ if adapter.databaseType == .mongodb {+ commitError = nil+ Task { await executeCommit() }+ return+ }++ let dialect = adapter.databaseType.sqlDialect++ // Remove any previously tracked inserts (in case prepareCommit is called again after cancel)+ changeTracker.removeInserts()++ // Track inserts from new rows before generating SQL+ for rowIndex in insertedRowIndices.sorted() {+ let values = buildInsertValues(forRow: rowIndex)+ if !values.isEmpty {+ changeTracker.trackInsert(values: values)+ }+ }++ commitSQL = changeTracker.generateSQL(table: tableName, schema: schema, dialect: dialect)+ commitError = nil+ showCommitPreview = true+ }++ func executeCommit() async {+ guard let adapter else { return }+ isCommitting = true+ commitError = nil++ // MongoDB: use adapter CRUD methods directly (no SQL)+ if adapter.databaseType == .mongodb {+ await executeCommitMongo(adapter: adapter)+ isCommitting = false+ return+ }++ do {+ logQuery(sql: "BEGIN", duration: nil)+ try await adapter.beginTransaction()+ for statement in commitSQL {+ let start = Date()+ _ = try await adapter.executeWithRowValues(sql: statement.sql, parameters: statement.parameters)+ let duration = Date().timeIntervalSince(start)+ let paramDesc = statement.parameters.isEmpty ? "" : " -- params: \(statement.parameters.map(\.description).joined(separator: ", "))"+ logQuery(sql: statement.sql + paramDesc, duration: duration)+ }+ try await adapter.commitTransaction()+ logQuery(sql: "COMMIT", duration: nil)++ changeTracker.discardAll()+ insertedRowIndices.removeAll()+ showCommitPreview = false+ // Reload to get server-generated values (serials, defaults, triggers)+ await loadPage(currentPage)+ } catch {+ try? await adapter.rollbackTransaction()+ logQuery(sql: "ROLLBACK", duration: nil)+ commitError = Self.detailedErrorMessage(error)+ }++ isCommitting = false+ }++ /// MongoDB-specific commit: applies pending changes via insertRow/updateRow/deleteRow+ /// instead of generating SQL.+ private func executeCommitMongo(adapter: any DatabaseAdapter) async {+ do {+ // Inserts (new rows)+ for rowIndex in insertedRowIndices.sorted() {+ let values = buildInsertValues(forRow: rowIndex)+ guard !values.isEmpty else { continue }+ _ = try await adapter.insertRow(table: tableName, schema: nil, values: values)+ }++ // Updates and deletes from change tracker+ // Group edits by row to issue one updateOne per modified document+ var updatesByRow: [Int: [String: RowValue]] = [:]+ var deletes: Set<Int> = []+ for change in changeTracker.pendingChanges {+ switch change.editType {+ case .update:+ if let col = change.column {+ var rowSet = updatesByRow[change.row] ?? [:]+ rowSet[col] = change.newValue+ updatesByRow[change.row] = rowSet+ }+ case .delete:+ deletes.insert(change.row)+ case .insert:+ break // handled above via insertedRowIndices+ }+ }++ for (rowIndex, setValues) in updatesByRow {+ guard let pk = buildPrimaryKey(forRow: rowIndex) else { continue }+ _ = try await adapter.updateRow(table: tableName, schema: nil, set: setValues, where: pk)+ }++ for rowIndex in deletes {+ guard let pk = buildPrimaryKey(forRow: rowIndex) else { continue }+ _ = try await adapter.deleteRow(table: tableName, schema: nil, where: pk)+ }++ changeTracker.discardAll()+ insertedRowIndices.removeAll()+ showCommitPreview = false+ await loadPage(currentPage)+ } catch {+ commitError = Self.detailedErrorMessage(error)+ }+ }+}++// MARK: - Header++struct DataGridHeader: View {+ let columns: [ColumnHeader]+ @Binding var columnWidths: [String: CGFloat]+ @Binding var sortColumn: String?+ @Binding var sortAscending: Bool++ var body: some View {+ HStack(spacing: 0) {+ ForEach(Array(columns.enumerated()), id: \.1.name) { idx, col in+ let colWidth = columnWidths[col.name] ?? 120++ ZStack(alignment: .trailing) {+ // Column label — entire cell is clickable for sort+ HStack(spacing: 4) {+ Text(col.name)+ .font(.system(size: 12, weight: .medium, design: .monospaced))+ .lineLimit(1)+ .foregroundStyle(.secondary)+ if sortColumn == col.name {+ Image(systemName: sortAscending ? "chevron.up" : "chevron.down")+ .font(.system(size: 8, weight: .semibold))+ .foregroundStyle(.secondary)+ }+ Spacer(minLength: 0)+ }+ .padding(.horizontal, 8)+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ .contentShape(Rectangle())+ .onTapGesture {+ if sortColumn == col.name {+ sortAscending.toggle()+ } else {+ sortColumn = col.name+ sortAscending = true+ }+ }++ // Resize handle + separator on right edge+ Rectangle()+ .fill(Color(nsColor: .separatorColor).opacity(0.5))+ .frame(width: 1)+ .padding(.vertical, 4)+ .overlay {+ Color.clear+ .frame(width: 8)+ .contentShape(Rectangle())+ .onHover { hovering in+ if hovering { NSCursor.resizeLeftRight.push() }+ else { NSCursor.pop() }+ }+ .gesture(+ DragGesture(minimumDistance: 1)+ .onChanged { value in+ let newWidth = max(50, colWidth + value.translation.width)+ columnWidths[col.name] = round(newWidth)+ }+ )+ }+ }+ .frame(width: colWidth)+ }++ Spacer(minLength: 0)+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ .frame(height: 28)+ .background(Color(nsColor: .windowBackgroundColor))+ .overlay(alignment: .bottom) {+ Rectangle().fill(Color(nsColor: .separatorColor)).frame(height: 1)+ }+ }+}++// MARK: - Row++struct DataGridRow: View {+ let rowIndex: Int+ let row: [RowValue]+ let columns: [ColumnHeader]+ let columnWidths: [String: CGFloat]+ let pageOffset: Int+ let isDeleted: Bool+ let modifiedColumns: Set<String>+ let primaryKeyColumns: [String]+ let isSelected: Bool+ @Binding var editingCell: DataGridViewState.CellID?+ let onSelectRow: (_ extend: Bool) -> Void+ let onCellEdit: (Int, String) -> Void+ @State private var lastClickedCol: Int = -1+ @State private var lastClickTime: Date = .distantPast++ private static let cellFont = NSFont.monospacedSystemFont(ofSize: 12, weight: .regular)+ private static let separatorColor = Color(nsColor: .separatorColor)+ private static let altRowColor = Color(nsColor: .alternatingContentBackgroundColors.last ?? .controlBackgroundColor)+ private static let bgColor = Color(nsColor: .textBackgroundColor)++ var body: some View {+ let editingRow = editingCell?.row == rowIndex+ HStack(spacing: 0) {+ ForEach(0..<columns.count, id: \.self) { colIdx in+ let col = columns[colIdx]+ let value = colIdx < row.count ? row[colIdx] : .null+ let colWidth = columnWidths[col.name] ?? 120++ if editingRow && editingCell?.col == colIdx {+ CellTextField(+ initialValue: value.isNull ? "" : value.description,+ onCommit: { newText in onCellEdit(colIdx, newText) },+ onCancel: { editingCell = nil }+ )+ .frame(width: colWidth, height: 26)+ } else {+ cellText(value: value, isModified: modifiedColumns.contains(col.name))+ .frame(width: colWidth, height: 26)+ .overlay(alignment: .trailing) {+ Self.separatorColor.opacity(0.3).frame(width: 1)+ }+ }+ }++ Spacer(minLength: 0)+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(rowBackground)+ .contentShape(Rectangle())+ .onTapGesture(count: 1) {+ handleClick(colIdx: nil, shiftKey: NSEvent.modifierFlags.contains(.shift))+ }+ .overlay(alignment: .bottom) {+ Self.separatorColor.opacity(0.15).frame(height: 1)+ }+ .contextMenu {+ Button("Copy Row") {+ let text = row.map { $0.isNull ? "NULL" : $0.description }.joined(separator: "\t")+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(text, forType: .string)+ }+ }+ }++ private func cellText(value: RowValue, isModified: Bool) -> some View {+ Text(value.isNull ? "NULL" : value.displayString)+ .font(.system(size: 12, design: .monospaced))+ .foregroundStyle(value.isNull ? Color.Gridex.cellNull : .primary)+ .italic(value.isNull)+ .lineLimit(1)+ .padding(.horizontal, 8)+ .frame(maxWidth: .infinity, alignment: value.isNumeric ? .trailing : .leading)+ .background(isModified ? Color.Gridex.cellModified : .clear)+ }++ private func handleClick(colIdx: Int?, shiftKey: Bool) {+ let now = Date()+ if let col = colIdx, lastClickedCol == col && now.timeIntervalSince(lastClickTime) < 0.3 {+ editingCell = DataGridViewState.CellID(row: rowIndex, col: col)+ lastClickTime = .distantPast+ } else {+ onSelectRow(shiftKey)+ lastClickedCol = colIdx ?? -1+ lastClickTime = now+ }+ }++ private var rowBackground: Color {+ if isDeleted { return Color.Gridex.cellDeleted }+ if isSelected { return Color.accentColor.opacity(0.18) }+ return rowIndex.isMultiple(of: 2) ? Self.bgColor : Self.altRowColor+ }+}++// MARK: - Cell TextField (for inline editing)++struct CellTextField: NSViewRepresentable {+ let initialValue: String+ let onCommit: (String) -> Void+ let onCancel: () -> Void++ func makeNSView(context: Context) -> NSTextField {+ let field = NSTextField(string: initialValue)+ field.font = NSFont.monospacedSystemFont(ofSize: 12, weight: .regular)+ field.isBordered = true+ field.bezelStyle = .squareBezel+ field.focusRingType = .none+ field.delegate = context.coordinator+ DispatchQueue.main.async { field.selectText(nil) }+ return field+ }++ func updateNSView(_ nsView: NSTextField, context: Context) {}++ func makeCoordinator() -> Coordinator {+ Coordinator(onCommit: onCommit, onCancel: onCancel)+ }++ class Coordinator: NSObject, NSTextFieldDelegate {+ let onCommit: (String) -> Void+ let onCancel: () -> Void++ init(onCommit: @escaping (String) -> Void, onCancel: @escaping () -> Void) {+ self.onCommit = onCommit+ self.onCancel = onCancel+ }++ func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {+ if commandSelector == #selector(NSResponder.insertNewline(_:)) {+ onCommit(control.stringValue)+ return true+ } else if commandSelector == #selector(NSResponder.insertTab(_:)) {+ onCommit(control.stringValue)+ return true+ } else if commandSelector == #selector(NSResponder.cancelOperation(_:)) {+ onCancel()+ return true+ }+ return false+ }++ func controlTextDidEndEditing(_ obj: Notification) {+ guard let field = obj.object as? NSTextField else { return }+ onCommit(field.stringValue)+ }+ }+}++// MARK: - Toolbar++struct DataGridToolbar: View {+ @ObservedObject var viewModel: DataGridViewState+ @EnvironmentObject private var appState: AppState+ @State private var showInsertDocSheet = false++ private var isMongoDB: Bool {+ appState.activeAdapter?.databaseType == .mongodb+ }++ var body: some View {+ HStack(spacing: 12) {+ // MongoDB: Insert document button+ if isMongoDB {+ Button {+ showInsertDocSheet = true+ } label: {+ HStack(spacing: 4) {+ Image(systemName: "plus.circle")+ .font(.system(size: 11))+ Text("Insert Document")+ .font(.system(size: 11, weight: .medium))+ }+ }+ .buttonStyle(.plain)+ .foregroundStyle(.green)+ .help("Insert a JSON document into this collection")+ .sheet(isPresented: $showInsertDocSheet) {+ insertDocumentSheet+ }+ }++ // Pending changes indicator+ if viewModel.hasPendingChanges {+ HStack(spacing: 6) {+ Circle()+ .fill(.orange)+ .frame(width: 6, height: 6)+ Text("\(viewModel.changeTracker.pendingChanges.count + viewModel.insertedRowIndices.count) pending")+ .font(.system(size: 11))+ .foregroundStyle(.orange)+ }++ Button {+ viewModel.discardAllChanges()+ } label: {+ HStack(spacing: 3) {+ Image(systemName: "arrow.uturn.backward")+ .font(.system(size: 10))+ Text("Discard")+ .font(.system(size: 11))+ }+ }+ .buttonStyle(.plain)+ .foregroundStyle(.secondary)++ Button {+ viewModel.prepareCommit()+ } label: {+ HStack(spacing: 3) {+ Image(systemName: "checkmark.circle.fill")+ .font(.system(size: 10))+ Text("Commit")+ .font(.system(size: 11, weight: .medium))+ }+ }+ .buttonStyle(.plain)+ .foregroundStyle(Color.accentColor)+ }++ Spacer()++ // Reload button+ Button {+ NotificationCenter.default.post(name: .reloadData, object: nil)+ } label: {+ Image(systemName: "arrow.clockwise")+ .font(.system(size: 11))+ }+ .buttonStyle(.plain)+ .foregroundStyle(.secondary)+ .help("Reload (⌘R)")+ }+ .padding(.horizontal, 12)+ .padding(.vertical, 5)+ .frame(height: 28)+ .background(Color(nsColor: .windowBackgroundColor))+ .overlay(alignment: .bottom) { Divider() }+ }++ @ViewBuilder+ private var insertDocumentSheet: some View {+ let fields: [(name: String, type: String)] = viewModel.columns.map { col in+ (name: col.name, type: col.dataType)+ }+ MongoDocumentEditorSheet(+ collectionName: viewModel.tableName,+ detectedFields: fields,+ onInsert: { jsonText in+ guard let mongo = appState.activeAdapter as? MongoDBAdapter else {+ return .failure(GridexError.queryExecutionFailed("Not connected to MongoDB"))+ }+ do {+ try await mongo.insertJSONDocument(into: viewModel.tableName, json: jsonText)+ await viewModel.loadPage(viewModel.currentPage)+ return .success(())+ } catch {+ return .failure(error)+ }+ }+ )+ }+}++// MARK: - Bottom Tab Bar (Data | Structure + Pagination)++struct BottomTabBar: View {+ @Binding var viewMode: DataGridViewMode+ @ObservedObject var viewModel: DataGridViewState+ var onAddColumn: (() -> Void)?+ @Binding var showAddIndex: Bool+ @EnvironmentObject private var appState: AppState++ var body: some View {+ HStack(spacing: 0) {+ // Left: Data / Structure tabs (Structure hidden for Redis)+ HStack(spacing: 0) {+ tabButton("Data", mode: .data)+ if appState.activeConfig?.databaseType != .redis {+ tabButton("Structure", mode: .structure)+ }+ }+ .background(Color(nsColor: .controlBackgroundColor))+ .clipShape(RoundedRectangle(cornerRadius: 5))+ .overlay(RoundedRectangle(cornerRadius: 5).stroke(Color(nsColor: .separatorColor), lineWidth: 0.5))++ Spacer().frame(width: 8)++ if viewMode == .data {+ // + Row / + Key button+ if appState.activeConfig?.databaseType == .redis {+ Button {+ appState.showRedisAddKey = true+ } label: {+ HStack(spacing: 3) {+ Image(systemName: "plus")+ .font(.system(size: 10, weight: .medium))+ Text("Key")+ .font(.system(size: 12))+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 4)+ .background(Color(nsColor: .controlBackgroundColor))+ .clipShape(RoundedRectangle(cornerRadius: 5))+ .overlay(RoundedRectangle(cornerRadius: 5).stroke(Color(nsColor: .separatorColor), lineWidth: 0.5))+ }+ .buttonStyle(.plain)+ .pointerCursor()+ .help("Add new Redis key")+ } else {+ Button {+ viewModel.addNewRow()+ } label: {+ HStack(spacing: 3) {+ Image(systemName: "plus")+ .font(.system(size: 10, weight: .medium))+ Text("Row")+ .font(.system(size: 12))+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 4)+ .background(Color(nsColor: .controlBackgroundColor))+ .clipShape(RoundedRectangle(cornerRadius: 5))+ .overlay(RoundedRectangle(cornerRadius: 5).stroke(Color(nsColor: .separatorColor), lineWidth: 0.5))+ }+ .buttonStyle(.plain)+ .pointerCursor()+ .help("Add new row")+ }+ } else if viewMode == .structure {+ // + Column / + Index buttons+ Button { onAddColumn?() } label: {+ HStack(spacing: 3) {+ Image(systemName: "plus").font(.system(size: 10, weight: .medium))+ Text("Column").font(.system(size: 12))+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 4)+ .background(Color(nsColor: .controlBackgroundColor))+ .clipShape(RoundedRectangle(cornerRadius: 5))+ .overlay(RoundedRectangle(cornerRadius: 5).stroke(Color(nsColor: .separatorColor), lineWidth: 0.5))+ }+ .buttonStyle(.plain)+ .pointerCursor()+ .help("Add column")++ Spacer().frame(width: 6)++ Button { showAddIndex = true } label: {+ HStack(spacing: 3) {+ Image(systemName: "plus").font(.system(size: 10, weight: .medium))+ Text("Index").font(.system(size: 12))+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 4)+ .background(Color(nsColor: .controlBackgroundColor))+ .clipShape(RoundedRectangle(cornerRadius: 5))+ .overlay(RoundedRectangle(cornerRadius: 5).stroke(Color(nsColor: .separatorColor), lineWidth: 0.5))+ }+ .buttonStyle(.plain)+ .pointerCursor()+ .help("Add index")+ }++ Spacer().frame(width: 16)++ // Row count+ if viewMode == .data {+ Text(pageText)+ .font(.system(size: 12))+ .foregroundStyle(.secondary)+ }++ Spacer()++ if viewMode == .data {+ HStack(spacing: 8) {+ // Pending changes+ if viewModel.hasPendingChanges {+ Text("\(viewModel.changeTracker.pendingChanges.count + viewModel.insertedRowIndices.count) pending")+ .font(.system(size: 12))+ .foregroundStyle(.orange)++ Button("Discard") {+ viewModel.discardAllChanges()+ }+ .controlSize(.small)++ Button("Commit") {+ viewModel.prepareCommit()+ }+ .controlSize(.small)+ .buttonStyle(.borderedProminent)+ }++ // Filters toggle+ Button {+ viewModel.showFilterBar.toggle()+ } label: {+ HStack(spacing: 3) {+ Image(systemName: "line.3.horizontal.decrease")+ .font(.system(size: 10, weight: .medium))+ Text("Filters")+ .font(.system(size: 12))+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 4)+ .background(viewModel.showFilterBar+ ? Color.accentColor.opacity(0.2)+ : Color(nsColor: .controlBackgroundColor))+ .clipShape(RoundedRectangle(cornerRadius: 5))+ .overlay(+ RoundedRectangle(cornerRadius: 5)+ .stroke(viewModel.showFilterBar+ ? Color.accentColor+ : Color(nsColor: .separatorColor), lineWidth: 0.5)+ )+ }+ .buttonStyle(.plain)+ .pointerCursor()+ .foregroundStyle(viewModel.showFilterBar ? Color.accentColor : .secondary)+ .help("Toggle filters (⌘F)")++ // Pagination+ Button {+ Task { await viewModel.previousPage() }+ } label: {+ Image(systemName: "chevron.left")+ .font(.system(size: 11))+ }+ .buttonStyle(.plain)+ .pointerCursor()+ .foregroundStyle(.secondary)+ .disabled(viewModel.currentPage == 0)++ Button {+ Task { await viewModel.nextPage() }+ } label: {+ Image(systemName: "chevron.right")+ .font(.system(size: 11))+ }+ .buttonStyle(.plain)+ .pointerCursor()+ .foregroundStyle(.secondary)+ .disabled(viewModel.rows.count < viewModel.pageSize)+ }+ }++ // SQL Log toggle+ Spacer().frame(width: 8)+ Button {+ withAnimation(.easeInOut(duration: 0.15)) {+ appState.showQueryLog.toggle()+ }+ } label: {+ Image(systemName: "rectangle.bottomhalf.filled")+ .font(.system(size: 13))+ .padding(4)+ .background(+ appState.showQueryLog+ ? Color.accentColor.opacity(0.2)+ : Color.clear+ )+ .clipShape(RoundedRectangle(cornerRadius: 4))+ .overlay(+ RoundedRectangle(cornerRadius: 4)+ .stroke(appState.showQueryLog ? Color.accentColor : Color.clear, lineWidth: 0.5)+ )+ }+ .buttonStyle(.plain)+ .pointerCursor()+ .foregroundStyle(appState.showQueryLog ? Color.accentColor : .secondary)+ .help("Toggle SQL Log")+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 5)+ .frame(height: 34)+ .background(Color(nsColor: .windowBackgroundColor))+ .overlay(alignment: .top) { Divider() }+ }++ private func tabButton(_ title: String, mode: DataGridViewMode) -> some View {+ Button(action: { viewMode = mode }) {+ Text(title)+ .font(.system(size: 12, weight: viewMode == mode ? .medium : .regular))+ .foregroundStyle(viewMode == mode ? .primary : .secondary)+ .padding(.horizontal, 12)+ .padding(.vertical, 4)+ .background(viewMode == mode ? Color(nsColor: .selectedContentBackgroundColor).opacity(0.3) : .clear)+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .pointerCursor()+ }++ private var pageText: String {+ guard !viewModel.rows.isEmpty else { return "No rows" }+ let start = viewModel.currentPage * viewModel.pageSize + 1+ let end = min(start + viewModel.rows.count - 1, viewModel.totalRows)+ return "\(start)–\(end) of \(viewModel.totalRows) rows"+ }+}++// MARK: - ComboBox (NSComboBox wrapper — editable text + dropdown)++private struct ComboBoxView: NSViewRepresentable {+ @Binding var text: String+ var items: [String]+ var onChange: ((String) -> Void)?++ func makeNSView(context: Context) -> NSComboBox {+ let combo = NSComboBox()+ combo.isEditable = true+ combo.completes = true+ combo.hasVerticalScroller = true+ combo.numberOfVisibleItems = 12+ combo.usesDataSource = false+ combo.font = .systemFont(ofSize: 12)+ combo.isBordered = true+ combo.isBezeled = true+ combo.bezelStyle = .roundedBezel+ combo.delegate = context.coordinator+ combo.target = context.coordinator+ combo.action = #selector(Coordinator.comboBoxAction(_:))+ return combo+ }++ func updateNSView(_ combo: NSComboBox, context: Context) {+ combo.removeAllItems()+ combo.addItems(withObjectValues: items)+ if combo.stringValue != text {+ combo.stringValue = text+ }+ context.coordinator.parent = self+ }++ func makeCoordinator() -> Coordinator { Coordinator(parent: self) }++ class Coordinator: NSObject, NSComboBoxDelegate {+ var parent: ComboBoxView+ init(parent: ComboBoxView) { self.parent = parent }++ @objc func comboBoxAction(_ sender: NSComboBox) {+ let newVal = sender.stringValue+ if parent.text != newVal {+ parent.text = newVal+ parent.onChange?(newVal)+ }+ }++ func comboBoxSelectionDidChange(_ notification: Notification) {+ guard let combo = notification.object as? NSComboBox,+ combo.indexOfSelectedItem >= 0,+ let val = combo.objectValueOfSelectedItem as? String else { return }+ DispatchQueue.main.async {+ if self.parent.text != val {+ self.parent.text = val+ self.parent.onChange?(val)+ }+ }+ }++ func controlTextDidEndEditing(_ obj: Notification) {+ guard let combo = obj.object as? NSComboBox else { return }+ let newVal = combo.stringValue+ if parent.text != newVal {+ parent.text = newVal+ parent.onChange?(newVal)+ }+ }+ }+}++// MARK: - Inline Structure View++// MARK: - Common Data Types (canonical names from format_type())++let postgresDataTypes = [+ "bool", "bytea", "char", "varchar",+ "int2", "int4", "int8", "serial", "bigserial", "smallserial",+ "float4", "float8", "numeric", "date",+ "time", "timetz", "timestamp", "timestamptz",+ "interval", "text", "json", "jsonb", "uuid", "xml"+]++let mysqlDataTypes = [+ "tinyint", "smallint", "int", "bigint", "float", "double",+ "decimal", "char", "varchar", "text", "mediumtext", "longtext",+ "date", "datetime", "timestamp", "time", "year",+ "blob", "json", "enum", "set", "bool"+]++let sqliteDataTypes = [+ "INTEGER", "REAL", "TEXT", "BLOB", "NUMERIC"+]++struct InlineStructureView: View {+ let tableDescription: TableDescription?+ let isLoading: Bool+ let tableName: String+ let schema: String?+ let adapter: (any DatabaseAdapter)?+ var onStructureChanged: (() async -> TableDescription?)?+ var onSelectColumn: ((_ details: [(column: String, value: String)]?) -> Void)?+ @Binding var showAddIndex: Bool++ enum ColumnField: Hashable {+ case name(UUID)+ case dataType(UUID)+ case comment(UUID)+ }++ @State private var editableColumns: [EditableColumn] = []+ @State private var columnIndexMap: [UUID: Int] = [:]+ @State private var selectedColumnId: EditableColumn.ID?+ @FocusState private var focusedColumnField: ColumnField?+ @State private var pendingChanges: [StructureChange] = []+ @State private var isApplying = false+ @State private var tableGeneration: Int = 0 // Force table recreation after apply+ @State private var cachedDataTypes: [String] = []+ @State private var errorMessage: String?+ @State private var showDeleteConfirm = false+ @State private var columnToDelete: EditableColumn?+ @State private var searchText: String = ""+ @State private var editableIndexes: [EditableIndex] = []+ @State private var selectedIndexId: EditableIndex.ID?+ @State private var fkEditColumnId: UUID? = nil+ @State private var fkRefTable: String = ""+ @State private var fkRefColumn: String = ""+ @State private var fkOnUpdate: ForeignKeyAction = .noAction+ @State private var fkOnDelete: ForeignKeyAction = .noAction+ @State private var availableTables: [String] = []+ @State private var newIndexName: String = ""+ @State private var newIndexColumns: String = ""+ @State private var newIndexAlgorithm: String = "BTREE"+ @State private var newIndexIsUnique: Bool = false+ @State private var newIndexCondition: String = ""++ // Default value editor+ @State private var defaultEditColumnId: UUID? = nil+ @State private var defaultTab: DefaultValueTab = .string+ @State private var defaultStringValue: String = ""+ @State private var defaultExpressionValue: String = ""+ @State private var defaultSequenceName: String = ""+ @State private var defaultCreateSequence: Bool = false++ enum DefaultValueTab: String, CaseIterable {+ case string = "String"+ case expression = "Expression"+ case sequence = "Sequence"+ }++ struct EditableColumn: Identifiable {+ let id = UUID()+ var originalName: String? // nil = new column+ var name: String+ var dataType: String+ var isNullable: Bool+ var defaultValue: String+ var comment: String+ var isPrimaryKey: Bool+ var foreignKeyDisplay: String // read-only display+ var checkConstraint: String // read-only display+ var isMarkedForDeletion: Bool = false+ // FK details+ var fkConstraintName: String = ""+ var fkReferencedTable: String = ""+ var fkReferencedColumn: String = ""+ var fkOnUpdate: ForeignKeyAction = .noAction+ var fkOnDelete: ForeignKeyAction = .noAction+ var hasForeignKey: Bool { !fkReferencedTable.isEmpty }+ var isNew: Bool { originalName == nil }+ }++ struct EditableIndex: Identifiable {+ let id = UUID()+ var originalName: String? // nil = new index+ var name: String+ var algorithm: String+ var isUnique: Bool+ var columns: String // comma-separated+ var condition: String+ var include: String+ var comment: String+ var isMarkedForDeletion: Bool = false+ var isNew: Bool { originalName == nil }+ }++ enum StructureChange {+ case addColumn(name: String, dataType: String, nullable: Bool, defaultValue: String?)+ case renameColumn(oldName: String, newName: String)+ case changeType(column: String, newType: String)+ case setNullable(column: String, nullable: Bool)+ case setDefault(column: String, value: String?)+ case setComment(column: String, comment: String?)+ case dropColumn(name: String)+ case addForeignKey(column: String, refTable: String, refColumn: String, onUpdate: ForeignKeyAction, onDelete: ForeignKeyAction)+ case dropForeignKey(constraintName: String)+ case addIndex(name: String, columns: [String], algorithm: String, isUnique: Bool, condition: String?)+ case dropIndex(name: String)+ case modifyIndex(oldName: String, newName: String, columns: [String], algorithm: String, isUnique: Bool, condition: String?)+ case setIndexComment(name: String, comment: String?)+ case createSequence(name: String) // raw SQL for CREATE SEQUENCE+ }++ private var primaryKeyName: String {+ editableColumns.first(where: { $0.isPrimaryKey })?.name ?? ""+ }++ private var filteredColumns: [EditableColumn] {+ guard !searchText.isEmpty else { return editableColumns }+ return editableColumns.filter { $0.name.localizedCaseInsensitiveContains(searchText) }+ }++ /// Full-bleed row background — extends beyond cell bounds with negative padding+ /// NSViewRepresentable that walks up to find NSTableRowView and sets its background color+ struct RowBackgroundSetter: NSViewRepresentable {+ let color: NSColor?++ final class RowBGView: NSView {+ var targetColor: NSColor?++ override func layout() {+ super.layout()+ applyColor()+ }++ override func viewDidMoveToSuperview() {+ super.viewDidMoveToSuperview()+ DispatchQueue.main.async { [weak self] in+ self?.applyColor()+ }+ }++ func applyColor() {+ var current: NSView? = superview+ while let view = current {+ if let rowView = view as? NSTableRowView {+ if let targetColor {+ rowView.backgroundColor = targetColor+ } else {+ let row = rowIndex(of: rowView)+ let colors = NSColor.alternatingContentBackgroundColors+ rowView.backgroundColor = colors[row % colors.count]+ }+ return+ }+ current = view.superview+ }+ }++ private func rowIndex(of rowView: NSTableRowView) -> Int {+ // Walk up to find NSTableView and get the row index+ var current: NSView? = rowView.superview+ while let view = current {+ if let tableView = view as? NSTableView {+ return tableView.row(for: rowView)+ }+ current = view.superview+ }+ return 0+ }+ }++ func makeNSView(context: Context) -> RowBGView {+ let view = RowBGView()+ view.targetColor = color+ return view+ }++ func updateNSView(_ nsView: RowBGView, context: Context) {+ nsView.targetColor = color+ nsView.applyColor()+ DispatchQueue.main.async {+ nsView.applyColor()+ }+ }+ }++ enum RowChangeState {+ case none, new, deleted, edited+ var color: Color {+ switch self {+ case .none: return .primary+ case .new: return .green+ case .deleted: return .red+ case .edited: return .orange+ }+ }+ var nsColor: NSColor? {+ switch self {+ case .none: return nil+ case .new: return NSColor.systemGreen.withAlphaComponent(0.25)+ case .deleted: return NSColor.systemRed.withAlphaComponent(0.3)+ case .edited: return NSColor.systemOrange.withAlphaComponent(0.25)+ }+ }+ }++ private func columnChangeState(_ col: EditableColumn) -> RowChangeState {+ if col.isMarkedForDeletion { return .deleted }+ if col.isNew { return .new }+ guard let origName = col.originalName else { return .none }+ let hasChange = pendingChanges.contains { change in+ switch change {+ case .renameColumn(let old, _): return old == origName+ case .changeType(let c, _): return c == origName+ case .setNullable(let c, _): return c == origName+ case .setDefault(let c, _): return c == origName+ case .setComment(let c, _): return c == origName+ case .addForeignKey(let c, _, _, _, _): return c == origName+ case .dropForeignKey(let n): return col.fkConstraintName == n+ default: return false+ }+ }+ return hasChange ? .edited : .none+ }++ private func indexChangeState(_ idx: EditableIndex) -> RowChangeState {+ if idx.isMarkedForDeletion { return .deleted }+ if idx.isNew { return .new }+ guard let origName = idx.originalName else { return .none }+ let hasChange = pendingChanges.contains { change in+ switch change {+ case .modifyIndex(let old, _, _, _, _, _): return old == origName+ case .setIndexComment(let n, _): return n == origName+ default: return false+ }+ }+ return hasChange ? .edited : .none+ }++ private var isMongoDB: Bool {+ adapter?.databaseType == .mongodb+ }++ var body: some View {+ if isLoading {+ ProgressView("Loading structure...")+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ } else if isMongoDB, let desc = tableDescription {+ mongoSchemalessNotice(desc: desc)+ } else if let desc = tableDescription {+ VStack(spacing: 0) {+ // Top info bar (Name, Primary, Search)+ structureInfoBar++ // Toolbar for pending changes + Column+ structureToolbar++ VSplitView {+ columnsSection(desc)+ indexesSection(desc)+ }+ }+ .onAppear {+ syncFromDescription(desc)+ }+ .alert("Drop Column", isPresented: $showDeleteConfirm) {+ Button("Cancel", role: .cancel) {}+ Button("Drop", role: .destructive) {+ if let col = columnToDelete {+ dropColumn(col)+ }+ }+ } message: {+ Text("Drop column \"\(columnToDelete?.name ?? "")\"? This cannot be undone.")+ }+ .alert("Error", isPresented: .constant(errorMessage != nil)) {+ Button("OK") { errorMessage = nil }+ } message: {+ Text(errorMessage ?? "")+ }+ .onReceive(NotificationCenter.default.publisher(for: .init("structureAddColumn"))) { _ in+ addNewColumn()+ }+ .sheet(isPresented: $showAddIndex) {+ addIndexPopover+ }+ } else {+ Text("Failed to load table structure")+ .foregroundStyle(.secondary)+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ }+ }++ // MARK: - MongoDB Schemaless Notice++ @ViewBuilder+ private func mongoSchemalessNotice(desc: TableDescription) -> some View {+ VStack(spacing: 0) {+ // Compact header with collection name + count+ HStack(spacing: 12) {+ Image(systemName: "doc.text")+ .foregroundStyle(.secondary)+ Text(desc.name)+ .font(.system(size: 13, weight: .semibold))+ if let count = desc.estimatedRowCount {+ Text("\(count) documents")+ .font(.system(size: 11))+ .foregroundStyle(.secondary)+ }+ Spacer()+ }+ .padding(.horizontal, 12)+ .padding(.vertical, 8)+ Divider()++ VStack(spacing: 12) {+ Spacer()+ Image(systemName: "doc.text.below.ecg")+ .font(.system(size: 40))+ .foregroundStyle(.secondary)+ Text("Schemaless Collection")+ .font(.system(size: 14, weight: .semibold))+ Text("MongoDB collections don't have a fixed schema.\nEach document can have its own structure.")+ .font(.system(size: 12))+ .foregroundStyle(.secondary)+ .multilineTextAlignment(.center)+ if !desc.columns.isEmpty {+ Divider().padding(.vertical, 8).frame(width: 200)+ Text("Detected fields (from sampled documents):")+ .font(.system(size: 11))+ .foregroundStyle(.secondary)+ VStack(alignment: .leading, spacing: 4) {+ ForEach(desc.columns, id: \.name) { col in+ HStack(spacing: 6) {+ if col.isPrimaryKey {+ Image(systemName: "key.fill")+ .font(.system(size: 9))+ .foregroundStyle(.yellow)+ }+ Text(col.name)+ .font(.system(size: 12, weight: .medium, design: .monospaced))+ Text(col.dataType)+ .font(.system(size: 11))+ .foregroundStyle(.secondary)+ }+ }+ }+ .padding(.horizontal, 16)+ .padding(.vertical, 8)+ .background(Color.primary.opacity(0.05))+ .cornerRadius(6)+ }+ Spacer()+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ }+ }++ // MARK: - Structure Toolbar++ // MARK: - Info Bar (Name, Primary, Search)++ private var structureInfoBar: some View {+ HStack(spacing: 16) {+ HStack(spacing: 6) {+ Text("Name").foregroundStyle(.secondary).font(.system(size: 11))+ TextField("", text: .constant(tableName))+ .textFieldStyle(.roundedBorder)+ .font(.system(size: 12))+ .frame(width: 160)+ .disabled(true)+ }++ HStack(spacing: 6) {+ Text("Primary").foregroundStyle(.secondary).font(.system(size: 11))+ Text(primaryKeyName)+ .font(.system(size: 12, weight: .medium))+ .padding(.horizontal, 8)+ .padding(.vertical, 2)+ .background(Color.accentColor.opacity(0.2))+ .cornerRadius(4)+ }++ Spacer()++ HStack(spacing: 4) {+ Image(systemName: "magnifyingglass").foregroundStyle(.tertiary).font(.system(size: 11))+ TextField("Search for column...", text: $searchText)+ .textFieldStyle(.plain)+ .font(.system(size: 12))+ .frame(width: 150)+ }+ .padding(.horizontal, 8)+ .padding(.vertical, 4)+ .background(Color(nsColor: .controlBackgroundColor))+ .cornerRadius(6)+ }+ .padding(.horizontal, 12)+ .padding(.vertical, 6)+ .background(Color(nsColor: .windowBackgroundColor))+ .overlay(alignment: .bottom) { Divider() }+ }++ // MARK: - Structure Toolbar++ private var structureToolbar: some View {+ HStack(spacing: 12) {+ if !pendingChanges.isEmpty {+ HStack(spacing: 6) {+ Circle().fill(.orange).frame(width: 6, height: 6)+ Text("\(pendingChanges.count) pending")+ .font(.system(size: 11))+ .foregroundStyle(.orange)+ }++ Button {+ pendingChanges.removeAll()+ if let desc = tableDescription { syncFromDescription(desc) }+ } label: {+ HStack(spacing: 3) {+ Image(systemName: "arrow.uturn.backward").font(.system(size: 10))+ Text("Discard").font(.system(size: 11))+ }+ }+ .buttonStyle(.plain)+ .pointerCursor()+ .foregroundStyle(.secondary)++ Button {+ Task { await applyChanges() }+ } label: {+ HStack(spacing: 3) {+ Image(systemName: "checkmark.circle.fill").font(.system(size: 10))+ Text("Apply").font(.system(size: 11, weight: .medium))+ }+ }+ .buttonStyle(.plain)+ .pointerCursor()+ .foregroundStyle(Color.accentColor)+ .disabled(isApplying)+ }++ Spacer()+ }+ .padding(.horizontal, 12)+ .padding(.vertical, 5)+ .frame(height: 28)+ .background(Color(nsColor: .windowBackgroundColor))+ .overlay(alignment: .bottom) { Divider() }+ }++ // MARK: - Columns Section (Editable on select)++ @ViewBuilder+ private func columnsSection(_ desc: TableDescription) -> some View {+ VStack(spacing: 0) {+ Table($editableColumns, selection: $selectedColumnId) {+ TableColumn("#") { $col in+ let state = columnChangeState(col)+ Text("\((columnIndexMap[col.id] ?? 0) + 1)")+ .foregroundStyle(.secondary)+ .background { RowBackgroundSetter(color: state.nsColor) }+ }+ .width(30)++ TableColumn("column_name") { $col in+ columnNameCell(col: $col)+ }++ TableColumn("data_type") { $col in+ dataTypeCell(col: $col)+ }++ TableColumn("is_nullable") { $col in+ nullableCell(col: $col)+ }+ .width(80)++ TableColumn("check") { $col in+ Text(col.checkConstraint.isEmpty ? "" : col.checkConstraint)+ .foregroundStyle(.secondary)+ .lineLimit(1)+ .help(col.checkConstraint)+ }++ TableColumn("foreign_key") { $col in+ HStack(spacing: 4) {+ Text(col.hasForeignKey ? col.foreignKeyDisplay : "EMPTY")+ .foregroundStyle(col.hasForeignKey ? .primary : .tertiary)+ .lineLimit(1)+ Spacer()+ Image(systemName: "arrow.right")+ .font(.system(size: 9))+ .foregroundStyle(.tertiary)+ }+ .contentShape(Rectangle())+ .pointerCursor()+ .onTapGesture { openFKEditor(col) }+ .popover(isPresented: Binding(+ get: { fkEditColumnId == col.id },+ set: { if !$0 { fkEditColumnId = nil } }+ )) {+ foreignKeyPopover(col)+ }+ }++ TableColumn("column_default") { $col in+ defaultCell(col: $col)+ }++ TableColumn("comment") { $col in+ commentCell(col: $col)+ }+ }+ .contextMenu(forSelectionType: EditableColumn.ID.self) { ids in+ if let id = ids.first, let col = editableColumns.first(where: { $0.id == id }) {+ if col.isMarkedForDeletion {+ Button("Undo Drop Column \"\(col.name)\"") {+ dropColumn(col) // toggles deletion+ }+ } else {+ Button("Drop Column \"\(col.name)\"", role: .destructive) {+ columnToDelete = col+ showDeleteConfirm = true+ }+ .disabled(col.isPrimaryKey)+ }+ }+ } primaryAction: { _ in }+ .onChange(of: selectedColumnId) { oldId, newId in+ // Track any uncommitted edits from the previously selected column+ if let oldId, let col = editableColumns.first(where: { $0.id == oldId }) {+ trackAllChanges(col)+ }+ focusedColumnField = nil // Clear focus when row changes to prevent scroll jump+ updateColumnDetails(newId)+ }+ .environment(\.defaultMinListRowHeight, 34)+ .id(tableGeneration)++ // Add new column button+ HStack {+ Button { addNewColumn() } label: {+ HStack(spacing: 4) {+ Image(systemName: "plus").font(.system(size: 9))+ Text("New column").font(.system(size: 11))+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 6)+ }+ .buttonStyle(.plain)+ .pointerCursor()+ .foregroundStyle(.tertiary)+ Spacer()+ }+ .padding(.leading, 8)+ .padding(.top, 4)+ }+ .frame(minHeight: 120)+ }++ // MARK: - Column Cell Views (extracted to help Swift type-checker)++ @ViewBuilder+ private func columnNameCell(col: Binding<EditableColumn>) -> some View {+ let c = col.wrappedValue+ let isEditable = selectedColumnId == c.id && !c.isMarkedForDeletion+ HStack(spacing: 4) {+ if c.isPrimaryKey {+ Image(systemName: "key.fill").font(.system(size: 9)).foregroundStyle(.yellow)+ }+ if isEditable {+ TextField("name", text: col.name)+ .textFieldStyle(.squareBorder)+ .fontWeight(c.isPrimaryKey ? .medium : .regular)+ .focused($focusedColumnField, equals: .name(c.id))+ .onSubmit { trackRename(c) }+ } else {+ Text(c.name)+ .fontWeight(c.isPrimaryKey ? .medium : .regular)+ .strikethrough(c.isMarkedForDeletion)+ .foregroundStyle(c.isMarkedForDeletion ? .secondary : .primary)+ .lineLimit(1)+ }+ }+ }++ @ViewBuilder+ private func dataTypeCell(col: Binding<EditableColumn>) -> some View {+ let c = col.wrappedValue+ let isEditable = selectedColumnId == c.id && !c.isMarkedForDeletion+ if isEditable {+ HStack(spacing: 2) {+ TextField("type", text: col.dataType)+ .textFieldStyle(.squareBorder)+ .focused($focusedColumnField, equals: .dataType(c.id))+ .onSubmit { trackTypeChange(c) }+ Menu {+ ForEach(cachedDataTypes, id: \.self) { t in+ Button(t) { col.wrappedValue.dataType = t; trackTypeChange(col.wrappedValue) }+ }+ } label: {+ Image(systemName: "chevron.down")+ .font(.system(size: 8, weight: .semibold))+ .foregroundStyle(.secondary)+ }+ .menuStyle(.borderlessButton)+ .menuIndicator(.hidden)+ .fixedSize()+ }+ } else {+ Text(c.dataType).lineLimit(1)+ }+ }++ @ViewBuilder+ private func nullableCell(col: Binding<EditableColumn>) -> some View {+ let c = col.wrappedValue+ let isEditable = selectedColumnId == c.id && !c.isMarkedForDeletion+ if isEditable {+ Picker("", selection: Binding(+ get: { c.isNullable },+ set: { col.wrappedValue.isNullable = $0; trackNullable(col.wrappedValue) }+ )) {+ Text("NO").tag(false)+ Text("YES").tag(true)+ }+ .pickerStyle(.menu)+ .labelsHidden()+ .focusable(false)+ } else {+ Text(c.isNullable ? "YES" : "NO")+ .foregroundStyle(c.isNullable ? .primary : .secondary)+ .lineLimit(1)+ }+ }++ @ViewBuilder+ private func defaultCell(col: Binding<EditableColumn>) -> some View {+ let c = col.wrappedValue+ HStack(spacing: 4) {+ Text(c.defaultValue.isEmpty ? "NULL" : c.defaultValue)+ .foregroundStyle(c.defaultValue.isEmpty ? .tertiary : .primary)+ .lineLimit(1)+ Image(systemName: "chevron.down")+ .font(.system(size: 8))+ .foregroundStyle(selectedColumnId == c.id ? Color.gray.opacity(0.4) : Color.clear)+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ .contentShape(Rectangle())+ .pointerCursor()+ .onTapGesture { openDefaultEditor(c) }+ .popover(isPresented: Binding(+ get: { defaultEditColumnId == c.id },+ set: { if !$0 { defaultEditColumnId = nil } }+ )) {+ defaultValuePopover(c)+ }+ }++ @ViewBuilder+ private func commentCell(col: Binding<EditableColumn>) -> some View {+ let c = col.wrappedValue+ let isEditable = selectedColumnId == c.id && !c.isMarkedForDeletion+ if isEditable {+ TextField("NULL", text: col.comment)+ .textFieldStyle(.squareBorder)+ .focused($focusedColumnField, equals: .comment(c.id))+ .onSubmit { trackComment(c) }+ } else {+ Text(c.comment.isEmpty ? "NULL" : c.comment)+ .foregroundStyle(c.comment.isEmpty ? .tertiary : .primary)+ .lineLimit(1)+ }+ }++ private func updateColumnDetails(_ colId: UUID?) {+ guard let colId, let col = editableColumns.first(where: { $0.id == colId }) else {+ onSelectColumn?(nil)+ return+ }+ let details: [(column: String, value: String)] = [+ (column: "column_name", value: col.name),+ (column: "data_type", value: col.dataType),+ (column: "is_nullable", value: col.isNullable ? "YES" : "NO"),+ (column: "is_primary_key", value: col.isPrimaryKey ? "YES" : "NO"),+ (column: "column_default", value: col.defaultValue.isEmpty ? "NULL" : col.defaultValue),+ (column: "foreign_key", value: col.hasForeignKey ? col.foreignKeyDisplay : "EMPTY"),+ (column: "fk_referenced_table", value: col.fkReferencedTable.isEmpty ? "NULL" : col.fkReferencedTable),+ (column: "fk_referenced_column", value: col.fkReferencedColumn.isEmpty ? "NULL" : col.fkReferencedColumn),+ (column: "fk_on_update", value: col.fkOnUpdate.rawValue),+ (column: "fk_on_delete", value: col.fkOnDelete.rawValue),+ (column: "check_constraint", value: col.checkConstraint.isEmpty ? "EMPTY" : col.checkConstraint),+ (column: "comment", value: col.comment.isEmpty ? "NULL" : col.comment),+ ]+ onSelectColumn?(details)+ }++ // MARK: - Indexes Section (Editable)++ @ViewBuilder+ private func indexesSection(_ desc: TableDescription) -> some View {+ VStack(spacing: 0) {+ Rectangle()+ .fill(Color.accentColor.opacity(0.6))+ .frame(height: 2)++ if editableIndexes.isEmpty {+ Text("No indexes")+ .foregroundStyle(.secondary)+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ } else {+ Table($editableIndexes, selection: $selectedIndexId) {+ TableColumn("index_name") { $idx in+ let state = indexChangeState(idx)+ HStack(spacing: 4) {+ if idx.isMarkedForDeletion {+ Text(idx.name).strikethrough().foregroundStyle(.secondary).lineLimit(1)+ } else if selectedIndexId == idx.id {+ TextField("name", text: $idx.name)+ .textFieldStyle(.squareBorder)+ .onSubmit { trackIndexChange(idx) }+ } else {+ Text(idx.name).lineLimit(1)+ }+ }+ .background { RowBackgroundSetter(color: state.nsColor) }+ }++ TableColumn("index_algorithm") { $idx in+ if selectedIndexId == idx.id && !idx.isMarkedForDeletion {+ Picker("", selection: Binding(+ get: { idx.algorithm },+ set: { idx.algorithm = $0; trackIndexChange(idx) }+ )) {+ Text("BTREE").tag("BTREE")+ Text("HASH").tag("HASH")+ Text("GIST").tag("GIST")+ Text("SPGIST").tag("SPGIST")+ Text("GIN").tag("GIN")+ Text("BRIN").tag("BRIN")+ }+ .pickerStyle(.menu)+ .labelsHidden()+ } else {+ Text(idx.algorithm).lineLimit(1)+ }+ }.width(120)++ TableColumn("is_unique") { $idx in+ if selectedIndexId == idx.id && !idx.isMarkedForDeletion {+ Picker("", selection: Binding(+ get: { idx.isUnique },+ set: { idx.isUnique = $0; trackIndexChange(idx) }+ )) {+ Text("FALSE").tag(false)+ Text("TRUE").tag(true)+ }+ .pickerStyle(.menu)+ .labelsHidden()+ } else {+ Text(idx.isUnique ? "TRUE" : "FALSE")+ .foregroundStyle(idx.isUnique ? .primary : .secondary)+ }+ }.width(80)++ TableColumn("column_name") { $idx in+ if selectedIndexId == idx.id && !idx.isMarkedForDeletion {+ TextField("col1, col2", text: $idx.columns)+ .textFieldStyle(.squareBorder)+ .onSubmit { trackIndexChange(idx) }+ } else {+ Text(idx.columns).lineLimit(1)+ }+ }++ TableColumn("condition") { $idx in+ if selectedIndexId == idx.id && !idx.isMarkedForDeletion {+ TextField("EMPTY", text: $idx.condition)+ .textFieldStyle(.squareBorder)+ .onSubmit { trackIndexChange(idx) }+ } else {+ Text(idx.condition.isEmpty ? "EMPTY" : idx.condition)+ .foregroundStyle(idx.condition.isEmpty ? .tertiary : .secondary)+ .lineLimit(1)+ }+ }++ TableColumn("include") { $idx in+ if selectedIndexId == idx.id && !idx.isMarkedForDeletion {+ TextField("EMPTY", text: $idx.include)+ .textFieldStyle(.squareBorder)+ } else {+ Text(idx.include.isEmpty ? "EMPTY" : idx.include)+ .foregroundStyle(idx.include.isEmpty ? .tertiary : .secondary)+ .lineLimit(1)+ }+ }++ TableColumn("comment") { $idx in+ if selectedIndexId == idx.id && !idx.isMarkedForDeletion {+ TextField("NULL", text: $idx.comment)+ .textFieldStyle(.squareBorder)+ .onSubmit { trackIndexComment(idx) }+ } else {+ Text(idx.comment.isEmpty ? "NULL" : idx.comment)+ .foregroundStyle(idx.comment.isEmpty ? .tertiary : .secondary)+ .lineLimit(1)+ }+ }+ }+ .contextMenu(forSelectionType: EditableIndex.ID.self) { ids in+ if let id = ids.first, let idx = editableIndexes.first(where: { $0.id == id }) {+ if idx.isMarkedForDeletion {+ Button("Undo Drop Index \"\(idx.name)\"") {+ dropIndex(idx) // toggles deletion+ }+ } else {+ Button("Drop Index \"\(idx.name)\"", role: .destructive) {+ dropIndex(idx)+ }+ }+ }+ } primaryAction: { _ in }+ .onChange(of: selectedIndexId) { oldId, _ in+ if let oldId, let idx = editableIndexes.first(where: { $0.id == oldId }) {+ trackIndexChangeOnDeselect(idx)+ }+ }+ .environment(\.defaultMinListRowHeight, 34)+ .id(tableGeneration)+ }++ // Add new index button+ HStack {+ Button { showAddIndex = true } label: {+ HStack(spacing: 4) {+ Image(systemName: "plus").font(.system(size: 9))+ Text("New index").font(.system(size: 11))+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 6)+ }+ .buttonStyle(.plain)+ .pointerCursor()+ .foregroundStyle(.tertiary)+ Spacer()+ }+ .padding(.leading, 8)+ .padding(.top, 4)+ }+ .frame(minHeight: 80)+ }++ /// Track all field changes for an index (called when deselecting a row)+ private func trackIndexChangeOnDeselect(_ idx: EditableIndex) {+ guard !idx.isNew, let orig = idx.originalName else { return }+ guard let desc = tableDescription,+ let origIdx = desc.indexes.first(where: { $0.name == orig }) else { return }++ let currentCols = idx.columns.split(separator: ",").map { String($0).trimmingCharacters(in: .whitespaces) }+ let origCols = origIdx.columns+ let origAlgo = origIdx.type?.uppercased() ?? "BTREE"+ let origCond = origIdx.condition ?? ""+ let origComment = origIdx.comment ?? ""++ if idx.name != orig || currentCols != origCols || idx.algorithm != origAlgo+ || idx.isUnique != origIdx.isUnique || idx.condition != origCond {+ trackIndexChange(idx)+ }+ if idx.comment != origComment {+ trackIndexComment(idx)+ }+ }++ private func trackIndexChange(_ idx: EditableIndex) {+ guard let orig = idx.originalName else { return }+ let cols = idx.columns.split(separator: ",").map { String($0).trimmingCharacters(in: .whitespaces) }+ guard !cols.isEmpty else { return }+ pendingChanges.removeAll { if case .modifyIndex(let o, _, _, _, _, _) = $0, o == orig { return true }; return false }+ let cond = idx.condition.isEmpty ? nil : idx.condition+ pendingChanges.append(.modifyIndex(oldName: orig, newName: idx.name, columns: cols, algorithm: idx.algorithm, isUnique: idx.isUnique, condition: cond))+ }++ private func trackIndexComment(_ idx: EditableIndex) {+ let name = idx.originalName ?? idx.name+ guard !idx.isNew else { return }+ pendingChanges.removeAll { if case .setIndexComment(let n, _) = $0, n == name { return true }; return false }+ let val = idx.comment.isEmpty ? nil : idx.comment+ pendingChanges.append(.setIndexComment(name: name, comment: val))+ }++ private func dropIndex(_ idx: EditableIndex) {+ if idx.isNew {+ editableIndexes.removeAll { $0.id == idx.id }+ pendingChanges.removeAll { if case .addIndex(let n, _, _, _, _) = $0, n == idx.name { return true }; return false }+ } else if let orig = idx.originalName {+ if let i = editableIndexes.firstIndex(where: { $0.id == idx.id }) {+ if idx.isMarkedForDeletion {+ // Undo delete+ editableIndexes[i].isMarkedForDeletion = false+ pendingChanges.removeAll { if case .dropIndex(let n) = $0, n == orig { return true }; return false }+ } else {+ // Mark for deletion+ editableIndexes[i].isMarkedForDeletion = true+ pendingChanges.append(.dropIndex(name: orig))+ }+ }+ }+ }++ // MARK: - Sync++ private func syncFromDescription(_ desc: TableDescription) {+ editableColumns = desc.columns.map { col in+ let fk = desc.foreignKeys.first { $0.columns.contains(col.name) }+ let fkDisplay = fk.map { "\($0.referencedTable)(\($0.referencedColumns.joined(separator: ", ")))" } ?? ""+ let fkRefCol = fk.flatMap { fkInfo -> String? in+ guard let idx = fkInfo.columns.firstIndex(of: col.name), idx < fkInfo.referencedColumns.count else { return nil }+ return fkInfo.referencedColumns[idx]+ } ?? ""+ return EditableColumn(+ originalName: col.name,+ name: col.name,+ dataType: col.dataType,+ isNullable: col.isNullable,+ defaultValue: col.defaultValue ?? "",+ comment: col.comment ?? "",+ isPrimaryKey: col.isPrimaryKey,+ foreignKeyDisplay: fkDisplay,+ checkConstraint: col.checkConstraint ?? "",+ fkConstraintName: fk?.name ?? "",+ fkReferencedTable: fk?.referencedTable ?? "",+ fkReferencedColumn: fkRefCol,+ fkOnUpdate: fk?.onUpdate ?? .noAction,+ fkOnDelete: fk?.onDelete ?? .noAction+ )+ }+ columnIndexMap = Dictionary(uniqueKeysWithValues: editableColumns.enumerated().map { ($1.id, $0) })+ editableIndexes = desc.indexes.map { idx in+ EditableIndex(+ originalName: idx.name,+ name: idx.name,+ algorithm: idx.type?.uppercased() ?? "BTREE",+ isUnique: idx.isUnique,+ columns: idx.columns.joined(separator: ", "),+ condition: idx.condition ?? "",+ include: idx.include ?? "",+ comment: idx.comment ?? ""+ )+ }+ rebuildDataTypeCache()+ }++ private func rebuildDataTypeCache() {+ let base: [String]+ if let adapter {+ switch adapter.databaseType {+ case .postgresql: base = postgresDataTypes+ case .mysql: base = mysqlDataTypes+ case .sqlite: base = sqliteDataTypes+ case .mssql: base = [+ // Exact numerics+ "INT", "BIGINT", "SMALLINT", "TINYINT", "BIT",+ "DECIMAL", "NUMERIC", "MONEY", "SMALLMONEY",+ // Approximate numerics+ "FLOAT", "REAL",+ // Date and time+ "DATE", "TIME", "DATETIME", "DATETIME2", "DATETIMEOFFSET", "SMALLDATETIME",+ // Character strings+ "CHAR", "VARCHAR", "VARCHAR(MAX)", "TEXT",+ // Unicode character strings+ "NCHAR", "NVARCHAR", "NVARCHAR(MAX)", "NTEXT",+ // Binary strings+ "BINARY", "VARBINARY", "VARBINARY(MAX)", "IMAGE",+ // Other+ "UNIQUEIDENTIFIER", "XML", "JSON", "ROWVERSION", "HIERARCHYID",+ "GEOGRAPHY", "GEOMETRY", "SQL_VARIANT",+ ]+ case .redis: base = ["string", "list", "set", "zset", "hash", "stream"]+ case .mongodb: base = ["string", "integer", "double", "boolean", "date", "objectId", "document", "array"]+ }+ } else {+ base = postgresDataTypes+ }+ let baseSet = Set(base.map { $0.lowercased() })+ let missing = Array(Set(+ editableColumns.map { $0.dataType }+ .filter { !$0.isEmpty && !baseSet.contains($0.lowercased()) }+ )).sorted()+ cachedDataTypes = missing + base+ }++ // MARK: - Change Tracking++ /// Track all field changes for a column (called when deselecting a row)+ private func trackAllChanges(_ col: EditableColumn) {+ guard !col.isNew, let orig = col.originalName else { return }+ // Find the original description to compare+ guard let desc = tableDescription,+ let origCol = desc.columns.first(where: { $0.name == orig }) else { return }++ if col.name != orig { trackRename(col) }+ if col.dataType != origCol.dataType { trackTypeChange(col) }+ if col.isNullable != origCol.isNullable { trackNullable(col) }+ let origDefault = origCol.defaultValue ?? ""+ if col.defaultValue != origDefault { trackDefault(col) }+ let origComment = origCol.comment ?? ""+ if col.comment != origComment { trackComment(col) }+ }++ private func trackRename(_ col: EditableColumn) {+ guard let orig = col.originalName, orig != col.name, !col.name.isEmpty else { return }+ pendingChanges.removeAll { if case .renameColumn(let o, _) = $0, o == orig { return true }; return false }+ pendingChanges.append(.renameColumn(oldName: orig, newName: col.name))+ }++ private func trackTypeChange(_ col: EditableColumn) {+ let name = col.originalName ?? col.name+ guard !col.isNew else { return }+ pendingChanges.removeAll { if case .changeType(let c, _) = $0, c == name { return true }; return false }+ pendingChanges.append(.changeType(column: name, newType: col.dataType))+ }++ private func trackNullable(_ col: EditableColumn) {+ let name = col.originalName ?? col.name+ guard !col.isNew else { return }+ pendingChanges.removeAll { if case .setNullable(let c, _) = $0, c == name { return true }; return false }+ pendingChanges.append(.setNullable(column: name, nullable: col.isNullable))+ }++ private func trackDefault(_ col: EditableColumn) {+ let name = col.originalName ?? col.name+ guard !col.isNew else { return }+ pendingChanges.removeAll { if case .setDefault(let c, _) = $0, c == name { return true }; return false }+ let val = col.defaultValue.isEmpty ? nil : col.defaultValue+ pendingChanges.append(.setDefault(column: name, value: val))+ }++ // MARK: - Default Value Editor++ private func openDefaultEditor(_ col: EditableColumn) {+ let current = col.defaultValue+ // Detect current default type+ if current.hasPrefix("nextval(") || current.contains("_seq") {+ defaultTab = .sequence+ // Extract sequence name from nextval('seq_name'::regclass)+ let seqName = current+ .replacingOccurrences(of: "nextval('", with: "")+ .replacingOccurrences(of: "'::regclass)", with: "")+ .replacingOccurrences(of: "nextval('", with: "")+ .replacingOccurrences(of: "')", with: "")+ defaultSequenceName = seqName+ defaultStringValue = ""+ defaultExpressionValue = ""+ defaultCreateSequence = false+ } else if current.contains("(") || current == "CURRENT_TIMESTAMP" || current == "NOW()" ||+ current == "true" || current == "false" || current == "gen_random_uuid()" ||+ current.uppercased().hasPrefix("CURRENT_") {+ defaultTab = .expression+ defaultExpressionValue = current+ defaultStringValue = ""+ defaultSequenceName = ""+ defaultCreateSequence = false+ } else {+ defaultTab = .string+ // Strip surrounding quotes if present+ var str = current+ if str.hasPrefix("'") && str.hasSuffix("'") && str.count >= 2 {+ str = String(str.dropFirst().dropLast())+ }+ defaultStringValue = str+ defaultExpressionValue = ""+ defaultSequenceName = ""+ defaultCreateSequence = false+ }+ defaultEditColumnId = col.id+ }++ private func saveDefaultValue(_ col: EditableColumn) {+ guard let idx = editableColumns.firstIndex(where: { $0.id == col.id }) else { return }+ let value: String+ switch defaultTab {+ case .string:+ value = defaultStringValue.isEmpty ? "" : "'\(defaultStringValue.replacingOccurrences(of: "'", with: "''"))'"+ case .expression:+ value = defaultExpressionValue+ case .sequence:+ if defaultSequenceName.isEmpty {+ value = ""+ } else {+ value = "nextval('\(defaultSequenceName)')"+ }+ }+ editableColumns[idx].defaultValue = value++ // Create sequence if needed+ if defaultTab == .sequence && defaultCreateSequence && !defaultSequenceName.isEmpty {+ let seqSQL = "CREATE SEQUENCE IF NOT EXISTS \(defaultSequenceName)"+ // Add as a pending change — we'll prepend it before the ALTER+ pendingChanges.removeAll { if case .createSequence(let n) = $0, n == defaultSequenceName { return true }; return false }+ pendingChanges.append(.createSequence(name: seqSQL))+ }++ trackDefault(editableColumns[idx])+ defaultEditColumnId = nil+ }++ private func defaultValuePopover(_ col: EditableColumn) -> some View {+ VStack(spacing: 12) {+ // Tab picker+ Picker("", selection: $defaultTab) {+ ForEach(DefaultValueTab.allCases, id: \.self) { tab in+ Text(tab.rawValue).tag(tab)+ }+ }+ .pickerStyle(.segmented)+ .labelsHidden()++ // Tab content+ switch defaultTab {+ case .string:+ VStack(alignment: .leading, spacing: 6) {+ Text("String value").font(.caption).foregroundStyle(.secondary)+ TextField("Enter string value...", text: $defaultStringValue)+ .textFieldStyle(.roundedBorder)+ }++ case .expression:+ VStack(alignment: .leading, spacing: 6) {+ Text("SQL expression").font(.caption).foregroundStyle(.secondary)+ TextField("e.g. CURRENT_TIMESTAMP, gen_random_uuid()", text: $defaultExpressionValue)+ .textFieldStyle(.roundedBorder)+ // Quick-pick buttons+ HStack(spacing: 4) {+ ForEach(["CURRENT_TIMESTAMP", "NOW()", "gen_random_uuid()", "true", "false"], id: \.self) { expr in+ Button(expr) { defaultExpressionValue = expr }+ .buttonStyle(.plain)+ .font(.system(size: 10, design: .monospaced))+ .padding(.horizontal, 6)+ .padding(.vertical, 2)+ .background(Color(nsColor: .controlBackgroundColor))+ .cornerRadius(4)+ }+ }+ }++ case .sequence:+ VStack(alignment: .leading, spacing: 6) {+ Text("Sequence name").font(.caption).foregroundStyle(.secondary)+ TextField("e.g. table_id_seq", text: $defaultSequenceName)+ .textFieldStyle(.roundedBorder)+ Toggle("Create sequence if not exists", isOn: $defaultCreateSequence)+ .font(.caption)+ }+ }++ Divider()++ // Buttons+ HStack {+ if !col.defaultValue.isEmpty {+ Button("Clear", role: .destructive) {+ guard let idx = editableColumns.firstIndex(where: { $0.id == col.id }) else { return }+ editableColumns[idx].defaultValue = ""+ trackDefault(editableColumns[idx])+ defaultEditColumnId = nil+ }+ }+ Spacer()+ Button("Cancel") { defaultEditColumnId = nil }+ Button("OK") { saveDefaultValue(col) }+ .buttonStyle(.borderedProminent)+ }+ }+ .padding(16)+ .frame(width: 360)+ }++ private func trackComment(_ col: EditableColumn) {+ let name = col.originalName ?? col.name+ guard !col.isNew else { return }+ pendingChanges.removeAll { if case .setComment(let c, _) = $0, c == name { return true }; return false }+ let val = col.comment.isEmpty ? nil : col.comment+ pendingChanges.append(.setComment(column: name, comment: val))+ }++ // MARK: - Foreign Key Editor++ private func openFKEditor(_ col: EditableColumn) {+ fkRefTable = col.fkReferencedTable+ fkRefColumn = col.fkReferencedColumn+ fkOnUpdate = col.fkOnUpdate+ fkOnDelete = col.fkOnDelete+ fkEditColumnId = col.id+ // Load available tables if needed+ if availableTables.isEmpty {+ Task {+ if let tables = try? await adapter?.listTables(schema: schema) {+ availableTables = tables+ .filter { $0.type == .table }+ .map { $0.name }+ .sorted()+ }+ }+ }+ }++ @ViewBuilder+ private func foreignKeyPopover(_ col: EditableColumn) -> some View {+ VStack(spacing: 12) {+ // Table (current, read-only)+ HStack {+ Text("Table").frame(width: 130, alignment: .trailing).foregroundStyle(.secondary)+ Text(tableName)+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(.horizontal, 8).padding(.vertical, 4)+ .background(Color(nsColor: .controlBackgroundColor))+ .cornerRadius(6)+ }++ // Column (read-only)+ HStack {+ Text("Columns").frame(width: 130, alignment: .trailing).foregroundStyle(.secondary)+ Text(col.name)+ .padding(.horizontal, 8).padding(.vertical, 4)+ .background(Color.accentColor.opacity(0.2))+ .cornerRadius(4)+ .frame(maxWidth: .infinity, alignment: .leading)+ }++ // Referenced Table+ HStack {+ Text("Referenced Table").frame(width: 130, alignment: .trailing).foregroundStyle(.secondary)+ Picker("", selection: $fkRefTable) {+ Text("Select a table...").tag("")+ ForEach(availableTables, id: \.self) { t in+ Text(t).tag(t)+ }+ }+ .labelsHidden()+ }++ // Referenced Column+ HStack {+ Text("Referenced Columns").frame(width: 130, alignment: .trailing).foregroundStyle(.secondary)+ TextField("Column name...", text: $fkRefColumn)+ .textFieldStyle(.roundedBorder)+ }++ // On Update+ HStack {+ Text("On Update").frame(width: 130, alignment: .trailing).foregroundStyle(.secondary)+ Picker("", selection: $fkOnUpdate) {+ ForEach([ForeignKeyAction.noAction, .cascade, .setNull, .setDefault, .restrict], id: \.self) { a in+ Text(a.rawValue).tag(a)+ }+ }+ .labelsHidden()+ }++ // On Delete+ HStack {+ Text("On Delete").frame(width: 130, alignment: .trailing).foregroundStyle(.secondary)+ Picker("", selection: $fkOnDelete) {+ ForEach([ForeignKeyAction.noAction, .cascade, .setNull, .setDefault, .restrict], id: \.self) { a in+ Text(a.rawValue).tag(a)+ }+ }+ .labelsHidden()+ }++ Divider()++ // Buttons+ HStack {+ if col.hasForeignKey {+ Button("Delete", role: .destructive) {+ deleteForeignKey(col)+ fkEditColumnId = nil+ }+ }+ Spacer()+ Button("Cancel") { fkEditColumnId = nil }+ Button("OK") {+ saveForeignKey(col)+ fkEditColumnId = nil+ }+ .disabled(fkRefTable.isEmpty || fkRefColumn.isEmpty)+ .buttonStyle(.borderedProminent)+ }+ }+ .padding(16)+ .frame(width: 400)+ }++ private func saveForeignKey(_ col: EditableColumn) {+ guard let idx = editableColumns.firstIndex(where: { $0.id == col.id }) else { return }+ let colName = col.originalName ?? col.name++ // Drop old FK if exists+ if !col.fkConstraintName.isEmpty {+ pendingChanges.append(.dropForeignKey(constraintName: col.fkConstraintName))+ }++ // Add new FK+ pendingChanges.append(.addForeignKey(+ column: colName, refTable: fkRefTable, refColumn: fkRefColumn,+ onUpdate: fkOnUpdate, onDelete: fkOnDelete+ ))++ // Update local state+ editableColumns[idx].fkReferencedTable = fkRefTable+ editableColumns[idx].fkReferencedColumn = fkRefColumn+ editableColumns[idx].fkOnUpdate = fkOnUpdate+ editableColumns[idx].fkOnDelete = fkOnDelete+ editableColumns[idx].foreignKeyDisplay = "\(fkRefTable)(\(fkRefColumn))"+ }++ private func deleteForeignKey(_ col: EditableColumn) {+ guard let idx = editableColumns.firstIndex(where: { $0.id == col.id }) else { return }+ if !col.fkConstraintName.isEmpty {+ pendingChanges.append(.dropForeignKey(constraintName: col.fkConstraintName))+ }+ editableColumns[idx].fkReferencedTable = ""+ editableColumns[idx].fkReferencedColumn = ""+ editableColumns[idx].fkOnUpdate = .noAction+ editableColumns[idx].fkOnDelete = .noAction+ editableColumns[idx].foreignKeyDisplay = ""+ }++ // MARK: - Add Index Popover++ private var addIndexPopover: some View {+ VStack(spacing: 12) {+ HStack {+ Text("Index Name").frame(width: 110, alignment: .trailing).foregroundStyle(.secondary)+ TextField("idx_\(tableName)_...", text: $newIndexName)+ .textFieldStyle(.roundedBorder)+ }++ HStack {+ Text("Columns").frame(width: 110, alignment: .trailing).foregroundStyle(.secondary)+ TextField("col1, col2", text: $newIndexColumns)+ .textFieldStyle(.roundedBorder)+ }++ HStack {+ Text("Algorithm").frame(width: 110, alignment: .trailing).foregroundStyle(.secondary)+ Picker("", selection: $newIndexAlgorithm) {+ Text("BTREE").tag("BTREE")+ Text("HASH").tag("HASH")+ Text("GIN").tag("GIN")+ Text("GIST").tag("GIST")+ Text("BRIN").tag("BRIN")+ }+ .labelsHidden()+ }++ HStack {+ Text("Unique").frame(width: 110, alignment: .trailing).foregroundStyle(.secondary)+ Toggle("", isOn: $newIndexIsUnique).labelsHidden()+ Spacer()+ }++ HStack {+ Text("Condition").frame(width: 110, alignment: .trailing).foregroundStyle(.secondary)+ TextField("WHERE ...", text: $newIndexCondition)+ .textFieldStyle(.roundedBorder)+ }++ Divider()++ HStack {+ Spacer()+ Button("Cancel") { showAddIndex = false }+ Button("OK") {+ addNewIndex()+ showAddIndex = false+ }+ .disabled(newIndexColumns.isEmpty)+ .buttonStyle(.borderedProminent)+ }+ }+ .padding(16)+ .frame(width: 380)+ }++ private func addNewIndex() {+ let cols = newIndexColumns.split(separator: ",").map { String($0).trimmingCharacters(in: .whitespaces) }+ guard !cols.isEmpty else { return }+ let name = newIndexName.isEmpty ? "idx_\(tableName)_\(cols.joined(separator: "_"))" : newIndexName+ let cond = newIndexCondition.isEmpty ? nil : newIndexCondition+ pendingChanges.append(.addIndex(name: name, columns: cols, algorithm: newIndexAlgorithm, isUnique: newIndexIsUnique, condition: cond))+ // Add to editable list+ let newIdx = EditableIndex(+ originalName: nil,+ name: name,+ algorithm: newIndexAlgorithm,+ isUnique: newIndexIsUnique,+ columns: newIndexColumns,+ condition: newIndexCondition,+ include: "",+ comment: ""+ )+ editableIndexes.append(newIdx)+ selectedIndexId = newIdx.id+ // Reset form+ newIndexName = ""+ newIndexColumns = ""+ newIndexAlgorithm = "BTREE"+ newIndexIsUnique = false+ newIndexCondition = ""+ }++ // MARK: - Add / Drop++ private func addNewColumn() {+ let newCol = EditableColumn(+ originalName: nil,+ name: "new_column",+ dataType: "text",+ isNullable: true,+ defaultValue: "",+ comment: "",+ isPrimaryKey: false,+ foreignKeyDisplay: "",+ checkConstraint: ""+ )+ editableColumns.append(newCol)+ columnIndexMap = Dictionary(uniqueKeysWithValues: editableColumns.enumerated().map { ($1.id, $0) })+ selectedColumnId = newCol.id+ // Placeholder — will be replaced with actual values at apply time+ pendingChanges.append(.addColumn(name: "__new__", dataType: "text", nullable: true, defaultValue: nil))+ }++ private func dropColumn(_ col: EditableColumn) {+ if col.isNew {+ editableColumns.removeAll { $0.id == col.id }+ columnIndexMap = Dictionary(uniqueKeysWithValues: editableColumns.enumerated().map { ($1.id, $0) })+ pendingChanges.removeAll {+ if case .addColumn(let n, _, _, _) = $0, n == col.name || n == "__new__" { return true }; return false+ }+ } else if let name = col.originalName {+ if let idx = editableColumns.firstIndex(where: { $0.id == col.id }) {+ if col.isMarkedForDeletion {+ // Undo delete+ editableColumns[idx].isMarkedForDeletion = false+ pendingChanges.removeAll { if case .dropColumn(let n) = $0, n == name { return true }; return false }+ } else {+ // Mark for deletion (keep row visible with red highlight)+ editableColumns[idx].isMarkedForDeletion = true+ pendingChanges.append(.dropColumn(name: name))+ }+ }+ }+ }++ // MARK: - Apply Changes++ private func applyChanges() async {+ guard let adapter else { return }++ // Remove placeholder addColumn entries and replace with actual user-edited values+ pendingChanges.removeAll { if case .addColumn(let n, _, _, _) = $0, n == "__new__" { return true }; return false }+ let newColumns = editableColumns.filter { $0.isNew && !$0.name.isEmpty }+ for col in newColumns {+ let def = col.defaultValue.isEmpty ? nil : col.defaultValue+ pendingChanges.append(.addColumn(name: col.name, dataType: col.dataType, nullable: col.isNullable, defaultValue: def))+ }++ guard !pendingChanges.isEmpty else { return }+ isApplying = true+ defer { isApplying = false }++ let d = adapter.databaseType.sqlDialect+ let schemaPrefix = schema.map { d.quoteIdentifier($0) + "." } ?? ""+ let qualifiedTable = "\(schemaPrefix)\(d.quoteIdentifier(tableName))"++ var sqls: [String] = []++ let isMSSQL = adapter.databaseType == .mssql+ for change in pendingChanges {+ switch change {+ case .addColumn(let name, let dataType, let nullable, let defaultValue):+ // MSSQL uses "ALTER TABLE ... ADD col type" (no COLUMN keyword, no IF NOT EXISTS)+ var sql: String+ if isMSSQL {+ sql = "ALTER TABLE \(qualifiedTable) ADD \(d.quoteIdentifier(name)) \(dataType)"+ } else {+ sql = "ALTER TABLE \(qualifiedTable) ADD COLUMN IF NOT EXISTS \(d.quoteIdentifier(name)) \(dataType)"+ }+ if let def = defaultValue, !def.isEmpty {+ sql += " DEFAULT \(def)"+ } else if !nullable {+ // NOT NULL column on existing table needs a default for existing rows+ let typeLower = dataType.lowercased()+ let autoDefault: String+ if typeLower.contains("int") || typeLower == "serial" || typeLower == "bigserial" || typeLower == "smallserial" {+ autoDefault = "0"+ } else if typeLower.contains("float") || typeLower.contains("double") || typeLower.contains("numeric") || typeLower.contains("decimal") || typeLower == "real" {+ autoDefault = "0"+ } else if typeLower == "bool" || typeLower == "boolean" {+ autoDefault = "false"+ } else if typeLower.contains("timestamp") || typeLower == "date" {+ autoDefault = "CURRENT_TIMESTAMP"+ } else if typeLower == "uuid" {+ autoDefault = "gen_random_uuid()"+ } else if typeLower == "jsonb" || typeLower == "json" {+ autoDefault = "'{}'"+ } else {+ autoDefault = "''"+ }+ sql += " DEFAULT \(autoDefault)"+ }+ if !nullable { sql += " NOT NULL" }+ sqls.append(sql)++ case .renameColumn(let oldName, let newName):+ if isMSSQL {+ // SQL Server: sp_rename 'schema.table.oldCol', 'newCol', 'COLUMN'+ let tableRef = "\(schemaPrefix.replacingOccurrences(of: "[", with: "").replacingOccurrences(of: "]", with: "").replacingOccurrences(of: ".", with: ""))\(tableName)"+ sqls.append("EXEC sp_rename '\(tableRef).\(oldName)', '\(newName)', 'COLUMN'")+ } else {+ sqls.append("ALTER TABLE \(qualifiedTable) RENAME COLUMN \(d.quoteIdentifier(oldName)) TO \(d.quoteIdentifier(newName))")+ }++ case .changeType(let column, let newType):+ if adapter.databaseType == .postgresql {+ // Try without USING first — PG handles implicit casts for most type changes.+ sqls.append("ALTER TABLE \(qualifiedTable) ALTER COLUMN \(d.quoteIdentifier(column)) TYPE \(newType)")+ } else if isMSSQL {+ // MSSQL: ALTER COLUMN col type (no TYPE keyword, no MODIFY)+ sqls.append("ALTER TABLE \(qualifiedTable) ALTER COLUMN \(d.quoteIdentifier(column)) \(newType)")+ } else {+ sqls.append("ALTER TABLE \(qualifiedTable) MODIFY COLUMN \(d.quoteIdentifier(column)) \(newType)")+ }++ case .setNullable(let column, let nullable):+ if isMSSQL {+ // MSSQL requires re-declaring the column type to toggle nullability;+ // skip for MVP (user can manually re-apply type with the right nullability)+ break+ }+ if nullable {+ sqls.append("ALTER TABLE \(qualifiedTable) ALTER COLUMN \(d.quoteIdentifier(column)) DROP NOT NULL")+ } else {+ sqls.append("ALTER TABLE \(qualifiedTable) ALTER COLUMN \(d.quoteIdentifier(column)) SET NOT NULL")+ }++ case .setDefault(let column, let value):+ if isMSSQL {+ // MSSQL uses constraint-based defaults — more complex, skip for MVP+ break+ }+ if let val = value {+ sqls.append("ALTER TABLE \(qualifiedTable) ALTER COLUMN \(d.quoteIdentifier(column)) SET DEFAULT \(val)")+ } else {+ sqls.append("ALTER TABLE \(qualifiedTable) ALTER COLUMN \(d.quoteIdentifier(column)) DROP DEFAULT")+ }++ case .setComment(let column, let comment):+ if adapter.databaseType == .postgresql {+ let val = comment.map { "'\($0.replacingOccurrences(of: "'", with: "''"))'" } ?? "NULL"+ sqls.append("COMMENT ON COLUMN \(qualifiedTable).\(d.quoteIdentifier(column)) IS \(val)")+ }++ case .dropColumn(let name):+ sqls.append("ALTER TABLE \(qualifiedTable) DROP COLUMN \(d.quoteIdentifier(name))")++ case .dropForeignKey(let constraintName):+ sqls.append("ALTER TABLE \(qualifiedTable) DROP CONSTRAINT \(d.quoteIdentifier(constraintName))")++ case .addForeignKey(let column, let refTable, let refColumn, let onUpdate, let onDelete):+ let refQualified = "\(schemaPrefix)\(d.quoteIdentifier(refTable))"+ var sql = "ALTER TABLE \(qualifiedTable) ADD FOREIGN KEY (\(d.quoteIdentifier(column))) REFERENCES \(refQualified)(\(d.quoteIdentifier(refColumn)))"+ if onUpdate != .noAction { sql += " ON UPDATE \(onUpdate.rawValue)" }+ if onDelete != .noAction { sql += " ON DELETE \(onDelete.rawValue)" }+ sqls.append(sql)++ case .addIndex(let name, let columns, let algorithm, let isUnique, let condition):+ let colList = columns.map { d.quoteIdentifier($0) }.joined(separator: ", ")+ var sql = "CREATE"+ if isUnique { sql += " UNIQUE" }+ sql += " INDEX \(d.quoteIdentifier(name)) ON \(qualifiedTable)"+ if algorithm != "BTREE" { sql += " USING \(algorithm)" }+ sql += " (\(colList))"+ if let cond = condition { sql += " WHERE \(cond)" }+ sqls.append(sql)++ case .dropIndex(let name):+ sqls.append("DROP INDEX \(schemaPrefix)\(d.quoteIdentifier(name))")++ case .modifyIndex(let oldName, let newName, let columns, let algorithm, let isUnique, let condition):+ // Drop old, create new (PG doesn't support ALTER INDEX for structure)+ sqls.append("DROP INDEX \(schemaPrefix)\(d.quoteIdentifier(oldName))")+ let colList = columns.map { d.quoteIdentifier($0) }.joined(separator: ", ")+ var sql = "CREATE"+ if isUnique { sql += " UNIQUE" }+ sql += " INDEX \(d.quoteIdentifier(newName)) ON \(qualifiedTable)"+ if algorithm != "BTREE" { sql += " USING \(algorithm)" }+ sql += " (\(colList))"+ if let cond = condition { sql += " WHERE \(cond)" }+ sqls.append(sql)++ case .setIndexComment(let name, let comment):+ if adapter.databaseType == .postgresql {+ let val = comment.map { "'\($0.replacingOccurrences(of: "'", with: "''"))'" } ?? "NULL"+ sqls.append("COMMENT ON INDEX \(schemaPrefix)\(d.quoteIdentifier(name)) IS \(val)")+ }++ case .createSequence(let rawSQL):+ // Insert at beginning so sequence exists before column default references it+ sqls.insert(rawSQL, at: 0)+ }+ }++ // Execute all ALTER statements+ for sql in sqls {+ do {+ _ = try await adapter.executeRaw(sql: sql)+ } catch {+ // If ALTER TYPE fails due to dependent views, retry with drop/recreate+ let errStr = String(reflecting: error)+ if adapter.databaseType == .postgresql,+ errStr.contains("0A000"),+ errStr.contains("used by a view or rule") {+ do {+ try await executeWithDependentViews(sql: sql, adapter: adapter, schema: schema ?? "public")+ } catch {+ errorMessage = "Failed: \(sql)\n\(DataGridViewState.detailedErrorMessage(error))"+ return+ }+ } else {+ errorMessage = "Failed: \(sql)\n\(DataGridViewState.detailedErrorMessage(error))"+ return+ }+ }+ }++ pendingChanges.removeAll()+ // Reload structure from database, then force full table recreation+ if let freshDesc = await onStructureChanged?() {+ tableGeneration += 1+ syncFromDescription(freshDesc)+ }+ }++ /// Drop dependent views, execute ALTER, then recreate them.+ private func executeWithDependentViews(sql: String, adapter: any DatabaseAdapter, schema: String) async throws {+ // Query all views that depend on this table (parameterized to prevent SQL injection)+ let depSQL = """+ SELECT DISTINCT v.oid, c.relname AS view_name, n.nspname AS view_schema,+ pg_get_viewdef(v.oid, true) AS view_def+ FROM pg_depend d+ JOIN pg_rewrite r ON r.oid = d.objid+ JOIN pg_class v ON v.oid = r.ev_class AND v.relkind = 'v'+ JOIN pg_namespace n ON n.oid = v.relnamespace+ JOIN pg_class c ON c.oid = v.oid+ WHERE d.refclassid = 'pg_class'::regclass+ AND d.refobjid = (SELECT oid FROM pg_class WHERE relname = $1 AND relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = $2))+ AND d.deptype = 'n'+ ORDER BY v.oid+ """++ let depResult = try await adapter.executeWithRowValues(sql: depSQL, parameters: [.string(tableName), .string(schema)])++ // Collect view definitions+ var views: [(schema: String, name: String, definition: String)] = []+ for row in depResult.rows {+ guard row.count >= 4,+ case .string(let vName) = row[1],+ case .string(let vSchema) = row[2],+ case .string(let vDef) = row[3] else { continue }+ views.append((schema: vSchema, name: vName, definition: vDef))+ }++ // Wrap in transaction so everything rolls back if any step fails+ _ = try await adapter.executeRaw(sql: "BEGIN")+ do {+ // Drop views in reverse order (handles dependencies between views)+ for view in views.reversed() {+ let dropSQL = "DROP VIEW IF EXISTS \"\(view.schema)\".\"\(view.name)\" CASCADE"+ _ = try await adapter.executeRaw(sql: dropSQL)+ }++ // Execute the ALTER statement+ _ = try await adapter.executeRaw(sql: sql)++ // Recreate views in original order+ for view in views {+ let createSQL = "CREATE VIEW \"\(view.schema)\".\"\(view.name)\" AS \(view.definition)"+ _ = try await adapter.executeRaw(sql: createSQL)+ }++ _ = try await adapter.executeRaw(sql: "COMMIT")+ } catch {+ _ = try? await adapter.executeRaw(sql: "ROLLBACK")+ throw error+ }+ }+}++// MARK: - Query Log Panel++struct QueryLogPanel: View {+ @ObservedObject var appState: AppState+ @State private var syntaxHighlighting = true+ @State private var panelHeight: CGFloat = 120+ @State private var dragStartY: CGFloat? = nil+ @State private var dragStartHeight: CGFloat? = nil++ private let minHeight: CGFloat = 60+ private let maxHeight: CGFloat = 400++ private static let timestampFormatter: DateFormatter = {+ let f = DateFormatter()+ f.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSS"+ return f+ }()++ var body: some View {+ VStack(spacing: 0) {+ // Resize handle — uses global Y to avoid layout feedback jitter+ Rectangle()+ .fill(Color(nsColor: .separatorColor))+ .frame(height: 5)+ .contentShape(Rectangle())+ .onHover { hovering in+ if hovering { NSCursor.resizeUpDown.push() }+ else { NSCursor.pop() }+ }+ .gesture(+ DragGesture(minimumDistance: 1, coordinateSpace: .global)+ .onChanged { value in+ if dragStartY == nil {+ dragStartY = value.startLocation.y+ dragStartHeight = panelHeight+ }+ let delta = value.location.y - (dragStartY ?? value.startLocation.y)+ panelHeight = max(minHeight, min(maxHeight, (dragStartHeight ?? 120) - delta))+ }+ .onEnded { _ in+ dragStartY = nil+ dragStartHeight = nil+ }+ )++ ScrollViewReader { proxy in+ ScrollView {+ LazyVStack(alignment: .leading, spacing: 0) {+ ForEach(appState.queryLog) { entry in+ VStack(alignment: .leading, spacing: 2) {+ // Timestamp + duration+ let ts = Self.timestampFormatter.string(from: entry.timestamp)+ let durationStr = entry.duration.map { String(format: " (%.1fms)", $0 * 1000) } ?? ""+ Text("-- \(ts)\(durationStr)")+ .font(.system(size: 11, design: .monospaced))+ .foregroundStyle(.green)++ // SQL with syntax highlighting+ Text(syntaxHighlighting ? entry.highlightedColored : entry.highlightedPlain)+ .font(.system(size: 12, design: .monospaced))+ .textSelection(.enabled)+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 4)+ .id(entry.id)+ }+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ }+ .onChange(of: appState.queryLog.count) { _, _ in+ if let last = appState.queryLog.last {+ proxy.scrollTo(last.id, anchor: .bottom)+ }+ }+ }+ .frame(height: panelHeight)+ .background(Color(nsColor: .textBackgroundColor))++ // Bottom toolbar+ Divider()+ HStack(spacing: 12) {+ Button {+ appState.clearQueryLog()+ } label: {+ Image(systemName: "trash")+ .font(.system(size: 11))+ }+ .buttonStyle(.plain)+ .foregroundStyle(.secondary)+ .help("Clear log")++ Toggle(isOn: $syntaxHighlighting) {+ Text("Enable syntax highlighting")+ .font(.system(size: 11))+ }+ .toggleStyle(.checkbox)+ .controlSize(.small)++ Spacer()+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 4)+ .frame(height: 26)+ .background(Color(nsColor: .windowBackgroundColor))+ }+ }++}++// MARK: - Commit Preview Sheet++struct CommitPreviewSheet: View {+ @ObservedObject var viewModel: DataGridViewState+ @Environment(\.dismiss) private var dismiss++ var body: some View {+ VStack(spacing: 0) {+ HStack {+ Text("Review Changes")+ .font(.headline)+ Spacer()+ Text("\(viewModel.commitSQL.count) statement(s) (parameterized)")+ .font(.subheadline)+ .foregroundStyle(.secondary)+ }+ .padding()++ Divider()++ ScrollView {+ VStack(alignment: .leading, spacing: 8) {+ ForEach(Array(viewModel.commitSQL.enumerated()), id: \.offset) { _, statement in+ Text(statement.sql + (statement.parameters.isEmpty ? "" : "\n-- params: \(statement.parameters.map(\.description).joined(separator: ", "))"))+ .font(.system(size: 13, design: .monospaced))+ .textSelection(.enabled)+ .padding(8)+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(Color(nsColor: .controlBackgroundColor))+ .clipShape(RoundedRectangle(cornerRadius: 4))+ }+ }+ .padding()+ }+ .frame(minHeight: 150, maxHeight: 300)++ if let error = viewModel.commitError {+ ScrollView {+ HStack(alignment: .top, spacing: 8) {+ Image(systemName: "exclamationmark.triangle.fill")+ .foregroundStyle(.red)+ .padding(.top, 2)+ Text(error)+ .font(.system(size: 12, design: .monospaced))+ .foregroundStyle(.red)+ .textSelection(.enabled)+ .frame(maxWidth: .infinity, alignment: .leading)+ }+ .padding(.horizontal)+ .padding(.vertical, 8)+ }+ .frame(maxHeight: 120)+ }++ Divider()++ HStack {+ Button("Copy SQL") {+ let allSQL = viewModel.commitSQL.map { $0.sql }.joined(separator: "\n")+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(allSQL, forType: .string)+ }+ .controlSize(.small)++ Spacer()++ Button("Cancel") { dismiss() }+ .keyboardShortcut(.cancelAction)++ Button("Execute") {+ Task { await viewModel.executeCommit() }+ }+ .buttonStyle(.borderedProminent)+ .keyboardShortcut(.defaultAction)+ .disabled(viewModel.isCommitting)+ }+ .padding()+ }+ .frame(width: 550)+ }+}++// MARK: - NSView Helper++private extension NSView {+ func findRowView() -> NSTableRowView? {+ var current: NSView? = superview+ while let view = current {+ if let rowView = view as? NSTableRowView {+ return rowView+ }+ current = view.superview+ }+ return nil+ }+}diff --git a/macos/Presentation/Views/ERDiagram/ERDiagramCanvas.swift b/macos/Presentation/Views/ERDiagram/ERDiagramCanvas.swiftnew file mode 100644index 0000000..a23343e--- /dev/null+++ b/macos/Presentation/Views/ERDiagram/ERDiagramCanvas.swift@@ -0,0 +1,500 @@+// ERDiagramCanvas.swift+// Gridex+//+// Custom NSView that renders ER diagram tables and relationships+// using CoreGraphics for high-performance drawing.++import AppKit++final class ERDiagramCanvas: NSView {++ // MARK: - Constants++ static let cardWidth: CGFloat = 220+ static let headerHeight: CGFloat = 32+ static let rowHeight: CGFloat = 22+ static let cornerRadius: CGFloat = 8++ static func cardHeight(for table: ERTable) -> CGFloat {+ headerHeight + CGFloat(table.columns.count) * rowHeight + 4 // 4pt bottom padding+ }++ // MARK: - State++ private unowned var viewModel: ERDiagramViewModel+ private var dragTableId: String?+ private var dragOffset: CGPoint = .zero+ private var hoveredTableId: String?+ private var isPanning = false+ private var panOrigin: NSPoint = .zero+ private var isSpaceDown = false++ // MARK: - Colors (adaptive)++ private var cardBackground: NSColor { .controlBackgroundColor }+ private var cardBorder: NSColor { .separatorColor }+ private var headerBackground: NSColor { NSColor.controlAccentColor.withAlphaComponent(0.12) }+ private var headerText: NSColor { .labelColor }+ private var columnText: NSColor { .labelColor }+ private var typeText: NSColor { .secondaryLabelColor }+ private var pkBadge: NSColor { NSColor.systemYellow.withAlphaComponent(0.85) }+ private var fkBadge: NSColor { NSColor.systemBlue.withAlphaComponent(0.7) }+ private var relationshipLine: NSColor { NSColor.systemBlue.withAlphaComponent(0.5) }+ private var canvasBackground: NSColor { NSColor(calibratedWhite: 0.13, alpha: 1.0) }+ private var canvasBackgroundLight: NSColor { NSColor(calibratedWhite: 0.95, alpha: 1.0) }+ private var gridColor: NSColor { NSColor.separatorColor.withAlphaComponent(0.15) }++ // MARK: - Init++ init(viewModel: ERDiagramViewModel) {+ self.viewModel = viewModel+ super.init(frame: NSRect(x: 0, y: 0, width: 4000, height: 4000))+ wantsLayer = true+ }++ @available(*, unavailable)+ required init?(coder: NSCoder) { fatalError() }++ // MARK: - Drawing++ override var isFlipped: Bool { true }++ override func draw(_ dirtyRect: NSRect) {+ guard let ctx = NSGraphicsContext.current?.cgContext else { return }++ // Resize canvas to fit all tables + padding.+ // Use the visible area (accounting for magnification) as a minimum+ // so the background always fills the viewport even when zoomed out.+ let tableBounds = viewModel.tableBounds()+ let scrollView = enclosingScrollView+ let visibleW = (scrollView?.contentView.bounds.width ?? 2000) / max(scrollView?.magnification ?? 1, 0.1)+ let visibleH = (scrollView?.contentView.bounds.height ?? 2000) / max(scrollView?.magnification ?? 1, 0.1)+ let needed = NSSize(+ width: max(visibleW + 200, tableBounds.maxX + 400),+ height: max(visibleH + 200, tableBounds.maxY + 400)+ )+ if abs(frame.size.width - needed.width) > 10 || abs(frame.size.height - needed.height) > 10 {+ setFrameSize(needed)+ }++ // Background+ let isDark = effectiveAppearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua+ let bg = isDark ? canvasBackground : canvasBackgroundLight+ ctx.setFillColor(bg.cgColor)+ ctx.fill(dirtyRect)++ // Draw grid dots+ drawGrid(ctx: ctx, rect: dirtyRect, isDark: isDark)++ // Draw relationships first (under cards)+ for rel in viewModel.relationships {+ drawRelationship(ctx: ctx, rel: rel, isDark: isDark)+ }++ // Draw table cards+ for table in viewModel.tables {+ drawTableCard(ctx: ctx, table: table, isDark: isDark)+ }+ }++ // MARK: - Grid++ private func drawGrid(ctx: CGContext, rect: NSRect, isDark: Bool) {+ let spacing: CGFloat = 30+ let dotSize: CGFloat = 1.2+ ctx.setFillColor(gridColor.cgColor)++ let startX = floor(rect.minX / spacing) * spacing+ let startY = floor(rect.minY / spacing) * spacing+ var x = startX+ while x < rect.maxX {+ var y = startY+ while y < rect.maxY {+ ctx.fillEllipse(in: CGRect(x: x - dotSize / 2, y: y - dotSize / 2, width: dotSize, height: dotSize))+ y += spacing+ }+ x += spacing+ }+ }++ // MARK: - Table Card++ private func drawTableCard(ctx: CGContext, table: ERTable, isDark: Bool) {+ let cardW = Self.cardWidth+ let cardH = Self.cardHeight(for: table)+ let rect = CGRect(origin: table.position, size: CGSize(width: cardW, height: cardH))+ let isSelected = viewModel.selectedTableId == table.id+ let isHovered = hoveredTableId == table.id++ // Shadow+ ctx.saveGState()+ let shadowColor = NSColor.black.withAlphaComponent(isDark ? 0.5 : 0.15)+ ctx.setShadow(offset: CGSize(width: 0, height: 2), blur: isSelected ? 12 : 6, color: shadowColor.cgColor)++ // Card body+ let cardPath = CGPath(roundedRect: rect, cornerWidth: Self.cornerRadius, cornerHeight: Self.cornerRadius, transform: nil)+ let bgColor = isDark+ ? NSColor(calibratedWhite: 0.18, alpha: 1.0)+ : NSColor(calibratedWhite: 1.0, alpha: 1.0)+ ctx.setFillColor(bgColor.cgColor)+ ctx.addPath(cardPath)+ ctx.fillPath()+ ctx.restoreGState()++ // Border+ let borderColor: NSColor = isSelected+ ? .controlAccentColor+ : (isHovered ? .controlAccentColor.withAlphaComponent(0.5) : cardBorder)+ ctx.setStrokeColor(borderColor.cgColor)+ ctx.setLineWidth(isSelected ? 2.0 : 1.0)+ ctx.addPath(cardPath)+ ctx.strokePath()++ // Header background+ let headerRect = CGRect(x: rect.minX, y: rect.minY, width: cardW, height: Self.headerHeight)+ let headerPath = CGMutablePath()+ headerPath.move(to: CGPoint(x: rect.minX + Self.cornerRadius, y: rect.minY))+ headerPath.addLine(to: CGPoint(x: rect.maxX - Self.cornerRadius, y: rect.minY))+ headerPath.addQuadCurve(to: CGPoint(x: rect.maxX, y: rect.minY + Self.cornerRadius),+ control: CGPoint(x: rect.maxX, y: rect.minY))+ headerPath.addLine(to: CGPoint(x: rect.maxX, y: headerRect.maxY))+ headerPath.addLine(to: CGPoint(x: rect.minX, y: headerRect.maxY))+ headerPath.addLine(to: CGPoint(x: rect.minX, y: rect.minY + Self.cornerRadius))+ headerPath.addQuadCurve(to: CGPoint(x: rect.minX + Self.cornerRadius, y: rect.minY),+ control: CGPoint(x: rect.minX, y: rect.minY))+ headerPath.closeSubpath()++ let accentColor = isSelected ? NSColor.controlAccentColor.withAlphaComponent(0.2) : headerBackground+ ctx.setFillColor(accentColor.cgColor)+ ctx.addPath(headerPath)+ ctx.fillPath()++ // Header separator+ ctx.setStrokeColor(cardBorder.cgColor)+ ctx.setLineWidth(0.5)+ ctx.move(to: CGPoint(x: rect.minX, y: headerRect.maxY))+ ctx.addLine(to: CGPoint(x: rect.maxX, y: headerRect.maxY))+ ctx.strokePath()++ // Table name+ let nameStr = NSAttributedString(string: table.name, attributes: [+ .font: NSFont.systemFont(ofSize: 12, weight: .semibold),+ .foregroundColor: headerText+ ])+ nameStr.draw(at: CGPoint(x: rect.minX + 10, y: rect.minY + 8))++ // Column count badge+ let countStr = NSAttributedString(string: "\(table.columns.count)", attributes: [+ .font: NSFont.systemFont(ofSize: 9, weight: .medium),+ .foregroundColor: NSColor.secondaryLabelColor+ ])+ let countSize = countStr.size()+ let badgeRect = CGRect(x: rect.maxX - countSize.width - 16, y: rect.minY + 9,+ width: countSize.width + 8, height: 14)+ let badgePath = CGPath(roundedRect: badgeRect, cornerWidth: 4, cornerHeight: 4, transform: nil)+ ctx.setFillColor(NSColor.secondaryLabelColor.withAlphaComponent(0.1).cgColor)+ ctx.addPath(badgePath)+ ctx.fillPath()+ countStr.draw(at: CGPoint(x: badgeRect.minX + 4, y: badgeRect.minY + 1))++ // Columns+ var y = rect.minY + Self.headerHeight + 2+ for col in table.columns {+ drawColumnRow(ctx: ctx, col: col, x: rect.minX, y: y, width: cardW, isDark: isDark)+ y += Self.rowHeight+ }+ }++ private func drawColumnRow(ctx: CGContext, col: ERColumn, x: CGFloat, y: CGFloat, width: CGFloat, isDark: Bool) {+ let leftPad: CGFloat = 10+ let iconWidth: CGFloat = 18++ // PK/FK icon+ if col.isPrimaryKey {+ let badge = NSAttributedString(string: "PK", attributes: [+ .font: NSFont.systemFont(ofSize: 8, weight: .bold),+ .foregroundColor: pkBadge+ ])+ badge.draw(at: CGPoint(x: x + leftPad, y: y + 4))+ } else if col.foreignKey != nil {+ let badge = NSAttributedString(string: "FK", attributes: [+ .font: NSFont.systemFont(ofSize: 8, weight: .bold),+ .foregroundColor: fkBadge+ ])+ badge.draw(at: CGPoint(x: x + leftPad, y: y + 4))+ }++ // Column name+ let nameX = x + leftPad + iconWidth+ let name = NSAttributedString(string: col.name, attributes: [+ .font: NSFont.systemFont(ofSize: 11, weight: col.isPrimaryKey ? .medium : .regular),+ .foregroundColor: columnText+ ])+ let nameSize = name.size()+ name.draw(in: CGRect(x: nameX, y: y + 3, width: width - iconWidth - 80, height: nameSize.height))++ // Data type — right aligned+ let shortType = abbreviateType(col.dataType)+ let typeStr = NSAttributedString(string: shortType, attributes: [+ .font: NSFont.monospacedSystemFont(ofSize: 10, weight: .regular),+ .foregroundColor: typeText+ ])+ let typeSize = typeStr.size()+ typeStr.draw(at: CGPoint(x: x + width - typeSize.width - 10, y: y + 4))++ // Nullable dot+ if !col.isNullable {+ ctx.setFillColor(NSColor.systemOrange.withAlphaComponent(0.6).cgColor)+ ctx.fillEllipse(in: CGRect(x: x + width - typeSize.width - 18, y: y + 8, width: 5, height: 5))+ }+ }++ private func abbreviateType(_ type: String) -> String {+ let t = type.lowercased()+ if t.hasPrefix("character varying") || t.hasPrefix("varchar") {+ let num = t.components(separatedBy: CharacterSet.decimalDigits.inverted)+ .joined().prefix(6)+ return num.isEmpty ? "varchar" : "varchar(\(num))"+ }+ if t.hasPrefix("timestamp") { return "timestamp" }+ if t.hasPrefix("double") { return "double" }+ if t == "integer" { return "int" }+ if t == "boolean" { return "bool" }+ if t == "bigint" { return "bigint" }+ if t == "smallint" { return "smallint" }+ if t == "text" { return "text" }+ if t == "uuid" { return "uuid" }+ if t == "jsonb" { return "jsonb" }+ if t == "json" { return "json" }+ return String(type.prefix(16))+ }++ // MARK: - Relationships++ private func drawRelationship(ctx: CGContext, rel: ERRelationship, isDark: Bool) {+ guard let source = viewModel.tables.first(where: { $0.name == rel.sourceTable }),+ let target = viewModel.tables.first(where: { $0.name == rel.targetTable }) else { return }++ let sourceColIdx = source.columns.firstIndex(where: { $0.name == rel.sourceColumn }) ?? 0+ let targetColIdx = target.columns.firstIndex(where: { $0.name == rel.targetColumn }) ?? 0++ let cardW = Self.cardWidth++ // Source point: right edge of source table at the FK column row+ let sourceY = source.position.y + Self.headerHeight + CGFloat(sourceColIdx) * Self.rowHeight + Self.rowHeight / 2+ // Target point: left edge of target table at the PK column row+ let targetY = target.position.y + Self.headerHeight + CGFloat(targetColIdx) * Self.rowHeight + Self.rowHeight / 2++ // Determine which sides to connect from+ let sourceRight = source.position.x + cardW+ let targetRight = target.position.x + cardW++ let (sx, tx): (CGFloat, CGFloat)+ if source.position.x > target.position.x + cardW {+ // Source is to the right of target+ sx = source.position.x+ tx = targetRight+ } else if target.position.x > sourceRight {+ // Target is to the right of source+ sx = sourceRight+ tx = target.position.x+ } else {+ // Overlapping horizontally — connect from sides that make sense+ sx = sourceRight+ tx = targetRight+ }++ // Draw bezier curve+ let midX = (sx + tx) / 2+ let cp1 = CGPoint(x: midX, y: sourceY)+ let cp2 = CGPoint(x: midX, y: targetY)++ ctx.setStrokeColor(relationshipLine.cgColor)+ ctx.setLineWidth(1.5)+ ctx.setLineDash(phase: 0, lengths: [])++ ctx.move(to: CGPoint(x: sx, y: sourceY))+ ctx.addCurve(to: CGPoint(x: tx, y: targetY), control1: cp1, control2: cp2)+ ctx.strokePath()++ // Draw arrowhead at target+ drawArrowhead(ctx: ctx, at: CGPoint(x: tx, y: targetY), from: cp2)++ // Draw "1" and "N" cardinality markers+ drawCardinalityMarker(ctx: ctx, text: "N", at: CGPoint(x: sx, y: sourceY), side: sx == sourceRight ? .right : .left)+ drawCardinalityMarker(ctx: ctx, text: "1", at: CGPoint(x: tx, y: targetY), side: tx == target.position.x ? .left : .right)+ }++ private enum Side { case left, right }++ private func drawCardinalityMarker(ctx: CGContext, text: String, at point: CGPoint, side: Side) {+ let offset: CGFloat = side == .right ? 6 : -14+ let str = NSAttributedString(string: text, attributes: [+ .font: NSFont.systemFont(ofSize: 9, weight: .bold),+ .foregroundColor: relationshipLine+ ])+ str.draw(at: CGPoint(x: point.x + offset, y: point.y - 14))+ }++ private func drawArrowhead(ctx: CGContext, at point: CGPoint, from control: CGPoint) {+ let angle = atan2(point.y - control.y, point.x - control.x)+ let arrowLen: CGFloat = 8+ let arrowAngle: CGFloat = .pi / 6++ ctx.setFillColor(relationshipLine.cgColor)+ ctx.move(to: point)+ ctx.addLine(to: CGPoint(+ x: point.x - arrowLen * cos(angle - arrowAngle),+ y: point.y - arrowLen * sin(angle - arrowAngle)+ ))+ ctx.addLine(to: CGPoint(+ x: point.x - arrowLen * cos(angle + arrowAngle),+ y: point.y - arrowLen * sin(angle + arrowAngle)+ ))+ ctx.closePath()+ ctx.fillPath()+ }++ // MARK: - Mouse Events++ override func mouseDown(with event: NSEvent) {+ let point = convert(event.locationInWindow, from: nil)++ // Space or Cmd + click = pan the canvas+ if isSpaceDown || event.modifierFlags.contains(.command) {+ isPanning = true+ panOrigin = event.locationInWindow+ NSCursor.closedHand.push()+ return+ }++ viewModel.selectedTableId = nil++ for table in viewModel.tables.reversed() {+ let cardH = Self.cardHeight(for: table)+ let rect = CGRect(origin: table.position, size: CGSize(width: Self.cardWidth, height: cardH))+ if rect.contains(point) {+ if event.clickCount == 2 {+ NotificationCenter.default.post(+ name: .erDiagramOpenTable,+ object: nil,+ userInfo: ["tableName": table.name, "schema": table.schema as Any]+ )+ return+ }+ dragTableId = table.id+ dragOffset = CGPoint(x: point.x - table.position.x, y: point.y - table.position.y)+ viewModel.selectedTableId = table.id+ needsDisplay = true+ return+ }+ }++ // Click on empty space = also pan+ isPanning = true+ panOrigin = event.locationInWindow+ NSCursor.closedHand.push()+ }++ override func mouseDragged(with event: NSEvent) {+ if isPanning {+ guard let clipView = enclosingScrollView?.contentView else { return }+ let current = event.locationInWindow+ let dx = panOrigin.x - current.x+ let dy = current.y - panOrigin.y // flipped+ var origin = clipView.bounds.origin+ origin.x += dx+ origin.y += dy+ clipView.scroll(to: origin)+ enclosingScrollView?.reflectScrolledClipView(clipView)+ panOrigin = current+ return+ }++ guard let id = dragTableId else { return }+ let point = convert(event.locationInWindow, from: nil)+ let newPos = CGPoint(+ x: max(0, point.x - dragOffset.x),+ y: max(0, point.y - dragOffset.y)+ )+ viewModel.moveTable(id: id, to: newPos)+ }++ override func mouseUp(with event: NSEvent) {+ if isPanning {+ isPanning = false+ NSCursor.pop()+ }+ dragTableId = nil+ }++ override var acceptsFirstResponder: Bool { true }++ override func keyDown(with event: NSEvent) {+ if event.keyCode == 49 { // Space+ if !isSpaceDown {+ isSpaceDown = true+ NSCursor.openHand.push()+ }+ } else {+ super.keyDown(with: event)+ }+ }++ override func keyUp(with event: NSEvent) {+ if event.keyCode == 49 {+ isSpaceDown = false+ NSCursor.pop()+ } else {+ super.keyUp(with: event)+ }+ }++ override func scrollWheel(with event: NSEvent) {+ guard event.modifierFlags.contains(.command),+ let scrollView = enclosingScrollView else {+ super.scrollWheel(with: event)+ return+ }++ // Cmd+scroll = zoom centered on cursor+ let delta = event.scrollingDeltaY * (event.hasPreciseScrollingDeltas ? 0.005 : 0.05)+ let newMag = min(scrollView.maxMagnification,+ max(scrollView.minMagnification,+ scrollView.magnification + delta))+ scrollView.magnification = newMag+ viewModel.zoom = Float(newMag)+ }++ override func mouseMoved(with event: NSEvent) {+ let point = convert(event.locationInWindow, from: nil)+ var newHovered: String?+ for table in viewModel.tables.reversed() {+ let cardH = Self.cardHeight(for: table)+ let rect = CGRect(origin: table.position, size: CGSize(width: Self.cardWidth, height: cardH))+ if rect.contains(point) {+ newHovered = table.id+ break+ }+ }+ if newHovered != hoveredTableId {+ hoveredTableId = newHovered+ needsDisplay = true+ }+ }++ override func updateTrackingAreas() {+ super.updateTrackingAreas()+ for area in trackingAreas { removeTrackingArea(area) }+ addTrackingArea(NSTrackingArea(+ rect: bounds,+ options: [.activeInKeyWindow, .mouseMoved, .inVisibleRect],+ owner: self+ ))+ }++}++extension Notification.Name {+ static let erDiagramOpenTable = Notification.Name("Gridex.erDiagramOpenTable")+}diff --git a/macos/Presentation/Views/ERDiagram/ERDiagramView.swift b/macos/Presentation/Views/ERDiagram/ERDiagramView.swiftnew file mode 100644index 0000000..26a86a3--- /dev/null+++ b/macos/Presentation/Views/ERDiagram/ERDiagramView.swift@@ -0,0 +1,151 @@+// ERDiagramView.swift+// Gridex+//+// SwiftUI wrapper for the ER diagram canvas.++import SwiftUI++struct ERDiagramView: View {+ let schema: String?+ @EnvironmentObject private var appState: AppState+ @StateObject private var viewModel = ERDiagramViewModel()++ var body: some View {+ ZStack {+ if viewModel.isLoading {+ VStack(spacing: 12) {+ ProgressView()+ .scaleEffect(0.8)+ Text("Loading schema…")+ .font(.system(size: 12))+ .foregroundStyle(.secondary)+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ } else if viewModel.tables.isEmpty {+ VStack(spacing: 8) {+ Image(systemName: "rectangle.3.group")+ .font(.system(size: 32))+ .foregroundStyle(.quaternary)+ Text("No tables found")+ .font(.system(size: 13))+ .foregroundStyle(.secondary)+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ } else {+ ERDiagramCanvasWrapper(viewModel: viewModel)+ }++ // Toolbar overlay — top-right+ if !viewModel.isLoading && !viewModel.tables.isEmpty {+ VStack {+ HStack {+ Spacer()+ diagramToolbar+ }+ Spacer()+ }+ .padding(12)+ }+ }+ .background(Color(nsColor: .controlBackgroundColor))+ .task {+ guard let adapter = appState.activeAdapter else { return }+ await viewModel.load(adapter: adapter, schema: schema)+ }+ }++ private var diagramToolbar: some View {+ HStack(spacing: 4) {+ Button(action: { viewModel.zoomIn() }) {+ Image(systemName: "plus.magnifyingglass")+ .frame(width: 28, height: 28)+ }+ .buttonStyle(.borderless)++ Text("\(Int(viewModel.zoom * 100))%")+ .font(.system(size: 10, weight: .medium, design: .monospaced))+ .foregroundStyle(.secondary)+ .frame(width: 38)++ Button(action: { viewModel.zoomOut() }) {+ Image(systemName: "minus.magnifyingglass")+ .frame(width: 28, height: 28)+ }+ .buttonStyle(.borderless)++ Divider()+ .frame(height: 16)++ Button(action: { viewModel.fitToView() }) {+ Image(systemName: "arrow.up.left.and.arrow.down.right")+ .frame(width: 28, height: 28)+ }+ .buttonStyle(.borderless)+ .help("Fit to view")++ Button(action: { viewModel.autoLayout() }) {+ Image(systemName: "rectangle.3.group")+ .frame(width: 28, height: 28)+ }+ .buttonStyle(.borderless)+ .help("Auto layout")+ }+ .padding(.horizontal, 8)+ .padding(.vertical, 4)+ .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 8))+ }+}++// MARK: - NSViewRepresentable wrapper++struct ERDiagramCanvasWrapper: NSViewRepresentable {+ @ObservedObject var viewModel: ERDiagramViewModel++ func makeNSView(context: Context) -> NSScrollView {+ let canvas = ERDiagramCanvas(viewModel: viewModel)+ viewModel.canvas = canvas++ let scrollView = NSScrollView()+ scrollView.documentView = canvas+ scrollView.hasVerticalScroller = true+ scrollView.hasHorizontalScroller = true+ scrollView.allowsMagnification = true+ scrollView.minMagnification = 0.1+ scrollView.maxMagnification = 3.0+ scrollView.magnification = CGFloat(viewModel.zoom)+ scrollView.backgroundColor = .clear+ scrollView.drawsBackground = false+ scrollView.scrollerStyle = .overlay+ scrollView.autohidesScrollers = true+ scrollView.contentView.postsBoundsChangedNotifications = true++ // Observe magnification changes from scroll view+ NotificationCenter.default.addObserver(+ forName: NSScrollView.didEndLiveMagnifyNotification,+ object: scrollView,+ queue: .main+ ) { _ in+ Task { @MainActor in+ viewModel.zoom = Float(scrollView.magnification)+ }+ }++ // Initial layout after a short delay so the scroll view has its frame+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {+ if viewModel.needsInitialLayout {+ viewModel.autoLayout()+ viewModel.fitToView()+ viewModel.needsInitialLayout = false+ }+ }++ return scrollView+ }++ func updateNSView(_ scrollView: NSScrollView, context: Context) {+ if abs(scrollView.magnification - CGFloat(viewModel.zoom)) > 0.01 {+ scrollView.magnification = CGFloat(viewModel.zoom)+ }+ (scrollView.documentView as? ERDiagramCanvas)?.needsDisplay = true+ }+}diff --git a/macos/Presentation/Views/ERDiagram/ERDiagramViewModel.swift b/macos/Presentation/Views/ERDiagram/ERDiagramViewModel.swiftnew file mode 100644index 0000000..8fdecb9--- /dev/null+++ b/macos/Presentation/Views/ERDiagram/ERDiagramViewModel.swift@@ -0,0 +1,242 @@+// ERDiagramViewModel.swift+// Gridex+//+// Loads table metadata and manages layout state for the ER diagram.++import SwiftUI+import AppKit++// MARK: - Models++struct ERTable: Identifiable {+ let id: String // table name+ let name: String+ let schema: String?+ let columns: [ERColumn]+ var position: CGPoint = .zero++ var primaryKeys: [ERColumn] { columns.filter(\.isPrimaryKey) }+ var foreignKeys: [ERColumn] { columns.filter { $0.foreignKey != nil } }+}++struct ERColumn: Identifiable {+ let id: String // column name+ let name: String+ let dataType: String+ let isPrimaryKey: Bool+ let isNullable: Bool+ let foreignKey: ERForeignKey?+}++struct ERForeignKey {+ let referencedTable: String+ let referencedColumn: String+}++struct ERRelationship: Identifiable {+ var id: String { "\(sourceTable).\(sourceColumn)->\(targetTable).\(targetColumn)" }+ let sourceTable: String+ let sourceColumn: String+ let targetTable: String+ let targetColumn: String+ let name: String?+}++// MARK: - ViewModel++@MainActor+final class ERDiagramViewModel: ObservableObject {+ @Published var tables: [ERTable] = []+ @Published var relationships: [ERRelationship] = []+ @Published var isLoading = false+ @Published var loadError: String?+ @Published var zoom: Float = 1.0+ @Published var selectedTableId: String?++ var needsInitialLayout = true+ weak var canvas: ERDiagramCanvas?++ // MARK: - Load++ func load(adapter: any DatabaseAdapter, schema: String?) async {+ isLoading = true+ defer { isLoading = false }++ do {+ let tableInfos = try await adapter.listTables(schema: schema)+ var erTables: [ERTable] = []+ var erRelationships: [ERRelationship] = []++ // Fetch all table descriptions in parallel+ try await withThrowingTaskGroup(of: (TableDescription?).self) { group in+ for info in tableInfos where info.type == .table {+ group.addTask {+ try? await adapter.describeTable(name: info.name, schema: schema)+ }+ }+ for try await desc in group {+ guard let desc else { continue }++ // Build FK lookup for this table+ var fkLookup: [String: ERForeignKey] = [:]+ for fk in desc.foreignKeys {+ for (i, col) in fk.columns.enumerated() {+ let refCol = i < fk.referencedColumns.count ? fk.referencedColumns[i] : fk.referencedColumns.first ?? ""+ fkLookup[col] = ERForeignKey(referencedTable: fk.referencedTable, referencedColumn: refCol)++ erRelationships.append(ERRelationship(+ sourceTable: desc.name,+ sourceColumn: col,+ targetTable: fk.referencedTable,+ targetColumn: refCol,+ name: fk.name+ ))+ }+ }++ let columns = desc.columns.sorted(by: { $0.ordinalPosition < $1.ordinalPosition }).map { col in+ ERColumn(+ id: col.name,+ name: col.name,+ dataType: col.dataType,+ isPrimaryKey: col.isPrimaryKey,+ isNullable: col.isNullable,+ foreignKey: fkLookup[col.name]+ )+ }++ erTables.append(ERTable(+ id: desc.name,+ name: desc.name,+ schema: desc.schema,+ columns: columns+ ))+ }+ }++ tables = erTables.sorted(by: { $0.name < $1.name })+ relationships = erRelationships+ needsInitialLayout = true+ } catch {+ loadError = error.localizedDescription+ }+ }++ // MARK: - Layout++ func autoLayout() {+ guard !tables.isEmpty else { return }++ // Build adjacency: tables connected by FK+ var adjacency: [String: Set<String>] = [:]+ for t in tables { adjacency[t.name] = [] }+ for r in relationships {+ adjacency[r.sourceTable, default: []].insert(r.targetTable)+ adjacency[r.targetTable, default: []].insert(r.sourceTable)+ }++ // Topological sort / layered layout (Sugiyama-lite)+ var layers: [[String]] = []+ var assigned: Set<String> = []++ // Start with tables that have no incoming FKs (root/referenced tables)+ let targets = Set(relationships.map(\.targetTable))+ let sources = Set(relationships.map(\.sourceTable))+ var roots = tables.filter { targets.contains($0.name) && !sources.contains($0.name) }.map(\.name)+ if roots.isEmpty {+ // No pure roots — pick tables with most references+ roots = tables.sorted { (adjacency[$0.name]?.count ?? 0) > (adjacency[$1.name]?.count ?? 0) }+ .prefix(max(1, tables.count / 4)).map(\.name)+ }++ // BFS layering+ var queue = roots+ assigned.formUnion(roots)+ while !queue.isEmpty {+ layers.append(queue)+ var next: [String] = []+ for node in queue {+ for neighbor in (adjacency[node] ?? []) where !assigned.contains(neighbor) {+ next.append(neighbor)+ assigned.insert(neighbor)+ }+ }+ queue = next+ }+ // Any unassigned tables go in a final layer+ let remaining = tables.filter { !assigned.contains($0.name) }.map(\.name)+ if !remaining.isEmpty { layers.append(remaining) }++ // Position tables in a grid+ let cardW: CGFloat = ERDiagramCanvas.cardWidth+ let hGap: CGFloat = 80+ let vGap: CGFloat = 60+ let padding: CGFloat = 60++ var x = padding+ for layer in layers {+ var y = padding+ for name in layer {+ if let idx = tables.firstIndex(where: { $0.name == name }) {+ let h = ERDiagramCanvas.cardHeight(for: tables[idx])+ tables[idx].position = CGPoint(x: x, y: y)+ y += h + vGap+ }+ }+ x += cardW + hGap+ }++ canvas?.needsDisplay = true+ objectWillChange.send()+ }++ func fitToView() {+ guard let canvas, let scrollView = canvas.enclosingScrollView, !tables.isEmpty else { return }++ let bounds = tableBounds()+ let visibleSize = scrollView.contentView.bounds.size+ guard bounds.width > 0 && bounds.height > 0 else { return }++ let scaleX = visibleSize.width / (bounds.width + 120)+ let scaleY = visibleSize.height / (bounds.height + 120)+ let newZoom = Float(min(scaleX, scaleY, 1.5))+ zoom = max(0.1, newZoom)+ scrollView.magnification = CGFloat(zoom)++ // Center+ let centerX = bounds.midX * CGFloat(zoom) - visibleSize.width / 2+ let centerY = bounds.midY * CGFloat(zoom) - visibleSize.height / 2+ scrollView.contentView.scroll(to: NSPoint(x: max(0, centerX), y: max(0, centerY)))+ }++ func zoomIn() {+ zoom = min(3.0, zoom + 0.15)+ canvas?.enclosingScrollView?.magnification = CGFloat(zoom)+ }++ func zoomOut() {+ zoom = max(0.1, zoom - 0.15)+ canvas?.enclosingScrollView?.magnification = CGFloat(zoom)+ }++ func tableBounds() -> CGRect {+ guard !tables.isEmpty else { return .zero }+ var minX = CGFloat.infinity, minY = CGFloat.infinity+ var maxX = -CGFloat.infinity, maxY = -CGFloat.infinity+ for t in tables {+ let h = ERDiagramCanvas.cardHeight(for: t)+ minX = min(minX, t.position.x)+ minY = min(minY, t.position.y)+ maxX = max(maxX, t.position.x + ERDiagramCanvas.cardWidth)+ maxY = max(maxY, t.position.y + h)+ }+ return CGRect(x: minX, y: minY, width: maxX - minX, height: maxY - minY)+ }++ func moveTable(id: String, to point: CGPoint) {+ if let idx = tables.firstIndex(where: { $0.id == id }) {+ tables[idx].position = point+ canvas?.needsDisplay = true+ }+ }+}diff --git a/macos/Presentation/Views/FilterBar/FilterBarSwiftUI.swift b/macos/Presentation/Views/FilterBar/FilterBarSwiftUI.swiftnew file mode 100644index 0000000..124828f--- /dev/null+++ b/macos/Presentation/Views/FilterBar/FilterBarSwiftUI.swift@@ -0,0 +1,152 @@+// FilterBarSwiftUI.swift+// Gridex+//+// Compact filter bar.++import SwiftUI++struct FilterBarSwiftUIView: View {+ let columns: [ColumnHeader]+ var initialFilter: FilterExpression?+ var onApply: (FilterExpression?) -> Void+ var onClear: () -> Void+ var onDismiss: (() -> Void)?++ @State private var conditions: [FilterUICondition] = [FilterUICondition()]+ @State private var combinator: FilterCombinator = .and+ @State private var didApplyInitial = false++ struct FilterUICondition: Identifiable {+ let id = UUID()+ var isEnabled: Bool = true+ var column: String = "" // "" = "Any column"+ var op: FilterOperator = .equal+ var value: String = ""+ }++ var body: some View {+ VStack(spacing: 0) {+ ForEach(Array(conditions.enumerated()), id: \.element.id) { index, _ in+ filterRow(index: index)+ if index < conditions.count - 1 {+ Divider().padding(.leading, 32)+ }+ }+ }+ .background(Color(nsColor: .controlBackgroundColor))+ .overlay(alignment: .bottom) { Divider() }+ .onAppear {+ guard !didApplyInitial, let filter = initialFilter, !filter.conditions.isEmpty else { return }+ didApplyInitial = true+ combinator = filter.combinator+ conditions = filter.conditions.map { cond in+ var value = ""+ if case .string(let v) = cond.value { value = v }+ return FilterUICondition(isEnabled: true, column: cond.column, op: cond.op, value: value)+ }+ }+ }++ @ViewBuilder+ private func filterRow(index: Int) -> some View {+ HStack(spacing: 6) {+ // Enable/disable checkbox+ Toggle("", isOn: $conditions[index].isEnabled)+ .toggleStyle(.checkbox)+ .labelsHidden()++ // Column picker+ Picker("", selection: $conditions[index].column) {+ Text("Any column").tag("")+ ForEach(columns, id: \.name) { col in+ Text(col.name).tag(col.name)+ }+ }+ .labelsHidden()+ .frame(width: 130)++ // Operator picker+ Picker("", selection: $conditions[index].op) {+ Text("=").tag(FilterOperator.equal)+ Text("!=").tag(FilterOperator.notEqual)+ Text(">").tag(FilterOperator.greaterThan)+ Text("<").tag(FilterOperator.lessThan)+ Text(">=").tag(FilterOperator.greaterOrEqual)+ Text("<=").tag(FilterOperator.lessOrEqual)+ Text("LIKE").tag(FilterOperator.like)+ Text("NOT LIKE").tag(FilterOperator.notLike)+ Text("IS NULL").tag(FilterOperator.isNull)+ Text("IS NOT NULL").tag(FilterOperator.isNotNull)+ }+ .labelsHidden()+ .frame(width: 80)++ // Value field (hidden for IS NULL / IS NOT NULL)+ if conditions[index].op != .isNull && conditions[index].op != .isNotNull {+ TextField("EMPTY", text: $conditions[index].value)+ .textFieldStyle(.roundedBorder)+ .font(.system(size: 12))+ .onSubmit { applyFilter() }+ } else {+ Spacer()+ }++ // Apply+ Button("Apply") { applyFilter() }+ .controlSize(.small)+ .buttonStyle(.borderedProminent)++ // Remove this row+ Button {+ if conditions.count > 1 {+ conditions.remove(at: index)+ } else {+ onClear()+ onDismiss?()+ }+ } label: {+ Image(systemName: "minus")+ .font(.system(size: 11, weight: .medium))+ .frame(width: 28, height: 28)+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .pointerCursor()+ .foregroundStyle(.secondary)++ // Add new row+ Button {+ conditions.insert(FilterUICondition(), at: index + 1)+ } label: {+ Image(systemName: "plus")+ .font(.system(size: 11, weight: .medium))+ .frame(width: 28, height: 28)+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .pointerCursor()+ .foregroundStyle(.secondary)+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 4)+ .frame(height: 30)+ }++ private func applyFilter() {+ let enabledConditions = conditions.filter { $0.isEnabled }+ let filterConditions = enabledConditions.compactMap { cond -> FilterCondition? in+ if cond.op == .isNull || cond.op == .isNotNull {+ if cond.column.isEmpty { return nil }+ return FilterCondition(column: cond.column, op: cond.op, value: .null)+ }+ guard !cond.value.isEmpty else { return nil }+ if cond.column.isEmpty { return nil }+ return FilterCondition(column: cond.column, op: cond.op, value: .string(cond.value))+ }+ if filterConditions.isEmpty {+ onApply(nil)+ } else {+ onApply(FilterExpression(conditions: filterConditions, combinator: combinator))+ }+ }+}diff --git a/macos/Presentation/Views/FunctionDetail/FunctionDetailView.swift b/macos/Presentation/Views/FunctionDetail/FunctionDetailView.swiftnew file mode 100644index 0000000..7686b65--- /dev/null+++ b/macos/Presentation/Views/FunctionDetail/FunctionDetailView.swift@@ -0,0 +1,432 @@+// FunctionDetailView.swift+// Gridex+//+// Displays and edits a database function's source code.++import SwiftUI+import AppKit++struct FunctionDetailView: View {+ let functionName: String+ let schema: String?+ var isProcedure: Bool = false++ @EnvironmentObject private var appState: AppState+ @State private var originalSource: String = ""+ @State private var editedSource: String = ""+ @State private var parameters: [String] = []+ @State private var isLoading = true+ @State private var errorMessage: String?+ @State private var isCommitting = false+ @State private var commitError: String?+ @State private var showCommitSuccess = false++ private var isDirty: Bool {+ editedSource != originalSource+ }++ private var routineKind: String {+ isProcedure ? "procedure" : "function"+ }++ var body: some View {+ VStack(spacing: 0) {+ headerBar+ Divider()+ contentArea+ }+ .task {+ await loadSource()+ }+ }++ // MARK: - Header++ private var headerBar: some View {+ HStack(spacing: 8) {+ Image(systemName: isProcedure ? "play.square" : "function")+ .font(.system(size: 12))+ .foregroundStyle(isProcedure ? .green : .blue)++ Text(functionName)+ .font(.system(size: 12, weight: .medium))+ .textSelection(.enabled)++ if isDirty {+ Text("Modified")+ .font(.system(size: 10, weight: .medium))+ .foregroundStyle(.white)+ .padding(.horizontal, 6)+ .padding(.vertical, 2)+ .background(Color.orange)+ .clipShape(Capsule())+ }++ Spacer()++ if let error = commitError {+ Text(error)+ .font(.system(size: 11))+ .foregroundStyle(.red)+ .lineLimit(1)+ }++ if showCommitSuccess {+ HStack(spacing: 3) {+ Image(systemName: "checkmark.circle.fill")+ .font(.system(size: 10))+ Text("Saved")+ .font(.system(size: 11))+ }+ .foregroundStyle(.green)+ }++ // Execute button (procedures only) — opens a new Query tab with EXEC template+ if isProcedure && !editedSource.isEmpty {+ Button(action: generateAndOpenExecTemplate) {+ HStack(spacing: 4) {+ Image(systemName: "play.fill")+ .font(.system(size: 10))+ Text("Execute")+ .font(.system(size: 11, weight: .medium))+ }+ }+ .buttonStyle(.plain)+ .foregroundStyle(.green)+ .help("Open a new Query tab with EXEC template")+ }++ if !editedSource.isEmpty {+ Button {+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(editedSource, forType: .string)+ } label: {+ HStack(spacing: 4) {+ Image(systemName: "doc.on.doc")+ .font(.system(size: 10))+ Text("Copy")+ .font(.system(size: 11))+ }+ }+ .buttonStyle(.plain)+ .foregroundStyle(.secondary)++ if isDirty {+ Button {+ editedSource = originalSource+ } label: {+ HStack(spacing: 4) {+ Image(systemName: "arrow.uturn.backward")+ .font(.system(size: 10))+ Text("Revert")+ .font(.system(size: 11))+ }+ }+ .buttonStyle(.plain)+ .foregroundStyle(.secondary)++ Button {+ Task { await commitChanges() }+ } label: {+ HStack(spacing: 4) {+ if isCommitting {+ ProgressView()+ .scaleEffect(0.5)+ .frame(width: 10, height: 10)+ } else {+ Image(systemName: "checkmark.circle")+ .font(.system(size: 10))+ }+ Text("Commit")+ .font(.system(size: 11, weight: .medium))+ }+ }+ .buttonStyle(.plain)+ .foregroundStyle(Color.accentColor)+ .disabled(isCommitting)+ }+ }+ }+ .padding(.horizontal, 16)+ .padding(.vertical, 8)+ .background(Color(nsColor: .windowBackgroundColor))+ }++ // MARK: - Content++ @ViewBuilder+ private var contentArea: some View {+ if isLoading {+ VStack {+ Spacer()+ ProgressView()+ .scaleEffect(0.8)+ Text("Loading \(routineKind) source...")+ .font(.system(size: 12))+ .foregroundStyle(.secondary)+ .padding(.top, 8)+ Spacer()+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ } else if let error = errorMessage {+ VStack {+ Spacer()+ Image(systemName: "exclamationmark.triangle")+ .font(.system(size: 24))+ .foregroundStyle(.secondary)+ Text(error)+ .font(.system(size: 12))+ .foregroundStyle(.secondary)+ .padding(.top, 8)+ Spacer()+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ } else if editedSource.isEmpty {+ VStack {+ Spacer()+ Image(systemName: "doc.text")+ .font(.system(size: 24))+ .foregroundStyle(.secondary)+ Text("No source code available")+ .font(.system(size: 12))+ .foregroundStyle(.secondary)+ .padding(.top, 8)+ Spacer()+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ } else {+ VStack(spacing: 0) {+ if isProcedure && !parameters.isEmpty {+ parameterSignatureBar+ Divider()+ }+ FunctionCodeEditor(text: $editedSource)+ }+ }+ }++ /// Compact parameter signature bar shown above the procedure source.+ private var parameterSignatureBar: some View {+ VStack(alignment: .leading, spacing: 2) {+ HStack(spacing: 6) {+ Image(systemName: "list.bullet.rectangle")+ .font(.system(size: 10))+ .foregroundStyle(.secondary)+ Text("Parameters (\(parameters.count))")+ .font(.system(size: 10, weight: .medium))+ .foregroundStyle(.secondary)+ Spacer()+ }+ .padding(.horizontal, 16)+ .padding(.top, 6)+ ScrollView(.horizontal, showsIndicators: false) {+ HStack(spacing: 6) {+ ForEach(parameters, id: \.self) { param in+ Text(param)+ .font(.system(size: 11, design: .monospaced))+ .padding(.horizontal, 6)+ .padding(.vertical, 2)+ .background(Color.primary.opacity(0.06))+ .clipShape(RoundedRectangle(cornerRadius: 3))+ .textSelection(.enabled)+ }+ }+ .padding(.horizontal, 16)+ .padding(.bottom, 6)+ }+ }+ .background(Color(nsColor: .controlBackgroundColor).opacity(0.5))+ }++ // MARK: - Actions++ private func loadSource() async {+ isLoading = true+ errorMessage = nil++ guard let adapter = appState.activeAdapter else {+ errorMessage = "No active connection"+ isLoading = false+ return+ }++ do {+ let source: String+ if isProcedure {+ source = try await adapter.getProcedureSource(name: functionName, schema: schema)+ // Fetch parameter signature in parallel (best-effort — ignore errors)+ parameters = (try? await adapter.listProcedureParameters(name: functionName, schema: schema)) ?? []+ } else {+ source = try await adapter.getFunctionSource(name: functionName, schema: schema)+ }+ originalSource = source+ editedSource = source+ isLoading = false+ } catch {+ errorMessage = error.localizedDescription+ isLoading = false+ }+ }++ /// Generate an EXEC template (e.g. "EXEC [dbo].[procname] @p1 = NULL, @p2 = NULL;")+ /// and open it in a new query editor tab, ready for the user to fill in values.+ private func generateAndOpenExecTemplate() {+ let schemaName = schema ?? "dbo"+ var sql = "EXEC [\(schemaName)].[\(functionName)]"++ // Parse param names from signature strings like "@p1 INT INPUT" or "@name NVARCHAR(100)"+ let paramAssignments: [String] = parameters.compactMap { sig in+ // First token is the @name+ let firstToken = sig.split(separator: " ", maxSplits: 1).first.map(String.init) ?? sig+ guard firstToken.hasPrefix("@") else { return nil }+ let isOutput = sig.uppercased().contains("OUTPUT")+ return " \(firstToken) = NULL\(isOutput ? " OUTPUT" : "")"+ }++ if !paramAssignments.isEmpty {+ sql += "\n" + paramAssignments.joined(separator: ",\n")+ }+ sql += ";"++ // Open a new query tab with the template pre-filled+ appState.openNewQueryTab()+ if let tabId = appState.activeTabId {+ appState.queryEditorText[tabId] = sql+ // Notify the query editor view to sync (it reads from queryEditorText on appear)+ NotificationCenter.default.post(+ name: .init("pasteQueryToEditor"),+ object: nil,+ userInfo: ["sql": sql]+ )+ }+ }++ private func commitChanges() async {+ guard let adapter = appState.activeAdapter else { return }+ isCommitting = true+ commitError = nil+ showCommitSuccess = false++ do {+ _ = try await adapter.executeRaw(sql: editedSource)+ originalSource = editedSource+ isCommitting = false+ showCommitSuccess = true+ Task {+ try? await Task.sleep(nanoseconds: 3_000_000_000)+ showCommitSuccess = false+ }+ } catch {+ commitError = error.localizedDescription+ isCommitting = false+ }+ }+}++// MARK: - Code editor with line numbers + syntax highlighting++struct FunctionCodeEditor: View {+ @Binding var text: String++ private var lineCount: Int {+ max(text.components(separatedBy: "\n").count, 1)+ }++ private var gutterWidth: CGFloat {+ CGFloat(max(String(lineCount).count, 2)) * 9 + 20+ }++ var body: some View {+ HStack(alignment: .top, spacing: 0) {+ // Line number gutter (SwiftUI)+ ScrollView(.vertical, showsIndicators: false) {+ VStack(alignment: .trailing, spacing: 0) {+ ForEach(1...max(lineCount, 1), id: \.self) { num in+ Text("\(num)")+ .font(.system(size: 12, design: .monospaced))+ .foregroundStyle(.tertiary)+ .frame(height: 17.5, alignment: .trailing)+ }+ }+ .padding(.top, 7)+ .padding(.horizontal, 8)+ }+ .disabled(true)+ .frame(width: gutterWidth)+ .background(Color(nsColor: .controlBackgroundColor))+ .overlay(alignment: .trailing) {+ Rectangle()+ .fill(Color(nsColor: .separatorColor))+ .frame(width: 1)+ }++ // Syntax-highlighted editor (NSViewRepresentable, no ruler)+ HighlightedTextEditor(text: $text)+ }+ .background(Color(nsColor: .textBackgroundColor))+ }+}++// MARK: - NSViewRepresentable editor with syntax highlighting (no ruler)+// Identical to the proven-working SQLEditorView pattern.++struct HighlightedTextEditor: NSViewRepresentable {+ @Binding var text: String++ func makeNSView(context: Context) -> NSScrollView {+ let scrollView = NSScrollView()+ scrollView.hasVerticalScroller = true+ scrollView.hasHorizontalScroller = false++ let textView = NSTextView()+ textView.isEditable = true+ textView.isRichText = false+ textView.font = NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)+ textView.textContainerInset = NSSize(width: 8, height: 8)+ textView.isAutomaticQuoteSubstitutionEnabled = false+ textView.isAutomaticDashSubstitutionEnabled = false+ textView.isAutomaticTextReplacementEnabled = false+ textView.isAutomaticSpellingCorrectionEnabled = false+ textView.isContinuousSpellCheckingEnabled = false+ textView.allowsUndo = true+ textView.delegate = context.coordinator+ textView.autoresizingMask = [.width]+ textView.isVerticallyResizable = true+ textView.isHorizontallyResizable = false+ textView.textContainer?.widthTracksTextView = true+ textView.textContainer?.containerSize = NSSize(width: 0, height: CGFloat.greatestFiniteMagnitude)++ scrollView.documentView = textView+ context.coordinator.textView = textView+ context.coordinator.highlighter = SyntaxHighlighter(textView: textView)++ return scrollView+ }++ func updateNSView(_ scrollView: NSScrollView, context: Context) {+ guard let textView = scrollView.documentView as? NSTextView else { return }+ if textView.string != text {+ textView.string = text+ if let storage = textView.textStorage {+ context.coordinator.highlighter?.highlight(storage)+ }+ }+ }++ func makeCoordinator() -> Coordinator { Coordinator(text: $text) }++ class Coordinator: NSObject, NSTextViewDelegate {+ @Binding var text: String+ weak var textView: NSTextView?+ var highlighter: SyntaxHighlighter?++ init(text: Binding<String>) {+ _text = text+ }++ func textDidChange(_ notification: Notification) {+ guard let textView = notification.object as? NSTextView else { return }+ text = textView.string+ }+ }+}diff --git a/macos/Presentation/Views/Main/MainView.swift b/macos/Presentation/Views/Main/MainView.swiftnew file mode 100644index 0000000..161b430--- /dev/null+++ b/macos/Presentation/Views/Main/MainView.swift@@ -0,0 +1,2169 @@+// MainView.swift+// Gridex+//+// Top-level SwiftUI view: routes between Home (no connection) and Workspace (connected).++import SwiftUI+import UniformTypeIdentifiers++// MARK: - Drag & Drop Transfer Type++struct ConnectionTransfer: Codable, Transferable {+ let connectionId: String++ static var transferRepresentation: some TransferRepresentation {+ CodableRepresentation(contentType: .json)+ }+}++// MARK: - Window Root (per-window AppState owner)++/// Each window owns its own AppState via @StateObject, enabling multiple+/// simultaneous database connections in separate windows.+struct WindowRoot: View {+ @StateObject private var appState = AppState()++ var body: some View {+ MainView()+ .environmentObject(appState)+ .focusedObject(appState)+ .onAppear {+ // Register as the active AppState for menu command routing+ AppState.active = appState++ // Shrink window to compact size so connection picker feels focused+ DispatchQueue.main.async {+ if let window = NSApp.keyWindow ?? NSApp.windows.last(where: { $0.isVisible && !($0 is NSPanel) }) {+ let target = NSSize(width: 900, height: 500)+ var frame = window.frame+ frame.origin.x += (frame.width - target.width) / 2+ frame.origin.y += (frame.height - target.height) / 2+ frame.size = target+ window.setFrame(frame, display: true, animate: false)+ window.center()+ }+ }+ }+ .onReceive(NotificationCenter.default.publisher(for: NSWindow.didBecomeKeyNotification)) { _ in+ // Update active AppState when this window gains focus+ AppState.active = appState+ }+ .onChange(of: appState.activeConnectionId) { _, newValue in+ guard newValue != nil else { return }+ DispatchQueue.main.async {+ if let window = NSApp.keyWindow ?? NSApp.mainWindow {+ if !window.isZoomed { window.zoom(nil) }+ }+ }+ }+ .onDisappear {+ if appState.activeAdapter != nil { appState.disconnect() }+ if AppState.active === appState { AppState.active = nil }+ }+ }+}++// MARK: - Main View++struct MainView: View {+ @EnvironmentObject private var appState: AppState++ var body: some View {+ Group {+ if appState.activeAdapter != nil {+ WorkspaceView()+ } else {+ HomeView()+ }+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ .sheet(isPresented: $appState.showDBTypePicker) {+ DatabaseTypePickerView()+ }+ .sheet(isPresented: $appState.showDatabaseSwitcher) {+ DatabaseSwitcherDialog()+ }+ .sheet(isPresented: $appState.showNewTableSheet) {+ NewTableSheet(schema: "public")+ }+ .onChange(of: appState.showConnectionForm) { _, show in+ if show {+ appState.showConnectionForm = false+ ConnectionFormPanel.open(+ databaseType: appState.selectedDBType ?? .postgresql,+ appState: appState+ )+ }+ }+ .onReceive(NotificationCenter.default.publisher(for: .windowCloseRequested)) { _ in+ // Only handle if this is the last main window (multi-window closes directly)+ let mainWindows = NSApp.windows.filter { $0.canBecomeMain && !($0 is NSPanel) && $0.isVisible }+ guard mainWindows.count <= 1 else { return }++ if appState.activeAdapter != nil {+ appState.disconnect()+ } else {+ NSApplication.shared.terminate(nil)+ }+ }+ }+}++// MARK: - Home View++struct HomeView: View {+ @EnvironmentObject private var appState: AppState+ @State private var selectedConnectionId: UUID?+ @State private var collapsedGroups: Set<String> = []+ @State private var showNewGroupAlert = false+ @State private var newGroupName = ""+ @State private var renamingGroup: String?+ @State private var renameGroupName = ""+ @State private var editingConnection: ConnectionConfig?+ @State private var showConnectionError = false++ var body: some View {+ HStack(spacing: 0) {+ // Left panel — branding+ brandingPanel++ Divider()++ // Right panel — connections+ connectionsPanel+ }+ .overlay {+ if appState.isConnecting {+ ZStack {+ Color.black.opacity(0.3)+ VStack(spacing: 12) {+ ProgressView()+ .scaleEffect(1.2)+ Text("Connecting...")+ .font(.system(size: 13, weight: .medium))+ .foregroundStyle(.white)+ }+ .padding(24)+ .background(.ultraThinMaterial)+ .clipShape(RoundedRectangle(cornerRadius: 12))+ }+ .ignoresSafeArea()+ }+ }+ .alert("Connection Failed", isPresented: $showConnectionError) {+ Button("OK") {+ showConnectionError = false+ appState.connectionError = nil+ }+ } message: {+ Text(appState.connectionError ?? "Unknown error")+ }+ .onChange(of: appState.connectionError) { _, newValue in+ if newValue != nil {+ showConnectionError = true+ }+ }+ .task {+ await appState.loadSavedConnections()+ }+ .sheet(isPresented: $showNewGroupAlert) {+ GroupNameSheet(+ title: "New Group",+ placeholder: "Group name",+ initialValue: "",+ onConfirm: { name in+ if !name.isEmpty {+ appState.connectionGroups.insert(name)+ }+ showNewGroupAlert = false+ },+ onCancel: { showNewGroupAlert = false }+ )+ }+ .sheet(isPresented: Binding(+ get: { renamingGroup != nil },+ set: { if !$0 { renamingGroup = nil } }+ )) {+ GroupNameSheet(+ title: "Rename Group",+ placeholder: "Group name",+ initialValue: renamingGroup ?? "",+ onConfirm: { name in+ if let oldName = renamingGroup, !name.isEmpty {+ renameGroup(from: oldName, to: name)+ }+ renamingGroup = nil+ },+ onCancel: { renamingGroup = nil }+ )+ }+ .onChange(of: editingConnection) { _, conn in+ guard let conn else { return }+ editingConnection = nil+ ConnectionFormPanel.open(+ databaseType: conn.databaseType,+ existingConfig: conn,+ existingPassword: (try? appState.container.keychainService.load(+ key: "db.password.\(conn.id.uuidString)")) ?? "",+ existingSSHPassword: (try? appState.container.keychainService.load(+ key: "ssh.password.\(conn.id.uuidString)")) ?? "",+ appState: appState+ )+ }+ }++ // MARK: - Left Branding Panel++ private var brandingPanel: some View {+ VStack(spacing: 0) {+ Spacer()++ VStack(spacing: 16) {+ AppLogoImage()+ .frame(width: 100, height: 100)++ VStack(spacing: 4) {+ Text("Gridex")+ .font(.system(size: 26, weight: .bold, design: .default))+ Text("AI-Native Database IDE")+ .font(.system(size: 12))+ .foregroundStyle(.tertiary)+ }+ }++ Spacer()++ VStack(spacing: 2) {+ HomeActionButton(icon: "arrow.up.doc.fill", title: "Backup database…") {+ BackupRestorePanel.openBackupWizard(appState: appState)+ }+ HomeActionButton(icon: "arrow.down.doc.fill", title: "Restore database…") {+ BackupRestorePanel.openRestoreWizard(appState: appState)+ }++ Divider()+ .padding(.vertical, 6)+ .padding(.horizontal, 14)++ HomeActionButton(icon: "plus.circle.fill", title: "New Connection") {+ appState.showDBTypePicker = true+ }+ HomeActionButton(icon: "folder.badge.plus", title: "New Group") {+ newGroupName = ""+ showNewGroupAlert = true+ }+ }+ .padding(.horizontal, 20)+ .padding(.bottom, 28)+ }+ .frame(width: 260)+ .background(Color.primary.opacity(0.02))+ }++ // MARK: - Right Connections Panel++ private var connectionsPanel: some View {+ VStack(spacing: 0) {+ // Toolbar+ HStack(spacing: 10) {+ HStack(spacing: 6) {+ Image(systemName: "magnifyingglass")+ .font(.system(size: 12))+ .foregroundStyle(.tertiary)+ TextField("Search connections...", text: $appState.connectionSearchText)+ .textFieldStyle(.plain)+ .font(.system(size: 13))+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 7)+ .background(Color.primary.opacity(0.04))+ .clipShape(RoundedRectangle(cornerRadius: 8))+ .overlay(+ RoundedRectangle(cornerRadius: 8)+ .stroke(Color.primary.opacity(0.06), lineWidth: 1)+ )++ toolbarButton(icon: "plus", tooltip: "New Connection") {+ appState.showDBTypePicker = true+ }+ toolbarButton(icon: "folder.badge.plus", tooltip: "New Group") {+ newGroupName = ""+ showNewGroupAlert = true+ }+ }+ .padding(.horizontal, 16)+ .padding(.vertical, 10)++ Divider()++ // Connection list+ if appState.savedConnections.isEmpty {+ emptyState+ } else {+ connectionList+ }+ }+ .frame(maxWidth: .infinity)+ .background(.background)+ }++ private func toolbarButton(icon: String, tooltip: String, action: @escaping () -> Void) -> some View {+ Button(action: action) {+ Image(systemName: icon)+ .font(.system(size: 13, weight: .medium))+ .foregroundStyle(.secondary)+ .frame(width: 28, height: 28)+ .background(Color.primary.opacity(0.04))+ .clipShape(RoundedRectangle(cornerRadius: 6))+ .overlay(+ RoundedRectangle(cornerRadius: 6)+ .stroke(Color.primary.opacity(0.06), lineWidth: 1)+ )+ }+ .buttonStyle(.plain)+ .help(tooltip)+ }++ private var emptyState: some View {+ VStack(spacing: 16) {+ Spacer()+ Image(systemName: "externaldrive.badge.plus")+ .font(.system(size: 40))+ .foregroundStyle(.quaternary)+ VStack(spacing: 4) {+ Text("No connections yet")+ .font(.system(size: 14, weight: .medium))+ .foregroundStyle(.secondary)+ Text("Create your first database connection to get started")+ .font(.system(size: 12))+ .foregroundStyle(.tertiary)+ }+ Button("Create Connection") {+ appState.showDBTypePicker = true+ }+ .buttonStyle(.borderedProminent)+ .controlSize(.regular)+ Spacer()+ }+ .frame(maxWidth: .infinity)+ }++ private var connectionList: some View {+ ScrollView {+ VStack(spacing: 2) {+ ForEach(groupNames, id: \.self) { groupName in+ ConnectionGroupSection(+ groupName: groupName,+ connections: connectionsForGroup(groupName),+ isCollapsed: collapsedGroups.contains(groupName),+ selectedConnectionId: selectedConnectionId,+ allGroups: groupNames,+ onToggle: {+ withAnimation(.spring(response: 0.25, dampingFraction: 0.9)) {+ if collapsedGroups.contains(groupName) {+ collapsedGroups.remove(groupName)+ } else {+ collapsedGroups.insert(groupName)+ }+ }+ },+ onSelect: { id in selectedConnectionId = id },+ onConnect: { conn in connectToDatabase(conn) },+ onMoveToGroup: { conn, group in+ if let actual = appState.savedConnections.first(where: { $0.id == conn.id }) {+ moveConnection(actual, toGroup: group)+ } else {+ moveConnection(conn, toGroup: group)+ }+ },+ onRenameGroup: { name in+ renameGroupName = name+ renamingGroup = name+ },+ onDeleteGroup: { name in+ deleteGroup(name)+ },+ onNewGroup: {+ newGroupName = ""+ showNewGroupAlert = true+ },+ onNewConnection: {+ appState.showDBTypePicker = true+ },+ onDeleteConnection: { conn in+ deleteConnection(conn)+ },+ onEditConnection: { conn in+ editingConnection = conn+ }+ )+ }++ ForEach(ungroupedConnections) { conn in+ ConnectionRow(+ connection: conn,+ isSelected: selectedConnectionId == conn.id,+ allGroups: groupNames,+ onSelect: { selectedConnectionId = conn.id },+ onConnect: { connectToDatabase(conn) },+ onMoveToGroup: { group in+ moveConnection(conn, toGroup: group)+ },+ onNewGroup: {+ newGroupName = ""+ showNewGroupAlert = true+ },+ onNewConnection: {+ appState.showDBTypePicker = true+ },+ onDelete: {+ deleteConnection(conn)+ },+ onEdit: {+ editingConnection = conn+ }+ )+ }+ }+ .padding(.vertical, 8)+ .padding(.horizontal, 12)+ }+ }++ // MARK: - Grouping Logic++ private var groupNames: [String] {+ let fromConnections = Set(filteredConnections.compactMap { $0.group })+ return fromConnections.union(appState.connectionGroups).sorted()+ }++ private func connectionsForGroup(_ group: String) -> [ConnectionConfig] {+ filteredConnections.filter { $0.group == group }+ }++ private var ungroupedConnections: [ConnectionConfig] {+ filteredConnections.filter { $0.group == nil || $0.group?.isEmpty == true }+ }++ private var filteredConnections: [ConnectionConfig] {+ let search = appState.connectionSearchText.lowercased()+ if search.isEmpty { return appState.savedConnections }+ return appState.savedConnections.filter {+ $0.name.lowercased().contains(search) ||+ ($0.host ?? "").lowercased().contains(search) ||+ ($0.database ?? "").lowercased().contains(search)+ }+ }++ private func moveConnection(_ conn: ConnectionConfig, toGroup group: String?) {+ var updated = conn+ updated.group = group+ Task { @MainActor in+ try? await appState.container.connectionRepository.update(updated)+ await appState.loadSavedConnections()+ }+ }++ private func renameGroup(from oldName: String, to newName: String) {+ let connections = appState.savedConnections.filter { $0.group == oldName }+ Task { @MainActor in+ for var conn in connections {+ conn.group = newName+ try? await appState.container.connectionRepository.update(conn)+ }+ appState.connectionGroups.remove(oldName)+ appState.connectionGroups.insert(newName)+ await appState.loadSavedConnections()+ }+ }++ private func deleteGroup(_ name: String) {+ let connections = appState.savedConnections.filter { $0.group == name }+ Task { @MainActor in+ for var conn in connections {+ conn.group = nil+ try? await appState.container.connectionRepository.update(conn)+ }+ appState.connectionGroups.remove(name)+ await appState.loadSavedConnections()+ }+ }++ private func connectToDatabase(_ conn: ConnectionConfig) {+ // SQLite doesn't need a password — connect directly+ if conn.databaseType == .sqlite {+ Task { await appState.connect(config: conn, password: "") }+ return+ }++ Task {+ // Load keychain passwords off the main thread.+ let keychain = appState.container.keychainService+ let hasSSH = conn.sshConfig != nil+ let credentials = await Task.detached { () -> (String?, String?) in+ let pw = try? keychain.load(key: "db.password.\(conn.id.uuidString)")+ let sshPw = hasSSH+ ? (try? keychain.load(key: "ssh.password.\(conn.id.uuidString)"))+ : nil+ return (pw, sshPw ?? nil)+ }.value++ // Connect even with empty/nil password — Redis and some databases don't require one+ await appState.connect(+ config: conn,+ password: credentials.0 ?? "",+ sshPassword: credentials.1+ )+ }+ }++ private func deleteConnection(_ conn: ConnectionConfig) {+ Task { @MainActor in+ try? await appState.container.connectionRepository.delete(conn.id)+ try? appState.container.keychainService.delete(key: "db.password.\(conn.id.uuidString)")+ try? appState.container.keychainService.delete(key: "ssh.password.\(conn.id.uuidString)")+ if selectedConnectionId == conn.id { selectedConnectionId = nil }+ await appState.loadSavedConnections()+ }+ }+}++// MARK: - Connection Group Section++struct ConnectionGroupSection: View {+ let groupName: String+ let connections: [ConnectionConfig]+ let isCollapsed: Bool+ let selectedConnectionId: UUID?+ let allGroups: [String]+ let onToggle: () -> Void+ let onSelect: (UUID) -> Void+ let onConnect: (ConnectionConfig) -> Void+ let onMoveToGroup: (ConnectionConfig, String?) -> Void+ let onRenameGroup: (String) -> Void+ let onDeleteGroup: (String) -> Void+ let onNewGroup: () -> Void+ let onNewConnection: () -> Void+ let onDeleteConnection: (ConnectionConfig) -> Void+ var onEditConnection: ((ConnectionConfig) -> Void)?+ @State private var isHovered = false+ @State private var isDropTargeted = false++ var body: some View {+ VStack(alignment: .leading, spacing: 0) {+ // Section header — minimal, always uppercase+ groupHeader+ .padding(.top, 14)+ .padding(.bottom, 4)++ // Connections+ if !isCollapsed {+ VStack(spacing: 2) {+ ForEach(connections) { conn in+ ConnectionRow(+ connection: conn,+ isSelected: selectedConnectionId == conn.id,+ allGroups: allGroups,+ onSelect: { onSelect(conn.id) },+ onConnect: { onConnect(conn) },+ onMoveToGroup: { group in onMoveToGroup(conn, group) },+ onNewGroup: onNewGroup,+ onNewConnection: onNewConnection,+ onDelete: { onDeleteConnection(conn) },+ onEdit: { onEditConnection?(conn) }+ )+ .transition(.opacity)+ }+ }+ }+ }+ }++ private var groupHeader: some View {+ HStack(spacing: 8) {+ // Disclosure chevron — subtle+ Image(systemName: "chevron.right")+ .font(.system(size: 9, weight: .semibold))+ .foregroundStyle(.tertiary)+ .frame(width: 10)+ .rotationEffect(.degrees(isCollapsed ? 0 : 90))++ // Group name in section-header style+ Text(groupName.uppercased())+ .font(.system(size: 11, weight: .semibold))+ .foregroundStyle(.secondary)+ .tracking(0.8)+ .lineLimit(1)++ // Count — quiet, inline+ Text("\(connections.count)")+ .font(.system(size: 11, weight: .regular, design: .rounded))+ .foregroundStyle(.tertiary)+ .monospacedDigit()++ Spacer()++ // Inline "+" — always rendered, opacity toggles on hover+ Button(action: onNewConnection) {+ Image(systemName: "plus")+ .font(.system(size: 10, weight: .semibold))+ .foregroundStyle(.secondary)+ .frame(width: 18, height: 18)+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .help("New connection in this group")+ .opacity(isHovered ? 1 : 0)+ .allowsHitTesting(isHovered)+ }+ .padding(.horizontal, 12)+ .padding(.vertical, 4)+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(+ RoundedRectangle(cornerRadius: 4)+ .strokeBorder(+ isDropTargeted ? Color.accentColor.opacity(0.5) : Color.clear,+ lineWidth: 1.5+ )+ .background(+ isDropTargeted ? Color.accentColor.opacity(0.10) : Color.clear+ )+ )+ .contentShape(Rectangle())+ .onHover { isHovered = $0 }+ .onTapGesture { onToggle() }+ .dropDestination(for: ConnectionTransfer.self) { items, _ in+ guard let item = items.first,+ let uuid = UUID(uuidString: item.connectionId) else { return false }+ onMoveToGroup(ConnectionConfig(id: uuid, name: "", databaseType: .postgresql), groupName)+ return true+ } isTargeted: { targeted in+ withAnimation(.easeInOut(duration: 0.15)) { isDropTargeted = targeted }+ }+ .contextMenu {+ Menu("New") {+ Button("Group...") { onNewGroup() }+ Button("Connection...") { onNewConnection() }+ }+ Button("Rename...") { onRenameGroup(groupName) }+ Divider()+ Button("Delete Group", role: .destructive) { onDeleteGroup(groupName) }+ }+ }+}++// MARK: - Connection Row++struct ConnectionRow: View {+ let connection: ConnectionConfig+ let isSelected: Bool+ let allGroups: [String]+ let onSelect: () -> Void+ let onConnect: () -> Void+ var onMoveToGroup: ((String?) -> Void)?+ var onNewGroup: (() -> Void)?+ var onNewConnection: (() -> Void)?+ var onDelete: (() -> Void)?+ var onEdit: (() -> Void)?+ @State private var isHovered = false+ @State private var lastClickTime: Date = .distantPast++ var body: some View {+ HStack(spacing: 12) {+ // Environment color tag bar (only visible when set)+ RoundedRectangle(cornerRadius: 2)+ .fill(connection.colorTag?.swiftUIColor ?? Color.clear)+ .frame(width: 3, height: 28)++ // DB type icon+ DatabaseTypeIcon(type: connection.databaseType, size: 32)++ // Name + subtitle+ VStack(alignment: .leading, spacing: 3) {+ HStack(spacing: 6) {+ Text(connection.name)+ .font(.system(size: 13, weight: .semibold))+ .foregroundStyle(isSelected ? .white : .primary)+ .lineLimit(1)++ if let color = connection.colorTag {+ Text(color.environmentHint)+ .font(.system(size: 9, weight: .bold))+ .tracking(0.3)+ .foregroundStyle(isSelected ? .white : color.swiftUIColor)+ .padding(.horizontal, 5)+ .padding(.vertical, 1)+ .background(+ RoundedRectangle(cornerRadius: 3)+ .fill(isSelected ? Color.white.opacity(0.2) : color.swiftUIColor.opacity(0.14))+ )+ }+ }++ Text(connectionSubtitle)+ .font(.system(size: 11, design: .monospaced))+ .foregroundStyle(isSelected ? Color.white.opacity(0.7) : Color.secondary)+ .lineLimit(1)+ .truncationMode(.middle)+ }++ Spacer(minLength: 8)++ // DB type label — quiet, tabular+ Text(connection.databaseType.displayName.uppercased())+ .font(.system(size: 9, weight: .semibold))+ .tracking(0.5)+ .foregroundStyle(isSelected ? AnyShapeStyle(Color.white.opacity(0.55)) : AnyShapeStyle(.tertiary))+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 8)+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(+ RoundedRectangle(cornerRadius: 7)+ .fill(+ isSelected+ ? Color.accentColor+ : (isHovered ? Color.primary.opacity(0.055) : Color.clear)+ )+ )+ .contentShape(Rectangle())+ .onHover { isHovered = $0 }+ .draggable(ConnectionTransfer(connectionId: connection.id.uuidString))+ .onTapGesture(count: 1) {+ let now = Date()+ if now.timeIntervalSince(lastClickTime) < 0.3 {+ onConnect()+ lastClickTime = .distantPast+ } else {+ onSelect()+ lastClickTime = now+ }+ }+ .contextMenu {+ Button("Connect") { onConnect() }+ Button("Edit...") { onEdit?() }++ Divider()++ Menu("New") {+ Button("Connection...") { onNewConnection?() }+ Button("Group...") { onNewGroup?() }+ }++ if !allGroups.isEmpty {+ Menu("Move to Group") {+ ForEach(allGroups, id: \.self) { group in+ Button(group) { onMoveToGroup?(group) }+ }+ if connection.group != nil {+ Divider()+ Button("Remove from Group") { onMoveToGroup?(nil) }+ }+ }+ }++ Menu("Sort By") {+ Button("Name") { }+ Button("Type") { }+ Button("Date Created") { }+ }++ Divider()++ Button("Delete", role: .destructive) { onDelete?() }+ }+ }++ private var connectionSubtitle: String {+ if connection.databaseType == .sqlite {+ return connection.filePath ?? "No file"+ }+ var parts: [String] = []+ parts.append(connection.displayHost)+ if let db = connection.database, !db.isEmpty {+ parts.append(" / \(db)")+ }+ return parts.joined()+ }+}++// MARK: - Database Type Icon++struct DatabaseTypeIcon: View {+ let type: DatabaseType+ var size: CGFloat = 36++ var body: some View {+ ZStack {+ RoundedRectangle(cornerRadius: size * 0.22)+ .fill(iconGradient)+ .frame(width: size, height: size)++ Text(iconText)+ .font(.system(size: size * 0.32, weight: .bold, design: .rounded))+ .foregroundStyle(.white)+ }+ }++ private var iconGradient: LinearGradient {+ switch type {+ case .postgresql:+ return LinearGradient(colors: [Color(red: 0.2, green: 0.45, blue: 0.85), Color(red: 0.15, green: 0.35, blue: 0.7)], startPoint: .top, endPoint: .bottom)+ case .mysql:+ return LinearGradient(colors: [Color(red: 0.0, green: 0.55, blue: 0.8), Color(red: 0.0, green: 0.4, blue: 0.65)], startPoint: .top, endPoint: .bottom)+ case .sqlite:+ return LinearGradient(colors: [Color(red: 0.45, green: 0.35, blue: 0.75), Color(red: 0.35, green: 0.25, blue: 0.6)], startPoint: .top, endPoint: .bottom)+ case .redis:+ return LinearGradient(colors: [Color(red: 0.85, green: 0.2, blue: 0.2), Color(red: 0.7, green: 0.15, blue: 0.15)], startPoint: .top, endPoint: .bottom)+ case .mongodb:+ return LinearGradient(colors: [Color(red: 0.30, green: 0.65, blue: 0.35), Color(red: 0.20, green: 0.50, blue: 0.25)], startPoint: .top, endPoint: .bottom)+ case .mssql:+ return LinearGradient(colors: [Color(red: 0.80, green: 0.20, blue: 0.40), Color(red: 0.65, green: 0.10, blue: 0.30)], startPoint: .top, endPoint: .bottom)+ }+ }++ private var iconText: String {+ switch type {+ case .postgresql: return "Pg"+ case .mysql: return "My"+ case .sqlite: return "SL"+ case .redis: return "Rd"+ case .mongodb: return "Mg"+ case .mssql: return "MS"+ }+ }+}++// MARK: - Home Action Button++struct HomeActionButton: View {+ let icon: String+ let title: String+ let action: () -> Void+ @State private var isHovered = false++ var body: some View {+ Button(action: action) {+ HStack(spacing: 10) {+ Image(systemName: icon)+ .font(.system(size: 14))+ .foregroundStyle(isHovered ? .blue : .secondary)+ .frame(width: 20)+ Text(title)+ .font(.system(size: 13, weight: .medium))+ .foregroundStyle(isHovered ? .primary : .secondary)+ Spacer()+ }+ .padding(.horizontal, 14)+ .padding(.vertical, 9)+ .background(isHovered ? Color.accentColor.opacity(0.08) : Color.clear)+ .clipShape(RoundedRectangle(cornerRadius: 8))+ }+ .buttonStyle(.plain)+ .onHover { isHovered = $0 }+ }+}++// MARK: - Group Name Sheet++struct GroupNameSheet: View {+ let title: String+ let placeholder: String+ let initialValue: String+ let onConfirm: (String) -> Void+ let onCancel: () -> Void+ @State private var name: String = ""+ @FocusState private var isFocused: Bool++ var body: some View {+ VStack(spacing: 20) {+ VStack(spacing: 4) {+ Text(title)+ .font(.system(size: 15, weight: .semibold))+ Text(title == "New Group" ? "Create a group to organize connections" : "Enter a new name for the group")+ .font(.system(size: 12))+ .foregroundStyle(.secondary)+ }++ TextField(placeholder, text: $name)+ .textFieldStyle(.roundedBorder)+ .frame(width: 280)+ .focused($isFocused)+ .onSubmit {+ if !name.isEmpty { onConfirm(name) }+ }++ HStack(spacing: 12) {+ Button("Cancel") { onCancel() }+ .keyboardShortcut(.cancelAction)+ Button(title == "New Group" ? "Create" : "Rename") {+ if !name.isEmpty { onConfirm(name) }+ }+ .buttonStyle(.borderedProminent)+ .disabled(name.isEmpty)+ .keyboardShortcut(.defaultAction)+ }+ }+ .padding(28)+ .frame(width: 360)+ .onAppear {+ name = initialValue+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {+ isFocused = true+ }+ }+ }+}++// MARK: - Database Type Picker++struct DatabaseTypePickerView: View {+ @EnvironmentObject private var appState: AppState+ @State private var searchText = ""+ @Environment(\.dismiss) private var dismiss++ var body: some View {+ VStack(spacing: 20) {+ VStack(spacing: 4) {+ Text("New Connection")+ .font(.system(size: 15, weight: .semibold))+ Text("Select a database type")+ .font(.system(size: 12))+ .foregroundStyle(.secondary)+ }+ .padding(.top, 20)++ HStack(spacing: 6) {+ Image(systemName: "magnifyingglass")+ .font(.system(size: 12))+ .foregroundStyle(.tertiary)+ TextField("Search", text: $searchText)+ .textFieldStyle(.plain)+ .font(.system(size: 13))+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 7)+ .background(Color.primary.opacity(0.04))+ .clipShape(RoundedRectangle(cornerRadius: 8))+ .overlay(+ RoundedRectangle(cornerRadius: 8)+ .stroke(Color.primary.opacity(0.06), lineWidth: 1)+ )+ .padding(.horizontal, 24)++ LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 16), count: 4), spacing: 16) {+ ForEach(filteredTypes) { type in+ DatabaseTypeCard(type: type) {+ appState.selectedDBType = type+ dismiss()+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {+ appState.showConnectionForm = true+ }+ }+ }+ }+ .padding(.horizontal, 24)++ Spacer()++ HStack {+ Button("Cancel") { dismiss() }+ .keyboardShortcut(.cancelAction)+ Spacer()+ }+ .padding(.horizontal, 24)+ .padding(.bottom, 16)+ }+ .frame(width: 440, height: 280)+ }++ private var filteredTypes: [DatabaseType] {+ if searchText.isEmpty { return DatabaseType.allCases }+ return DatabaseType.allCases.filter { $0.displayName.localizedCaseInsensitiveContains(searchText) }+ }+}++struct DatabaseTypeCard: View {+ let type: DatabaseType+ let action: () -> Void+ @State private var isHovered = false++ var body: some View {+ Button(action: action) {+ VStack(spacing: 8) {+ DatabaseTypeIcon(type: type, size: 44)+ Text(type.displayName)+ .font(.system(size: 11, weight: .medium))+ .foregroundStyle(.primary)+ }+ .frame(width: 86, height: 86)+ .background(isHovered ? Color.accentColor.opacity(0.08) : Color.primary.opacity(0.02))+ .clipShape(RoundedRectangle(cornerRadius: 10))+ .overlay(+ RoundedRectangle(cornerRadius: 10)+ .stroke(isHovered ? Color.accentColor.opacity(0.4) : Color.primary.opacity(0.06), lineWidth: 1)+ )+ }+ .buttonStyle(.plain)+ .onHover { isHovered = $0 }+ }+}++// MARK: - Workspace View (connected state)++struct WorkspaceView: View {+ @EnvironmentObject private var appState: AppState+ @State private var showConnectionPicker = false+ @State private var showDatabasePicker = false+ private let sidebarWidth: CGFloat = 280++ /// Max width for the right details panel: half of the main screen.+ private var detailsPanelMaxWidth: CGFloat {+ let screenWidth = NSScreen.main?.visibleFrame.width ?? 1440+ return screenWidth * 0.5+ }++ var body: some View {+ HStack(spacing: 0) {+ // Sidebar — always in hierarchy; width animates between 0 and sidebarWidth+ SidebarView()+ .frame(width: sidebarWidth)+ .frame(width: appState.sidebarVisible ? sidebarWidth : 0, alignment: .leading)+ .clipped()++ // Thin separator line+ Rectangle()+ .fill(Color(NSColor.separatorColor))+ .frame(width: appState.sidebarVisible ? 1 : 0)++ // Main content area+ VStack(spacing: 0) {+ if !appState.tabs.isEmpty {+ TabBarSwiftUIView()+ }++ ZStack(alignment: .topLeading) {+ if let activeId = appState.activeTabId,+ let tab = appState.tabs.first(where: { $0.id == activeId }) {+ tabContent(for: tab)+ .id(tab.id)+ } else {+ ConnectedWelcomeView()+ }+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)++ StatusBarSwiftUIView()+ }+ .frame(minWidth: 400, maxWidth: .infinity, maxHeight: .infinity)++ // Resize handle + details panel — fixed width persisted in AppState+ if appState.detailsPanelVisible {+ ResizeHandle(width: $appState.detailsPanelWidth,+ minWidth: 220,+ maxWidth: detailsPanelMaxWidth)+ .frame(width: 1)++ DetailsPanel()+ .frame(width: appState.detailsPanelWidth)+ }+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ .transaction { $0.disablesAnimations = true }+ .toolbar {+ // Left: sidebar toggle + database picker+ ToolbarItemGroup(placement: .navigation) {+ Button {+ appState.sidebarVisible.toggle()+ } label: {+ Image(systemName: "sidebar.left")+ }+ .help("Toggle Sidebar")++ // Database selector+ if appState.activeAdapter != nil {+ Button {+ showDatabasePicker.toggle()+ } label: {+ HStack(spacing: 5) {+ Image(systemName: "cylinder")+ .font(.system(size: 11))+ Text(appState.currentDatabaseName ?? "Database")+ .font(.system(size: 11, weight: .medium))+ .lineLimit(1)+ Image(systemName: "chevron.up.chevron.down")+ .font(.system(size: 8, weight: .semibold))+ .foregroundStyle(.secondary)+ }+ }+ .help("Switch Database")+ .popover(isPresented: $showDatabasePicker, arrowEdge: .bottom) {+ DatabasePickerPopover(isPresented: $showDatabasePicker)+ }+ }+ }++ // Connection breadcrumb in title bar+ ToolbarItem(placement: .principal) {+ ConnectionBreadcrumb()+ }++ // Right: unified icon toolbar+ ToolbarItemGroup(placement: .primaryAction) {+ // Data actions+ Button {+ NotificationCenter.default.post(name: .deleteSelectedRows, object: nil)+ } label: {+ Image(systemName: "trash")+ }+ .help("Delete Selected Rows")++ Button {+ NotificationCenter.default.post(name: .commitChanges, object: nil)+ } label: {+ Image(systemName: "text.insert")+ }+ .help("Commit Changes")++ // ER Diagram (SQL databases only)+ if appState.activeConfig?.databaseType.isSQL == true {+ Button { appState.openERDiagram(schema: nil) } label: {+ Image(systemName: "point.3.connected.trianglepath.dotted")+ }.help("ER Diagram")+ }++ // SQL Editor+ Button { appState.openNewQueryTab() } label: {+ Image(systemName: "chevron.left.forwardslash.chevron.right")+ }.help("New SQL Query (⌘⇧N)")++ // Redis-specific+ if appState.activeConfig?.databaseType == .redis {+ Button { appState.openRedisServerInfo() } label: {+ Image(systemName: "chart.bar")+ }.help("Server Info")++ Button { appState.openRedisSlowLog() } label: {+ Image(systemName: "tortoise")+ }.help("Slow Log")+ }++ // Panel toggles+ Button { appState.detailsPanelVisible.toggle() } label: {+ Image(systemName: "sidebar.trailing")+ }+ .help("Toggle Details Panel")+ }+ }+ .alert("Flush Database", isPresented: $appState.showFlushDBConfirm) {+ Button("Cancel", role: .cancel) {}+ Button("Flush", role: .destructive) {+ Task {+ if let redis = appState.activeAdapter as? RedisAdapter {+ try? await redis.flushDB()+ appState.redisDBSize = 0+ NotificationCenter.default.post(name: .reloadData, object: nil)+ }+ }+ }+ } message: { Text("This will permanently delete ALL keys in the current database. This cannot be undone.") }+ .sheet(isPresented: $appState.showRedisAddKey) {+ RedisAddKeySheet()+ }+ }++ @ViewBuilder+ private func tabContent(for tab: AppState.ContentTab) -> some View {+ switch tab.type {+ case .dataGrid:+ if let tableName = tab.tableName {+ DataGridView(tableName: tableName, schema: tab.schema, tabId: tab.id, initialViewMode: tab.initialViewMode)+ }+ case .queryEditor:+ QueryEditorView(tabId: tab.id)+ case .tableStructure:+ if let tableName = tab.tableName {+ TableStructureView(tableName: tableName, schema: tab.schema)+ }+ case .tableList:+ TableListView(schema: tab.schema)+ case .functionDetail:+ if let funcName = tab.tableName {+ FunctionDetailView(+ functionName: funcName,+ schema: tab.schema,+ isProcedure: tab.initialViewMode == "procedure"+ )+ }+ case .createTable:+ CreateTableView(schema: tab.schema)+ case .erDiagram:+ ERDiagramView(schema: tab.schema)+ .onReceive(NotificationCenter.default.publisher(for: .erDiagramOpenTable)) { notif in+ if let name = notif.userInfo?["tableName"] as? String {+ let schema = notif.userInfo?["schema"] as? String+ appState.openTable(name: name, schema: schema)+ }+ }+ // Redis-specific tabs+ case .redisKeyDetail:+ if let keyName = tab.tableName {+ RedisKeyDetailView(keyName: keyName)+ }+ case .redisServerInfo:+ RedisServerInfoView()+ case .redisSlowLog:+ RedisSlowLogView()+ }+ }+}++// MARK: - Connection picker popover++struct ConnectionPickerPopover: View {+ @EnvironmentObject private var appState: AppState+ @Binding var isPresented: Bool++ var body: some View {+ VStack(spacing: 0) {+ Text("Connections")+ .font(.system(size: 12, weight: .semibold))+ .foregroundStyle(.secondary)+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(.horizontal, 12)+ .padding(.vertical, 8)++ Divider()++ if appState.savedConnections.isEmpty {+ Text("No saved connections")+ .font(.system(size: 12))+ .foregroundStyle(.secondary)+ .padding(20)+ } else {+ ScrollView {+ VStack(spacing: 0) {+ ForEach(appState.savedConnections) { conn in+ Button {+ isPresented = false+ let keychain = appState.container.keychainService+ let pw = (try? keychain.load(+ key: "db.password.\(conn.id.uuidString)")) ?? ""+ let sshPw: String? = conn.sshConfig != nil+ ? (try? keychain.load(key: "ssh.password.\(conn.id.uuidString)")) ?? nil+ : nil+ Task { await appState.connect(config: conn, password: pw, sshPassword: sshPw) }+ } label: {+ HStack(spacing: 8) {+ Image(systemName: conn.databaseType.iconName)+ .font(.system(size: 12))+ .foregroundStyle(.secondary)+ .frame(width: 16)++ VStack(alignment: .leading, spacing: 1) {+ Text(conn.name)+ .font(.system(size: 12))+ .foregroundStyle(.primary)+ if let host = conn.host {+ Text(host)+ .font(.system(size: 10))+ .foregroundStyle(.secondary)+ }+ }++ Spacer()++ if appState.activeConnectionId == conn.id {+ Image(systemName: "checkmark")+ .font(.system(size: 10, weight: .semibold))+ .foregroundStyle(.green)+ }+ }+ .contentShape(Rectangle())+ .padding(.horizontal, 12)+ .padding(.vertical, 7)+ }+ .buttonStyle(.plain)+ .background(+ appState.activeConnectionId == conn.id+ ? Color.accentColor.opacity(0.1) as Color+ : Color.clear+ )++ Divider().padding(.leading, 36)+ }+ }+ }+ .frame(maxHeight: 280)+ }++ Divider()++ HStack(spacing: 0) {+ Button {+ isPresented = false+ appState.showDBTypePicker = true+ } label: {+ HStack(spacing: 6) {+ Image(systemName: "plus")+ .font(.system(size: 11))+ Text("New Connection")+ .font(.system(size: 12))+ }+ .foregroundColor(.accentColor)+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(.horizontal, 12)+ .padding(.vertical, 8)+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)++ if appState.activeAdapter != nil {+ Divider().frame(height: 16)+ Button {+ isPresented = false+ appState.disconnect()+ } label: {+ HStack(spacing: 4) {+ Image(systemName: "xmark.circle")+ .font(.system(size: 11))+ Text("Disconnect")+ .font(.system(size: 12))+ }+ .foregroundColor(.red)+ .padding(.horizontal, 12)+ .padding(.vertical, 8)+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ }+ }+ }+ .frame(width: 280)+ }+}++// MARK: - Database picker popover++struct DatabasePickerPopover: View {+ @EnvironmentObject private var appState: AppState+ @Binding var isPresented: Bool++ var body: some View {+ VStack(spacing: 0) {+ Text("Databases")+ .font(.system(size: 12, weight: .semibold))+ .foregroundStyle(.secondary)+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(.horizontal, 12)+ .padding(.vertical, 8)++ Divider()++ if appState.availableDatabases.isEmpty {+ Text("No databases found")+ .font(.system(size: 12))+ .foregroundStyle(.secondary)+ .padding(20)+ } else {+ ScrollView {+ VStack(spacing: 0) {+ ForEach(appState.availableDatabases, id: \.self) { dbName in+ Button {+ isPresented = false+ Task { await appState.switchDatabase(dbName) }+ } label: {+ HStack(spacing: 8) {+ Image(systemName: "cylinder")+ .font(.system(size: 11))+ .foregroundStyle(.secondary)+ .frame(width: 16)++ Text(dbName)+ .font(.system(size: 12))+ .foregroundStyle(.primary)++ Spacer()++ if dbName == appState.currentDatabaseName {+ Image(systemName: "checkmark")+ .font(.system(size: 10, weight: .semibold))+ .foregroundStyle(.green)+ }+ }+ .contentShape(Rectangle())+ .padding(.horizontal, 12)+ .padding(.vertical, 7)+ }+ .buttonStyle(.plain)+ .background(+ dbName == appState.currentDatabaseName+ ? Color.accentColor.opacity(0.1)+ : Color.clear+ )++ Divider().padding(.leading, 36)+ }+ }+ }+ .frame(maxHeight: 320)+ }+ }+ .frame(width: 240)+ }+}++// MARK: - Database Switcher Dialog (Cmd+K)++struct DatabaseSwitcherDialog: View {+ @EnvironmentObject private var appState: AppState+ @Environment(\.dismiss) private var dismiss+ @State private var searchText = ""+ @State private var selected: String?+ @State private var showNewDBSheet = false+ @State private var showDeleteConfirm = false+ @State private var deleteError: String?++ private var filteredDatabases: [String] {+ if searchText.isEmpty {+ return appState.availableDatabases+ }+ return appState.availableDatabases.filter {+ $0.localizedCaseInsensitiveContains(searchText)+ }+ }++ var body: some View {+ VStack(spacing: 0) {+ // Title+ Text("Open database")+ .font(.system(size: 14, weight: .semibold))+ .padding(.top, 16)+ .padding(.bottom, 12)++ // Search field+ HStack(spacing: 6) {+ Image(systemName: "magnifyingglass")+ .foregroundStyle(.secondary)+ .font(.system(size: 13))+ TextField("Search for database...", text: $searchText)+ .textFieldStyle(.plain)+ .font(.system(size: 13))+ .onSubmit { openSelected() }+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 7)+ .background(Color(nsColor: .controlBackgroundColor))+ .clipShape(RoundedRectangle(cornerRadius: 6))+ .overlay(+ RoundedRectangle(cornerRadius: 6)+ .stroke(Color.accentColor, lineWidth: 2)+ )+ .padding(.horizontal, 16)++ // Database list — native List selection for instant response+ List(filteredDatabases, id: \.self, selection: $selected) { dbName in+ HStack(spacing: 8) {+ Image(systemName: "cylinder.fill")+ .font(.system(size: 12))+ .foregroundStyle(dbName == appState.currentDatabaseName ? .blue : .secondary)+ .frame(width: 18)++ Text(dbName)+ .font(.system(size: 13))++ Spacer()+ }+ .padding(.vertical, 2)+ .tag(dbName)+ }+ .listStyle(.plain)+ .frame(minHeight: 200, maxHeight: 360)+ .environment(\.defaultMinListRowHeight, 30)+ .onDoubleClick { openSelected() }++ Divider()++ // Bottom buttons+ HStack {+ Button("Cancel") { dismiss() }+ .keyboardShortcut(.cancelAction)++ Spacer()++ // Delete database+ Button(role: .destructive) {+ showDeleteConfirm = true+ } label: {+ Image(systemName: "trash")+ }+ .buttonStyle(.plain)+ .foregroundStyle(.red)+ .help("Delete database")+ .disabled(selected == nil || selected == appState.currentDatabaseName)++ Button("New...") {+ showNewDBSheet = true+ }+ .sheet(isPresented: $showNewDBSheet) {+ NewDatabaseSheet(onCreated: { dbName in+ dismiss()+ Task { await appState.switchDatabase(dbName) }+ })+ }++ Button("Open") { openSelected() }+ .keyboardShortcut(.defaultAction)+ .disabled(selected == nil)+ }+ .padding(.horizontal, 16)+ .padding(.vertical, 12)+ }+ .frame(width: 400)+ .background(Color(nsColor: .windowBackgroundColor))+ .onAppear {+ selected = appState.currentDatabaseName ?? filteredDatabases.first+ }+ .onChange(of: searchText) { _, _ in+ selected = filteredDatabases.first+ }+ .alert("Delete Database", isPresented: $showDeleteConfirm) {+ Button("Cancel", role: .cancel) {}+ Button("Delete", role: .destructive) {+ Task { await deleteSelected() }+ }+ } message: {+ Text("Are you sure you want to delete \"\(selected ?? "")\"?\nThis will permanently remove all data. This cannot be undone.")+ }+ .alert("Delete Failed", isPresented: Binding(+ get: { deleteError != nil },+ set: { if !$0 { deleteError = nil } }+ )) {+ Button("OK", role: .cancel) {}+ } message: {+ Text(deleteError ?? "")+ }+ }++ private func deleteSelected() async {+ guard let name = selected, let adapter = appState.activeAdapter else { return }+ do {+ try await adapter.dropDatabase(name: name)+ // Refresh database list+ if let databases = try? await adapter.listDatabases() {+ appState.availableDatabases = databases+ }+ selected = appState.currentDatabaseName ?? filteredDatabases.first+ } catch {+ deleteError = error.localizedDescription+ }+ }++ private func openSelected() {+ guard let name = selected else { return }+ dismiss()+ Task { await appState.switchDatabase(name) }+ }+}++// MARK: - App Logo (resolves from .module or main bundle)++private struct AppLogoImage: View {+ var body: some View {+ if let nsImage = loadLogo() {+ Image(nsImage: nsImage)+ .resizable()+ .aspectRatio(contentMode: .fit)+ } else {+ Image(systemName: "cylinder.split.1x2")+ .resizable()+ .aspectRatio(contentMode: .fit)+ }+ }++ private func loadLogo() -> NSImage? {+ // Load from the main .app bundle (Contents/Resources/Assets.car), which is+ // populated by scripts/build-app.sh from macos/Resources/Assets.xcassets.+ //+ // Do NOT use Bundle.module here — it's an SPM-generated lazy static that+ // fatalErrors if the "Gridex_Gridex.bundle" subbundle lookup fails, which+ // happens when the .app is run on a machine different from the build host.+ if let img = Bundle.main.image(forResource: "AppLogo") { return img }++ // Legacy fallback for older builds that shipped the SPM sub-bundle.+ let resourcePath = Bundle.main.bundlePath + "/Contents/Resources/Gridex_Gridex.bundle"+ if let bundle = Bundle(path: resourcePath),+ let img = bundle.image(forResource: "AppLogo") { return img }+ return nil+ }+}++// Double-click modifier for List rows+private struct DoubleClickModifier: ViewModifier {+ let action: () -> Void++ func body(content: Content) -> some View {+ content.background(DoubleClickView(action: action))+ }+}++private struct DoubleClickView: NSViewRepresentable {+ let action: () -> Void++ func makeNSView(context: Context) -> NSView {+ let view = DoubleClickNSView(action: action)+ return view+ }+ func updateNSView(_ nsView: NSView, context: Context) {}++ class DoubleClickNSView: NSView {+ let action: () -> Void+ init(action: @escaping () -> Void) {+ self.action = action+ super.init(frame: .zero)+ }+ required init?(coder: NSCoder) { fatalError() }++ override func mouseDown(with event: NSEvent) {+ super.mouseDown(with: event)+ if event.clickCount == 2 { action() }+ }+ }+}++private extension View {+ func onDoubleClick(_ action: @escaping () -> Void) -> some View {+ modifier(DoubleClickModifier(action: action))+ }+}++// MARK: - New Database Sheet++struct NewDatabaseSheet: View {+ var onCreated: (String) -> Void+ @EnvironmentObject private var appState: AppState+ @Environment(\.dismiss) private var dismiss++ @State private var dbName = ""+ @State private var encoding = "Default"+ @State private var collation = "Default"+ @State private var isCreating = false+ @State private var errorMessage: String?++ private var encodings: [String] {+ guard let adapter = appState.activeAdapter else { return ["Default"] }+ switch adapter.databaseType {+ case .postgresql: return ["Default", "UTF8", "LATIN1", "SQL_ASCII"]+ case .mysql: return ["Default", "utf8mb4", "utf8", "latin1"]+ case .sqlite, .redis, .mongodb, .mssql: return ["Default"]+ }+ }++ private var collations: [String] {+ guard let adapter = appState.activeAdapter else { return ["Default"] }+ switch adapter.databaseType {+ case .postgresql: return ["Default", "C", "POSIX", "en_US.UTF-8"]+ case .mysql: return ["Default", "utf8mb4_unicode_ci", "utf8mb4_general_ci", "utf8_general_ci"]+ case .sqlite, .redis, .mongodb, .mssql: return ["Default"]+ }+ }++ var body: some View {+ VStack(spacing: 0) {+ Text("New Database")+ .font(.system(size: 14, weight: .semibold))+ .padding(.top, 16)+ .padding(.bottom, 12)++ Grid(alignment: .trailing, horizontalSpacing: 10, verticalSpacing: 10) {+ GridRow {+ Text("Name:").font(.system(size: 12))+ TextField("", text: $dbName)+ .textFieldStyle(.roundedBorder)+ .frame(width: 220)+ }+ GridRow {+ Text("Encoding:").font(.system(size: 12))+ Picker("", selection: $encoding) {+ ForEach(encodings, id: \.self) { Text($0).tag($0) }+ }+ .labelsHidden()+ .frame(maxWidth: .infinity)+ }+ GridRow {+ Text("Collation:").font(.system(size: 12))+ Picker("", selection: $collation) {+ ForEach(collations, id: \.self) { Text($0).tag($0) }+ }+ .labelsHidden()+ .frame(maxWidth: .infinity)+ }+ }+ .padding(.horizontal, 20)++ if let errorMessage {+ Text(errorMessage)+ .font(.system(size: 11))+ .foregroundStyle(.red)+ .padding(.horizontal, 20)+ .padding(.top, 8)+ }++ Divider().padding(.top, 16)++ HStack {+ Button("Cancel") { dismiss() }+ .keyboardShortcut(.cancelAction)+ Spacer()+ Button {+ Task { await createDatabase() }+ } label: {+ if isCreating { ProgressView().controlSize(.small) }+ Text("OK")+ }+ .keyboardShortcut(.defaultAction)+ .disabled(dbName.isEmpty || isCreating)+ }+ .padding(.horizontal, 20)+ .padding(.vertical, 12)+ }+ .frame(width: 360)+ }++ private func createDatabase() async {+ guard let adapter = appState.activeAdapter else { return }+ isCreating = true+ errorMessage = nil+ defer { isCreating = false }++ let d = adapter.databaseType.sqlDialect+ var sql = "CREATE DATABASE \(d.quoteIdentifier(dbName))"++ var skipExecuteRaw = false+ switch adapter.databaseType {+ case .postgresql:+ var opts: [String] = []+ if encoding != "Default" { opts.append("ENCODING '\(encoding)'") }+ if collation != "Default" { opts.append("LC_COLLATE '\(collation)'") }+ if !opts.isEmpty { sql += " WITH " + opts.joined(separator: " ") }+ case .mysql:+ if encoding != "Default" { sql += " CHARACTER SET \(encoding)" }+ if collation != "Default" { sql += " COLLATE \(collation)" }+ case .sqlite, .redis:+ break // SQLite/Redis don't support CREATE DATABASE+ case .mssql:+ break // SQL Server: use plain CREATE DATABASE without options for MVP+ case .mongodb:+ // MongoDB: use the adapter's createDatabase method+ skipExecuteRaw = true+ do {+ try await adapter.createDatabase(name: dbName)+ } catch {+ errorMessage = DataGridViewState.detailedErrorMessage(error)+ return+ }+ }++ do {+ if !skipExecuteRaw {+ _ = try await adapter.executeRaw(sql: sql)+ }+ } catch {+ errorMessage = DataGridViewState.detailedErrorMessage(error)+ return+ }++ // Refresh database list and switch+ if let databases = try? await adapter.listDatabases() {+ appState.availableDatabases = databases+ }+ dismiss()+ onCreated(dbName)+ }+}++// MARK: - Connection breadcrumb bar (Gridex style)++struct ConnectionBreadcrumb: View {+ @EnvironmentObject private var appState: AppState++ private var activeTablePath: String? {+ guard let activeId = appState.activeTabId,+ let tab = appState.tabs.first(where: { $0.id == activeId }) else { return nil }+ if let tableName = tab.tableName {+ let schema = tab.schema ?? "public"+ return "\(schema).\(tableName)"+ }+ if tab.type == .tableList {+ return tab.title // e.g. "Tables.public"+ }+ return nil+ }++ private var tagColor: Color {+ appState.activeConfig?.colorTag?.swiftUIColor ?? Color(red: 0.22, green: 0.54, blue: 0.87)+ }++ var body: some View {+ if let config = appState.activeConfig {+ HStack(spacing: 0) {+ Circle()+ .fill(tagColor)+ .frame(width: 8, height: 8)+ .padding(.trailing, 6)++ Text(config.name.uppercased())+ .font(.system(size: 11, weight: .bold))++ breadcrumbSep++ let dbLabel = appState.serverVersion.map { "\(config.databaseType.displayName) \($0)" } ?? config.databaseType.displayName+ Text(dbLabel)+ .font(.system(size: 11))+ .foregroundStyle(.secondary)++ if let ssl = appState.sslInfo {+ breadcrumbColon+ Text(ssl)+ .font(.system(size: 11))+ .foregroundStyle(.secondary)+ }++ if let user = config.username, !user.isEmpty {+ breadcrumbColon+ Text(user)+ .font(.system(size: 11))+ .foregroundStyle(.secondary)+ }++ if let db = config.database, !db.isEmpty {+ breadcrumbColon+ Text(db)+ .font(.system(size: 11))+ .foregroundStyle(.secondary)+ }++ if let path = activeTablePath {+ breadcrumbColon+ Text(path)+ .font(.system(size: 11, weight: .semibold))+ }+ }+ .padding(.horizontal, 12)+ .frame(minWidth: 400)+ }+ }++ private var breadcrumbSep: some View {+ Text(" | ")+ .font(.system(size: 11))+ .foregroundStyle(.tertiary)+ }++ private var breadcrumbColon: some View {+ Text(" : ")+ .font(.system(size: 11))+ .foregroundStyle(.tertiary)+ }+}++// MARK: - Details panel (right side)++struct DetailsPanel: View {+ @EnvironmentObject private var appState: AppState+ @State private var activeTab = 0++ var body: some View {+ VStack(spacing: 0) {+ // Tab bar+ HStack(spacing: 0) {+ tabButton("Details", index: 0)+ tabButton("Assistant", index: 1)+ }+ .background(.bar)++ Divider()++ if activeTab == 0 {+ detailsContent+ } else {+ AIChatView()+ }+ }+ }++ private func tabButton(_ title: String, index: Int) -> some View {+ Button { activeTab = index } label: {+ Text(title)+ .font(.system(size: 12, weight: activeTab == index ? .semibold : .regular))+ .foregroundStyle(activeTab == index ? Color.primary : Color.secondary)+ .frame(maxWidth: .infinity)+ .padding(.vertical, 7)+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .overlay(alignment: .bottom) {+ if activeTab == index {+ Rectangle().fill(Color.accentColor).frame(height: 2)+ }+ }+ }++ @State private var detailsSearchText = ""++ private var detailsContent: some View {+ VStack(spacing: 0) {+ // Search bar+ HStack(spacing: 5) {+ Image(systemName: "magnifyingglass")+ .font(.system(size: 11))+ .foregroundStyle(.tertiary)+ TextField("Search for field...", text: $detailsSearchText)+ .textFieldStyle(.plain)+ .font(.system(size: 12))+ if !detailsSearchText.isEmpty {+ Button {+ detailsSearchText = ""+ } label: {+ Image(systemName: "xmark.circle.fill")+ .font(.system(size: 10))+ .foregroundStyle(.tertiary)+ }+ .buttonStyle(.plain)+ }+ }+ .padding(.horizontal, 8)+ .padding(.vertical, 6)++ Divider()++ if let details = appState.selectedRowDetails {+ let filtered: [(index: Int, column: String, value: String)] = {+ let indexed = details.enumerated().map { (index: $0.offset, column: $0.element.column, value: $0.element.value) }+ if detailsSearchText.isEmpty { return indexed }+ return indexed.filter {+ $0.column.localizedCaseInsensitiveContains(detailsSearchText) ||+ $0.value.localizedCaseInsensitiveContains(detailsSearchText)+ }+ }()+ ScrollView {+ LazyVStack(spacing: 0) {+ ForEach(filtered, id: \.index) { field in+ DetailFieldRow(+ column: field.column,+ value: field.value,+ onCommit: { newValue in+ appState.onDetailFieldEdit?(field.index, newValue)+ }+ )+ Divider().padding(.leading, 10)+ }+ }+ }+ } else {+ VStack(spacing: 6) {+ Text("No row selected")+ .font(.system(size: 12))+ .foregroundStyle(.secondary)+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ }+ }+ }++ private var emptyAssistant: some View {+ VStack(spacing: 8) {+ Image(systemName: "brain")+ .font(.system(size: 28))+ .foregroundStyle(.quaternary)+ Text("AI Assistant")+ .font(.system(size: 12))+ .foregroundStyle(.secondary)+ Button("Enable") { appState.aiPanelVisible = true }+ .font(.system(size: 12))+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ }+}++// MARK: - Detail Field Row++struct DetailFieldRow: View {+ let column: String+ let value: String+ let onCommit: (String) -> Void++ @State private var editText: String = ""+ @State private var isEditing = false+ @FocusState private var isFocused: Bool++ var body: some View {+ VStack(alignment: .leading, spacing: 3) {+ Text(column)+ .font(.system(size: 11, weight: .medium))+ .foregroundStyle(.secondary)+ if isEditing {+ TextField("", text: $editText, axis: .vertical)+ .font(.system(size: 12))+ .textFieldStyle(.plain)+ .focused($isFocused)+ .onSubmit {+ commitEdit()+ }+ .onChange(of: isFocused) { _, focused in+ if !focused {+ commitEdit()+ }+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ } else {+ Text(value)+ .font(.system(size: 12))+ .foregroundStyle(value == "NULL" ? .tertiary : .primary)+ .frame(maxWidth: .infinity, alignment: .leading)+ .contentShape(Rectangle())+ .onTapGesture {+ editText = value == "NULL" ? "" : value+ isEditing = true+ isFocused = true+ }+ }+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 6)+ .onChange(of: value) { _, newVal in+ // Sync if external change+ if !isEditing {+ editText = newVal+ }+ }+ }++ private func commitEdit() {+ isEditing = false+ let trimmed = editText+ if trimmed != value {+ onCommit(trimmed)+ }+ }+}++// MARK: - Connected Welcome++struct ConnectedWelcomeView: View {+ var body: some View {+ VStack(spacing: 0) {+ Spacer()++ VStack(spacing: 16) {+ // Placeholder illustration (robot + fishbowl style)+ ZStack {+ Circle()+ .fill(Color.secondary.opacity(0.06))+ .frame(width: 120, height: 120)+ Image(systemName: "terminal")+ .font(.system(size: 38))+ .foregroundStyle(Color.secondary.opacity(0.3))+ }++ VStack(spacing: 6) {+ Text("Console log, please execute a query")+ .font(.system(size: 13))+ .foregroundStyle(.secondary)+ Text("or select a table to see the log")+ .font(.system(size: 13))+ .foregroundStyle(.secondary)+ }+ }++ Spacer()++ // Bottom bar (matches Gridex style)+ Divider()+ HStack(spacing: 12) {+ Button {+ } label: {+ Image(systemName: "trash")+ .font(.system(size: 12))+ .foregroundStyle(.secondary)+ }+ .buttonStyle(.plain)++ Divider().frame(height: 14)++ Toggle(isOn: .constant(true)) {+ Text("Enable syntax highlighting")+ .font(.system(size: 12))+ .foregroundStyle(.secondary)+ }+ .toggleStyle(.checkbox)++ Spacer()+ }+ .padding(.horizontal, 12)+ .padding(.vertical, 6)+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ }+}++// MARK: - Resize Handle++/// Draggable vertical divider backed by an NSView to avoid SwiftUI jitter.+private struct ResizeHandle: NSViewRepresentable {+ @Binding var width: CGFloat+ let minWidth: CGFloat+ let maxWidth: CGFloat++ func makeNSView(context: Context) -> ResizeHandleView {+ let view = ResizeHandleView()+ view.setWidth = { newWidth in+ self.width = min(max(newWidth, self.minWidth), self.maxWidth)+ }+ view.getWidth = { self.width }+ return view+ }++ func updateNSView(_ nsView: ResizeHandleView, context: Context) {+ nsView.setWidth = { newWidth in+ self.width = min(max(newWidth, self.minWidth), self.maxWidth)+ }+ nsView.getWidth = { self.width }+ }+}++final class ResizeHandleView: NSView {+ var setWidth: ((CGFloat) -> Void)?+ var getWidth: (() -> CGFloat)?++ private var dragStartX: CGFloat = 0+ private var dragStartWidth: CGFloat = 0++ override init(frame frameRect: NSRect) {+ super.init(frame: frameRect)+ wantsLayer = true+ layer?.backgroundColor = NSColor.separatorColor.cgColor+ }+ required init?(coder: NSCoder) { fatalError() }++ override var intrinsicContentSize: NSSize {+ NSSize(width: 1, height: NSView.noIntrinsicMetric)+ }++ override func resetCursorRects() {+ let hitArea = NSRect(x: -3, y: 0, width: 7, height: bounds.height)+ addCursorRect(hitArea, cursor: .resizeLeftRight)+ }++ override func mouseDown(with event: NSEvent) {+ dragStartX = event.locationInWindow.x+ dragStartWidth = getWidth?() ?? 0+ }++ override func mouseDragged(with event: NSEvent) {+ let deltaX = event.locationInWindow.x - dragStartX+ // Drag right (positive delta) → panel shrinks+ let newWidth = dragStartWidth - deltaX+ setWidth?(newWidth)+ }+}diff --git a/macos/Presentation/Views/MongoDB/MongoDocumentEditorSheet.swift b/macos/Presentation/Views/MongoDB/MongoDocumentEditorSheet.swiftnew file mode 100644index 0000000..7ad0d56--- /dev/null+++ b/macos/Presentation/Views/MongoDB/MongoDocumentEditorSheet.swift@@ -0,0 +1,156 @@+// MongoDocumentEditorSheet.swift+// Gridex+//+// JSON document editor for inserting MongoDB documents.++import SwiftUI++struct MongoDocumentEditorSheet: View {+ let collectionName: String+ let detectedFields: [(name: String, type: String)]+ let onInsert: (String) async -> Result<Void, Error>++ @Environment(\.dismiss) private var dismiss+ @State private var jsonText: String = ""+ @State private var isInserting = false+ @State private var errorMessage: String?++ var body: some View {+ VStack(spacing: 0) {+ // Header+ HStack(spacing: 8) {+ Image(systemName: "doc.text")+ .foregroundStyle(.green)+ Text("Insert Document")+ .font(.system(size: 14, weight: .semibold))+ Text("·")+ .foregroundStyle(.tertiary)+ Text(collectionName)+ .font(.system(size: 12, design: .monospaced))+ .foregroundStyle(.secondary)+ Spacer()+ Button(action: { jsonText = templateJSON() }) {+ Label("Reset", systemImage: "arrow.counterclockwise")+ .font(.system(size: 11))+ }+ .buttonStyle(.plain)+ .help("Reset to template from detected fields")+ }+ .padding(.horizontal, 16)+ .padding(.vertical, 12)++ Divider()++ // JSON editor+ ScrollView {+ TextEditor(text: $jsonText)+ .font(.system(size: 12, design: .monospaced))+ .frame(minHeight: 280)+ .padding(8)+ .scrollContentBackground(.hidden)+ .background(Color(nsColor: .textBackgroundColor))+ }+ .frame(minHeight: 300)++ if let errorMessage {+ Divider()+ HStack(spacing: 6) {+ Image(systemName: "exclamationmark.triangle.fill")+ .foregroundStyle(.red)+ Text(errorMessage)+ .font(.system(size: 11))+ .foregroundStyle(.red)+ .lineLimit(3)+ Spacer()+ }+ .padding(.horizontal, 16)+ .padding(.vertical, 8)+ .background(Color.red.opacity(0.08))+ }++ Divider()++ // Footer+ HStack {+ if !detectedFields.isEmpty {+ Text("\(detectedFields.count) fields detected from samples")+ .font(.system(size: 11))+ .foregroundStyle(.tertiary)+ }+ Spacer()+ Button("Cancel") { dismiss() }+ .keyboardShortcut(.cancelAction)+ Button(action: insert) {+ HStack(spacing: 6) {+ if isInserting {+ ProgressView().controlSize(.small)+ }+ Text("Insert")+ }+ }+ .buttonStyle(.borderedProminent)+ .keyboardShortcut(.defaultAction)+ .disabled(jsonText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || isInserting)+ }+ .padding(.horizontal, 16)+ .padding(.vertical, 12)+ }+ .frame(width: 560, height: 460)+ .onAppear {+ if jsonText.isEmpty {+ jsonText = templateJSON()+ }+ }+ }++ private func templateJSON() -> String {+ // Build a template document from detected fields, excluding _id+ // (Mongo will auto-generate _id on insert)+ let fields = detectedFields.filter { $0.name != "_id" }+ if fields.isEmpty {+ return """+ {+ "name": "",+ "createdAt": { "$date": "\(ISO8601DateFormatter().string(from: Date()))" }+ }+ """+ }+ var lines: [String] = ["{"]+ for (idx, field) in fields.enumerated() {+ let placeholder = templateValue(for: field.type)+ let comma = idx < fields.count - 1 ? "," : ""+ lines.append(" \"\(field.name)\": \(placeholder)\(comma)")+ }+ lines.append("}")+ return lines.joined(separator: "\n")+ }++ private func templateValue(for type: String) -> String {+ switch type {+ case "string": return "\"\""+ case "integer": return "0"+ case "double": return "0.0"+ case "boolean": return "false"+ case "date": return "{ \"$date\": \"\(ISO8601DateFormatter().string(from: Date()))\" }"+ case "objectId": return "{ \"$oid\": \"000000000000000000000000\" }"+ case "document": return "{}"+ case "array": return "[]"+ default: return "null"+ }+ }++ private func insert() {+ errorMessage = nil+ isInserting = true+ Task {+ let result = await onInsert(jsonText)+ isInserting = false+ switch result {+ case .success:+ dismiss()+ case .failure(let error):+ errorMessage = error.localizedDescription+ }+ }+ }+}diff --git a/macos/Presentation/Views/QueryEditor/Autocomplete/AutocompleteProvider.swift b/macos/Presentation/Views/QueryEditor/Autocomplete/AutocompleteProvider.swiftnew file mode 100644index 0000000..13e6400--- /dev/null+++ b/macos/Presentation/Views/QueryEditor/Autocomplete/AutocompleteProvider.swift@@ -0,0 +1,577 @@+// AutocompleteProvider.swift+// Gridex+//+// Context-aware SQL autocomplete with FK-based JOIN suggestions,+// fuzzy matching, and smart ranking.++import Foundation++final class AutocompleteProvider {+ private var tableNames: [String] = []+ private var columnsByTable: [String: [ColumnInfo]] = [:]+ private var foreignKeys: [String: [ForeignKeyInfo]] = [:]+ private var allColumnNames: [String] = []+ private var recentlyUsed: [String] = []++ // MARK: - Schema Update++ func updateSchema(_ tables: [TableDescription]) {+ tableNames = tables.map(\.name).sorted()+ columnsByTable = Dictionary(uniqueKeysWithValues: tables.map { ($0.name, $0.columns) })+ foreignKeys = Dictionary(uniqueKeysWithValues: tables.map { ($0.name, $0.foreignKeys) })+ allColumnNames = Array(Set(tables.flatMap { $0.columns.map(\.name) })).sorted()+ }++ func trackUsed(_ text: String) {+ recentlyUsed.removeAll { $0 == text }+ recentlyUsed.insert(text, at: 0)+ if recentlyUsed.count > 50 { recentlyUsed.removeLast() }+ }++ // MARK: - Suggestions++ func suggestions(for context: CompletionContext) -> [CompletionItem] {+ var items: [CompletionItem]++ switch context.trigger {+ case .none:+ return []+ case .keyword:+ items = keywordSuggestions(prefix: context.prefix)+ case .table:+ items = tableSuggestions(prefix: context.prefix)+ case .column(let table):+ items = columnSuggestions(table: table, prefix: context.prefix, scopeTables: context.scopeTables)+ case .join(let fromTables):+ items = joinSuggestions(fromTables: fromTables, prefix: context.prefix)+ case .selectList(let scopeTables):+ items = selectListSuggestions(prefix: context.prefix, scopeTables: scopeTables)+ case .afterIdentifier(let clause, let scopeTables):+ items = afterIdentifierSuggestions(clause: clause, prefix: context.prefix, scopeTables: scopeTables)+ case .function:+ items = functionSuggestions(prefix: context.prefix)+ case .general:+ items = generalSuggestions(prefix: context.prefix, scopeTables: context.scopeTables)+ }++ // Boost recently used+ for i in items.indices {+ if let idx = recentlyUsed.firstIndex(of: items[i].text) {+ items[i].score += 30 - idx+ }+ }++ // Deduplicate by (text + type), keeping highest score+ var seen: [String: Int] = [:]+ var deduplicated: [CompletionItem] = []+ for item in items {+ let key = "\(item.text.lowercased())|\(item.type)"+ if let existing = seen[key] {+ if item.score > existing {+ if let idx = deduplicated.firstIndex(where: {+ "\($0.text.lowercased())|\($0.type)" == key+ }) {+ deduplicated[idx] = item+ }+ seen[key] = item.score+ }+ } else {+ seen[key] = item.score+ deduplicated.append(item)+ }+ }++ // Sort by score descending, then by type priority, then alphabetically+ deduplicated.sort { a, b in+ 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+ }++ // Show up to 20 items — let user scroll through all matches+ return Array(deduplicated.prefix(20))+ }++ private func typeRank(_ type: CompletionItem.CompletionType) -> Int {+ switch type {+ case .keyword: return 0+ case .table: return 1+ case .column: return 2+ case .function: return 3+ case .join: return 4+ }+ }++ // MARK: - Keyword Suggestions++ private func keywordSuggestions(prefix: String) -> [CompletionItem] {+ return Self.sqlKeywords.compactMap { kw in+ guard let score = fuzzyScore(prefix, kw) else { return nil }+ // Boost common clause keywords so they appear first+ let boost = Self.primaryKeywords.contains(kw) ? 100 : 0+ return CompletionItem(text: kw, type: .keyword, detail: nil, insertText: kw,+ score: score + boost, matchRanges: fuzzyMatchRanges(prefix, kw))+ }+ }++ /// Top-tier SQL keywords that should rank highest in suggestions.+ private static let primaryKeywords: Set<String> = [+ "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"+ ]++ // MARK: - Table Suggestions++ private func tableSuggestions(prefix: String) -> [CompletionItem] {+ return tableNames.compactMap { name in+ guard prefix.isEmpty || fuzzyScore(prefix, name) != nil else { return nil }+ let score = prefix.isEmpty ? 0 : (fuzzyScore(prefix, name) ?? 0)+ let cols = columnsByTable[name]?.count ?? 0+ return CompletionItem(text: name, type: .table, detail: "\(cols) cols",+ insertText: name, score: score,+ matchRanges: prefix.isEmpty ? [] : fuzzyMatchRanges(prefix, name))+ }+ }++ // MARK: - Column Suggestions++ private func columnSuggestions(table: String?, prefix: String, scopeTables: [TableRef]) -> [CompletionItem] {+ var items: [CompletionItem] = []++ // Columns from the specific table (highest priority)+ if let table, let columns = columnsByTable[table] {+ for col in columns {+ guard prefix.isEmpty || fuzzyScore(prefix, col.name) != nil else { continue }+ let score = (prefix.isEmpty ? 10 : (fuzzyScore(prefix, col.name) ?? 0)) ++ (col.isPrimaryKey ? 5 : 0)+ items.append(CompletionItem(+ text: col.name, type: .column, detail: "\(col.dataType) · \(table)",+ insertText: col.name, score: score,+ matchRanges: prefix.isEmpty ? [] : fuzzyMatchRanges(prefix, col.name)+ ))+ }+ }++ // Columns from all scope tables (if no specific table or augmenting)+ if table == nil {+ let scopeTableNames = Set(scopeTables.map(\.name))+ for ref in scopeTables {+ guard let columns = columnsByTable[ref.name] else { continue }+ let qualifier = ref.alias ?? ref.name+ for col in columns {+ guard prefix.isEmpty || fuzzyScore(prefix, col.name) != nil else { continue }+ let score = (prefix.isEmpty ? 8 : (fuzzyScore(prefix, col.name) ?? 0)) ++ (col.isPrimaryKey ? 5 : 0) ++ (scopeTableNames.contains(ref.name) ? 3 : 0)+ let detail = "\(col.dataType) · \(qualifier)"+ items.append(CompletionItem(+ text: col.name, type: .column, detail: detail,+ insertText: col.name, score: score,+ matchRanges: prefix.isEmpty ? [] : fuzzyMatchRanges(prefix, col.name)+ ))+ }+ }+ }++ // Deduplicate by name, keeping highest score+ var seen: [String: Int] = [:]+ items = items.filter { item in+ if let existing = seen[item.text], existing >= item.score { return false }+ seen[item.text] = item.score+ return true+ }++ return items+ }++ // MARK: - JOIN Suggestions (FK-aware)++ private func joinSuggestions(fromTables: [TableRef], prefix: String) -> [CompletionItem] {+ var items: [CompletionItem] = []++ for tableRef in fromTables {+ let tableName = tableRef.name+ let alias = tableRef.alias ?? tableName++ // FK from this table → referenced tables+ if let fks = foreignKeys[tableName] {+ for fk in fks {+ let refTable = fk.referencedTable+ let refAlias = suggestAlias(for: refTable, existing: fromTables)+ let onClause = zip(fk.columns, fk.referencedColumns)+ .map { "\(alias).\($0.0) = \(refAlias).\($0.1)" }+ .joined(separator: " AND ")+ let insertText = "JOIN \(refTable) \(refAlias) ON \(onClause)"+ let displayText = "JOIN \(refTable) \(refAlias) ON \(onClause)"++ guard prefix.isEmpty || fuzzyScore(prefix, insertText) != nil ||+ fuzzyScore(prefix, refTable) != nil else { continue }++ items.append(CompletionItem(+ text: displayText, type: .join,+ detail: "FK: \(fk.columns.joined(separator: ","))",+ insertText: insertText, score: 20,+ matchRanges: []+ ))+ }+ }++ // Reverse FKs: other tables referencing this table+ for (otherTable, otherFks) in foreignKeys {+ guard otherTable != tableName else { continue }+ for fk in otherFks where fk.referencedTable == tableName {+ let refAlias = suggestAlias(for: otherTable, existing: fromTables)+ let onClause = zip(fk.referencedColumns, fk.columns)+ .map { "\(alias).\($0.0) = \(refAlias).\($0.1)" }+ .joined(separator: " AND ")+ let insertText = "JOIN \(otherTable) \(refAlias) ON \(onClause)"++ guard prefix.isEmpty || fuzzyScore(prefix, insertText) != nil ||+ fuzzyScore(prefix, otherTable) != nil else { continue }++ items.append(CompletionItem(+ text: insertText, type: .join,+ detail: "FK: \(otherTable).\(fk.columns.joined(separator: ","))",+ insertText: insertText, score: 18,+ matchRanges: []+ ))+ }+ }+ }++ // If no FK matches, fall back to table suggestions prefixed with JOIN+ if items.isEmpty {+ let tables = tableSuggestions(prefix: prefix)+ items = tables.map { item in+ CompletionItem(text: "JOIN \(item.text)", type: .join, detail: item.detail,+ insertText: "JOIN \(item.insertText)", score: item.score,+ matchRanges: [])+ }+ }++ return items+ }++ // MARK: - SELECT List (columns + functions + *)++ private func selectListSuggestions(prefix: String, scopeTables: [TableRef]) -> [CompletionItem] {+ var items: [CompletionItem] = []++ // Star shortcut+ if prefix.isEmpty || "*".hasPrefix(prefix) {+ items.append(CompletionItem(text: "*", type: .keyword, detail: "All columns",+ insertText: "*", score: 20, matchRanges: []))+ }++ // Functions (high priority in SELECT)+ items.append(contentsOf: functionSuggestions(prefix: prefix).map {+ var item = $0; item.score += 5; return item+ })++ // Columns from scope tables+ items.append(contentsOf: columnSuggestions(table: nil, prefix: prefix, scopeTables: scopeTables))++ // DISTINCT keyword+ if prefix.isEmpty || fuzzyScore(prefix, "DISTINCT") != nil {+ items.append(CompletionItem(text: "DISTINCT", type: .keyword, detail: nil,+ insertText: "DISTINCT", score: fuzzyScore(prefix, "DISTINCT") ?? 8,+ matchRanges: prefix.isEmpty ? [] : fuzzyMatchRanges(prefix, "DISTINCT")))+ }++ return items+ }++ // MARK: - After Identifier (suggest next keywords based on clause)++ private func afterIdentifierSuggestions(clause: String, prefix: String, scopeTables: [TableRef]) -> [CompletionItem] {+ // Context-aware next-keyword suggestions+ let nextKeywords: [String]++ switch clause {+ case "SELECT":+ nextKeywords = ["FROM"]+ case "FROM":+ nextKeywords = ["WHERE", "JOIN", "LEFT JOIN", "RIGHT JOIN", "INNER JOIN",+ "FULL JOIN", "CROSS JOIN", "ORDER BY", "GROUP BY",+ "LIMIT", "OFFSET", "UNION", "RETURNING"]+ case "JOIN":+ nextKeywords = ["ON", "WHERE", "JOIN", "LEFT JOIN", "RIGHT JOIN",+ "ORDER BY", "GROUP BY", "LIMIT"]+ case "WHERE":+ nextKeywords = ["AND", "OR", "ORDER BY", "GROUP BY", "LIMIT",+ "UNION", "RETURNING"]+ case "ORDER BY", "GROUP BY":+ nextKeywords = ["LIMIT", "OFFSET", "ASC", "DESC"]+ case "HAVING":+ nextKeywords = ["ORDER BY", "LIMIT"]+ case "INSERT":+ nextKeywords = ["VALUES", "SELECT", "RETURNING"]+ default:+ nextKeywords = ["SELECT", "FROM", "WHERE", "JOIN", "ORDER BY",+ "GROUP BY", "LIMIT", "HAVING", "AND", "OR"]+ }++ return nextKeywords.compactMap { kw in+ guard prefix.isEmpty || fuzzyScore(prefix, kw) != nil else { return nil }+ let score = prefix.isEmpty ? 15 : (fuzzyScore(prefix, kw) ?? 0) + 10+ return CompletionItem(text: kw, type: .keyword, detail: nil,+ insertText: kw, score: score,+ matchRanges: prefix.isEmpty ? [] : fuzzyMatchRanges(prefix, kw))+ }+ }++ // MARK: - Function Suggestions++ private func functionSuggestions(prefix: String) -> [CompletionItem] {+ return Self.sqlFunctions.compactMap { fn in+ guard prefix.isEmpty || fuzzyScore(prefix, fn.name) != nil else { return nil }+ // Functions are slightly deprioritized vs keywords at same score+ let score = prefix.isEmpty ? 0 : ((fuzzyScore(prefix, fn.name) ?? 0) - 10)+ return CompletionItem(+ text: fn.name, type: .function, detail: fn.signature,+ insertText: fn.snippet, score: score,+ matchRanges: prefix.isEmpty ? [] : fuzzyMatchRanges(prefix, fn.name)+ )+ }+ }++ // MARK: - General (search everything)++ private func generalSuggestions(prefix: String, scopeTables: [TableRef]) -> [CompletionItem] {+ guard !prefix.isEmpty else { return [] }+ var items: [CompletionItem] = []+ items.append(contentsOf: keywordSuggestions(prefix: prefix))+ items.append(contentsOf: tableSuggestions(prefix: prefix))+ items.append(contentsOf: allColumnsSuggestions(prefix: prefix))+ items.append(contentsOf: functionSuggestions(prefix: prefix))+ return items+ }++ /// Search columns across ALL tables (not scoped to a query).+ private func allColumnsSuggestions(prefix: String) -> [CompletionItem] {+ var items: [CompletionItem] = []+ for (tableName, columns) in columnsByTable {+ for col in columns {+ guard let score = fuzzyScore(prefix, col.name) else { continue }+ items.append(CompletionItem(+ text: col.name, type: .column,+ detail: "\(col.dataType) · \(tableName)",+ insertText: col.name,+ score: score + (col.isPrimaryKey ? 3 : 0),+ matchRanges: fuzzyMatchRanges(prefix, col.name)+ ))+ }+ }+ return items+ }++ // MARK: - Fuzzy Matching++ /// Returns a score if query matches candidate, nil if no match.+ /// Strongly favors prefix matches over fuzzy subsequence matches.+ func fuzzyScore(_ query: String, _ candidate: String) -> Int? {+ guard !query.isEmpty else { return 0 }++ let q = query.lowercased()+ let c = candidate.lowercased()++ // Exact match — highest priority+ if q == c { return 1000 }++ // Exact prefix match — very strong boost+ if c.hasPrefix(q) {+ // Shorter candidates rank higher (SELECT beats SUBSTRING for "s")+ let lengthPenalty = max(0, candidate.count - query.count)+ return 500 - lengthPenalty+ }++ // Word-boundary prefix match (e.g., "uid" matches "user_id" at "_id")+ // Check if any word in the candidate starts with the query+ let words = c.split(whereSeparator: { $0 == "_" || $0 == "." || $0 == " " })+ for word in words {+ if word.hasPrefix(q) {+ return 200 - max(0, candidate.count - query.count)+ }+ }++ // Fuzzy subsequence match — weakest priority+ let qChars = Array(q)+ let cChars = Array(c)+ var qi = 0+ var score = 0+ var consecutive = 0+ var lastMatchIndex = -2++ for (ci, ch) in cChars.enumerated() {+ guard qi < qChars.count else { break }+ if ch == qChars[qi] {+ score += 1+ if ci == lastMatchIndex + 1 {+ consecutive += 1+ score += consecutive+ } else {+ consecutive = 0+ }+ if ci > 0 {+ let prev = cChars[ci - 1]+ if prev == "_" || prev == "." { score += 3 }+ }+ lastMatchIndex = ci+ qi += 1+ }+ }++ return qi == qChars.count ? score : nil+ }++ /// Returns ranges of matched characters for highlighting.+ func fuzzyMatchRanges(_ query: String, _ candidate: String) -> [Int] {+ let q = Array(query.lowercased())+ let c = Array(candidate.lowercased())+ var qi = 0+ var ranges: [Int] = []++ for (ci, ch) in c.enumerated() {+ guard qi < q.count else { break }+ if ch == q[qi] {+ ranges.append(ci)+ qi += 1+ }+ }+ return ranges+ }++ // MARK: - Helpers++ private func suggestAlias(for table: String, existing: [TableRef]) -> String {+ let usedAliases = Set(existing.compactMap { $0.alias ?? $0.name })+ let base = String(table.prefix(1)).lowercased()+ if !usedAliases.contains(base) { return base }+ let base2 = String(table.prefix(2)).lowercased()+ if !usedAliases.contains(base2) { return base2 }+ let base3 = String(table.prefix(3)).lowercased()+ if !usedAliases.contains(base3) { return base3 }+ return table+ }++ // MARK: - SQL Keywords & Functions++ static let sqlKeywords: [String] = [+ "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"+ ]++ static let sqlFunctions: [(name: String, signature: String, snippet: String)] = [+ ("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 → 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(, '')"),+ ]+}++// MARK: - Models++struct CompletionItem: Identifiable {+ let id = UUID()+ let text: String+ let type: CompletionType+ let detail: String?+ let insertText: String+ var score: Int+ var matchRanges: [Int] // Indices of matched chars for highlighting++ enum CompletionType: Equatable {+ case keyword, table, column, function, join++ var icon: String {+ switch self {+ case .keyword: return "k"+ case .table: return "T"+ case .column: return "C"+ case .function: return "f"+ case .join: return "J"+ }+ }++ var iconColor: (r: CGFloat, g: CGFloat, b: CGFloat) {+ switch self {+ case .keyword: return (0.67, 0.33, 0.67)+ case .table: return (0.33, 0.67, 0.33)+ case .column: return (0.33, 0.53, 0.87)+ case .function: return (0.87, 0.67, 0.33)+ case .join: return (0.53, 0.33, 0.87)+ }+ }+ }+}++struct TableRef {+ let name: String+ let alias: String?+}++struct CompletionContext {+ let trigger: CompletionTrigger+ let prefix: String+ let scopeTables: [TableRef]+}++enum CompletionTrigger {+ case none // Inside string literal, no completions+ case keyword // Suggest SQL keywords+ case table // Suggest table names+ case column(table: String?) // Suggest columns (optionally scoped to table)+ case join(fromTables: [TableRef]) // Suggest FK-aware JOINs+ case selectList(scopeTables: [TableRef]) // After SELECT: *, functions, columns, DISTINCT+ case afterIdentifier(clause: String, scopeTables: [TableRef]) // After table/column name: next keywords+ case function // Suggest SQL functions+ case general // Mixed suggestions+}diff --git a/macos/Presentation/Views/QueryEditor/Autocomplete/CompletionWindow.swift b/macos/Presentation/Views/QueryEditor/Autocomplete/CompletionWindow.swiftnew file mode 100644index 0000000..f9ae183--- /dev/null+++ b/macos/Presentation/Views/QueryEditor/Autocomplete/CompletionWindow.swift@@ -0,0 +1,274 @@+// CompletionWindow.swift+// Gridex+//+// Simple NSStackView-based autocomplete popup. No scroll view, no table view.+// Max 10 items — all rendered inline as NSStackView rows.++import AppKit++final class CompletionWindow: NSPanel {+ private let stackView = NSStackView()+ private let footerLabel = NSTextField(labelWithString: "")+ private var items: [CompletionItem] = []+ private var rowViews: [CompletionRowView] = []+ private var selectedIndex: Int = 0+ var onSelect: ((CompletionItem) -> Void)?++ private let rowHeight: CGFloat = 28+ private let maxRows = 10+ private let windowWidth: CGFloat = 420+ private let footerHeight: CGFloat = 22+ private let topPadding: CGFloat = 4+ private let bottomPadding: CGFloat = 4++ override var canBecomeKey: Bool { false }++ init() {+ super.init(+ contentRect: NSRect(x: 0, y: 0, width: 420, height: 100),+ styleMask: [.borderless, .nonactivatingPanel],+ backing: .buffered,+ defer: true+ )++ isOpaque = false+ backgroundColor = .clear+ level = .floating+ hasShadow = true+ isMovableByWindowBackground = false+ hidesOnDeactivate = true++ setupUI()+ }++ private func setupUI() {+ let container = NSVisualEffectView(frame: contentView!.bounds)+ container.material = .popover+ container.state = .active+ container.blendingMode = .behindWindow+ container.wantsLayer = true+ container.layer?.cornerRadius = 6+ container.layer?.masksToBounds = true+ container.autoresizingMask = [.width, .height]+ contentView?.addSubview(container)++ // Vertical stack of rows+ stackView.orientation = .vertical+ stackView.alignment = .leading+ stackView.distribution = .fill+ stackView.spacing = 0+ stackView.translatesAutoresizingMaskIntoConstraints = false++ // Footer+ footerLabel.font = NSFont.systemFont(ofSize: 10)+ footerLabel.textColor = .tertiaryLabelColor+ footerLabel.translatesAutoresizingMaskIntoConstraints = false++ container.addSubview(stackView)+ container.addSubview(footerLabel)++ NSLayoutConstraint.activate([+ stackView.topAnchor.constraint(equalTo: container.topAnchor, constant: topPadding),+ stackView.leadingAnchor.constraint(equalTo: container.leadingAnchor),+ stackView.trailingAnchor.constraint(equalTo: container.trailingAnchor),++ footerLabel.topAnchor.constraint(equalTo: stackView.bottomAnchor, constant: bottomPadding),+ footerLabel.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: 10),+ footerLabel.trailingAnchor.constraint(equalTo: container.trailingAnchor, constant: -10),+ footerLabel.bottomAnchor.constraint(equalTo: container.bottomAnchor, constant: -4),+ footerLabel.heightAnchor.constraint(equalToConstant: 14)+ ])+ }++ // MARK: - Public API++ func show(items: [CompletionItem], at screenPoint: NSPoint) {+ let visible = Array(items.prefix(maxRows))+ guard !visible.isEmpty else { dismiss(); return }++ self.items = visible+ self.selectedIndex = 0++ // Rebuild rows+ rowViews.forEach { $0.removeFromSuperview() }+ rowViews.removeAll()++ for (i, item) in visible.enumerated() {+ let row = CompletionRowView(item: item, width: windowWidth, height: rowHeight)+ row.translatesAutoresizingMaskIntoConstraints = false+ row.onClick = { [weak self] in+ self?.selectedIndex = i+ self?.updateSelection()+ self?.onSelect?(item)+ }+ stackView.addArrangedSubview(row)+ NSLayoutConstraint.activate([+ row.widthAnchor.constraint(equalToConstant: windowWidth),+ row.heightAnchor.constraint(equalToConstant: rowHeight)+ ])+ rowViews.append(row)+ }++ updateSelection()++ let tableHeight = CGFloat(visible.count) * rowHeight+ let contentHeight = topPadding + tableHeight + bottomPadding + footerHeight + 4++ setContentSize(NSSize(width: windowWidth, height: contentHeight))++ var origin = NSPoint(x: screenPoint.x, y: screenPoint.y - contentHeight)+ if let screen = NSScreen.main?.visibleFrame {+ let maxX = screen.maxX - windowWidth - 8+ origin.x = min(origin.x, maxX)+ origin.x = max(origin.x, screen.minX + 8)+ if origin.y < screen.minY + 8 {+ origin.y = screenPoint.y + 20+ }+ }+ setFrameOrigin(origin)+ contentView?.layoutSubtreeIfNeeded()++ footerLabel.stringValue = "Press ↩ to insert, ⇥ to replace · \(items.count) items"++ if !isVisible {+ orderFront(nil)+ }+ }++ func dismiss() {+ orderOut(nil)+ items = []+ rowViews.forEach { $0.removeFromSuperview() }+ rowViews.removeAll()+ }++ var isActive: Bool { isVisible && !items.isEmpty }++ var selectedItem: CompletionItem? {+ guard selectedIndex >= 0, selectedIndex < items.count else { return nil }+ return items[selectedIndex]+ }++ func moveSelectionUp() {+ selectedIndex = max(0, selectedIndex - 1)+ updateSelection()+ }++ func moveSelectionDown() {+ selectedIndex = min(items.count - 1, selectedIndex + 1)+ updateSelection()+ }++ private func updateSelection() {+ for (i, row) in rowViews.enumerated() {+ row.setSelected(i == selectedIndex)+ }+ }+}++// MARK: - Completion Row View++private final class CompletionRowView: NSView {+ private let item: CompletionItem+ private let iconLabel = NSTextField(labelWithString: "")+ private let textLabel = NSTextField(labelWithString: "")+ private let detailLabel = NSTextField(labelWithString: "")+ var onClick: (() -> Void)?++ override var isFlipped: Bool { true }++ init(item: CompletionItem, width: CGFloat, height: CGFloat) {+ self.item = item+ super.init(frame: NSRect(x: 0, y: 0, width: width, height: height))+ wantsLayer = true+ layer?.masksToBounds = true+ setupContent(width: width, height: height)+ }++ required init?(coder: NSCoder) { fatalError() }++ private func setupContent(width: CGFloat, height: CGFloat) {+ // Icon badge (18x16, vertically centered)+ let iconHeight: CGFloat = 16+ let iconY = (height - iconHeight) / 2+ iconLabel.stringValue = item.type.icon+ iconLabel.font = NSFont.monospacedSystemFont(ofSize: 9, weight: .bold)+ let c = item.type.iconColor+ iconLabel.textColor = NSColor(red: c.r, green: c.g, blue: c.b, alpha: 1)+ iconLabel.alignment = .center+ iconLabel.wantsLayer = true+ iconLabel.layer?.backgroundColor = NSColor(red: c.r, green: c.g, blue: c.b, alpha: 0.15).cgColor+ iconLabel.layer?.cornerRadius = 3+ iconLabel.frame = NSRect(x: 10, y: iconY, width: 18, height: iconHeight)+ addSubview(iconLabel)++ // Text labels use a tight height (18) centered in the row,+ // so their baseline matches the icon badge center.+ let labelHeight: CGFloat = 18+ let labelY = (height - labelHeight) / 2++ // Detail label (right-aligned)+ detailLabel.attributedStringValue = NSAttributedString(+ string: item.detail ?? "",+ attributes: [+ .font: NSFont.systemFont(ofSize: 10),+ .foregroundColor: NSColor.tertiaryLabelColor+ ]+ )+ detailLabel.alignment = .right+ detailLabel.maximumNumberOfLines = 1+ if let cell = detailLabel.cell as? NSTextFieldCell {+ cell.lineBreakMode = .byTruncatingTail+ cell.usesSingleLineMode = true+ cell.truncatesLastVisibleLine = true+ }+ let detailWidth: CGFloat = 140+ detailLabel.frame = NSRect(x: width - detailWidth - 12, y: labelY, width: detailWidth, height: labelHeight)+ addSubview(detailLabel)++ // Main text+ textLabel.attributedStringValue = highlightedText(for: item)+ textLabel.maximumNumberOfLines = 1+ if let cell = textLabel.cell as? NSTextFieldCell {+ cell.lineBreakMode = .byTruncatingTail+ cell.usesSingleLineMode = true+ cell.truncatesLastVisibleLine = true+ }+ let textX: CGFloat = 10 + 18 + 8+ let textWidth = width - textX - detailWidth - 14+ textLabel.frame = NSRect(x: textX, y: labelY, width: textWidth, height: labelHeight)+ addSubview(textLabel)+ }++ func setSelected(_ selected: Bool) {+ layer?.backgroundColor = selected+ ? NSColor.selectedContentBackgroundColor.withAlphaComponent(0.4).cgColor+ : NSColor.clear.cgColor+ }++ override func mouseDown(with event: NSEvent) {+ onClick?()+ }++ override func resetCursorRects() {+ addCursorRect(bounds, cursor: .pointingHand)+ }++ private func highlightedText(for item: CompletionItem) -> NSAttributedString {+ let str = NSMutableAttributedString(+ string: item.text,+ attributes: [+ .font: NSFont.monospacedSystemFont(ofSize: 12, weight: .regular),+ .foregroundColor: NSColor.labelColor+ ]+ )+ let boldFont = NSFont.monospacedSystemFont(ofSize: 12, weight: .bold)+ for charIndex in item.matchRanges {+ guard charIndex < item.text.count else { continue }+ let nsRange = NSRange(location: charIndex, length: 1)+ str.addAttribute(.font, value: boldFont, range: nsRange)+ str.addAttribute(.foregroundColor, value: NSColor.controlAccentColor, range: nsRange)+ }+ return str+ }+}diff --git a/macos/Presentation/Views/QueryEditor/Autocomplete/SQLContextParser.swift b/macos/Presentation/Views/QueryEditor/Autocomplete/SQLContextParser.swiftnew file mode 100644index 0000000..49c82f9--- /dev/null+++ b/macos/Presentation/Views/QueryEditor/Autocomplete/SQLContextParser.swift@@ -0,0 +1,427 @@+// SQLContextParser.swift+// Gridex+//+// Parses SQL text to determine autocomplete context at cursor position.+// Handles: statement isolation, string detection, aliases, CTEs,+// multi-table scope, compound keywords, positional awareness.++import Foundation++final class SQLContextParser {++ /// Analyze SQL text up to cursor position and return completion context.+ func parse(sql: String, cursorOffset: Int) -> CompletionContext {+ let safeOffset = max(0, min(cursorOffset, sql.count))+ let fullText = String(sql.prefix(safeOffset))++ // 1. Check if cursor is inside a string literal → no completions+ if isInsideString(fullText) {+ return CompletionContext(trigger: .none, prefix: "", scopeTables: [])+ }++ // 2. Isolate current statement (split by ;)+ let currentStatement = isolateCurrentStatement(fullText)++ let prefix = currentWord(in: currentStatement)+ let tokens = tokenize(currentStatement)+ let scopeTables = extractAllTables(tokens: tokens)+ let trigger = determineTrigger(tokens: tokens, text: currentStatement, prefix: prefix, scopeTables: scopeTables)++ return CompletionContext(trigger: trigger, prefix: prefix, scopeTables: scopeTables)+ }++ // MARK: - String Literal Detection++ private func isInsideString(_ text: String) -> Bool {+ var inSingle = false+ for ch in text {+ if ch == "'" { inSingle.toggle() }+ }+ return inSingle+ }++ // MARK: - Statement Isolation++ private func isolateCurrentStatement(_ text: String) -> String {+ // Find the last ; and take everything after it+ if let lastSemicolon = text.lastIndex(of: ";") {+ let after = text[text.index(after: lastSemicolon)...]+ return String(after).trimmingCharacters(in: .whitespaces).isEmpty+ ? String(after) : String(after)+ }+ return text+ }++ // MARK: - Current Word++ private func currentWord(in text: String) -> String {+ var start = text.endIndex+ while start > text.startIndex {+ let prev = text.index(before: start)+ let ch = text[prev]+ if ch.isLetter || ch.isNumber || ch == "_" || ch == "." {+ start = prev+ } else {+ break+ }+ }+ return String(text[start..<text.endIndex])+ }++ private func prefixBeforeDot(in word: String) -> String? {+ guard word.contains(".") else { return nil }+ return String(word.split(separator: ".", maxSplits: 1)[0])+ }++ // MARK: - Tokenizer++ private func tokenize(_ text: String) -> [Token] {+ let pattern = #"(?:'[^']*')|(?:--[^\n]*)|(?:/\*[\s\S]*?\*/)|(?:\w+)|(?:[.,();=<>!*])"#+ guard let regex = try? NSRegularExpression(pattern: pattern) else { return [] }+ let range = NSRange(location: 0, length: (text as NSString).length)++ var tokens: [Token] = []+ regex.enumerateMatches(in: text, range: range) { match, _, _ in+ guard let match, let swiftRange = Range(match.range, in: text) else { return }+ let value = String(text[swiftRange])+ if value.hasPrefix("'") || value.hasPrefix("--") || value.hasPrefix("/*") { return }+ tokens.append(Token(value: value, upper: value.uppercased()))+ }+ return tokens+ }++ // MARK: - Trigger Detection++ private func determineTrigger(tokens: [Token], text: String, prefix: String, scopeTables: [TableRef]) -> CompletionTrigger {+ // Dot notation: alias.column+ if prefix.contains(".") {+ if let beforeDot = prefixBeforeDot(in: prefix) {+ let resolved = resolveAlias(beforeDot, scopeTables: scopeTables)+ return .column(table: resolved)+ }+ }++ guard !tokens.isEmpty else { return .general }++ // Effective tokens = all tokens minus the current prefix being typed+ let effectiveTokens: [Token]+ if !prefix.isEmpty && tokens.last?.value.lowercased() == prefix.lowercased() {+ effectiveTokens = Array(tokens.dropLast())+ } else {+ effectiveTokens = tokens+ }++ guard let lastToken = effectiveTokens.last else {+ // Empty query with prefix being typed → general+ return prefix.isEmpty ? .none : .general+ }++ let lastUpper = lastToken.upper++ // === KEYWORD-IMMEDIATE TRIGGERS (lastToken IS the keyword, cursor right after it) ===++ // JOIN / LEFT JOIN etc.+ if lastUpper == "JOIN" {+ return .join(fromTables: scopeTables)+ }+ if isJoinModifier(lastUpper) {+ // User typed "LEFT " — suggest "JOIN" as compound+ return .keyword+ }++ // FROM, INTO, UPDATE table, TABLE+ if ["FROM", "INTO", "TABLE"].contains(lastUpper) {+ return .table+ }+ if lastUpper == "UPDATE" {+ return .table+ }++ // SELECT, DISTINCT → columns + functions + *+ if lastUpper == "SELECT" || lastUpper == "DISTINCT" {+ return .selectList(scopeTables: scopeTables)+ }++ // WHERE, AND, OR, ON, HAVING, SET, BY → columns+ if ["WHERE", "AND", "OR", "ON", "HAVING", "BY"].contains(lastUpper) {+ return .column(table: nil)+ }+ if lastUpper == "SET" {+ // UPDATE table SET → suggest columns of that table+ let updateTable = findUpdateTable(tokens: effectiveTokens)+ return .column(table: updateTable)+ }++ // After * → suggest FROM+ if lastToken.value == "*" {+ return .afterIdentifier(clause: "SELECT", scopeTables: scopeTables)+ }++ // After comma → depends on clause+ if lastToken.value == "," {+ let clause = findCurrentClause(tokens: effectiveTokens)+ switch clause {+ case "SELECT": return .selectList(scopeTables: scopeTables)+ case "FROM", "JOIN": return .table+ case "ORDER BY", "GROUP BY": return .column(table: nil)+ case "INSERT": return .column(table: findInsertTable(tokens: effectiveTokens))+ default: return .column(table: nil)+ }+ }++ // After ( → check context+ if lastToken.value == "(" {+ // INSERT INTO table ( → table columns+ if let insertTable = findInsertIntoParenContext(tokens: effectiveTokens) {+ return .column(table: insertTable)+ }+ // Function args+ if effectiveTokens.count >= 2 {+ let prev = effectiveTokens[effectiveTokens.count - 2].upper+ if AutocompleteProvider.sqlFunctions.contains(where: { $0.name == prev }) {+ return .column(table: nil)+ }+ }+ return .selectList(scopeTables: scopeTables)+ }++ // After = > < != → columns/values+ if ["=", ">", "<", "!"].contains(lastToken.value) {+ return .column(table: nil)+ }++ // === NON-KEYWORD LAST TOKEN (table name, column name, alias, etc.) ===++ // If prefix is empty and last token is a non-keyword identifier:+ // User just finished typing a table name/alias and pressed space+ // → Suggest next keywords based on current clause+ if prefix.isEmpty {+ let clause = findCurrentClause(tokens: effectiveTokens)+ return .afterIdentifier(clause: clause, scopeTables: scopeTables)+ }++ // === PREFIX IS BEING TYPED ===++ // Find the governing keyword and distance+ if let (kw, distance) = findPreviousKeywordWithDistance(tokens: effectiveTokens) {+ switch kw {+ case "FROM", "INTO", "TABLE":+ if distance == 0 { return .table }+ return .keyword // Table already given, expecting next keyword+ case "UPDATE":+ if distance == 0 { return .table }+ return .keyword+ case "JOIN":+ if distance == 0 { return .join(fromTables: scopeTables) }+ return .keyword+ case "SELECT", "DISTINCT":+ return .selectList(scopeTables: scopeTables)+ case "WHERE", "AND", "OR", "ON", "HAVING", "BY":+ // Could be typing a column name OR a keyword (e.g., after WHERE col = val, typing "AN" for AND)+ // Check if there's a comparison operator between keyword and prefix+ if distance >= 2 { return .keyword }+ return .column(table: nil)+ case "SET":+ if distance == 0 {+ let updateTable = findUpdateTable(tokens: effectiveTokens)+ return .column(table: updateTable)+ }+ return .keyword+ default:+ break+ }+ }++ return .general+ }++ // MARK: - Context-Specific Extractors++ /// Find table name in `UPDATE <table> SET ...`+ private func findUpdateTable(tokens: [Token]) -> String? {+ for i in 0..<tokens.count {+ if tokens[i].upper == "UPDATE" && i + 1 < tokens.count {+ return tokens[i + 1].value+ }+ }+ return nil+ }++ /// Find table name in `INSERT INTO <table>`+ private func findInsertTable(tokens: [Token]) -> String? {+ for i in 0..<tokens.count {+ if tokens[i].upper == "INTO" && i + 1 < tokens.count {+ return tokens[i + 1].value+ }+ }+ return nil+ }++ /// Detect `INSERT INTO table (` pattern+ private func findInsertIntoParenContext(tokens: [Token]) -> String? {+ // Walk back from the `(` to find INSERT INTO <table>+ let count = tokens.count+ guard count >= 3 else { return nil } // Need at least: INTO, table, (+ // tokens[-1] is "(", tokens[-2] should be table name, tokens[-3] should be INTO+ let beforeParen = count - 2 // table name position+ let beforeTable = count - 3 // INTO position+ if beforeTable >= 0 && tokens[beforeTable].upper == "INTO" {+ return tokens[beforeParen].value+ }+ // Also handle INSERT INTO schema.table (+ if beforeTable >= 1 && count >= 5 {+ let dotPos = count - 3+ let intoPos = count - 5+ if dotPos >= 0 && tokens[dotPos].value == "." &&+ intoPos >= 0 && tokens[intoPos].upper == "INTO" {+ return tokens[beforeParen].value+ }+ }+ return nil+ }++ // MARK: - Table Extraction++ private func extractAllTables(tokens: [Token]) -> [TableRef] {+ var tables: [TableRef] = []+ var i = 0++ while i < tokens.count {+ let upper = tokens[i].upper+ if upper == "FROM" || upper == "JOIN" {+ i += 1+ if i >= tokens.count { break }++ // Handle schema.table+ let tableName = resolveSchemaPrefix(tokens: tokens, index: &i)++ // Check for alias+ var alias: String? = nil+ if i < tokens.count {+ let next = tokens[i].upper+ if next == "AS" {+ i += 1+ if i < tokens.count {+ alias = tokens[i].value+ i += 1+ }+ } else if !Self.clauseKeywords.contains(next) && next != "ON" && next != "," &&+ next != "(" && next != ")" && next != ";" && next != "*" {+ alias = tokens[i].value+ i += 1+ }+ }+ tables.append(TableRef(name: tableName, alias: alias))+ continue+ }+ // UPDATE table+ if upper == "UPDATE" {+ i += 1+ if i < tokens.count && !Self.clauseKeywords.contains(tokens[i].upper) {+ let tableName = resolveSchemaPrefix(tokens: tokens, index: &i)+ var alias: String? = nil+ if i < tokens.count && tokens[i].upper == "AS" {+ i += 1+ if i < tokens.count { alias = tokens[i].value; i += 1 }+ } else if i < tokens.count && tokens[i].upper == "SET" {+ // no alias+ } else if i < tokens.count && !Self.clauseKeywords.contains(tokens[i].upper) {+ alias = tokens[i].value+ i += 1+ }+ tables.append(TableRef(name: tableName, alias: alias))+ continue+ }+ }+ i += 1+ }++ return tables+ }++ // MARK: - Helpers++ private func resolveAlias(_ aliasOrTable: String, scopeTables: [TableRef]) -> String? {+ if let ref = scopeTables.first(where: { $0.alias == aliasOrTable }) {+ return ref.name+ }+ if let ref = scopeTables.first(where: { $0.name == aliasOrTable }) {+ return ref.name+ }+ return aliasOrTable+ }++ private func resolveSchemaPrefix(tokens: [Token], index: inout Int) -> String {+ var name = tokens[index].value+ index += 1+ if index < tokens.count && tokens[index].value == "." {+ index += 1+ if index < tokens.count {+ name = tokens[index].value+ index += 1+ }+ }+ return name+ }++ private func findPreviousKeywordWithDistance(tokens: [Token]) -> (String, Int)? {+ var identifierCount = 0+ for i in stride(from: tokens.count - 1, through: 0, by: -1) {+ let upper = tokens[i].upper+ if Self.clauseKeywords.contains(upper) {+ return (upper, identifierCount)+ }+ let val = tokens[i].value+ if val != "," && val != "(" && val != ")" && val != "." && val != ";" && val != "*" && val != "=" && val != ">" && val != "<" && val != "!" {+ identifierCount += 1+ }+ }+ return nil+ }++ private func findCurrentClause(tokens: [Token]) -> String {+ for i in stride(from: tokens.count - 1, through: 0, by: -1) {+ let upper = tokens[i].upper+ switch upper {+ case "SELECT", "FROM", "WHERE", "HAVING", "SET":+ return upper+ case "JOIN":+ return "JOIN"+ case "ORDER":+ if i + 1 < tokens.count && tokens[i + 1].upper == "BY" { return "ORDER BY" }+ return upper+ case "GROUP":+ if i + 1 < tokens.count && tokens[i + 1].upper == "BY" { return "GROUP BY" }+ return upper+ case "INSERT", "INTO":+ return "INSERT"+ default:+ break+ }+ }+ return ""+ }++ private func isJoinModifier(_ upper: String) -> Bool {+ ["LEFT", "RIGHT", "INNER", "OUTER", "FULL", "CROSS", "NATURAL"].contains(upper)+ }++ // Keywords that start clauses — used for boundary detection+ private static let clauseKeywords: Set<String> = [+ "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"+ ]+}++// MARK: - Token++private struct Token {+ let value: String+ let upper: String+}diff --git a/macos/Presentation/Views/QueryEditor/QueryEditorView.swift b/macos/Presentation/Views/QueryEditor/QueryEditorView.swiftnew file mode 100644index 0000000..d5605c9--- /dev/null+++ b/macos/Presentation/Views/QueryEditor/QueryEditorView.swift@@ -0,0 +1,726 @@+// QueryEditorView.swift+// Gridex+//+// SwiftUI query editor: SQL editor (top) + results grid (bottom).+// Uses NSViewRepresentable to wrap NSTextView for syntax highlighting.++import SwiftUI+import AppKit++struct QueryEditorView: View {+ let tabId: UUID+ @EnvironmentObject private var appState: AppState+ @State private var sqlText = ""+ @State private var cursorOffset: Int = 0+ @StateObject private var resultViewModel = DataGridViewState()+ @State private var resultRowCount: Int = 0+ @State private var errorMessage: String?+ @State private var statusMessage: String?+ @State private var isExecuting = false+ @State private var splitRatio: CGFloat = 0.5++ private var isRedis: Bool { appState.activeConfig?.databaseType == .redis }++ var body: some View {+ VSplitView {+ // SQL Editor pane+ VStack(spacing: 0) {+ HStack(spacing: 6) {+ Text(isRedis ? "Redis CLI" : "SQL Editor")+ .font(.system(size: 11, weight: .medium))+ .foregroundStyle(.secondary)+ Spacer()++ if !isRedis {+ Button(action: beautifySQL) {+ HStack(spacing: 4) {+ Image(systemName: "wand.and.stars")+ Text("Format")+ }+ }+ .controlSize(.small)+ .pointerCursor()+ .help("Beautify SQL (Ctrl+Shift+F)")+ .keyboardShortcut("f", modifiers: [.control, .shift])++ Button(action: minifySQL) {+ HStack(spacing: 4) {+ Image(systemName: "arrow.down.right.and.arrow.up.left")+ Text("Minify")+ }+ }+ .controlSize(.small)+ .pointerCursor()+ .help("Minify SQL to single line")++ Divider().frame(height: 14)+ }++ Button(action: executeQuery) {+ HStack(spacing: 4) {+ Image(systemName: "play.fill")+ Text("Run")+ }+ }+ .controlSize(.small)+ .pointerCursor()+ .keyboardShortcut("r", modifiers: .command)+ .disabled(isExecuting || sqlText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+ .help(isRedis ? "Run Redis command (⌘R)" : "Run statement at cursor (⌘R)")++ if !isRedis {+ Button(action: explainQuery) {+ HStack(spacing: 4) {+ Image(systemName: "lightbulb")+ Text("Explain")+ }+ }+ .controlSize(.small)+ .pointerCursor()+ }+ }+ .padding(.horizontal, 8)+ .padding(.vertical, 4)+ .background(Color(nsColor: .windowBackgroundColor))++ SQLEditorView(text: $sqlText, cursorOffset: $cursorOffset, adapter: appState.activeAdapter)+ .frame(maxHeight: .infinity)+ }++ // Results pane+ VStack(spacing: 0) {+ HStack {+ Text("Results")+ .font(.system(size: 11, weight: .medium))+ .foregroundStyle(.secondary)+ if resultRowCount > 0 {+ Text("(\(resultRowCount) rows)")+ .font(.system(size: 11))+ .foregroundStyle(.tertiary)+ }+ Spacer()+ }+ .padding(.horizontal, 8)+ .padding(.vertical, 4)+ .background(Color(nsColor: .windowBackgroundColor))++ if isExecuting {+ ProgressView("Executing...")+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ } else if let error = errorMessage {+ VStack {+ Image(systemName: "exclamationmark.triangle")+ .font(.title)+ .foregroundStyle(.red)+ Text(error)+ .foregroundStyle(.red)+ .font(.system(size: 13, design: .monospaced))+ .textSelection(.enabled)+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ .padding()+ } else if let status = statusMessage {+ VStack(spacing: 8) {+ Image(systemName: "checkmark.circle")+ .font(.title)+ .foregroundStyle(.green)+ Text(status)+ .foregroundStyle(.secondary)+ .font(.system(size: 13, design: .monospaced))+ .textSelection(.enabled)+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ .padding()+ } else if !resultViewModel.columns.isEmpty {+ AppKitDataGrid(+ viewModel: resultViewModel,+ onSelectRows: { _ in },+ onFKClick: nil+ )+ } else {+ Text("Run a query to see results")+ .foregroundStyle(.secondary)+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ }+ }+ }+ .onReceive(NotificationCenter.default.publisher(for: .executeQuery)) { _ in+ executeQuery()+ }+ .onReceive(NotificationCenter.default.publisher(for: .explainQuery)) { _ in+ explainQuery()+ }+ .onAppear {+ // Restore persisted text for this tab+ if let saved = appState.queryEditorText[tabId] {+ sqlText = saved+ }+ }+ .onChange(of: sqlText) { _, newValue in+ // Persist so tab switches don't lose the query+ appState.queryEditorText[tabId] = newValue+ }+ .onReceive(NotificationCenter.default.publisher(for: .init("pasteQueryToEditor"))) { notif in+ // Only the currently active query editor tab handles the paste+ guard appState.activeTabId == tabId,+ let sql = notif.userInfo?["sql"] as? String else { return }+ sqlText = sql+ }+ }++ // MARK: - Cursor-aware statement extraction++ /// Returns the SQL statement at the current cursor position.+ /// Falls back to the full text if there's only one statement or selection is empty.+ private func statementToRun() -> String {+ let trimmed = sqlText.trimmingCharacters(in: .whitespacesAndNewlines)+ // If no semicolons present, just use the whole text+ if !sqlText.contains(";") { return trimmed }+ let stmt = SQLFormatter.statementAt(sql: sqlText, cursorOffset: cursorOffset)+ return stmt.isEmpty ? trimmed : stmt+ }++ // MARK: - Format / Minify++ private func beautifySQL() {+ sqlText = SQLFormatter.beautify(sqlText)+ }++ private func minifySQL() {+ sqlText = SQLFormatter.minify(sqlText)+ }++ private func executeQuery() {+ guard let adapter = appState.activeAdapter else { return }++ // Decide: run a single statement at cursor, or a full multi-statement script.+ // Heuristic: if the text contains `GO` batch separators (SQL Server) or+ // multiple non-empty statements separated by `;`, treat it as a script.+ let fullText = sqlText.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !fullText.isEmpty else { return }++ let batches = splitIntoBatches(fullText, databaseType: adapter.databaseType)++ // If only one statement, use the cursor-aware behavior (backwards compat)+ let toRun: [String]+ if batches.count <= 1 {+ let single = statementToRun()+ guard !single.isEmpty else { return }+ toRun = [single]+ } else {+ toRun = batches+ }++ isExecuting = true+ errorMessage = nil+ statusMessage = nil++ // For MSSQL multi-batch scripts, use a dedicated connection so that+ // USE statements persist across batches.+ let isMultiBatchMSSQL = adapter.databaseType == .mssql && toRun.count > 1+ let mssqlAdapter = adapter as? MSSQLAdapter++ Task {+ if isMultiBatchMSSQL, let mssql = mssqlAdapter {+ do {+ try await mssql.beginScript()+ } catch {+ errorMessage = error.localizedDescription+ isExecuting = false+ return+ }+ }+ var lastResult: QueryResult?+ var totalRowsAffected = 0+ let overallStart = Date()+ for stmt in toRun {+ let start = Date()+ do {+ let result = try await adapter.executeRaw(sql: stmt)+ let duration = Date().timeIntervalSince(start)+ appState.logQuery(sql: stmt, duration: duration)+ appState.recordQueryHistory(sql: stmt, duration: duration, rowCount: result.rowCount)+ // Remember the most recent result that has rows (SELECT) to display+ if !result.columns.isEmpty {+ lastResult = result+ }+ totalRowsAffected += result.rowsAffected+ } catch {+ let duration = Date().timeIntervalSince(start)+ appState.logQuery(sql: stmt, duration: duration)+ appState.recordQueryHistory(sql: stmt, duration: duration, error: error.localizedDescription)+ errorMessage = error.localizedDescription+ if isMultiBatchMSSQL, let mssql = mssqlAdapter {+ await mssql.endScript()+ }+ isExecuting = false+ // Reload sidebar so DDL effects show up even on partial failure+ appState.refreshSidebar()+ return+ }+ }+ if isMultiBatchMSSQL, let mssql = mssqlAdapter {+ await mssql.endScript()+ }++ if let result = lastResult {+ applyResult(result)+ appState.statusRowCount = result.rowCount+ appState.statusQueryTime = result.executionTime+ } else if toRun.count > 1 {+ // Script with only DDL/DML — show a success status (not an error)+ let totalDuration = Date().timeIntervalSince(overallStart)+ statusMessage = "\(toRun.count) statement(s) executed · \(totalRowsAffected) row(s) affected · \(String(format: "%.2fs", totalDuration))"+ }++ // If the script changed database context (USE) or created/dropped databases,+ // sync AppState so the sidebar and DB picker reflect the new state.+ let upperScript = fullText.uppercased()+ let changedDBContext = upperScript.contains("USE ")+ || upperScript.contains("CREATE DATABASE")+ || upperScript.contains("DROP DATABASE")+ if changedDBContext {+ // Re-fetch current database from the server and update AppState+ if let newDB = try? await adapter.currentDatabase() {+ appState.currentDatabaseName = newDB+ }+ // Refresh the available databases list (picker shows new/removed DBs)+ if let databases = try? await adapter.listDatabases() {+ appState.availableDatabases = databases+ }+ }++ // Script may have created/altered/dropped tables — refresh the sidebar+ appState.refreshSidebar()+ isExecuting = false+ }+ }++ /// Split a SQL script into individual statements/batches. SQL Server uses+ /// `GO` on its own line as a batch separator; other databases use `;`.+ private func splitIntoBatches(_ script: String, databaseType: DatabaseType) -> [String] {+ if databaseType == .mssql {+ // Split on lines containing only "GO" (case-insensitive, allow whitespace)+ let lines = script.components(separatedBy: .newlines)+ var batches: [String] = []+ var current: [String] = []+ for line in lines {+ let trimmed = line.trimmingCharacters(in: .whitespaces)+ if trimmed.uppercased() == "GO" {+ let batch = current.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines)+ if !batch.isEmpty { batches.append(batch) }+ current = []+ } else {+ current.append(line)+ }+ }+ let last = current.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines)+ if !last.isEmpty { batches.append(last) }+ return batches+ }++ // Non-MSSQL: split by `;`, respecting quoted strings and comments.+ return splitSQLStatements(script)+ }++ /// Split SQL by `;` terminator, respecting single/double quoted strings and line comments.+ private func splitSQLStatements(_ sql: String) -> [String] {+ var statements: [String] = []+ var current = ""+ var inSingle = false+ var inDouble = false+ var inLineComment = false+ var i = sql.startIndex++ while i < sql.endIndex {+ let ch = sql[i]+ let next = sql.index(after: i) < sql.endIndex ? sql[sql.index(after: i)] : " "++ if inLineComment {+ current.append(ch)+ if ch == "\n" { inLineComment = false }+ } else if inSingle {+ current.append(ch)+ if ch == "'" { inSingle = false }+ } else if inDouble {+ current.append(ch)+ if ch == "\"" { inDouble = false }+ } else if ch == "-" && next == "-" {+ inLineComment = true+ current.append(ch)+ } else if ch == "'" {+ inSingle = true+ current.append(ch)+ } else if ch == "\"" {+ inDouble = true+ current.append(ch)+ } else if ch == ";" {+ let stmt = current.trimmingCharacters(in: .whitespacesAndNewlines)+ if !stmt.isEmpty { statements.append(stmt) }+ current = ""+ } else {+ current.append(ch)+ }+ i = sql.index(after: i)+ }+ let tail = current.trimmingCharacters(in: .whitespacesAndNewlines)+ if !tail.isEmpty { statements.append(tail) }+ return statements+ }++ private func explainQuery() {+ guard let adapter = appState.activeAdapter else { return }+ let sql = statementToRun()+ guard !sql.isEmpty else { return }++ isExecuting = true+ errorMessage = nil++ let explainSQL = "EXPLAIN QUERY PLAN \(sql)"+ Task {+ let start = Date()+ do {+ let result = try await adapter.executeRaw(sql: explainSQL)+ let duration = Date().timeIntervalSince(start)+ appState.logQuery(sql: explainSQL, duration: duration)+ appState.recordQueryHistory(sql: explainSQL, duration: duration, rowCount: result.rowCount)+ applyResult(result)+ } catch {+ let duration = Date().timeIntervalSince(start)+ appState.logQuery(sql: explainSQL, duration: duration)+ appState.recordQueryHistory(sql: explainSQL, duration: duration, error: error.localizedDescription)+ errorMessage = error.localizedDescription+ }+ isExecuting = false+ }+ }++ /// Populate the DataGridViewState with query results so AppKitDataGrid can render them+ /// with the same look & feel as the table data view.+ private func applyResult(_ result: QueryResult) {+ resultViewModel.columns = result.columns+ resultViewModel.rows = result.rows+ resultViewModel.totalRows = result.rowCount+ resultViewModel.primaryKeyColumns = []+ resultViewModel.foreignKeyColumns = [:]+ resultViewModel.foreignKeyRefColumns = [:]+ resultViewModel.columnDefaults = [:]+ resultViewModel.columnEnumValues = [:]+ resultViewModel.sortColumn = nil+ resultViewModel.insertedRowIndices = []+ resultViewModel.selectedRows = []+ resultViewModel.editingCell = nil+ // Reset column widths so the grid auto-sizes for the new result set+ resultViewModel.columnWidths = [:]+ resultRowCount = result.rowCount+ }+}++// MARK: - NSViewRepresentable SQL Editor with Syntax Highlighting + Autocomplete++struct SQLEditorView: NSViewRepresentable {+ @Binding var text: String+ @Binding var cursorOffset: Int+ let adapter: (any DatabaseAdapter)?++ func makeNSView(context: Context) -> NSScrollView {+ let scrollView = NSScrollView()+ scrollView.hasVerticalScroller = true+ scrollView.hasHorizontalScroller = false++ let textView = SQLTextView()+ textView.isEditable = true+ textView.isRichText = false+ textView.allowsUndo = true+ textView.delegate = context.coordinator+ textView.autoresizingMask = [.width]+ textView.isVerticallyResizable = true+ textView.isHorizontallyResizable = false+ textView.textContainer?.widthTracksTextView = true+ textView.textContainer?.containerSize = NSSize(width: 0, height: CGFloat.greatestFiniteMagnitude)++ scrollView.documentView = textView+ context.coordinator.textView = textView+ context.coordinator.highlighter = SyntaxHighlighter(textView: textView)+ context.coordinator.setupCompletion(textView: textView)++ // Load schema for autocomplete+ context.coordinator.loadSchema(adapter: adapter)++ return scrollView+ }++ func updateNSView(_ scrollView: NSScrollView, context: Context) {+ guard let textView = scrollView.documentView as? NSTextView else { return }+ if textView.string != text {+ textView.string = text+ if let storage = textView.textStorage {+ context.coordinator.highlighter?.highlight(storage)+ }+ }+ // Refresh schema if adapter changed+ context.coordinator.loadSchema(adapter: adapter)+ }++ func makeCoordinator() -> Coordinator {+ Coordinator(text: $text, cursorOffset: $cursorOffset)+ }++ class Coordinator: NSObject, NSTextViewDelegate {+ @Binding var text: String+ @Binding var cursorOffset: Int+ weak var textView: NSTextView?+ var highlighter: SyntaxHighlighter?++ private let completionProvider = AutocompleteProvider()+ private let contextParser = SQLContextParser()+ private let completionWindow = CompletionWindow()+ private var schemaLoaded = false+ private var debounceWork: DispatchWorkItem?+ private var lastInsertedChar: Character?++ init(text: Binding<String>, cursorOffset: Binding<Int>) {+ _text = text+ _cursorOffset = cursorOffset+ super.init()+ completionWindow.onSelect = { [weak self] item in+ self?.insertCompletion(item)+ }+ }++ /// Called by NSTextView when the selection (cursor) changes.+ func textViewDidChangeSelection(_ notification: Notification) {+ guard let textView = notification.object as? NSTextView else { return }+ cursorOffset = textView.selectedRange().location+ }++ func setupCompletion(textView: NSTextView) {+ if let sqlTextView = textView as? SQLTextView {+ sqlTextView.completionCoordinator = self+ }+ }++ func loadSchema(adapter: (any DatabaseAdapter)?) {+ guard !schemaLoaded, let adapter else { return }+ schemaLoaded = true+ Task { @MainActor in+ do {+ let tables = try await adapter.listTables(schema: nil)+ var descriptions: [TableDescription] = []+ for table in tables {+ if let desc = try? await adapter.describeTable(name: table.name, schema: table.schema) {+ descriptions.append(desc)+ }+ }+ completionProvider.updateSchema(descriptions)+ } catch {+ schemaLoaded = false+ }+ }+ }++ func textDidChange(_ notification: Notification) {+ guard let textView = notification.object as? NSTextView else { return }+ text = textView.string+ cursorOffset = textView.selectedRange().location++ // Detect what character was just typed+ let sql = textView.string+ let cursor = textView.selectedRange().location+ if cursor > 0, cursor <= sql.utf16.count {+ let idx = sql.index(sql.startIndex, offsetBy: cursor - 1, limitedBy: sql.endIndex) ?? sql.endIndex+ if idx < sql.endIndex {+ lastInsertedChar = sql[idx]+ }+ }++ // Dismiss on space, semicolon, or when the current word is empty.+ // Only show completions when user is actively typing an identifier/keyword.+ if let ch = lastInsertedChar {+ if ch == " " || ch == ";" || ch == "\n" || ch == "\t" {+ dismissCompletion()+ return+ }+ // Instant trigger on dot (alias.column)+ if ch == "." {+ triggerCompletionNow()+ return+ }+ }++ // Only trigger if current word is non-empty (user is typing a word)+ let currentWordAtCursor = wordAtCursor(sql: sql, cursor: cursor)+ if currentWordAtCursor.isEmpty {+ dismissCompletion()+ return+ }++ // Debounced trigger (80ms)+ debounceWork?.cancel()+ let work = DispatchWorkItem { [weak self] in+ self?.triggerCompletionNow()+ }+ debounceWork = work+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.08, execute: work)+ }++ private func wordAtCursor(sql: String, cursor: Int) -> String {+ let safeCursor = max(0, min(cursor, sql.count))+ let before = String(sql.prefix(safeCursor))+ var start = before.endIndex+ while start > before.startIndex {+ let prev = before.index(before: start)+ let ch = before[prev]+ if ch.isLetter || ch.isNumber || ch == "_" || ch == "." {+ start = prev+ } else {+ break+ }+ }+ return String(before[start..<before.endIndex])+ }++ private func lastWordBefore(_ text: String) -> String {+ var end = text.endIndex+ // Skip trailing spaces+ while end > text.startIndex && text[text.index(before: end)] == " " {+ end = text.index(before: end)+ }+ var start = end+ while start > text.startIndex {+ let prev = text.index(before: start)+ let ch = text[prev]+ if ch.isLetter || ch.isNumber || ch == "_" {+ start = prev+ } else {+ break+ }+ }+ return String(text[start..<end])+ }++ // MARK: - Completion Logic++ func triggerCompletionNow() {+ guard let textView else { return }+ let sql = textView.string+ let cursorLocation = textView.selectedRange().location+ guard cursorLocation <= sql.utf16.count else { return }++ // Simple mode: take current word as prefix, search everything+ let prefix = wordAtCursor(sql: sql, cursor: cursorLocation)+ guard !prefix.isEmpty else {+ dismissCompletion()+ return+ }++ let context = CompletionContext(+ trigger: .general,+ prefix: prefix,+ scopeTables: []+ )+ let items = completionProvider.suggestions(for: context)++ if items.isEmpty {+ dismissCompletion()+ return+ }++ // Don't show if only 1 item and it exactly matches the prefix+ if items.count == 1 && items[0].text.lowercased() == context.prefix.lowercased() {+ dismissCompletion()+ return+ }++ showCompletionWindow(items: items, cursorLocation: cursorLocation)+ }++ private func showCompletionWindow(items: [CompletionItem], cursorLocation: Int) {+ guard let textView else { return }++ let glyphRange = textView.layoutManager?.glyphRange(+ forCharacterRange: NSRange(location: cursorLocation, length: 0),+ actualCharacterRange: nil+ ) ?? NSRange(location: cursorLocation, length: 0)++ var rect = textView.layoutManager?.boundingRect(forGlyphRange: glyphRange, in: textView.textContainer!) ?? .zero+ rect.origin.x += textView.textContainerInset.width+ rect.origin.y += textView.textContainerInset.height++ let windowPoint = textView.convert(NSPoint(x: rect.origin.x, y: rect.origin.y + rect.height + 4), to: nil)+ let screenPoint = textView.window?.convertPoint(toScreen: windowPoint) ?? windowPoint++ completionWindow.show(items: items, at: screenPoint)+ }++ func dismissCompletion() {+ debounceWork?.cancel()+ completionWindow.dismiss()+ }++ func insertCompletion(_ item: CompletionItem) {+ guard let textView else { return }++ let sql = textView.string+ let cursorLocation = textView.selectedRange().location+ let context = contextParser.parse(sql: sql, cursorOffset: cursorLocation)+ let prefix = context.prefix++ // For JOIN completions, replace the whole typed prefix (e.g., "j" or "jo")+ let prefixLength: Int+ if item.type == .join {+ // Replace everything the user typed for the join+ prefixLength = prefix.utf16.count+ } else if prefix.contains(".") {+ // For alias.column, only replace after the dot+ let afterDot = prefix.split(separator: ".", maxSplits: 1)+ prefixLength = afterDot.count > 1 ? afterDot[1].utf16.count : 0+ } else {+ prefixLength = prefix.utf16.count+ }++ let safePrefixLength = max(0, min(prefixLength, cursorLocation))+ let replaceRange = NSRange(location: cursorLocation - safePrefixLength, length: safePrefixLength)++ if textView.shouldChangeText(in: replaceRange, replacementString: item.insertText) {+ textView.replaceCharacters(in: replaceRange, with: item.insertText)+ textView.didChangeText()+ }++ completionProvider.trackUsed(item.text)+ dismissCompletion()+ }++ // MARK: - Key Handling++ func handleKeyForCompletion(_ event: NSEvent) -> Bool {+ guard completionWindow.isActive else { return false }++ switch event.keyCode {+ case 125: // Down arrow+ completionWindow.moveSelectionDown()+ return true+ case 126: // Up arrow+ completionWindow.moveSelectionUp()+ return true+ case 36: // Return/Enter+ if let item = completionWindow.selectedItem {+ insertCompletion(item)+ return true+ }+ case 48: // Tab+ if let item = completionWindow.selectedItem {+ insertCompletion(item)+ return true+ }+ case 53: // Escape+ dismissCompletion()+ return true+ default:+ break+ }++ return false+ }+ }+}diff --git a/macos/Presentation/Views/QueryEditor/SQLFormatter.swift b/macos/Presentation/Views/QueryEditor/SQLFormatter.swiftnew file mode 100644index 0000000..dae033d--- /dev/null+++ b/macos/Presentation/Views/QueryEditor/SQLFormatter.swift@@ -0,0 +1,448 @@+// SQLFormatter.swift+// Gridex+//+// SQL beautify / minify with tab-indented clause style + cursor-aware statement split.++import Foundation++enum SQLFormatter {++ // MARK: - Beautify++ /// Reformat SQL with clause keywords on their own line and arguments indented.+ ///+ /// Target style:+ /// ```+ /// SELECT+ /// col1,+ /// col2,+ /// col3+ /// FROM+ /// table_name+ /// WHERE+ /// condition = 'x'+ /// ```+ static func beautify(_ sql: String) -> String {+ // Split into statements and format each independently+ let statements = splitStatements(sql)+ let formatted = statements.map { beautifyStatement($0) }+ return formatted.joined(separator: ";\n\n").trimmingCharacters(in: .whitespacesAndNewlines) + (sql.trimmingCharacters(in: .whitespaces).hasSuffix(";") ? ";" : "")+ }++ private static func beautifyStatement(_ sql: String) -> String {+ let tokens = tokenize(sql)+ guard !tokens.isEmpty else { return "" }++ // Keywords that begin a top-level clause (line by themselves)+ // Arguments follow on the next line indented by 1 tab+ let clauseKeywords: Set<String> = [+ "SELECT", "FROM", "WHERE", "GROUP BY", "HAVING", "ORDER BY",+ "LIMIT", "OFFSET", "UNION", "UNION ALL", "INTERSECT", "EXCEPT",+ "INSERT INTO", "VALUES", "UPDATE", "SET", "DELETE FROM",+ "WITH", "RETURNING"+ ]++ // Join keywords — own line at indent 0 with argument inline+ let joinKeywords: Set<String> = [+ "JOIN", "LEFT JOIN", "RIGHT JOIN", "INNER JOIN", "FULL JOIN",+ "FULL OUTER JOIN", "LEFT OUTER JOIN", "RIGHT OUTER JOIN",+ "CROSS JOIN", "NATURAL JOIN"+ ]++ var lines: [String] = []+ var currentLine = ""+ let indent = "\t"+ let clauseIndent = 1 // 1 tab by default for clause body+ var parenDepth = 0++ func flush() {+ if !currentLine.isEmpty {+ lines.append(currentLine)+ currentLine = ""+ }+ }++ func addToken(_ tok: String, spaceBefore: Bool) {+ if currentLine.isEmpty {+ currentLine = tok+ } else if spaceBefore {+ currentLine += " " + tok+ } else {+ currentLine += tok+ }+ }++ var i = 0+ while i < tokens.count {+ let tok = tokens[i]+ let upper = tok.uppercased()++ // Check 2- or 3-word keywords+ var matchedKeyword: String? = nil+ var matchedLength = 1++ for length in [3, 2] {+ if i + length <= tokens.count {+ let candidate = tokens[i..<(i+length)].map { $0.uppercased() }.joined(separator: " ")+ if clauseKeywords.contains(candidate) || joinKeywords.contains(candidate) {+ matchedKeyword = candidate+ matchedLength = length+ break+ }+ }+ }++ if matchedKeyword == nil && (clauseKeywords.contains(upper) || joinKeywords.contains(upper)) {+ matchedKeyword = upper+ matchedLength = 1+ }++ // Handle clause keyword (only at top level, paren depth 0)+ if let kw = matchedKeyword, parenDepth == 0 {+ flush()++ if joinKeywords.contains(kw) {+ // JOIN: keyword on its own indented line, argument follows inline+ currentLine = kw+ i += matchedLength+ // Collect JOIN target + ON clause on same line+ while i < tokens.count {+ let t = tokens[i]+ // Stop at next clause keyword+ if isClauseStart(tokens: tokens, at: i, clauseKeywords: clauseKeywords, joinKeywords: joinKeywords) {+ break+ }+ if t == ";" { break }+ addToken(t, spaceBefore: shouldSpaceBefore(prev: lastChar(currentLine), tok: t))+ i += 1+ }+ flush()+ continue+ }++ // Top-level clause: keyword on its own line, then args indented+ lines.append(kw)+ i += matchedLength++ // Collect clause body+ var bodyParts: [String] = []+ var current = ""+ var bodyParen = 0+ while i < tokens.count {+ let t = tokens[i]+ if t == ";" { break }+ if bodyParen == 0 && isClauseStart(tokens: tokens, at: i, clauseKeywords: clauseKeywords, joinKeywords: joinKeywords) {+ break+ }+ if t == "(" { bodyParen += 1 }+ if t == ")" { bodyParen -= 1 }++ // Split on comma at top of this clause's body+ if t == "," && bodyParen == 0 {+ if !current.isEmpty { bodyParts.append(current) }+ current = ""+ i += 1+ continue+ }++ if current.isEmpty {+ current = t+ } else {+ let needsSpace = shouldSpaceBefore(prev: lastChar(current), tok: t)+ current += (needsSpace ? " " : "") + t+ }+ i += 1+ }+ if !current.isEmpty { bodyParts.append(current) }++ // Emit body parts+ for (idx, part) in bodyParts.enumerated() {+ let suffix = (idx < bodyParts.count - 1) ? "," : ""+ lines.append(indent.repeating(clauseIndent) + part.trimmingCharacters(in: .whitespaces) + suffix)+ }+ continue+ }++ // Handle parentheses tracking+ if tok == "(" {+ let needsSpace = shouldSpaceBefore(prev: lastChar(currentLine), tok: tok)+ addToken(tok, spaceBefore: needsSpace)+ parenDepth += 1+ i += 1+ continue+ }+ if tok == ")" {+ addToken(tok, spaceBefore: false)+ parenDepth = max(0, parenDepth - 1)+ i += 1+ continue+ }++ if tok == ";" {+ flush()+ lines.append(";")+ i += 1+ continue+ }++ // Normal token — uppercase SQL keywords+ let emitted = isSQLKeyword(upper) ? upper : tok+ let needsSpace = shouldSpaceBefore(prev: lastChar(currentLine), tok: tok)+ addToken(emitted, spaceBefore: needsSpace)+ i += 1+ }++ flush()++ return lines+ .map { $0.trimmingCharacters(in: .init(charactersIn: " ")) }+ .filter { !$0.isEmpty }+ .joined(separator: "\n")+ }++ private static func isClauseStart(tokens: [String], at index: Int, clauseKeywords: Set<String>, joinKeywords: Set<String>) -> Bool {+ for length in [3, 2, 1] {+ if index + length <= tokens.count {+ let candidate = tokens[index..<(index+length)].map { $0.uppercased() }.joined(separator: " ")+ if clauseKeywords.contains(candidate) || joinKeywords.contains(candidate) {+ return true+ }+ }+ }+ return false+ }++ private static func shouldSpaceBefore(prev: Character?, tok: String) -> Bool {+ guard let prev else { return false }+ let noSpaceBeforeTokens: Set<String> = [",", ")", ";", ".", "::"]+ if noSpaceBeforeTokens.contains(tok) { return false }+ if prev == "(" || prev == "." { return false }+ // No space between function name and (+ if tok == "(" && (prev.isLetter || prev.isNumber || prev == "_") { return false }+ return true+ }++ private static func lastChar(_ s: String) -> Character? {+ s.last+ }++ // MARK: - Minify++ static func minify(_ sql: String) -> String {+ let tokens = tokenize(sql)+ var result = ""+ for tok in tokens {+ if result.isEmpty {+ result = tok+ } else {+ let needsSpace = shouldSpaceBefore(prev: result.last, tok: tok)+ result += (needsSpace ? " " : "") + tok+ }+ }+ return result.trimmingCharacters(in: .whitespacesAndNewlines)+ }++ // MARK: - Statement splitting++ /// Split SQL into statements by unquoted `;`.+ private static func splitStatements(_ sql: String) -> [String] {+ let chars = Array(sql)+ var stmts: [String] = []+ var current = ""+ var inSingle = false, inDouble = false, inLineComment = false, inBlockComment = false+ var i = 0+ while i < chars.count {+ let c = chars[i]+ if inLineComment {+ current.append(c)+ if c == "\n" { inLineComment = false }+ i += 1; continue+ }+ if inBlockComment {+ current.append(c)+ if c == "*" && i + 1 < chars.count && chars[i+1] == "/" {+ current.append("/"); inBlockComment = false; i += 2; continue+ }+ i += 1; continue+ }+ if inSingle {+ current.append(c)+ if c == "'" { inSingle = false }+ i += 1; continue+ }+ if inDouble {+ current.append(c)+ if c == "\"" { inDouble = false }+ i += 1; continue+ }+ if c == "'" { inSingle = true; current.append(c); i += 1; continue }+ if c == "\"" { inDouble = true; current.append(c); i += 1; continue }+ if c == "-" && i + 1 < chars.count && chars[i+1] == "-" {+ inLineComment = true; current += "--"; i += 2; continue+ }+ if c == "/" && i + 1 < chars.count && chars[i+1] == "*" {+ inBlockComment = true; current += "/*"; i += 2; continue+ }+ if c == ";" {+ let trimmed = current.trimmingCharacters(in: .whitespacesAndNewlines)+ if !trimmed.isEmpty { stmts.append(trimmed) }+ current = ""+ i += 1+ continue+ }+ current.append(c)+ i += 1+ }+ let trimmed = current.trimmingCharacters(in: .whitespacesAndNewlines)+ if !trimmed.isEmpty { stmts.append(trimmed) }+ return stmts+ }++ // MARK: - Statement at cursor++ static func statementAt(sql: String, cursorOffset: Int) -> String {+ let safeCursor = max(0, min(cursorOffset, sql.count))+ let chars = Array(sql)++ var inSingle = false, inDouble = false, inLineComment = false, inBlockComment = false+ var boundaries: [Int] = [-1]++ var i = 0+ while i < chars.count {+ let c = chars[i]+ if inLineComment {+ if c == "\n" { inLineComment = false }+ i += 1; continue+ }+ if inBlockComment {+ if c == "*" && i + 1 < chars.count && chars[i+1] == "/" {+ inBlockComment = false+ i += 2; continue+ }+ i += 1; continue+ }+ if inSingle {+ if c == "'" { inSingle = false }+ i += 1; continue+ }+ if inDouble {+ if c == "\"" { inDouble = false }+ i += 1; continue+ }+ if c == "-" && i + 1 < chars.count && chars[i+1] == "-" {+ inLineComment = true; i += 2; continue+ }+ if c == "/" && i + 1 < chars.count && chars[i+1] == "*" {+ inBlockComment = true; i += 2; continue+ }+ if c == "'" { inSingle = true; i += 1; continue }+ if c == "\"" { inDouble = true; i += 1; continue }+ if c == ";" { boundaries.append(i) }+ i += 1+ }+ boundaries.append(chars.count)++ var start = 0+ var end = chars.count+ for k in 0..<(boundaries.count - 1) {+ let lo = boundaries[k] + 1+ let hi = boundaries[k+1]+ if safeCursor >= lo && safeCursor <= hi {+ start = lo+ end = hi+ break+ }+ }++ return String(chars[start..<end]).trimmingCharacters(in: .whitespacesAndNewlines)+ }++ // MARK: - Tokenizer++ private static func tokenize(_ sql: String) -> [String] {+ var tokens: [String] = []+ let chars = Array(sql)+ var i = 0+ while i < chars.count {+ let c = chars[i]+ if c.isWhitespace { i += 1; continue }++ if c == "'" {+ var str = "'"+ i += 1+ while i < chars.count {+ str.append(chars[i])+ if chars[i] == "'" {+ if i + 1 < chars.count && chars[i+1] == "'" {+ str.append("'"); i += 2; continue+ }+ i += 1; break+ }+ i += 1+ }+ tokens.append(str)+ continue+ }++ if c == "-" && i + 1 < chars.count && chars[i+1] == "-" {+ var cmt = ""+ while i < chars.count && chars[i] != "\n" { cmt.append(chars[i]); i += 1 }+ tokens.append(cmt)+ continue+ }+ if c == "/" && i + 1 < chars.count && chars[i+1] == "*" {+ var cmt = "/*"; i += 2+ while i + 1 < chars.count && !(chars[i] == "*" && chars[i+1] == "/") {+ cmt.append(chars[i]); i += 1+ }+ if i + 1 < chars.count { cmt += "*/"; i += 2 }+ tokens.append(cmt)+ continue+ }++ if c.isLetter || c.isNumber || c == "_" || c == "." || c == "$" || c == "@" {+ var word = ""+ while i < chars.count && (chars[i].isLetter || chars[i].isNumber || chars[i] == "_" || chars[i] == ".") {+ word.append(chars[i]); i += 1+ }+ tokens.append(word)+ continue+ }++ if i + 1 < chars.count {+ let two = String(chars[i...i+1])+ if ["<=", ">=", "<>", "!=", "||", "::"].contains(two) {+ tokens.append(two); i += 2; continue+ }+ }++ tokens.append(String(c))+ i += 1+ }+ return tokens+ }++ private static func isSQLKeyword(_ word: String) -> Bool {+ Self.sqlKeywordsSet.contains(word)+ }++ private static let sqlKeywordsSet: Set<String> = [+ "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",+ "TRUE", "FALSE", "ASC", "DESC", "NULLS", "FIRST", "LAST",+ "PARTITION", "OVER", "CAST", "COALESCE", "NULLIF"+ ]+}++// MARK: - String helper++private extension String {+ func repeating(_ count: Int) -> String {+ String(repeating: self, count: count)+ }+}diff --git a/macos/Presentation/Views/QueryEditor/SQLTextView.swift b/macos/Presentation/Views/QueryEditor/SQLTextView.swiftnew file mode 100644index 0000000..83301f4--- /dev/null+++ b/macos/Presentation/Views/QueryEditor/SQLTextView.swift@@ -0,0 +1,62 @@+// SQLTextView.swift+// Gridex+//+// Custom NSTextView subclass for SQL editing with autocomplete support.++import AppKit++final class SQLTextView: NSTextView {++ /// Bridge to the SwiftUI coordinator that manages autocomplete.+ weak var completionCoordinator: SQLEditorView.Coordinator?++ override init(frame frameRect: NSRect) {+ super.init(frame: frameRect)+ commonInit()+ }++ override init(frame frameRect: NSRect, textContainer container: NSTextContainer?) {+ super.init(frame: frameRect, textContainer: container)+ commonInit()+ }++ required init?(coder: NSCoder) {+ super.init(coder: coder)+ commonInit()+ }++ private func commonInit() {+ font = NSFont.monospacedSystemFont(ofSize: 14, weight: .regular)+ textContainerInset = NSSize(width: 12, height: 8)+ isAutomaticQuoteSubstitutionEnabled = false+ isAutomaticDashSubstitutionEnabled = false+ isAutomaticTextReplacementEnabled = false+ isAutomaticSpellingCorrectionEnabled = false+ isContinuousSpellCheckingEnabled = false+ }++ override func keyDown(with event: NSEvent) {+ let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask)++ // Cmd+Shift+R: Execute query+ if flags == [.command, .shift] && event.charactersIgnoringModifiers?.lowercased() == "r" {+ NotificationCenter.default.post(name: .executeQuery, object: self)+ return+ }++ // Let completion coordinator handle arrow keys, enter, tab, escape+ if let coordinator = completionCoordinator, coordinator.handleKeyForCompletion(event) {+ return+ }++ // Ctrl+Space or Cmd+.: Manual trigger autocomplete+ if (flags == .control && event.charactersIgnoringModifiers == " ") ||+ (flags == .command && event.charactersIgnoringModifiers == ".") {+ super.keyDown(with: event)+ completionCoordinator?.triggerCompletionNow()+ return+ }++ super.keyDown(with: event)+ }+}diff --git a/macos/Presentation/Views/QueryEditor/SyntaxHighlighting/SyntaxHighlighter.swift b/macos/Presentation/Views/QueryEditor/SyntaxHighlighting/SyntaxHighlighter.swiftnew file mode 100644index 0000000..efa01b0--- /dev/null+++ b/macos/Presentation/Views/QueryEditor/SyntaxHighlighting/SyntaxHighlighter.swift@@ -0,0 +1,106 @@+// SyntaxHighlighter.swift+// Gridex+//+// Real-time SQL syntax highlighting engine.++import AppKit++final class SyntaxHighlighter: NSObject {+ private weak var textView: NSTextView?++ private static let keywords: Set<String> = [+ "SELECT", "FROM", "WHERE", "JOIN", "LEFT", "RIGHT", "INNER", "OUTER",+ "FULL", "CROSS", "ON", "AND", "OR", "NOT", "IN", "EXISTS", "BETWEEN",+ "LIKE", "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",+ "TRANSACTION", "CASCADE", "RESTRICT", "REFERENCES", "FOREIGN", "KEY",+ "PRIMARY", "UNIQUE", "CHECK", "CONSTRAINT", "DEFAULT", "ADD", "COLUMN",+ "RENAME", "TO", "TRUNCATE", "GRANT", "REVOKE", "ASC", "DESC", "FETCH",+ "NEXT", "ROWS", "ONLY", "NATURAL", "USING", "EXCEPT", "INTERSECT",+ "COALESCE", "NULLIF", "CAST", "TRUE", "FALSE", "BOOLEAN", "INTEGER",+ "VARCHAR", "TEXT", "TIMESTAMP", "DATE", "TIME", "SERIAL", "BIGSERIAL",+ "JSONB", "JSON", "UUID", "ARRAY", "FLOAT", "DOUBLE", "NUMERIC", "DECIMAL"+ ]++ private static let functions: Set<String> = [+ "COUNT", "SUM", "AVG", "MIN", "MAX", "COALESCE", "CONCAT",+ "LENGTH", "UPPER", "LOWER", "TRIM", "SUBSTRING", "REPLACE",+ "NOW", "CURRENT_TIMESTAMP", "EXTRACT", "DATE_TRUNC",+ "ROW_NUMBER", "RANK", "DENSE_RANK", "LAG", "LEAD",+ "STRING_AGG", "ARRAY_AGG", "JSON_AGG", "JSONB_AGG",+ "ROUND", "CEIL", "FLOOR", "ABS", "MOD", "POWER", "SQRT"+ ]++ init(textView: NSTextView) {+ self.textView = textView+ super.init()+ NotificationCenter.default.addObserver(+ self,+ selector: #selector(textDidChange),+ name: NSText.didChangeNotification,+ object: textView+ )+ }++ @objc private func textDidChange(_ notification: Notification) {+ guard let textView = textView,+ let textStorage = textView.textStorage else { return }+ highlight(textStorage)+ }++ func highlight(_ textStorage: NSTextStorage) {+ let text = textStorage.string+ let fullRange = NSRange(location: 0, length: text.utf16.count)+ let defaultFont = NSFont.monospacedSystemFont(ofSize: 14, weight: .regular)++ textStorage.beginEditing()+ textStorage.addAttribute(.foregroundColor, value: NSColor.labelColor, range: fullRange)+ textStorage.addAttribute(.font, value: defaultFont, range: fullRange)++ // Highlight keywords+ let words = text.components(separatedBy: CharacterSet.alphanumerics.inverted)+ var searchStart = text.startIndex+ for word in words where !word.isEmpty {+ if let range = text.range(of: word, range: searchStart..<text.endIndex) {+ let nsRange = NSRange(range, in: text)+ let upper = word.uppercased()++ if Self.keywords.contains(upper) {+ textStorage.addAttribute(.foregroundColor, value: NSColor.Gridex.syntaxKeyword, range: nsRange)+ textStorage.addAttribute(.font, value: NSFont.monospacedSystemFont(ofSize: 14, weight: .bold), range: nsRange)+ } else if Self.functions.contains(upper) {+ textStorage.addAttribute(.foregroundColor, value: NSColor.Gridex.syntaxFunction, range: nsRange)+ }++ searchStart = range.upperBound+ }+ }++ // Highlight strings ('...')+ highlightPattern("'[^']*'", color: NSColor.Gridex.syntaxString, in: textStorage, text: text)++ // Highlight numbers+ highlightPattern("\\b\\d+(\\.\\d+)?\\b", color: NSColor.Gridex.syntaxNumber, in: textStorage, text: text)++ // Highlight single-line comments+ highlightPattern("--[^\n]*", color: NSColor.Gridex.syntaxComment, in: textStorage, text: text)++ // Highlight multi-line comments+ highlightPattern("/\\*[\\s\\S]*?\\*/", color: NSColor.Gridex.syntaxComment, in: textStorage, text: text)++ textStorage.endEditing()+ }++ private func highlightPattern(_ pattern: String, color: NSColor, in textStorage: NSTextStorage, text: String) {+ guard let regex = try? NSRegularExpression(pattern: pattern) else { return }+ let fullRange = NSRange(location: 0, length: text.utf16.count)+ regex.enumerateMatches(in: text, range: fullRange) { match, _, _ in+ if let range = match?.range {+ textStorage.addAttribute(.foregroundColor, value: color, range: range)+ }+ }+ }+}diff --git a/macos/Presentation/Views/Redis/RedisAddKeySheet.swift b/macos/Presentation/Views/Redis/RedisAddKeySheet.swiftnew file mode 100644index 0000000..26dc5f7--- /dev/null+++ b/macos/Presentation/Views/Redis/RedisAddKeySheet.swift@@ -0,0 +1,180 @@+// RedisAddKeySheet.swift+// Gridex+//+// Sheet for creating a new Redis key with type selection.++import SwiftUI++struct RedisAddKeySheet: View {+ @EnvironmentObject private var appState: AppState+ @Environment(\.dismiss) private var dismiss++ @State private var keyName = ""+ @State private var keyType: RedisKeyType = .string+ @State private var ttlString = ""+ @State private var errorMessage: String?+ @State private var isCreating = false++ // String+ @State private var stringValue = ""+ // Hash+ @State private var hashFields: [(field: String, value: String)] = [("", "")]+ // List+ @State private var listItems: [String] = [""]+ // Set+ @State private var setMembers: [String] = [""]+ // ZSet+ @State private var zsetMembers: [(member: String, score: String)] = [("", "0")]++ var body: some View {+ VStack(spacing: 0) {+ Text("Add Key")+ .font(.system(size: 14, weight: .semibold))+ .padding(.top, 16)++ Form {+ TextField("Key", text: $keyName)++ Picker("Type", selection: $keyType) {+ ForEach(RedisKeyType.allCases, id: \.self) { t in+ Text(t.rawValue.uppercased()).tag(t)+ }+ }++ switch keyType {+ case .string:+ TextField("Value", text: $stringValue)+ case .hash:+ hashFieldsEditor+ case .list:+ listItemsEditor+ case .set:+ setMembersEditor+ case .zset:+ zsetMembersEditor+ }++ TextField("TTL (seconds, optional)", text: $ttlString)+ }+ .formStyle(.grouped)+ .scrollContentBackground(.hidden)++ if let err = errorMessage {+ Text(err).foregroundStyle(.red).font(.system(size: 11)).padding(.horizontal)+ }++ HStack {+ Button("Cancel") { dismiss() }+ .keyboardShortcut(.cancelAction)+ Spacer()+ Button("Create") { createKey() }+ .keyboardShortcut(.defaultAction)+ .disabled(keyName.isEmpty || isCreating)+ }+ .padding()+ }+ .frame(width: 420)+ }++ // MARK: - Editors++ private var hashFieldsEditor: some View {+ Section("Fields") {+ ForEach(hashFields.indices, id: \.self) { i in+ HStack {+ TextField("field", text: Binding(get: { hashFields[i].field }, set: { hashFields[i].field = $0 }))+ TextField("value", text: Binding(get: { hashFields[i].value }, set: { hashFields[i].value = $0 }))+ removeButton { hashFields.remove(at: i) }+ }+ }+ addButton { hashFields.append(("", "")) }+ }+ }++ private var listItemsEditor: some View {+ Section("Items") {+ ForEach(listItems.indices, id: \.self) { i in+ HStack {+ TextField("item \(i)", text: Binding(get: { listItems[i] }, set: { listItems[i] = $0 }))+ removeButton { listItems.remove(at: i) }+ }+ }+ addButton { listItems.append("") }+ }+ }++ private var setMembersEditor: some View {+ Section("Members") {+ ForEach(setMembers.indices, id: \.self) { i in+ HStack {+ TextField("member", text: Binding(get: { setMembers[i] }, set: { setMembers[i] = $0 }))+ removeButton { setMembers.remove(at: i) }+ }+ }+ addButton { setMembers.append("") }+ }+ }++ private var zsetMembersEditor: some View {+ Section("Members") {+ ForEach(zsetMembers.indices, id: \.self) { i in+ HStack {+ TextField("member", text: Binding(get: { zsetMembers[i].member }, set: { zsetMembers[i].member = $0 }))+ TextField("score", text: Binding(get: { zsetMembers[i].score }, set: { zsetMembers[i].score = $0 }))+ .frame(width: 80)+ removeButton { zsetMembers.remove(at: i) }+ }+ }+ addButton { zsetMembers.append(("", "0")) }+ }+ }++ private func addButton(action: @escaping () -> Void) -> some View {+ Button(action: action) {+ Label("Add", systemImage: "plus.circle")+ .font(.system(size: 12))+ }.buttonStyle(.plain)+ }++ private func removeButton(action: @escaping () -> Void) -> some View {+ Button(action: action) {+ Image(systemName: "minus.circle").foregroundStyle(.red)+ }.buttonStyle(.plain)+ }++ // MARK: - Create++ private func createKey() {+ guard let redis = appState.activeAdapter as? RedisAdapter else { return }+ isCreating = true+ errorMessage = nil++ let data: RedisKeyData+ switch keyType {+ case .string: data = .string(value: stringValue)+ case .hash: data = .hash(fields: hashFields.filter { !$0.field.isEmpty })+ case .list: data = .list(items: listItems.filter { !$0.isEmpty })+ case .set: data = .set(members: setMembers.filter { !$0.isEmpty })+ case .zset: data = .zset(members: zsetMembers.compactMap {+ guard !$0.member.isEmpty else { return nil }+ return (member: $0.member, score: Double($0.score) ?? 0)+ })+ }++ let ttl = Int(ttlString)+ Task {+ do {+ try await redis.redisInsertTyped(key: keyName, type: keyType, data: data, ttl: ttl)+ await MainActor.run {+ dismiss()+ NotificationCenter.default.post(name: .reloadData, object: nil)+ }+ } catch {+ await MainActor.run {+ errorMessage = error.localizedDescription+ isCreating = false+ }+ }+ }+ }+}diff --git a/macos/Presentation/Views/Redis/RedisFilterBar.swift b/macos/Presentation/Views/Redis/RedisFilterBar.swiftnew file mode 100644index 0000000..9948436--- /dev/null+++ b/macos/Presentation/Views/Redis/RedisFilterBar.swift@@ -0,0 +1,132 @@+// RedisFilterBar.swift+// Gridex+//+// Pattern-based filter bar for Redis keys (replaces SQL filter bar).+// Supports Redis glob patterns: * (any), ? (single char), [abc] (char class).++import SwiftUI++struct RedisFilterBar: View {+ var initialFilter: FilterExpression?+ var onApply: (FilterExpression?) -> Void+ var onClear: () -> Void+ var onDismiss: (() -> Void)?++ @State private var pattern: String = ""+ @State private var didApplyInitial = false++ // Quick-filter presets based on common key naming conventions+ private let presets = ["user:*", "session:*", "cache:*", "config:*", "queue:*"]++ var body: some View {+ HStack(spacing: 8) {+ Image(systemName: "magnifyingglass")+ .font(.system(size: 11))+ .foregroundStyle(.secondary)++ TextField("Filter keys by pattern (e.g. user:* or *session*)", text: $pattern)+ .textFieldStyle(.plain)+ .font(.system(size: 12, design: .monospaced))+ .onSubmit { applyPattern() }++ if !pattern.isEmpty {+ Text("\(pattern.contains("*") || pattern.contains("?") ? "glob" : "exact")")+ .font(.system(size: 9, weight: .medium))+ .foregroundStyle(.tertiary)+ .padding(.horizontal, 4)+ .padding(.vertical, 1)+ .background(Color.secondary.opacity(0.1))+ .clipShape(RoundedRectangle(cornerRadius: 2))+ }++ // Quick presets+ Menu {+ ForEach(presets, id: \.self) { preset in+ Button(preset) {+ pattern = preset+ applyPattern()+ }+ }+ Divider()+ Button("All keys (*)") {+ pattern = ""+ onClear()+ }+ } label: {+ Image(systemName: "text.badge.star")+ .font(.system(size: 11))+ }+ .menuStyle(.borderlessButton)+ .frame(width: 24)+ .help("Quick filter presets")++ Button("Apply") { applyPattern() }+ .controlSize(.small)+ .buttonStyle(.borderedProminent)++ Button {+ pattern = ""+ onClear()+ } label: {+ Image(systemName: "xmark")+ .font(.system(size: 10, weight: .medium))+ .frame(width: 24, height: 24)+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .foregroundStyle(.secondary)+ .help("Clear filter")++ Button {+ onDismiss?()+ } label: {+ Image(systemName: "chevron.up")+ .font(.system(size: 10, weight: .medium))+ .frame(width: 24, height: 24)+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .foregroundStyle(.secondary)+ .help("Hide filter bar")+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 5)+ .frame(height: 30)+ .background(Color(nsColor: .controlBackgroundColor))+ .overlay(alignment: .bottom) { Divider() }+ .onAppear {+ guard !didApplyInitial, let filter = initialFilter else { return }+ didApplyInitial = true+ // Extract pattern from existing filter+ for cond in filter.conditions where cond.column == "key" {+ if case .like = cond.op, let v = cond.value.stringValue {+ pattern = v.replacingOccurrences(of: "%", with: "*")+ .replacingOccurrences(of: "_", with: "?")+ } else if case .equal = cond.op, let v = cond.value.stringValue {+ pattern = v+ }+ }+ }+ }++ private func applyPattern() {+ let trimmed = pattern.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !trimmed.isEmpty else {+ onClear()+ return+ }++ // Convert glob pattern to LIKE for FilterExpression transport+ // RedisAdapter.extractPattern() converts it back to glob for SCAN+ let likePattern = trimmed+ .replacingOccurrences(of: "*", with: "%")+ .replacingOccurrences(of: "?", with: "_")++ let condition = FilterCondition(+ column: "key",+ op: trimmed.contains("*") || trimmed.contains("?") ? .like : .equal,+ value: .string(likePattern)+ )+ onApply(FilterExpression(conditions: [condition], combinator: .and))+ }+}diff --git a/macos/Presentation/Views/Redis/RedisKeyDetailView.swift b/macos/Presentation/Views/Redis/RedisKeyDetailView.swiftnew file mode 100644index 0000000..74a0d4d--- /dev/null+++ b/macos/Presentation/Views/Redis/RedisKeyDetailView.swift@@ -0,0 +1,324 @@+// RedisKeyDetailView.swift+// Gridex+//+// Detailed view for a single Redis key — shows hash fields, list items, set members, etc.++import SwiftUI++struct RedisKeyDetailView: View {+ let keyName: String+ @EnvironmentObject private var appState: AppState+ @State private var detail: RedisKeyDetail?+ @State private var isLoading = true+ @State private var errorMessage: String?++ // Editing+ @State private var showRename = false+ @State private var newKeyName = ""+ @State private var showTTLInput = false+ @State private var ttlInput = ""+ @State private var newFieldName = ""+ @State private var newFieldValue = ""++ var body: some View {+ VStack(spacing: 0) {+ // Header+ headerBar+ Divider()++ if isLoading {+ ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity)+ } else if let err = errorMessage {+ Text(err).foregroundStyle(.red).padding()+ } else if let detail {+ detailContent(detail)+ }+ }+ .task { await loadDetail() }+ }++ // MARK: - Header++ private var headerBar: some View {+ HStack(spacing: 8) {+ Image(systemName: "key.fill")+ .foregroundStyle(.secondary)+ Text(keyName)+ .font(.system(size: 13, weight: .semibold, design: .monospaced))++ if let detail {+ Text(detail.type.rawValue.uppercased())+ .font(.system(size: 10, weight: .bold))+ .padding(.horizontal, 6)+ .padding(.vertical, 2)+ .background(Color.accentColor.opacity(0.15))+ .clipShape(RoundedRectangle(cornerRadius: 3))++ if let ttl = detail.ttl {+ Text("TTL: \(ttl)s")+ .font(.system(size: 11, design: .monospaced))+ .foregroundStyle(.secondary)+ }++ if let mem = detail.memoryBytes {+ Text(formatBytes(mem))+ .font(.system(size: 11, design: .monospaced))+ .foregroundStyle(.secondary)+ }+ }++ Spacer()++ Button("Set TTL") { showTTLInput = true }+ .font(.system(size: 11))+ Button("Rename") {+ newKeyName = keyName+ showRename = true+ }.font(.system(size: 11))+ Button { Task { await loadDetail() } } label: {+ Image(systemName: "arrow.clockwise").font(.system(size: 11))+ }+ }+ .padding(.horizontal, 12)+ .padding(.vertical, 8)+ .alert("Rename Key", isPresented: $showRename) {+ TextField("New name", text: $newKeyName)+ Button("Cancel", role: .cancel) {}+ Button("Rename") { Task { await renameKey() } }+ }+ .alert("Set TTL", isPresented: $showTTLInput) {+ TextField("Seconds (0 = remove)", text: $ttlInput)+ Button("Cancel", role: .cancel) {}+ Button("Set") { Task { await setTTL() } }+ }+ }++ // MARK: - Detail Content++ @ViewBuilder+ private func detailContent(_ d: RedisKeyDetail) -> some View {+ switch d.data {+ case .string(let value):+ stringView(value)+ case .hash(let fields):+ hashView(fields)+ case .list(let items):+ listView(items)+ case .set(let members):+ setView(members)+ case .zset(let members):+ zsetView(members)+ }+ }++ private func stringView(_ value: String) -> some View {+ VStack(alignment: .leading, spacing: 8) {+ Text("Value").font(.system(size: 11, weight: .semibold)).foregroundStyle(.secondary)+ ScrollView {+ Text(value)+ .font(.system(size: 12, design: .monospaced))+ .textSelection(.enabled)+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(8)+ }+ }+ .padding()+ }++ private func hashView(_ fields: [(field: String, value: String)]) -> some View {+ VStack(spacing: 0) {+ HStack {+ Text("\(fields.count) fields").font(.system(size: 11)).foregroundStyle(.secondary)+ Spacer()+ HStack(spacing: 4) {+ TextField("field", text: $newFieldName).frame(width: 100).textFieldStyle(.roundedBorder).font(.system(size: 11))+ TextField("value", text: $newFieldValue).frame(width: 120).textFieldStyle(.roundedBorder).font(.system(size: 11))+ Button("Add") {+ guard !newFieldName.isEmpty else { return }+ Task {+ guard let redis = appState.activeAdapter as? RedisAdapter else { return }+ try? await redis.updateHashField(key: keyName, field: newFieldName, value: newFieldValue)+ newFieldName = ""; newFieldValue = ""+ await loadDetail()+ }+ }.font(.system(size: 11))+ }+ }+ .padding(.horizontal, 12).padding(.vertical, 6)++ tableGrid(headers: ["Field", "Value"], rows: fields.map { [$0.field, $0.value] }) { row in+ if let field = row.first {+ Button("Delete Field") {+ Task {+ guard let redis = appState.activeAdapter as? RedisAdapter else { return }+ try? await redis.deleteHashField(key: keyName, field: field)+ await loadDetail()+ }+ }+ }+ }+ }+ }++ private func listView(_ items: [String]) -> some View {+ VStack(spacing: 0) {+ HStack {+ Text("\(items.count) items").font(.system(size: 11)).foregroundStyle(.secondary)+ Spacer()+ }.padding(.horizontal, 12).padding(.vertical, 6)++ tableGrid(headers: ["Index", "Value"], rows: items.enumerated().map { [String($0.offset), $0.element] })+ }+ }++ private func setView(_ members: [String]) -> some View {+ VStack(spacing: 0) {+ HStack {+ Text("\(members.count) members").font(.system(size: 11)).foregroundStyle(.secondary)+ Spacer()+ HStack(spacing: 4) {+ TextField("member", text: $newFieldName).frame(width: 140).textFieldStyle(.roundedBorder).font(.system(size: 11))+ Button("Add") {+ guard !newFieldName.isEmpty else { return }+ Task {+ guard let redis = appState.activeAdapter as? RedisAdapter else { return }+ try? await redis.addSetMember(key: keyName, member: newFieldName)+ newFieldName = ""+ await loadDetail()+ }+ }.font(.system(size: 11))+ }+ }.padding(.horizontal, 12).padding(.vertical, 6)++ tableGrid(headers: ["Member"], rows: members.map { [$0] }) { row in+ if let member = row.first {+ Button("Remove") {+ Task {+ guard let redis = appState.activeAdapter as? RedisAdapter else { return }+ try? await redis.removeSetMember(key: keyName, member: member)+ await loadDetail()+ }+ }+ }+ }+ }+ }++ private func zsetView(_ members: [(member: String, score: Double)]) -> some View {+ VStack(spacing: 0) {+ HStack {+ Text("\(members.count) members").font(.system(size: 11)).foregroundStyle(.secondary)+ Spacer()+ HStack(spacing: 4) {+ TextField("member", text: $newFieldName).frame(width: 100).textFieldStyle(.roundedBorder).font(.system(size: 11))+ TextField("score", text: $newFieldValue).frame(width: 60).textFieldStyle(.roundedBorder).font(.system(size: 11))+ Button("Add") {+ guard !newFieldName.isEmpty else { return }+ Task {+ guard let redis = appState.activeAdapter as? RedisAdapter else { return }+ try? await redis.addZSetMember(key: keyName, member: newFieldName, score: Double(newFieldValue) ?? 0)+ newFieldName = ""; newFieldValue = ""+ await loadDetail()+ }+ }.font(.system(size: 11))+ }+ }.padding(.horizontal, 12).padding(.vertical, 6)++ tableGrid(headers: ["Member", "Score"], rows: members.map { [$0.member, String($0.score)] }) { row in+ if let member = row.first {+ Button("Remove") {+ Task {+ guard let redis = appState.activeAdapter as? RedisAdapter else { return }+ try? await redis.removeZSetMember(key: keyName, member: member)+ await loadDetail()+ }+ }+ }+ }+ }+ }++ // MARK: - Reusable Table Grid++ private func tableGrid(headers: [String], rows: [[String]], @ViewBuilder contextMenuBuilder: @escaping ([String]) -> some View = { _ in EmptyView() }) -> some View {+ ScrollView {+ LazyVStack(spacing: 0) {+ HStack(spacing: 0) {+ ForEach(headers, id: \.self) { h in+ Text(h)+ .font(.system(size: 11, weight: .semibold))+ .foregroundStyle(.secondary)+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(.horizontal, 8)+ .padding(.vertical, 4)+ }+ }+ .background(Color(nsColor: .controlBackgroundColor))+ Divider()++ ForEach(Array(rows.enumerated()), id: \.offset) { _, row in+ HStack(spacing: 0) {+ ForEach(Array(row.enumerated()), id: \.offset) { _, cell in+ Text(cell)+ .font(.system(size: 12, design: .monospaced))+ .lineLimit(3)+ .textSelection(.enabled)+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(.horizontal, 8)+ .padding(.vertical, 3)+ }+ }+ .contextMenu {+ contextMenuBuilder(row)+ Button("Copy") {+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(row.joined(separator: "\t"), forType: .string)+ }+ }+ Divider()+ }+ }+ }+ }++ // MARK: - Actions++ private func loadDetail() async {+ guard let redis = appState.activeAdapter as? RedisAdapter else { return }+ isLoading = true+ do {+ detail = try await redis.fetchKeyDetail(key: keyName)+ isLoading = false+ } catch {+ errorMessage = error.localizedDescription+ isLoading = false+ }+ }++ private func renameKey() async {+ guard let redis = appState.activeAdapter as? RedisAdapter, !newKeyName.isEmpty else { return }+ do {+ try await redis.renameKey(oldName: keyName, newName: newKeyName)+ NotificationCenter.default.post(name: .reloadData, object: nil)+ } catch { errorMessage = error.localizedDescription }+ }++ private func setTTL() async {+ guard let redis = appState.activeAdapter as? RedisAdapter else { return }+ let seconds = Int(ttlInput) ?? 0+ do {+ if seconds <= 0 {+ try await redis.removeTTL(key: keyName)+ } else {+ try await redis.setTTL(key: keyName, seconds: seconds)+ }+ await loadDetail()+ } catch { errorMessage = error.localizedDescription }+ }++ private func formatBytes(_ bytes: Int) -> String {+ if bytes < 1024 { return "\(bytes) B" }+ if bytes < 1024 * 1024 { return String(format: "%.1f KB", Double(bytes) / 1024) }+ return String(format: "%.1f MB", Double(bytes) / 1024 / 1024)+ }+}diff --git a/macos/Presentation/Views/Redis/RedisServerInfoView.swift b/macos/Presentation/Views/Redis/RedisServerInfoView.swiftnew file mode 100644index 0000000..194a5fe--- /dev/null+++ b/macos/Presentation/Views/Redis/RedisServerInfoView.swift@@ -0,0 +1,165 @@+// RedisServerInfoView.swift+// Gridex+//+// Dashboard showing Redis server INFO sections.++import SwiftUI++struct RedisServerInfoView: View {+ @EnvironmentObject private var appState: AppState+ @State private var sections: [RedisInfoSection] = []+ @State private var isLoading = true+ @State private var errorMessage: String?+ @State private var autoRefresh = false+ @State private var refreshTask: Task<Void, Never>?++ var body: some View {+ VStack(spacing: 0) {+ // Toolbar+ HStack(spacing: 8) {+ Image(systemName: "chart.bar.fill").foregroundStyle(.secondary)+ Text("Redis Server Info")+ .font(.system(size: 13, weight: .semibold))+ Spacer()+ Toggle("Auto-refresh", isOn: $autoRefresh)+ .toggleStyle(.checkbox)+ .font(.system(size: 11))+ Button { Task { await load() } } label: {+ Image(systemName: "arrow.clockwise").font(.system(size: 11))+ }+ }+ .padding(.horizontal, 12).padding(.vertical, 8)+ Divider()++ // Key metrics+ if !sections.isEmpty {+ keyMetrics+ Divider()+ }++ // Sections+ if let err = errorMessage {+ VStack(spacing: 8) {+ Image(systemName: "exclamationmark.triangle").font(.system(size: 28)).foregroundStyle(.orange)+ Text(err).font(.system(size: 12)).foregroundStyle(.secondary).textSelection(.enabled)+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ } else if isLoading {+ ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity)+ } else if sections.isEmpty {+ VStack(spacing: 8) {+ Image(systemName: "info.circle").font(.system(size: 28)).foregroundStyle(.secondary)+ Text("No server info available").font(.system(size: 12)).foregroundStyle(.secondary)+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ } else {+ ScrollView {+ LazyVStack(alignment: .leading, spacing: 0) {+ ForEach(Array(sections.enumerated()), id: \.offset) { _, section in+ sectionView(section)+ }+ }+ }+ }+ }+ .task { await load() }+ .onChange(of: autoRefresh) { _, on in+ refreshTask?.cancel()+ if on {+ refreshTask = Task {+ while !Task.isCancelled {+ try? await Task.sleep(nanoseconds: 5_000_000_000)+ guard !Task.isCancelled else { break }+ await load()+ }+ }+ }+ }+ .onDisappear { refreshTask?.cancel() }+ }++ // MARK: - Key Metrics++ private var keyMetrics: some View {+ HStack(spacing: 20) {+ metricCard("Memory", value: findValue("used_memory_human") ?? "—")+ metricCard("Clients", value: findValue("connected_clients") ?? "—")+ metricCard("Uptime", value: uptimeString)+ metricCard("Keys", value: appState.redisDBSize.map { "\($0)" } ?? "—")+ metricCard("Ops/sec", value: findValue("instantaneous_ops_per_sec") ?? "—")+ metricCard("Hit Rate", value: hitRateString)+ Spacer()+ }+ .padding(.horizontal, 12).padding(.vertical, 8)+ }++ private func metricCard(_ title: String, value: String) -> some View {+ VStack(spacing: 2) {+ Text(value)+ .font(.system(size: 16, weight: .semibold, design: .monospaced))+ Text(title)+ .font(.system(size: 10))+ .foregroundStyle(.secondary)+ }+ .frame(minWidth: 70)+ }++ // MARK: - Section View++ private func sectionView(_ section: RedisInfoSection) -> some View {+ DisclosureGroup(section.name) {+ ForEach(Array(section.entries.enumerated()), id: \.offset) { _, entry in+ HStack {+ Text(entry.key)+ .font(.system(size: 12, design: .monospaced))+ .foregroundStyle(.secondary)+ .frame(width: 280, alignment: .leading)+ Text(entry.value)+ .font(.system(size: 12, design: .monospaced))+ .textSelection(.enabled)+ Spacer()+ }+ .padding(.horizontal, 8).padding(.vertical, 1)+ }+ }+ .padding(.horizontal, 12).padding(.vertical, 4)+ }++ // MARK: - Helpers++ private func findValue(_ key: String) -> String? {+ for s in sections {+ for e in s.entries where e.key == key { return e.value }+ }+ return nil+ }++ private var uptimeString: String {+ guard let days = findValue("uptime_in_days") else { return "—" }+ return "\(days)d"+ }++ private var hitRateString: String {+ guard let hitsStr = findValue("keyspace_hits"), let hits = Double(hitsStr),+ let missStr = findValue("keyspace_misses"), let misses = Double(missStr) else { return "—" }+ let total = hits + misses+ guard total > 0 else { return "—" }+ return String(format: "%.1f%%", hits / total * 100)+ }++ private func load() async {+ guard let redis = appState.activeAdapter as? RedisAdapter else {+ await MainActor.run { errorMessage = "Not connected to Redis"; isLoading = false }+ return+ }+ do {+ let s = try await redis.serverInfoSections()+ await MainActor.run { sections = s; errorMessage = nil; isLoading = false }+ if let size = try? await redis.dbSize() {+ await MainActor.run { appState.redisDBSize = size }+ }+ } catch {+ await MainActor.run { errorMessage = error.localizedDescription; isLoading = false }+ }+ }+}diff --git a/macos/Presentation/Views/Redis/RedisSlowLogView.swift b/macos/Presentation/Views/Redis/RedisSlowLogView.swiftnew file mode 100644index 0000000..0c771ae--- /dev/null+++ b/macos/Presentation/Views/Redis/RedisSlowLogView.swift@@ -0,0 +1,139 @@+// RedisSlowLogView.swift+// Gridex+//+// Displays SLOWLOG GET entries in a table.++import SwiftUI++struct RedisSlowLogView: View {+ @EnvironmentObject private var appState: AppState+ @State private var entries: [RedisSlowLogEntry] = []+ @State private var isLoading = true+ @State private var showResetConfirm = false++ var body: some View {+ VStack(spacing: 0) {+ HStack(spacing: 8) {+ Image(systemName: "tortoise.fill").foregroundStyle(.secondary)+ Text("Redis Slow Log")+ .font(.system(size: 13, weight: .semibold))+ Text("\(entries.count) entries")+ .font(.system(size: 11))+ .foregroundStyle(.secondary)+ Spacer()+ Button("Reset") { showResetConfirm = true }+ .font(.system(size: 11))+ Button { Task { await load() } } label: {+ Image(systemName: "arrow.clockwise").font(.system(size: 11))+ }+ }+ .padding(.horizontal, 12).padding(.vertical, 8)+ Divider()++ if isLoading {+ ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity)+ } else if entries.isEmpty {+ VStack(spacing: 8) {+ Image(systemName: "checkmark.circle").font(.system(size: 32)).foregroundStyle(.green)+ Text("No slow queries recorded")+ .font(.system(size: 13)).foregroundStyle(.secondary)+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ } else {+ ScrollView {+ LazyVStack(spacing: 0) {+ // Header+ HStack(spacing: 0) {+ headerCell("ID", width: 50)+ headerCell("Time", width: 160)+ headerCell("Duration", width: 90)+ headerCell("Command", width: nil)+ headerCell("Client", width: 140)+ }+ .background(Color(nsColor: .controlBackgroundColor))+ Divider()++ ForEach(entries) { entry in+ HStack(spacing: 0) {+ cell(String(entry.id), width: 50)+ cell(dateFormatter.string(from: entry.timestamp), width: 160)+ cell(formatDuration(entry.durationMicros), width: 90)+ .foregroundStyle(entry.durationMicros > 100_000 ? .red : .primary)+ cell(entry.command, width: nil)+ cell(entry.clientInfo, width: 140)+ }+ Divider()+ }+ }+ }+ }+ }+ .task { await load() }+ .alert("Reset Slow Log", isPresented: $showResetConfirm) {+ Button("Cancel", role: .cancel) {}+ Button("Reset", role: .destructive) {+ Task {+ guard let redis = appState.activeAdapter as? RedisAdapter else { return }+ try? await redis.executeRaw(sql: "SLOWLOG RESET")+ await load()+ }+ }+ } message: { Text("This will clear all slow log entries.") }+ }++ @ViewBuilder+ private func headerCell(_ text: String, width: CGFloat? = nil) -> some View {+ if let w = width {+ Text(text)+ .font(.system(size: 11, weight: .semibold))+ .foregroundStyle(.secondary)+ .frame(width: w, alignment: .leading)+ .padding(.horizontal, 8).padding(.vertical, 4)+ } else {+ Text(text)+ .font(.system(size: 11, weight: .semibold))+ .foregroundStyle(.secondary)+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(.horizontal, 8).padding(.vertical, 4)+ }+ }++ @ViewBuilder+ private func cell(_ text: String, width: CGFloat? = nil) -> some View {+ if let w = width {+ Text(text)+ .font(.system(size: 12, design: .monospaced))+ .lineLimit(2)+ .textSelection(.enabled)+ .frame(width: w, alignment: .leading)+ .padding(.horizontal, 8).padding(.vertical, 3)+ } else {+ Text(text)+ .font(.system(size: 12, design: .monospaced))+ .lineLimit(2)+ .textSelection(.enabled)+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(.horizontal, 8).padding(.vertical, 3)+ }+ }++ private func formatDuration(_ micros: Int) -> String {+ if micros < 1000 { return "\(micros) \u{00B5}s" }+ if micros < 1_000_000 { return String(format: "%.1f ms", Double(micros) / 1000) }+ return String(format: "%.2f s", Double(micros) / 1_000_000)+ }++ private var dateFormatter: DateFormatter {+ let f = DateFormatter()+ f.dateFormat = "yyyy-MM-dd HH:mm:ss"+ return f+ }++ private func load() async {+ guard let redis = appState.activeAdapter as? RedisAdapter else { return }+ do {+ entries = try await redis.slowLog()+ isLoading = false+ } catch { isLoading = false }+ }+}diff --git a/macos/Presentation/Views/Shared/ClickableModifier.swift b/macos/Presentation/Views/Shared/ClickableModifier.swiftnew file mode 100644index 0000000..ff7622e--- /dev/null+++ b/macos/Presentation/Views/Shared/ClickableModifier.swift@@ -0,0 +1,59 @@+import SwiftUI+import AppKit++// MARK: - Pointer Cursor on Hover++/// Adds pointingHand cursor when hovering over any interactive element.+struct PointingHandCursor: ViewModifier {+ @State private var isHovering = false++ func body(content: Content) -> some View {+ content+ .onHover { hovering in+ isHovering = hovering+ if hovering {+ NSCursor.pointingHand.push()+ } else {+ NSCursor.pop()+ }+ }+ }+}++// MARK: - Clickable Style (cursor + subtle hover highlight)++/// Full clickable treatment: pointer cursor + background highlight on hover.+struct ClickableStyle: ViewModifier {+ var cornerRadius: CGFloat = 4+ @State private var isHovering = false++ func body(content: Content) -> some View {+ content+ .background(+ RoundedRectangle(cornerRadius: cornerRadius)+ .fill(isHovering ? Color.primary.opacity(0.06) : Color.clear)+ )+ .onHover { hovering in+ isHovering = hovering+ if hovering {+ NSCursor.pointingHand.push()+ } else {+ NSCursor.pop()+ }+ }+ }+}++// MARK: - View Extension++extension View {+ /// Adds pointingHand cursor on hover.+ func pointerCursor() -> some View {+ modifier(PointingHandCursor())+ }++ /// Adds pointingHand cursor + subtle background highlight on hover.+ func clickable(cornerRadius: CGFloat = 4) -> some View {+ modifier(ClickableStyle(cornerRadius: cornerRadius))+ }+}diff --git a/macos/Presentation/Views/Sidebar/BackupRestorePanel.swift b/macos/Presentation/Views/Sidebar/BackupRestorePanel.swiftnew file mode 100644index 0000000..ede9b3b--- /dev/null+++ b/macos/Presentation/Views/Sidebar/BackupRestorePanel.swift@@ -0,0 +1,832 @@+// BackupRestorePanel.swift+// Gridex+//+// Native NSPanel for database backup and restore operations.+// Layout: connections | databases | options.++import SwiftUI+import AppKit++// MARK: - Panel Controller++@MainActor+final class BackupRestorePanel {+ private static var current: NSPanel?++ /// Open from sidebar (already connected — pre-selects active connection + database)+ static func openBackup(appState: AppState) {+ open(mode: .backup, appState: appState)+ }++ static func openRestore(appState: AppState) {+ open(mode: .restore, appState: appState)+ }++ /// Open from Home screen (no connection yet — user picks from saved list)+ static func openBackupWizard(appState: AppState) {+ open(mode: .backup, appState: appState)+ }++ static func openRestoreWizard(appState: AppState) {+ open(mode: .restore, appState: appState)+ }++ private static func open(mode: BackupRestoreMode, appState: AppState) {+ current?.close()+ current = nil++ let view = BackupRestoreView(+ mode: mode,+ onClose: { BackupRestorePanel.close() }+ )+ .environmentObject(appState)++ let controller = NSHostingController(rootView: view)++ let panel = NSPanel(+ contentRect: NSRect(x: 0, y: 0, width: 780, height: 520),+ styleMask: [.titled, .closable, .resizable],+ backing: .buffered,+ defer: false+ )+ panel.title = mode == .backup ? "Backup database" : "Restore database"+ panel.contentViewController = controller+ panel.layoutIfNeeded()++ let parentWindow = NSApp.mainWindow+ ?? NSApp.windows.first(where: { $0.canBecomeMain && !($0 is NSPanel) && $0.isVisible })+ if let parent = parentWindow {+ let pf = parent.frame+ let ps = panel.frame.size+ panel.setFrameOrigin(NSPoint(x: pf.midX - ps.width / 2, y: pf.midY - ps.height / 2))+ } else {+ panel.center()+ }++ panel.makeKeyAndOrderFront(nil)+ current = panel+ }++ static func close() {+ current?.close()+ current = nil+ }+}++// MARK: - Mode++enum BackupRestoreMode {+ case backup, restore+}++// MARK: - View++struct BackupRestoreView: View {+ let mode: BackupRestoreMode+ let onClose: () -> Void++ @EnvironmentObject private var appState: AppState++ // Connection selection+ @State private var selectedConnectionId: UUID?+ @State private var connectionSearchText = ""++ // Database selection+ @State private var selectedDatabase: String?+ @State private var databaseSearchText = ""+ @State private var availableDatabases: [String] = []+ @State private var isLoadingDatabases = false++ // The temporary adapter used to list databases (when not already connected)+ @State private var tempAdapter: (any DatabaseAdapter)?++ // Backup options+ @State private var selectedFormat: BackupFormat = .sql+ @State private var compress = true+ @State private var dataOnly = false+ @State private var schemaOnly = false+ @State private var fileName = ""++ // Restore+ @State private var restoreFileURL: URL?+ @State private var restoreFormat: BackupFormat = .sql++ // State+ @State private var isRunning = false+ @State private var result: BackupResult?+ @State private var restoreProgress: Double = 0+ @State private var backupBytesWritten: Int64 = 0+ @State private var backupElapsed: TimeInterval = 0++ private let backupService = BackupService()++ private var selectedConfig: ConnectionConfig? {+ appState.savedConnections.first(where: { $0.id == selectedConnectionId })+ }++ var body: some View {+ VStack(spacing: 0) {+ // File name header (backup only)+ if mode == .backup {+ fileNameHeader+ .padding(.horizontal, 16)+ .padding(.vertical, 10)+ Divider()+ }++ // Main 3-column layout+ HStack(spacing: 0) {+ // Left: Connection list+ connectionListColumn+ .frame(width: 220)++ Divider()++ // Center: Database list+ databaseListColumn+ .frame(width: 200)++ Divider()++ // Right: Options+ optionsColumn+ }++ Divider()++ // Result + action button+ footerBar+ .padding(.horizontal, 16)+ .padding(.vertical, 10)+ }+ .frame(minWidth: 700, minHeight: 440)+ .onAppear {+ // Pre-select active connection if connected+ if let activeConfig = appState.activeConfig {+ selectedConnectionId = activeConfig.id+ selectedDatabase = appState.currentDatabaseName ?? activeConfig.database+ let available = BackupFormat.available(for: activeConfig.databaseType)+ selectedFormat = available.first ?? .sql+ restoreFormat = available.first ?? .sql+ if let adapter = appState.activeAdapter {+ loadDatabases(adapter: adapter, config: activeConfig)+ }+ } else if let first = appState.savedConnections.first {+ selectedConnectionId = first.id+ let available = BackupFormat.available(for: first.databaseType)+ selectedFormat = available.first ?? .sql+ restoreFormat = available.first ?? .sql+ connectAndLoadDatabases(first)+ }+ updateFileName()+ }+ }++ // MARK: - File Name Header++ private var fileNameHeader: some View {+ HStack(spacing: 8) {+ Text("File name:")+ .font(.system(size: 12))+ .foregroundStyle(.secondary)+ Text(fileName.isEmpty ? "untitled" : fileName)+ .font(.system(size: 12, weight: .medium))+ Spacer()+ Text("Click to change the file name pattern")+ .font(.system(size: 10))+ .foregroundStyle(.tertiary)+ }+ }++ // MARK: - Connection List Column++ private var connectionListColumn: some View {+ VStack(spacing: 0) {+ // Search+ searchField(text: $connectionSearchText, placeholder: "Search for connection…")+ .padding(8)++ Divider()++ // Grouped connection list+ ScrollView {+ LazyVStack(spacing: 0) {+ ForEach(filteredConnectionGroups, id: \.name) { group in+ connectionGroupRow(group)+ }+ }+ }+ }+ }++ private struct ConnectionGroup: Identifiable {+ var id: String { name }+ let name: String+ let connections: [ConnectionConfig]+ }++ private var filteredConnectionGroups: [ConnectionGroup] {+ let conns = connectionSearchText.isEmpty+ ? appState.savedConnections+ : appState.savedConnections.filter { $0.name.localizedCaseInsensitiveContains(connectionSearchText) }++ var groups: [String: [ConnectionConfig]] = [:]+ for c in conns {+ let g = c.group ?? "Default"+ groups[g, default: []].append(c)+ }+ return groups.sorted(by: { $0.key < $1.key }).map { ConnectionGroup(name: $0.key, connections: $0.value) }+ }++ private func connectionGroupRow(_ group: ConnectionGroup) -> some View {+ VStack(alignment: .leading, spacing: 0) {+ // Group header+ HStack(spacing: 6) {+ Image(systemName: "bolt.fill")+ .font(.system(size: 10))+ .foregroundColor(.orange)+ Text(group.name)+ .font(.system(size: 11, weight: .semibold))+ .foregroundStyle(.secondary)+ Text("\(group.connections.count)")+ .font(.system(size: 9, weight: .medium))+ .foregroundStyle(.tertiary)+ Spacer()+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 6)++ // Connections+ ForEach(group.connections, id: \.id) { conn in+ connectionRow(conn)+ }+ }+ }++ private func connectionRow(_ conn: ConnectionConfig) -> some View {+ let isSelected = selectedConnectionId == conn.id+ return Button {+ selectedConnectionId = conn.id+ selectedDatabase = nil+ // Reset formats to the first available for this DB type+ let available = BackupFormat.available(for: conn.databaseType)+ selectedFormat = available.first ?? .sql+ restoreFormat = available.first ?? .sql+ connectAndLoadDatabases(conn)+ } label: {+ HStack(spacing: 8) {+ // DB type badge+ ZStack {+ RoundedRectangle(cornerRadius: 5)+ .fill(dbColor(conn.databaseType).opacity(0.2))+ .frame(width: 28, height: 28)+ Text(dbInitials(conn.databaseType))+ .font(.system(size: 10, weight: .bold, design: .rounded))+ .foregroundColor(dbColor(conn.databaseType))+ }++ VStack(alignment: .leading, spacing: 1) {+ Text(conn.name)+ .font(.system(size: 12, weight: isSelected ? .semibold : .regular))+ .foregroundColor(isSelected ? .white : .primary)+ .lineLimit(1)+ Text(conn.displayHost)+ .font(.system(size: 10))+ .foregroundColor(isSelected ? .white.opacity(0.7) : .secondary)+ .lineLimit(1)+ }+ Spacer()+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 5)+ .background(isSelected ? Color.accentColor : Color.clear)+ .clipShape(RoundedRectangle(cornerRadius: 6))+ }+ .buttonStyle(.plain)+ .padding(.horizontal, 4)+ }++ // MARK: - Database List Column++ private var databaseListColumn: some View {+ VStack(spacing: 0) {+ searchField(text: $databaseSearchText, placeholder: "Search for database…")+ .padding(8)++ Divider()++ if isLoadingDatabases {+ VStack {+ Spacer()+ ProgressView()+ .scaleEffect(0.7)+ Text("Loading…")+ .font(.system(size: 11))+ .foregroundStyle(.secondary)+ Spacer()+ }+ } else if availableDatabases.isEmpty {+ VStack {+ Spacer()+ Text("Select a connection")+ .font(.system(size: 11))+ .foregroundStyle(.tertiary)+ Spacer()+ }+ } else {+ ScrollView {+ LazyVStack(spacing: 0) {+ ForEach(filteredDatabases, id: \.self) { db in+ databaseRow(db)+ }+ }+ .padding(.vertical, 4)+ }+ }+ }+ }++ private var filteredDatabases: [String] {+ if databaseSearchText.isEmpty { return availableDatabases }+ return availableDatabases.filter { $0.localizedCaseInsensitiveContains(databaseSearchText) }+ }++ private func databaseRow(_ name: String) -> some View {+ let isSelected = selectedDatabase == name+ return Button {+ selectedDatabase = name+ updateFileName()+ } label: {+ HStack(spacing: 8) {+ Image(systemName: "cylinder.fill")+ .font(.system(size: 12))+ .foregroundColor(isSelected ? .white : .blue.opacity(0.6))+ Text(name)+ .font(.system(size: 12))+ .foregroundColor(isSelected ? .white : .primary)+ .lineLimit(1)+ Spacer()+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 5)+ .background(isSelected ? Color.accentColor : Color.clear)+ .clipShape(RoundedRectangle(cornerRadius: 6))+ }+ .buttonStyle(.plain)+ .padding(.horizontal, 4)+ }++ // MARK: - Options Column++ private var optionsColumn: some View {+ VStack(alignment: .leading, spacing: 0) {+ if mode == .backup {+ backupOptionsView+ } else {+ restoreOptionsView+ }++ Spacer()+ }+ .padding(12)+ }++ private var backupOptionsView: some View {+ VStack(alignment: .leading, spacing: 12) {+ // DB version label+ if let config = selectedConfig {+ HStack {+ Spacer()+ Text(config.databaseType.displayName)+ .font(.system(size: 11, weight: .medium))+ .foregroundStyle(.secondary)+ .padding(.horizontal, 10)+ .padding(.vertical, 4)+ .background(Color.secondary.opacity(0.1))+ .clipShape(RoundedRectangle(cornerRadius: 6))+ }+ }++ Divider()++ // Format+ Text("Format")+ .font(.system(size: 11, weight: .medium))+ .foregroundStyle(.secondary)++ if let config = selectedConfig {+ Picker("", selection: $selectedFormat) {+ ForEach(BackupFormat.available(for: config.databaseType), id: \.self) { fmt in+ Text("--format=\(fmt.rawValue)").tag(fmt)+ }+ }+ .labelsHidden()+ .pickerStyle(.menu)+ }++ Divider()++ // Content+ Text("Content")+ .font(.system(size: 11, weight: .medium))+ .foregroundStyle(.secondary)++ VStack(alignment: .leading, spacing: 6) {+ radioButton("Full (schema + data)", isSelected: !dataOnly && !schemaOnly) {+ dataOnly = false; schemaOnly = false+ }+ radioButton("Schema only", isSelected: schemaOnly) {+ schemaOnly = true; dataOnly = false+ }+ radioButton("Data only", isSelected: dataOnly) {+ dataOnly = true; schemaOnly = false+ }+ }++ if selectedFormat == .custom {+ Divider()+ Toggle("Compress file using Gzip", isOn: $compress)+ .toggleStyle(.checkbox)+ .font(.system(size: 12))+ }+ }+ }++ private var restoreOptionsView: some View {+ VStack(alignment: .leading, spacing: 12) {+ // File picker+ Text("Backup file")+ .font(.system(size: 11, weight: .medium))+ .foregroundStyle(.secondary)++ Button { pickRestoreFile() } label: {+ HStack(spacing: 6) {+ Image(systemName: "doc.fill")+ .font(.system(size: 11))+ .foregroundStyle(.secondary)+ if let url = restoreFileURL {+ Text(url.lastPathComponent)+ .font(.system(size: 11))+ .lineLimit(1)+ .truncationMode(.middle)+ } else {+ Text("Browse…")+ .font(.system(size: 11))+ .foregroundStyle(.secondary)+ }+ }+ .padding(.horizontal, 8)+ .padding(.vertical, 5)+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(Color.primary.opacity(0.04))+ .clipShape(RoundedRectangle(cornerRadius: 6))+ .overlay(+ RoundedRectangle(cornerRadius: 6)+ .stroke(Color.primary.opacity(0.08), lineWidth: 1)+ )+ }+ .buttonStyle(.plain)++ if let url = restoreFileURL {+ Text(fileSizeString(url))+ .font(.system(size: 10, design: .monospaced))+ .foregroundStyle(.tertiary)+ }++ Divider()++ // Format+ Text("Format")+ .font(.system(size: 11, weight: .medium))+ .foregroundStyle(.secondary)++ if let config = selectedConfig {+ Picker("", selection: $restoreFormat) {+ ForEach(BackupFormat.available(for: config.databaseType), id: \.self) { fmt in+ Text(fmt.displayName).tag(fmt)+ }+ }+ .labelsHidden()+ .pickerStyle(.menu)+ }++ Divider()++ // Warning+ HStack(spacing: 6) {+ Image(systemName: "exclamationmark.triangle.fill")+ .font(.system(size: 11))+ .foregroundColor(.orange)+ Text("This will overwrite existing data.")+ .font(.system(size: 11))+ .foregroundStyle(.secondary)+ }+ }+ }++ private func radioButton(_ label: String, isSelected: Bool, action: @escaping () -> Void) -> some View {+ Button(action: action) {+ HStack(spacing: 4) {+ Image(systemName: isSelected ? "largecircle.fill.circle" : "circle")+ .font(.system(size: 12))+ .foregroundColor(isSelected ? .accentColor : .secondary)+ Text(label)+ .font(.system(size: 12))+ }+ }+ .buttonStyle(.plain)+ }++ // MARK: - Footer++ private var footerBar: some View {+ HStack(spacing: 8) {+ // Result inline+ if let result {+ Image(systemName: result.success ? "checkmark.circle.fill" : "xmark.circle.fill")+ .foregroundColor(result.success ? .green : .red)+ .font(.system(size: 13))+ VStack(alignment: .leading, spacing: 1) {+ Text(result.success+ ? (mode == .backup ? "Backup completed" : "Restore completed")+ : (mode == .backup ? "Backup failed" : "Restore failed"))+ .font(.system(size: 11, weight: .medium))+ if let err = result.errorMessage, !result.success {+ Text(String(err.prefix(120)))+ .font(.system(size: 10))+ .foregroundColor(.red)+ .lineLimit(2)+ }+ if result.success {+ HStack(spacing: 6) {+ if let size = result.fileSize {+ Text(ByteCountFormatter.string(fromByteCount: size, countStyle: .file))+ }+ Text(String(format: "%.1fs", result.duration))+ }+ .font(.system(size: 10, design: .monospaced))+ .foregroundStyle(.secondary)+ }+ }+ }++ if isRunning {+ if mode == .restore && restoreProgress > 0 {+ ProgressView(value: restoreProgress)+ .frame(width: 120)+ Text("\(Int(restoreProgress * 100))%")+ .font(.system(size: 11, design: .monospaced))+ .foregroundStyle(.secondary)+ } else if mode == .backup && backupBytesWritten > 0 {+ ProgressView()+ .scaleEffect(0.6)+ Text("\(ByteCountFormatter.string(fromByteCount: backupBytesWritten, countStyle: .file)) · \(Int(backupElapsed))s")+ .font(.system(size: 11, design: .monospaced))+ .foregroundStyle(.secondary)+ } else {+ ProgressView()+ .scaleEffect(0.6)+ Text(mode == .backup ? "Backing up…" : "Restoring…")+ .font(.system(size: 11))+ .foregroundStyle(.secondary)+ }+ }++ Spacer()++ Button(mode == .backup ? "Start backup…" : "Start restore…") {+ Task {+ if mode == .backup { await startBackup() } else { await startRestore() }+ }+ }+ .buttonStyle(.borderedProminent)+ .controlSize(.regular)+ .disabled(isRunning || selectedConnectionId == nil || selectedDatabase == nil+ || (mode == .restore && restoreFileURL == nil))+ }+ }++ // MARK: - Helpers++ private func searchField(text: Binding<String>, placeholder: String) -> some View {+ HStack(spacing: 6) {+ Image(systemName: "magnifyingglass")+ .font(.system(size: 11))+ .foregroundStyle(.tertiary)+ TextField(placeholder, text: text)+ .textFieldStyle(.plain)+ .font(.system(size: 12))+ }+ .padding(.horizontal, 8)+ .padding(.vertical, 5)+ .background(Color.primary.opacity(0.04))+ .clipShape(RoundedRectangle(cornerRadius: 6))+ }++ private func dbColor(_ type: DatabaseType) -> Color {+ switch type {+ case .postgresql: return .blue+ case .mysql: return .orange+ case .sqlite: return .purple+ case .redis: return .red+ case .mongodb: return .green+ case .mssql: return Color(red: 0.8, green: 0.2, blue: 0.4)+ }+ }++ private func dbInitials(_ type: DatabaseType) -> String {+ switch type {+ case .postgresql: return "Pg"+ case .mysql: return "My"+ case .sqlite: return "SL"+ case .redis: return "Rd"+ case .mongodb: return "Mg"+ case .mssql: return "MS"+ }+ }++ private func updateFileName() {+ fileName = selectedDatabase ?? "untitled"+ }++ // MARK: - Connect + Load Databases++ private func connectAndLoadDatabases(_ conn: ConnectionConfig) {+ // If this is the active connection, use the existing adapter+ if conn.id == appState.activeConfig?.id, let adapter = appState.activeAdapter {+ loadDatabases(adapter: adapter, config: conn)+ return+ }++ // Otherwise, create a temporary connection to list databases+ isLoadingDatabases = true+ availableDatabases = []++ Task {+ let pw = (try? appState.container.keychainService.load(+ key: "db.password.\(conn.id.uuidString)")) ?? ""++ let adapter: any DatabaseAdapter = switch conn.databaseType {+ case .sqlite: SQLiteAdapter()+ case .postgresql: PostgreSQLAdapter()+ case .mysql: MySQLAdapter()+ case .redis: RedisAdapter()+ case .mongodb: MongoDBAdapter()+ case .mssql: MSSQLAdapter()+ }++ do {+ try await adapter.connect(config: conn, password: pw)+ let dbs = try await adapter.listDatabases()+ await MainActor.run {+ availableDatabases = dbs+ tempAdapter = adapter+ isLoadingDatabases = false+ // Auto-select default database+ if let db = conn.database, dbs.contains(db) {+ selectedDatabase = db+ } else {+ selectedDatabase = dbs.first+ }+ updateFileName()+ }+ } catch {+ await MainActor.run {+ availableDatabases = []+ isLoadingDatabases = false+ }+ try? await adapter.disconnect()+ }+ }+ }++ private func loadDatabases(adapter: any DatabaseAdapter, config: ConnectionConfig) {+ isLoadingDatabases = true+ Task {+ let dbs = (try? await adapter.listDatabases()) ?? []+ await MainActor.run {+ availableDatabases = dbs+ isLoadingDatabases = false+ if selectedDatabase == nil {+ if let db = config.database, dbs.contains(db) {+ selectedDatabase = db+ } else {+ selectedDatabase = dbs.first+ }+ }+ updateFileName()+ }+ }+ }++ // MARK: - Actions++ private func startBackup() async {+ guard let config = selectedConfig, let database = selectedDatabase else { return }++ let pw = (try? appState.container.keychainService.load(+ key: "db.password.\(config.id.uuidString)")) ?? ""++ let panel = NSSavePanel()+ panel.title = "Save Backup"+ let ext = selectedFormat.fileExtension+ let defaultName = "\(database)_\(dateStamp()).\(ext.isEmpty ? "dump" : ext)"+ panel.nameFieldStringValue = defaultName+ guard panel.runModal() == .OK, let url = panel.url else { return }++ isRunning = true+ result = nil+ backupBytesWritten = 0+ backupElapsed = 0++ let options = BackupOptions(+ format: selectedFormat,+ compress: compress,+ dataOnly: dataOnly,+ schemaOnly: schemaOnly+ )+ // Pass the active adapter if it matches this connection (needed for+ // Redis/MongoDB/MSSQL backups which use the driver directly).+ let adapterForBackup: (any DatabaseAdapter)? = {+ if appState.activeConfig?.id == config.id { return appState.activeAdapter }+ return nil+ }()++ let res = await backupService.backup(+ config: config, password: pw, database: database,+ to: url, options: options,+ adapter: adapterForBackup,+ onProgress: { bytes, elapsed in+ Task { @MainActor in+ backupBytesWritten = bytes+ backupElapsed = elapsed+ }+ }+ )+ result = res+ isRunning = false+ }++ private func startRestore() async {+ guard let config = selectedConfig,+ let database = selectedDatabase,+ let fileURL = restoreFileURL else { return }++ let pw = (try? appState.container.keychainService.load(+ key: "db.password.\(config.id.uuidString)")) ?? ""++ isRunning = true+ result = nil+ restoreProgress = 0++ let adapterForRestore: (any DatabaseAdapter)? = {+ if appState.activeConfig?.id == config.id { return appState.activeAdapter }+ return nil+ }()++ let res = await backupService.restore(+ config: config, password: pw, database: database,+ from: fileURL, format: restoreFormat,+ adapter: adapterForRestore,+ onProgress: { progress in+ Task { @MainActor in+ restoreProgress = progress+ }+ }+ )+ result = res+ isRunning = false++ if res.success { appState.refreshSidebar() }+ }++ private func pickRestoreFile() {+ let panel = NSOpenPanel()+ panel.title = "Select Backup File"+ panel.allowsMultipleSelection = false+ panel.canChooseDirectories = false+ panel.canChooseFiles = true+ if panel.runModal() == .OK, let url = panel.url {+ restoreFileURL = url+ let ext = url.pathExtension.lowercased()+ switch ext {+ case "sql": restoreFormat = .sql+ case "dump": restoreFormat = .custom+ case "tar": restoreFormat = .tar+ default: break+ }+ }+ }++ private func dateStamp() -> String {+ let f = DateFormatter()+ f.dateFormat = "yyyy-MM-dd_HHmmss"+ return f.string(from: Date())+ }++ private func fileSizeString(_ url: URL) -> String {+ guard let attrs = try? FileManager.default.attributesOfItem(atPath: url.path),+ let size = attrs[.size] as? Int64 else { return "" }+ return ByteCountFormatter.string(fromByteCount: size, countStyle: .file)+ }+}diff --git a/macos/Presentation/Views/Sidebar/DeleteTableSheet.swift b/macos/Presentation/Views/Sidebar/DeleteTableSheet.swiftnew file mode 100644index 0000000..1eb6031--- /dev/null+++ b/macos/Presentation/Views/Sidebar/DeleteTableSheet.swift@@ -0,0 +1,65 @@+// DeleteTableSheet.swift+// Gridex+//+// Confirmation dialog shown when marking a table for deletion.+// Offers "Ignore foreign key checks" and "Cascade" options.+// The actual DROP is deferred until the user commits from the sidebar header.++import SwiftUI++struct DeleteTableSheet: View {+ let tableName: String+ let onConfirm: (_ cascade: Bool, _ ignoreFK: Bool) -> Void++ @Environment(\.dismiss) private var dismiss+ @State private var cascade: Bool = true+ @State private var ignoreFK: Bool = false++ var body: some View {+ VStack(spacing: 0) {+ Text("Delete table '\(tableName)'")+ .font(.system(size: 14, weight: .semibold))+ .padding(.top, 20)+ .padding(.bottom, 16)++ VStack(alignment: .leading, spacing: 10) {+ Toggle(isOn: $ignoreFK) {+ Text("Ignore foreign key checks")+ .font(.system(size: 12))+ }+ .toggleStyle(.checkbox)++ Toggle(isOn: $cascade) {+ VStack(alignment: .leading, spacing: 2) {+ Text("Cascade")+ .font(.system(size: 12))+ Text("Delete all rows linked by foreign keys")+ .font(.system(size: 10))+ .foregroundStyle(.tertiary)+ }+ }+ .toggleStyle(.checkbox)+ }+ .padding(.horizontal, 24)+ .padding(.bottom, 16)++ Divider()++ HStack {+ Spacer()+ Button("Cancel") { dismiss() }+ .keyboardShortcut(.cancelAction)+ .pointerCursor()+ Button("OK") {+ onConfirm(cascade, ignoreFK)+ dismiss()+ }+ .keyboardShortcut(.defaultAction)+ .buttonStyle(.borderedProminent)+ .pointerCursor()+ }+ .padding(16)+ }+ .frame(width: 380)+ }+}diff --git a/macos/Presentation/Views/Sidebar/ExportTableSheet.swift b/macos/Presentation/Views/Sidebar/ExportTableSheet.swiftnew file mode 100644index 0000000..d59de7b--- /dev/null+++ b/macos/Presentation/Views/Sidebar/ExportTableSheet.swift@@ -0,0 +1,435 @@+import SwiftUI+import AppKit++// MARK: - Export Format++enum ExportFormat: String, CaseIterable {+ case csv = "CSV"+ case json = "JSON"+ case sql = "SQL"+}++// MARK: - Export Table Sheet++struct ExportTableSheet: View {+ let tableName: String+ @EnvironmentObject private var appState: AppState+ @Environment(\.dismiss) private var dismiss++ // Table selection+ @State private var allTables: [String] = []+ @State private var selectedTables: Set<String> = []+ @State private var tableSearchText = ""++ // Format+ @State private var format: ExportFormat = .csv++ // CSV options+ @State private var convertNullToEmpty = true+ @State private var convertLineBreakToSpace = false+ @State private var includeFieldNames = true+ @State private var delimiter: String = ","+ @State private var quoteMode: String = "Quote if needed"+ @State private var lineBreak: String = "\\n"+ @State private var decimal: String = "."++ // State+ @State private var isExporting = false+ @State private var errorMessage: String?++ private let delimiters = [",", ";", "\\t", "|"]+ private let quoteModes = ["Quote if needed", "Always quote", "Never quote"]+ private let lineBreaks = ["\\n", "\\r\\n", "\\r"]+ private let decimals = [".", ","]++ private var filteredTables: [String] {+ if tableSearchText.isEmpty { return allTables }+ return allTables.filter { $0.localizedCaseInsensitiveContains(tableSearchText) }+ }++ var body: some View {+ VStack(spacing: 0) {+ // Header tabs+ HStack {+ Text("Items")+ .font(.system(size: 12, weight: .medium))+ .foregroundStyle(.secondary)+ .frame(width: 200, alignment: .leading)+ .padding(.leading, 16)++ Spacer()++ Text("Data")+ .font(.system(size: 12, weight: .medium))+ .foregroundStyle(.secondary)+ }+ .padding(.top, 10)+ .padding(.trailing, 16)+ .padding(.bottom, 6)++ Divider()++ // Main content: table list | options+ HStack(spacing: 0) {+ // Left: table list with checkboxes+ tableListPanel+ .frame(width: 220)++ Divider()++ // Right: format tabs + options+ optionsPanel+ }+ .frame(minHeight: 380)++ Divider()++ // File name+ HStack {+ Text("File name:")+ .foregroundStyle(.secondary)+ .font(.system(size: 12))+ Text(exportFileName)+ .font(.system(size: 12, weight: .medium))+ Spacer()+ }+ .padding(.horizontal, 16)+ .padding(.vertical, 8)++ Divider()++ // Bottom buttons+ HStack {+ if let error = errorMessage {+ Text(error)+ .font(.system(size: 11))+ .foregroundStyle(.red)+ .lineLimit(2)+ }+ Spacer()+ Button("Cancel") { dismiss() }+ .keyboardShortcut(.cancelAction)+ Button("Export...") {+ Task { await performExport() }+ }+ .buttonStyle(.borderedProminent)+ .keyboardShortcut(.defaultAction)+ .disabled(isExporting || selectedTables.isEmpty)+ }+ .padding(12)+ }+ .frame(width: 620, height: 520)+ .onAppear {+ loadTables()+ selectedTables = [tableName]+ }+ }++ // MARK: - Table List Panel++ private var tableListPanel: some View {+ VStack(spacing: 0) {+ List {+ // Schema group+ ForEach(filteredTables, id: \.self) { name in+ HStack(spacing: 8) {+ Toggle("", isOn: Binding(+ get: { selectedTables.contains(name) },+ set: { isOn in+ if isOn { selectedTables.insert(name) }+ else { selectedTables.remove(name) }+ }+ ))+ .toggleStyle(.checkbox)+ .labelsHidden()++ Image(systemName: "tablecells")+ .font(.system(size: 10))+ .foregroundStyle(Color(red: 0.8, green: 0.5, blue: 0.2))++ Text(name)+ .font(.system(size: 12))+ .lineLimit(1)+ }+ .padding(.vertical, 1)+ }+ }+ .listStyle(.plain)+ .environment(\.defaultMinListRowHeight, 24)+ }+ }++ // MARK: - Options Panel++ private var optionsPanel: some View {+ VStack(spacing: 0) {+ // Format tabs+ HStack(spacing: 0) {+ ForEach(ExportFormat.allCases, id: \.self) { fmt in+ Button(action: { format = fmt }) {+ Text(fmt.rawValue)+ .font(.system(size: 12, weight: format == fmt ? .semibold : .regular))+ .foregroundStyle(format == fmt ? .primary : .secondary)+ .padding(.horizontal, 20)+ .padding(.vertical, 6)+ .background(format == fmt ? Color(nsColor: .selectedContentBackgroundColor).opacity(0.3) : .clear)+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .pointerCursor()+ }+ }+ .background(Color(nsColor: .controlBackgroundColor))+ .clipShape(RoundedRectangle(cornerRadius: 6))+ .overlay(RoundedRectangle(cornerRadius: 6).stroke(Color(nsColor: .separatorColor), lineWidth: 0.5))+ .padding(.top, 16)+ .padding(.bottom, 12)++ Divider()++ // Options+ ScrollView {+ VStack(spacing: 12) {+ switch format {+ case .csv: csvOptions+ case .json: jsonOptions+ case .sql: sqlOptions+ }+ }+ .padding(16)+ }++ Spacer()+ }+ }++ // MARK: - CSV Options++ private var csvOptions: some View {+ VStack(alignment: .leading, spacing: 10) {+ Toggle("Convert NULL to EMPTY", isOn: $convertNullToEmpty)+ Toggle("Convert line break to space", isOn: $convertLineBreakToSpace)+ Toggle("Put field names in the first row", isOn: $includeFieldNames)++ optionRow("Delimiter") {+ Picker("", selection: $delimiter) {+ ForEach(delimiters, id: \.self) { d in Text(d).tag(d) }+ }.labelsHidden().frame(width: 160)+ }+ optionRow("Swap") {+ Picker("", selection: $quoteMode) {+ ForEach(quoteModes, id: \.self) { m in Text(m).tag(m) }+ }.labelsHidden().frame(width: 160)+ }+ optionRow("Line break") {+ Picker("", selection: $lineBreak) {+ ForEach(lineBreaks, id: \.self) { l in Text(l).tag(l) }+ }.labelsHidden().frame(width: 160)+ }+ optionRow("Decimal") {+ Picker("", selection: $decimal) {+ ForEach(decimals, id: \.self) { d in Text(d).tag(d) }+ }.labelsHidden().frame(width: 160)+ }+ }+ .font(.system(size: 12))+ }++ // MARK: - JSON Options++ private var jsonOptions: some View {+ VStack(alignment: .leading, spacing: 10) {+ Toggle("Convert NULL to EMPTY", isOn: $convertNullToEmpty)+ Toggle("Pretty print", isOn: .constant(true))+ }+ .font(.system(size: 12))+ }++ // MARK: - SQL Options++ private var sqlOptions: some View {+ VStack(alignment: .leading, spacing: 10) {+ Toggle("Convert NULL to EMPTY", isOn: $convertNullToEmpty)+ Text("Generates INSERT INTO statements for all rows.")+ .font(.system(size: 11))+ .foregroundStyle(.secondary)+ }+ .font(.system(size: 12))+ }++ // MARK: - Helpers++ private func optionRow(_ label: String, @ViewBuilder content: () -> some View) -> some View {+ HStack {+ Text(label)+ .frame(width: 100, alignment: .trailing)+ .foregroundStyle(.secondary)+ content()+ }+ }++ private var exportFileName: String {+ if selectedTables.count == 1, let name = selectedTables.first {+ return "\(name).\(format.rawValue.lowercased())"+ }+ return "export.\(format.rawValue.lowercased())"+ }++ private func loadTables() {+ // Extract table names from sidebar items+ func extractTables(_ items: [SidebarItem]) -> [String] {+ var result: [String] = []+ for item in items {+ if case .table(let name) = item.type {+ result.append(name)+ }+ result.append(contentsOf: extractTables(item.children))+ }+ return result+ }+ allTables = extractTables(appState.sidebarItems).sorted()+ }++ // MARK: - Export Action++ private func performExport() async {+ guard let adapter = appState.activeAdapter else {+ errorMessage = "No active connection"+ return+ }+ guard !selectedTables.isEmpty else { return }++ isExporting = true+ errorMessage = nil++ do {+ if selectedTables.count == 1, let table = selectedTables.first {+ // Single table export+ let url = showSavePanel(defaultName: "\(table).\(format.rawValue.lowercased())")+ guard let url else { isExporting = false; return }+ try await exportTable(table, to: url, adapter: adapter)+ } else {+ // Multiple tables — pick a directory+ let dir = showDirectoryPanel()+ guard let dir else { isExporting = false; return }+ for table in selectedTables.sorted() {+ let url = dir.appendingPathComponent("\(table).\(format.rawValue.lowercased())")+ try await exportTable(table, to: url, adapter: adapter)+ }+ }+ dismiss()+ } catch {+ errorMessage = error.localizedDescription+ }++ isExporting = false+ }++ private func exportTable(_ table: String, to url: URL, adapter: any DatabaseAdapter) async throws {+ let d = adapter.databaseType.sqlDialect+ let sql = "SELECT * FROM \(d.quoteIdentifier(table))"+ var result = try await adapter.executeRaw(sql: sql)++ if convertNullToEmpty {+ result = convertNulls(in: result)+ }++ switch format {+ case .csv:+ try await exportCSV(data: result, to: url)+ case .json:+ try await ExportService().exportJSON(data: result, to: url)+ case .sql:+ // Full-fidelity SQL export — fetch structure first so we can emit+ // DROP/CREATE/sequences/indices alongside the INSERT rows.+ let description = try await adapter.describeTable(name: table, schema: nil)+ try await ExportService().exportTableSQL(+ description: description,+ rows: result.rows,+ databaseType: adapter.databaseType,+ databaseName: appState.currentDatabaseName ?? "",+ to: url+ )+ }+ }++ private func exportCSV(data: QueryResult, to url: URL) async throws {+ let sep = delimiter == "\\t" ? "\t" : delimiter+ let lb: String+ switch lineBreak {+ case "\\r\\n": lb = "\r\n"+ case "\\r": lb = "\r"+ default: lb = "\n"+ }++ var csv = ""+ if includeFieldNames {+ csv += data.columns.map(\.name).joined(separator: sep) + lb+ }++ for row in data.rows {+ csv += row.map { value in+ var str = value.description+ if convertLineBreakToSpace {+ str = str.replacingOccurrences(of: "\n", with: " ")+ .replacingOccurrences(of: "\r", with: " ")+ }+ if decimal != "." {+ if Double(str) != nil {+ str = str.replacingOccurrences(of: ".", with: decimal)+ }+ }+ switch quoteMode {+ case "Always quote":+ return "\"\(str.replacingOccurrences(of: "\"", with: "\"\""))\""+ case "Never quote":+ return str+ default:+ if str.contains(sep) || str.contains("\"") || str.contains("\n") || str.contains("\r") {+ return "\"\(str.replacingOccurrences(of: "\"", with: "\"\""))\""+ }+ return str+ }+ }.joined(separator: sep) + lb+ }++ try csv.write(to: url, atomically: true, encoding: .utf8)+ }++ private func convertNulls(in result: QueryResult) -> QueryResult {+ let rows = result.rows.map { row in+ row.map { value in+ value.isNull ? RowValue.string("") : value+ }+ }+ return QueryResult(+ columns: result.columns,+ rows: rows,+ rowsAffected: result.rowsAffected,+ executionTime: result.executionTime,+ queryType: result.queryType+ )+ }++ @MainActor+ private func showSavePanel(defaultName: String) -> URL? {+ let panel = NSSavePanel()+ panel.title = "Export"+ panel.nameFieldStringValue = defaultName+ panel.allowedContentTypes = [.data]+ panel.canCreateDirectories = true+ guard panel.runModal() == .OK else { return nil }+ return panel.url+ }++ @MainActor+ private func showDirectoryPanel() -> URL? {+ let panel = NSOpenPanel()+ panel.title = "Choose export folder"+ panel.canChooseFiles = false+ panel.canChooseDirectories = true+ panel.canCreateDirectories = true+ guard panel.runModal() == .OK else { return nil }+ return panel.url+ }+}diff --git a/macos/Presentation/Views/Sidebar/ImportCSVSheet.swift b/macos/Presentation/Views/Sidebar/ImportCSVSheet.swiftnew file mode 100644index 0000000..603dad3--- /dev/null+++ b/macos/Presentation/Views/Sidebar/ImportCSVSheet.swift@@ -0,0 +1,300 @@+// ImportCSVSheet.swift+// Gridex+//+// Dialog to import rows from a CSV file into an existing table.+// Auto-detects columns from the CSV header and maps to table columns by name.++import SwiftUI+import AppKit++struct ImportCSVSheet: View {+ let tableName: String+ @EnvironmentObject private var appState: AppState+ @Environment(\.dismiss) private var dismiss++ @State private var fileURL: URL?+ @State private var delimiter: String = ","+ @State private var hasHeader: Bool = true+ @State private var previewRows: [[String]] = []+ @State private var headerRow: [String] = []+ @State private var tableColumns: [String] = []+ @State private var columnMapping: [String: String] = [:] // CSV header → table column+ @State private var isImporting = false+ @State private var errorMessage: String?+ @State private var importedCount: Int = 0++ private let delimiters = [",", ";", "\\t", "|"]++ var body: some View {+ VStack(spacing: 0) {+ // Header+ Text("Import CSV to '\(tableName)'")+ .font(.system(size: 14, weight: .semibold))+ .padding(.top, 16)+ .padding(.bottom, 12)++ Divider()++ ScrollView {+ VStack(alignment: .leading, spacing: 12) {+ // File picker+ HStack {+ Text("File:")+ .frame(width: 90, alignment: .trailing)+ .foregroundStyle(.secondary)+ .font(.system(size: 12))+ if let url = fileURL {+ Text(url.lastPathComponent)+ .font(.system(size: 12))+ .lineLimit(1)+ Spacer()+ Button("Change…") { pickFile() }+ .pointerCursor()+ } else {+ Button("Choose CSV file…") { pickFile() }+ .pointerCursor()+ Spacer()+ }+ }++ // Options+ optionRow("Delimiter") {+ Picker("", selection: $delimiter) {+ ForEach(delimiters, id: \.self) { d in Text(d).tag(d) }+ }+ .labelsHidden()+ .frame(width: 140)+ .onChange(of: delimiter) { _, _ in loadPreview() }+ }++ optionRow("First row is header") {+ Toggle("", isOn: $hasHeader)+ .labelsHidden()+ .onChange(of: hasHeader) { _, _ in loadPreview() }+ }++ // Column mapping+ if !headerRow.isEmpty && !tableColumns.isEmpty {+ Divider()+ Text("Column mapping")+ .font(.system(size: 12, weight: .semibold))+ .foregroundStyle(.secondary)++ ForEach(headerRow, id: \.self) { csvCol in+ HStack {+ Text(csvCol)+ .frame(width: 140, alignment: .trailing)+ .font(.system(size: 11, design: .monospaced))+ .foregroundStyle(.secondary)+ Image(systemName: "arrow.right")+ .font(.system(size: 9))+ .foregroundStyle(.tertiary)+ Picker("", selection: Binding(+ get: { columnMapping[csvCol] ?? "" },+ set: { columnMapping[csvCol] = $0 }+ )) {+ Text("— skip —").tag("")+ ForEach(tableColumns, id: \.self) { col in+ Text(col).tag(col)+ }+ }+ .labelsHidden()+ }+ }+ }++ // Preview+ if !previewRows.isEmpty {+ Divider()+ Text("Preview (\(previewRows.count) rows)")+ .font(.system(size: 12, weight: .semibold))+ .foregroundStyle(.secondary)++ VStack(alignment: .leading, spacing: 2) {+ ForEach(Array(previewRows.prefix(5).enumerated()), id: \.offset) { _, row in+ Text(row.joined(separator: " | "))+ .font(.system(size: 10, design: .monospaced))+ .foregroundStyle(.tertiary)+ .lineLimit(1)+ }+ }+ .padding(8)+ .background(Color(nsColor: .controlBackgroundColor))+ .cornerRadius(6)+ }+ }+ .padding(16)+ }+ .frame(minHeight: 300)++ Divider()++ // Status + buttons+ HStack {+ if let err = errorMessage {+ Text(err)+ .font(.system(size: 11))+ .foregroundStyle(.red)+ .lineLimit(2)+ } else if importedCount > 0 {+ Text("Imported \(importedCount) rows")+ .font(.system(size: 11))+ .foregroundStyle(.green)+ }+ Spacer()+ Button("Cancel") { dismiss() }+ .keyboardShortcut(.cancelAction)+ .pointerCursor()+ Button("Import") {+ Task { await performImport() }+ }+ .buttonStyle(.borderedProminent)+ .pointerCursor()+ .disabled(fileURL == nil || isImporting || columnMapping.values.allSatisfy { $0.isEmpty })+ }+ .padding(12)+ }+ .frame(width: 500, height: 540)+ .task { await loadTableColumns() }+ }++ // MARK: - Helpers++ private func optionRow(_ label: String, @ViewBuilder content: () -> some View) -> some View {+ HStack {+ Text(label)+ .frame(width: 140, alignment: .trailing)+ .foregroundStyle(.secondary)+ .font(.system(size: 12))+ content()+ Spacer()+ }+ }++ private func pickFile() {+ let panel = NSOpenPanel()+ panel.title = "Choose CSV file"+ panel.allowsMultipleSelection = false+ panel.canChooseDirectories = false+ panel.allowedContentTypes = [.commaSeparatedText, .plainText, .data]+ if panel.runModal() == .OK, let url = panel.url {+ fileURL = url+ loadPreview()+ }+ }++ private func loadPreview() {+ guard let url = fileURL else { return }+ do {+ let content = try String(contentsOf: url, encoding: .utf8)+ let sep = delimiter == "\\t" ? "\t" : delimiter+ let lines = content.components(separatedBy: .newlines).filter { !$0.isEmpty }+ guard !lines.isEmpty else { return }++ let parsed = lines.map { parseCSVLine($0, separator: sep) }++ if hasHeader, let first = parsed.first {+ headerRow = first+ previewRows = Array(parsed.dropFirst().prefix(10))+ } else {+ headerRow = (0..<(parsed.first?.count ?? 0)).map { "col_\($0 + 1)" }+ previewRows = Array(parsed.prefix(10))+ }++ // Auto-map columns by name match+ for csvCol in headerRow {+ if columnMapping[csvCol] == nil {+ if tableColumns.contains(csvCol) {+ columnMapping[csvCol] = csvCol+ } else {+ columnMapping[csvCol] = ""+ }+ }+ }+ } catch {+ errorMessage = error.localizedDescription+ }+ }++ private func parseCSVLine(_ line: String, separator: String) -> [String] {+ // Basic CSV parsing with quoted field support+ var result: [String] = []+ var current = ""+ var inQuotes = false+ var i = line.startIndex+ while i < line.endIndex {+ let c = line[i]+ if c == "\"" {+ if inQuotes, line.index(after: i) < line.endIndex, line[line.index(after: i)] == "\"" {+ current.append("\"")+ i = line.index(i, offsetBy: 2)+ continue+ }+ inQuotes.toggle()+ } else if String(c) == separator && !inQuotes {+ result.append(current)+ current = ""+ } else {+ current.append(c)+ }+ i = line.index(after: i)+ }+ result.append(current)+ return result+ }++ private func loadTableColumns() async {+ guard let adapter = appState.activeAdapter else { return }+ if let desc = try? await adapter.describeTable(name: tableName, schema: nil) {+ tableColumns = desc.columns.map(\.name)+ }+ }++ private func performImport() async {+ guard let adapter = appState.activeAdapter,+ let url = fileURL else { return }+ isImporting = true+ errorMessage = nil+ importedCount = 0+ defer { isImporting = false }++ do {+ let content = try String(contentsOf: url, encoding: .utf8)+ let sep = delimiter == "\\t" ? "\t" : delimiter+ let lines = content.components(separatedBy: .newlines).filter { !$0.isEmpty }+ guard !lines.isEmpty else { return }++ let rows = lines.map { parseCSVLine($0, separator: sep) }+ let dataRows = hasHeader ? Array(rows.dropFirst()) : rows++ // Build INSERT statements+ let mappedCols = headerRow.compactMap { csvCol -> (csvIdx: Int, tableCol: String)? in+ guard let tableCol = columnMapping[csvCol], !tableCol.isEmpty,+ let idx = headerRow.firstIndex(of: csvCol) else { return nil }+ return (idx, tableCol)+ }+ guard !mappedCols.isEmpty else {+ errorMessage = "No columns mapped"+ return+ }++ let d = adapter.databaseType.sqlDialect+ let colList = mappedCols.map { d.quoteIdentifier($0.tableCol) }.joined(separator: ", ")++ for row in dataRows {+ let values = mappedCols.map { mapping -> String in+ guard mapping.csvIdx < row.count else { return "NULL" }+ let raw = row[mapping.csvIdx]+ if raw.isEmpty { return "NULL" }+ return "'\(raw.replacingOccurrences(of: "'", with: "''"))'"+ }.joined(separator: ", ")++ let sql = "INSERT INTO \(d.quoteIdentifier(tableName)) (\(colList)) VALUES (\(values))"+ _ = try await adapter.executeRaw(sql: sql)+ importedCount += 1+ }+ } catch {+ errorMessage = error.localizedDescription+ }+ }+}diff --git a/macos/Presentation/Views/Sidebar/ImportSQLWizard.swift b/macos/Presentation/Views/Sidebar/ImportSQLWizard.swiftnew file mode 100644index 0000000..f950be3--- /dev/null+++ b/macos/Presentation/Views/Sidebar/ImportSQLWizard.swift@@ -0,0 +1,306 @@+// ImportSQLWizard.swift+// Gridex+//+// Preview dialog shown after picking a .sql file for import.+// Displays file metadata and a syntax-highlighted preview of the first+// 100,000 characters before executing against the database.++import SwiftUI+import AppKit++/// Result returned from an SQL import run, displayed inline in the wizard.+struct ImportSQLResult {+ let success: Int+ let total: Int+ let firstError: String?++ var isSuccess: Bool { firstError == nil && success == total }+}++struct ImportSQLWizard: View {+ let fileURL: URL+ let onImport: (_ content: String) async -> ImportSQLResult++ @Environment(\.dismiss) private var dismiss+ @State private var encoding: String = "utf8"+ @State private var fileContent: String = ""+ @State private var fileSize: Int = 0+ @State private var loadError: String?+ @State private var isImporting: Bool = false+ @State private var importResult: ImportSQLResult?++ private let encodings = ["utf8", "ascii", "latin1", "utf16"]+ private let previewLimit = 100_000++ var body: some View {+ VStack(spacing: 0) {+ // Title+ Text("Import SQL Wizard")+ .font(.system(size: 14, weight: .semibold))+ .padding(.top, 16)+ .padding(.bottom, 12)++ Divider()++ // Header: encoding picker + file info+ HStack {+ Text("Encoding")+ .font(.system(size: 12))+ .foregroundStyle(.secondary)+ Picker("", selection: $encoding) {+ ForEach(encodings, id: \.self) { enc in+ Text(enc).tag(enc)+ }+ }+ .labelsHidden()+ .frame(width: 100)+ .onChange(of: encoding) { _, _ in loadFile() }++ Spacer()++ Text("\(fileURL.lastPathComponent) · \(formattedSize)")+ .font(.system(size: 12))+ .foregroundStyle(.secondary)+ }+ .padding(.horizontal, 16)+ .padding(.vertical, 10)++ HStack {+ Text("First 100,000 characters of the SQL file")+ .font(.system(size: 11))+ .foregroundStyle(.tertiary)+ Spacer()+ }+ .padding(.horizontal, 16)+ .padding(.bottom, 6)++ // Preview+ if let loadError {+ VStack {+ Image(systemName: "exclamationmark.triangle")+ .font(.title)+ .foregroundStyle(.red)+ Text(loadError)+ .font(.system(size: 12))+ .foregroundStyle(.red)+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ .padding()+ } else {+ SQLPreviewView(text: fileContent)+ .padding(.horizontal, 16)+ }++ // Inline result banner (shown after clicking Import)+ if let result = importResult {+ Divider()+ HStack(alignment: .top, spacing: 8) {+ Image(systemName: result.isSuccess ? "checkmark.circle.fill" : "exclamationmark.triangle.fill")+ .foregroundStyle(result.isSuccess ? .green : .orange)+ .font(.system(size: 14))+ VStack(alignment: .leading, spacing: 2) {+ Text(result.isSuccess+ ? "✓ Imported \(result.success) statements successfully"+ : "Imported \(result.success) / \(result.total) statements")+ .font(.system(size: 12, weight: .medium))+ .foregroundStyle(result.isSuccess ? .green : .primary)+ if let err = result.firstError {+ Text("First error: \(err)")+ .font(.system(size: 10))+ .foregroundStyle(.red)+ .lineLimit(3)+ .textSelection(.enabled)+ }+ }+ Spacer()+ }+ .padding(.horizontal, 16)+ .padding(.vertical, 10)+ .background(result.isSuccess+ ? Color.green.opacity(0.08)+ : Color.orange.opacity(0.08))+ }++ Divider()++ // Buttons+ HStack {+ if isImporting {+ ProgressView().controlSize(.small)+ Text("Importing…")+ .font(.system(size: 11))+ .foregroundStyle(.secondary)+ }+ Spacer()+ Button("Close") { dismiss() }+ .keyboardShortcut(.cancelAction)+ .pointerCursor()+ Button("Import") {+ Task { await runImport() }+ }+ .buttonStyle(.borderedProminent)+ .pointerCursor()+ .disabled(fileContent.isEmpty || isImporting)+ }+ .padding(16)+ }+ .frame(width: 760, height: 600)+ .onAppear { loadFile() }+ }++ private func runImport() async {+ isImporting = true+ importResult = nil+ defer { isImporting = false }+ do {+ let full = try String(contentsOf: fileURL, encoding: stringEncoding)+ let result = await onImport(full)+ importResult = result+ } catch {+ loadError = "Failed to read file: \(error.localizedDescription)"+ }+ }++ private var stringEncoding: String.Encoding {+ switch encoding {+ case "ascii": return .ascii+ case "latin1": return .isoLatin1+ case "utf16": return .utf16+ default: return .utf8+ }+ }++ private var formattedSize: String {+ let formatter = ByteCountFormatter()+ formatter.allowedUnits = [.useKB, .useMB]+ formatter.countStyle = .file+ return formatter.string(fromByteCount: Int64(fileSize))+ }++ private func loadFile() {+ loadError = nil+ do {+ let attrs = try FileManager.default.attributesOfItem(atPath: fileURL.path)+ fileSize = (attrs[.size] as? Int) ?? 0++ let fullContent = try String(contentsOf: fileURL, encoding: stringEncoding)+ // Only show first N characters in preview+ if fullContent.count > previewLimit {+ fileContent = String(fullContent.prefix(previewLimit))+ } else {+ fileContent = fullContent+ }+ } catch {+ loadError = "Failed to read file: \(error.localizedDescription)"+ fileContent = ""+ }+ }+}++// MARK: - Syntax-highlighted SQL preview++private struct SQLPreviewView: NSViewRepresentable {+ let text: String++ func makeNSView(context: Context) -> NSScrollView {+ let scrollView = NSScrollView()+ scrollView.hasVerticalScroller = true+ scrollView.hasHorizontalScroller = true+ scrollView.autohidesScrollers = true+ scrollView.borderType = .bezelBorder++ let textView = NSTextView()+ textView.isEditable = false+ textView.isSelectable = true+ textView.isRichText = false+ textView.font = NSFont.monospacedSystemFont(ofSize: 11, weight: .regular)+ textView.textContainerInset = NSSize(width: 8, height: 8)+ textView.backgroundColor = NSColor.textBackgroundColor+ textView.drawsBackground = true+ textView.isVerticallyResizable = true+ textView.isHorizontallyResizable = true+ textView.autoresizingMask = [.width]+ textView.textContainer?.widthTracksTextView = false+ textView.textContainer?.containerSize = NSSize(+ width: CGFloat.greatestFiniteMagnitude,+ height: CGFloat.greatestFiniteMagnitude+ )++ scrollView.documentView = textView+ applyText(to: textView)+ return scrollView+ }++ func updateNSView(_ scrollView: NSScrollView, context: Context) {+ if let textView = scrollView.documentView as? NSTextView {+ applyText(to: textView)+ }+ }++ private func applyText(to textView: NSTextView) {+ let attributed = highlightSQL(text)+ textView.textStorage?.setAttributedString(attributed)+ }++ private func highlightSQL(_ sql: String) -> NSAttributedString {+ let base = NSMutableAttributedString(+ string: sql,+ attributes: [+ .font: NSFont.monospacedSystemFont(ofSize: 11, weight: .regular),+ .foregroundColor: NSColor(white: 0.85, alpha: 1)+ ]+ )++ // Line numbers would add complexity — rely on SQL keyword highlighting + comments+ let nsText = sql as NSString+ let fullRange = NSRange(location: 0, length: nsText.length)++ // Comments (-- to end of line)+ if let commentRegex = try? NSRegularExpression(pattern: "--[^\\n]*") {+ commentRegex.enumerateMatches(in: sql, range: fullRange) { match, _, _ in+ if let r = match?.range {+ base.addAttribute(.foregroundColor, value: NSColor.systemGreen, range: r)+ }+ }+ }++ // Strings 'single-quoted'+ if let stringRegex = try? NSRegularExpression(pattern: "'(?:[^']|'')*'") {+ stringRegex.enumerateMatches(in: sql, range: fullRange) { match, _, _ in+ if let r = match?.range {+ base.addAttribute(.foregroundColor, value: NSColor.systemOrange, range: r)+ }+ }+ }++ // Double-quoted identifiers (highlighted subtly)+ if let idRegex = try? NSRegularExpression(pattern: "\"[^\"]*\"") {+ idRegex.enumerateMatches(in: sql, range: fullRange) { match, _, _ in+ if let r = match?.range {+ base.addAttribute(.foregroundColor, value: NSColor.systemTeal, range: r)+ }+ }+ }++ // Keywords+ let keywords = [+ "CREATE", "TABLE", "SEQUENCE", "INDEX", "DROP", "IF", "NOT", "EXISTS",+ "INSERT", "INTO", "VALUES", "SELECT", "FROM", "WHERE", "AND", "OR",+ "UPDATE", "SET", "DELETE", "ALTER", "ADD", "COLUMN", "CONSTRAINT",+ "PRIMARY", "KEY", "FOREIGN", "REFERENCES", "UNIQUE", "NULL", "DEFAULT",+ "ON", "CASCADE", "USING", "BTREE", "HASH", "GIN", "GIST",+ "BEGIN", "COMMIT", "ROLLBACK", "TRUE", "FALSE", "AS"+ ]+ let kwPattern = "\\b(" + keywords.joined(separator: "|") + ")\\b"+ if let kwRegex = try? NSRegularExpression(pattern: kwPattern, options: .caseInsensitive) {+ kwRegex.enumerateMatches(in: sql, range: fullRange) { match, _, _ in+ if let r = match?.range {+ base.addAttribute(.foregroundColor, value: NSColor(red: 0.75, green: 0.45, blue: 0.9, alpha: 1), range: r)+ base.addAttribute(.font, value: NSFont.monospacedSystemFont(ofSize: 11, weight: .semibold), range: r)+ }+ }+ }++ return base+ }+}diff --git a/macos/Presentation/Views/Sidebar/QueryHistoryTab.swift b/macos/Presentation/Views/Sidebar/QueryHistoryTab.swiftnew file mode 100644index 0000000..55d49cd--- /dev/null+++ b/macos/Presentation/Views/Sidebar/QueryHistoryTab.swift@@ -0,0 +1,415 @@+// QueryHistoryTab.swift+// Gridex+//+// Sidebar tab showing SQL query history persisted via SwiftData.+// Only records queries run from the SQL editor (not data grid loads).++import SwiftUI+import AppKit++struct QueryHistoryTab: View {+ @EnvironmentObject private var appState: AppState+ @State private var entries: [QueryHistoryEntry] = []+ @State private var searchText = ""+ @State private var isLoading = false+ @State private var hoveredId: UUID?++ var body: some View {+ VStack(spacing: 0) {+ // Search bar+ HStack(spacing: 6) {+ Image(systemName: "magnifyingglass")+ .font(.system(size: 11))+ .foregroundStyle(.secondary)+ TextField("Search history…", text: $searchText)+ .textFieldStyle(.plain)+ .font(.system(size: 12))+ .onSubmit { Task { await reload() } }+ if !searchText.isEmpty {+ Button {+ searchText = ""+ Task { await reload() }+ } label: {+ Image(systemName: "xmark.circle.fill")+ .font(.system(size: 11))+ .foregroundStyle(.secondary)+ }+ .buttonStyle(.plain)+ .pointerCursor()+ }+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 8)+ .background(Color(NSColor.windowBackgroundColor))++ Divider()++ if isLoading {+ ProgressView().controlSize(.small)+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ } else if entries.isEmpty {+ emptyState+ } else {+ list+ }++ Divider()++ // Footer+ HStack {+ Text("\(entries.count) \(entries.count == 1 ? "entry" : "entries")")+ .font(.system(size: 10))+ .foregroundStyle(.tertiary)+ Spacer()+ Button {+ Task { await clearAll() }+ } label: {+ HStack(spacing: 3) {+ Image(systemName: "trash")+ .font(.system(size: 10))+ Text("Clear")+ .font(.system(size: 10))+ }+ .foregroundStyle(.secondary)+ }+ .buttonStyle(.plain)+ .pointerCursor()+ .help("Clear history for this connection")+ .disabled(entries.isEmpty)+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 5)+ }+ .task { await reload() }+ .onChange(of: appState.activeConnectionId) { _, _ in+ Task { await reload() }+ }+ .onChange(of: appState.queryHistoryVersion) { _, _ in+ Task { await reload() }+ }+ .onChange(of: searchText) { _, _ in+ Task { await reload() }+ }+ }++ // MARK: - Subviews++ private var emptyState: some View {+ VStack(spacing: 10) {+ Image(systemName: "clock.arrow.circlepath")+ .font(.system(size: 32))+ .foregroundStyle(.tertiary)+ Text("No query history")+ .font(.system(size: 12, weight: .medium))+ .foregroundStyle(.secondary)+ Text("Run a query in the SQL editor to see it here")+ .font(.system(size: 10))+ .foregroundStyle(.tertiary)+ .multilineTextAlignment(.center)+ .padding(.horizontal, 16)+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ }++ private var list: some View {+ ScrollView {+ LazyVStack(alignment: .leading, spacing: 0, pinnedViews: [.sectionHeaders]) {+ ForEach(groupedByDay, id: \.key) { group in+ Section {+ ForEach(group.entries) { entry in+ HistoryRow(+ entry: entry,+ isHovered: hoveredId == entry.id,+ onPaste: { paste(entry) },+ onCopy: { copy(entry) },+ onToggleFavorite: { Task { await toggleFavorite(entry) } },+ onDelete: { Task { await delete(entry) } }+ )+ .onHover { hovering in+ hoveredId = hovering ? entry.id : nil+ }+ }+ } header: {+ SectionHeader(title: group.key, count: group.entries.count)+ }+ }+ }+ }+ .background(Color(NSColor.windowBackgroundColor))+ }++ // MARK: - Grouping++ private var groupedByDay: [(key: String, entries: [QueryHistoryEntry])] {+ let cal = Calendar.current+ let now = Date()+ var groups: [(String, [QueryHistoryEntry])] = []+ var currentKey: String? = nil+ var currentList: [QueryHistoryEntry] = []++ for entry in entries {+ let key: String+ if cal.isDateInToday(entry.executedAt) {+ key = "Today"+ } else if cal.isDateInYesterday(entry.executedAt) {+ key = "Yesterday"+ } else if cal.dateComponents([.day], from: entry.executedAt, to: now).day ?? 0 <= 7 {+ let df = DateFormatter()+ df.dateFormat = "EEEE"+ key = df.string(from: entry.executedAt)+ } else {+ let df = DateFormatter()+ df.dateFormat = "MMM d, yyyy"+ key = df.string(from: entry.executedAt)+ }++ if currentKey == nil || currentKey == key {+ currentKey = key+ currentList.append(entry)+ } else {+ if let k = currentKey { groups.append((k, currentList)) }+ currentKey = key+ currentList = [entry]+ }+ }+ if let k = currentKey { groups.append((k, currentList)) }+ return groups+ }++ // MARK: - Actions++ private func reload() async {+ guard let connectionId = appState.activeConnectionId else {+ entries = []+ return+ }+ isLoading = true+ defer { isLoading = false }++ let repo = appState.container.queryHistoryRepository+ do {+ if searchText.trimmingCharacters(in: .whitespaces).isEmpty {+ entries = try await repo.fetchRecent(connectionId: connectionId, limit: 200)+ } else {+ entries = try await repo.search(query: searchText, connectionId: connectionId)+ }+ } catch {+ entries = []+ }+ }++ private func paste(_ entry: QueryHistoryEntry) {+ NotificationCenter.default.post(+ name: .init("pasteQueryToEditor"),+ object: nil,+ userInfo: ["sql": entry.sql]+ )+ }++ private func copy(_ entry: QueryHistoryEntry) {+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(entry.sql, forType: .string)+ }++ private func toggleFavorite(_ entry: QueryHistoryEntry) async {+ let repo = appState.container.queryHistoryRepository+ try? await repo.toggleFavorite(id: entry.id)+ await reload()+ }++ private func delete(_ entry: QueryHistoryEntry) async {+ let repo = appState.container.queryHistoryRepository+ try? await repo.delete(id: entry.id)+ await reload()+ }++ private func clearAll() async {+ guard let connectionId = appState.activeConnectionId else { return }+ let repo = appState.container.queryHistoryRepository+ try? await repo.deleteAll(connectionId: connectionId)+ await reload()+ }+}++// MARK: - Section Header++private struct SectionHeader: View {+ let title: String+ let count: Int++ var body: some View {+ HStack {+ Text(title.uppercased())+ .font(.system(size: 10, weight: .semibold))+ .foregroundStyle(.secondary)+ Text("·")+ .foregroundStyle(.tertiary)+ Text("\(count)")+ .font(.system(size: 10))+ .foregroundStyle(.tertiary)+ Spacer()+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 5)+ .background(Color(NSColor.windowBackgroundColor).opacity(0.95))+ }+}++// MARK: - History Row++private struct HistoryRow: View {+ let entry: QueryHistoryEntry+ let isHovered: Bool+ let onPaste: () -> Void+ let onCopy: () -> Void+ let onToggleFavorite: () -> Void+ let onDelete: () -> Void++ var body: some View {+ VStack(alignment: .leading, spacing: 4) {+ // Top row: status dot + time + duration + rows + fav+ HStack(spacing: 6) {+ Circle()+ .fill(entry.status == .success ? Color.green : Color.red)+ .frame(width: 6, height: 6)++ Text(timeString)+ .font(.system(size: 10, weight: .medium))+ .foregroundStyle(.secondary)++ if entry.duration > 0 {+ Text("·")+ .font(.system(size: 10))+ .foregroundStyle(.tertiary)+ Text(durationString)+ .font(.system(size: 10))+ .foregroundStyle(.tertiary)+ }++ if let rows = entry.rowCount {+ Text("·")+ .font(.system(size: 10))+ .foregroundStyle(.tertiary)+ Text("\(rows) \(rows == 1 ? "row" : "rows")")+ .font(.system(size: 10))+ .foregroundStyle(.tertiary)+ }++ Spacer()++ if entry.isFavorite {+ Image(systemName: "star.fill")+ .font(.system(size: 9))+ .foregroundStyle(.yellow)+ }++ // Hover actions+ if isHovered {+ Button(action: onCopy) {+ Image(systemName: "doc.on.doc")+ .font(.system(size: 10))+ }+ .buttonStyle(.plain)+ .pointerCursor()+ .help("Copy SQL")++ Button(action: onPaste) {+ Image(systemName: "arrow.up.doc")+ .font(.system(size: 10))+ }+ .buttonStyle(.plain)+ .pointerCursor()+ .help("Paste to editor")+ }+ }++ // SQL preview with keyword highlighting+ Text(highlightedSQL)+ .font(.system(size: 11, design: .monospaced))+ .lineLimit(3)+ .fixedSize(horizontal: false, vertical: true)++ // Error message (if any)+ if let err = entry.errorMessage, !err.isEmpty {+ Text(err)+ .font(.system(size: 10))+ .foregroundStyle(.red.opacity(0.8))+ .lineLimit(2)+ .padding(.top, 2)+ }+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 7)+ .background(+ isHovered ? Color.primary.opacity(0.05) : Color.clear+ )+ .contentShape(Rectangle())+ .onTapGesture(count: 2) { onPaste() }+ .contextMenu {+ Button("Paste to Editor", action: onPaste)+ Button("Copy SQL", action: onCopy)+ Divider()+ Button(entry.isFavorite ? "Unfavorite" : "Favorite", action: onToggleFavorite)+ Divider()+ Button("Delete", role: .destructive, action: onDelete)+ }+ }++ private var timeString: String {+ let df = DateFormatter()+ df.dateFormat = "HH:mm:ss"+ return df.string(from: entry.executedAt)+ }++ private var durationString: String {+ let ms = entry.duration * 1000+ if ms < 1 { return "<1ms" }+ if ms < 1000 { return String(format: "%.0fms", ms) }+ return String(format: "%.2fs", entry.duration)+ }++ /// Collapse whitespace and highlight SQL keywords in color.+ private var highlightedSQL: AttributedString {+ let collapsed = entry.sql+ .replacingOccurrences(of: "\n", with: " ")+ .replacingOccurrences(of: "\t", with: " ")+ .components(separatedBy: " ")+ .filter { !$0.isEmpty }+ .joined(separator: " ")++ var result = AttributedString(collapsed)+ result.foregroundColor = .primary++ let keywords = [+ "SELECT", "FROM", "WHERE", "JOIN", "LEFT JOIN", "RIGHT JOIN",+ "INNER JOIN", "ON", "AND", "OR", "ORDER BY", "GROUP BY",+ "HAVING", "LIMIT", "OFFSET", "INSERT INTO", "VALUES",+ "UPDATE", "SET", "DELETE FROM", "CREATE TABLE", "ALTER TABLE",+ "DROP TABLE", "WITH", "AS", "DISTINCT", "UNION", "EXISTS",+ "IN", "NOT", "NULL", "IS", "LIKE", "BETWEEN", "CASE",+ "WHEN", "THEN", "ELSE", "END", "RETURNING", "EXPLAIN"+ ]++ let upper = collapsed.uppercased()+ for kw in keywords {+ var searchRange = upper.startIndex..<upper.endIndex+ while let range = upper.range(of: kw, options: .literal, range: searchRange) {+ // Check word boundaries+ let before = range.lowerBound == upper.startIndex || !upper[upper.index(before: range.lowerBound)].isLetter+ let afterIdx = range.upperBound+ let after = afterIdx == upper.endIndex || !upper[afterIdx].isLetter+ if before && after {+ let start = collapsed.distance(from: collapsed.startIndex, to: range.lowerBound)+ let length = kw.count+ if let attrRange = Range(NSRange(location: start, length: length), in: result) {+ result[attrRange].foregroundColor = Color(red: 0.53, green: 0.33, blue: 0.87)+ result[attrRange].font = .system(size: 11, weight: .semibold, design: .monospaced)+ }+ }+ searchRange = range.upperBound..<upper.endIndex+ }+ }++ return result+ }+}diff --git a/macos/Presentation/Views/Sidebar/SidebarItem.swift b/macos/Presentation/Views/Sidebar/SidebarItem.swiftnew file mode 100644index 0000000..a128d60--- /dev/null+++ b/macos/Presentation/Views/Sidebar/SidebarItem.swift@@ -0,0 +1,76 @@+// SidebarItem.swift+// Gridex++import Foundation++class SidebarItem: Identifiable {+ let id: UUID+ let title: String+ let type: SidebarItemType+ let iconName: String+ var children: [SidebarItem]+ var badge: String?+ var isFavorite: Bool++ init(+ id: UUID = UUID(),+ title: String,+ type: SidebarItemType,+ iconName: String = "",+ children: [SidebarItem] = [],+ badge: String? = nil,+ isFavorite: Bool = false+ ) {+ self.id = id+ self.title = title+ self.type = type+ self.iconName = iconName+ self.children = children+ self.badge = badge+ self.isFavorite = isFavorite+ }+}++enum SidebarItemType: Hashable {+ case connection(ConnectionConfig)+ case database(String)+ case schema(String)+ case table(String)+ case view(String)+ case materializedView(String)+ case function(String)+ case procedure(String)+ case enumType(String)+ case group(String)++ static func == (lhs: SidebarItemType, rhs: SidebarItemType) -> Bool {+ switch (lhs, rhs) {+ case (.connection(let a), .connection(let b)): return a.id == b.id+ case (.database(let a), .database(let b)): return a == b+ case (.schema(let a), .schema(let b)): return a == b+ case (.table(let a), .table(let b)): return a == b+ case (.view(let a), .view(let b)): return a == b+ case (.materializedView(let a), .materializedView(let b)): return a == b+ case (.function(let a), .function(let b)): return a == b+ case (.procedure(let a), .procedure(let b)): return a == b+ case (.enumType(let a), .enumType(let b)): return a == b+ case (.group(let a), .group(let b)): return a == b+ default: return false+ }+ }++ func hash(into hasher: inout Hasher) {+ switch self {+ case .connection(let c): hasher.combine("connection"); hasher.combine(c.id)+ case .database(let s): hasher.combine("database"); hasher.combine(s)+ case .schema(let s): hasher.combine("schema"); hasher.combine(s)+ case .table(let s): hasher.combine("table"); hasher.combine(s)+ case .view(let s): hasher.combine("view"); hasher.combine(s)+ case .materializedView(let s): hasher.combine("matview"); hasher.combine(s)+ case .function(let s): hasher.combine("function"); hasher.combine(s)+ case .procedure(let s): hasher.combine("procedure"); hasher.combine(s)+ case .enumType(let s): hasher.combine("enum"); hasher.combine(s)+ case .group(let s): hasher.combine("group"); hasher.combine(s)+ }+ }+}diff --git a/macos/Presentation/Views/Sidebar/SidebarView.swift b/macos/Presentation/Views/Sidebar/SidebarView.swiftnew file mode 100644index 0000000..962eca1--- /dev/null+++ b/macos/Presentation/Views/Sidebar/SidebarView.swift@@ -0,0 +1,916 @@+// SidebarView.swift+// Gridex+//+// Sidebar: Items / Queries / History tabs, tree, bottom schema bar.++import SwiftUI++// MARK: - Sidebar Tab++private enum SidebarTab: String, CaseIterable {+ case items, queries, history++ var title: String { rawValue.capitalized }++ var iconName: String {+ switch self {+ case .items: return "folder"+ case .queries: return "doc.text"+ case .history: return "clock"+ }+ }+}++// MARK: - SidebarView++struct SidebarView: View {+ @EnvironmentObject private var appState: AppState+ @State private var searchText = ""+ @State private var activeTab: SidebarTab = .items+ @State private var selectedSchema = "public"+ @State private var showNewTableSheet = false+ @State private var deleteErrorMessage: String?++ var body: some View {+ VStack(spacing: 0) {+ tabBar+ Divider()++ switch activeTab {+ case .items:+ itemsTab+ case .queries:+ emptyTab(icon: "doc.text", label: "No Queries")+ case .history:+ QueryHistoryTab()+ }+ }+ .alert("Delete Failed", isPresented: Binding(+ get: { deleteErrorMessage != nil },+ set: { if !$0 { deleteErrorMessage = nil } }+ )) {+ Button("OK", role: .cancel) {}+ } message: {+ Text(deleteErrorMessage ?? "")+ }+ }++ // MARK: - Tab bar++ private var tabBar: some View {+ HStack(spacing: 1) {+ ForEach(SidebarTab.allCases, id: \.self) { tab in+ Button {+ activeTab = tab+ } label: {+ Image(systemName: tab.iconName)+ .font(.system(size: 13))+ .foregroundStyle(activeTab == tab ? Color.accentColor : Color.secondary)+ .frame(maxWidth: .infinity)+ .frame(height: 28)+ .background(+ activeTab == tab+ ? Color.accentColor.opacity(0.12)+ : Color.clear+ )+ .clipShape(RoundedRectangle(cornerRadius: 5))+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .help(tab.title)+ }+ }+ .padding(.horizontal, 6)+ .padding(.vertical, 4)+ .background(Color(NSColor.windowBackgroundColor))+ }++ // MARK: - Items tab++ private var itemsTab: some View {+ VStack(spacing: 0) {+ searchBar+ Divider()++ List {+ ForEach(filteredItems, id: \.id) { item in+ SidebarItemRow(item: item, searchText: searchText)+ }+ }+ .listStyle(.plain)+ .scrollContentBackground(.hidden)+ .background(Color(NSColor.windowBackgroundColor))++ Divider()+ bottomBar+ }+ .onReceive(NotificationCenter.default.publisher(for: .commitChanges)) { _ in+ // Commit pending table deletions when the toolbar ✓ button is clicked.+ // Only handle if the current workspace focus is the sidebar (no data-grid tab with pending changes).+ guard !appState.pendingTableDeletions.isEmpty || !appState.pendingTableTruncations.isEmpty else { return }+ Task {+ await commitPendingTruncations()+ await commitPendingDeletions()+ }+ }+ }++ private func commitPendingTruncations() async {+ guard let adapter = appState.activeAdapter else { return }+ let d = adapter.databaseType.sqlDialect+ for name in appState.pendingTableTruncations {+ let quoted = d.quoteIdentifier(name)+ let sql: String+ if adapter.databaseType == .sqlite {+ sql = "DELETE FROM \(quoted)"+ } else {+ sql = "TRUNCATE TABLE \(quoted)"+ }+ _ = try? await adapter.executeRaw(sql: sql)+ }+ appState.pendingTableTruncations.removeAll()+ appState.refreshSidebar()+ NotificationCenter.default.post(name: .reloadData, object: nil)+ }++ private func commitPendingDeletions() async {+ guard let adapter = appState.activeAdapter else { return }+ let d = adapter.databaseType.sqlDialect+ let schemaName = "public" // TODO: use selected schema++ // MySQL-specific: disable FK checks globally if any table has ignoreForeignKeys+ let shouldIgnoreFK = appState.pendingTableDeletions.values.contains { $0.ignoreForeignKeys }+ if shouldIgnoreFK && adapter.databaseType == .mysql {+ _ = try? await adapter.executeRaw(sql: "SET FOREIGN_KEY_CHECKS = 0")+ }++ var failedTables: [String: String] = [:]++ for pending in appState.pendingTableDeletions.values {+ let qualified: String+ if adapter.databaseType == .sqlite {+ qualified = d.quoteIdentifier(pending.tableName)+ } else {+ qualified = "\(d.quoteIdentifier(schemaName)).\(d.quoteIdentifier(pending.tableName))"+ }+ var sql = "DROP TABLE IF EXISTS \(qualified)"+ if pending.cascade && adapter.databaseType == .postgresql {+ sql += " CASCADE"+ }+ do {+ _ = try await adapter.executeRaw(sql: sql)+ // Close any open tabs for this table+ appState.tabs.removeAll { $0.tableName == pending.tableName && $0.type == .dataGrid }+ appState.pendingTableDeletions.removeValue(forKey: pending.tableName)+ } catch {+ failedTables[pending.tableName] = error.localizedDescription+ }+ }++ if shouldIgnoreFK && adapter.databaseType == .mysql {+ _ = try? await adapter.executeRaw(sql: "SET FOREIGN_KEY_CHECKS = 1")+ }++ if !failedTables.isEmpty {+ let details = failedTables.map { "\($0.key): \($0.value)" }.joined(separator: "\n")+ deleteErrorMessage = "Failed to delete:\n\(details)"+ }++ appState.refreshSidebar()+ }++ private var searchBar: some View {+ HStack(spacing: 5) {+ Image(systemName: "magnifyingglass")+ .font(.system(size: 11))+ .foregroundStyle(.tertiary)++ TextField("Search for item...", text: $searchText)+ .textFieldStyle(.plain)+ .font(.system(size: 12))++ if searchText.isEmpty {+ Button {+ } label: {+ Image(systemName: "line.3.horizontal.decrease")+ .font(.system(size: 11))+ .foregroundStyle(.tertiary)+ }+ .buttonStyle(.plain)+ } else {+ Button { searchText = "" } label: {+ Image(systemName: "xmark.circle.fill")+ .font(.system(size: 11))+ .foregroundStyle(.secondary)+ }+ .buttonStyle(.plain)+ }+ }+ .padding(.horizontal, 8)+ .padding(.vertical, 6)+ }++ private var bottomBar: some View {+ HStack(spacing: 2) {+ // Backup+ Button { BackupRestorePanel.openBackup(appState: appState) } label: {+ Image(systemName: "arrow.up.doc")+ .font(.system(size: 12))+ .frame(width: 28, height: 22)+ }+ .buttonStyle(.plain)+ .help("Backup database…")++ // Restore+ Button { BackupRestorePanel.openRestore(appState: appState) } label: {+ Image(systemName: "arrow.down.doc")+ .font(.system(size: 12))+ .frame(width: 28, height: 22)+ }+ .buttonStyle(.plain)+ .help("Restore database…")++ Spacer()++ Picker("", selection: $selectedSchema) {+ Text("public").tag("public")+ }+ .labelsHidden()+ .pickerStyle(.menu)+ .font(.system(size: 12))+ .frame(width: 80)+ }+ .padding(.horizontal, 6)+ .padding(.vertical, 4)+ }++ // MARK: - Empty tabs++ private func emptyTab(icon: String, label: String) -> some View {+ VStack(spacing: 8) {+ Image(systemName: icon)+ .font(.system(size: 28))+ .foregroundStyle(.quaternary)+ Text(label)+ .font(.system(size: 12))+ .foregroundStyle(.secondary)+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ }++ // MARK: - Filtering++ private var filteredItems: [SidebarItem] {+ guard !searchText.isEmpty else { return appState.sidebarItems }+ return appState.sidebarItems.compactMap { filterItem($0, query: searchText.lowercased()) }+ }++ private func filterItem(_ item: SidebarItem, query: String) -> SidebarItem? {+ if item.children.isEmpty {+ return item.title.lowercased().contains(query) ? item : nil+ }+ let matched = item.children.compactMap { filterItem($0, query: query) }+ if matched.isEmpty && !item.title.lowercased().contains(query) { return nil }+ return SidebarItem(id: item.id, title: item.title, type: item.type, iconName: item.iconName,+ children: matched.isEmpty ? item.children : matched, badge: item.badge)+ }+}++// MARK: - Sidebar Item Row++struct SidebarItemRow: View {+ let item: SidebarItem+ let searchText: String+ @EnvironmentObject private var appState: AppState+ @State private var isExpanded = true+ @State private var showTruncateConfirm = false+ @State private var showDeleteSheet = false+ @State private var showExportSheet = false+ @State private var showImportCSVSheet = false+ @State private var importSQLFile: IdentifiableURL?+ @State private var importResultMessage: String?++ var body: some View {+ if item.children.isEmpty {+ leafRow+ } else {+ groupRow+ }+ }++ // Leaf item (table, view, function)+ private var leafRow: some View {+ let isActive = appState.selectedSidebarItem == item.type+ let isPendingDelete: Bool = {+ if case .table(let name) = item.type {+ return appState.pendingTableDeletions[name] != nil+ }+ return false+ }()+ let isPendingTruncate: Bool = {+ if case .table(let name) = item.type {+ return appState.pendingTableTruncations.contains(name)+ }+ return false+ }()++ return HStack(spacing: 6) {+ tableIcon+ Text(item.title)+ .font(.system(size: 12))+ .lineLimit(1)+ .strikethrough(isPendingDelete)+ .foregroundStyle(+ isPendingDelete ? Color.white.opacity(0.8)+ : (isPendingTruncate || isActive) ? .white+ : .primary+ )+ Spacer()+ }+ .padding(.vertical, 3)+ .padding(.horizontal, 6)+ .background(+ isPendingDelete+ ? Color.red.opacity(0.35)+ : isPendingTruncate+ ? Color.orange.opacity(0.6)+ : isActive+ ? Color.accentColor+ : Color.clear+ )+ .clipShape(RoundedRectangle(cornerRadius: 5))+ .tag(item.type)+ .contentShape(Rectangle())+ .pointerCursor()+ .onTapGesture {+ appState.selectedSidebarItem = item.type+ // Open table/view on single click+ switch item.type {+ case .table(let name):+ appState.openTable(name: name, schema: nil)+ case .view(let name):+ appState.openTable(name: name, schema: nil)+ case .function(let name):+ appState.openFunction(name: name, schema: nil)+ case .procedure(let name):+ appState.openProcedure(name: name, schema: nil)+ default:+ break+ }+ }+ .contextMenu { tableContextMenu }+ .alert("Truncate Table", isPresented: $showTruncateConfirm) {+ Button("Cancel", role: .cancel) {}+ Button("Truncate", role: .destructive) {+ if case .table(let name) = item.type {+ appState.pendingTableTruncations.insert(name)+ }+ }+ } message: {+ if case .table(let name) = item.type {+ Text("Are you sure you want to remove all rows from \"\(name)\"? This cannot be undone.")+ }+ }+ .sheet(isPresented: $showDeleteSheet) {+ if case .table(let name) = item.type {+ DeleteTableSheet(tableName: name) { cascade, ignoreFK in+ appState.pendingTableDeletions[name] = AppState.PendingTableDeletion(+ tableName: name,+ cascade: cascade,+ ignoreForeignKeys: ignoreFK+ )+ }+ }+ }+ .sheet(isPresented: $showExportSheet) {+ if case .table(let name) = item.type {+ ExportTableSheet(tableName: name)+ }+ }+ .sheet(isPresented: $showImportCSVSheet) {+ if case .table(let name) = item.type {+ ImportCSVSheet(tableName: name)+ }+ }+ .sheet(item: $importSQLFile, onDismiss: {+ // Refresh sidebar after the wizard closes so newly-imported tables appear+ appState.refreshSidebar()+ }) { wrapper in+ ImportSQLWizard(fileURL: wrapper.url) { content in+ await executeSQLDump(content: content, fileName: wrapper.url.lastPathComponent)+ }+ }+ .alert("Import Result", isPresented: Binding(+ get: { importResultMessage != nil },+ set: { if !$0 { importResultMessage = nil } }+ )) {+ Button("OK") { importResultMessage = nil }+ } message: {+ Text(importResultMessage ?? "")+ }+ }++ // Group row (Functions, Tables, Views)+ private var groupRow: some View {+ DisclosureGroup(isExpanded: $isExpanded) {+ ForEach(item.children, id: \.id) { child in+ SidebarItemRow(item: child, searchText: searchText)+ }+ } label: {+ HStack(spacing: 5) {+ Text(item.title)+ .font(.system(size: 12, weight: .medium))+ .foregroundStyle(.secondary)+ .onTapGesture {+ if case .group(let kind) = item.type, kind == "tables" {+ appState.openTableList(schema: nil)+ }+ }+ Spacer()+ if let badge = item.badge {+ Text(badge)+ .font(.system(size: 10))+ .foregroundStyle(.tertiary)+ .padding(.trailing, 2)+ }+ // Inline "+" button for the Tables group to create a new table+ if case .group(let kind) = item.type, kind == "tables" {+ Button {+ appState.openCreateTable(schema: nil)+ } label: {+ Image(systemName: "plus")+ .font(.system(size: 10, weight: .semibold))+ .foregroundStyle(.secondary)+ .frame(width: 18, height: 18)+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .pointerCursor()+ .help("New Table")+ }+ }+ .contentShape(Rectangle())+ .contextMenu { groupContextMenu }+ }+ }++ @ViewBuilder+ private var groupContextMenu: some View {+ if case .group(let kind) = item.type {+ switch kind {+ case "tables":+ Button("New Table…") {+ appState.openCreateTable(schema: nil)+ }+ Button("Open Table List") {+ appState.openTableList(schema: nil)+ }+ Button("ER Diagram") {+ appState.openERDiagram(schema: nil)+ }+ Divider()+ Button("Refresh") { appState.refreshSidebar() }+ default:+ Button("Refresh") { appState.refreshSidebar() }+ }+ }+ }++ // Small grid icon for tables/views+ @ViewBuilder+ private var tableIcon: some View {+ switch item.type {+ case .table:+ Image(systemName: "tablecells")+ .font(.system(size: 11))+ .foregroundStyle(Color(red: 0.8, green: 0.5, blue: 0.2))+ .frame(width: 14)+ case .view:+ Image(systemName: "eye")+ .font(.system(size: 11))+ .foregroundStyle(.purple)+ .frame(width: 14)+ case .procedure:+ Image(systemName: "play.square")+ .font(.system(size: 11))+ .foregroundStyle(.green)+ .frame(width: 14)+ default:+ Image(systemName: "function")+ .font(.system(size: 11))+ .foregroundStyle(.blue)+ .frame(width: 14)+ }+ }++ // MARK: - Context Menu++ @ViewBuilder+ private var tableContextMenu: some View {+ if appState.activeConfig?.databaseType == .redis {+ // Redis-specific context menu+ if case .table(_) = item.type {+ Button("Browse Keys") {+ appState.openTable(name: "Keys", schema: nil)+ }+ Button("Add Key…") {+ appState.showRedisAddKey = true+ }+ Divider()+ Button("Server Info") { appState.openRedisServerInfo() }+ Button("Slow Log") { appState.openRedisSlowLog() }+ Divider()+ Button("Flush Database…") { appState.showFlushDBConfirm = true }+ Divider()+ Button("Refresh") { appState.refreshSidebar() }+ } else {+ Button("Refresh") { appState.refreshSidebar() }+ }+ } else if case .table(let name) = item.type {+ Button("Open in new tab") {+ appState.openTable(name: name, schema: nil)+ }++ Button("Open structure") {+ appState.openTableStructure(name: name, schema: nil)+ }++ Divider()++ Button("New Table…") {+ appState.openCreateTable(schema: nil)+ }++ Button("Copy name") {+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(name, forType: .string)+ }++ Divider()++ Button("Export...") {+ showExportSheet = true+ }++ Menu("Import") {+ Button("From CSV…") {+ DispatchQueue.main.async {+ showImportCSVSheet = true+ }+ }+ Button("From SQL Dump…") {+ DispatchQueue.main.async {+ pickSQLDumpFile()+ }+ }+ }++ Divider()++ Menu("Copy Script As") {+ Button("CREATE TABLE") {+ Task { await copyCreateScript(name) }+ }+ Button("SELECT") {+ copyToClipboard("SELECT * FROM \(quoted(name)) LIMIT 100;")+ }+ Button("INSERT") {+ Task { await copyInsertScript(name) }+ }+ Button("UPDATE") {+ Task { await copyUpdateScript(name) }+ }+ Button("DELETE") {+ copyToClipboard("DELETE FROM \(quoted(name)) WHERE <condition>;")+ }+ }++ Divider()++ if appState.pendingTableTruncations.contains(name) {+ Button("Undo Truncate") {+ appState.pendingTableTruncations.remove(name)+ }+ } else {+ Button("Truncate...") {+ showTruncateConfirm = true+ }+ }++ if appState.pendingTableDeletions[name] != nil {+ Button("Undo Delete") {+ appState.pendingTableDeletions.removeValue(forKey: name)+ }+ } else {+ Button("Delete...") {+ showDeleteSheet = true+ }+ }+ } else {+ Button("New Table…") {+ appState.openCreateTable(schema: nil)+ }+ Divider()+ Button("Refresh") { appState.refreshSidebar() }+ }+ }++ // MARK: - Context Menu Actions++ private func quoted(_ name: String) -> String {+ guard let adapter = appState.activeAdapter else { return "\"\(name)\"" }+ return adapter.databaseType.sqlDialect.quoteIdentifier(name)+ }++ private func copyToClipboard(_ text: String) {+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(text, forType: .string)+ }++ private func copyCreateScript(_ name: String) async {+ guard let adapter = appState.activeAdapter else { return }+ if let desc = try? await adapter.describeTable(name: name, schema: nil) {+ let ddl = desc.toDDL(dialect: adapter.databaseType.sqlDialect)+ copyToClipboard(ddl)+ }+ }++ private func copyInsertScript(_ name: String) async {+ guard let adapter = appState.activeAdapter else { return }+ if let desc = try? await adapter.describeTable(name: name, schema: nil) {+ let cols = desc.columns.map { adapter.databaseType.sqlDialect.quoteIdentifier($0.name) }.joined(separator: ", ")+ let vals = desc.columns.map { _ in "?" }.joined(separator: ", ")+ copyToClipboard("INSERT INTO \(quoted(name)) (\(cols)) VALUES (\(vals));")+ }+ }++ private func copyUpdateScript(_ name: String) async {+ guard let adapter = appState.activeAdapter else { return }+ if let desc = try? await adapter.describeTable(name: name, schema: nil) {+ let sets = desc.columns.filter { !$0.isPrimaryKey }.map { "\(adapter.databaseType.sqlDialect.quoteIdentifier($0.name)) = ?" }.joined(separator: ", ")+ let pk = desc.columns.first(where: \.isPrimaryKey)+ let whereClause = pk.map { "\(adapter.databaseType.sqlDialect.quoteIdentifier($0.name)) = ?" } ?? "<condition>"+ copyToClipboard("UPDATE \(quoted(name)) SET \(sets) WHERE \(whereClause);")+ }+ }++ /// Show NSOpenPanel to pick a .sql file, then open the ImportSQLWizard+ /// with a preview before executing.+ private func pickSQLDumpFile() {+ let panel = NSOpenPanel()+ panel.title = "Import SQL Dump"+ panel.allowsMultipleSelection = false+ panel.canChooseDirectories = false+ panel.canChooseFiles = true+ panel.allowedContentTypes = [.data]+ if panel.runModal() == .OK, let url = panel.url {+ importSQLFile = IdentifiableURL(url: url)+ }+ }++ /// Execute the SQL content from the wizard (called after user clicks Import).+ /// Returns an ImportSQLResult so the wizard can display it inline.+ /// Does NOT call refreshSidebar() here — the wizard would re-render the+ /// parent and dismiss itself. The sidebar is refreshed when the wizard closes.+ private func executeSQLDump(content: String, fileName: String) async -> ImportSQLResult {+ guard let adapter = appState.activeAdapter else {+ return ImportSQLResult(success: 0, total: 0, firstError: "No active database connection")+ }++ let statements = Self.splitSQLStatements(content)++ var successCount = 0+ var firstError: String?+ for stmt in statements {+ do {+ _ = try await adapter.executeRaw(sql: stmt)+ successCount += 1+ } catch {+ if firstError == nil {+ firstError = error.localizedDescription+ }+ }+ }++ return ImportSQLResult(success: successCount, total: statements.count, firstError: firstError)+ }++ /// Split a SQL dump into individual statements. Correctly handles:+ /// - `;` inside single-quoted strings+ /// - `;` inside double-quoted identifiers+ /// - `--` line comments+ /// - `/* ... */` block comments+ /// - escaped quotes `''` inside strings+ static func splitSQLStatements(_ sql: String) -> [String] {+ var result: [String] = []+ var current = ""+ var inSingle = false+ var inDouble = false+ var inLineComment = false+ var inBlockComment = false++ let chars = Array(sql)+ var i = 0+ while i < chars.count {+ let c = chars[i]++ if inLineComment {+ current.append(c)+ if c == "\n" { inLineComment = false }+ i += 1+ continue+ }+ if inBlockComment {+ current.append(c)+ if c == "*" && i + 1 < chars.count && chars[i + 1] == "/" {+ current.append("/")+ inBlockComment = false+ i += 2+ continue+ }+ i += 1+ continue+ }+ if inSingle {+ current.append(c)+ if c == "'" {+ // Check for escaped ''+ if i + 1 < chars.count && chars[i + 1] == "'" {+ current.append("'")+ i += 2+ continue+ }+ inSingle = false+ }+ i += 1+ continue+ }+ if inDouble {+ current.append(c)+ if c == "\"" { inDouble = false }+ i += 1+ continue+ }++ // Not inside any literal+ if c == "-" && i + 1 < chars.count && chars[i + 1] == "-" {+ inLineComment = true+ current.append("--")+ i += 2+ continue+ }+ if c == "/" && i + 1 < chars.count && chars[i + 1] == "*" {+ inBlockComment = true+ current.append("/*")+ i += 2+ continue+ }+ if c == "'" {+ inSingle = true+ current.append(c)+ i += 1+ continue+ }+ if c == "\"" {+ inDouble = true+ current.append(c)+ i += 1+ continue+ }+ if c == ";" {+ let trimmed = current.trimmingCharacters(in: .whitespacesAndNewlines)+ if !trimmed.isEmpty {+ result.append(trimmed)+ }+ current = ""+ i += 1+ continue+ }+ current.append(c)+ i += 1+ }++ let trailing = current.trimmingCharacters(in: .whitespacesAndNewlines)+ if !trailing.isEmpty {+ result.append(trailing)+ }++ return result+ }+}++// MARK: - New Table Sheet++struct NewTableSheet: View {+ let schema: String+ @EnvironmentObject private var appState: AppState+ @Environment(\.dismiss) private var dismiss++ @State private var tableName = ""+ @State private var encoding = "Default"+ @State private var collation = "Default"+ @State private var isCreating = false+ @State private var errorMessage: String?++ private let encodings = ["Default", "UTF8", "LATIN1", "SQL_ASCII"]+ private let collations = ["Default", "C", "POSIX", "en_US.UTF-8"]++ var body: some View {+ VStack(spacing: 0) {+ // Title+ Text("New Table")+ .font(.system(size: 13, weight: .semibold))+ .padding(.top, 16)+ .padding(.bottom, 12)++ // Form+ Grid(alignment: .trailing, horizontalSpacing: 10, verticalSpacing: 10) {+ GridRow {+ Text("Name:").font(.system(size: 12))+ TextField("", text: $tableName)+ .textFieldStyle(.roundedBorder)+ .frame(width: 220)+ }+ GridRow {+ Text("Schema:").font(.system(size: 12))+ Text(schema)+ .font(.system(size: 12))+ .foregroundStyle(.secondary)+ .frame(maxWidth: .infinity, alignment: .leading)+ }+ }+ .padding(.horizontal, 20)++ if let errorMessage {+ Text(errorMessage)+ .font(.system(size: 11))+ .foregroundStyle(.red)+ .padding(.horizontal, 20)+ .padding(.top, 8)+ }++ Divider().padding(.top, 16)++ // Buttons+ HStack {+ Button("Cancel") { dismiss() }+ .keyboardShortcut(.cancelAction)+ Spacer()+ Button {+ Task { await create() }+ } label: {+ if isCreating {+ ProgressView().controlSize(.small)+ }+ Text("OK")+ }+ .keyboardShortcut(.defaultAction)+ .disabled(tableName.isEmpty || isCreating)+ }+ .padding(.horizontal, 20)+ .padding(.vertical, 12)+ }+ .frame(width: 320)+ }++ private func create() async {+ guard let adapter = appState.activeAdapter else { return }+ isCreating = true+ errorMessage = nil+ defer { isCreating = false }++ let d = adapter.databaseType.sqlDialect+ let qualifiedTable = adapter.databaseType == .sqlite+ ? d.quoteIdentifier(tableName)+ : "\(d.quoteIdentifier(schema)).\(d.quoteIdentifier(tableName))"++ // Create table with a default id column+ let idType: String+ switch adapter.databaseType {+ case .postgresql: idType = "serial PRIMARY KEY"+ case .mysql: idType = "int AUTO_INCREMENT PRIMARY KEY"+ case .sqlite: idType = "INTEGER PRIMARY KEY AUTOINCREMENT"+ case .mssql: idType = "INT IDENTITY(1,1) PRIMARY KEY"+ case .redis, .mongodb: return // Non-SQL databases don't support CREATE TABLE+ }++ let sql = "CREATE TABLE \(qualifiedTable) (id \(idType))"+ do {+ _ = try await adapter.executeRaw(sql: sql)+ } catch {+ errorMessage = DataGridViewState.detailedErrorMessage(error)+ return+ }++ dismiss()+ appState.refreshSidebar()+ appState.openTable(name: tableName, schema: schema)+ }+}++// MARK: - Helper wrapper so we can use sheet(item:) with a URL++struct IdentifiableURL: Identifiable {+ let url: URL+ var id: String { url.absoluteString }+}diff --git a/macos/Presentation/Views/StatusBar/StatusBarSwiftUI.swift b/macos/Presentation/Views/StatusBar/StatusBarSwiftUI.swiftnew file mode 100644index 0000000..bf0beb3--- /dev/null+++ b/macos/Presentation/Views/StatusBar/StatusBarSwiftUI.swift@@ -0,0 +1,49 @@+// StatusBarSwiftUI.swift+// Gridex+//+// SwiftUI bottom status bar.++import SwiftUI++struct StatusBarSwiftUIView: View {+ @EnvironmentObject private var appState: AppState++ var body: some View {+ HStack(spacing: 0) {+ statusItem(appState.statusConnection ?? "Not connected")+ separator+ statusItem(appState.statusSchema ?? "")+ separator+ statusItem(appState.statusRowCount.map { "\($0) rows" } ?? "")+ separator+ statusItem(appState.statusQueryTime.map { "\(Int($0 * 1000))ms" } ?? "")++ if let dbSize = appState.redisDBSize {+ separator+ statusItem("\(dbSize) keys")+ }++ Spacer()++ statusItem("v\(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "0")")+ }+ .padding(.horizontal, 8)+ .frame(height: 24)+ .background(Color(nsColor: .windowBackgroundColor))+ .overlay(alignment: .top) { Divider() }+ }++ private func statusItem(_ text: String) -> some View {+ Text(text)+ .font(.system(size: 11))+ .foregroundStyle(.secondary)+ .lineLimit(1)+ }++ private var separator: some View {+ Text("|")+ .font(.system(size: 11))+ .foregroundStyle(.quaternary)+ .padding(.horizontal, 6)+ }+}diff --git a/macos/Presentation/Views/TabBar/TabBarSwiftUI.swift b/macos/Presentation/Views/TabBar/TabBarSwiftUI.swiftnew file mode 100644index 0000000..d0e2472--- /dev/null+++ b/macos/Presentation/Views/TabBar/TabBarSwiftUI.swift@@ -0,0 +1,310 @@+// TabBarSwiftUI.swift+// Gridex+//+// SwiftUI tab bar for content area. Supports Chrome-style tab groups+// when multiple databases are open within a single connection.++import SwiftUI++struct TabBarSwiftUIView: View {+ @EnvironmentObject private var appState: AppState++ var body: some View {+ ScrollView(.horizontal, showsIndicators: false) {+ HStack(spacing: 0) {+ ForEach(Array(appState.groupedTabs.enumerated()), id: \.offset) { _, section in+ // Group header (only in multi-database mode)+ if let group = section.group {+ TabGroupHeaderView(group: group)+ }++ // Tab items (hidden when group is collapsed)+ if section.group?.isCollapsed != true {+ ForEach(section.tabs) { tab in+ TabItemView(tab: tab, isActive: tab.id == appState.activeTabId)+ }+ }+ }++ // [+] new tab button+ Button(action: { appState.openNewQueryTab() }) {+ Image(systemName: "plus")+ .font(.system(size: 12))+ .foregroundStyle(.secondary)+ .frame(width: 36, height: 38)+ }+ .buttonStyle(.plain)+ .pointerCursor()+ .help("New Query Tab")++ Spacer()+ }+ }+ .frame(height: 38)+ .background(Color(nsColor: .windowBackgroundColor))+ .overlay(alignment: .bottom) { Divider() }+ }+}++// MARK: - Tab Group Header++struct TabGroupHeaderView: View {+ let group: AppState.TabGroup+ @EnvironmentObject private var appState: AppState+ @State private var isHovering = false+ @State private var isRenaming = false+ @State private var renameText = ""++ private var groupColor: Color {+ Color(nsColor: group.color.nsColor)+ }++ private var tabCount: Int {+ appState.tabs.filter { $0.databaseName == group.id }.count+ }++ var body: some View {+ HStack(spacing: 4) {+ Image(systemName: group.isCollapsed ? "chevron.right" : "chevron.down")+ .font(.system(size: 8, weight: .semibold))++ if isRenaming {+ TextField("", text: $renameText, onCommit: {+ let trimmed = renameText.trimmingCharacters(in: .whitespaces)+ if !trimmed.isEmpty {+ appState.renameGroup(group.id, newName: trimmed)+ }+ isRenaming = false+ })+ .textFieldStyle(.plain)+ .font(.system(size: 11, weight: .medium))+ .frame(width: 80)+ .onAppear { renameText = group.label }+ .onExitCommand { isRenaming = false }+ } else {+ Text(group.label)+ .font(.system(size: 11, weight: .medium))+ .lineLimit(1)+ }++ if group.isCollapsed {+ Text("\(tabCount)")+ .font(.system(size: 9))+ .padding(.horizontal, 4)+ .padding(.vertical, 1)+ .background(groupColor.opacity(0.3))+ .clipShape(Capsule())+ }+ }+ .foregroundColor(groupColor)+ .padding(.horizontal, 10)+ .frame(height: 38)+ .background(groupColor.opacity(isHovering ? 0.12 : 0.07))+ .contentShape(Rectangle())+ .pointerCursor()+ .onTapGesture { appState.toggleGroupCollapsed(group.id) }+ .onHover { isHovering = $0 }+ .overlay(alignment: .bottom) {+ Rectangle()+ .fill(groupColor)+ .frame(height: 2)+ }+ .contextMenu {+ Button("Close Group") {+ appState.closeGroup(group.id)+ }++ Divider()++ Button("Rename Group") {+ isRenaming = true+ }++ Menu("Group Color") {+ ForEach(ColorTag.allCases, id: \.self) { color in+ Button {+ appState.changeGroupColor(group.id, color: color)+ } label: {+ Label(color.environmentHint, systemImage: "circle.fill")+ }+ }+ }+ }+ }+}++// MARK: - Tab Item++struct TabItemView: View {+ let tab: AppState.ContentTab+ let isActive: Bool++ @EnvironmentObject private var appState: AppState+ @State private var isHovering = false+ @State private var isRenaming = false+ @State private var renameText = ""++ /// Use the group color for the active tab accent when in multi-database mode+ private var accentColor: Color {+ if let dbName = tab.databaseName,+ let group = appState.tabGroups[dbName] {+ return Color(nsColor: group.color.nsColor)+ }+ return Color.accentColor+ }++ var body: some View {+ HStack(spacing: 7) {+ Image(systemName: tabIcon)+ .font(.system(size: 11))++ if isRenaming {+ TextField("", text: $renameText, onCommit: {+ let trimmed = renameText.trimmingCharacters(in: .whitespaces)+ if !trimmed.isEmpty {+ appState.renameTab(id: tab.id, newTitle: trimmed)+ }+ isRenaming = false+ })+ .textFieldStyle(.plain)+ .font(.system(size: 12))+ .frame(width: 100)+ .onAppear { renameText = tab.title }+ .onExitCommand { isRenaming = false }+ } else {+ Text(tab.title)+ .font(.system(size: 12))+ .lineLimit(1)+ }++ Button(action: { appState.closeTab(id: tab.id) }) {+ Image(systemName: "xmark")+ .font(.system(size: 8, weight: .bold))+ .foregroundStyle(.secondary)+ }+ .buttonStyle(.plain)+ .opacity(isHovering || isActive ? 1 : 0)+ }+ .padding(.horizontal, 14)+ .frame(height: 38)+ .contentShape(Rectangle())+ .background(isActive ? Color(nsColor: .controlBackgroundColor) : .clear)+ .overlay(alignment: .bottom) {+ if isActive {+ Rectangle()+ .fill(accentColor)+ .frame(height: 2)+ }+ }+ .overlay(alignment: .trailing) {+ Divider().frame(height: 18)+ }+ .pointerCursor()+ .onTapGesture { appState.activeTabId = tab.id }+ .overlay(MiddleClickOverlay { appState.closeTab(id: tab.id) })+ .onHover { isHovering = $0 }+ .contextMenu {+ Button("New Tab") {+ appState.openNewQueryTab()+ }++ Divider()++ Button("Close Tab") {+ appState.closeTab(id: tab.id)+ }++ Button("Close Other Tabs") {+ appState.closeOtherTabs(except: tab.id)+ }+ .disabled(appState.tabs.count <= 1)++ Button("Close Tabs to the Right") {+ appState.closeTabsToTheRight(of: tab.id)+ }+ .disabled(appState.tabs.last?.id == tab.id)++ Divider()++ Button("Close All Tabs") {+ appState.closeAllTabs()+ }++ Divider()++ Button("Rename Tab") {+ isRenaming = true+ }+ }+ }++ private var tabIcon: String {+ switch tab.type {+ case .dataGrid: return "tablecells"+ case .queryEditor: return "doc.text"+ case .tableStructure: return "list.bullet.rectangle"+ case .tableList: return "tablecells.badge.ellipsis"+ case .functionDetail: return "function"+ case .createTable: return "plus.rectangle"+ case .erDiagram: return "point.3.connected.trianglepath.dotted"+ case .redisKeyDetail: return "key.fill"+ case .redisServerInfo: return "chart.bar"+ case .redisSlowLog: return "tortoise"+ }+ }+}++// MARK: - Middle Click (scroll wheel button) to close tab++struct MiddleClickOverlay: NSViewRepresentable {+ let action: () -> Void++ func makeNSView(context: Context) -> MiddleClickNSView {+ let view = MiddleClickNSView()+ view.action = action+ return view+ }++ func updateNSView(_ nsView: MiddleClickNSView, context: Context) {+ nsView.action = action+ }+}++class MiddleClickNSView: NSView {+ var action: (() -> Void)?+ private var monitor: Any?++ override func viewDidMoveToWindow() {+ super.viewDidMoveToWindow()+ if window != nil, monitor == nil {+ monitor = NSEvent.addLocalMonitorForEvents(matching: .otherMouseDown) { [weak self] event in+ guard let self, let action = self.action, event.buttonNumber == 2 else { return event }+ let locationInView = self.convert(event.locationInWindow, from: nil)+ if self.bounds.contains(locationInView) {+ action()+ return nil+ }+ return event+ }+ }+ }++ override func removeFromSuperview() {+ if let monitor { NSEvent.removeMonitor(monitor) }+ monitor = nil+ super.removeFromSuperview()+ }++ override func viewDidMoveToSuperview() {+ super.viewDidMoveToSuperview()+ if superview == nil, let monitor {+ NSEvent.removeMonitor(monitor)+ self.monitor = nil+ }+ }++ // Completely transparent to all direct mouse events+ override func hitTest(_ point: NSPoint) -> NSView? {+ nil+ }+}diff --git a/macos/Presentation/Views/TableList/TableListView.swift b/macos/Presentation/Views/TableList/TableListView.swiftnew file mode 100644index 0000000..8ee041c--- /dev/null+++ b/macos/Presentation/Views/TableList/TableListView.swift@@ -0,0 +1,314 @@+// TableListView.swift+// Gridex+//+// Shows all tables in a schema with statistics (name, schema, kind, owner, sizes, etc.)++import SwiftUI++struct TableListView: View {+ let schema: String?++ @EnvironmentObject private var appState: AppState+ @StateObject private var viewModel = TableListViewModel()+ @State private var lastClickTime: Date = .distantPast+ @State private var lastClickedRow: Int = -1++ var body: some View {+ VStack(spacing: 0) {+ if viewModel.isLoading && viewModel.rows.isEmpty {+ ProgressView("Loading...")+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ } else if let err = viewModel.loadError {+ VStack(spacing: 8) {+ Text("Failed to load tables").foregroundStyle(.secondary)+ Text(err).font(.system(size: 11)).foregroundStyle(.red).textSelection(.enabled)+ Button("Retry") { Task { await viewModel.load(adapter: appState.activeAdapter, schema: schema) } }+ .controlSize(.small)+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ } else if viewModel.rows.isEmpty {+ Text("No tables")+ .foregroundStyle(.secondary)+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ } else {+ GeometryReader { geo in+ ScrollView([.horizontal, .vertical]) {+ let minContentWidth = max(totalColumnsWidth, geo.size.width)+ LazyVStack(alignment: .leading, spacing: 0, pinnedViews: [.sectionHeaders]) {+ Section {+ ForEach(Array(viewModel.rows.enumerated()), id: \.offset) { rowIndex, row in+ tableListRow(rowIndex: rowIndex, row: row)+ }+ } header: {+ tableListHeader+ }+ }+ .frame(minWidth: minContentWidth, minHeight: geo.size.height, alignment: .topLeading)+ }+ }+ .background(Color(nsColor: .textBackgroundColor))+ }+ }+ .task {+ await viewModel.load(adapter: appState.activeAdapter, schema: schema)+ }+ }++ // MARK: - Header++ private var tableListHeader: some View {+ HStack(spacing: 0) {+ ForEach(viewModel.columns, id: \.self) { col in+ HStack(spacing: 4) {+ Text(col)+ .font(.system(size: 11, weight: .semibold))+ .foregroundStyle(.secondary)+ Spacer()+ }+ .padding(.horizontal, 8)+ .frame(width: viewModel.columnWidths[col] ?? 120, height: 26)+ .frame(maxHeight: .infinity)+ }+ }+ .background(Color(nsColor: .controlBackgroundColor))+ .overlay(alignment: .bottom) {+ Divider()+ }+ }++ // MARK: - Row++ private func tableListRow(rowIndex: Int, row: [String]) -> some View {+ let isSelected = viewModel.selectedRow == rowIndex++ return HStack(spacing: 0) {+ // Table icon+ ForEach(Array(row.enumerated()), id: \.offset) { colIdx, value in+ HStack(spacing: 4) {+ if colIdx == 0 {+ Image(systemName: "tablecells")+ .font(.system(size: 10))+ .foregroundStyle(Color(red: 0.8, green: 0.5, blue: 0.2))+ }+ Text(value)+ .font(.system(size: 12, weight: .regular, design: .default))+ .lineLimit(1)+ .foregroundStyle(value == "NULL" || value == "EMPTY" ? .tertiary : .primary)+ Spacer()+ }+ .padding(.horizontal, 8)+ .frame(width: viewModel.columnWidths[viewModel.columns[safe: colIdx] ?? ""] ?? 120)+ }+ }+ .frame(height: 28)+ .background(isSelected ? Color.accentColor.opacity(0.2) : (rowIndex % 2 == 0 ? Color.clear : Color(nsColor: .controlBackgroundColor).opacity(0.3)))+ .contentShape(Rectangle())+ .onTapGesture {+ let now = Date()+ if lastClickedRow == rowIndex && now.timeIntervalSince(lastClickTime) < 0.3 {+ // Double click — open the table+ if let tableName = row.first {+ appState.openTable(name: tableName, schema: schema)+ }+ lastClickTime = .distantPast+ } else {+ // Single click — select and show details+ viewModel.selectedRow = rowIndex+ if rowIndex < viewModel.rows.count {+ let rowData = viewModel.rows[rowIndex]+ appState.selectedRowDetails = viewModel.columns.enumerated().map { idx, col in+ (column: col, value: idx < rowData.count ? rowData[idx] : "")+ }+ appState.onDetailFieldEdit = nil+ }+ lastClickedRow = rowIndex+ lastClickTime = now+ }+ }+ .overlay(alignment: .bottom) {+ Divider().padding(.leading, 8)+ }+ }++ private var totalColumnsWidth: CGFloat {+ viewModel.columns.reduce(CGFloat(0)) { sum, col in+ sum + (viewModel.columnWidths[col] ?? 120)+ }+ }+}++// MARK: - Safe subscript++private extension Array {+ subscript(safe index: Index) -> Element? {+ indices.contains(index) ? self[index] : nil+ }+}++// MARK: - View Model++@MainActor+final class TableListViewModel: ObservableObject {+ @Published var columns: [String] = []+ @Published var rows: [[String]] = []+ @Published var columnWidths: [String: CGFloat] = [:]+ @Published var isLoading = false+ @Published var selectedRow: Int?+ @Published var loadError: String?++ func load(adapter: (any DatabaseAdapter)?, schema: String?) async {+ guard let adapter else { return }+ isLoading = true+ defer { isLoading = false }++ do {+ let result: QueryResult+ switch adapter.databaseType {+ case .postgresql:+ result = try await adapter.executeRaw(sql: tableStatsQueryPostgres(schema: schema ?? "public"))+ case .mysql:+ result = try await adapter.executeRaw(sql: tableStatsQueryMySQL(schema: schema))+ case .sqlite:+ result = try await adapter.executeRaw(sql: tableStatsQuerySQLite())+ case .redis:+ result = try await adapter.executeRaw(sql: "INFO keyspace")+ case .mongodb:+ // MongoDB: list collections via adapter.listTables+ let tables = try await adapter.listTables(schema: nil)+ let cols = [+ ColumnHeader(name: "name", dataType: "string"),+ ColumnHeader(name: "rows", dataType: "integer"),+ ]+ let rows: [[RowValue]] = tables.map { t in+ [.string(t.name), .integer(Int64(t.estimatedRowCount ?? 0))]+ }+ result = QueryResult(columns: cols, rows: rows, rowsAffected: 0, executionTime: 0, queryType: .select)+ case .mssql:+ // SQL Server: list tables via INFORMATION_SCHEMA (portable across SQL Server / Azure SQL Edge)+ result = try await adapter.executeRaw(sql: """+ SELECT TABLE_NAME, TABLE_TYPE+ FROM INFORMATION_SCHEMA.TABLES+ WHERE TABLE_SCHEMA = '\(schema ?? "dbo")' AND TABLE_TYPE = 'BASE TABLE'+ ORDER BY TABLE_NAME+ """)+ }++ columns = result.columns.map(\.name)+ rows = result.rows.map { row in+ row.map { $0.description }+ }++ // Set column widths based on header names+ let widthMap: [String: CGFloat] = [+ "name": 150,+ "schema": 80,+ "kind": 80,+ "owner": 100,+ "columns": 80,+ "indexes": 80,+ "has_pk": 70,+ "estimated_row": 120,+ "total_size": 100,+ "data_size": 100,+ "index_size": 100,+ "toast_size": 100,+ "last_vacuum": 140,+ "last_analyze": 140,+ "live_tuples": 110,+ "dead_tuples": 110,+ "modifications": 120,+ "comment": 160,+ "type": 80,+ "rows": 100,+ "engine": 90,+ "collation": 110,+ "auto_increment": 120,+ "create_time": 140,+ "update_time": 140,+ ]+ for col in columns {+ columnWidths[col] = widthMap[col] ?? 120+ }+ } catch {+ loadError = error.localizedDescription+ }+ }++ private func tableStatsQueryPostgres(schema: String) -> String {+ """+ SELECT+ c.relname AS name,+ n.nspname AS schema,+ CASE c.relkind+ WHEN 'r' THEN 'TABLE'+ WHEN 'v' THEN 'VIEW'+ WHEN 'm' THEN 'MAT VIEW'+ WHEN 'f' THEN 'FOREIGN'+ ELSE 'OTHER'+ END AS kind,+ pg_get_userbyid(c.relowner) AS owner,+ (SELECT count(*) FROM information_schema.columns ic+ WHERE ic.table_schema = n.nspname AND ic.table_name = c.relname) AS columns,+ (SELECT count(*) FROM pg_indexes pi+ WHERE pi.schemaname = n.nspname AND pi.tablename = c.relname) AS indexes,+ CASE WHEN EXISTS (+ SELECT 1 FROM pg_constraint pc+ WHERE pc.conrelid = c.oid AND pc.contype = 'p'+ ) THEN 'YES' ELSE 'NO' END AS has_pk,+ c.reltuples::bigint AS estimated_row,+ pg_size_pretty(pg_total_relation_size(c.oid)) AS total_size,+ pg_size_pretty(pg_relation_size(c.oid)) AS data_size,+ pg_size_pretty(pg_indexes_size(c.oid)) AS index_size,+ pg_size_pretty(COALESCE(pg_total_relation_size(c.oid) - pg_relation_size(c.oid) - pg_indexes_size(c.oid), 0)) AS toast_size,+ COALESCE(to_char(s.last_vacuum, 'YYYY-MM-DD HH24:MI'), 'Never') AS last_vacuum,+ COALESCE(to_char(s.last_analyze, 'YYYY-MM-DD HH24:MI'), 'Never') AS last_analyze,+ COALESCE(s.n_live_tup, 0) AS live_tuples,+ COALESCE(s.n_dead_tup, 0) AS dead_tuples,+ COALESCE(s.n_mod_since_analyze, 0) AS modifications,+ COALESCE(obj_description(c.oid, 'pg_class'), 'EMPTY') AS comment+ FROM pg_class c+ JOIN pg_namespace n ON n.oid = c.relnamespace+ LEFT JOIN pg_stat_user_tables s ON s.relid = c.oid+ WHERE n.nspname = '\(schema)'+ AND c.relkind IN ('r', 'f')+ ORDER BY c.relname+ """+ }++ private func tableStatsQueryMySQL(schema: String?) -> String {+ let db = schema.map { "'\($0)'" } ?? "DATABASE()"+ return """+ SELECT+ TABLE_NAME AS name,+ TABLE_SCHEMA AS `schema`,+ TABLE_TYPE AS kind,+ ENGINE AS engine,+ TABLE_ROWS AS estimated_row,+ CONCAT(ROUND((DATA_LENGTH + INDEX_LENGTH) / 1024), ' KB') AS total_size,+ CONCAT(ROUND(DATA_LENGTH / 1024), ' KB') AS data_size,+ CONCAT(ROUND(INDEX_LENGTH / 1024), ' KB') AS index_size,+ TABLE_COLLATION AS collation,+ COALESCE(AUTO_INCREMENT, 0) AS auto_increment,+ COALESCE(CREATE_TIME, '') AS create_time,+ COALESCE(UPDATE_TIME, '') AS update_time,+ COALESCE(NULLIF(TABLE_COMMENT, ''), 'EMPTY') AS comment+ FROM information_schema.TABLES+ WHERE TABLE_SCHEMA = \(db)+ ORDER BY TABLE_NAME+ """+ }++ private func tableStatsQuerySQLite() -> String {+ """+ SELECT+ name,+ 'main' AS schema,+ type AS kind,+ '' AS owner,+ '' AS estimated_row+ FROM sqlite_master+ WHERE type = 'table' AND name NOT LIKE 'sqlite_%'+ ORDER BY name+ """+ }+}diff --git a/macos/Presentation/Views/TableStructure/TableStructureView.swift b/macos/Presentation/Views/TableStructure/TableStructureView.swiftnew file mode 100644index 0000000..759930e--- /dev/null+++ b/macos/Presentation/Views/TableStructure/TableStructureView.swift@@ -0,0 +1,175 @@+// TableStructureView.swift+// Gridex+//+// SwiftUI table structure inspector: Columns | Indexes | Foreign Keys | Constraints.++import SwiftUI++struct TableStructureView: View {+ let tableName: String+ let schema: String?++ @EnvironmentObject private var appState: AppState+ @State private var tableDescription: TableDescription?+ @State private var selectedTab = 0+ @State private var isLoading = false+ @State private var loadError: String?++ var body: some View {+ VStack(spacing: 0) {+ // Tab picker+ Picker("", selection: $selectedTab) {+ Text("Columns").tag(0)+ Text("Indexes").tag(1)+ Text("Foreign Keys").tag(2)+ Text("Constraints").tag(3)+ }+ .pickerStyle(.segmented)+ .padding(8)++ Divider()++ if isLoading {+ ProgressView("Loading structure...")+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ } else if let desc = tableDescription {+ switch selectedTab {+ case 0: columnsTab(desc)+ case 1: indexesTab(desc)+ case 2: foreignKeysTab(desc)+ case 3: constraintsTab(desc)+ default: EmptyView()+ }+ } else {+ VStack(spacing: 8) {+ Text("Failed to load table structure")+ .foregroundStyle(.secondary)+ if let err = loadError {+ Text(err).font(.system(size: 11)).foregroundStyle(.red).textSelection(.enabled)+ }+ Button("Retry") { Task { await loadStructure() } }+ .controlSize(.small)+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ }+ }+ .task {+ await loadStructure()+ }+ }++ private func loadStructure() async {+ guard let adapter = appState.activeAdapter else { return }+ isLoading = true+ defer { isLoading = false }++ do {+ tableDescription = try await adapter.describeTable(name: tableName, schema: schema)+ } catch {+ loadError = error.localizedDescription+ }+ }++ @ViewBuilder+ private func columnsTab(_ desc: TableDescription) -> some View {+ Table(desc.columns) {+ TableColumn("Name", value: \.name)+ TableColumn("Type", value: \.dataType)+ TableColumn("Nullable") { col in+ Image(systemName: col.isNullable ? "checkmark" : "xmark")+ .foregroundStyle(col.isNullable ? .green : .red)+ }+ .width(60)+ TableColumn("Default") { col in+ Text(col.defaultValue ?? "—")+ .foregroundStyle(.secondary)+ }+ TableColumn("PK") { col in+ if col.isPrimaryKey {+ Image(systemName: "key.fill")+ .foregroundStyle(.yellow)+ }+ }+ .width(40)+ }+ }++ @ViewBuilder+ private func indexesTab(_ desc: TableDescription) -> some View {+ if desc.indexes.isEmpty {+ Text("No indexes")+ .foregroundStyle(.secondary)+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ } else {+ Table(desc.indexes) {+ TableColumn("Name", value: \.name)+ TableColumn("Columns") { idx in+ Text(idx.columns.joined(separator: ", "))+ }+ TableColumn("Unique") { idx in+ Image(systemName: idx.isUnique ? "checkmark" : "xmark")+ .foregroundStyle(idx.isUnique ? .green : .secondary)+ }+ .width(60)+ }+ }+ }++ @ViewBuilder+ private func foreignKeysTab(_ desc: TableDescription) -> some View {+ if desc.foreignKeys.isEmpty {+ Text("No foreign keys")+ .foregroundStyle(.secondary)+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ } else {+ Table(desc.foreignKeys) {+ TableColumn("Column", value: \.column)+ TableColumn("References") { fk in+ Text("\(fk.referencedTable).\(fk.referencedColumn)")+ }+ TableColumn("On Delete") { fk in+ Text(fk.onDelete.rawValue)+ .foregroundStyle(.secondary)+ }+ TableColumn("On Update") { fk in+ Text(fk.onUpdate.rawValue)+ .foregroundStyle(.secondary)+ }+ }+ }+ }++ @ViewBuilder+ private func constraintsTab(_ desc: TableDescription) -> some View {+ // Combine primary keys and unique constraints+ let items = desc.primaryKeyColumns.map { col in+ ConstraintDisplayItem(name: "PRIMARY KEY", type: "Primary Key", columns: col.name)+ }+ if items.isEmpty {+ Text("No constraints")+ .foregroundStyle(.secondary)+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ } else {+ List(items) { item in+ HStack {+ Image(systemName: "key.fill")+ .foregroundStyle(.yellow)+ VStack(alignment: .leading) {+ Text(item.type)+ .font(.system(size: 13, weight: .medium))+ Text(item.columns)+ .font(.system(size: 12))+ .foregroundStyle(.secondary)+ }+ }+ }+ }+ }+}++private struct ConstraintDisplayItem: Identifiable {+ let id = UUID()+ let name: String+ let type: String+ let columns: String+}diff --git a/macos/Presentation/Windows/Settings/SettingsView.swift b/macos/Presentation/Windows/Settings/SettingsView.swiftnew file mode 100644index 0000000..228b565--- /dev/null+++ b/macos/Presentation/Windows/Settings/SettingsView.swift@@ -0,0 +1,308 @@+// SettingsView.swift+// Gridex+//+// Settings window using SwiftUI.++import SwiftUI++struct SettingsView: View {+ var body: some View {+ TabView {+ GeneralSettingsView()+ .tabItem {+ Label("General", systemImage: "gear")+ }++ AISettingsView()+ .tabItem {+ Label("AI", systemImage: "brain")+ }++ EditorSettingsView()+ .tabItem {+ Label("Editor", systemImage: "pencil")+ }+ }+ .frame(width: 580, height: 420)+ }+}++struct GeneralSettingsView: View {+ @AppStorage("general.pageSize") private var pageSize = 300+ @AppStorage("general.confirmBeforeDelete") private var confirmBeforeDelete = true+ @AppStorage("general.autoRefreshSidebar") private var autoRefreshSidebar = true+ @AppStorage("general.refreshInterval") private var refreshInterval = 300 // seconds+ @AppStorage("general.showQueryLog") private var showQueryLog = false++ var body: some View {+ Form {+ Section("Data Grid") {+ Picker("Default page size", selection: $pageSize) {+ Text("100").tag(100)+ Text("300").tag(300)+ Text("500").tag(500)+ Text("1000").tag(1000)+ }+ Toggle("Confirm before deleting rows", isOn: $confirmBeforeDelete)+ }++ Section("Sidebar") {+ Toggle("Auto-refresh schema", isOn: $autoRefreshSidebar)+ if autoRefreshSidebar {+ Picker("Refresh interval", selection: $refreshInterval) {+ Text("1 minute").tag(60)+ Text("5 minutes").tag(300)+ Text("15 minutes").tag(900)+ Text("Never").tag(0)+ }+ }+ }++ Section("Query") {+ Toggle("Show query log panel by default", isOn: $showQueryLog)+ }+ }+ .formStyle(.grouped)+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ }+}++struct AISettingsView: View {+ private let keychainService: KeychainServiceProtocol = DependencyContainer.shared.keychainService++ @AppStorage("ai.provider") private var providerType = "gemini"+ @AppStorage("ai.provider.baseURL") private var baseURL = "https://generativelanguage.googleapis.com/v1beta/openai"+ @AppStorage("ai.provider.enabled") private var isEnabled = true+ @AppStorage("ai.provider.model") private var selectedModel = "gemini-2.5-flash"++ @State private var apiKey = ""+ @State private var isValidating = false+ @State private var validationResult: ValidationResult?+ @State private var availableModels: [LLMModel] = []+ @State private var isLoadingModels = false++ private enum ValidationResult {+ case success, failure(String)+ }++ private let providerTypes = [+ ("gemini", "Google Gemini"),+ ("anthropic", "Anthropic"),+ ("openai", "OpenAI"),+ ("ollama", "Ollama"),+ ]++ var body: some View {+ Form {+ Picker("Provider", selection: $providerType) {+ ForEach(providerTypes, id: \.0) { value, label in+ Text(label).tag(value)+ }+ }+ .onChange(of: providerType) { _, newValue in+ applyProviderDefaults(newValue)+ }++ if providerType != "ollama" {+ TextField("API Base URL", text: $baseURL)+ SecureField("API Key", text: $apiKey)+ }++ HStack {+ Picker("Model", selection: $selectedModel) {+ if availableModels.isEmpty {+ ForEach(fallbackModels, id: \.self) { model in+ Text(model).tag(model)+ }+ } else {+ ForEach(availableModels) { model in+ Text(model.name).tag(model.id)+ }+ }+ }+ Button(action: fetchModels) {+ if isLoadingModels {+ ProgressView()+ .controlSize(.small)+ } else {+ Image(systemName: "arrow.clockwise")+ }+ }+ .buttonStyle(.plain)+ .disabled(isLoadingModels || (providerType != "ollama" && apiKey.isEmpty))+ .help("Fetch models from API")+ }++ Toggle("Enabled", isOn: $isEnabled)++ HStack {+ Button(action: validateConnection) {+ HStack(spacing: 6) {+ if isValidating {+ ProgressView()+ .controlSize(.small)+ }+ Text("Validate")+ }+ }+ .disabled(isValidating || (providerType != "ollama" && apiKey.isEmpty))++ if let result = validationResult {+ switch result {+ case .success:+ Label("Connected", systemImage: "checkmark.circle.fill")+ .foregroundStyle(.green)+ .font(.system(size: 12))+ case .failure(let msg):+ Label(msg, systemImage: "xmark.circle.fill")+ .foregroundStyle(.red)+ .font(.system(size: 12))+ .lineLimit(1)+ }+ }+ }+ }+ .formStyle(.grouped)+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ .onAppear {+ loadAPIKey()+ fetchModels()+ }+ .onChange(of: apiKey) { _, newValue in saveAPIKey(newValue) }+ }++ private var fallbackModels: [String] {+ switch providerType {+ case "gemini": return ["gemini-2.5-flash", "gemini-2.5-pro", "gemini-2.0-flash"]+ case "anthropic": return ["claude-sonnet-4-6", "claude-haiku-4-5-20251001", "claude-opus-4-6"]+ case "openai": return ["gpt-4o", "gpt-4o-mini"]+ case "ollama": return ["llama3", "codellama", "mistral"]+ default: return []+ }+ }++ private func fetchModels() {+ isLoadingModels = true+ Task {+ let service = DependencyContainer.shared.makeLLMService(+ provider: providerType,+ apiKey: apiKey,+ baseURL: baseURL+ )+ do {+ let models = try await service.availableModels()+ await MainActor.run {+ availableModels = models+ if !models.isEmpty && !models.contains(where: { $0.id == selectedModel }) {+ selectedModel = models[0].id+ }+ isLoadingModels = false+ }+ } catch {+ await MainActor.run {+ availableModels = []+ isLoadingModels = false+ }+ }+ }+ }++ private func applyProviderDefaults(_ provider: String) {+ switch provider {+ case "gemini":+ baseURL = "https://generativelanguage.googleapis.com/v1beta/openai"+ selectedModel = "gemini-2.5-flash"+ case "anthropic":+ baseURL = "https://api.anthropic.com/v1"+ selectedModel = "claude-sonnet-4-6"+ case "openai":+ baseURL = "https://api.openai.com/v1"+ selectedModel = "gpt-4o"+ case "ollama":+ baseURL = "http://localhost:11434"+ selectedModel = "llama3"+ default: break+ }+ loadAPIKey()+ availableModels = []+ fetchModels()+ }++ private func loadAPIKey() {+ apiKey = (try? keychainService.load(key: "ai.apikey.\(providerType)")) ?? ""+ }++ private func saveAPIKey(_ key: String) {+ if key.isEmpty {+ try? keychainService.delete(key: "ai.apikey.\(providerType)")+ } else {+ try? keychainService.save(key: "ai.apikey.\(providerType)", value: key)+ }+ }++ private func validateConnection() {+ isValidating = true+ validationResult = nil+ Task {+ do {+ let service = DependencyContainer.shared.makeLLMService(+ provider: providerType,+ apiKey: apiKey,+ baseURL: baseURL+ )+ let valid = try await service.validateAPIKey()+ await MainActor.run {+ validationResult = valid ? .success : .failure("Invalid API key")+ isValidating = false+ }+ } catch {+ await MainActor.run {+ validationResult = .failure(error.localizedDescription)+ isValidating = false+ }+ }+ }+ }+}++struct EditorSettingsView: View {+ @AppStorage("editor.fontSize") private var fontSize = 12.0+ @AppStorage("editor.tabSize") private var tabSize = 4+ @AppStorage("editor.useSpaces") private var useSpaces = true+ @AppStorage("editor.wordWrap") private var wordWrap = false+ @AppStorage("editor.showLineNumbers") private var showLineNumbers = true+ @AppStorage("editor.highlightCurrentLine") private var highlightCurrentLine = true++ var body: some View {+ Form {+ Section("Font") {+ HStack {+ Text("Font size")+ Spacer()+ TextField("", value: $fontSize, format: .number)+ .frame(width: 50)+ .textFieldStyle(.roundedBorder)+ Stepper("", value: $fontSize, in: 8...24, step: 1)+ .labelsHidden()+ }+ }++ Section("Indentation") {+ Picker("Tab size", selection: $tabSize) {+ Text("2 spaces").tag(2)+ Text("4 spaces").tag(4)+ Text("8 spaces").tag(8)+ }+ Toggle("Use spaces instead of tabs", isOn: $useSpaces)+ }++ Section("Display") {+ Toggle("Word wrap", isOn: $wordWrap)+ Toggle("Show line numbers", isOn: $showLineNumbers)+ Toggle("Highlight current line", isOn: $highlightCurrentLine)+ }+ }+ .formStyle(.grouped)+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ }+}diff --git a/macos/Resources/AppIcon.icns b/macos/Resources/AppIcon.icnsnew file mode 100644index 0000000..cc10088Binary files /dev/null and b/macos/Resources/AppIcon.icns differdiff --git a/macos/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json b/macos/Resources/Assets.xcassets/AppIcon.appiconset/Contents.jsonnew file mode 100644index 0000000..5031363--- /dev/null+++ b/macos/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json@@ -0,0 +1,44 @@+{+ "images" : [+ {+ "filename" : "icon_128.png",+ "idiom" : "mac",+ "scale" : "1x",+ "size" : "128x128"+ },+ {+ "filename" : "icon_256.png",+ "idiom" : "mac",+ "scale" : "2x",+ "size" : "128x128"+ },+ {+ "filename" : "icon_256.png",+ "idiom" : "mac",+ "scale" : "1x",+ "size" : "256x256"+ },+ {+ "filename" : "icon_512.png",+ "idiom" : "mac",+ "scale" : "2x",+ "size" : "256x256"+ },+ {+ "filename" : "icon_512.png",+ "idiom" : "mac",+ "scale" : "1x",+ "size" : "512x512"+ },+ {+ "filename" : "icon_1024.png",+ "idiom" : "mac",+ "scale" : "2x",+ "size" : "512x512"+ }+ ],+ "info" : {+ "author" : "xcode",+ "version" : 1+ }+}diff --git a/macos/Resources/Assets.xcassets/AppIcon.appiconset/icon_1024.png b/macos/Resources/Assets.xcassets/AppIcon.appiconset/icon_1024.pngnew file mode 100644index 0000000..714aae8Binary files /dev/null and b/macos/Resources/Assets.xcassets/AppIcon.appiconset/icon_1024.png differdiff --git a/macos/Resources/Assets.xcassets/AppIcon.appiconset/icon_128.png b/macos/Resources/Assets.xcassets/AppIcon.appiconset/icon_128.pngnew file mode 100644index 0000000..839b284Binary files /dev/null and b/macos/Resources/Assets.xcassets/AppIcon.appiconset/icon_128.png differdiff --git a/macos/Resources/Assets.xcassets/AppIcon.appiconset/icon_256.png b/macos/Resources/Assets.xcassets/AppIcon.appiconset/icon_256.pngnew file mode 100644index 0000000..d0daf4dBinary files /dev/null and b/macos/Resources/Assets.xcassets/AppIcon.appiconset/icon_256.png differdiff --git a/macos/Resources/Assets.xcassets/AppIcon.appiconset/icon_512.png b/macos/Resources/Assets.xcassets/AppIcon.appiconset/icon_512.pngnew file mode 100644index 0000000..3a5e3fcBinary files /dev/null and b/macos/Resources/Assets.xcassets/AppIcon.appiconset/icon_512.png differdiff --git a/macos/Resources/Assets.xcassets/AppLogo.imageset/Contents.json b/macos/Resources/Assets.xcassets/AppLogo.imageset/Contents.jsonnew file mode 100644index 0000000..5f670ca--- /dev/null+++ b/macos/Resources/Assets.xcassets/AppLogo.imageset/Contents.json@@ -0,0 +1,21 @@+{+ "images" : [+ {+ "filename" : "logo.png",+ "idiom" : "universal",+ "scale" : "1x"+ },+ {+ "idiom" : "universal",+ "scale" : "2x"+ },+ {+ "idiom" : "universal",+ "scale" : "3x"+ }+ ],+ "info" : {+ "author" : "xcode",+ "version" : 1+ }+}diff --git a/macos/Resources/Assets.xcassets/AppLogo.imageset/logo.png b/macos/Resources/Assets.xcassets/AppLogo.imageset/logo.pngnew file mode 100644index 0000000..cc8608eBinary files /dev/null and b/macos/Resources/Assets.xcassets/AppLogo.imageset/logo.png differdiff --git a/macos/Resources/Assets.xcassets/Contents.json b/macos/Resources/Assets.xcassets/Contents.jsonnew file mode 100644index 0000000..73c0059--- /dev/null+++ b/macos/Resources/Assets.xcassets/Contents.json@@ -0,0 +1,6 @@+{+ "info" : {+ "author" : "xcode",+ "version" : 1+ }+}diff --git a/macos/Resources/Gridex.entitlements b/macos/Resources/Gridex.entitlementsnew file mode 100644index 0000000..80bb647--- /dev/null+++ b/macos/Resources/Gridex.entitlements@@ -0,0 +1,18 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>com.apple.security.app-sandbox</key>+ <false/>+ <key>com.apple.security.network.client</key>+ <true/>+ <key>com.apple.security.network.server</key>+ <true/>+ <key>com.apple.security.files.user-selected.read-write</key>+ <true/>+ <key>keychain-access-groups</key>+ <array>+ <string>$(AppIdentifierPrefix)com.gridex.app</string>+ </array>+</dict>+</plist>diff --git a/macos/Resources/Info.plist b/macos/Resources/Info.plistnew file mode 100644index 0000000..bdbade6--- /dev/null+++ b/macos/Resources/Info.plist@@ -0,0 +1,54 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>CFBundleDevelopmentRegion</key>+ <string>en</string>+ <key>CFBundleDocumentTypes</key>+ <array>+ <dict>+ <key>CFBundleTypeExtensions</key>+ <array>+ <string>db</string>+ <string>sqlite</string>+ <string>sqlite3</string>+ </array>+ <key>CFBundleTypeName</key>+ <string>SQLite Database</string>+ <key>CFBundleTypeRole</key>+ <string>Viewer</string>+ </dict>+ </array>+ <key>CFBundleExecutable</key>+ <string>Gridex</string>+ <key>CFBundleIconFile</key>+ <string>AppIcon</string>+ <key>CFBundleIdentifier</key>+ <string>com.gridex.app</string>+ <key>CFBundleInfoDictionaryVersion</key>+ <string>6.0</string>+ <key>CFBundleName</key>+ <string>Gridex</string>+ <key>CFBundlePackageType</key>+ <string>APPL</string>+ <key>CFBundleShortVersionString</key>+ <string>0.22.1</string>+ <key>CFBundleVersion</key>+ <string>2</string>+ <key>LSMinimumSystemVersion</key>+ <string>14.0</string>+ <key>NSAppTransportSecurity</key>+ <dict>+ <key>NSAllowsArbitraryLoads</key>+ <false/>+ <key>NSAllowsLocalNetworking</key>+ <true/>+ </dict>+ <key>NSHumanReadableCopyright</key>+ <string>Copyright © 2026 Gridex. All rights reserved.</string>+ <key>NSMainNibFile</key>+ <string></string>+ <key>NSPrincipalClass</key>+ <string>NSApplication</string>+</dict>+</plist>diff --git a/macos/Services/AI/Context/AIContextEngine.swift b/macos/Services/AI/Context/AIContextEngine.swiftnew file mode 100644index 0000000..f6d4032--- /dev/null+++ b/macos/Services/AI/Context/AIContextEngine.swift@@ -0,0 +1,97 @@+// AIContextEngine.swift+// Gridex+//+// Builds optimized context from database schema for LLM queries.+// Handles token budgeting and smart table selection.++import Foundation++final class AIContextEngine: AIContextProvider, @unchecked Sendable {+ private let schemaCache: SchemaCache++ init(schemaCache: SchemaCache) {+ self.schemaCache = schemaCache+ }++ func buildContext(+ for question: String,+ schema: SchemaSnapshot,+ tokenBudget: Int+ ) async throws -> AIContext {+ let relevantTables = selectRelevantTables(question: question, schema: schema)+ let ddl = relevantTables.map { $0.toDDL(dialect: schema.databaseType.sqlDialect) }.joined(separator: "\n\n")+ let estimatedTokens = estimateTokenCount(ddl)++ return AIContext(+ relevantTables: relevantTables,+ schemaSQL: ddl,+ sampleData: [:],+ statistics: [:],+ tokenCount: estimatedTokens+ )+ }++ func buildSystemPrompt(+ databaseType: DatabaseType,+ connectionInfo: String,+ context: AIContext+ ) -> String {+ """+ You are a database expert assistant. You have access to the following schema:++ \(context.schemaSQL)++ Current connection: \(connectionInfo)+ Database type: \(databaseType.displayName)++ Rules:+ - Generate SQL that is valid for \(databaseType.displayName)+ - Always use parameterized queries for user input+ - Explain your reasoning+ - When suggesting changes, show the SQL and explain risks+ - If asked to execute, wait for user confirmation+ - Format SQL blocks with ```sql markers+ """+ }++ private func selectRelevantTables(question: String, schema: SchemaSnapshot) -> [TableDescription] {+ let keywords = question.lowercased().split(separator: " ").map(String.init)+ let allTables = schema.allTables++ // Score tables by keyword relevance+ let scored = allTables.map { table -> (TableDescription, Int) in+ var score = 0+ let tableName = table.name.lowercased()++ for keyword in keywords {+ if tableName.contains(keyword) { score += 10 }+ for column in table.columns {+ if column.name.lowercased().contains(keyword) { score += 5 }+ }+ }++ // Include tables related via foreign keys+ for fk in table.foreignKeys {+ if keywords.contains(where: { fk.referencedTable.lowercased().contains($0) }) {+ score += 3+ }+ }++ return (table, score)+ }++ let relevant = scored.filter { $0.1 > 0 }.sorted { $0.1 > $1.1 }.map(\.0)++ // If no keyword match, return all tables (up to limit)+ if relevant.isEmpty {+ return Array(allTables.prefix(20))+ }++ return Array(relevant.prefix(15))+ }++ private func estimateTokenCount(_ text: String) -> Int {+ // Rough estimation: ~4 characters per token+ text.count / 4+ }+}diff --git a/macos/Services/AI/Providers/AnthropicProvider.swift b/macos/Services/AI/Providers/AnthropicProvider.swiftnew file mode 100644index 0000000..a300668--- /dev/null+++ b/macos/Services/AI/Providers/AnthropicProvider.swift@@ -0,0 +1,79 @@+// AnthropicProvider.swift+// Gridex+//+// Anthropic Claude API integration with streaming support.++import Foundation++final class AnthropicProvider: LLMService, @unchecked Sendable {+ let providerName = "Anthropic"+ private let apiKey: String++ init(apiKey: String) {+ self.apiKey = apiKey+ }++ func stream(+ messages: [LLMMessage],+ systemPrompt: String,+ model: String,+ maxTokens: Int,+ temperature: Double+ ) -> AsyncThrowingStream<String, Error> {+ AsyncThrowingStream { continuation in+ Task {+ do {+ var request = URLRequest(url: URL(string: "https://api.anthropic.com/v1/messages")!)+ request.httpMethod = "POST"+ request.setValue("application/json", forHTTPHeaderField: "content-type")+ request.setValue(apiKey, forHTTPHeaderField: "x-api-key")+ request.setValue("2023-06-01", forHTTPHeaderField: "anthropic-version")++ let body: [String: Any] = [+ "model": model,+ "max_tokens": maxTokens,+ "temperature": temperature,+ "stream": true,+ "system": systemPrompt,+ "messages": messages.map { ["role": $0.role.rawValue, "content": $0.content] }+ ]+ request.httpBody = try JSONSerialization.data(withJSONObject: body)++ let (stream, response) = try await URLSession.shared.bytes(for: request)++ guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {+ continuation.finish(throwing: GridexError.aiProviderError("HTTP error"))+ return+ }++ for try await line in stream.lines {+ guard line.hasPrefix("data: ") else { continue }+ let data = String(line.dropFirst(6))+ guard data != "[DONE]" else { break }++ if let json = try? JSONSerialization.jsonObject(with: Data(data.utf8)) as? [String: Any],+ let delta = (json["delta"] as? [String: Any])?["text"] as? String {+ continuation.yield(delta)+ }+ }+ continuation.finish()+ } catch {+ continuation.finish(throwing: error)+ }+ }+ }+ }++ func availableModels() async throws -> [LLMModel] {+ [+ LLMModel(id: "claude-sonnet-4-6", name: "Claude Sonnet 4.6", provider: providerName, contextWindow: 200000, supportsStreaming: true),+ LLMModel(id: "claude-haiku-4-5-20251001", name: "Claude Haiku 4.5", provider: providerName, contextWindow: 200000, supportsStreaming: true),+ LLMModel(id: "claude-opus-4-6", name: "Claude Opus 4.6", provider: providerName, contextWindow: 200000, supportsStreaming: true),+ ]+ }++ func validateAPIKey() async throws -> Bool {+ // TODO: Make a minimal API call to validate+ return !apiKey.isEmpty+ }+}diff --git a/macos/Services/AI/Providers/GeminiProvider.swift b/macos/Services/AI/Providers/GeminiProvider.swiftnew file mode 100644index 0000000..5ef8770--- /dev/null+++ b/macos/Services/AI/Providers/GeminiProvider.swift@@ -0,0 +1,112 @@+// GeminiProvider.swift+// Gridex+//+// Google Gemini API integration via OpenAI-compatible endpoint.++import Foundation++final class GeminiProvider: LLMService, @unchecked Sendable {+ let providerName = "Gemini"+ private let apiKey: String+ private let baseURL: String++ init(apiKey: String, baseURL: String = "https://generativelanguage.googleapis.com/v1beta/openai") {+ self.apiKey = apiKey+ self.baseURL = baseURL.hasSuffix("/") ? String(baseURL.dropLast()) : baseURL+ }++ func stream(+ messages: [LLMMessage],+ systemPrompt: String,+ model: String,+ maxTokens: Int,+ temperature: Double+ ) -> AsyncThrowingStream<String, Error> {+ AsyncThrowingStream { continuation in+ Task {+ do {+ var request = URLRequest(url: URL(string: "\(baseURL)/chat/completions")!)+ request.httpMethod = "POST"+ request.setValue("application/json", forHTTPHeaderField: "content-type")+ request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "authorization")++ var msgs: [[String: Any]] = [+ ["role": "system", "content": systemPrompt]+ ]+ msgs += messages.map { ["role": $0.role.rawValue, "content": $0.content] }++ let body: [String: Any] = [+ "model": model,+ "max_tokens": maxTokens,+ "temperature": temperature,+ "stream": true,+ "messages": msgs+ ]+ request.httpBody = try JSONSerialization.data(withJSONObject: body)++ let (stream, response) = try await URLSession.shared.bytes(for: request)++ guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {+ let statusCode = (response as? HTTPURLResponse)?.statusCode ?? 0+ continuation.finish(throwing: GridexError.aiProviderError("Gemini HTTP \(statusCode)"))+ return+ }++ for try await line in stream.lines {+ guard line.hasPrefix("data: ") else { continue }+ let data = String(line.dropFirst(6))+ guard data != "[DONE]" else { break }++ if let json = try? JSONSerialization.jsonObject(with: Data(data.utf8)) as? [String: Any],+ let choices = json["choices"] as? [[String: Any]],+ let delta = choices.first?["delta"] as? [String: Any],+ let content = delta["content"] as? String {+ continuation.yield(content)+ }+ }+ continuation.finish()+ } catch {+ continuation.finish(throwing: error)+ }+ }+ }+ }++ func availableModels() async throws -> [LLMModel] {+ var request = URLRequest(url: URL(string: "\(baseURL)/models")!)+ request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "authorization")+ let (data, response) = try await URLSession.shared.data(for: request)++ guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {+ // Fallback to known models+ return defaultModels+ }++ guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ let modelsArray = json["data"] as? [[String: Any]] else {+ return defaultModels+ }++ let models = modelsArray.compactMap { model -> LLMModel? in+ guard let id = model["id"] as? String else { return nil }+ return LLMModel(id: id, name: id, provider: providerName, contextWindow: 1000000, supportsStreaming: true)+ }++ return models.isEmpty ? defaultModels : models+ }++ private var defaultModels: [LLMModel] {+ [+ LLMModel(id: "gemini-2.5-flash", name: "Gemini 2.5 Flash", provider: providerName, contextWindow: 1000000, supportsStreaming: true),+ LLMModel(id: "gemini-2.5-pro", name: "Gemini 2.5 Pro", provider: providerName, contextWindow: 1000000, supportsStreaming: true),+ LLMModel(id: "gemini-2.0-flash", name: "Gemini 2.0 Flash", provider: providerName, contextWindow: 1000000, supportsStreaming: true),+ ]+ }++ func validateAPIKey() async throws -> Bool {+ var request = URLRequest(url: URL(string: "\(baseURL)/models")!)+ request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "authorization")+ let (_, response) = try await URLSession.shared.data(for: request)+ return (response as? HTTPURLResponse)?.statusCode == 200+ }+}diff --git a/macos/Services/AI/Providers/OllamaProvider.swift b/macos/Services/AI/Providers/OllamaProvider.swiftnew file mode 100644index 0000000..2c7b3c5--- /dev/null+++ b/macos/Services/AI/Providers/OllamaProvider.swift@@ -0,0 +1,47 @@+// OllamaProvider.swift+// Gridex+//+// Local Ollama LLM integration.++import Foundation++final class OllamaProvider: LLMService, @unchecked Sendable {+ let providerName = "Ollama"+ private let baseURL: URL++ init(baseURL: URL = URL(string: "http://localhost:11434")!) {+ self.baseURL = baseURL+ }++ func stream(+ messages: [LLMMessage],+ systemPrompt: String,+ model: String,+ maxTokens: Int,+ temperature: Double+ ) -> AsyncThrowingStream<String, Error> {+ AsyncThrowingStream { continuation in+ Task {+ // TODO: Implement Ollama streaming API+ continuation.finish(throwing: GridexError.unsupportedOperation("Ollama provider not yet implemented"))+ }+ }+ }++ func availableModels() async throws -> [LLMModel] {+ // TODO: GET /api/tags to list installed models+ return []+ }++ func validateAPIKey() async throws -> Bool {+ // Ollama doesn't need an API key, just check if server is running+ var request = URLRequest(url: baseURL.appendingPathComponent("/api/tags"))+ request.timeoutInterval = 5+ do {+ let (_, response) = try await URLSession.shared.data(for: request)+ return (response as? HTTPURLResponse)?.statusCode == 200+ } catch {+ return false+ }+ }+}diff --git a/macos/Services/AI/Providers/OpenAIProvider.swift b/macos/Services/AI/Providers/OpenAIProvider.swiftnew file mode 100644index 0000000..976c191--- /dev/null+++ b/macos/Services/AI/Providers/OpenAIProvider.swift@@ -0,0 +1,41 @@+// OpenAIProvider.swift+// Gridex+//+// OpenAI GPT API integration with streaming support.++import Foundation++final class OpenAIProvider: LLMService, @unchecked Sendable {+ let providerName = "OpenAI"+ private let apiKey: String++ init(apiKey: String) {+ self.apiKey = apiKey+ }++ func stream(+ messages: [LLMMessage],+ systemPrompt: String,+ model: String,+ maxTokens: Int,+ temperature: Double+ ) -> AsyncThrowingStream<String, Error> {+ AsyncThrowingStream { continuation in+ Task {+ // TODO: Implement OpenAI streaming API+ continuation.finish(throwing: GridexError.unsupportedOperation("OpenAI provider not yet implemented"))+ }+ }+ }++ func availableModels() async throws -> [LLMModel] {+ [+ LLMModel(id: "gpt-4o", name: "GPT-4o", provider: providerName, contextWindow: 128000, supportsStreaming: true),+ LLMModel(id: "gpt-4o-mini", name: "GPT-4o Mini", provider: providerName, contextWindow: 128000, supportsStreaming: true),+ ]+ }++ func validateAPIKey() async throws -> Bool {+ return !apiKey.isEmpty+ }+}diff --git a/macos/Services/Export/BackupService.swift b/macos/Services/Export/BackupService.swiftnew file mode 100644index 0000000..bdb122a--- /dev/null+++ b/macos/Services/Export/BackupService.swift@@ -0,0 +1,828 @@+// BackupService.swift+// Gridex+//+// Executes database backup and restore via CLI tools:+// PostgreSQL: pg_dump / pg_restore+// MySQL: mysqldump / mysql+// SQLite: file copy++import Foundation+import MongoKitten++enum BackupFormat: String, CaseIterable, Sendable {+ case custom = "custom" // pg_dump -Fc (PostgreSQL only, supports pg_restore)+ case sql = "sql" // plain SQL dump+ case tar = "tar" // pg_dump -Ft+ case directory = "directory" // pg_dump -Fd+ case bak = "bak" // SQL Server native BACKUP DATABASE+ case ndjson = "ndjson" // MongoDB: NDJSON (one document per line)+ case redisJSON = "redisJSON" // Redis: JSON snapshot via SCAN++ var displayName: String {+ switch self {+ case .custom: return "Custom (compressed)"+ case .sql: return "Plain SQL"+ case .tar: return "Tar archive"+ case .directory: return "Directory"+ case .bak: return "SQL Server Backup (.bak)"+ case .ndjson: return "NDJSON (one doc per line)"+ case .redisJSON: return "JSON snapshot"+ }+ }++ var fileExtension: String {+ switch self {+ case .custom: return "dump"+ case .sql: return "sql"+ case .tar: return "tar"+ case .directory: return ""+ case .bak: return "bak"+ case .ndjson: return "ndjson"+ case .redisJSON: return "json"+ }+ }++ static func available(for dbType: DatabaseType) -> [BackupFormat] {+ switch dbType {+ case .postgresql: return [.custom, .sql, .tar]+ case .mysql: return [.sql]+ case .sqlite: return [.sql]+ case .mssql: return [.bak]+ case .mongodb: return [.ndjson]+ case .redis: return [.redisJSON]+ }+ }+}++struct BackupOptions: Sendable {+ var format: BackupFormat = .custom+ var compress: Bool = true+ var dataOnly: Bool = false+ var schemaOnly: Bool = false+ var tables: [String] = [] // empty = all tables+ var excludeTables: [String] = []+}++struct BackupResult: Sendable {+ let success: Bool+ let outputPath: String?+ let errorMessage: String?+ let duration: TimeInterval+ let fileSize: Int64?+}++actor BackupService {++ // MARK: - Backup++ func backup(+ config: ConnectionConfig,+ password: String,+ database: String,+ to outputURL: URL,+ options: BackupOptions,+ adapter: (any DatabaseAdapter)? = nil,+ onProgress: (@Sendable (Int64, TimeInterval) -> Void)? = nil+ ) async -> BackupResult {+ let start = CFAbsoluteTimeGetCurrent()++ switch config.databaseType {+ case .postgresql:+ return await pgDump(config: config, password: password, database: database, to: outputURL, options: options, start: start, onProgress: onProgress)+ case .mysql:+ return await mysqlDump(config: config, password: password, database: database, to: outputURL, options: options, start: start, onProgress: onProgress)+ case .sqlite:+ return sqliteCopy(config: config, to: outputURL, start: start)+ case .redis:+ guard let redis = adapter as? RedisAdapter else {+ return BackupResult(success: false, outputPath: nil, errorMessage: "Redis adapter required for backup", duration: 0, fileSize: nil)+ }+ return await redisJSONBackup(adapter: redis, to: outputURL, start: start, onProgress: onProgress)+ case .mongodb:+ guard let mongo = adapter as? MongoDBAdapter else {+ return BackupResult(success: false, outputPath: nil, errorMessage: "MongoDB adapter required for backup", duration: 0, fileSize: nil)+ }+ return await mongoNDJSONBackup(adapter: mongo, to: outputURL, start: start, onProgress: onProgress)+ case .mssql:+ guard let mssql = adapter as? MSSQLAdapter else {+ return BackupResult(success: false, outputPath: nil, errorMessage: "SQL Server adapter required for backup", duration: 0, fileSize: nil)+ }+ return await mssqlBackup(adapter: mssql, database: database, to: outputURL, start: start)+ }+ }++ // MARK: - Restore++ func restore(+ config: ConnectionConfig,+ password: String,+ database: String,+ from inputURL: URL,+ format: BackupFormat,+ adapter: (any DatabaseAdapter)? = nil,+ onProgress: (@Sendable (Double) -> Void)? = nil+ ) async -> BackupResult {+ let start = CFAbsoluteTimeGetCurrent()++ switch config.databaseType {+ case .postgresql:+ return await pgRestore(config: config, password: password, database: database, from: inputURL, format: format, start: start, onProgress: onProgress)+ case .mysql:+ return await mysqlRestore(config: config, password: password, database: database, from: inputURL, start: start, onProgress: onProgress)+ case .sqlite:+ return sqliteRestore(config: config, from: inputURL, start: start)+ case .redis:+ guard let redis = adapter as? RedisAdapter else {+ return BackupResult(success: false, outputPath: nil, errorMessage: "Redis adapter required for restore", duration: 0, fileSize: nil)+ }+ return await redisJSONRestore(adapter: redis, from: inputURL, start: start, onProgress: onProgress)+ case .mongodb:+ guard let mongo = adapter as? MongoDBAdapter else {+ return BackupResult(success: false, outputPath: nil, errorMessage: "MongoDB adapter required for restore", duration: 0, fileSize: nil)+ }+ return await mongoNDJSONRestore(adapter: mongo, from: inputURL, start: start, onProgress: onProgress)+ case .mssql:+ guard let mssql = adapter as? MSSQLAdapter else {+ return BackupResult(success: false, outputPath: nil, errorMessage: "SQL Server adapter required for restore", duration: 0, fileSize: nil)+ }+ return await mssqlRestore(adapter: mssql, database: database, from: inputURL, start: start)+ }+ }++ // MARK: - PostgreSQL++ private func pgDump(+ config: ConnectionConfig,+ password: String,+ database: String,+ to outputURL: URL,+ options: BackupOptions,+ start: CFAbsoluteTime,+ onProgress: (@Sendable (Int64, TimeInterval) -> Void)?+ ) async -> BackupResult {+ guard let pgDumpPath = findTool("pg_dump") else {+ return BackupResult(success: false, outputPath: nil,+ errorMessage: "pg_dump not found. Install PostgreSQL client tools:\n brew install libpq", duration: 0, fileSize: nil)+ }++ var args: [String] = []+ args += ["-h", config.host ?? "localhost"]+ args += ["-p", "\(config.port ?? 5432)"]+ args += ["-U", config.username ?? "postgres"]+ args += ["-d", database]+ args += ["-f", outputURL.path]++ switch options.format {+ case .custom: args += ["-Fc"]+ case .sql: args += ["-Fp"]+ case .tar: args += ["-Ft"]+ case .directory: args += ["-Fd"]+ case .bak, .ndjson, .redisJSON: break // non-PostgreSQL formats; handled elsewhere+ }++ if options.compress && options.format == .custom { args += ["-Z", "6"] }+ if options.dataOnly { args.append("--data-only") }+ if options.schemaOnly { args.append("--schema-only") }+ for t in options.tables { args += ["-t", t] }+ for t in options.excludeTables { args += ["-T", t] }++ var env = ProcessInfo.processInfo.environment+ env["PGPASSWORD"] = password++ return await runProcessWithOutputProgress(path: pgDumpPath, args: args, env: env, start: start, outputURL: outputURL, onProgress: onProgress)+ }++ private func pgRestore(+ config: ConnectionConfig,+ password: String,+ database: String,+ from inputURL: URL,+ format: BackupFormat,+ start: CFAbsoluteTime,+ onProgress: (@Sendable (Double) -> Void)?+ ) async -> BackupResult {+ var env = ProcessInfo.processInfo.environment+ env["PGPASSWORD"] = password++ if format == .sql {+ // Plain SQL: pipe through stdin for progress tracking+ guard let psqlPath = findTool("psql") else {+ return BackupResult(success: false, outputPath: nil,+ errorMessage: "psql not found. Install PostgreSQL client tools:\n brew install libpq", duration: 0, fileSize: nil)+ }+ var args: [String] = []+ args += ["-h", config.host ?? "localhost"]+ args += ["-p", "\(config.port ?? 5432)"]+ args += ["-U", config.username ?? "postgres"]+ args += ["-d", database]+ return await runProcessWithStdinProgress(path: psqlPath, args: args, env: env, inputFile: inputURL, start: start, onProgress: onProgress)+ } else {+ // Custom/Tar: use pg_restore+ guard let pgRestorePath = findTool("pg_restore") else {+ return BackupResult(success: false, outputPath: nil,+ errorMessage: "pg_restore not found. Install PostgreSQL client tools:\n brew install libpq", duration: 0, fileSize: nil)+ }+ var args: [String] = []+ args += ["-h", config.host ?? "localhost"]+ args += ["-p", "\(config.port ?? 5432)"]+ args += ["-U", config.username ?? "postgres"]+ args += ["-d", database]+ args.append(inputURL.path)+ return await runProcess(path: pgRestorePath, args: args, env: env, start: start, outputURL: nil)+ }+ }++ // MARK: - MySQL++ private func mysqlDump(+ config: ConnectionConfig,+ password: String,+ database: String,+ to outputURL: URL,+ options: BackupOptions,+ start: CFAbsoluteTime,+ onProgress: (@Sendable (Int64, TimeInterval) -> Void)?+ ) async -> BackupResult {+ guard let mysqldumpPath = findTool("mysqldump") else {+ return BackupResult(success: false, outputPath: nil,+ errorMessage: "mysqldump not found. Install MySQL client tools:\n brew install mysql-client", duration: 0, fileSize: nil)+ }++ var args: [String] = []+ args += ["-h", config.host ?? "localhost"]+ args += ["-P", "\(config.port ?? 3306)"]+ args += ["-u", config.username ?? "root"]+ args += ["--password=\(password)"]+ args += ["--result-file=\(outputURL.path)"]+ if options.dataOnly { args.append("--no-create-info") }+ if options.schemaOnly { args.append("--no-data") }+ args.append(database)+ if !options.tables.isEmpty { args += options.tables }++ return await runProcessWithOutputProgress(path: mysqldumpPath, args: args, env: nil, start: start, outputURL: outputURL, onProgress: onProgress)+ }++ private func mysqlRestore(+ config: ConnectionConfig,+ password: String,+ database: String,+ from inputURL: URL,+ start: CFAbsoluteTime,+ onProgress: (@Sendable (Double) -> Void)?+ ) async -> BackupResult {+ guard let mysqlPath = findTool("mysql") else {+ return BackupResult(success: false, outputPath: nil,+ errorMessage: "mysql not found. Install MySQL client tools:\n brew install mysql-client", duration: 0, fileSize: nil)+ }++ var args: [String] = []+ args += ["-h", config.host ?? "localhost"]+ args += ["-P", "\(config.port ?? 3306)"]+ args += ["-u", config.username ?? "root"]+ args += ["--password=\(password)"]+ args += [database]++ return await runProcessWithStdinProgress(path: mysqlPath, args: args, env: nil, inputFile: inputURL, start: start, onProgress: onProgress)+ }++ // MARK: - SQLite++ private func sqliteCopy(config: ConnectionConfig, to outputURL: URL, start: CFAbsoluteTime) -> BackupResult {+ guard let filePath = config.filePath ?? config.database else {+ return BackupResult(success: false, outputPath: nil,+ errorMessage: "No SQLite file path configured", duration: 0, fileSize: nil)+ }+ do {+ let src = URL(fileURLWithPath: filePath)+ if FileManager.default.fileExists(atPath: outputURL.path) {+ try FileManager.default.removeItem(at: outputURL)+ }+ try FileManager.default.copyItem(at: src, to: outputURL)+ let size = try FileManager.default.attributesOfItem(atPath: outputURL.path)[.size] as? Int64+ return BackupResult(success: true, outputPath: outputURL.path, errorMessage: nil,+ duration: CFAbsoluteTimeGetCurrent() - start, fileSize: size)+ } catch {+ return BackupResult(success: false, outputPath: nil,+ errorMessage: error.localizedDescription,+ duration: CFAbsoluteTimeGetCurrent() - start, fileSize: nil)+ }+ }++ private func sqliteRestore(config: ConnectionConfig, from inputURL: URL, start: CFAbsoluteTime) -> BackupResult {+ guard let filePath = config.filePath ?? config.database else {+ return BackupResult(success: false, outputPath: nil,+ errorMessage: "No SQLite file path configured", duration: 0, fileSize: nil)+ }+ do {+ let dest = URL(fileURLWithPath: filePath)+ if FileManager.default.fileExists(atPath: dest.path) {+ try FileManager.default.removeItem(at: dest)+ }+ try FileManager.default.copyItem(at: inputURL, to: dest)+ return BackupResult(success: true, outputPath: dest.path, errorMessage: nil,+ duration: CFAbsoluteTimeGetCurrent() - start, fileSize: nil)+ } catch {+ return BackupResult(success: false, outputPath: nil,+ errorMessage: error.localizedDescription,+ duration: CFAbsoluteTimeGetCurrent() - start, fileSize: nil)+ }+ }++ // MARK: - SQL Server (native BACKUP/RESTORE DATABASE)++ /// MSSQL backup uses SQL Server's native BACKUP DATABASE command.+ /// IMPORTANT: The path is **server-side** — SQL Server process writes the file.+ /// For Docker, user must volume-mount the path. Not supported on Azure SQL Database.+ private func mssqlBackup(+ adapter: MSSQLAdapter,+ database: String,+ to outputURL: URL,+ start: CFAbsoluteTime+ ) async -> BackupResult {+ let safeDB = database.replacingOccurrences(of: "]", with: "]]")+ let safePath = outputURL.path.replacingOccurrences(of: "'", with: "''")+ let sql = """+ BACKUP DATABASE [\(safeDB)] TO DISK = N'\(safePath)'+ WITH FORMAT, INIT, NAME = 'Gridex Full Backup', COMPRESSION+ """+ do {+ _ = try await adapter.executeRaw(sql: sql)+ let size = try? FileManager.default.attributesOfItem(atPath: outputURL.path)[.size] as? Int64+ return BackupResult(+ success: true,+ outputPath: outputURL.path,+ errorMessage: "Note: Path is server-side. For Docker, ensure the container has access to this path (volume mount).",+ duration: CFAbsoluteTimeGetCurrent() - start,+ fileSize: size+ )+ } catch {+ return BackupResult(+ success: false, outputPath: nil,+ errorMessage: "BACKUP DATABASE failed: \(error.localizedDescription). The path must be accessible to the SQL Server process (server-side, not client).",+ duration: CFAbsoluteTimeGetCurrent() - start, fileSize: nil+ )+ }+ }++ private func mssqlRestore(+ adapter: MSSQLAdapter,+ database: String,+ from inputURL: URL,+ start: CFAbsoluteTime+ ) async -> BackupResult {+ let safeDB = database.replacingOccurrences(of: "]", with: "]]")+ let safePath = inputURL.path.replacingOccurrences(of: "'", with: "''")+ // Force-disconnect users and restore with REPLACE+ let setSingleSQL = "ALTER DATABASE [\(safeDB)] SET SINGLE_USER WITH ROLLBACK IMMEDIATE"+ let restoreSQL = "RESTORE DATABASE [\(safeDB)] FROM DISK = N'\(safePath)' WITH REPLACE"+ let setMultiSQL = "ALTER DATABASE [\(safeDB)] SET MULTI_USER"+ do {+ _ = try? await adapter.executeRaw(sql: setSingleSQL)+ _ = try await adapter.executeRaw(sql: restoreSQL)+ _ = try? await adapter.executeRaw(sql: setMultiSQL)+ return BackupResult(+ success: true, outputPath: nil, errorMessage: nil,+ duration: CFAbsoluteTimeGetCurrent() - start, fileSize: nil+ )+ } catch {+ _ = try? await adapter.executeRaw(sql: setMultiSQL)+ return BackupResult(+ success: false, outputPath: nil,+ errorMessage: "RESTORE DATABASE failed: \(error.localizedDescription). The file must be server-side accessible.",+ duration: CFAbsoluteTimeGetCurrent() - start, fileSize: nil+ )+ }+ }++ // MARK: - MongoDB (NDJSON pure Swift)++ /// MongoDB backup: iterate all collections and write one JSON document per line.+ /// Format: `{"_collection": "name", "_doc": {...}}` per line.+ private func mongoNDJSONBackup(+ adapter: MongoDBAdapter,+ to outputURL: URL,+ start: CFAbsoluteTime,+ onProgress: (@Sendable (Int64, TimeInterval) -> Void)?+ ) async -> BackupResult {+ do {+ // Create file+ FileManager.default.createFile(atPath: outputURL.path, contents: nil)+ guard let handle = try? FileHandle(forWritingTo: outputURL) else {+ return BackupResult(success: false, outputPath: nil,+ errorMessage: "Cannot create output file at \(outputURL.path)",+ duration: CFAbsoluteTimeGetCurrent() - start, fileSize: nil)+ }+ defer { try? handle.close() }++ try await adapter.backupStream(onBatch: { collection, batch in+ for doc in batch {+ let json = adapter.documentToJSON(doc)+ // Wrap each document with its collection name+ let line = "{\"_collection\":\"\(collection)\",\"_doc\":\(json)}\n"+ if let data = line.data(using: .utf8) {+ try handle.write(contentsOf: data)+ }+ }+ }, onProgress: onProgress)++ let size = try? FileManager.default.attributesOfItem(atPath: outputURL.path)[.size] as? Int64+ return BackupResult(+ success: true, outputPath: outputURL.path, errorMessage: nil,+ duration: CFAbsoluteTimeGetCurrent() - start, fileSize: size+ )+ } catch {+ return BackupResult(+ success: false, outputPath: nil,+ errorMessage: "MongoDB backup failed: \(error.localizedDescription)",+ duration: CFAbsoluteTimeGetCurrent() - start, fileSize: nil+ )+ }+ }++ private func mongoNDJSONRestore(+ adapter: MongoDBAdapter,+ from inputURL: URL,+ start: CFAbsoluteTime,+ onProgress: (@Sendable (Double) -> Void)?+ ) async -> BackupResult {+ do {+ let totalSize = (try? FileManager.default.attributesOfItem(atPath: inputURL.path)[.size] as? Int64) ?? 0+ let data = try Data(contentsOf: inputURL)+ guard let content = String(data: data, encoding: .utf8) else {+ return BackupResult(success: false, outputPath: nil,+ errorMessage: "Invalid UTF-8 in backup file",+ duration: CFAbsoluteTimeGetCurrent() - start, fileSize: nil)+ }+ let lines = content.components(separatedBy: "\n")+ var bytesProcessed: Int64 = 0+ // Group documents by collection for efficient batch insert+ var batches: [String: [String]] = [:]+ for line in lines {+ let trimmed = line.trimmingCharacters(in: .whitespaces)+ guard !trimmed.isEmpty else { continue }+ bytesProcessed += Int64(line.utf8.count + 1)+ // Parse wrapper {"_collection": "...", "_doc": {...}}+ guard let lineData = trimmed.data(using: .utf8),+ let json = try? JSONSerialization.jsonObject(with: lineData) as? [String: Any],+ let coll = json["_collection"] as? String,+ let docObj = json["_doc"] else { continue }+ // Re-serialize the doc back to JSON string for adapter parsing+ if let docData = try? JSONSerialization.data(withJSONObject: docObj),+ let docJson = String(data: docData, encoding: .utf8) {+ batches[coll, default: []].append(docJson)+ }+ if totalSize > 0 {+ onProgress?(Double(bytesProcessed) / Double(totalSize))+ }+ }+ // Insert batches+ for (collection, jsonDocs) in batches {+ var docs: [Document] = []+ for jsonStr in jsonDocs {+ if let doc = adapter.jsonLineToDocument(jsonStr) {+ docs.append(doc)+ }+ }+ try await adapter.insertBatch(collection: collection, documents: docs)+ }+ return BackupResult(+ success: true, outputPath: nil, errorMessage: nil,+ duration: CFAbsoluteTimeGetCurrent() - start, fileSize: totalSize+ )+ } catch {+ return BackupResult(+ success: false, outputPath: nil,+ errorMessage: "MongoDB restore failed: \(error.localizedDescription)",+ duration: CFAbsoluteTimeGetCurrent() - start, fileSize: nil+ )+ }+ }++ // MARK: - Redis (JSON snapshot via SCAN + DUMP/RESTORE fallback to type-specific commands)++ /// Redis backup: SCAN all keys, fetch value + TTL based on type, write as JSON array.+ /// Format: `[{"key": "...", "type": "...", "ttl": N, "value": ...}, ...]`+ private func redisJSONBackup(+ adapter: RedisAdapter,+ to outputURL: URL,+ start: CFAbsoluteTime,+ onProgress: (@Sendable (Int64, TimeInterval) -> Void)?+ ) async -> BackupResult {+ do {+ FileManager.default.createFile(atPath: outputURL.path, contents: nil)+ guard let handle = try? FileHandle(forWritingTo: outputURL) else {+ return BackupResult(success: false, outputPath: nil,+ errorMessage: "Cannot create output file",+ duration: CFAbsoluteTimeGetCurrent() - start, fileSize: nil)+ }+ defer { try? handle.close() }++ // Use NDJSON format for streaming (one entry per line)+ try await adapter.backupScanAll(onBatch: { batch in+ for entry in batch {+ let line = RedisJSONSerializer.serialize(entry) + "\n"+ if let data = line.data(using: .utf8) {+ try handle.write(contentsOf: data)+ }+ }+ }, onProgress: onProgress)++ let size = try? FileManager.default.attributesOfItem(atPath: outputURL.path)[.size] as? Int64+ return BackupResult(+ success: true, outputPath: outputURL.path, errorMessage: nil,+ duration: CFAbsoluteTimeGetCurrent() - start, fileSize: size+ )+ } catch {+ return BackupResult(+ success: false, outputPath: nil,+ errorMessage: "Redis backup failed: \(error.localizedDescription)",+ duration: CFAbsoluteTimeGetCurrent() - start, fileSize: nil+ )+ }+ }++ private func redisJSONRestore(+ adapter: RedisAdapter,+ from inputURL: URL,+ start: CFAbsoluteTime,+ onProgress: (@Sendable (Double) -> Void)?+ ) async -> BackupResult {+ do {+ let totalSize = (try? FileManager.default.attributesOfItem(atPath: inputURL.path)[.size] as? Int64) ?? 0+ let data = try Data(contentsOf: inputURL)+ guard let content = String(data: data, encoding: .utf8) else {+ return BackupResult(success: false, outputPath: nil,+ errorMessage: "Invalid UTF-8 in backup file",+ duration: CFAbsoluteTimeGetCurrent() - start, fileSize: nil)+ }+ let lines = content.components(separatedBy: "\n")+ var bytesProcessed: Int64 = 0+ for line in lines {+ let trimmed = line.trimmingCharacters(in: .whitespaces)+ bytesProcessed += Int64(line.utf8.count + 1)+ guard !trimmed.isEmpty else { continue }+ if let entry = RedisJSONSerializer.deserialize(trimmed) {+ try await adapter.restoreKeyEntry(entry)+ }+ if totalSize > 0 {+ onProgress?(Double(bytesProcessed) / Double(totalSize))+ }+ }+ return BackupResult(+ success: true, outputPath: nil, errorMessage: nil,+ duration: CFAbsoluteTimeGetCurrent() - start, fileSize: totalSize+ )+ } catch {+ return BackupResult(+ success: false, outputPath: nil,+ errorMessage: "Redis restore failed: \(error.localizedDescription)",+ duration: CFAbsoluteTimeGetCurrent() - start, fileSize: nil+ )+ }+ }++ // MARK: - Helpers++ private func findTool(_ name: String) -> String? {+ let searchPaths = [+ "/usr/local/bin/\(name)",+ "/opt/homebrew/bin/\(name)",+ "/usr/bin/\(name)",+ "/opt/homebrew/opt/libpq/bin/\(name)",+ "/usr/local/opt/libpq/bin/\(name)",+ "/opt/homebrew/opt/mysql-client/bin/\(name)",+ "/usr/local/opt/mysql-client/bin/\(name)",+ "/Applications/Postgres.app/Contents/Versions/latest/bin/\(name)",+ ]+ for p in searchPaths {+ if FileManager.default.isExecutableFile(atPath: p) { return p }+ }+ // Try `which`+ let proc = Process()+ proc.executableURL = URL(fileURLWithPath: "/usr/bin/which")+ proc.arguments = [name]+ let pipe = Pipe()+ proc.standardOutput = pipe+ proc.standardError = Pipe()+ try? proc.run()+ proc.waitUntilExit()+ let data = pipe.fileHandleForReading.readDataToEndOfFile()+ let path = String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines)+ if let path, !path.isEmpty, FileManager.default.isExecutableFile(atPath: path) { return path }+ return nil+ }++ /// Run a CLI tool that writes to an output file, polling file size for progress reporting.+ private func runProcessWithOutputProgress(+ path: String,+ args: [String],+ env: [String: String]?,+ start: CFAbsoluteTime,+ outputURL: URL,+ onProgress: (@Sendable (Int64, TimeInterval) -> Void)?+ ) async -> BackupResult {+ await withCheckedContinuation { continuation in+ DispatchQueue.global(qos: .userInitiated).async {+ let proc = Process()+ proc.executableURL = URL(fileURLWithPath: path)+ proc.arguments = args+ if let env { proc.environment = env }++ let stderrPipe = Pipe()+ proc.standardError = stderrPipe+ proc.standardOutput = Pipe()++ do {+ try proc.run()+ } catch {+ continuation.resume(returning: BackupResult(+ success: false, outputPath: nil,+ errorMessage: "Failed to launch \(path): \(error.localizedDescription)",+ duration: CFAbsoluteTimeGetCurrent() - start, fileSize: nil))+ return+ }++ // Poll output file size while process runs+ if onProgress != nil {+ let pollQueue = DispatchQueue(label: "backup.progress")+ let timer = DispatchSource.makeTimerSource(queue: pollQueue)+ timer.schedule(deadline: .now() + 0.5, repeating: 0.5)+ timer.setEventHandler {+ let elapsed = CFAbsoluteTimeGetCurrent() - start+ let size = (try? FileManager.default.attributesOfItem(atPath: outputURL.path)[.size] as? Int64) ?? 0+ onProgress?(size, elapsed)+ }+ timer.resume()+ proc.waitUntilExit()+ timer.cancel()+ } else {+ proc.waitUntilExit()+ }++ let duration = CFAbsoluteTimeGetCurrent() - start+ let stderrData = stderrPipe.fileHandleForReading.readDataToEndOfFile()+ let stderrStr = String(data: stderrData, encoding: .utf8) ?? ""++ var fileSize: Int64?+ fileSize = (try? FileManager.default.attributesOfItem(atPath: outputURL.path)[.size] as? Int64)++ if proc.terminationStatus == 0 {+ continuation.resume(returning: BackupResult(+ success: true, outputPath: outputURL.path,+ errorMessage: stderrStr.isEmpty ? nil : stderrStr,+ duration: duration, fileSize: fileSize))+ } else {+ continuation.resume(returning: BackupResult(+ success: false, outputPath: nil,+ errorMessage: stderrStr.isEmpty ? "Process exited with code \(proc.terminationStatus)" : stderrStr,+ duration: duration, fileSize: nil))+ }+ }+ }+ }++ /// Run a CLI tool, piping a file through stdin in chunks, reporting progress as bytes sent / total.+ private func runProcessWithStdinProgress(+ path: String,+ args: [String],+ env: [String: String]?,+ inputFile: URL,+ start: CFAbsoluteTime,+ onProgress: (@Sendable (Double) -> Void)?+ ) async -> BackupResult {+ await withCheckedContinuation { continuation in+ DispatchQueue.global(qos: .userInitiated).async {+ let totalSize: Int64+ do {+ let attrs = try FileManager.default.attributesOfItem(atPath: inputFile.path)+ totalSize = (attrs[.size] as? Int64) ?? 0+ } catch {+ continuation.resume(returning: BackupResult(+ success: false, outputPath: nil,+ errorMessage: "Cannot read file: \(error.localizedDescription)",+ duration: CFAbsoluteTimeGetCurrent() - start, fileSize: nil))+ return+ }++ guard let inputStream = InputStream(url: inputFile) else {+ continuation.resume(returning: BackupResult(+ success: false, outputPath: nil,+ errorMessage: "Cannot open file for reading",+ duration: CFAbsoluteTimeGetCurrent() - start, fileSize: nil))+ return+ }++ let proc = Process()+ proc.executableURL = URL(fileURLWithPath: path)+ proc.arguments = args+ if let env { proc.environment = env }++ let stdinPipe = Pipe()+ let stderrPipe = Pipe()+ proc.standardInput = stdinPipe+ proc.standardError = stderrPipe+ proc.standardOutput = Pipe()++ do {+ try proc.run()+ } catch {+ continuation.resume(returning: BackupResult(+ success: false, outputPath: nil,+ errorMessage: "Failed to launch \(path): \(error.localizedDescription)",+ duration: CFAbsoluteTimeGetCurrent() - start, fileSize: nil))+ return+ }++ // Stream file to stdin in chunks, reporting progress+ inputStream.open()+ let chunkSize = 64 * 1024 // 64KB chunks+ var buffer = [UInt8](repeating: 0, count: chunkSize)+ var bytesSent: Int64 = 0+ let writeHandle = stdinPipe.fileHandleForWriting++ while inputStream.hasBytesAvailable {+ let bytesRead = inputStream.read(&buffer, maxLength: chunkSize)+ guard bytesRead > 0 else { break }+ writeHandle.write(Data(buffer[0..<bytesRead]))+ bytesSent += Int64(bytesRead)+ if totalSize > 0 {+ onProgress?(Double(bytesSent) / Double(totalSize))+ }+ }+ inputStream.close()+ try? writeHandle.close()++ proc.waitUntilExit()++ let duration = CFAbsoluteTimeGetCurrent() - start+ let stderrData = stderrPipe.fileHandleForReading.readDataToEndOfFile()+ let stderrStr = String(data: stderrData, encoding: .utf8) ?? ""++ if proc.terminationStatus == 0 {+ onProgress?(1.0)+ continuation.resume(returning: BackupResult(+ success: true, outputPath: nil,+ errorMessage: stderrStr.isEmpty ? nil : stderrStr,+ duration: duration, fileSize: totalSize))+ } else {+ continuation.resume(returning: BackupResult(+ success: false, outputPath: nil,+ errorMessage: stderrStr.isEmpty ? "Process exited with code \(proc.terminationStatus)" : stderrStr,+ duration: duration, fileSize: nil))+ }+ }+ }+ }++ private func runProcess(+ path: String,+ args: [String],+ env: [String: String]?,+ start: CFAbsoluteTime,+ outputURL: URL?+ ) async -> BackupResult {+ await withCheckedContinuation { continuation in+ DispatchQueue.global(qos: .userInitiated).async {+ let proc = Process()+ proc.executableURL = URL(fileURLWithPath: path)+ proc.arguments = args+ if let env { proc.environment = env }++ let stderrPipe = Pipe()+ proc.standardError = stderrPipe+ proc.standardOutput = Pipe() // suppress stdout++ do {+ try proc.run()+ proc.waitUntilExit()+ } catch {+ continuation.resume(returning: BackupResult(+ success: false, outputPath: nil,+ errorMessage: "Failed to launch \(path): \(error.localizedDescription)",+ duration: CFAbsoluteTimeGetCurrent() - start, fileSize: nil))+ return+ }++ let duration = CFAbsoluteTimeGetCurrent() - start+ let stderrData = stderrPipe.fileHandleForReading.readDataToEndOfFile()+ let stderrStr = String(data: stderrData, encoding: .utf8) ?? ""++ if proc.terminationStatus == 0 {+ var fileSize: Int64?+ if let outputURL {+ fileSize = (try? FileManager.default.attributesOfItem(atPath: outputURL.path)[.size] as? Int64)+ }+ continuation.resume(returning: BackupResult(+ success: true, outputPath: outputURL?.path,+ errorMessage: stderrStr.isEmpty ? nil : stderrStr,+ duration: duration, fileSize: fileSize))+ } else {+ continuation.resume(returning: BackupResult(+ success: false, outputPath: nil,+ errorMessage: stderrStr.isEmpty ? "Process exited with code \(proc.terminationStatus)" : stderrStr,+ duration: duration, fileSize: nil))+ }+ }+ }+ }+}diff --git a/macos/Services/Export/ExportService.swift b/macos/Services/Export/ExportService.swiftnew file mode 100644index 0000000..ebb2b44--- /dev/null+++ b/macos/Services/Export/ExportService.swift@@ -0,0 +1,211 @@+// ExportService.swift+// Gridex++import Foundation++final class ExportService: ExportDataUseCase, @unchecked Sendable {++ func exportCSV(data: QueryResult, to url: URL) async throws {+ var csv = data.columns.map(\.name).joined(separator: ",") + "\n"+ for row in data.rows {+ csv += row.map { value in+ let str = value.description+ if str.contains(",") || str.contains("\"") || str.contains("\n") {+ return "\"\(str.replacingOccurrences(of: "\"", with: "\"\""))\""+ }+ return str+ }.joined(separator: ",") + "\n"+ }+ try csv.write(to: url, atomically: true, encoding: .utf8)+ }++ func exportJSON(data: QueryResult, to url: URL) async throws {+ let rows = data.rows.map { row in+ Dictionary(uniqueKeysWithValues: zip(data.columns.map(\.name), row.map(\.description)))+ }+ let jsonData = try JSONSerialization.data(withJSONObject: rows, options: [.prettyPrinted, .sortedKeys])+ try jsonData.write(to: url)+ }++ func exportSQL(data: QueryResult, table: String, to url: URL) async throws {+ var sql = ""+ let columns = data.columns.map(\.name).joined(separator: ", ")+ for row in data.rows {+ let values = row.map { value -> String in+ if value.isNull { return "NULL" }+ return "'\(value.description.replacingOccurrences(of: "'", with: "''"))'"+ }.joined(separator: ", ")+ sql += "INSERT INTO \(table) (\(columns)) VALUES (\(values));\n"+ }+ try sql.write(to: url, atomically: true, encoding: .utf8)+ }++ /// Full-fidelity SQL export: header comment, DROP/CREATE, sequences,+ /// multi-row INSERT, indices — matches professional output so the+ /// file can be re-imported to recreate the table exactly.+ func exportTableSQL(+ description: TableDescription,+ rows: [[RowValue]],+ databaseType: DatabaseType,+ databaseName: String,+ to url: URL+ ) async throws {+ let d = databaseType.sqlDialect+ let schemaName = description.schema ?? "public"+ let qualified: String = {+ if databaseType == .sqlite {+ return d.quoteIdentifier(description.name)+ }+ return "\(d.quoteIdentifier(schemaName)).\(d.quoteIdentifier(description.name))"+ }()++ var sql = ""++ // Header comment block+ let ts = {+ let f = DateFormatter()+ f.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSS"+ return f.string(from: Date())+ }()+ sql += "-- -------------------------------------------------------------\n"+ sql += "-- Gridex SQL Export\n"+ sql += "--\n"+ sql += "-- Database: \(databaseName)\n"+ sql += "-- Table: \(description.name)\n"+ sql += "-- Generation Time: \(ts)\n"+ sql += "-- -------------------------------------------------------------\n\n\n"++ // DROP+ sql += "DROP TABLE IF EXISTS \(qualified);\n"++ // Sequences (PostgreSQL only — detect from defaultValue containing nextval)+ if databaseType == .postgresql {+ var seqNames: [String] = []+ for col in description.columns {+ if let def = col.defaultValue, def.contains("nextval(") {+ // Extract sequence name from nextval('name'::regclass) or nextval('name')+ let pattern = #"nextval\(['"]?([^'")]+)['"]?"#+ if let regex = try? NSRegularExpression(pattern: pattern),+ let match = regex.firstMatch(in: def, range: NSRange(def.startIndex..., in: def)),+ let range = Range(match.range(at: 1), in: def) {+ let name = String(def[range])+ seqNames.append(name)+ }+ }+ }+ if !seqNames.isEmpty {+ sql += "-- Sequence and defined type\n"+ for name in seqNames {+ sql += "CREATE SEQUENCE IF NOT EXISTS \(name);\n"+ }+ sql += "\n"+ }+ }++ // CREATE TABLE+ sql += "-- Table Definition\n"+ sql += "CREATE TABLE \(qualified) (\n"+ var colDefs: [String] = []+ for col in description.columns {+ var def = " \(d.quoteIdentifier(col.name)) \(col.dataType)"+ if !col.isNullable { def += " NOT NULL" }+ if let defVal = col.defaultValue, !defVal.isEmpty {+ def += " DEFAULT \(defVal)"+ }+ colDefs.append(def)+ }+ // Primary key+ let pkCols = description.columns.filter(\.isPrimaryKey).map { d.quoteIdentifier($0.name) }+ if !pkCols.isEmpty {+ colDefs.append(" PRIMARY KEY (\(pkCols.joined(separator: ", ")))")+ }+ sql += colDefs.joined(separator: ",\n")+ sql += "\n);\n\n"++ // INSERT rows (multi-row single statement)+ if !rows.isEmpty {+ let colList = description.columns.map { d.quoteIdentifier($0.name) }.joined(separator: ", ")+ sql += "INSERT INTO \(qualified) (\(colList)) VALUES\n"+ let rowStrings: [String] = rows.map { row in+ let values = row.enumerated().map { (idx, value) -> String in+ formatValue(value, columnType: idx < description.columns.count ? description.columns[idx].dataType : "")+ }.joined(separator: ", ")+ return "(\(values))"+ }+ sql += rowStrings.joined(separator: ",\n")+ sql += ";\n\n"+ }++ // Indices (skip primary key index — already included in CREATE TABLE)+ let nonPKIndexes = description.indexes.filter {+ !$0.name.hasSuffix("_pkey") && !$0.name.hasSuffix("_pk")+ }+ if !nonPKIndexes.isEmpty {+ sql += "\n-- Indices\n"+ for idx in nonPKIndexes {+ let unique = idx.isUnique ? "UNIQUE " : ""+ let method = idx.type?.lowercased() ?? "btree"+ let cols = idx.columns.joined(separator: ", ")+ if databaseType == .postgresql {+ var indexSQL = "CREATE \(unique)INDEX \(idx.name) ON \(qualified) USING \(method) (\(cols))"+ if let include = idx.include, !include.isEmpty {+ indexSQL += " INCLUDE (\(include))"+ }+ if let cond = idx.condition, !cond.isEmpty {+ indexSQL += " WHERE \(cond)"+ }+ indexSQL += ";\n"+ sql += indexSQL+ } else {+ sql += "CREATE \(unique)INDEX \(idx.name) ON \(qualified) (\(cols));\n"+ }+ }+ }++ try sql.write(to: url, atomically: true, encoding: .utf8)+ }++ /// Format a row value for SQL output — handles NULL, numbers, booleans,+ /// timestamps, and quoted strings with proper escaping.+ private func formatValue(_ value: RowValue, columnType: String) -> String {+ if value.isNull { return "NULL" }+ let raw = value.description+ let typeLower = columnType.lowercased()++ // Numeric types — no quotes+ if typeLower.contains("int") || typeLower == "float" || typeLower == "double" ||+ typeLower.contains("numeric") || typeLower.contains("decimal") ||+ typeLower.contains("real") || typeLower == "serial" || typeLower == "bigserial" {+ return raw.isEmpty ? "NULL" : raw+ }++ // Boolean+ if typeLower == "bool" || typeLower == "boolean" {+ let lower = raw.lowercased()+ if lower == "true" || lower == "t" || lower == "1" { return "true" }+ if lower == "false" || lower == "f" || lower == "0" { return "false" }+ return "NULL"+ }++ // Everything else — quote and escape+ let escaped = raw.replacingOccurrences(of: "'", with: "''")+ return "'\(escaped)'"+ }++ func exportExcel(data: QueryResult, to url: URL) async throws {+ // TODO: Implement Excel export using a library+ throw GridexError.unsupportedOperation("Excel export not yet implemented")+ }++ func exportSchemaDDL(schema: SchemaSnapshot, to url: URL) async throws {+ let dialect = schema.databaseType.sqlDialect+ var ddl = "-- Schema export: \(schema.databaseName)\n"+ ddl += "-- Generated by Gridex on \(ISO8601DateFormatter().string(from: Date()))\n\n"++ for table in schema.allTables {+ ddl += table.toDDL(dialect: dialect) + "\n\n"+ }++ try ddl.write(to: url, atomically: true, encoding: .utf8)+ }+}diff --git a/macos/Services/Export/RedisJSONSerializer.swift b/macos/Services/Export/RedisJSONSerializer.swiftnew file mode 100644index 0000000..6b59939--- /dev/null+++ b/macos/Services/Export/RedisJSONSerializer.swift@@ -0,0 +1,73 @@+// RedisJSONSerializer.swift+// Gridex+//+// Serialize/deserialize RedisKeyEntry as JSON for backup/restore.+// Format (one entry per line in NDJSON):+// {"key":"...","type":"string","ttl":null,"value":"hello"}+// {"key":"...","type":"list","ttl":60,"value":["a","b","c"]}+// {"key":"...","type":"zset","ttl":null,"value":[{"m":"a","s":1.0},...]}+// {"key":"...","type":"hash","ttl":null,"value":{"f1":"v1","f2":"v2"}}++import Foundation++enum RedisJSONSerializer {+ static func serialize(_ entry: RedisAdapter.RedisKeyEntry) -> String {+ var json: [String: Any] = [+ "key": entry.key,+ "type": entry.type,+ ]+ json["ttl"] = entry.ttl as Any? ?? NSNull()++ switch entry.value {+ case .string(let s):+ json["value"] = s+ case .list(let items):+ json["value"] = items+ case .set(let members):+ json["value"] = Array(members)+ case .zset(let pairs):+ json["value"] = pairs.map { ["m": $0.0, "s": $0.1] as [String: Any] }+ case .hash(let dict):+ json["value"] = dict+ }++ if let data = try? JSONSerialization.data(withJSONObject: json),+ let str = String(data: data, encoding: .utf8) {+ return str+ }+ return "{}"+ }++ static func deserialize(_ line: String) -> RedisAdapter.RedisKeyEntry? {+ guard let data = line.data(using: .utf8),+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ let key = json["key"] as? String,+ let type = json["type"] as? String else {+ return nil+ }+ let ttl: Int? = (json["ttl"] as? Int)++ let value: RedisAdapter.RedisKeyEntry.Value+ switch type {+ case "string":+ value = .string((json["value"] as? String) ?? "")+ case "list":+ value = .list((json["value"] as? [String]) ?? [])+ case "set":+ value = .set((json["value"] as? [String]) ?? [])+ case "zset":+ let pairs = (json["value"] as? [[String: Any]]) ?? []+ value = .zset(pairs.compactMap { dict in+ guard let m = dict["m"] as? String,+ let s = dict["s"] as? Double else { return nil }+ return (m, s)+ })+ case "hash":+ value = .hash((json["value"] as? [String: String]) ?? [:])+ default:+ return nil+ }++ return RedisAdapter.RedisKeyEntry(key: key, type: type, ttl: ttl, value: value)+ }+}diff --git a/macos/Services/QueryEngine/ConnectionManager.swift b/macos/Services/QueryEngine/ConnectionManager.swiftnew file mode 100644index 0000000..4311a5d--- /dev/null+++ b/macos/Services/QueryEngine/ConnectionManager.swift@@ -0,0 +1,83 @@+// ConnectionManager.swift+// Gridex+//+// Manages active database connections and adapter lifecycle.++import Foundation++actor ConnectionManager {+ private var activeConnections: [UUID: ActiveConnection] = [:]+ private let sshService = SSHTunnelService()++ func connect(config: ConnectionConfig, password: String?, sshPassword: String?) async throws -> ActiveConnection {+ let adapter = createAdapter(for: config.databaseType)++ var effectiveConfig = config++ // If SSH tunnel is configured, establish it first and redirect connection through localhost+ if let ssh = config.sshConfig {+ let remoteHost = config.host ?? "127.0.0.1"+ let remotePort = config.port ?? config.databaseType.defaultPort+ let localPort = try await sshService.establish(+ connectionId: config.id,+ config: ssh,+ remoteHost: remoteHost,+ remotePort: remotePort,+ password: sshPassword+ )+ effectiveConfig.host = "127.0.0.1"+ effectiveConfig.port = Int(localPort)+ }++ try await adapter.connect(config: effectiveConfig, password: password)++ let connection = ActiveConnection(+ id: config.id,+ config: config,+ adapter: adapter,+ initialSchema: nil,+ connectedAt: Date()+ )++ activeConnections[config.id] = connection+ return connection+ }++ func disconnect(connectionId: UUID) async throws {+ guard let connection = activeConnections[connectionId] else { return }+ try await connection.adapter.disconnect()+ await sshService.disconnect(connectionId: connectionId)+ activeConnections[connectionId] = nil+ }++ func disconnectAll() async {+ for (_, connection) in activeConnections {+ try? await connection.adapter.disconnect()+ }+ await sshService.disconnectAll()+ activeConnections.removeAll()+ }++ func activeConnection(for connectionId: UUID) -> ActiveConnection? {+ activeConnections[connectionId]+ }++ func isConnected(_ connectionId: UUID) -> Bool {+ activeConnections[connectionId] != nil+ }++ var allActiveConnections: [ActiveConnection] {+ Array(activeConnections.values)+ }++ private func createAdapter(for type: DatabaseType) -> any DatabaseAdapter {+ switch type {+ case .sqlite: return SQLiteAdapter()+ case .postgresql: return PostgreSQLAdapter()+ case .mysql: return MySQLAdapter()+ case .redis: return RedisAdapter()+ case .mongodb: return MongoDBAdapter()+ case .mssql: return MSSQLAdapter()+ }+ }+}diff --git a/macos/Services/QueryEngine/QueryBuilder.swift b/macos/Services/QueryEngine/QueryBuilder.swiftnew file mode 100644index 0000000..2cb2ec2--- /dev/null+++ b/macos/Services/QueryEngine/QueryBuilder.swift@@ -0,0 +1,130 @@+// QueryBuilder.swift+// Gridex+//+// Fluent SQL query builder with dialect support.++import Foundation++struct QueryBuilder {+ private let dialect: SQLDialect+ private var selectColumns: [String] = ["*"]+ private var fromTable: String = ""+ private var fromSchema: String?+ private var whereClauses: [String] = []+ private var orderByClauses: [String] = []+ private var limitValue: Int?+ private var offsetValue: Int?+ private var joinClauses: [String] = []++ init(dialect: SQLDialect) {+ self.dialect = dialect+ }++ func select(_ columns: [String]) -> QueryBuilder {+ var copy = self+ copy.selectColumns = columns.map { dialect.quoteIdentifier($0) }+ return copy+ }++ func selectAll() -> QueryBuilder {+ var copy = self+ copy.selectColumns = ["*"]+ return copy+ }++ func from(_ table: String, schema: String? = nil) -> QueryBuilder {+ var copy = self+ copy.fromTable = table+ copy.fromSchema = schema+ return copy+ }++ func whereClause(_ condition: String) -> QueryBuilder {+ var copy = self+ copy.whereClauses.append(condition)+ return copy+ }++ func whereFilter(_ filter: FilterExpression) -> QueryBuilder {+ var copy = self+ copy.whereClauses.append(filter.toSQL(dialect: dialect))+ return copy+ }++ func orderBy(_ column: String, _ direction: SortDirection = .ascending) -> QueryBuilder {+ var copy = self+ copy.orderByClauses.append("\(dialect.quoteIdentifier(column)) \(direction.rawValue)")+ return copy+ }++ func orderBy(_ descriptors: [QuerySortDescriptor]) -> QueryBuilder {+ var copy = self+ copy.orderByClauses = descriptors.map { $0.toSQL(dialect: dialect) }+ return copy+ }++ func limit(_ n: Int) -> QueryBuilder {+ var copy = self+ copy.limitValue = n+ return copy+ }++ func offset(_ n: Int) -> QueryBuilder {+ var copy = self+ copy.offsetValue = n+ return copy+ }++ func build() -> String {+ var sql = "SELECT \(selectColumns.joined(separator: ", "))"++ let tableRef: String+ if let schema = fromSchema {+ tableRef = "\(dialect.quoteIdentifier(schema)).\(dialect.quoteIdentifier(fromTable))"+ } else {+ tableRef = dialect.quoteIdentifier(fromTable)+ }+ sql += " FROM \(tableRef)"++ for join in joinClauses {+ sql += " \(join)"+ }++ if !whereClauses.isEmpty {+ sql += " WHERE " + whereClauses.joined(separator: " AND ")+ }++ if !orderByClauses.isEmpty {+ sql += " ORDER BY " + orderByClauses.joined(separator: ", ")+ }++ if let limit = limitValue {+ sql += " LIMIT \(limit)"+ }++ if let offset = offsetValue, offset > 0 {+ sql += " OFFSET \(offset)"+ }++ return sql+ }++ // MARK: - Count query++ func buildCount() -> String {+ var sql = "SELECT COUNT(*)"+ let tableRef: String+ if let schema = fromSchema {+ tableRef = "\(dialect.quoteIdentifier(schema)).\(dialect.quoteIdentifier(fromTable))"+ } else {+ tableRef = dialect.quoteIdentifier(fromTable)+ }+ sql += " FROM \(tableRef)"++ if !whereClauses.isEmpty {+ sql += " WHERE " + whereClauses.joined(separator: " AND ")+ }++ return sql+ }+}diff --git a/macos/Services/QueryEngine/QueryEngine.swift b/macos/Services/QueryEngine/QueryEngine.swiftnew file mode 100644index 0000000..19b58df--- /dev/null+++ b/macos/Services/QueryEngine/QueryEngine.swift@@ -0,0 +1,86 @@+// QueryEngine.swift+// Gridex+//+// Central query execution engine.+// Manages query lifecycle: parse, validate, execute, track history.++import Foundation++actor QueryEngine {+ private let connectionManager: ConnectionManager+ private let historyRepository: any QueryHistoryRepository+ private var runningQueries: [UUID: Task<QueryResult, Error>] = [:]++ init(connectionManager: ConnectionManager, historyRepository: any QueryHistoryRepository) {+ self.connectionManager = connectionManager+ self.historyRepository = historyRepository+ }++ func execute(sql: String, connectionId: UUID, parameters: [QueryParameter]? = nil) async throws -> QueryResult {+ let queryId = UUID()+ let startTime = CFAbsoluteTimeGetCurrent()++ guard let connection = await connectionManager.activeConnection(for: connectionId) else {+ throw GridexError.connectionFailed(underlying: NSError(domain: "QueryEngine", code: -1, userInfo: [NSLocalizedDescriptionKey: "No active connection"]))+ }++ let task = Task {+ try await connection.adapter.execute(query: sql, parameters: parameters)+ }++ runningQueries[queryId] = task++ do {+ let result = try await task.value+ runningQueries[queryId] = nil++ let duration = CFAbsoluteTimeGetCurrent() - startTime+ let dbName = try? await connection.adapter.currentDatabase()++ try? await historyRepository.save(entry: QueryHistoryEntry(+ id: queryId,+ connectionId: connectionId,+ database: dbName ?? "",+ sql: sql,+ executedAt: Date(),+ duration: duration,+ rowCount: result.rowCount,+ status: .success,+ errorMessage: nil,+ isFavorite: false+ ))++ return result+ } catch {+ runningQueries[queryId] = nil++ let duration = CFAbsoluteTimeGetCurrent() - startTime+ let dbName = try? await connection.adapter.currentDatabase()++ try? await historyRepository.save(entry: QueryHistoryEntry(+ id: queryId,+ connectionId: connectionId,+ database: dbName ?? "",+ sql: sql,+ executedAt: Date(),+ duration: duration,+ rowCount: nil,+ status: .error,+ errorMessage: error.localizedDescription,+ isFavorite: false+ ))++ throw error+ }+ }++ func cancel(queryId: UUID) {+ runningQueries[queryId]?.cancel()+ runningQueries[queryId] = nil+ }++ func cancelAll() {+ runningQueries.values.forEach { $0.cancel() }+ runningQueries.removeAll()+ }+}diff --git a/macos/Services/SSH/SSHTunnelService.swift b/macos/Services/SSH/SSHTunnelService.swiftnew file mode 100644index 0000000..c42193a--- /dev/null+++ b/macos/Services/SSH/SSHTunnelService.swift@@ -0,0 +1,236 @@+// SSHTunnelService.swift+// Gridex+//+// SSH tunnel management for secure database connections.+// Uses NIOSSH for local port forwarding: localhost:localPort → remoteHost:remotePort via SSH.++import Foundation+import NIOCore+import NIOPosix+import NIOSSH++actor SSHTunnelService {+ private var activeTunnels: [UUID: SSHTunnel] = [:]++ struct SSHTunnel: Sendable {+ let connectionId: UUID+ let localPort: UInt16+ let remoteHost: String+ let remotePort: Int+ let status: TunnelStatus+ let serverChannel: Channel?+ let sshChannel: Channel?+ }++ enum TunnelStatus: Sendable {+ case connecting+ case connected+ case disconnected+ case error(String)+ }++ func establish(+ connectionId: UUID,+ config: SSHTunnelConfig,+ remoteHost: String,+ remotePort: Int,+ password: String?+ ) async throws -> UInt16 {+ let localPort = try await findFreePort()+ let group = MultiThreadedEventLoopGroup(numberOfThreads: 2)++ let authDelegate: NIOSSHClientUserAuthenticationDelegate+ switch config.authMethod {+ case .password:+ authDelegate = PasswordAuthDelegate(username: config.username, password: password ?? "")+ case .privateKey, .keyWithPassphrase:+ authDelegate = PasswordAuthDelegate(username: config.username, password: password ?? "")+ // TODO: Implement private key auth with PEM parsing+ }++ // Connect to SSH server+ let sshChannel = try await ClientBootstrap(group: group)+ .channelInitializer { channel in+ channel.pipeline.addHandlers([+ NIOSSHHandler(+ role: .client(.init(+ userAuthDelegate: authDelegate,+ serverAuthDelegate: AcceptAllHostKeysDelegate()+ )),+ allocator: channel.allocator,+ inboundChildChannelInitializer: nil+ )+ ])+ }+ .channelOption(.socketOption(.so_reuseaddr), value: 1)+ .connectTimeout(.seconds(10))+ .connect(host: config.host, port: config.port)+ .get()++ // Start local TCP server that forwards connections through SSH+ let serverChannel = try await ServerBootstrap(group: group)+ .childChannelInitializer { childChannel in+ let promise = childChannel.eventLoop.makePromise(of: Channel.self)++ sshChannel.pipeline.handler(type: NIOSSHHandler.self).whenSuccess { handler in+ do {+ let origin = try SocketAddress(ipAddress: "127.0.0.1", port: Int(localPort))+ let channelType = SSHChannelType.directTCPIP(.init(+ targetHost: remoteHost,+ targetPort: remotePort,+ originatorAddress: origin+ ))+ handler.createChannel(promise, channelType: channelType) { sshChildChannel, _ in+ sshChildChannel.pipeline.addHandler(SSHToTCPHandler(tcpChannel: childChannel))+ }+ } catch {+ promise.fail(error)+ }+ }++ return promise.futureResult.flatMap { sshChildChannel in+ childChannel.pipeline.addHandler(TCPToSSHHandler(sshChannel: sshChildChannel))+ }+ }+ .bind(host: "127.0.0.1", port: Int(localPort))+ .get()++ activeTunnels[connectionId] = SSHTunnel(+ connectionId: connectionId,+ localPort: localPort,+ remoteHost: remoteHost,+ remotePort: remotePort,+ status: .connected,+ serverChannel: serverChannel,+ sshChannel: sshChannel+ )++ return localPort+ }++ func disconnect(connectionId: UUID) async {+ if let tunnel = activeTunnels[connectionId] {+ try? await tunnel.serverChannel?.close()+ try? await tunnel.sshChannel?.close()+ }+ activeTunnels[connectionId] = nil+ }++ func status(connectionId: UUID) -> TunnelStatus {+ activeTunnels[connectionId]?.status ?? .disconnected+ }++ func disconnectAll() async {+ for tunnel in activeTunnels.values {+ try? await tunnel.serverChannel?.close()+ try? await tunnel.sshChannel?.close()+ }+ activeTunnels.removeAll()+ }++ // MARK: - Private++ private func findFreePort() async throws -> UInt16 {+ let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)+ defer { try? group.syncShutdownGracefully() }+ let ch = try await ServerBootstrap(group: group)+ .bind(host: "127.0.0.1", port: 0)+ .get()+ guard let port = ch.localAddress?.port else {+ try await ch.close()+ throw GridexError.sshTunnelFailed+ }+ let p = UInt16(port)+ try await ch.close()+ return p+ }+}++// MARK: - Auth Delegates++private final class PasswordAuthDelegate: NIOSSHClientUserAuthenticationDelegate {+ let username: String+ let password: String+ private var offered = false++ init(username: String, password: String) {+ self.username = username+ self.password = password+ }++ func nextAuthenticationType(+ availableMethods: NIOSSHAvailableUserAuthenticationMethods,+ nextChallengePromise: EventLoopPromise<NIOSSHUserAuthenticationOffer?>+ ) {+ if !offered && availableMethods.contains(.password) {+ offered = true+ nextChallengePromise.succeed(.init(+ username: username,+ serviceName: "",+ offer: .password(.init(password: password))+ ))+ } else {+ nextChallengePromise.succeed(nil)+ }+ }+}++private final class AcceptAllHostKeysDelegate: NIOSSHClientServerAuthenticationDelegate {+ func validateHostKey(hostKey: NIOSSHPublicKey, validationCompletePromise: EventLoopPromise<Void>) {+ validationCompletePromise.succeed(())+ }+}++// MARK: - Port Forward Handlers++/// Forwards data from SSH channel → local TCP client+private final class SSHToTCPHandler: ChannelDuplexHandler {+ typealias InboundIn = SSHChannelData+ typealias OutboundIn = ByteBuffer+ typealias OutboundOut = SSHChannelData++ private let tcpChannel: Channel++ init(tcpChannel: Channel) {+ self.tcpChannel = tcpChannel+ }++ func channelRead(context: ChannelHandlerContext, data: NIOAny) {+ let channelData = unwrapInboundIn(data)+ guard case .byteBuffer(let buf) = channelData.data else { return }+ tcpChannel.writeAndFlush(buf, promise: nil)+ }++ func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {+ let buf = unwrapOutboundIn(data)+ context.write(wrapOutboundOut(.init(type: .channel, data: .byteBuffer(buf))), promise: promise)+ }++ func channelInactive(context: ChannelHandlerContext) {+ tcpChannel.close(promise: nil)+ context.fireChannelInactive()+ }+}++/// Forwards data from local TCP client → SSH channel+private final class TCPToSSHHandler: ChannelDuplexHandler {+ typealias InboundIn = ByteBuffer+ typealias OutboundIn = ByteBuffer+ typealias OutboundOut = ByteBuffer++ private let sshChannel: Channel++ init(sshChannel: Channel) {+ self.sshChannel = sshChannel+ }++ func channelRead(context: ChannelHandlerContext, data: NIOAny) {+ let buf = unwrapInboundIn(data)+ sshChannel.writeAndFlush(buf, promise: nil)+ }++ func channelInactive(context: ChannelHandlerContext) {+ sshChannel.close(promise: nil)+ context.fireChannelInactive()+ }+}diff --git a/macos/Services/SchemaInspector/SchemaInspectorService.swift b/macos/Services/SchemaInspector/SchemaInspectorService.swiftnew file mode 100644index 0000000..af501eb--- /dev/null+++ b/macos/Services/SchemaInspector/SchemaInspectorService.swift@@ -0,0 +1,35 @@+// SchemaInspectorService.swift+// Gridex+//+// High-level schema inspection with caching.++import Foundation++actor SchemaInspectorService {+ private let cache: SchemaCache+ private let connectionManager: ConnectionManager++ init(cache: SchemaCache, connectionManager: ConnectionManager) {+ self.cache = cache+ self.connectionManager = connectionManager+ }++ func loadSchema(connectionId: UUID, forceRefresh: Bool = false) async throws -> SchemaSnapshot {+ if !forceRefresh, let cached = await cache.get(connectionId: connectionId) {+ return cached+ }++ guard let connection = await connectionManager.activeConnection(for: connectionId),+ let inspectable = connection.adapter as? SchemaInspectable else {+ throw GridexError.schemaLoadFailed("No inspectable connection")+ }++ let snapshot = try await inspectable.fullSchemaSnapshot(database: connection.config.database)+ await cache.set(connectionId: connectionId, snapshot: snapshot)+ return snapshot+ }++ func invalidateCache(connectionId: UUID) async {+ await cache.invalidate(connectionId: connectionId)+ }+}diff --git a/scripts/build-app.sh b/scripts/build-app.shnew file mode 100755index 0000000..48e5fd0--- /dev/null+++ b/scripts/build-app.sh@@ -0,0 +1,164 @@+#!/bin/bash+# build-app.sh — Build Gridex.app bundle from SPM executable.+#+# Usage:+# ./scripts/build-app.sh # Debug build (ad-hoc sign, quick local run)+# ./scripts/build-app.sh release # Release: build + sign + notarize + staple + verify+# NOTARIZE=0 ./scripts/build-app.sh release # Release, skip notarization+#+# Env (release mode):+# SIGN_IDENTITY SHA-1 or name of Developer ID cert (default pinned to 16/4/26 cert)+# NOTARY_PROFILE notarytool keychain profile (default: gridex-notarize)+# NOTARIZE 0 to skip notarization (useful while iterating locally)++set -euo pipefail++MODE="${1:-debug}"+APP_NAME="Gridex"+BUNDLE_ID="com.gridex.app"+PROJECT_DIR="$(cd "$(dirname "$0")/.." && pwd)"+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+RESOURCES_DIR="$PROJECT_DIR/macos/Resources"+INFO_PLIST="$RESOURCES_DIR/Info.plist"+ICON="$RESOURCES_DIR/AppIcon.icns"+XCASSETS="$RESOURCES_DIR/Assets.xcassets"+NOTARIZE="${NOTARIZE:-1}"++# 1. Build+echo "→ Building ($MODE)..."+if [ "$MODE" = "release" ]; then+ swift build -c release --package-path "$PROJECT_DIR" 2>&1 | tail -3+ BUILD_DIR="$PROJECT_DIR/.build/release"+else+ swift build --package-path "$PROJECT_DIR" 2>&1 | tail -3+ BUILD_DIR="$PROJECT_DIR/.build/debug"+fi++EXECUTABLE="$BUILD_DIR/$APP_NAME"+if [ ! -f "$EXECUTABLE" ]; then+ echo "✗ Build failed — executable not found at $EXECUTABLE"+ exit 1+fi++# 2. Create .app bundle structure+OUTPUT_DIR="$PROJECT_DIR/dist"+APP_BUNDLE="$OUTPUT_DIR/$APP_NAME.app"+CONTENTS="$APP_BUNDLE/Contents"+MACOS_DIR="$CONTENTS/MacOS"+RESOURCES="$CONTENTS/Resources"++rm -rf "$APP_BUNDLE"+mkdir -p "$MACOS_DIR" "$RESOURCES"++# 3. Copy executable+cp "$EXECUTABLE" "$MACOS_DIR/$APP_NAME"++# 4. Copy Info.plist+cp "$INFO_PLIST" "$CONTENTS/Info.plist"++# 5. Copy icon+if [ -f "$ICON" ]; then+ cp "$ICON" "$RESOURCES/AppIcon.icns"+fi++# 6. Compile Asset Catalog → Assets.car + AppIcon.icns+if [ -d "$XCASSETS" ]; then+ echo "→ Compiling assets..."+ actool "$XCASSETS" \+ --compile "$RESOURCES" \+ --platform macosx \+ --minimum-deployment-target 14.0 \+ --app-icon AppIcon \+ --output-partial-info-plist "$OUTPUT_DIR/assetcatalog_generated_info.plist" \+ 2>/dev/null || echo "⚠ actool failed, assets may be missing"+ rm -f "$OUTPUT_DIR/assetcatalog_generated_info.plist"+fi++# 7. Copy SPM resource bundle and compile xcassets.+# SPM Bundle.module looks at: Bundle.main.bundlePath + "/Gridex_Gridex.bundle"+# For .app bundles, bundlePath = "Gridex.app" (the root), so we place it there.+BUNDLE_RESOURCE="$BUILD_DIR/Gridex_Gridex.bundle"+if [ -d "$BUNDLE_RESOURCE" ]; then+ DEST="$CONTENTS/Resources/Gridex_Gridex.bundle"+ cp -R "$BUNDLE_RESOURCE" "$DEST"+ SPM_XCASSETS="$DEST/Assets.xcassets"+ if [ -d "$SPM_XCASSETS" ]; then+ actool "$SPM_XCASSETS" \+ --compile "$DEST" \+ --platform macosx \+ --minimum-deployment-target 14.0 \+ --output-partial-info-plist /dev/null \+ 2>/dev/null || true+ rm -rf "$SPM_XCASSETS"+ fi+fi++# 8. Generate runtime entitlements (strip Xcode-only macros)+RUNTIME_ENT="$OUTPUT_DIR/runtime.entitlements"+/usr/libexec/PlistBuddy -c "Clear dict" "$RUNTIME_ENT" 2>/dev/null || plutil -create xml1 "$RUNTIME_ENT"+/usr/libexec/PlistBuddy -c "Add :com.apple.security.app-sandbox bool false" "$RUNTIME_ENT"+/usr/libexec/PlistBuddy -c "Add :com.apple.security.network.client bool true" "$RUNTIME_ENT"+/usr/libexec/PlistBuddy -c "Add :com.apple.security.network.server bool true" "$RUNTIME_ENT"+/usr/libexec/PlistBuddy -c "Add :com.apple.security.files.user-selected.read-write bool true" "$RUNTIME_ENT"++# 9. Sign+# - Debug: ad-hoc signature so the app runs locally without a network round-trip.+# - Release: full sign + notarize + staple + verify via sign-notarize.sh (which also+# handles inside-out signing when Sparkle.framework is embedded in the future).++if [ "$MODE" = "release" ]; then+ echo "→ Release sign + notarize pipeline..."+ # Keep runtime.entitlements alongside the .app so sign-notarize.sh can pick it up+ # (it sits at $(dirname .app)/runtime.entitlements).+ # (already at $RUNTIME_ENT, no move needed)++ if [ "$NOTARIZE" = "1" ]; then+ "$SCRIPT_DIR/sign-notarize.sh" "$APP_BUNDLE"+ else+ # Sign only, skip notarize (useful during iteration).+ echo "→ Signing only (NOTARIZE=0)..."+ # Resolve SIGN_IDENTITY the same way sign-notarize.sh does+ if [ -z "${SIGN_IDENTITY:-}" ] && [ -f "$PROJECT_DIR/.env" ]; then+ SIGN_IDENTITY=$(grep -E "^SIGN_IDENTITY=" "$PROJECT_DIR/.env" | cut -d= -f2- | tr -d '"')+ fi+ if [ -z "${SIGN_IDENTITY:-}" ]; then+ echo "✗ SIGN_IDENTITY not set. Add it to .env or export it."+ rm -f "$RUNTIME_ENT"+ exit 1+ fi+ codesign --force --deep --options runtime --timestamp \+ --sign "$SIGN_IDENTITY" \+ --entitlements "$RUNTIME_ENT" \+ --generate-entitlement-der \+ "$APP_BUNDLE" 2>&1 | grep -v "unsealed contents" || {+ echo "✗ Signing failed"+ rm -f "$RUNTIME_ENT"+ exit 1+ }+ codesign --verify --deep --strict --verbose=2 "$APP_BUNDLE"+ fi+ rm -f "$RUNTIME_ENT"+else+ echo "→ Ad-hoc signing (debug)..."+ codesign --force --deep --sign - \+ --entitlements "$RUNTIME_ENT" \+ --generate-entitlement-der \+ "$APP_BUNDLE" 2>&1 | grep -v "unsealed contents" || echo "⚠ Signing skipped"+ rm -f "$RUNTIME_ENT"+ xattr -cr "$APP_BUNDLE" 2>/dev/null || true+fi++# 10. Done+APP_SIZE=$(du -sh "$APP_BUNDLE" | cut -f1)+VERSION=$(/usr/libexec/PlistBuddy -c "Print :CFBundleShortVersionString" "$CONTENTS/Info.plist")+echo ""+echo "✓ $APP_NAME.app v$VERSION ($MODE, $APP_SIZE)"+echo " $APP_BUNDLE"+echo ""+if [ "$MODE" = "release" ]; then+ echo "Next: package into DMG"+ echo " ./scripts/make-dmg.sh"+else+ echo "To install: drag to /Applications or run:"+ echo " open $APP_BUNDLE"+fidiff --git a/scripts/make-dmg.sh b/scripts/make-dmg.shnew file mode 100755index 0000000..cc98511--- /dev/null+++ b/scripts/make-dmg.sh@@ -0,0 +1,67 @@+#!/bin/bash+# make-dmg.sh — Package a signed .app into a DMG, then sign + notarize the DMG.+#+# Usage:+# ./scripts/make-dmg.sh [path-to-app]+# (defaults to dist/Gridex.app)+#+# Env:+# VERSION Override version (default: read from Info.plist)+# ARCH arm64 | x86_64 (default: host uname -m)+# NOTARIZE=0 Skip notarization (for local testing)+# SIGN_IDENTITY Passed through to sign-notarize.sh+# NOTARY_PROFILE Passed through to sign-notarize.sh++set -euo pipefail++APP_PATH="${1:-dist/Gridex.app}"+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"++if [ ! -d "$APP_PATH" ]; then+ echo "✗ .app not found: $APP_PATH"+ echo " Run ./scripts/build-app.sh release first."+ exit 1+fi++APP_NAME="$(basename "$APP_PATH" .app)"+VERSION="${VERSION:-$(/usr/libexec/PlistBuddy -c "Print :CFBundleShortVersionString" "$APP_PATH/Contents/Info.plist")}"+ARCH="${ARCH:-$(uname -m)}"+NOTARIZE="${NOTARIZE:-1}"++OUTPUT_DIR="$PROJECT_DIR/dist"+DMG_PATH="$OUTPUT_DIR/${APP_NAME}-${VERSION}-${ARCH}.dmg"++echo "═══════════════════════════════════════════"+echo " Packaging DMG"+echo " App: $APP_PATH"+echo " Version: $VERSION"+echo " Arch: $ARCH"+echo " Output: $DMG_PATH"+echo "═══════════════════════════════════════════"++# Stage: .app + /Applications symlink for drag-to-install UX+STAGING="/tmp/gridex-dmg-staging"+rm -rf "$STAGING"+mkdir -p "$STAGING"+cp -R "$APP_PATH" "$STAGING/"+ln -s /Applications "$STAGING/Applications"++rm -f "$DMG_PATH"+hdiutil create \+ -volname "${APP_NAME} ${VERSION}" \+ -srcfolder "$STAGING" \+ -ov -format UDZO \+ "$DMG_PATH"++rm -rf "$STAGING"++echo "✓ DMG created: $DMG_PATH"++if [ "$NOTARIZE" = "1" ]; then+ echo ""+ "$SCRIPT_DIR/sign-notarize.sh" "$DMG_PATH"+else+ echo "⚠ Skipped notarization (NOTARIZE=0). Sign + notarize manually with:"+ echo " ./scripts/sign-notarize.sh $DMG_PATH"+fidiff --git a/scripts/release.sh b/scripts/release.shnew file mode 100755index 0000000..3549fee--- /dev/null+++ b/scripts/release.sh@@ -0,0 +1,43 @@+#!/bin/bash+# release.sh — Full release pipeline in one command:+# build → sign → notarize .app → package DMG → sign → notarize DMG+#+# Usage:+# ./scripts/release.sh+#+# Env:+# SIGN_IDENTITY, NOTARY_PROFILE, NOTARIZE — same as build-app.sh / sign-notarize.sh+#+# Produces: dist/Gridex-<version>-<arch>.dmg (notarized, stapled, ready to ship)++set -euo pipefail++SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"++cd "$PROJECT_DIR"++VERSION=$(/usr/libexec/PlistBuddy -c "Print :CFBundleShortVersionString" macos/Resources/Info.plist)+ARCH=$(uname -m)++echo "═══════════════════════════════════════════"+echo " Gridex Release Pipeline"+echo " Version: $VERSION"+echo " Arch: $ARCH"+echo "═══════════════════════════════════════════"++# 1. Build + sign + notarize the .app+"$SCRIPT_DIR/build-app.sh" release++# 2. Package + sign + notarize the DMG+"$SCRIPT_DIR/make-dmg.sh"++echo ""+echo "═══════════════════════════════════════════"+echo " ✓ Release artifacts:"+ls -lh "$PROJECT_DIR/dist/"*.dmg 2>/dev/null || true+echo "═══════════════════════════════════════════"+echo ""+echo "Next:"+echo " • Upload DMG to R2: wrangler r2 object put gridex-downloads/releases/Gridex-${VERSION}-${ARCH}.dmg --file dist/Gridex-${VERSION}-${ARCH}.dmg"+echo " • Update landing env: NEXT_PUBLIC_DOWNLOAD_MAC_ARM64=https://downloads.gridex.app/releases/Gridex-${VERSION}-${ARCH}.dmg"diff --git a/scripts/sign-notarize.sh b/scripts/sign-notarize.shnew file mode 100755index 0000000..d901791--- /dev/null+++ b/scripts/sign-notarize.sh@@ -0,0 +1,154 @@+#!/bin/bash+# sign-notarize.sh — Sign + Notarize a macOS .app or .dmg for distribution+#+# Usage:+# ./scripts/sign-notarize.sh <path-to-app-or-dmg>+#+# Env:+# SIGN_IDENTITY SHA-1 or full name of Developer ID Application cert.+# Defaults to the Gridex production cert (16/4/26, team W3C6S577FM).+# NOTARY_PROFILE notarytool keychain profile name (default: gridex-notarize).+# SKIP_SIGN=1 Skip resigning (useful when already signed, just notarize).+#+# Flow:+# .app → sign (inside-out if Sparkle present) → zip → submit → wait → staple → verify+# .dmg → sign → submit → wait → staple → verify++set -euo pipefail++if [ -z "${1:-}" ]; then+ echo "Usage: $0 <path-to-app-or-dmg>"+ exit 1+fi++TARGET="$1"++if [ ! -e "$TARGET" ]; then+ echo "✗ Not found: $TARGET"+ exit 1+fi++# SIGN_IDENTITY: SHA-1 fingerprint or common name of your Developer ID Application cert.+# Not a secret — certs are public. Set via .env or export before running.+# Fall back to "-" (ad-hoc) if unset, so forks can build without an Apple account.+SIGN_IDENTITY="${SIGN_IDENTITY:-${GRIDEX_SIGN_IDENTITY:-}}"+if [ -z "$SIGN_IDENTITY" ] && [ -f "$(dirname "$0")/../.env" ]; then+ SIGN_IDENTITY=$(grep -E "^SIGN_IDENTITY=" "$(dirname "$0")/../.env" | cut -d= -f2- | tr -d '"')+fi+if [ -z "$SIGN_IDENTITY" ]; then+ echo "✗ SIGN_IDENTITY not set. Set it in .env or export it:"+ echo " echo 'SIGN_IDENTITY=<your-sha1-or-cert-name>' >> .env"+ echo " Find your cert with: security find-identity -v -p codesigning"+ exit 1+fi++NOTARY_PROFILE="${NOTARY_PROFILE:-gridex-notarize}"+SKIP_SIGN="${SKIP_SIGN:-0}"++echo "═══════════════════════════════════════════"+echo " Sign + Notarize"+echo " Target: $TARGET"+echo " Identity: $SIGN_IDENTITY"+echo " Profile: $NOTARY_PROFILE"+echo "═══════════════════════════════════════════"++EXT="${TARGET##*.}"++sign_app() {+ local app="$1"++ # Inside-out: if Sparkle.framework is embedded, sign its nested helpers first+ local sparkle="$app/Contents/Frameworks/Sparkle.framework"+ if [ -d "$sparkle/Versions/B" ]; then+ echo "→ Signing Sparkle helpers (inside-out)..."+ codesign --force --options runtime --timestamp \+ --sign "$SIGN_IDENTITY" \+ "$sparkle/Versions/B/Autoupdate" \+ "$sparkle/Versions/B/Updater.app" 2>&1 | grep -v "unsealed contents" || true+ codesign --force --options runtime --timestamp \+ --sign "$SIGN_IDENTITY" \+ "$sparkle" 2>&1 | grep -v "unsealed contents" || true+ fi++ # Entitlements live alongside the runtime (generated by build-app.sh)+ local ent_arg=""+ local runtime_ent="$(dirname "$app")/runtime.entitlements"+ if [ -f "$runtime_ent" ]; then+ ent_arg="--entitlements $runtime_ent --generate-entitlement-der"+ fi++ echo "→ Signing app bundle..."+ # shellcheck disable=SC2086+ codesign --force --deep --options runtime --timestamp \+ --sign "$SIGN_IDENTITY" \+ $ent_arg \+ "$app" 2>&1 | grep -v "unsealed contents" || {+ echo "✗ codesign failed"+ exit 1+ }+}++verify_app() {+ local app="$1"+ echo "→ Verifying signature..."+ codesign --verify --deep --strict --verbose=2 "$app"+ echo "→ Checking Gatekeeper assessment (pre-notarize, may reject — OK)..."+ spctl -a -t exec -vv "$app" 2>&1 || true+}++notarize() {+ local archive="$1"+ echo "→ Submitting to Apple Notary Service (5-15 min)..."+ xcrun notarytool submit "$archive" \+ --keychain-profile "$NOTARY_PROFILE" \+ --wait+}++if [ "$EXT" = "app" ]; then+ APP_PATH="$TARGET"++ if [ "$SKIP_SIGN" != "1" ]; then+ sign_app "$APP_PATH"+ fi+ verify_app "$APP_PATH"++ ZIP_PATH="$(dirname "$APP_PATH")/$(basename "$APP_PATH" .app).zip"+ echo "→ Creating zip for notarization..."+ rm -f "$ZIP_PATH"+ ditto -c -k --keepParent "$APP_PATH" "$ZIP_PATH"++ notarize "$ZIP_PATH"+ rm -f "$ZIP_PATH"++ echo "→ Stapling notarization ticket..."+ xcrun stapler staple "$APP_PATH"++ echo "→ Final Gatekeeper check..."+ spctl -a -t exec -vv "$APP_PATH"++ echo ""+ echo "✓ Done: $APP_PATH"++elif [ "$EXT" = "dmg" ]; then+ DMG_PATH="$TARGET"++ if [ "$SKIP_SIGN" != "1" ]; then+ echo "→ Signing DMG..."+ codesign --force --sign "$SIGN_IDENTITY" --timestamp "$DMG_PATH"+ fi++ notarize "$DMG_PATH"++ echo "→ Stapling notarization ticket..."+ xcrun stapler staple "$DMG_PATH"++ echo "→ Final Gatekeeper check..."+ spctl -a -t open --context context:primary-signature -vv "$DMG_PATH"++ echo ""+ echo "✓ Done: $DMG_PATH"++else+ echo "✗ Target must be .app or .dmg (got .$EXT)"+ exit 1+fidiff --git a/windows/Gridex.slnx b/windows/Gridex.slnxnew file mode 100644index 0000000..5f7f61c--- /dev/null+++ b/windows/Gridex.slnx@@ -0,0 +1,10 @@+<Solution>+ <Configurations>+ <Platform Name="ARM64" />+ <Platform Name="x64" />+ <Platform Name="x86" />+ </Configurations>+ <Project Path="Gridex/Gridex.vcxproj" Id="89a0fae9-44a2-4889-9bd1-50998c237d7c">+ <Deploy />+ </Project>+</Solution>diff --git a/windows/Gridex/AiService.cpp b/windows/Gridex/AiService.cppnew file mode 100644index 0000000..e699757--- /dev/null+++ b/windows/Gridex/AiService.cpp@@ -0,0 +1,411 @@+#define WIN32_LEAN_AND_MEAN+#include <winsock2.h>+#include <windows.h>+#include "Models/AiService.h"+#include <nlohmann/json.hpp>++// cpp-httplib for HTTP client — suppress deprecated SSL API warnings+#pragma warning(push)+#pragma warning(disable: 4996)+#define CPPHTTPLIB_OPENSSL_SUPPORT+#include <httplib.h>+#pragma warning(pop)++namespace DBModels+{+ // Trim leading/trailing whitespace from a wide string+ static std::wstring trimWs(const std::wstring& s)+ {+ size_t start = s.find_first_not_of(L" \t\r\n");+ if (start == std::wstring::npos) return {};+ size_t end = s.find_last_not_of(L" \t\r\n");+ return s.substr(start, end - start + 1);+ }++ std::string AiService::toUtf8(const std::wstring& wstr)+ {+ if (wstr.empty()) return {};+ int size = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(),+ static_cast<int>(wstr.size()), nullptr, 0, nullptr, nullptr);+ std::string result(size, '\0');+ WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(),+ static_cast<int>(wstr.size()), &result[0], size, nullptr, nullptr);+ return result;+ }++ std::wstring AiService::fromUtf8(const std::string& str)+ {+ if (str.empty()) return {};+ int size = MultiByteToWideChar(CP_UTF8, 0, str.c_str(),+ static_cast<int>(str.size()), nullptr, 0);+ std::wstring result(size, L'\0');+ MultiByteToWideChar(CP_UTF8, 0, str.c_str(),+ static_cast<int>(str.size()), &result[0], size);+ return result;+ }++ std::wstring AiService::SendChat(+ const std::vector<ChatMessage>& messages,+ const std::wstring& systemPrompt)+ {+ switch (config_.provider)+ {+ case AiProvider::Anthropic: return CallAnthropic(messages, systemPrompt);+ case AiProvider::OpenAI: return CallOpenAI(messages, systemPrompt);+ case AiProvider::Ollama: return CallOllama(messages, systemPrompt);+ case AiProvider::Gemini: return CallGemini(messages, systemPrompt);+ case AiProvider::OpenRouter: return CallOpenRouter(messages, systemPrompt);+ default: return L"Unsupported AI provider";+ }+ }++ std::wstring AiService::TextToSql(+ const std::wstring& naturalLanguage,+ const std::wstring& schemaDescription)+ {+ std::wstring systemPrompt =+ L"You are a SQL expert. Convert natural language to SQL queries. "+ L"Only output the SQL query, no explanations.\n\n"+ L"Database schema:\n" + schemaDescription;++ std::vector<ChatMessage> messages;+ messages.push_back({ L"user", naturalLanguage });++ return SendChat(messages, systemPrompt);+ }++ // ── Anthropic Messages API ──────────────────────+ std::wstring AiService::CallAnthropic(+ const std::vector<ChatMessage>& messages,+ const std::wstring& systemPrompt)+ {+ httplib::Client cli("https://api.anthropic.com");+ cli.set_connection_timeout(30);+ cli.set_read_timeout(60);++ // Validate API key+ auto apiKey = trimWs(config_.apiKey);+ if (apiKey.empty())+ return L"Error: Anthropic API key is missing. Set it in Settings.";++ nlohmann::json body;+ auto model = trimWs(config_.model);+ body["model"] = toUtf8(model.empty() ? L"claude-sonnet-4-20250514" : model);+ body["max_tokens"] = 2048;++ if (!systemPrompt.empty())+ body["system"] = toUtf8(systemPrompt);++ nlohmann::json msgs = nlohmann::json::array();+ for (auto& m : messages)+ {+ nlohmann::json msg;+ msg["role"] = toUtf8(m.role);+ msg["content"] = toUtf8(m.content);+ msgs.push_back(msg);+ }+ body["messages"] = msgs;++ httplib::Headers headers = {+ {"x-api-key", toUtf8(apiKey)},+ {"anthropic-version", "2023-06-01"}+ };++ auto res = cli.Post("/v1/messages", headers, body.dump(), "application/json");+ if (!res)+ return L"Error: Failed to connect to Anthropic API";++ if (res->status != 200)+ return fromUtf8("Error " + std::to_string(res->status) ++ " (model=" + toUtf8(model) + "): " + res->body);++ try+ {+ auto json = nlohmann::json::parse(res->body);+ if (json.contains("content") && !json["content"].empty())+ {+ auto& first = json["content"][0];+ if (first.contains("text"))+ return fromUtf8(first["text"].get<std::string>());+ }+ }+ catch (const std::exception& e)+ {+ return fromUtf8(std::string("Parse error: ") + e.what());+ }+ return L"No response content";+ }++ // ── OpenAI Chat Completions API ─────────────────+ std::wstring AiService::CallOpenAI(+ const std::vector<ChatMessage>& messages,+ const std::wstring& systemPrompt)+ {+ httplib::Client cli("https://api.openai.com");+ cli.set_connection_timeout(30);+ cli.set_read_timeout(60);++ // Validate API key+ auto apiKey = trimWs(config_.apiKey);+ if (apiKey.empty())+ return L"Error: OpenAI API key is missing. Set it in Settings.";++ nlohmann::json body;+ auto model = trimWs(config_.model);+ body["model"] = toUtf8(model.empty() ? L"gpt-4o" : model);+ body["max_tokens"] = 2048;++ nlohmann::json msgs = nlohmann::json::array();+ if (!systemPrompt.empty())+ {+ nlohmann::json sysMsg;+ sysMsg["role"] = "system";+ sysMsg["content"] = toUtf8(systemPrompt);+ msgs.push_back(sysMsg);+ }+ for (auto& m : messages)+ {+ nlohmann::json msg;+ msg["role"] = toUtf8(m.role);+ msg["content"] = toUtf8(m.content);+ msgs.push_back(msg);+ }+ body["messages"] = msgs;++ httplib::Headers headers = {+ {"Authorization", "Bearer " + toUtf8(apiKey)}+ };++ auto res = cli.Post("/v1/chat/completions", headers, body.dump(), "application/json");+ if (!res)+ return L"Error: Failed to connect to OpenAI API";++ if (res->status != 200)+ return fromUtf8("Error " + std::to_string(res->status) ++ " (model=" + toUtf8(model) + "): " + res->body);++ try+ {+ auto json = nlohmann::json::parse(res->body);+ if (json.contains("choices") && !json["choices"].empty())+ return fromUtf8(json["choices"][0]["message"]["content"].get<std::string>());+ }+ catch (const std::exception& e)+ {+ return fromUtf8(std::string("Parse error: ") + e.what());+ }+ return L"No response content";+ }++ // ── Ollama API (local) ──────────────────────────+ std::wstring AiService::CallOllama(+ const std::vector<ChatMessage>& messages,+ const std::wstring& systemPrompt)+ {+ auto endpointW = trimWs(config_.ollamaEndpoint);+ std::string endpoint = toUtf8(+ endpointW.empty() ? L"http://localhost:11434" : endpointW);+ httplib::Client cli(endpoint);+ cli.set_connection_timeout(10);+ cli.set_read_timeout(120); // Ollama can be slow++ nlohmann::json body;+ auto model = trimWs(config_.model);+ body["model"] = toUtf8(model.empty() ? L"llama3" : model);+ body["stream"] = false;++ nlohmann::json msgs = nlohmann::json::array();+ if (!systemPrompt.empty())+ {+ nlohmann::json sysMsg;+ sysMsg["role"] = "system";+ sysMsg["content"] = toUtf8(systemPrompt);+ msgs.push_back(sysMsg);+ }+ for (auto& m : messages)+ {+ nlohmann::json msg;+ msg["role"] = toUtf8(m.role);+ msg["content"] = toUtf8(m.content);+ msgs.push_back(msg);+ }+ body["messages"] = msgs;++ auto res = cli.Post("/api/chat", body.dump(), "application/json");+ if (!res)+ return L"Error: Failed to connect to Ollama (is it running?)";++ if (res->status != 200)+ return fromUtf8("Error " + std::to_string(res->status) + ": " + res->body);++ try+ {+ auto json = nlohmann::json::parse(res->body);+ if (json.contains("message") && json["message"].contains("content"))+ return fromUtf8(json["message"]["content"].get<std::string>());+ }+ catch (const std::exception& e)+ {+ return fromUtf8(std::string("Parse error: ") + e.what());+ }+ return L"No response content";+ }++ // ── Google Gemini generateContent API ────────────+ //+ // POST https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={KEY}+ //+ // Body shape differs from OpenAI/Anthropic:+ // - Messages live under "contents" as { role, parts:[{text}] }+ // - The assistant role is "model", not "assistant"+ // - System prompt goes in a top-level "systemInstruction" object+ // - Max tokens is inside "generationConfig.maxOutputTokens"+ std::wstring AiService::CallGemini(+ const std::vector<ChatMessage>& messages,+ const std::wstring& systemPrompt)+ {+ httplib::Client cli("https://generativelanguage.googleapis.com");+ cli.set_connection_timeout(30);+ cli.set_read_timeout(60);++ auto apiKey = trimWs(config_.apiKey);+ if (apiKey.empty())+ return L"Error: Gemini API key is missing. Set it in Settings.";++ auto model = trimWs(config_.model);+ if (model.empty()) model = L"gemini-2.0-flash";++ nlohmann::json body;+ body["generationConfig"]["maxOutputTokens"] = 2048;++ if (!systemPrompt.empty())+ {+ nlohmann::json sys;+ sys["parts"] = nlohmann::json::array({+ nlohmann::json{{"text", toUtf8(systemPrompt)}}+ });+ body["systemInstruction"] = sys;+ }++ nlohmann::json contents = nlohmann::json::array();+ for (auto& m : messages)+ {+ // Map roles: user→user, assistant→model. System messages are+ // promoted to systemInstruction above and skipped here.+ std::wstring role = m.role;+ if (role == L"assistant") role = L"model";+ else if (role == L"system") continue;++ nlohmann::json entry;+ entry["role"] = toUtf8(role);+ entry["parts"] = nlohmann::json::array({+ nlohmann::json{{"text", toUtf8(m.content)}}+ });+ contents.push_back(entry);+ }+ body["contents"] = contents;++ std::string path = "/v1beta/models/" + toUtf8(model)+ + ":generateContent?key=" + toUtf8(apiKey);++ auto res = cli.Post(path, body.dump(), "application/json");+ if (!res)+ return L"Error: Failed to connect to Gemini API";++ if (res->status != 200)+ return fromUtf8("Error " + std::to_string(res->status) ++ " (model=" + toUtf8(model) + "): " + res->body);++ try+ {+ auto json = nlohmann::json::parse(res->body);+ if (json.contains("candidates") && !json["candidates"].empty())+ {+ auto& cand = json["candidates"][0];+ if (cand.contains("content") && cand["content"].contains("parts"))+ {+ auto& parts = cand["content"]["parts"];+ if (!parts.empty() && parts[0].contains("text"))+ return fromUtf8(parts[0]["text"].get<std::string>());+ }+ }+ }+ catch (const std::exception& e)+ {+ return fromUtf8(std::string("Parse error: ") + e.what());+ }+ return L"No response content";+ }++ // ── OpenRouter chat completions ────────────────+ //+ // OpenRouter is OpenAI-protocol-compatible, so the request/response+ // shapes are identical to CallOpenAI. Only the host and the optional+ // HTTP-Referer / X-Title headers (used by OpenRouter for usage+ // attribution) differ.+ std::wstring AiService::CallOpenRouter(+ const std::vector<ChatMessage>& messages,+ const std::wstring& systemPrompt)+ {+ httplib::Client cli("https://openrouter.ai");+ cli.set_connection_timeout(30);+ cli.set_read_timeout(60);++ auto apiKey = trimWs(config_.apiKey);+ if (apiKey.empty())+ return L"Error: OpenRouter API key is missing. Set it in Settings.";++ nlohmann::json body;+ auto model = trimWs(config_.model);+ // OpenRouter requires a fully-qualified model slug like+ // "openai/gpt-4o" or "anthropic/claude-3.5-sonnet". Pick a sane+ // default that's cheap and always available.+ body["model"] = toUtf8(model.empty() ? L"openai/gpt-4o-mini" : model);+ body["max_tokens"] = 2048;++ nlohmann::json msgs = nlohmann::json::array();+ if (!systemPrompt.empty())+ {+ nlohmann::json sysMsg;+ sysMsg["role"] = "system";+ sysMsg["content"] = toUtf8(systemPrompt);+ msgs.push_back(sysMsg);+ }+ for (auto& m : messages)+ {+ nlohmann::json msg;+ msg["role"] = toUtf8(m.role);+ msg["content"] = toUtf8(m.content);+ msgs.push_back(msg);+ }+ body["messages"] = msgs;++ httplib::Headers headers = {+ {"Authorization", "Bearer " + toUtf8(apiKey)},+ // Optional attribution headers recommended by OpenRouter.+ {"HTTP-Referer", "https://gridex.app"},+ {"X-Title", "Gridex"}+ };++ auto res = cli.Post("/api/v1/chat/completions", headers,+ body.dump(), "application/json");+ if (!res)+ return L"Error: Failed to connect to OpenRouter API";++ if (res->status != 200)+ return fromUtf8("Error " + std::to_string(res->status) ++ " (model=" + toUtf8(model) + "): " + res->body);++ try+ {+ auto json = nlohmann::json::parse(res->body);+ if (json.contains("choices") && !json["choices"].empty())+ return fromUtf8(json["choices"][0]["message"]["content"].get<std::string>());+ }+ catch (const std::exception& e)+ {+ return fromUtf8(std::string("Parse error: ") + e.what());+ }+ return L"No response content";+ }+}diff --git a/windows/Gridex/App.xaml b/windows/Gridex/App.xamlnew file mode 100644index 0000000..f712493--- /dev/null+++ b/windows/Gridex/App.xaml@@ -0,0 +1,16 @@+<?xml version="1.0" encoding="utf-8"?>+<Application+ x:Class="Gridex.App"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:local="using:Gridex">+ <Application.Resources>+ <ResourceDictionary>+ <ResourceDictionary.MergedDictionaries>+ <XamlControlsResources xmlns="using:Microsoft.UI.Xaml.Controls" />+ <!-- Other merged dictionaries here -->+ </ResourceDictionary.MergedDictionaries>+ <!-- Other app resources here -->+ </ResourceDictionary>+ </Application.Resources>+</Application>diff --git a/windows/Gridex/App.xaml.cpp b/windows/Gridex/App.xaml.cppnew file mode 100644index 0000000..9dc3d61--- /dev/null+++ b/windows/Gridex/App.xaml.cpp@@ -0,0 +1,181 @@+#include "pch.h"+#include "xaml-includes.h"+#include "App.xaml.h"+#include "MainWindow.xaml.h"+#include <shellapi.h>+#include <string>+#include <cwchar>++using namespace winrt;+using namespace Microsoft::UI::Xaml;++#include <microsoft.ui.xaml.window.h>++namespace winrt::Gridex::implementation+{+ // Handle Velopack lifecycle hook flags passed by Setup.exe / Update.exe.+ //+ // When the Velopack installer runs, it launches the main app exe with+ // one of these flags and expects the process to exit cleanly within+ // 30 seconds. Without this handler the app tries to launch its full+ // WinUI main window instead, which:+ // - Shows a visible Gridex window while Setup.exe is still running+ // - Never exits the hook process+ // - Causes Velopack to display the error:+ // "Installation has completed, but the application install+ // hook failed. It may not have installed correctly."+ //+ // Hook flags that MUST exit-on-sight:+ // --veloapp-install first-time install, after files extracted+ // --veloapp-updated after auto-update applied (new version)+ // --veloapp-obsolete before old version is removed post-update+ // --veloapp-uninstall user uninstalling via Add/Remove Programs+ //+ // --veloapp-firstrun is a normal launch (just with a flag) and must+ // NOT exit -- the app should start as usual.+ //+ // We avoid linking the full Velopack C++ SDK for v1 and just probe+ // argv directly via CommandLineToArgvW. This is enough to silence+ // the install-hook error dialog; full update orchestration would+ // require the real SDK (phase 02 of the installer plan).+ static void HandleVelopackLifecycleFlags()+ {+ int argc = 0;+ LPWSTR* argv = CommandLineToArgvW(GetCommandLineW(), &argc);+ if (!argv) return;++ bool exitNow = false;+ for (int i = 1; i < argc; ++i)+ {+ if (wcscmp(argv[i], L"--veloapp-install") == 0 ||+ wcscmp(argv[i], L"--veloapp-updated") == 0 ||+ wcscmp(argv[i], L"--veloapp-obsolete") == 0 ||+ wcscmp(argv[i], L"--veloapp-uninstall") == 0)+ {+ exitNow = true;+ break;+ }+ }+ LocalFree(argv);++ if (exitNow)+ {+ ::ExitProcess(0);+ }+ }++ // Detect whether the Microsoft Edge WebView2 Runtime is installed.+ // Gridex bundles Microsoft.Web.WebView2.Core.dll (the projection) but+ // the actual WebView2 runtime is a separate system component. On+ // Windows 11 and recently-updated Windows 10 (20H2+) it ships with+ // Edge automatically; fresh/stripped installs may be missing it and+ // any Gridex feature that uses a WebView2 element (ER Diagram) will+ // crash. Probe the registry key documented by Microsoft for WebView2+ // Runtime detection.+ static bool WebView2RuntimeIsInstalled()+ {+ static const wchar_t* const kClientsSubKey =+ L"SOFTWARE\\WOW6432Node\\Microsoft\\EdgeUpdate\\Clients\\"+ L"{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}";+ static const wchar_t* const kClientsSubKey32 =+ L"SOFTWARE\\Microsoft\\EdgeUpdate\\Clients\\"+ L"{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}";++ HKEY hKey = nullptr;+ for (HKEY root : { HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER })+ {+ if (RegOpenKeyExW(root, kClientsSubKey, 0, KEY_READ, &hKey) == ERROR_SUCCESS)+ {+ RegCloseKey(hKey);+ return true;+ }+ if (RegOpenKeyExW(root, kClientsSubKey32, 0, KEY_READ, &hKey) == ERROR_SUCCESS)+ {+ RegCloseKey(hKey);+ return true;+ }+ }+ return false;+ }++ // If WebView2 Runtime is missing, run the bundled+ // MicrosoftEdgeWebView2Setup.exe bootstrap installer silently and wait+ // up to 2 minutes for it to finish. Best-effort: any failure is+ // swallowed because Gridex's startup path doesn't require WebView2 --+ // only the ER Diagram feature does. Worst case the user sees a+ // one-time startup delay on first run of a fresh install.+ static void EnsureWebView2Runtime()+ {+ if (WebView2RuntimeIsInstalled()) return;++ // Resolve path to the bundled bootstrap next to Gridex.exe.+ wchar_t modulePath[MAX_PATH]{};+ if (GetModuleFileNameW(nullptr, modulePath, MAX_PATH) == 0) return;++ std::wstring path(modulePath);+ auto slash = path.find_last_of(L'\\');+ if (slash == std::wstring::npos) return;+ std::wstring installer = path.substr(0, slash) + L"\\MicrosoftEdgeWebView2Setup.exe";++ if (GetFileAttributesW(installer.c_str()) == INVALID_FILE_ATTRIBUTES) return;++ SHELLEXECUTEINFOW sei{};+ sei.cbSize = sizeof(sei);+ sei.fMask = SEE_MASK_NOCLOSEPROCESS;+ sei.lpVerb = L"open";+ sei.lpFile = installer.c_str();+ sei.lpParameters = L"/silent /install";+ sei.nShow = SW_HIDE;+ if (ShellExecuteExW(&sei) && sei.hProcess)+ {+ WaitForSingleObject(sei.hProcess, 120'000); // 2 min cap+ CloseHandle(sei.hProcess);+ }+ }++ HWND App::MainHwnd = nullptr;+ /// <summary>+ /// Initializes the singleton application object. This is the first line of authored code+ /// executed, and as such is the logical equivalent of main() or WinMain().+ /// </summary>+ App::App()+ {+ // CRITICAL: run BEFORE anything else. If the process was launched+ // by Velopack as an install/uninstall/updated/obsolete hook, exit+ // immediately so the installer's hook wait completes successfully+ // and the full WinUI main window never opens during an install.+ HandleVelopackLifecycleFlags();++ // Bootstrap the WebView2 Runtime before any XAML / WinAppSDK code+ // touches WebView2. Fast no-op (single registry probe) once the+ // runtime is installed.+ EnsureWebView2Runtime();++ // Xaml objects should not call InitializeComponent during construction.+ // See https://github.com/microsoft/cppwinrt/tree/master/nuget#initializecomponent++#if defined _DEBUG && !defined DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION+ UnhandledException([](IInspectable const&, UnhandledExceptionEventArgs const& e)+ {+ if (IsDebuggerPresent())+ {+ auto errorMessage = e.Message();+ __debugbreak();+ }+ });+#endif+ }++ /// <summary>+ /// Invoked when the application is launched.+ /// </summary>+ /// <param name="e">Details about the launch request and process.</param>+ void App::OnLaunched([[maybe_unused]] LaunchActivatedEventArgs const& e)+ {+ window = make<MainWindow>();+ window.Activate();++ auto windowNative = window.as<IWindowNative>();+ windowNative->get_WindowHandle(&MainHwnd);+ }+}diff --git a/windows/Gridex/App.xaml.h b/windows/Gridex/App.xaml.hnew file mode 100644index 0000000..416f33e--- /dev/null+++ b/windows/Gridex/App.xaml.h@@ -0,0 +1,17 @@+#pragma once++#include "App.xaml.g.h"++namespace winrt::Gridex::implementation+{+ struct App : AppT<App>+ {+ App();++ void OnLaunched(Microsoft::UI::Xaml::LaunchActivatedEventArgs const&);+ static HWND MainHwnd;++ private:+ winrt::Microsoft::UI::Xaml::Window window{ nullptr };+ };+}diff --git a/windows/Gridex/AppSettings.cpp b/windows/Gridex/AppSettings.cppnew file mode 100644index 0000000..1e9fcdb--- /dev/null+++ b/windows/Gridex/AppSettings.cpp@@ -0,0 +1,365 @@+#include <windows.h>+#include <shlobj.h>+#include <wincred.h>+#pragma comment(lib, "Advapi32.lib")+#include "Models/AppSettings.h"+#include <fstream>+#include <sstream>++namespace DBModels+{+ // ── Helpers ──────────────────────────────────────────++ static std::string toUtf8(const std::wstring& wstr)+ {+ if (wstr.empty()) return {};+ int sz = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(),+ static_cast<int>(wstr.size()), nullptr, 0, nullptr, nullptr);+ std::string out(sz, '\0');+ WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(),+ static_cast<int>(wstr.size()), &out[0], sz, nullptr, nullptr);+ return out;+ }++ static std::wstring fromUtf8(const std::string& utf8)+ {+ if (utf8.empty()) return {};+ int sz = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(),+ static_cast<int>(utf8.size()), nullptr, 0);+ std::wstring out(sz, L'\0');+ MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(),+ static_cast<int>(utf8.size()), &out[0], sz);+ return out;+ }++ static std::wstring escapeJson(const std::wstring& s)+ {+ std::wstring out;+ out.reserve(s.size() + 2);+ for (wchar_t c : s)+ {+ if (c == L'"') out += L"\\\"";+ else if (c == L'\\') out += L"\\\\";+ else if (c == L'\n') out += L"\\n";+ else if (c == L'\r') out += L"\\r";+ else if (c == L'\t') out += L"\\t";+ else out += c;+ }+ return out;+ }++ // Simple "key":"value" extractor for minimal JSON (no external deps)+ static std::wstring extractString(const std::wstring& json, const std::wstring& key)+ {+ std::wstring needle = L"\"" + key + L"\":";+ size_t pos = json.find(needle);+ if (pos == std::wstring::npos) return {};+ pos += needle.size();+ while (pos < json.size() && (json[pos] == L' ' || json[pos] == L'\t')) pos++;+ if (pos >= json.size() || json[pos] != L'"') return {};+ pos++; // skip opening quote+ std::wstring result;+ while (pos < json.size() && json[pos] != L'"')+ {+ if (json[pos] == L'\\' && pos + 1 < json.size())+ {+ wchar_t next = json[pos + 1];+ if (next == L'"') { result += L'"'; pos += 2; }+ else if (next == L'\\') { result += L'\\'; pos += 2; }+ else if (next == L'n') { result += L'\n'; pos += 2; }+ else if (next == L'r') { result += L'\r'; pos += 2; }+ else if (next == L't') { result += L'\t'; pos += 2; }+ else { result += json[pos]; pos++; }+ }+ else+ {+ result += json[pos++];+ }+ }+ return result;+ }++ static int extractInt(const std::wstring& json, const std::wstring& key, int defaultVal)+ {+ std::wstring needle = L"\"" + key + L"\":";+ size_t pos = json.find(needle);+ if (pos == std::wstring::npos) return defaultVal;+ pos += needle.size();+ while (pos < json.size() && (json[pos] == L' ' || json[pos] == L'\t')) pos++;+ std::wstring num;+ if (pos < json.size() && (json[pos] == L'-' || iswdigit(json[pos])))+ {+ num += json[pos++];+ while (pos < json.size() && iswdigit(json[pos])) num += json[pos++];+ }+ if (num.empty()) return defaultVal;+ try { return std::stoi(num); } catch (...) { return defaultVal; }+ }++ static bool extractBool(const std::wstring& json, const std::wstring& key, bool defaultVal)+ {+ std::wstring needle = L"\"" + key + L"\":";+ size_t pos = json.find(needle);+ if (pos == std::wstring::npos) return defaultVal;+ pos += needle.size();+ while (pos < json.size() && (json[pos] == L' ' || json[pos] == L'\t')) pos++;+ if (json.compare(pos, 4, L"true") == 0) return true;+ if (json.compare(pos, 5, L"false") == 0) return false;+ return defaultVal;+ }++ // Extract a JSON array of strings: "key": ["a", "b", "c"]+ static std::vector<std::wstring> extractStringArray(+ const std::wstring& json, const std::wstring& key)+ {+ std::vector<std::wstring> result;+ std::wstring needle = L"\"" + key + L"\":";+ size_t pos = json.find(needle);+ if (pos == std::wstring::npos) return result;+ pos += needle.size();+ while (pos < json.size() && (json[pos] == L' ' || json[pos] == L'\t' ||+ json[pos] == L'\r' || json[pos] == L'\n')) pos++;+ if (pos >= json.size() || json[pos] != L'[') return result;+ pos++; // skip '['++ while (pos < json.size())+ {+ while (pos < json.size() && (json[pos] == L' ' || json[pos] == L'\t' ||+ json[pos] == L'\r' || json[pos] == L'\n' || json[pos] == L',')) pos++;+ if (pos >= json.size() || json[pos] == L']') break;+ if (json[pos] != L'"') break;+ pos++; // opening quote+ std::wstring item;+ while (pos < json.size() && json[pos] != L'"')+ {+ if (json[pos] == L'\\' && pos + 1 < json.size())+ {+ wchar_t next = json[pos + 1];+ if (next == L'"') { item += L'"'; pos += 2; }+ else if (next == L'\\') { item += L'\\'; pos += 2; }+ else if (next == L'n') { item += L'\n'; pos += 2; }+ else { item += json[pos]; pos++; }+ }+ else+ {+ item += json[pos++];+ }+ }+ if (pos < json.size()) pos++; // closing quote+ result.push_back(item);+ }+ return result;+ }++ // ── Legacy DataBridge -> Gridex migration ───────────+ //+ // App was renamed from "DataBridge" to "Gridex". Existing users have+ // settings, connection database, and credential vault entries under+ // the old name. Migrate them ONCE on first launch of the renamed app.+ //+ // Idempotent: only runs if Gridex dir is missing AND DataBridge dir exists.+ // Original DataBridge data is preserved (not deleted) so user can roll+ // back if needed.+ //+ // Note: the legacy strings below intentionally hard-code "DataBridge"+ // because this is the OLD name we are migrating FROM. Mass-rename+ // tools must skip this block.+ static constexpr const wchar_t* kLegacyAppName = L"DataBridge";+ static constexpr const wchar_t* kLegacyCredPrefix = L"DataBridge:";+ static constexpr const wchar_t* kLegacyCredFilter = L"DataBridge:*";+ static constexpr const wchar_t* kLegacyDbFilename = L"databridge.db";++ // Recursive directory copy via SHFileOperationW.+ // Source must end with double-null (SHFileOp quirk), so we build a buffer.+ static bool copyDirectory(const std::wstring& src, const std::wstring& dst)+ {+ std::vector<wchar_t> from(src.begin(), src.end());+ from.push_back(L'\0');+ from.push_back(L'\0');++ std::vector<wchar_t> to(dst.begin(), dst.end());+ to.push_back(L'\0');+ to.push_back(L'\0');++ SHFILEOPSTRUCTW op = {};+ op.wFunc = FO_COPY;+ op.pFrom = from.data();+ op.pTo = to.data();+ op.fFlags = FOF_NO_UI | FOF_NOCONFIRMATION |+ FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMMKDIR;+ return SHFileOperationW(&op) == 0;+ }++ // Migrate Windows Credential Vault entries from legacy prefix to "Gridex:".+ // Failures are silently ignored (user can re-enter passwords if needed).+ static void migrateCredentialVault()+ {+ DWORD count = 0;+ PCREDENTIALW* creds = nullptr;+ if (!CredEnumerateW(kLegacyCredFilter, 0, &count, &creds) || !creds)+ return;++ const std::wstring legacyPrefix = kLegacyCredPrefix;+ const size_t legacyPrefixLen = legacyPrefix.size();++ for (DWORD i = 0; i < count; ++i)+ {+ PCREDENTIALW c = creds[i];+ if (!c || !c->TargetName) continue;++ std::wstring oldTarget = c->TargetName;+ if (oldTarget.rfind(legacyPrefix, 0) != 0) continue;+ std::wstring newTarget = L"Gridex:" + oldTarget.substr(legacyPrefixLen);++ // Skip if already migrated+ PCREDENTIALW existing = nullptr;+ if (CredReadW(newTarget.c_str(), CRED_TYPE_GENERIC, 0, &existing))+ {+ CredFree(existing);+ continue;+ }++ CREDENTIALW dst = {};+ dst.Type = CRED_TYPE_GENERIC;+ dst.TargetName = const_cast<LPWSTR>(newTarget.c_str());+ dst.CredentialBlobSize = c->CredentialBlobSize;+ dst.CredentialBlob = c->CredentialBlob;+ dst.Persist = CRED_PERSIST_LOCAL_MACHINE;+ dst.UserName = const_cast<LPWSTR>(L"Gridex");+ CredWriteW(&dst, 0);+ }+ CredFree(creds);+ }++ // Run all migration steps. Idempotent — safe to call on every launch.+ // Static flag avoids redundant filesystem probes on repeated Load/Save calls.+ static void migrateLegacyDataIfNeeded()+ {+ static bool ran = false;+ if (ran) return;+ ran = true;++ wchar_t local[MAX_PATH] = {};+ wchar_t roaming[MAX_PATH] = {};+ SHGetFolderPathW(nullptr, CSIDL_LOCAL_APPDATA, nullptr, 0, local);+ SHGetFolderPathW(nullptr, CSIDL_APPDATA, nullptr, 0, roaming);++ const std::wstring legacyDir = std::wstring(L"\\") + kLegacyAppName;++ // 1. %LOCALAPPDATA%\DataBridge -> %LOCALAPPDATA%\Gridex (settings.json)+ std::wstring localOld = std::wstring(local) + legacyDir;+ std::wstring localNew = std::wstring(local) + L"\\Gridex";+ if (GetFileAttributesW(localNew.c_str()) == INVALID_FILE_ATTRIBUTES &&+ GetFileAttributesW(localOld.c_str()) != INVALID_FILE_ATTRIBUTES)+ {+ copyDirectory(localOld, localNew);+ }++ // 2. %APPDATA%\DataBridge -> %APPDATA%\Gridex (connection store .db)+ std::wstring roamingOld = std::wstring(roaming) + legacyDir;+ std::wstring roamingNew = std::wstring(roaming) + L"\\Gridex";+ if (GetFileAttributesW(roamingNew.c_str()) == INVALID_FILE_ATTRIBUTES &&+ GetFileAttributesW(roamingOld.c_str()) != INVALID_FILE_ATTRIBUTES)+ {+ copyDirectory(roamingOld, roamingNew);+ // Rename the .db file inside the new dir if it kept the old name+ std::wstring oldDbInNew = roamingNew + L"\\" + kLegacyDbFilename;+ std::wstring newDbInNew = roamingNew + L"\\gridex.db";+ if (GetFileAttributesW(oldDbInNew.c_str()) != INVALID_FILE_ATTRIBUTES &&+ GetFileAttributesW(newDbInNew.c_str()) == INVALID_FILE_ATTRIBUTES)+ {+ MoveFileW(oldDbInNew.c_str(), newDbInNew.c_str());+ }+ }++ // 3. Credential vault: DataBridge:* -> Gridex:*+ migrateCredentialVault();+ }++ // ── Path resolution ─────────────────────────────────++ std::wstring AppSettings::GetSettingsPath()+ {+ wchar_t path[MAX_PATH] = {};+ if (FAILED(SHGetFolderPathW(nullptr, CSIDL_LOCAL_APPDATA, nullptr, 0, path)))+ return {};++ // Run legacy migration before computing path so the new dir is+ // populated by the time AppSettings::Load() reads from it.+ migrateLegacyDataIfNeeded();++ std::wstring dir = std::wstring(path) + L"\\Gridex";+ CreateDirectoryW(dir.c_str(), nullptr);+ return dir + L"\\settings.json";+ }++ // ── Load ────────────────────────────────────────────++ AppSettings AppSettings::Load()+ {+ AppSettings s;+ std::wstring path = GetSettingsPath();+ if (path.empty()) return s;++ std::ifstream file(path, std::ios::binary);+ if (!file.is_open()) return s;++ std::string bytes(+ (std::istreambuf_iterator<char>(file)),+ std::istreambuf_iterator<char>());+ file.close();+ if (bytes.empty()) return s;++ // Strip UTF-8 BOM+ if (bytes.size() >= 3 && bytes[0] == '\xEF' &&+ bytes[1] == '\xBB' && bytes[2] == '\xBF')+ bytes = bytes.substr(3);++ std::wstring json = fromUtf8(bytes);++ s.themeIndex = extractInt(json, L"themeIndex", 0);+ s.aiProviderIndex = extractInt(json, L"aiProviderIndex", 0);+ s.aiApiKey = extractString(json, L"aiApiKey");+ s.aiModel = extractString(json, L"aiModel");+ s.ollamaEndpoint = extractString(json, L"ollamaEndpoint");+ s.editorFontSize = extractInt(json, L"editorFontSize", 13);+ s.rowLimit = extractInt(json, L"rowLimit", 100);+ s.lastPageBeforeSettings = extractString(json, L"lastPageBeforeSettings");+ s.connectionGroups = extractStringArray(json, L"connectionGroups");+ return s;+ }++ // ── Save ────────────────────────────────────────────++ bool AppSettings::Save() const+ {+ std::wstring path = GetSettingsPath();+ if (path.empty()) return false;++ std::wstringstream ss;+ ss << L"{\n";+ ss << L" \"themeIndex\": " << themeIndex << L",\n";+ ss << L" \"aiProviderIndex\": " << aiProviderIndex << L",\n";+ ss << L" \"aiApiKey\": \"" << escapeJson(aiApiKey) << L"\",\n";+ ss << L" \"aiModel\": \"" << escapeJson(aiModel) << L"\",\n";+ ss << L" \"ollamaEndpoint\": \"" << escapeJson(ollamaEndpoint) << L"\",\n";+ ss << L" \"editorFontSize\": " << editorFontSize << L",\n";+ ss << L" \"rowLimit\": " << rowLimit << L",\n";+ ss << L" \"lastPageBeforeSettings\": \"" << escapeJson(lastPageBeforeSettings) << L"\",\n";+ ss << L" \"connectionGroups\": [";+ for (size_t i = 0; i < connectionGroups.size(); i++)+ {+ if (i > 0) ss << L", ";+ ss << L"\"" << escapeJson(connectionGroups[i]) << L"\"";+ }+ ss << L"]\n";+ ss << L"}\n";++ std::string utf8 = toUtf8(ss.str());+ std::ofstream file(path, std::ios::binary);+ if (!file.is_open()) return false;+ file.write(utf8.c_str(), utf8.size());+ file.close();+ return true;+ }+}diff --git a/windows/Gridex/Assets/Gridex.ico b/windows/Gridex/Assets/Gridex.iconew file mode 100644index 0000000..0de07e3Binary files /dev/null and b/windows/Gridex/Assets/Gridex.ico differdiff --git a/windows/Gridex/Assets/LockScreenLogo.scale-200.png b/windows/Gridex/Assets/LockScreenLogo.scale-200.pngnew file mode 100644index 0000000..a347ab6Binary files /dev/null and b/windows/Gridex/Assets/LockScreenLogo.scale-200.png differdiff --git a/windows/Gridex/Assets/SplashScreen.scale-200.png b/windows/Gridex/Assets/SplashScreen.scale-200.pngnew file mode 100644index 0000000..200ea36Binary files /dev/null and b/windows/Gridex/Assets/SplashScreen.scale-200.png differdiff --git a/windows/Gridex/Assets/Square150x150Logo.scale-200.png b/windows/Gridex/Assets/Square150x150Logo.scale-200.pngnew file mode 100644index 0000000..0cf2a34Binary files /dev/null and b/windows/Gridex/Assets/Square150x150Logo.scale-200.png differdiff --git a/windows/Gridex/Assets/Square44x44Logo.scale-200.png b/windows/Gridex/Assets/Square44x44Logo.scale-200.pngnew file mode 100644index 0000000..a8e3afdBinary files /dev/null and b/windows/Gridex/Assets/Square44x44Logo.scale-200.png differdiff --git a/windows/Gridex/Assets/Square44x44Logo.targetsize-24_altform-unplated.png b/windows/Gridex/Assets/Square44x44Logo.targetsize-24_altform-unplated.pngnew file mode 100644index 0000000..9e81a10Binary files /dev/null and b/windows/Gridex/Assets/Square44x44Logo.targetsize-24_altform-unplated.png differdiff --git a/windows/Gridex/Assets/StoreLogo.png b/windows/Gridex/Assets/StoreLogo.pngnew file mode 100644index 0000000..f36840aBinary files /dev/null and b/windows/Gridex/Assets/StoreLogo.png differdiff --git a/windows/Gridex/Assets/THIRD-PARTY-NOTICES.txt b/windows/Gridex/Assets/THIRD-PARTY-NOTICES.txtnew file mode 100644index 0000000..01e880a--- /dev/null+++ b/windows/Gridex/Assets/THIRD-PARTY-NOTICES.txt@@ -0,0 +1,176 @@+Gridex - Third-Party Notices+================================++Gridex incorporates components from the projects listed below.+The original copyright notices and the licenses under which Gridex+received such components are set forth below for informational purposes.+Gridex licenses these components under the terms of the licenses+shown below. All other rights are reserved by their respective owners.+++--------------------------------------------------------------------------------+1. D2 (https://github.com/terrastruct/d2)+--------------------------------------------------------------------------------+Used as a bundled CLI binary (Assets/d2/d2.exe) to compile D2 declarative+diagram source into SVG for the ER Diagram feature. Invoked as a separate+process; not statically linked into Gridex.++License: Mozilla Public License 2.0 (MPL-2.0)+Source: https://github.com/terrastruct/d2+License text: see Assets/d2/LICENSE+++--------------------------------------------------------------------------------+2. Microsoft Edge WebView2+--------------------------------------------------------------------------------+Used to host an HTML page that renders the SVG produced by D2 in the+ER Diagram tab. Distributed via NuGet as Microsoft.Web.WebView2.++License: Microsoft Software License Terms for Microsoft Edge WebView2 SDK+ (free for commercial and non-commercial use)+Source: https://developer.microsoft.com/en-us/microsoft-edge/webview2/+++--------------------------------------------------------------------------------+3. Windows App SDK / WinUI 3+--------------------------------------------------------------------------------+UI framework. Distributed via NuGet as Microsoft.WindowsAppSDK and related+packages.++License: MIT License+Source: https://github.com/microsoft/WindowsAppSDK+++--------------------------------------------------------------------------------+4. C++/WinRT+--------------------------------------------------------------------------------+C++ language projection for the Windows Runtime. Distributed via NuGet+as Microsoft.Windows.CppWinRT.++License: MIT License+Source: https://github.com/microsoft/cppwinrt+++--------------------------------------------------------------------------------+5. Windows Implementation Libraries (WIL)+--------------------------------------------------------------------------------+Header-only helpers for Windows interop. Distributed via NuGet as+Microsoft.Windows.ImplementationLibrary.++License: MIT License+Source: https://github.com/microsoft/wil+++--------------------------------------------------------------------------------+6. PostgreSQL libpq+--------------------------------------------------------------------------------+PostgreSQL client library used by the PostgreSQLAdapter. Linked+dynamically as libpq.dll.++License: PostgreSQL License (BSD-style permissive)+Source: https://www.postgresql.org/++Copyright (c) 1996-2024, PostgreSQL Global Development Group+Copyright (c) 1994, The Regents of the University of California+++--------------------------------------------------------------------------------+7. MariaDB Connector/C (libmariadb)+--------------------------------------------------------------------------------+MySQL/MariaDB client library used by the MySQLAdapter. Linked+DYNAMICALLY as libmariadb.dll, which satisfies the LGPL requirement+that users be able to replace the library.++License: GNU Lesser General Public License v2.1 (LGPL-2.1)+Source: https://github.com/mariadb-corporation/mariadb-connector-c++Per LGPL-2.1, the user is free to replace libmariadb.dll with another+compatible build of MariaDB Connector/C.+++--------------------------------------------------------------------------------+8. SQLite+--------------------------------------------------------------------------------+Embedded database engine used by the SQLiteAdapter and for storing+Gridex connection metadata. Linked dynamically as sqlite3.dll.++License: Public Domain+Source: https://www.sqlite.org/+++--------------------------------------------------------------------------------+9. OpenSSL+--------------------------------------------------------------------------------+Cryptography and TLS used for SSL connections to PostgreSQL/MySQL and+HTTPS calls to AI providers. Linked dynamically as libssl-3-x64.dll+and libcrypto-3-x64.dll.++License: Apache License 2.0 (OpenSSL 3.x)+Source: https://www.openssl.org/+++--------------------------------------------------------------------------------+10. cpp-httplib+--------------------------------------------------------------------------------+Header-only HTTP/HTTPS client used by AiService and McpServer.++License: MIT License+Source: https://github.com/yhirose/cpp-httplib+++--------------------------------------------------------------------------------+11. nlohmann/json+--------------------------------------------------------------------------------+Header-only JSON library used by AiService and McpServer for request+and response payloads.++License: MIT License+Source: https://github.com/nlohmann/json+++--------------------------------------------------------------------------------+12. Source Sans Pro / Source Code Pro (fonts, embedded by D2)+--------------------------------------------------------------------------------+Default fonts used inside SVG output produced by D2.++License: SIL Open Font License 1.1+Source: https://github.com/adobe-fonts/source-sans-pro+ https://github.com/adobe-fonts/source-code-pro+++--------------------------------------------------------------------------------+Compliance Notes+--------------------------------------------------------------------------------+- D2 (MPL-2.0): bundled binary unmodified; LICENSE file shipped at+ Assets/d2/LICENSE; attribution shown in Gridex Settings -> About.+- libmariadb (LGPL-2.1): linked dynamically; user can replace the DLL.+- All other components use permissive licenses (MIT, BSD, Apache 2.0,+ PostgreSQL License, Public Domain, SIL OFL).++12. hiredis+ https://github.com/redis/hiredis+ Copyright (c) 2009-2011, Salvatore Sanfilippo+ License: BSD-3-Clause+ Used for Redis protocol communication in RedisAdapter.++13. mongo-cxx-driver (mongocxx / bsoncxx)+ https://github.com/mongodb/mongo-cxx-driver+ Copyright (c) 2014-present MongoDB, Inc.+ License: Apache 2.0+ Used for MongoDB connectivity in MongoDBAdapter.++14. libssh2+ https://github.com/libssh2/libssh2+ Copyright (c) 2004-2019 Sara Golemon and contributors+ License: BSD-3-Clause+ Used for SSH tunnel (local port forwarding) in SSHTunnelService.++15. Velopack+ https://github.com/velopack/velopack+ Copyright (c) 2023-present Clowd Pty Ltd+ License: MIT+ Used for Windows installer packaging and auto-update framework.++For full license texts, see the individual upstream repositories+linked above. The MPL-2.0 text for D2 is included verbatim at+Assets/d2/LICENSE.diff --git a/windows/Gridex/Assets/Wide310x150Logo.scale-200.png b/windows/Gridex/Assets/Wide310x150Logo.scale-200.pngnew file mode 100644index 0000000..9d5e61aBinary files /dev/null and b/windows/Gridex/Assets/Wide310x150Logo.scale-200.png differdiff --git a/windows/Gridex/Assets/d2/LICENSE b/windows/Gridex/Assets/d2/LICENSEnew file mode 100644index 0000000..cfaf2c6--- /dev/null+++ b/windows/Gridex/Assets/d2/LICENSE@@ -0,0 +1,375 @@+Copyright 2022 Terrastruct Inc.++Mozilla Public License Version 2.0+==================================++1. Definitions+--------------++1.1. "Contributor"+ means each individual or legal entity that creates, contributes to+ the creation of, or owns Covered Software.++1.2. "Contributor Version"+ means the combination of the Contributions of others (if any) used+ by a Contributor and that particular Contributor's Contribution.++1.3. "Contribution"+ means Covered Software of a particular Contributor.++1.4. "Covered Software"+ means Source Code Form to which the initial Contributor has attached+ the notice in Exhibit A, the Executable Form of such Source Code+ Form, and Modifications of such Source Code Form, in each case+ including portions thereof.++1.5. "Incompatible With Secondary Licenses"+ means++ (a) that the initial Contributor has attached the notice described+ in Exhibit B to the Covered Software; or++ (b) that the Covered Software was made available under the terms of+ version 1.1 or earlier of the License, but not also under the+ terms of a Secondary License.++1.6. "Executable Form"+ means any form of the work other than Source Code Form.++1.7. "Larger Work"+ means a work that combines Covered Software with other material, in+ a separate file or files, that is not Covered Software.++1.8. "License"+ means this document.++1.9. "Licensable"+ means having the right to grant, to the maximum extent possible,+ whether at the time of the initial grant or subsequently, any and+ all of the rights conveyed by this License.++1.10. "Modifications"+ means any of the following:++ (a) any file in Source Code Form that results from an addition to,+ deletion from, or modification of the contents of Covered+ Software; or++ (b) any new file in Source Code Form that contains any Covered+ Software.++1.11. "Patent Claims" of a Contributor+ means any patent claim(s), including without limitation, method,+ process, and apparatus claims, in any patent Licensable by such+ Contributor that would be infringed, but for the grant of the+ License, by the making, using, selling, offering for sale, having+ made, import, or transfer of either its Contributions or its+ Contributor Version.++1.12. "Secondary License"+ means either the GNU General Public License, Version 2.0, the GNU+ Lesser General Public License, Version 2.1, the GNU Affero General+ Public License, Version 3.0, or any later versions of those+ licenses.++1.13. "Source Code Form"+ means the form of the work preferred for making modifications.++1.14. "You" (or "Your")+ means an individual or a legal entity exercising rights under this+ License. For legal entities, "You" includes any entity that+ controls, is controlled by, or is under common control with You. For+ purposes of this definition, "control" means (a) the power, direct+ or indirect, to cause the direction or management of such entity,+ whether by contract or otherwise, or (b) ownership of more than+ fifty percent (50%) of the outstanding shares or beneficial+ ownership of such entity.++2. License Grants and Conditions+--------------------------------++2.1. Grants++Each Contributor hereby grants You a world-wide, royalty-free,+non-exclusive license:++(a) under intellectual property rights (other than patent or trademark)+ Licensable by such Contributor to use, reproduce, make available,+ modify, display, perform, distribute, and otherwise exploit its+ Contributions, either on an unmodified basis, with Modifications, or+ as part of a Larger Work; and++(b) under Patent Claims of such Contributor to make, use, sell, offer+ for sale, have made, import, and otherwise transfer either its+ Contributions or its Contributor Version.++2.2. Effective Date++The licenses granted in Section 2.1 with respect to any Contribution+become effective for each Contribution on the date the Contributor first+distributes such Contribution.++2.3. Limitations on Grant Scope++The licenses granted in this Section 2 are the only rights granted under+this License. No additional rights or licenses will be implied from the+distribution or licensing of Covered Software under this License.+Notwithstanding Section 2.1(b) above, no patent license is granted by a+Contributor:++(a) for any code that a Contributor has removed from Covered Software;+ or++(b) for infringements caused by: (i) Your and any other third party's+ modifications of Covered Software, or (ii) the combination of its+ Contributions with other software (except as part of its Contributor+ Version); or++(c) under Patent Claims infringed by Covered Software in the absence of+ its Contributions.++This License does not grant any rights in the trademarks, service marks,+or logos of any Contributor (except as may be necessary to comply with+the notice requirements in Section 3.4).++2.4. Subsequent Licenses++No Contributor makes additional grants as a result of Your choice to+distribute the Covered Software under a subsequent version of this+License (see Section 10.2) or under the terms of a Secondary License (if+permitted under the terms of Section 3.3).++2.5. Representation++Each Contributor represents that the Contributor believes its+Contributions are its original creation(s) or it has sufficient rights+to grant the rights to its Contributions conveyed by this License.++2.6. Fair Use++This License is not intended to limit any rights You have under+applicable copyright doctrines of fair use, fair dealing, or other+equivalents.++2.7. Conditions++Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted+in Section 2.1.++3. Responsibilities+-------------------++3.1. Distribution of Source Form++All distribution of Covered Software in Source Code Form, including any+Modifications that You create or to which You contribute, must be under+the terms of this License. You must inform recipients that the Source+Code Form of the Covered Software is governed by the terms of this+License, and how they can obtain a copy of this License. You may not+attempt to alter or restrict the recipients' rights in the Source Code+Form.++3.2. Distribution of Executable Form++If You distribute Covered Software in Executable Form then:++(a) such Covered Software must also be made available in Source Code+ Form, as described in Section 3.1, and You must inform recipients of+ the Executable Form how they can obtain a copy of such Source Code+ Form by reasonable means in a timely manner, at a charge no more+ than the cost of distribution to the recipient; and++(b) You may distribute such Executable Form under the terms of this+ License, or sublicense it under different terms, provided that the+ license for the Executable Form does not attempt to limit or alter+ the recipients' rights in the Source Code Form under this License.++3.3. Distribution of a Larger Work++You may create and distribute a Larger Work under terms of Your choice,+provided that You also comply with the requirements of this License for+the Covered Software. If the Larger Work is a combination of Covered+Software with a work governed by one or more Secondary Licenses, and the+Covered Software is not Incompatible With Secondary Licenses, this+License permits You to additionally distribute such Covered Software+under the terms of such Secondary License(s), so that the recipient of+the Larger Work may, at their option, further distribute the Covered+Software under the terms of either this License or such Secondary+License(s).++3.4. Notices++You may not remove or alter the substance of any license notices+(including copyright notices, patent notices, disclaimers of warranty,+or limitations of liability) contained within the Source Code Form of+the Covered Software, except that You may alter any license notices to+the extent required to remedy known factual inaccuracies.++3.5. Application of Additional Terms++You may choose to offer, and to charge a fee for, warranty, support,+indemnity or liability obligations to one or more recipients of Covered+Software. However, You may do so only on Your own behalf, and not on+behalf of any Contributor. You must make it absolutely clear that any+such warranty, support, indemnity, or liability obligation is offered by+You alone, and You hereby agree to indemnify every Contributor for any+liability incurred by such Contributor as a result of warranty, support,+indemnity or liability terms You offer. You may include additional+disclaimers of warranty and limitations of liability specific to any+jurisdiction.++4. Inability to Comply Due to Statute or Regulation+---------------------------------------------------++If it is impossible for You to comply with any of the terms of this+License with respect to some or all of the Covered Software due to+statute, judicial order, or regulation then You must: (a) comply with+the terms of this License to the maximum extent possible; and (b)+describe the limitations and the code they affect. Such description must+be placed in a text file included with all distributions of the Covered+Software under this License. Except to the extent prohibited by statute+or regulation, such description must be sufficiently detailed for a+recipient of ordinary skill to be able to understand it.++5. Termination+--------------++5.1. The rights granted under this License will terminate automatically+if You fail to comply with any of its terms. However, if You become+compliant, then the rights granted under this License from a particular+Contributor are reinstated (a) provisionally, unless and until such+Contributor explicitly and finally terminates Your grants, and (b) on an+ongoing basis, if such Contributor fails to notify You of the+non-compliance by some reasonable means prior to 60 days after You have+come back into compliance. Moreover, Your grants from a particular+Contributor are reinstated on an ongoing basis if such Contributor+notifies You of the non-compliance by some reasonable means, this is the+first time You have received notice of non-compliance with this License+from such Contributor, and You become compliant prior to 30 days after+Your receipt of the notice.++5.2. If You initiate litigation against any entity by asserting a patent+infringement claim (excluding declaratory judgment actions,+counter-claims, and cross-claims) alleging that a Contributor Version+directly or indirectly infringes any patent, then the rights granted to+You by any and all Contributors for the Covered Software under Section+2.1 of this License shall terminate.++5.3. In the event of termination under Sections 5.1 or 5.2 above, all+end user license agreements (excluding distributors and resellers) which+have been validly granted by You or Your distributors under this License+prior to termination shall survive termination.++************************************************************************+* *+* 6. Disclaimer of Warranty *+* ------------------------- *+* *+* Covered Software is provided under this License on an "as is" *+* basis, without warranty of any kind, either expressed, implied, or *+* statutory, including, without limitation, warranties that the *+* Covered Software is free of defects, merchantable, fit for a *+* particular purpose or non-infringing. The entire risk as to the *+* quality and performance of the Covered Software is with You. *+* Should any Covered Software prove defective in any respect, You *+* (not any Contributor) assume the cost of any necessary servicing, *+* repair, or correction. This disclaimer of warranty constitutes an *+* essential part of this License. No use of any Covered Software is *+* authorized under this License except under this disclaimer. *+* *+************************************************************************++************************************************************************+* *+* 7. Limitation of Liability *+* -------------------------- *+* *+* Under no circumstances and under no legal theory, whether tort *+* (including negligence), contract, or otherwise, shall any *+* Contributor, or anyone who distributes Covered Software as *+* permitted above, be liable to You for any direct, indirect, *+* special, incidental, or consequential damages of any character *+* including, without limitation, damages for lost profits, loss of *+* goodwill, work stoppage, computer failure or malfunction, or any *+* and all other commercial damages or losses, even if such party *+* shall have been informed of the possibility of such damages. This *+* limitation of liability shall not apply to liability for death or *+* personal injury resulting from such party's negligence to the *+* extent applicable law prohibits such limitation. Some *+* jurisdictions do not allow the exclusion or limitation of *+* incidental or consequential damages, so this exclusion and *+* limitation may not apply to You. *+* *+************************************************************************++8. Litigation+-------------++Any litigation relating to this License may be brought only in the+courts of a jurisdiction where the defendant maintains its principal+place of business and such litigation shall be governed by laws of that+jurisdiction, without reference to its conflict-of-law provisions.+Nothing in this Section shall prevent a party's ability to bring+cross-claims or counter-claims.++9. Miscellaneous+----------------++This License represents the complete agreement concerning the subject+matter hereof. If any provision of this License is held to be+unenforceable, such provision shall be reformed only to the extent+necessary to make it enforceable. Any law or regulation which provides+that the language of a contract shall be construed against the drafter+shall not be used to construe this License against a Contributor.++10. Versions of the License+---------------------------++10.1. New Versions++Mozilla Foundation is the license steward. Except as provided in Section+10.3, no one other than the license steward has the right to modify or+publish new versions of this License. Each version will be given a+distinguishing version number.++10.2. Effect of New Versions++You may distribute the Covered Software under the terms of the version+of the License under which You originally received the Covered Software,+or under the terms of any subsequent version published by the license+steward.++10.3. Modified Versions++If you create software not governed by this License, and you want to+create a new license for such software, you may create and use a+modified version of this License if you rename the license and remove+any references to the name of the license steward (except to note that+such modified license differs from this License).++10.4. Distributing Source Code Form that is Incompatible With Secondary+Licenses++If You choose to distribute Source Code Form that is Incompatible With+Secondary Licenses under the terms of this version of the License, the+notice described in Exhibit B of this License must be attached.++Exhibit A - Source Code Form License Notice+-------------------------------------------++ This Source Code Form is subject to the terms of the Mozilla Public+ License, v. 2.0. If a copy of the MPL was not distributed with this+ file, You can obtain one at http://mozilla.org/MPL/2.0/.++If it is not possible or desirable to put the notice in a particular+file, then You may include the notice in a location (such as a LICENSE+file in a relevant directory) where a recipient would be likely to look+for such a notice.++You may add additional accurate notices of copyright ownership.++Exhibit B - "Incompatible With Secondary Licenses" Notice+---------------------------------------------------------++ This Source Code Form is "Incompatible With Secondary Licenses", as+ defined by the Mozilla Public License, v. 2.0.\ No newline at end of filediff --git a/windows/Gridex/Assets/d2/README.txt b/windows/Gridex/Assets/d2/README.txtnew file mode 100644index 0000000..01079db--- /dev/null+++ b/windows/Gridex/Assets/d2/README.txt@@ -0,0 +1,21 @@+D2 CLI binary placement+=======================++Place d2.exe (Windows x64 build) in this directory.++Download from:+ https://github.com/terrastruct/d2/releases/latest++Steps:+1. Download d2-vX.Y.Z-windows-amd64.zip+2. Extract d2.exe and LICENSE+3. Drop both files into this folder (Assets/d2/)+4. Rebuild the solution++Verify:+ d2.exe --version++Without this binary, the ER Diagram feature will show+"d2.exe not found" when triggered.++License: D2 is MPL-2.0diff --git a/windows/Gridex/Assets/gridex-icon-source.png b/windows/Gridex/Assets/gridex-icon-source.pngnew file mode 100644index 0000000..8ce0385Binary files /dev/null and b/windows/Gridex/Assets/gridex-icon-source.png differdiff --git a/windows/Gridex/Assets/monaco-editor.html b/windows/Gridex/Assets/monaco-editor.htmlnew file mode 100644index 0000000..1cbc136--- /dev/null+++ b/windows/Gridex/Assets/monaco-editor.html@@ -0,0 +1,195 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>SQL Editor</title>+ <style>+ * { margin: 0; padding: 0; box-sizing: border-box; }+ html, body { width: 100%; height: 100%; overflow: hidden; }+ #editor-container { width: 100%; height: 100%; }++ /* Dark theme fallback when Monaco not loaded */+ body { background: #1e1e1e; color: #d4d4d4; font-family: 'Cascadia Code', Consolas, monospace; }+ body.light { background: #ffffff; color: #1e1e1e; }+ </style>+</head>+<body>+ <div id="editor-container"></div>++ <!-- Load Monaco from CDN — offline bundle can replace this later -->+ <script src="https://cdn.jsdelivr.net/npm/[email protected]/min/vs/loader.js"></script>+ <script>+ let editor = null;+ let currentTheme = 'vs-dark';++ // Initialize Monaco Editor+ require.config({+ paths: { 'vs': 'https://cdn.jsdelivr.net/npm/[email protected]/min/vs' }+ });++ require(['vs/editor/editor.main'], function () {+ // Register SQL language completions will be added dynamically+ editor = monaco.editor.create(document.getElementById('editor-container'), {+ value: '',+ language: 'sql',+ theme: currentTheme,+ automaticLayout: true,+ minimap: { enabled: false },+ fontSize: 13,+ fontFamily: "'Cascadia Code', Consolas, 'Courier New', monospace",+ lineNumbers: 'on',+ scrollBeyondLastLine: false,+ wordWrap: 'off',+ tabSize: 4,+ insertSpaces: true,+ renderWhitespace: 'none',+ suggestOnTriggerCharacters: true,+ quickSuggestions: true,+ parameterHints: { enabled: true },+ folding: false,+ glyphMargin: false,+ lineDecorationsWidth: 8,+ lineNumbersMinChars: 3,+ padding: { top: 8, bottom: 8 },+ scrollbar: {+ verticalScrollbarSize: 10,+ horizontalScrollbarSize: 10+ }+ });++ // Ctrl+Enter / F5 → execute query+ editor.addAction({+ id: 'execute-query',+ label: 'Execute Query',+ keybindings: [+ monaco.KeyMod.CtrlCmd | monaco.KeyCode.Enter,+ monaco.KeyCode.F5+ ],+ run: function () {+ const sql = getSelectedOrAllText();+ if (sql.trim()) {+ sendMessage('execute', { sql: sql });+ }+ }+ });++ // Ctrl+Shift+F → format SQL+ editor.addAction({+ id: 'format-sql',+ label: 'Format SQL',+ keybindings: [+ monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.KeyF+ ],+ run: function () {+ const sql = editor.getValue();+ sendMessage('format', { sql: sql });+ }+ });++ // Notify host that editor is ready+ sendMessage('ready', {});+ });++ // Get selected text or full content+ function getSelectedOrAllText() {+ const selection = editor.getSelection();+ if (selection && !selection.isEmpty()) {+ return editor.getModel().getValueInRange(selection);+ }+ return editor.getValue();+ }++ // Send message to C++ host via WebView2 bridge+ function sendMessage(type, data) {+ if (window.chrome && window.chrome.webview) {+ window.chrome.webview.postMessage(JSON.stringify({+ type: type,+ ...data+ }));+ }+ }++ // ── API called from C++ host ──────────────────++ // Set editor content+ function setValue(text) {+ if (editor) editor.setValue(text);+ }++ // Get editor content+ function getValue() {+ return editor ? editor.getValue() : '';+ }++ // Set theme (vs-dark or vs)+ function setTheme(theme) {+ currentTheme = theme;+ if (editor) monaco.editor.setTheme(theme);+ document.body.classList.toggle('light', theme === 'vs');+ }++ // Set schema data for autocomplete+ function setSchemaCompletions(schemaJson) {+ try {+ const schema = JSON.parse(schemaJson);+ monaco.languages.registerCompletionItemProvider('sql', {+ provideCompletionItems: function (model, position) {+ const suggestions = [];++ // Table names+ if (schema.tables) {+ schema.tables.forEach(function (table) {+ suggestions.push({+ label: table.name,+ kind: monaco.languages.CompletionItemKind.Class,+ insertText: '"' + table.name + '"',+ detail: 'Table'+ });++ // Column completions for each table+ if (table.columns) {+ table.columns.forEach(function (col) {+ suggestions.push({+ label: table.name + '.' + col.name,+ kind: monaco.languages.CompletionItemKind.Field,+ insertText: '"' + col.name + '"',+ detail: col.type + (col.nullable ? ' NULL' : ' NOT NULL')+ });+ });+ }+ });+ }++ // Function names+ if (schema.functions) {+ schema.functions.forEach(function (fn) {+ suggestions.push({+ label: fn,+ kind: monaco.languages.CompletionItemKind.Function,+ insertText: fn + '()',+ detail: 'Function'+ });+ });+ }++ return { suggestions: suggestions };+ }+ });+ } catch (e) {+ console.error('Failed to parse schema:', e);+ }+ }++ // Focus the editor+ function focusEditor() {+ if (editor) editor.focus();+ }++ // Handle window resize+ window.addEventListener('resize', function () {+ if (editor) editor.layout();+ });+ </script>+</body>+</html>diff --git a/windows/Gridex/ConnectionCard.cpp b/windows/Gridex/ConnectionCard.cppnew file mode 100644index 0000000..09f9f0a--- /dev/null+++ b/windows/Gridex/ConnectionCard.cpp@@ -0,0 +1,63 @@+#include "pch.h"+#include "xaml-includes.h"+#include <winrt/Windows.UI.h>+#include "ConnectionCard.h"+#if __has_include("ConnectionCard.g.cpp")+#include "ConnectionCard.g.cpp"+#endif++namespace winrt::Gridex::implementation+{+ ConnectionCard::ConnectionCard()+ {+ InitializeComponent();+ }++ void ConnectionCard::SetConnection(const DBModels::ConnectionConfig& config)+ {+ connectionId_ = config.id;+ ConnNameText().Text(winrt::hstring(config.name));+ SubtitleText().Text(winrt::hstring(config.subtitle()));+ DbTypeIcon().Glyph(winrt::hstring(DBModels::DatabaseTypeGlyph(config.databaseType)));+ DbTypeLabel().Text(winrt::hstring(DBModels::DatabaseTypeDisplayName(config.databaseType)));++ if (config.colorTag.has_value())+ {+ auto& info = DBModels::GetColorTagInfo(config.colorTag.value());+ auto color = winrt::Windows::UI::ColorHelper::FromArgb(255, info.r, info.g, info.b);+ ColorTagBar().Background(winrt::Microsoft::UI::Xaml::Media::SolidColorBrush(color));+ TagBadge().Visibility(winrt::Microsoft::UI::Xaml::Visibility::Visible);+ TagBadge().Background(winrt::Microsoft::UI::Xaml::Media::SolidColorBrush(color));+ TagBadgeText().Text(winrt::hstring(info.hint));+ }+ else+ {+ auto gray = winrt::Windows::UI::ColorHelper::FromArgb(255, 128, 128, 128);+ ColorTagBar().Background(winrt::Microsoft::UI::Xaml::Media::SolidColorBrush(gray));+ TagBadge().Visibility(winrt::Microsoft::UI::Xaml::Visibility::Collapsed);+ }+ }++ void ConnectionCard::ContextConnect_Click(+ winrt::Windows::Foundation::IInspectable const&,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const&)+ {+ // Handled by ListView ItemClick in HomePage+ }++ void ConnectionCard::ContextEdit_Click(+ winrt::Windows::Foundation::IInspectable const&,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const&)+ {+ if (OnEdit)+ OnEdit(connectionId_);+ }++ void ConnectionCard::ContextDelete_Click(+ winrt::Windows::Foundation::IInspectable const&,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const&)+ {+ if (OnDelete)+ OnDelete(connectionId_);+ }+}diff --git a/windows/Gridex/ConnectionCard.h b/windows/Gridex/ConnectionCard.hnew file mode 100644index 0000000..a98c09e--- /dev/null+++ b/windows/Gridex/ConnectionCard.h@@ -0,0 +1,38 @@+#pragma once++#include "ConnectionCard.g.h"+#include "Models/ConnectionConfig.h"+#include <functional>++namespace winrt::Gridex::implementation+{+ struct ConnectionCard : ConnectionCardT<ConnectionCard>+ {+ ConnectionCard();++ void SetConnection(const DBModels::ConnectionConfig& config);++ void ContextConnect_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);+ void ContextEdit_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);+ void ContextDelete_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);++ std::function<void(const std::wstring& id)> OnDelete;+ std::function<void(const std::wstring& id)> OnEdit;++ private:+ std::wstring connectionId_;+ };+}++namespace winrt::Gridex::factory_implementation+{+ struct ConnectionCard : ConnectionCardT<ConnectionCard, implementation::ConnectionCard>+ {+ };+}diff --git a/windows/Gridex/ConnectionCard.idl b/windows/Gridex/ConnectionCard.idlnew file mode 100644index 0000000..27979e5--- /dev/null+++ b/windows/Gridex/ConnectionCard.idl@@ -0,0 +1,8 @@+namespace Gridex+{+ [default_interface]+ runtimeclass ConnectionCard : Microsoft.UI.Xaml.Controls.UserControl+ {+ ConnectionCard();+ }+}diff --git a/windows/Gridex/ConnectionCard.xaml b/windows/Gridex/ConnectionCard.xamlnew file mode 100644index 0000000..7e13e92--- /dev/null+++ b/windows/Gridex/ConnectionCard.xaml@@ -0,0 +1,92 @@+<UserControl+ x:Class="Gridex.ConnectionCard"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">++ <Grid Padding="12,10" CornerRadius="8"+ Background="{ThemeResource CardBackgroundFillColorDefaultBrush}"+ BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}"+ BorderThickness="1"+ Height="72">++ <!-- Right-click context menu -->+ <Grid.ContextFlyout>+ <MenuFlyout>+ <MenuFlyoutItem Text="Connect" Click="ContextConnect_Click">+ <MenuFlyoutItem.Icon>+ <FontIcon Glyph="" />+ </MenuFlyoutItem.Icon>+ </MenuFlyoutItem>+ <MenuFlyoutItem Text="Edit" Click="ContextEdit_Click">+ <MenuFlyoutItem.Icon>+ <FontIcon Glyph="" />+ </MenuFlyoutItem.Icon>+ </MenuFlyoutItem>+ <MenuFlyoutSeparator />+ <MenuFlyoutItem Text="Delete" Click="ContextDelete_Click">+ <MenuFlyoutItem.Icon>+ <FontIcon Glyph="" />+ </MenuFlyoutItem.Icon>+ </MenuFlyoutItem>+ </MenuFlyout>+ </Grid.ContextFlyout>+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="12" />+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="12" />+ <ColumnDefinition Width="*" />+ <ColumnDefinition Width="Auto" />+ </Grid.ColumnDefinitions>++ <!-- Color Tag Bar -->+ <Border x:Name="ColorTagBar"+ Grid.Column="0"+ Width="4" CornerRadius="2"+ VerticalAlignment="Stretch" />++ <!-- Database Type Icon -->+ <Border Grid.Column="2"+ Width="36" Height="36"+ CornerRadius="8"+ Background="{ThemeResource AccentFillColorDefaultBrush}">+ <FontIcon x:Name="DbTypeIcon"+ FontSize="18"+ Foreground="White"+ HorizontalAlignment="Center"+ VerticalAlignment="Center" />+ </Border>++ <!-- Name + Subtitle -->+ <StackPanel Grid.Column="4" VerticalAlignment="Center" Spacing="2">+ <StackPanel Orientation="Horizontal" Spacing="8">+ <TextBlock x:Name="ConnNameText"+ FontSize="14"+ FontWeight="SemiBold"+ Foreground="{ThemeResource TextFillColorPrimaryBrush}"+ TextTrimming="CharacterEllipsis" />+ <!-- Color tag hint badge -->+ <Border x:Name="TagBadge"+ CornerRadius="4"+ Padding="6,1"+ Visibility="Collapsed">+ <TextBlock x:Name="TagBadgeText"+ FontSize="10"+ Foreground="White" />+ </Border>+ </StackPanel>+ <TextBlock x:Name="SubtitleText"+ FontSize="12"+ Foreground="{ThemeResource TextFillColorTertiaryBrush}"+ TextTrimming="CharacterEllipsis" />+ </StackPanel>++ <!-- DB Type Label -->+ <TextBlock x:Name="DbTypeLabel"+ Grid.Column="5"+ FontSize="11"+ FontWeight="SemiBold"+ VerticalAlignment="Center"+ Foreground="{ThemeResource TextFillColorDisabledBrush}" />+ </Grid>+</UserControl>diff --git a/windows/Gridex/ConnectionFormDialog.cpp b/windows/Gridex/ConnectionFormDialog.cppnew file mode 100644index 0000000..1f266d7--- /dev/null+++ b/windows/Gridex/ConnectionFormDialog.cpp@@ -0,0 +1,246 @@+#include "pch.h"+#include "xaml-includes.h"+#include <winrt/Windows.UI.h>+#include "ConnectionFormDialog.h"+#include "Models/AppSettings.h"+#if __has_include("ConnectionFormDialog.g.cpp")+#include "ConnectionFormDialog.g.cpp"+#endif++namespace winrt::Gridex::implementation+{+ namespace mux = winrt::Microsoft::UI::Xaml;+ namespace muxc = winrt::Microsoft::UI::Xaml::Controls;++ ConnectionFormDialog::ConnectionFormDialog()+ {+ InitializeComponent();+ PopulateGroupCombo();+ }++ void ConnectionFormDialog::PopulateGroupCombo()+ {+ auto combo = GroupCombo();+ combo.Items().Clear();+ // First item: no group+ combo.Items().Append(winrt::box_value(winrt::hstring(L"(None)")));+ // Load groups from settings+ auto s = DBModels::AppSettings::Load();+ for (const auto& g : s.connectionGroups)+ combo.Items().Append(winrt::box_value(winrt::hstring(g)));+ combo.SelectedIndex(0);+ }++ void ConnectionFormDialog::SetDatabaseType(DBModels::DatabaseType type)+ {+ dbType_ = type;+ PortInput().Value(static_cast<double>(DBModels::DatabaseTypeDefaultPort(type)));+ UpdateFieldVisibility();+ BuildColorTagPicker();+ }++ void ConnectionFormDialog::UpdateFieldVisibility()+ {+ bool isSqlite = (dbType_ == DBModels::DatabaseType::SQLite);+ bool isRedis = (dbType_ == DBModels::DatabaseType::Redis);+ bool isMongo = (dbType_ == DBModels::DatabaseType::MongoDB);+ auto show = mux::Visibility::Visible;+ auto hide = mux::Visibility::Collapsed;++ // MongoDB URI + Options section (shown only for MongoDB)+ UriLabel().Visibility(isMongo ? show : hide);+ MongoUriSection().Visibility(isMongo ? show : hide);++ // Network fields hidden only for SQLite+ HostLabel().Visibility(isSqlite ? hide : show);+ HostRow().Visibility(isSqlite ? hide : show);++ // User row hidden for SQLite AND Redis (Redis only uses password)+ UserLabel().Visibility((isSqlite || isRedis) ? hide : show);+ UserRow().Visibility((isSqlite || isRedis) ? hide : show);++ // Password row hidden only for SQLite (Redis can have password)+ PasswordLabel().Visibility(isSqlite ? hide : show);+ PasswordRow().Visibility(isSqlite ? hide : show);++ // SSL keys hidden for SQLite, Redis, and MongoDB (MongoDB TLS via URI options)+ SslKeysLabel().Visibility((isSqlite || isRedis || isMongo) ? hide : show);+ SslKeysRow().Visibility((isSqlite || isRedis || isMongo) ? hide : show);++ // SSH toggle hidden for SQLite AND Redis+ SshToggle().Visibility((isSqlite || isRedis) ? hide : show);++ // Show SQLite file section only for SQLite+ FileLabel().Visibility(isSqlite ? show : hide);+ SqliteFileSection().Visibility(isSqlite ? show : hide);++ // Adjust Database field placeholder per type+ if (isRedis)+ DatabaseInput().PlaceholderText(L"0");+ else if (isMongo)+ DatabaseInput().PlaceholderText(L"mydb (or leave empty for URI)");+ else if (dbType_ == DBModels::DatabaseType::MSSQLServer)+ DatabaseInput().PlaceholderText(L"master");+ else if (!isSqlite)+ DatabaseInput().PlaceholderText(L"mydb");+ }++ void ConnectionFormDialog::BuildColorTagPicker()+ {+ auto panel = ColorTagPicker();+ panel.Children().Clear();++ for (const auto& info : DBModels::GetColorTags())+ {+ auto swatch = muxc::Button();+ swatch.Width(28);+ swatch.Height(20);+ swatch.CornerRadius(mux::CornerRadiusHelper::FromUniformRadius(4));+ swatch.Padding(mux::ThicknessHelper::FromUniformLength(0));+ auto color = winrt::Windows::UI::ColorHelper::FromArgb(255, info.r, info.g, info.b);+ swatch.Background(mux::Media::SolidColorBrush(color));++ auto tag = info.tag;+ swatch.Click([this, tag](auto const&, auto const&) { selectedColor_ = tag; });+ panel.Children().Append(swatch);+ }+ }++ std::wstring ConnectionFormDialog::GetPassword()+ {+ if (auto pwd = PasswordInput())+ return std::wstring(pwd.Password());+ return L"";+ }++ DBModels::ConnectionConfig ConnectionFormDialog::GetConnectionConfig()+ {+ DBModels::ConnectionConfig config;+ config.name = std::wstring(NameInput().Text());+ config.databaseType = dbType_;++ // Read selected group (index 0 = "(None)" = no group)+ int groupIdx = GroupCombo().SelectedIndex();+ if (groupIdx > 0)+ {+ auto item = GroupCombo().Items().GetAt(groupIdx);+ config.group = std::wstring(winrt::unbox_value<winrt::hstring>(item));+ }+ config.host = std::wstring(HostInput().Text());+ config.port = static_cast<uint16_t>(PortInput().Value());+ config.username = std::wstring(UserInput().Text());+ config.database = std::wstring(DatabaseInput().Text());+ config.colorTag = selectedColor_;+ auto sslIdx = SslModeInput().SelectedIndex();+ config.sslMode = static_cast<DBModels::SSLMode>(sslIdx);+ config.sslEnabled = (sslIdx != 1);+ if (dbType_ == DBModels::DatabaseType::SQLite)+ config.filePath = std::wstring(FilePathInput().Text());+ if (dbType_ == DBModels::DatabaseType::MongoDB)+ {+ config.connectionUri = std::wstring(UriInput().Text());+ config.mongoOptions = std::wstring(MongoOptionsInput().Text());+ }+ if (SshToggle().IsChecked().Value())+ {+ DBModels::SSHTunnelConfig ssh;+ ssh.host = std::wstring(SshHostInput().Text());+ ssh.port = static_cast<uint16_t>(SshPortInput().Value());+ ssh.username = std::wstring(SshUserInput().Text());+ ssh.password = std::wstring(SshPasswordInput().Password());+ ssh.authMethod = static_cast<DBModels::SSHAuthMethod>(SshAuthInput().SelectedIndex());+ ssh.keyPath = std::wstring(SshKeyInput().Text());+ config.sshConfig = ssh;+ }+ return config;+ }++ void ConnectionFormDialog::SetConnectionConfig(const DBModels::ConnectionConfig& config)+ {+ // Set database type FIRST so it doesn't overwrite user fields with defaults+ SetDatabaseType(config.databaseType);++ NameInput().Text(winrt::hstring(config.name));++ // Select group in combo (or add if not in settings yet)+ if (!config.group.empty())+ {+ auto combo = GroupCombo();+ int foundIdx = -1;+ for (uint32_t i = 0; i < combo.Items().Size(); i++)+ {+ auto item = winrt::unbox_value<winrt::hstring>(combo.Items().GetAt(i));+ if (std::wstring(item) == config.group) { foundIdx = static_cast<int>(i); break; }+ }+ if (foundIdx < 0)+ {+ combo.Items().Append(winrt::box_value(winrt::hstring(config.group)));+ foundIdx = static_cast<int>(combo.Items().Size()) - 1;+ }+ combo.SelectedIndex(foundIdx);+ }++ HostInput().Text(winrt::hstring(config.host));+ PortInput().Value(static_cast<double>(config.port));+ UserInput().Text(winrt::hstring(config.username));+ PasswordInput().Password(winrt::hstring(config.password));+ DatabaseInput().Text(winrt::hstring(config.database));+ SslModeInput().SelectedIndex(static_cast<int>(config.sslMode));+ FilePathInput().Text(winrt::hstring(config.filePath));+ UriInput().Text(winrt::hstring(config.connectionUri));+ MongoOptionsInput().Text(winrt::hstring(config.mongoOptions));+ selectedColor_ = config.colorTag;+ if (config.sshConfig.has_value())+ {+ SshToggle().IsChecked(true);+ SshSection().Visibility(mux::Visibility::Visible);+ SshHostInput().Text(winrt::hstring(config.sshConfig->host));+ SshPortInput().Value(static_cast<double>(config.sshConfig->port));+ SshUserInput().Text(winrt::hstring(config.sshConfig->username));+ SshPasswordInput().Password(winrt::hstring(config.sshConfig->password));+ SshAuthInput().SelectedIndex(static_cast<int>(config.sshConfig->authMethod));+ SshKeyInput().Text(winrt::hstring(config.sshConfig->keyPath));+ }+ }++ void ConnectionFormDialog::SshToggle_Click(+ winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ bool show = SshToggle().IsChecked().Value();+ SshSection().Visibility(show ? mux::Visibility::Visible : mux::Visibility::Collapsed);+ }++ void ConnectionFormDialog::SshAuth_Changed(+ winrt::Windows::Foundation::IInspectable const&, muxc::SelectionChangedEventArgs const&)+ {+ // Guard: event can fire during InitializeComponent before elements exist+ auto pwd = SshPasswordInput();+ auto key = SshKeySection();+ if (!pwd || !key) return;++ auto idx = SshAuthInput().SelectedIndex();+ pwd.Visibility((idx == 0 || idx == 2) ? mux::Visibility::Visible : mux::Visibility::Collapsed);+ key.Visibility((idx == 1 || idx == 2) ? mux::Visibility::Visible : mux::Visibility::Collapsed);+ }++ void ConnectionFormDialog::BrowseFile_Click(+ winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&) {}+ void ConnectionFormDialog::BrowseSshKey_Click(+ winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&) {}++ void ConnectionFormDialog::SaveButton_Click(+ winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ if (OnSave) OnSave();+ }+ void ConnectionFormDialog::TestButton_Click(+ winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ if (OnTest) OnTest();+ }+ void ConnectionFormDialog::ConnectButton_Click(+ winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ if (OnConnect) OnConnect();+ }+}diff --git a/windows/Gridex/ConnectionFormDialog.h b/windows/Gridex/ConnectionFormDialog.hnew file mode 100644index 0000000..e7707b9--- /dev/null+++ b/windows/Gridex/ConnectionFormDialog.h@@ -0,0 +1,58 @@+#pragma once++#include "ConnectionFormDialog.g.h"+#include "Models/ConnectionConfig.h"+#include <functional>++namespace winrt::Gridex::implementation+{+ struct ConnectionFormDialog : ConnectionFormDialogT<ConnectionFormDialog>+ {+ ConnectionFormDialog();++ void SetDatabaseType(DBModels::DatabaseType type);+ DBModels::ConnectionConfig GetConnectionConfig();+ std::wstring GetPassword();+ void SetConnectionConfig(const DBModels::ConnectionConfig& config);++ void SshToggle_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);+ void SshAuth_Changed(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::Controls::SelectionChangedEventArgs const& e);+ void BrowseFile_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);+ void BrowseSshKey_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);+ void SaveButton_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);+ void TestButton_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);+ void ConnectButton_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);++ std::function<void()> OnSave;+ std::function<void()> OnTest;+ std::function<void()> OnConnect;++ private:+ DBModels::DatabaseType dbType_ = DBModels::DatabaseType::PostgreSQL;+ std::optional<DBModels::ColorTag> selectedColor_;+ void BuildColorTagPicker();+ void UpdateFieldVisibility();+ void PopulateGroupCombo();+ };+}++namespace winrt::Gridex::factory_implementation+{+ struct ConnectionFormDialog : ConnectionFormDialogT<ConnectionFormDialog, implementation::ConnectionFormDialog>+ {+ };+}diff --git a/windows/Gridex/ConnectionFormDialog.idl b/windows/Gridex/ConnectionFormDialog.idlnew file mode 100644index 0000000..fa2f060--- /dev/null+++ b/windows/Gridex/ConnectionFormDialog.idl@@ -0,0 +1,8 @@+namespace Gridex+{+ [default_interface]+ runtimeclass ConnectionFormDialog : Microsoft.UI.Xaml.Controls.UserControl+ {+ ConnectionFormDialog();+ }+}diff --git a/windows/Gridex/ConnectionFormDialog.xaml b/windows/Gridex/ConnectionFormDialog.xamlnew file mode 100644index 0000000..77b0cca--- /dev/null+++ b/windows/Gridex/ConnectionFormDialog.xaml@@ -0,0 +1,358 @@+<UserControl+ x:Class="Gridex.ConnectionFormDialog"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">++ <!-- Horizontal label-input grid layout matching macOS -->+ <StackPanel Spacing="0" MinWidth="680">+ <ScrollViewer VerticalScrollBarVisibility="Auto" MaxHeight="480">+ <Grid Margin="0,8,0,0">+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="110" />+ <ColumnDefinition Width="*" />+ </Grid.ColumnDefinitions>+ <Grid.RowDefinitions>+ <RowDefinition Height="Auto" />+ <RowDefinition Height="Auto" />+ <RowDefinition Height="Auto" />+ <RowDefinition Height="Auto" />+ <RowDefinition Height="Auto" />+ <RowDefinition Height="Auto" />+ <RowDefinition Height="Auto" />+ <RowDefinition Height="Auto" />+ <RowDefinition Height="Auto" />+ <RowDefinition Height="Auto" />+ </Grid.RowDefinitions>++ <!-- Row 0: Name + Group -->+ <TextBlock Grid.Row="0" Grid.Column="0"+ Text="Name"+ VerticalAlignment="Center"+ HorizontalAlignment="Right"+ Margin="0,0,16,0"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ <Grid Grid.Row="0" Grid.Column="1" Margin="0,0,0,12">+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="*" />+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="Auto" />+ </Grid.ColumnDefinitions>+ <TextBox x:Name="NameInput" Grid.Column="0"+ PlaceholderText="My Database" />+ <TextBlock Grid.Column="1" Text="Group"+ VerticalAlignment="Center"+ Margin="12,0,8,0"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ <ComboBox x:Name="GroupCombo" Grid.Column="2"+ MinWidth="160"+ PlaceholderText="(None)" />+ </Grid>++ <!-- Row 1: Status Color + Tag -->+ <TextBlock Grid.Row="1" Grid.Column="0"+ Text="Status color"+ VerticalAlignment="Center"+ HorizontalAlignment="Right"+ Margin="0,0,16,0"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ <Grid Grid.Row="1" Grid.Column="1" Margin="0,0,0,12">+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="*" />+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="Auto" />+ </Grid.ColumnDefinitions>+ <StackPanel x:Name="ColorTagPicker" Grid.Column="0"+ Orientation="Horizontal" Spacing="6"+ VerticalAlignment="Center" />+ <TextBlock Grid.Column="1" Text="Tag"+ VerticalAlignment="Center"+ Margin="16,0,8,0"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ <ComboBox x:Name="TagCombo" Grid.Column="2"+ MinWidth="120"+ SelectedIndex="0">+ <ComboBoxItem Content="None" />+ <ComboBoxItem Content="Production" />+ <ComboBoxItem Content="Staging" />+ <ComboBoxItem Content="Development" />+ <ComboBoxItem Content="Testing" />+ <ComboBoxItem Content="Local" />+ </ComboBox>+ </Grid>++ <!-- Row 2a: MongoDB URI (shown only for MongoDB) -->+ <TextBlock x:Name="UriLabel" Grid.Row="2" Grid.Column="0"+ Text="URI"+ VerticalAlignment="Center"+ HorizontalAlignment="Right"+ Margin="0,0,16,0"+ Visibility="Collapsed"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ <StackPanel Grid.Row="2" Grid.Column="1" Spacing="6"+ Visibility="Collapsed" x:Name="MongoUriSection"+ Margin="0,0,0,12">+ <TextBox x:Name="UriInput"+ PlaceholderText="mongodb://user:pass@host:27017/db (optional, overrides fields below)" />+ <TextBox x:Name="MongoOptionsInput"+ PlaceholderText="authSource=admin&replicaSet=rs0&tls=true (optional)" />+ </StackPanel>++ <!-- Row 3: Host/Socket + Port -->+ <TextBlock x:Name="HostLabel" Grid.Row="3" Grid.Column="0"+ Text="Host/Socket"+ VerticalAlignment="Center"+ HorizontalAlignment="Right"+ Margin="0,0,16,0"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ <Grid x:Name="HostRow" Grid.Row="3" Grid.Column="1" Margin="0,0,0,12">+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="*" />+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="Auto" />+ </Grid.ColumnDefinitions>+ <TextBox x:Name="HostInput" Grid.Column="0"+ PlaceholderText="127.0.0.1" />+ <TextBlock Grid.Column="1" Text="Port"+ VerticalAlignment="Center"+ Margin="12,0,8,0"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ <NumberBox x:Name="PortInput" Grid.Column="2"+ Value="5432"+ SpinButtonPlacementMode="Compact"+ Minimum="1" Maximum="65535"+ MinWidth="100" />+ </Grid>++ <!-- Row 4: User + Other Options -->+ <TextBlock x:Name="UserLabel" Grid.Row="4" Grid.Column="0"+ Text="User"+ VerticalAlignment="Center"+ HorizontalAlignment="Right"+ Margin="0,0,16,0"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ <Grid x:Name="UserRow" Grid.Row="4" Grid.Column="1" Margin="0,0,0,12">+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="*" />+ <ColumnDefinition Width="Auto" />+ </Grid.ColumnDefinitions>+ <TextBox x:Name="UserInput" Grid.Column="0"+ PlaceholderText="postgres" />+ <Button Grid.Column="1" Content="Other options"+ Margin="8,0,0,0"+ VerticalAlignment="Stretch" />+ </Grid>++ <!-- Row 5: Password + Store in keychain -->+ <TextBlock x:Name="PasswordLabel" Grid.Row="5" Grid.Column="0"+ Text="Password"+ VerticalAlignment="Center"+ HorizontalAlignment="Right"+ Margin="0,0,16,0"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ <Grid x:Name="PasswordRow" Grid.Row="5" Grid.Column="1" Margin="0,0,0,12">+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="*" />+ <ColumnDefinition Width="Auto" />+ </Grid.ColumnDefinitions>+ <PasswordBox x:Name="PasswordInput" Grid.Column="0"+ PlaceholderText="Enter password" />+ <ComboBox Grid.Column="1"+ Margin="8,0,0,0"+ SelectedIndex="0"+ MinWidth="140">+ <ComboBoxItem Content="Store in keychain" />+ <ComboBoxItem Content="Don't store" />+ </ComboBox>+ </Grid>++ <!-- Row 6: Database + SSL mode -->+ <TextBlock Grid.Row="6" Grid.Column="0"+ Text="Database"+ VerticalAlignment="Center"+ HorizontalAlignment="Right"+ Margin="0,0,16,0"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ <Grid Grid.Row="6" Grid.Column="1" Margin="0,0,0,12">+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="*" />+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="Auto" />+ </Grid.ColumnDefinitions>+ <TextBox x:Name="DatabaseInput" Grid.Column="0"+ PlaceholderText="mydb" />+ <TextBlock Grid.Column="1" Text="SSL mode"+ VerticalAlignment="Center"+ Margin="12,0,8,0"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ <ComboBox x:Name="SslModeInput" Grid.Column="2"+ MinWidth="130"+ SelectedIndex="0">+ <ComboBoxItem Content="Preferred" />+ <ComboBoxItem Content="Disabled" />+ <ComboBoxItem Content="Required" />+ <ComboBoxItem Content="Verify CA" />+ <ComboBoxItem Content="Verify Identity" />+ </ComboBox>+ </Grid>++ <!-- Row 7: SSL Keys -->+ <TextBlock x:Name="SslKeysLabel" Grid.Row="7" Grid.Column="0"+ Text="SSL keys"+ VerticalAlignment="Center"+ HorizontalAlignment="Right"+ Margin="0,0,16,0"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ <StackPanel x:Name="SslKeysRow" Grid.Row="7" Grid.Column="1"+ Orientation="Horizontal" Spacing="6" Margin="0,0,0,12">+ <Button Content="Key..." MinWidth="80" />+ <Button Content="Cert..." MinWidth="80" />+ <Button Content="CA Cert..." MinWidth="80" />+ <Button Width="32" Padding="0">+ <FontIcon Glyph="" FontSize="12" />+ </Button>+ </StackPanel>++ <!-- Row 8: SQLite File Path (shown only for SQLite) -->+ <TextBlock x:Name="FileLabel" Grid.Row="8" Grid.Column="0"+ Text="Database File"+ VerticalAlignment="Center"+ HorizontalAlignment="Right"+ Margin="0,0,16,0"+ Visibility="Collapsed"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ <Grid x:Name="SqliteFileSection" Grid.Row="8" Grid.Column="1"+ Visibility="Collapsed" Margin="0,0,0,12">+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="*" />+ <ColumnDefinition Width="Auto" />+ </Grid.ColumnDefinitions>+ <TextBox x:Name="FilePathInput" Grid.Column="0"+ PlaceholderText="path/to/database.db" />+ <Button Content="Browse..." Grid.Column="1"+ Margin="8,0,0,0"+ Click="BrowseFile_Click" />+ </Grid>++ <!-- Row 9: SSH Section (collapsed by default) -->+ <StackPanel x:Name="SshSection" Grid.Row="9" Grid.Column="0" Grid.ColumnSpan="2"+ Visibility="Collapsed"+ Margin="0,4,0,0"+ Padding="16"+ CornerRadius="8"+ Background="{ThemeResource CardBackgroundFillColorSecondaryBrush}">+ <TextBlock Text="SSH TUNNEL" FontSize="11" FontWeight="SemiBold"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}"+ Margin="0,0,0,12" />+ <Grid>+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="90" />+ <ColumnDefinition Width="*" />+ </Grid.ColumnDefinitions>+ <Grid.RowDefinitions>+ <RowDefinition Height="Auto" />+ <RowDefinition Height="Auto" />+ <RowDefinition Height="Auto" />+ <RowDefinition Height="Auto" />+ <RowDefinition Height="Auto" />+ </Grid.RowDefinitions>++ <TextBlock Grid.Row="0" Grid.Column="0" Text="SSH Host"+ VerticalAlignment="Center" HorizontalAlignment="Right"+ Margin="0,0,12,0"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ <Grid Grid.Row="0" Grid.Column="1" Margin="0,0,0,10">+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="*" />+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="Auto" />+ </Grid.ColumnDefinitions>+ <TextBox x:Name="SshHostInput" Grid.Column="0"+ PlaceholderText="ssh.example.com" />+ <TextBlock Grid.Column="1" Text="Port"+ VerticalAlignment="Center" Margin="12,0,8,0"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ <NumberBox x:Name="SshPortInput" Grid.Column="2"+ Value="22" SpinButtonPlacementMode="Compact"+ MinWidth="80" />+ </Grid>++ <TextBlock Grid.Row="1" Grid.Column="0" Text="Username"+ VerticalAlignment="Center" HorizontalAlignment="Right"+ Margin="0,0,12,0"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ <TextBox x:Name="SshUserInput" Grid.Row="1" Grid.Column="1"+ PlaceholderText="user" Margin="0,0,0,10" />++ <TextBlock Grid.Row="2" Grid.Column="0" Text="Auth"+ VerticalAlignment="Center" HorizontalAlignment="Right"+ Margin="0,0,12,0"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ <ComboBox x:Name="SshAuthInput" Grid.Row="2" Grid.Column="1"+ HorizontalAlignment="Stretch" SelectedIndex="0"+ Margin="0,0,0,10"+ SelectionChanged="SshAuth_Changed">+ <ComboBoxItem Content="Password" />+ <ComboBoxItem Content="Private Key" />+ <ComboBoxItem Content="Key + Passphrase" />+ </ComboBox>++ <TextBlock Grid.Row="3" Grid.Column="0" Text="Password"+ VerticalAlignment="Center" HorizontalAlignment="Right"+ Margin="0,0,12,0"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ <PasswordBox x:Name="SshPasswordInput" Grid.Row="3" Grid.Column="1"+ PlaceholderText="SSH password" Margin="0,0,0,10" />++ <TextBlock Grid.Row="4" Grid.Column="0" Text="Key file"+ VerticalAlignment="Center" HorizontalAlignment="Right"+ Margin="0,0,12,0"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ <Grid x:Name="SshKeySection" Grid.Row="4" Grid.Column="1"+ Visibility="Collapsed">+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="*" />+ <ColumnDefinition Width="Auto" />+ </Grid.ColumnDefinitions>+ <TextBox x:Name="SshKeyInput" Grid.Column="0"+ PlaceholderText="~/.ssh/id_rsa" />+ <Button Content="Browse..." Grid.Column="1"+ Margin="8,0,0,0"+ Click="BrowseSshKey_Click" />+ </Grid>+ </Grid>+ </StackPanel>+ </Grid>+ </ScrollViewer>++ <!-- Bottom Action Bar (matches macOS: Over SSH | Save | Test | Connect) -->+ <Border BorderThickness="0,1,0,0"+ BorderBrush="{ThemeResource DividerStrokeColorDefaultBrush}"+ Margin="0,12,0,0"+ Padding="0,12,0,0">+ <Grid>+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="*" />+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="Auto" />+ </Grid.ColumnDefinitions>++ <ToggleButton x:Name="SshToggle" Grid.Column="0"+ Content="Over SSH"+ Click="SshToggle_Click" />++ <Button x:Name="SaveButton" Grid.Column="2"+ Content="Save" Margin="0,0,8,0"+ Click="SaveButton_Click" />+ <Button x:Name="TestButton" Grid.Column="3"+ Content="Test" Margin="0,0,8,0"+ Click="TestButton_Click" />+ <Button x:Name="ConnectButton" Grid.Column="4"+ Content="Connect"+ Style="{StaticResource AccentButtonStyle}"+ Click="ConnectButton_Click" />+ </Grid>+ </Border>+ </StackPanel>+</UserControl>diff --git a/windows/Gridex/ConnectionManager.cpp b/windows/Gridex/ConnectionManager.cppnew file mode 100644index 0000000..0f5991e--- /dev/null+++ b/windows/Gridex/ConnectionManager.cpp@@ -0,0 +1,116 @@+#include <windows.h>+#include "Models/ConnectionManager.h"+#include "Models/PostgreSQLAdapter.h"+#include "Models/MySQLAdapter.h"+#include "Models/SQLiteAdapter.h"+#include "Models/RedisAdapter.h"+#include "Models/MongoDBAdapter.h"+#include "Models/MSSQLAdapter.h"++namespace DBModels+{+ // Helper: if SSH tunnel is configured, establish it and rewrite+ // the connection config to point at localhost:localPort instead+ // of the remote DB host. Returns the (possibly modified) config.+ static ConnectionConfig applySSHTunnel(+ const ConnectionConfig& config,+ const std::wstring& password,+ std::unique_ptr<SSHTunnelService>& tunnel)+ {+ if (!config.sshConfig.has_value())+ return config;++ auto& ssh = config.sshConfig.value();+ if (ssh.host.empty())+ return config; // SSH not actually configured++ // Use SSH-specific password from config. Falls back to DB+ // password only if SSH password is empty (backward compat).+ auto sshPass = ssh.password.empty() ? password : ssh.password;++ auto remoteHost = std::string(+ config.host.begin(), config.host.end());+ int remotePort = config.port > 0 ? config.port : 5432;++ tunnel = std::make_unique<SSHTunnelService>();+ auto localPort = tunnel->establish(+ ssh, sshPass, remoteHost, remotePort);++ // Rewrite config to connect through tunnel+ ConnectionConfig tunneled = config;+ tunneled.host = L"127.0.0.1";+ tunneled.port = localPort;+ tunneled.sshConfig.reset(); // don't recurse+ return tunneled;+ }++ std::shared_ptr<DatabaseAdapter> ConnectionManager::connect(+ const ConnectionConfig& config,+ const std::wstring& password)+ {+ // Disconnect existing connection + tear down old tunnel+ disconnect();++ // Establish SSH tunnel if configured+ auto effectiveConfig = applySSHTunnel(config, password, sshTunnel_);++ activeAdapter_ = createAdapter(config.databaseType);+ activeConfig_ = config; // store ORIGINAL config (not tunneled)+ activeAdapter_->connect(effectiveConfig, password);++ return activeAdapter_;+ }++ void ConnectionManager::disconnect()+ {+ if (activeAdapter_)+ {+ if (activeAdapter_->isConnected())+ activeAdapter_->disconnect();+ activeAdapter_.reset();+ }+ // Tear down SSH tunnel after DB disconnect+ if (sshTunnel_)+ {+ sshTunnel_->close();+ sshTunnel_.reset();+ }+ }++ bool ConnectionManager::testConnection(+ const ConnectionConfig& config,+ const std::wstring& password)+ {+ // Test with SSH tunnel if configured+ std::unique_ptr<SSHTunnelService> testTunnel;+ auto effectiveConfig = applySSHTunnel(config, password, testTunnel);++ auto adapter = createAdapter(config.databaseType);+ bool ok = adapter->testConnection(effectiveConfig, password);++ if (testTunnel) testTunnel->close();+ return ok;+ }++ std::shared_ptr<DatabaseAdapter> ConnectionManager::createAdapter(DatabaseType type)+ {+ switch (type)+ {+ case DatabaseType::PostgreSQL:+ return std::make_shared<PostgreSQLAdapter>();+ case DatabaseType::MySQL:+ return std::make_shared<MySQLAdapter>();+ case DatabaseType::SQLite:+ return std::make_shared<SQLiteAdapter>();+ case DatabaseType::Redis:+ return std::make_shared<RedisAdapter>();+ case DatabaseType::MongoDB:+ return std::make_shared<MongoDBAdapter>();+ case DatabaseType::MSSQLServer:+ return std::make_shared<MSSQLAdapter>();+ default:+ throw DatabaseError(DatabaseError::Code::ConnectionFailed,+ "Unsupported database type");+ }+ }+}diff --git a/windows/Gridex/CredentialManager.cpp b/windows/Gridex/CredentialManager.cppnew file mode 100644index 0000000..15cf195--- /dev/null+++ b/windows/Gridex/CredentialManager.cpp@@ -0,0 +1,69 @@+#include <windows.h>+#include "Models/CredentialManager.h"+#include <wincred.h>+#pragma comment(lib, "Advapi32.lib")++namespace DBModels+{+ std::wstring CredentialManager::TargetName(const std::wstring& connectionId)+ {+ return std::wstring(TARGET_PREFIX) + connectionId;+ }++ bool CredentialManager::Save(const std::wstring& connectionId, const std::wstring& password)+ {+ std::wstring target = TargetName(connectionId);++ // Convert password to byte blob+ DWORD blobSize = static_cast<DWORD>(password.size() * sizeof(wchar_t));++ CREDENTIALW cred = {};+ cred.Type = CRED_TYPE_GENERIC;+ cred.TargetName = const_cast<LPWSTR>(target.c_str());+ cred.CredentialBlobSize = blobSize;+ cred.CredentialBlob = reinterpret_cast<LPBYTE>(const_cast<wchar_t*>(password.c_str()));+ cred.Persist = CRED_PERSIST_LOCAL_MACHINE;+ cred.UserName = const_cast<LPWSTR>(L"Gridex");++ return CredWriteW(&cred, 0) == TRUE;+ }++ std::wstring CredentialManager::Load(const std::wstring& connectionId)+ {+ std::wstring target = TargetName(connectionId);++ PCREDENTIALW pCred = nullptr;+ if (!CredReadW(target.c_str(), CRED_TYPE_GENERIC, 0, &pCred))+ return L"";++ std::wstring password;+ if (pCred->CredentialBlob && pCred->CredentialBlobSize > 0)+ {+ DWORD charCount = pCred->CredentialBlobSize / sizeof(wchar_t);+ password.assign(+ reinterpret_cast<const wchar_t*>(pCred->CredentialBlob),+ charCount);+ }++ CredFree(pCred);+ return password;+ }++ bool CredentialManager::Remove(const std::wstring& connectionId)+ {+ std::wstring target = TargetName(connectionId);+ return CredDeleteW(target.c_str(), CRED_TYPE_GENERIC, 0) == TRUE;+ }++ bool CredentialManager::Exists(const std::wstring& connectionId)+ {+ std::wstring target = TargetName(connectionId);+ PCREDENTIALW pCred = nullptr;+ if (CredReadW(target.c_str(), CRED_TYPE_GENERIC, 0, &pCred))+ {+ CredFree(pCred);+ return true;+ }+ return false;+ }+}diff --git a/windows/Gridex/DataGridView.cpp b/windows/Gridex/DataGridView.cppnew file mode 100644index 0000000..42d2985--- /dev/null+++ b/windows/Gridex/DataGridView.cpp@@ -0,0 +1,888 @@+#include "pch.h"+#include "xaml-includes.h"+#include "DataGridView.h"+#include <winrt/Windows.UI.Text.h>+#include <winrt/Windows.UI.Core.h>+#include <winrt/Windows.System.h>+#include <winrt/Microsoft.UI.Input.h>+#include <winrt/Windows.ApplicationModel.DataTransfer.h>+#include <algorithm>+#include <cmath>+#if __has_include("DataGridView.g.cpp")+#include "DataGridView.g.cpp"+#endif++namespace winrt::Gridex::implementation+{+ namespace mux = winrt::Microsoft::UI::Xaml;+ namespace muxc = winrt::Microsoft::UI::Xaml::Controls;+ namespace muxm = winrt::Microsoft::UI::Xaml::Media;++ // Forward declaration — defined later in the file but called from+ // BuildRowElement's DoubleTapped lambda above its definition site.+ static muxc::StackPanel findRowPanelByDataIndex(+ muxc::Panel const& container, int dataIdx);++ // Cap on characters fed to a row's TextBlock. The full value is kept in+ // data_.rows so DetailsPanel, copy, and inline edit still see everything+ // — but TextBlock's CharacterEllipsis trimming has to measure the whole+ // string to know where to clip, and multi-KB HTML/text cells make the+ // first measure pass dominate BuildRows(). 80 chars is enough preview+ // for any column at default width (~150-300px) and keeps measure cost+ // bounded; the rest of the value is one click away in DetailsPanel.+ static constexpr size_t MAX_CELL_DISPLAY_CHARS = 80;++ void DataGridView::EnsureCellStyles()+ {+ if (cellStyle_) return; // already cached+ auto resources = this->Resources();+ if (auto v = resources.TryLookup(winrt::box_value(L"GridCellStyle")))+ cellStyle_ = v.try_as<mux::Style>();+ if (auto v = resources.TryLookup(winrt::box_value(L"GridRowNumStyle")))+ rowNumStyle_ = v.try_as<mux::Style>();+ }++ DataGridView::DataGridView()+ {+ InitializeComponent();++ // Rows are plain StackPanels (not focusable). Without this the+ // UserControl never receives focus after a row click, so KeyDown+ // (Delete, Ctrl+C) never fires. Making the UserControl itself a+ // tab stop lets SelectRow programmatically park focus here.+ this->IsTabStop(true);+ this->UseSystemFocusVisuals(false);++ this->KeyDown([this](winrt::Windows::Foundation::IInspectable const& sender,+ mux::Input::KeyRoutedEventArgs const& e)+ {+ Grid_KeyDown(sender, e);+ });+ this->Loaded([this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ DataScroller().ViewChanged(+ [this](winrt::Windows::Foundation::IInspectable const& sender,+ muxc::ScrollViewerViewChangedEventArgs const& e)+ {+ DataScroller_ViewChanged(sender, e);+ });++ // Shift + mouse wheel → horizontal scroll.+ // Attached to the inner StackPanel (DataRows) rather than the+ // ScrollViewer itself: ScrollViewer installs its own internal+ // wheel handler for vertical scroll, so a handler on the child+ // fires first and can intercept Shift-wheel before the SV+ // consumes it. No Shift → leave Handled=false so the default+ // vertical-scroll path still runs.+ DataRows().PointerWheelChanged(+ [this](winrt::Windows::Foundation::IInspectable const&,+ mux::Input::PointerRoutedEventArgs const& e)+ {+ auto mods = e.KeyModifiers();+ bool shiftHeld =+ (static_cast<uint32_t>(mods) &+ static_cast<uint32_t>(winrt::Windows::System::VirtualKeyModifiers::Shift)) != 0;+ if (!shiftHeld) return;++ int delta = e.GetCurrentPoint(nullptr).Properties().MouseWheelDelta();+ if (delta == 0) return;++ // Wheel delta is ±120 per click; subtract so wheel-up+ // scrolls left (matches the Windows convention used by+ // VS Code, Excel, File Explorer, etc.).+ double newH = DataScroller().HorizontalOffset() - static_cast<double>(delta);+ if (newH < 0.0) newH = 0.0;+ DataScroller().ChangeView(newH, nullptr, nullptr, true);+ e.Handled(true);+ });+ });+ }++ void DataGridView::SetData(const DBModels::QueryResult& result)+ {+ data_ = result;+ selectedRow_ = -1;++ // EXPLAIN / EXPLAIN ANALYZE (and similar verbatim single-column+ // outputs) must not be truncated at 80 chars — each row is a+ // full plan line the user needs to read end-to-end. Detect the+ // PostgreSQL convention (single "QUERY PLAN" column) and flip+ // off the per-cell truncation for this render pass only.+ skipCellTruncation_ =+ (data_.columnNames.size() == 1 &&+ data_.columnNames[0] == L"QUERY PLAN");++ ComputeColumnWidths();+ BuildHeaders();+ BuildRows();+ }++ const DBModels::TableRow* DataGridView::GetSelectedRow() const+ {+ if (selectedRow_ >= 0 && selectedRow_ < static_cast<int>(data_.rows.size()))+ return &data_.rows[selectedRow_];+ return nullptr;+ }++ // ── Compute uniform column widths ──────────────────+ void DataGridView::ComputeColumnWidths()+ {+ size_t nCols = data_.columnNames.size();+ columnWidths_.clear();+ columnWidths_.resize(nCols, COL_DEFAULT_WIDTH);++ if (nCols == 0) return;++ // Single-column verbatim mode (EXPLAIN / EXPLAIN ANALYZE):+ // widen the column to fit the longest plan line so horizontal+ // scroll reveals the full content. TextTrimming in the cached+ // cell style would otherwise clip at the viewport width even+ // though the string itself is intact in memory.+ if (skipCellTruncation_ && nCols == 1)+ {+ size_t maxChars = data_.columnNames[0].size();+ for (const auto& row : data_.rows)+ {+ auto it = row.find(data_.columnNames[0]);+ if (it != row.end() && it->second.size() > maxChars)+ maxChars = it->second.size();+ }+ // Rough monospace estimate: ~7px per char + 24px padding.+ // Cap below 4000px to keep scroll bounds sane on giant plans.+ double width = static_cast<double>(maxChars) * 7.0 + 24.0;+ if (width < COL_DEFAULT_WIDTH) width = COL_DEFAULT_WIDTH;+ if (width > 4000.0) width = 4000.0;+ columnWidths_[0] = width;+ return;+ }++ // Distribute available width evenly ONLY when there's leftover+ // space at default width. Never shrink below COL_DEFAULT_WIDTH —+ // 30+ skinny columns are unreadable; horizontal scroll is the+ // standard DB-tool behavior for wide tables.+ double availWidth = this->ActualWidth() - ROW_NUM_WIDTH - 20.0; // 20px scrollbar+ if (availWidth > 0 && nCols > 0)+ {+ double evenWidth = availWidth / static_cast<double>(nCols);+ if (evenWidth < COL_DEFAULT_WIDTH) evenWidth = COL_DEFAULT_WIDTH;+ if (evenWidth > COL_MAX_WIDTH) evenWidth = COL_MAX_WIDTH;+ for (size_t i = 0; i < nCols; i++)+ columnWidths_[i] = evenWidth;+ }+ }++ // ── Header rendering with sort + resize handle ─────+ void DataGridView::BuildHeaders()+ {+ HeaderRow().Children().Clear();++ // Row-number column+ muxc::Border numHeader;+ numHeader.Width(ROW_NUM_WIDTH);+ numHeader.MinHeight(ROW_HEIGHT);+ numHeader.Padding(mux::Thickness{ 4.0, 0.0, 4.0, 0.0 });+ numHeader.BorderBrush(muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(40, 128, 128, 128)));+ numHeader.BorderThickness(mux::Thickness{ 0, 0, 1, 0 });+ {+ muxc::TextBlock lbl;+ lbl.Text(L"#");+ lbl.FontSize(11.0);+ lbl.FontWeight(winrt::Windows::UI::Text::FontWeights::SemiBold());+ lbl.VerticalAlignment(mux::VerticalAlignment::Center);+ lbl.HorizontalAlignment(mux::HorizontalAlignment::Center);+ lbl.Opacity(0.5);+ numHeader.Child(lbl);+ }+ HeaderRow().Children().Append(numHeader);++ for (size_t ci = 0; ci < data_.columnNames.size(); ci++)+ {+ auto& colName = data_.columnNames[ci];+ double colWidth = (ci < columnWidths_.size()) ? columnWidths_[ci] : COL_DEFAULT_WIDTH;++ // Container: header cell + resize grip+ muxc::Grid cellGrid;+ cellGrid.Width(colWidth);+ cellGrid.MinHeight(ROW_HEIGHT);++ // Two columns: content (star) + resize grip (4px)+ auto contentCol = mux::GridLength{ 1.0, mux::GridUnitType::Star };+ auto gripCol = mux::GridLength{ 8.0, mux::GridUnitType::Pixel };+ muxc::ColumnDefinition cd1; cd1.Width(contentCol);+ muxc::ColumnDefinition cd2; cd2.Width(gripCol);+ cellGrid.ColumnDefinitions().Append(cd1);+ cellGrid.ColumnDefinitions().Append(cd2);++ // Header button (sort on click)+ muxc::Button headerBtn;+ headerBtn.HorizontalAlignment(mux::HorizontalAlignment::Stretch);+ headerBtn.VerticalAlignment(mux::VerticalAlignment::Stretch);+ headerBtn.Padding(mux::Thickness{ 8.0, 0.0, 4.0, 0.0 });+ headerBtn.Background(muxm::SolidColorBrush(winrt::Windows::UI::Colors::Transparent()));+ headerBtn.BorderThickness(mux::Thickness{ 0, 0, 0, 0 });+ muxc::Grid::SetColumn(headerBtn, 0);++ // Header content layout: Grid with [auto icon] [* label] [auto sort].+ // Star column on the label means it auto-stretches to whatever+ // space is left after the icons — when the user resizes the+ // outer cellGrid, the label's available width tracks live via+ // layout pass, no manual MaxWidth bookkeeping needed.+ muxc::Grid headerContent;+ {+ muxc::ColumnDefinition iconCol, labelCol, sortCol;+ iconCol.Width(mux::GridLength{ 0.0, mux::GridUnitType::Auto });+ labelCol.Width(mux::GridLength{ 1.0, mux::GridUnitType::Star });+ sortCol.Width(mux::GridLength{ 0.0, mux::GridUnitType::Auto });+ headerContent.ColumnDefinitions().Append(iconCol);+ headerContent.ColumnDefinitions().Append(labelCol);+ headerContent.ColumnDefinitions().Append(sortCol);+ }++ // Column type icon at column 0+ std::wstring colType;+ if (ci < data_.columnTypes.size()) colType = data_.columnTypes[ci];+ muxc::FontIcon typeIcon;+ typeIcon.FontSize(10.0);+ typeIcon.Opacity(0.4);+ typeIcon.Margin(mux::Thickness{ 0.0, 0.0, 4.0, 0.0 });+ if (colType.find(L"int") != std::wstring::npos || colType.find(L"numeric") != std::wstring::npos)+ typeIcon.Glyph(L"\xE8EF");+ else if (colType.find(L"bool") != std::wstring::npos)+ typeIcon.Glyph(L"\xE73E");+ else if (colType.find(L"time") != std::wstring::npos || colType.find(L"date") != std::wstring::npos)+ typeIcon.Glyph(L"\xE787");+ else+ typeIcon.Glyph(L"\xE8C1");+ muxc::Grid::SetColumn(typeIcon, 0);+ headerContent.Children().Append(typeIcon);++ // Label at column 1 — fills the star column. NO MaxWidth — the+ // grid layout constrains it; trimming kicks in only when the+ // column is actually narrower than the text.+ muxc::TextBlock lbl;+ lbl.Text(winrt::hstring(colName));+ lbl.FontSize(11.0);+ lbl.FontWeight(winrt::Windows::UI::Text::FontWeights::SemiBold());+ lbl.VerticalAlignment(mux::VerticalAlignment::Center);+ lbl.TextTrimming(mux::TextTrimming::CharacterEllipsis);+ lbl.TextWrapping(mux::TextWrapping::NoWrap);+ muxc::Grid::SetColumn(lbl, 1);+ headerContent.Children().Append(lbl);++ // Sort indicator at column 2 (only if this column is the sort key)+ if (sortColumn_ == colName)+ {+ muxc::FontIcon sortIcon;+ sortIcon.FontSize(9.0);+ sortIcon.Glyph(sortAscending_ ? L"\xE70E" : L"\xE70D");+ sortIcon.Opacity(0.7);+ sortIcon.Margin(mux::Thickness{ 4.0, 0.0, 0.0, 0.0 });+ muxc::Grid::SetColumn(sortIcon, 2);+ headerContent.Children().Append(sortIcon);+ }++ headerBtn.Content(headerContent);++ std::wstring col = colName;+ headerBtn.Click([this, col](auto&&, auto&&)+ {+ if (sortColumn_ == col)+ sortAscending_ = !sortAscending_;+ else+ {+ sortColumn_ = col;+ sortAscending_ = true;+ }+ BuildHeaders();+ if (OnSortRequested)+ OnSortRequested(sortColumn_, sortAscending_);+ });++ cellGrid.Children().Append(headerBtn);++ // Resize grip — wider hit area (8px) with visible line (1px) inside+ muxc::Grid resizeGrip;+ resizeGrip.Width(8.0);+ resizeGrip.Background(muxm::SolidColorBrush(winrt::Windows::UI::Colors::Transparent()));+ muxc::Grid::SetColumn(resizeGrip, 1);++ // Visible 1px line centered in the grip+ muxc::Border gripLine;+ gripLine.Width(1.0);+ gripLine.HorizontalAlignment(mux::HorizontalAlignment::Center);+ gripLine.Background(muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(50, 128, 128, 128)));+ gripLine.IsHitTestVisible(false);+ resizeGrip.Children().Append(gripLine);++ // Cursor: use IUIElementProtected.ProtectedCursor — the only+ // reliable WinUI 3 cursor API. cppwinrt strips ProtectedCursor+ // from the public projection of UIElement, but the ABI interface+ // winrt::Microsoft::UI::Xaml::IUIElementProtected is publicly+ // declared and any UIElement implements it. Set it inside the+ // grip's Loaded handler so it runs after the element is fully+ // attached to the visual tree (ProtectedCursor throws otherwise).+ //+ // Win32 SetCursor() in PointerMoved was tried first but races+ // with the WinUI input pipeline's WM_SETCURSOR handling and+ // never sticks visually.+ resizeGrip.Loaded(+ [](winrt::Windows::Foundation::IInspectable const& sender,+ mux::RoutedEventArgs const&)+ {+ static auto sizeWECursor =+ winrt::Microsoft::UI::Input::InputSystemCursor::Create(+ winrt::Microsoft::UI::Input::InputSystemCursorShape::SizeWestEast);+ if (auto el = sender.try_as<mux::UIElement>())+ el.as<winrt::Microsoft::UI::Xaml::IUIElementProtected>()+ .ProtectedCursor(sizeWECursor);+ });++ // Resize drag via PointerPressed/Moved/Released+ int colIndex = static_cast<int>(ci);+ resizeGrip.PointerPressed([this, colIndex](winrt::Windows::Foundation::IInspectable const& sender,+ mux::Input::PointerRoutedEventArgs const& e)+ {+ resizingCol_ = colIndex;+ auto point = e.GetCurrentPoint(this->try_as<mux::UIElement>());+ resizeStartX_ = point.Position().X;+ resizeStartWidth_ = (colIndex < static_cast<int>(columnWidths_.size()))+ ? columnWidths_[colIndex] : COL_DEFAULT_WIDTH;+ auto el = sender.try_as<mux::UIElement>();+ if (el) el.CapturePointer(e.Pointer());+ e.Handled(true);+ });++ resizeGrip.PointerMoved([this](winrt::Windows::Foundation::IInspectable const&,+ mux::Input::PointerRoutedEventArgs const& e)+ {+ if (resizingCol_ < 0) { return; }+ auto point = e.GetCurrentPoint(this->try_as<mux::UIElement>());+ double delta = point.Position().X - resizeStartX_;+ double newWidth = resizeStartWidth_ + delta;+ if (newWidth < COL_MIN_WIDTH) newWidth = COL_MIN_WIDTH;+ if (newWidth > COL_MAX_WIDTH) newWidth = COL_MAX_WIDTH;+ if (resizingCol_ < static_cast<int>(columnWidths_.size()))+ {+ columnWidths_[resizingCol_] = newWidth;+ // Update header cell width live+ // Header: index 0 = row num, then columns start at 1+ uint32_t headerIdx = static_cast<uint32_t>(resizingCol_) + 1;+ if (headerIdx < HeaderRow().Children().Size())+ {+ auto headerEl = HeaderRow().Children().GetAt(headerIdx);+ auto grid = headerEl.try_as<muxc::Grid>();+ if (grid) grid.Width(newWidth);+ }+ }+ e.Handled(true);+ });++ resizeGrip.PointerReleased([this](winrt::Windows::Foundation::IInspectable const& sender,+ mux::Input::PointerRoutedEventArgs const& e)+ {+ if (resizingCol_ >= 0)+ {+ auto el = sender.try_as<mux::UIElement>();+ if (el) el.ReleasePointerCapture(e.Pointer());+ resizingCol_ = -1;+ // Rebuild rows with new column widths+ BuildRows();+ }+ e.Handled(true);+ });++ cellGrid.Children().Append(resizeGrip);++ // Right border for the whole cell+ muxc::Border rightBorder;+ rightBorder.HorizontalAlignment(mux::HorizontalAlignment::Right);+ rightBorder.Width(1.0);+ rightBorder.Background(muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(40, 128, 128, 128)));+ rightBorder.IsHitTestVisible(false);+ muxc::Grid::SetColumnSpan(rightBorder, 2);+ cellGrid.Children().Append(rightBorder);++ HeaderRow().Children().Append(cellGrid);+ }+ }++ // ── Row rendering (full sync) ───────────────────────+ //+ // Render every row of the current page in one pass. The user wants the+ // whole page on first paint (database tool feel). Per-cell cost is the+ // bottleneck on wide tables, so BuildRowElement is hand-tuned to issue+ // the minimum number of WinRT property crossings per TextBlock.+ //+ // After this returns, every row is realized in the visual tree and the+ // ScrollViewer handles scrolling natively — no per-frame rebuild work,+ // no scroll lag.+ void DataGridView::BuildRows()+ {+ EnsureCellStyles();++ auto rows = DataRows();+ rows.Visibility(mux::Visibility::Collapsed); // coalesce layout passes+ rows.Children().Clear();++ const int totalRows = static_cast<int>(data_.rows.size());+ for (int i = 0; i < totalRows; i++)+ rows.Children().Append(BuildRowElement(i));++ rows.Visibility(mux::Visibility::Visible);++ // Re-apply selection highlight (selectedRow_ may carry over from+ // a previous load if the host hasn't reset it).+ if (selectedRow_ >= 0 && selectedRow_ < totalRows)+ HighlightRow(selectedRow_);+ }++ // Build a single row's UI element. Layout: a horizontal StackPanel that+ // IS the row container, the click target, the bg fill, and the cell+ // host. No Button (drops the Button template + visual states), no Grid+ // (drops N+1 ColumnDefinitions per row), no Grid::SetColumn calls.+ //+ // Children layout: index 0 = row number, index k+1 = data cell for col k.+ // The row's data index is stored in Tag for selection / edit lookup.+ muxc::StackPanel DataGridView::BuildRowElement(int rowIdx)+ {+ const auto& row = data_.rows[rowIdx];+ const bool alternate = (rowIdx % 2 == 1);+ const size_t nCols = data_.columnNames.size();++ auto altRowBg = muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(8, 128, 128, 128));+ auto normalRowBg = muxm::SolidColorBrush(+ winrt::Windows::UI::Colors::Transparent());++ muxc::StackPanel rowPanel;+ rowPanel.Orientation(muxc::Orientation::Horizontal);+ rowPanel.Height(ROW_HEIGHT);+ rowPanel.Background(alternate ? altRowBg : normalRowBg);+ // Tag = data row index. Used by findRowPanelByDataIndex /+ // GetRowPanel / HighlightRow to locate the row visual.+ rowPanel.Tag(winrt::box_value(static_cast<int32_t>(rowIdx)));++ // Row number cell — uses the cached row-num style (4 properties+ // baked in). Only Text + Width set per call.+ muxc::TextBlock numLbl;+ if (rowNumStyle_) numLbl.Style(rowNumStyle_);+ numLbl.Text(winrt::hstring(std::to_wstring(rowIdx + 1)));+ numLbl.Width(ROW_NUM_WIDTH);+ rowPanel.Children().Append(numLbl);++ // Statics shared across all rows / cells. Constructed exactly once+ // per process — keeps the inner loop free of std::wstring allocations+ // for the common short-cell path.+ static const std::wstring kEmptyStr;+ static const std::wstring kNullText{ L"NULL" };++ // Reusable scratch buffer for cells that overflow MAX_CELL_DISPLAY_CHARS.+ // Hoisted out of the column loop and reserved upfront so a long cell+ // costs an in-place `assign` (no heap alloc), not a fresh wstring.+ std::wstring truncBuf;+ truncBuf.reserve(MAX_CELL_DISPLAY_CHARS + 1);++ // Data cells. With the cached cellStyle_, per-cell crossings are+ // just: Style + Text + Width (+ Opacity only on null/empty). The+ // 4 static properties (VerticalAlignment, TextTrimming, TextWrapping,+ // Padding, FontSize) come from the Style in a single property set.+ for (size_t ci = 0; ci < nCols; ci++)+ {+ const auto& colName = data_.columnNames[ci];+ double colWidth = (ci < columnWidths_.size()) ? columnWidths_[ci] : COL_DEFAULT_WIDTH;++ // Bind val by const-ref to the map's storage — zero alloc, zero+ // copy in the inner loop's hottest path.+ auto it = row.find(colName);+ const std::wstring& val = (it != row.end()) ? it->second : kEmptyStr;++ const bool isNull = DBModels::isNullCell(val);+ // Pick the display source by pointer so the short-cell path+ // does no string work at all. EXPLAIN output bypasses the+ // truncation entirely — its lines are always short enough+ // and must render verbatim.+ const std::wstring* displayPtr;+ if (isNull)+ {+ displayPtr = &kNullText;+ }+ else if (!skipCellTruncation_ && val.size() > MAX_CELL_DISPLAY_CHARS)+ {+ truncBuf.assign(val, 0, MAX_CELL_DISPLAY_CHARS);+ truncBuf.push_back(L'\x2026'); // single-char ellipsis+ displayPtr = &truncBuf;+ }+ else+ {+ displayPtr = &val;+ }++ muxc::TextBlock cellLbl;+ if (cellStyle_) cellLbl.Style(cellStyle_);+ cellLbl.Text(winrt::hstring(*displayPtr));+ cellLbl.Width(colWidth);+ if (isNull || val.empty())+ cellLbl.Opacity(0.4);++ rowPanel.Children().Append(cellLbl);+ }++ // Selection on Tap. Tap fires on any FrameworkElement.+ const int ri = rowIdx;+ rowPanel.Tapped(+ [this, ri](winrt::Windows::Foundation::IInspectable const&,+ mux::Input::TappedRoutedEventArgs const&)+ {+ SelectRow(ri);+ });++ // DoubleTap → inline edit. CRITICAL: do NOT capture the row panel+ // by value here — that would store a strong COM ref to the panel+ // inside a delegate the panel itself owns, forming a reference+ // cycle that survives Children().Clear() and leaks every old row+ // forever (C++/WinRT has no GC). Look the panel up by data index+ // at click time instead; the O(N) walk is irrelevant on a click.+ rowPanel.DoubleTapped(+ [this, ri](winrt::Windows::Foundation::IInspectable const&,+ mux::Input::DoubleTappedRoutedEventArgs const& e)+ {+ auto src = e.OriginalSource().try_as<mux::FrameworkElement>();+ if (!src) return;+ auto sp = findRowPanelByDataIndex(DataRows(), ri);+ if (!sp) return;+ auto children = sp.Children();+ // Skip index 0 (row number); data cells start at index 1.+ for (uint32_t k = 1; k < children.Size(); k++)+ {+ if (children.GetAt(k) == src)+ {+ BeginCellEdit(ri, static_cast<size_t>(k - 1));+ e.Handled(true);+ return;+ }+ }+ });++ return rowPanel;+ }++ void DataGridView::SelectRow(int index)+ {+ int prevRow = selectedRow_;+ selectedRow_ = index;+ if (prevRow >= 0) HighlightRow(prevRow);+ HighlightRow(index);+ if (OnRowSelected) OnRowSelected(index);++ // Park focus on the UserControl so subsequent KeyDown events+ // (Delete, Ctrl+C, etc.) are routed to Grid_KeyDown. Row panels+ // themselves are not focusable.+ this->Focus(mux::FocusState::Programmatic);+ }++ // Find the realized row StackPanel for a given DATA index by walking+ // DataRows().Children() and matching the Tag we set in BuildRowElement.+ // Returns nullptr if the row hasn't been realized.+ static muxc::StackPanel findRowPanelByDataIndex(+ muxc::Panel const& container, int dataIdx)+ {+ auto children = container.Children();+ for (uint32_t k = 0; k < children.Size(); k++)+ {+ auto sp = children.GetAt(k).try_as<muxc::StackPanel>();+ if (!sp) continue;+ auto tag = sp.Tag();+ if (!tag) continue;+ int idx = winrt::unbox_value<int32_t>(tag);+ if (idx == dataIdx) return sp;+ }+ return nullptr;+ }++ void DataGridView::HighlightRow(int index)+ {+ if (index < 0 || index >= static_cast<int>(data_.rows.size()))+ return;+ auto sp = findRowPanelByDataIndex(DataRows(), index);+ if (!sp) return;++ if (index == selectedRow_)+ {+ sp.Background(muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(30, 0, 120, 212)));+ }+ else+ {+ bool alternate = (index % 2 == 1);+ auto bg = alternate+ ? winrt::Windows::UI::ColorHelper::FromArgb(8, 128, 128, 128)+ : winrt::Windows::UI::Colors::Transparent();+ sp.Background(muxm::SolidColorBrush(bg));+ }+ }++ // ── Mark/clear row visual states ─────────────────+ void DataGridView::MarkRowDeleted(int index)+ {+ if (index < 0 || index >= static_cast<int>(data_.rows.size()))+ return;+ auto sp = findRowPanelByDataIndex(DataRows(), index);+ if (!sp) return;+ sp.Background(muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(40, 196, 43, 28)));+ sp.Opacity(0.5);+ }++ void DataGridView::ClearRowMarks()+ {+ for (uint32_t i = 0; i < DataRows().Children().Size(); i++)+ {+ auto sp = DataRows().Children().GetAt(i).try_as<muxc::StackPanel>();+ if (!sp) continue;+ int dataIdx = static_cast<int>(i);+ if (auto tag = sp.Tag()) dataIdx = winrt::unbox_value<int32_t>(tag);+ bool alternate = (dataIdx % 2 == 1);+ auto bg = alternate+ ? winrt::Windows::UI::ColorHelper::FromArgb(8, 128, 128, 128)+ : winrt::Windows::UI::Colors::Transparent();+ sp.Background(muxm::SolidColorBrush(bg));+ sp.Opacity(1.0);+ }+ }++ // ── Inline cell editing ──────────────────────────+ // Resolve the row's StackPanel for a given DATA index. Returns nullptr+ // if the row hasn't been realized.+ muxc::StackPanel DataGridView::GetRowPanel(int rowIndex)+ {+ if (rowIndex < 0 || rowIndex >= static_cast<int>(data_.rows.size()))+ return nullptr;+ return findRowPanelByDataIndex(DataRows(), rowIndex);+ }++ // Inline edit: row StackPanel children index 0 = row number, index k+1 =+ // data cell for column k. We swap children[colIndex+1] with a TextBox.+ void DataGridView::BeginCellEdit(int rowIndex, size_t colIndex)+ {+ // Read-only mode: bail out before we touch the visual tree. Used+ // for Redis adapters where inline SQL-style edits cannot map to+ // Redis commands safely.+ if (readOnly_) return;++ if (rowIndex < 0 || rowIndex >= static_cast<int>(data_.rows.size()))+ return;+ if (colIndex >= data_.columnNames.size()) return;++ auto rowPanel = GetRowPanel(rowIndex);+ if (!rowPanel) return;++ const uint32_t targetIdx = static_cast<uint32_t>(colIndex) + 1u;+ if (targetIdx >= rowPanel.Children().Size()) return;+ auto existingLbl = rowPanel.Children().GetAt(targetIdx).try_as<muxc::TextBlock>();+ if (!existingLbl) return; // already editing (TextBox at this slot)++ auto& colName = data_.columnNames[colIndex];+ std::wstring oldValue;+ auto it = data_.rows[rowIndex].find(colName);+ if (it != data_.rows[rowIndex].end()) oldValue = it->second;++ double colWidth = (colIndex < columnWidths_.size())+ ? columnWidths_[colIndex] : COL_DEFAULT_WIDTH;++ // Build the editor — match cell sizing. SQL NULL shows as empty+ // TextBox; user can type a value to set, or leave empty to keep NULL.+ muxc::TextBox editBox;+ editBox.Text(winrt::hstring(DBModels::isNullCell(oldValue) ? L"" : oldValue));+ editBox.FontSize(12.0);+ editBox.Width(colWidth);+ editBox.Padding(mux::Thickness{ 4.0, 3.0, 4.0, 3.0 });+ editBox.MinHeight(0.0);+ editBox.Height(ROW_HEIGHT);+ editBox.MinWidth(0.0);+ editBox.BorderThickness(mux::Thickness{ 0, 0, 0, 0 });+ editBox.VerticalAlignment(mux::VerticalAlignment::Center);+ editBox.Background(muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(30, 0, 120, 212)));+ editBox.Resources().Insert(+ winrt::box_value(L"TextControlThemePadding"),+ winrt::box_value(mux::Thickness{ 4.0, 3.0, 4.0, 3.0 }));+ editBox.Resources().Insert(+ winrt::box_value(L"TextControlThemeMinHeight"),+ winrt::box_value(0.0));+ editBox.SelectionStart(static_cast<int32_t>(editBox.Text().size()));++ // Replace TextBlock with TextBox at the same Children index+ rowPanel.Children().RemoveAt(targetIdx);+ rowPanel.Children().InsertAt(targetIdx, editBox);+ editBox.Focus(mux::FocusState::Programmatic);++ // Save on Enter key. Empty input -> SQL NULL sentinel.+ editBox.KeyDown([this, rowIndex, colIndex, oldValue]+ (winrt::Windows::Foundation::IInspectable const& sender,+ mux::Input::KeyRoutedEventArgs const& e)+ {+ if (e.Key() == winrt::Windows::System::VirtualKey::Enter)+ {+ auto tb = sender.try_as<muxc::TextBox>();+ if (!tb) return;+ std::wstring newValue(tb.Text());+ if (newValue.empty()) newValue = DBModels::nullValue();+ CommitCellEdit(rowIndex, colIndex, oldValue, newValue);+ e.Handled(true);+ }+ else if (e.Key() == winrt::Windows::System::VirtualKey::Escape)+ {+ CommitCellEdit(rowIndex, colIndex, oldValue, oldValue);+ e.Handled(true);+ }+ });++ // Save on focus lost+ editBox.LostFocus([this, rowIndex, colIndex, oldValue]+ (winrt::Windows::Foundation::IInspectable const& sender, mux::RoutedEventArgs const&)+ {+ auto tb = sender.try_as<muxc::TextBox>();+ if (!tb) return;+ std::wstring newValue(tb.Text());+ if (newValue.empty()) newValue = DBModels::nullValue();+ CommitCellEdit(rowIndex, colIndex, oldValue, newValue);+ });+ }++ void DataGridView::CommitCellEdit(int rowIndex, size_t colIndex,+ const std::wstring& oldValue, const std::wstring& newValue)+ {+ auto rowPanel = GetRowPanel(rowIndex);+ if (!rowPanel) return;++ const uint32_t targetIdx = static_cast<uint32_t>(colIndex) + 1u;+ if (targetIdx >= rowPanel.Children().Size()) return;+ // Double-fire guard: if the slot is already a TextBlock the prior+ // call (Enter / LostFocus) already committed — bail out.+ if (!rowPanel.Children().GetAt(targetIdx).try_as<muxc::TextBox>()) return;++ auto& colName = data_.columnNames[colIndex];+ data_.rows[rowIndex][colName] = newValue;++ double colWidth = (colIndex < columnWidths_.size())+ ? columnWidths_[colIndex] : COL_DEFAULT_WIDTH;+ // Render NULL sentinel as visible text "NULL" with dim opacity.+ // Truncate to keep the post-edit cell consistent with BuildRowElement.+ const bool isNull = DBModels::isNullCell(newValue);+ std::wstring display;+ if (isNull)+ {+ display = L"NULL";+ }+ else if (newValue.size() > MAX_CELL_DISPLAY_CHARS)+ {+ display.reserve(MAX_CELL_DISPLAY_CHARS + 1);+ display.assign(newValue, 0, MAX_CELL_DISPLAY_CHARS);+ display.push_back(L'\x2026');+ }+ else+ {+ display = newValue;+ }++ muxc::TextBlock lbl;+ if (cellStyle_) lbl.Style(cellStyle_);+ lbl.Text(winrt::hstring(display));+ lbl.Width(colWidth);+ if (isNull || newValue.empty())+ lbl.Opacity(0.4);++ rowPanel.Children().RemoveAt(targetIdx);+ rowPanel.Children().InsertAt(targetIdx, lbl);++ if (newValue != oldValue && OnCellEdited)+ OnCellEdited(rowIndex, colName, oldValue, newValue);+ }++ // ── Key shortcuts: Ctrl+C copy, Delete mark-deleted ───+ void DataGridView::Grid_KeyDown(+ winrt::Windows::Foundation::IInspectable const&,+ winrt::Microsoft::UI::Xaml::Input::KeyRoutedEventArgs const& e)+ {+ auto key = e.Key();++ if (key == winrt::Windows::System::VirtualKey::C)+ {+ auto ctrlState = winrt::Microsoft::UI::Input::InputKeyboardSource::GetKeyStateForCurrentThread(+ winrt::Windows::System::VirtualKey::Control);+ bool ctrlDown = (static_cast<int>(ctrlState) &+ static_cast<int>(winrt::Windows::UI::Core::CoreVirtualKeyStates::Down)) != 0;+ if (ctrlDown)+ {+ CopySelectedRowToClipboard();+ e.Handled(true);+ }+ return;+ }++ // Delete key → mark selected row as deleted (pending commit).+ // No-op when read-only (e.g. Redis) or when nothing is selected.+ // Focused TextBox cells eat the key first during inline edit, so+ // this only fires when focus is on the row itself.+ if (key == winrt::Windows::System::VirtualKey::Delete)+ {+ if (readOnly_) return;+ if (selectedRow_ < 0) return;+ if (OnDeleteRequested)+ {+ OnDeleteRequested();+ e.Handled(true);+ }+ }+ }++ void DataGridView::CopySelectedRowToClipboard()+ {+ auto* row = GetSelectedRow();+ if (!row) return;+ std::wstring tsv;+ bool first = true;+ for (auto& col : data_.columnNames)+ {+ if (!first) tsv += L'\t';+ tsv += col;+ first = false;+ }+ tsv += L'\n';+ first = true;+ for (auto& col : data_.columnNames)+ {+ if (!first) tsv += L'\t';+ auto it = row->find(col);+ if (it != row->end())+ {+ // Render NULL sentinel as visible "NULL" in clipboard text+ tsv += DBModels::isNullCell(it->second) ? std::wstring(L"NULL") : it->second;+ }+ first = false;+ }+ winrt::Windows::ApplicationModel::DataTransfer::DataPackage dataPackage;+ dataPackage.SetText(winrt::hstring(tsv));+ winrt::Windows::ApplicationModel::DataTransfer::Clipboard::SetContent(dataPackage);+ }++ // ── Scroll sync ────────────────────────────────────+ // Header H-scroll follows data H-scroll. No row-rebuild work happens+ // here — all rows are realized after BuildRows + chunked completion,+ // so scrolling is handled natively by ScrollViewer.+ void DataGridView::DataScroller_ViewChanged(+ winrt::Windows::Foundation::IInspectable const&,+ muxc::ScrollViewerViewChangedEventArgs const&)+ {+ SyncHeaderScroll();+ }++ void DataGridView::SyncHeaderScroll()+ {+ double hOffset = DataScroller().HorizontalOffset();+ HeaderScroller().ChangeView(hOffset, nullptr, nullptr);+ }+}diff --git a/windows/Gridex/DataGridView.h b/windows/Gridex/DataGridView.hnew file mode 100644index 0000000..20dad22--- /dev/null+++ b/windows/Gridex/DataGridView.h@@ -0,0 +1,120 @@+#pragma once++#include "DataGridView.g.h"+#include "Models/QueryResult.h"+#include <functional>++namespace winrt::Gridex::implementation+{+ struct DataGridView : DataGridViewT<DataGridView>+ {+ DataGridView();++ void SetData(const DBModels::QueryResult& result);++ // Put the grid in read-only mode (disables inline cell editing).+ // Used for adapters like Redis where the "table" is a key/value+ // projection and inline SQL-style edit does not map to a single+ // Redis command (hash / list / set would be silently overwritten+ // as a plain string via SET).+ void SetReadOnly(bool ro) { readOnly_ = ro; }+ bool IsReadOnly() const { return readOnly_; }++ // Callback fired when user selects a row (zero-based index)+ std::function<void(int rowIndex)> OnRowSelected;++ // Callback for column sort — host re-queries with ORDER BY+ std::function<void(const std::wstring& column, bool ascending)> OnSortRequested;++ // Callback when cell is edited (rowIndex, columnName, oldValue, newValue)+ std::function<void(int, const std::wstring&, const std::wstring&, const std::wstring&)> OnCellEdited;++ // Callback when user presses Delete to mark the selected row as+ // deleted (pending commit). Host routes this to DeleteSelectedRow.+ std::function<void()> OnDeleteRequested;++ // Get selected row data for copy+ const DBModels::TableRow* GetSelectedRow() const;++ // Expose selected row index for CRUD operations+ int GetSelectedRowIndex() const { return selectedRow_; }++ // Mark a row as deleted (red bg, dimmed text)+ void MarkRowDeleted(int index);++ // Clear all row visual marks (after discard/commit)+ void ClearRowMarks();++ void Grid_KeyDown(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::Input::KeyRoutedEventArgs const& e);++ void DataScroller_ViewChanged(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::Controls::ScrollViewerViewChangedEventArgs const& e);++ private:+ DBModels::QueryResult data_;+ int selectedRow_ = -1;+ std::wstring sortColumn_;+ bool sortAscending_ = true;+ bool readOnly_ = false;++ // Disable the 80-char cell truncation for single-column results+ // like PostgreSQL EXPLAIN/EXPLAIN ANALYZE (one "QUERY PLAN"+ // column whose values are full plan lines that need to be read+ // verbatim, not cut off with an ellipsis). Set in SetData based+ // on the incoming schema.+ bool skipCellTruncation_ = false;++ // Column widths for uniform sizing + resize+ std::vector<double> columnWidths_;+ int resizingCol_ = -1;+ double resizeStartX_ = 0.0;+ double resizeStartWidth_ = 0.0;++ // Cached XAML cell styles. Looked up once on first BuildRows; reused+ // across every cell so per-cell crossings drop to ~3 (Style + Text ++ // Width) instead of 5-6 individual property sets.+ winrt::Microsoft::UI::Xaml::Style cellStyle_{ nullptr };+ winrt::Microsoft::UI::Xaml::Style rowNumStyle_{ nullptr };++ void EnsureCellStyles();++ void ComputeColumnWidths();+ void BuildHeaders();+ // Render every row of the current page synchronously. Per-cell cost+ // is the bottleneck on wide tables. The current refactor drops the+ // per-row Button + Grid + N+1 ColumnDefinitions in favor of a single+ // horizontal StackPanel that doubles as the click target, the bg+ // fill, and the cell container — eliminating ~3100 ColumnDefinition+ // objects (for a 100x30 page) and the Button visual-state machinery.+ void BuildRows();+ winrt::Microsoft::UI::Xaml::Controls::StackPanel BuildRowElement(int rowIdx);+ void SelectRow(int index);+ void HighlightRow(int index);+ void CopySelectedRowToClipboard();+ void SyncHeaderScroll();+ // Inline edit: row is a horizontal StackPanel; cell at column k is+ // child at index k+1 (index 0 = row number). We swap that child+ // with a TextBox in BeginCellEdit and back in CommitCellEdit.+ // (Non-const because DataRows() accessor is non-const in WinRT projection.)+ winrt::Microsoft::UI::Xaml::Controls::StackPanel GetRowPanel(int rowIndex);+ void BeginCellEdit(int rowIndex, size_t colIndex);+ void CommitCellEdit(int rowIndex, size_t colIndex,+ const std::wstring& oldValue, const std::wstring& newValue);++ static constexpr double COL_DEFAULT_WIDTH = 150.0;+ static constexpr double COL_MIN_WIDTH = 60.0;+ static constexpr double COL_MAX_WIDTH = 500.0;+ static constexpr double ROW_HEIGHT = 28.0;+ static constexpr double ROW_NUM_WIDTH = 44.0;+ };+}++namespace winrt::Gridex::factory_implementation+{+ struct DataGridView : DataGridViewT<DataGridView, implementation::DataGridView>+ {+ };+}diff --git a/windows/Gridex/DataGridView.idl b/windows/Gridex/DataGridView.idlnew file mode 100644index 0000000..ca7e9d7--- /dev/null+++ b/windows/Gridex/DataGridView.idl@@ -0,0 +1,8 @@+namespace Gridex+{+ [default_interface]+ runtimeclass DataGridView : Microsoft.UI.Xaml.Controls.UserControl+ {+ DataGridView();+ }+}diff --git a/windows/Gridex/DataGridView.xaml b/windows/Gridex/DataGridView.xamlnew file mode 100644index 0000000..e8d7120--- /dev/null+++ b/windows/Gridex/DataGridView.xaml@@ -0,0 +1,51 @@+<UserControl+ x:Class="Gridex.DataGridView"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:local="using:Gridex"+>+ <!-- Cell styles cached once, applied per-cell as a single Style property+ set instead of 4-5 individual property crossings. This is the bulk+ of the BuildRows() perf win for wide tables. -->+ <UserControl.Resources>+ <Style x:Key="GridCellStyle" TargetType="TextBlock">+ <Setter Property="VerticalAlignment" Value="Center" />+ <Setter Property="TextTrimming" Value="CharacterEllipsis" />+ <Setter Property="TextWrapping" Value="NoWrap" />+ <Setter Property="Padding" Value="8,0,8,0" />+ <Setter Property="FontSize" Value="12" />+ </Style>+ <Style x:Key="GridRowNumStyle" TargetType="TextBlock">+ <Setter Property="VerticalAlignment" Value="Center" />+ <Setter Property="TextAlignment" Value="Right" />+ <Setter Property="Padding" Value="4,0,4,0" />+ <Setter Property="FontSize" Value="10" />+ <Setter Property="Opacity" Value="0.4" />+ </Style>+ </UserControl.Resources>++ <Grid>+ <Grid.RowDefinitions>+ <RowDefinition Height="Auto" />+ <RowDefinition Height="*" />+ </Grid.RowDefinitions>++ <!-- Column headers (synced scroll with data) -->+ <ScrollViewer Grid.Row="0" x:Name="HeaderScroller"+ HorizontalScrollBarVisibility="Hidden"+ VerticalScrollBarVisibility="Disabled">+ <StackPanel x:Name="HeaderRow" Orientation="Horizontal"+ Background="{ThemeResource LayerFillColorDefaultBrush}"+ BorderBrush="{ThemeResource DividerStrokeColorDefaultBrush}"+ BorderThickness="0,0,0,1" />+ </ScrollViewer>++ <!-- Data rows with virtual scrolling -->+ <ScrollViewer Grid.Row="1" x:Name="DataScroller"+ HorizontalScrollBarVisibility="Auto"+ VerticalScrollBarVisibility="Auto"+>+ <StackPanel x:Name="DataRows" Spacing="0" />+ </ScrollViewer>+ </Grid>+</UserControl>diff --git a/windows/Gridex/DatabaseTypePickerDialog.cpp b/windows/Gridex/DatabaseTypePickerDialog.cppnew file mode 100644index 0000000..868f33f--- /dev/null+++ b/windows/Gridex/DatabaseTypePickerDialog.cpp@@ -0,0 +1,32 @@+#include "pch.h"+#include "xaml-includes.h"+#include "DatabaseTypePickerDialog.h"+#if __has_include("DatabaseTypePickerDialog.g.cpp")+#include "DatabaseTypePickerDialog.g.cpp"+#endif++namespace winrt::Gridex::implementation+{+ DatabaseTypePickerDialog::DatabaseTypePickerDialog()+ {+ InitializeComponent();+ }++ void DatabaseTypePickerDialog::TypeButton_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const&)+ {+ // Button.Tag contains the database type string+ if (auto btn = sender.try_as<winrt::Microsoft::UI::Xaml::Controls::Button>())+ {+ auto tag = winrt::unbox_value<winrt::hstring>(btn.Tag());+ DBModels::DatabaseType selectedType = DBModels::DatabaseType::PostgreSQL;+ if (tag == L"MySQL") selectedType = DBModels::DatabaseType::MySQL;+ else if (tag == L"SQLite") selectedType = DBModels::DatabaseType::SQLite;+ else if (tag == L"Redis") selectedType = DBModels::DatabaseType::Redis;+ else if (tag == L"MongoDB") selectedType = DBModels::DatabaseType::MongoDB;+ else if (tag == L"MSSQLServer") selectedType = DBModels::DatabaseType::MSSQLServer;+ if (OnTypeSelected) OnTypeSelected(selectedType);+ }+ }+}diff --git a/windows/Gridex/DatabaseTypePickerDialog.h b/windows/Gridex/DatabaseTypePickerDialog.hnew file mode 100644index 0000000..b9e7896--- /dev/null+++ b/windows/Gridex/DatabaseTypePickerDialog.h@@ -0,0 +1,26 @@+#pragma once++#include "DatabaseTypePickerDialog.g.h"+#include "Models/DatabaseType.h"+#include <functional>++namespace winrt::Gridex::implementation+{+ struct DatabaseTypePickerDialog : DatabaseTypePickerDialogT<DatabaseTypePickerDialog>+ {+ DatabaseTypePickerDialog();++ void TypeButton_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);++ std::function<void(DBModels::DatabaseType)> OnTypeSelected;+ };+}++namespace winrt::Gridex::factory_implementation+{+ struct DatabaseTypePickerDialog : DatabaseTypePickerDialogT<DatabaseTypePickerDialog, implementation::DatabaseTypePickerDialog>+ {+ };+}diff --git a/windows/Gridex/DatabaseTypePickerDialog.idl b/windows/Gridex/DatabaseTypePickerDialog.idlnew file mode 100644index 0000000..47d461c--- /dev/null+++ b/windows/Gridex/DatabaseTypePickerDialog.idl@@ -0,0 +1,8 @@+namespace Gridex+{+ [default_interface]+ runtimeclass DatabaseTypePickerDialog : Microsoft.UI.Xaml.Controls.UserControl+ {+ DatabaseTypePickerDialog();+ }+}diff --git a/windows/Gridex/DatabaseTypePickerDialog.xaml b/windows/Gridex/DatabaseTypePickerDialog.xamlnew file mode 100644index 0000000..305e5cd--- /dev/null+++ b/windows/Gridex/DatabaseTypePickerDialog.xaml@@ -0,0 +1,99 @@+<UserControl+ x:Class="Gridex.DatabaseTypePickerDialog"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">++ <StackPanel Spacing="16" MinWidth="420">+ <TextBlock Text="Select a database type"+ FontSize="14"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />++ <!-- Row 1: PostgreSQL, MySQL, SQLite -->+ <StackPanel Orientation="Horizontal" Spacing="12"+ HorizontalAlignment="Center">+ <Button Tag="PostgreSQL" Click="TypeButton_Click"+ Padding="16,12" CornerRadius="8"+ Background="Transparent" BorderThickness="1"+ BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}">+ <StackPanel Width="88" Spacing="8" HorizontalAlignment="Center">+ <Border Width="48" Height="48" CornerRadius="12"+ Background="#3B82F6" HorizontalAlignment="Center">+ <FontIcon Glyph="" FontSize="24" Foreground="White" />+ </Border>+ <TextBlock Text="PostgreSQL" FontSize="12" FontWeight="SemiBold"+ HorizontalAlignment="Center" />+ </StackPanel>+ </Button>+ <Button Tag="MySQL" Click="TypeButton_Click"+ Padding="16,12" CornerRadius="8"+ Background="Transparent" BorderThickness="1"+ BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}">+ <StackPanel Width="88" Spacing="8" HorizontalAlignment="Center">+ <Border Width="48" Height="48" CornerRadius="12"+ Background="#06B6D4" HorizontalAlignment="Center">+ <FontIcon Glyph="" FontSize="24" Foreground="White" />+ </Border>+ <TextBlock Text="MySQL" FontSize="12" FontWeight="SemiBold"+ HorizontalAlignment="Center" />+ </StackPanel>+ </Button>+ <Button Tag="SQLite" Click="TypeButton_Click"+ Padding="16,12" CornerRadius="8"+ Background="Transparent" BorderThickness="1"+ BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}">+ <StackPanel Width="88" Spacing="8" HorizontalAlignment="Center">+ <Border Width="48" Height="48" CornerRadius="12"+ Background="#8B5CF6" HorizontalAlignment="Center">+ <FontIcon Glyph="" FontSize="24" Foreground="White" />+ </Border>+ <TextBlock Text="SQLite" FontSize="12" FontWeight="SemiBold"+ HorizontalAlignment="Center" />+ </StackPanel>+ </Button>+ </StackPanel>++ <!-- Row 2: Redis, MongoDB -->+ <StackPanel Orientation="Horizontal" Spacing="12"+ HorizontalAlignment="Center">+ <Button Tag="Redis" Click="TypeButton_Click"+ Padding="16,12" CornerRadius="8"+ Background="Transparent" BorderThickness="1"+ BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}">+ <StackPanel Width="88" Spacing="8" HorizontalAlignment="Center">+ <Border Width="48" Height="48" CornerRadius="12"+ Background="#DC382D" HorizontalAlignment="Center">+ <FontIcon Glyph="" FontSize="24" Foreground="White" />+ </Border>+ <TextBlock Text="Redis" FontSize="12" FontWeight="SemiBold"+ HorizontalAlignment="Center" />+ </StackPanel>+ </Button>+ <Button Tag="MongoDB" Click="TypeButton_Click"+ Padding="16,12" CornerRadius="8"+ Background="Transparent" BorderThickness="1"+ BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}">+ <StackPanel Width="88" Spacing="8" HorizontalAlignment="Center">+ <Border Width="48" Height="48" CornerRadius="12"+ Background="#47A248" HorizontalAlignment="Center">+ <FontIcon Glyph="" FontSize="24" Foreground="White" />+ </Border>+ <TextBlock Text="MongoDB" FontSize="12" FontWeight="SemiBold"+ HorizontalAlignment="Center" />+ </StackPanel>+ </Button>+ <Button Tag="MSSQLServer" Click="TypeButton_Click"+ Padding="16,12" CornerRadius="8"+ Background="Transparent" BorderThickness="1"+ BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}">+ <StackPanel Width="88" Spacing="8" HorizontalAlignment="Center">+ <Border Width="48" Height="48" CornerRadius="12"+ Background="#F97316" HorizontalAlignment="Center">+ <FontIcon Glyph="" FontSize="24" Foreground="White" />+ </Border>+ <TextBlock Text="SQL Server" FontSize="11" FontWeight="SemiBold"+ HorizontalAlignment="Center" />+ </StackPanel>+ </Button>+ </StackPanel>+ </StackPanel>+</UserControl>diff --git a/windows/Gridex/DetailsPanel.cpp b/windows/Gridex/DetailsPanel.cppnew file mode 100644index 0000000..8b26524--- /dev/null+++ b/windows/Gridex/DetailsPanel.cpp@@ -0,0 +1,550 @@+#include "pch.h"+#include "xaml-includes.h"+#include <winrt/Windows.UI.h>+#include <winrt/Windows.System.h>+#include "DetailsPanel.h"+#if __has_include("DetailsPanel.g.cpp")+#include "DetailsPanel.g.cpp"+#endif++namespace winrt::Gridex::implementation+{+ namespace mux = winrt::Microsoft::UI::Xaml;+ namespace muxc = winrt::Microsoft::UI::Xaml::Controls;+ namespace muxm = winrt::Microsoft::UI::Xaml::Media;++ DetailsPanel::DetailsPanel()+ {+ InitializeComponent();++ // Wire chat events in code-behind (not XAML) to avoid IDL requirements+ this->Loaded([this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ SendChatButton().Click(+ [this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ std::wstring text(ChatInputBox().Text());+ if (text.empty()) return;+ ChatInputBox().Text(L"");+ SendChatMessage(text);+ });++ ChatInputBox().KeyDown(+ [this](winrt::Windows::Foundation::IInspectable const&, mux::Input::KeyRoutedEventArgs const& e)+ {+ if (e.Key() == winrt::Windows::System::VirtualKey::Enter)+ {+ std::wstring text(ChatInputBox().Text());+ if (text.empty()) return;+ ChatInputBox().Text(L"");+ SendChatMessage(text);+ e.Handled(true);+ }+ });++ // "+" context picker: populate the list each time the flyout+ // opens so the table set stays in sync with the current DB.+ TablePickerFlyout().Opened(+ [this](winrt::Windows::Foundation::IInspectable const&,+ winrt::Windows::Foundation::IInspectable const&)+ {+ OpenTablePickerFlyout();+ });++ // Search filter: re-run OpenTablePickerFlyout so the ListView+ // reflects the current query (cheap — just rebuilds items).+ TablePickerSearch().TextChanged(+ [this](muxc::AutoSuggestBox const&,+ muxc::AutoSuggestBoxTextChangedEventArgs const&)+ {+ OpenTablePickerFlyout();+ });++ // Click a table row → add it as a context chip and close flyout.+ TablePickerList().IsItemClickEnabled(true);+ TablePickerList().ItemClick(+ [this](winrt::Windows::Foundation::IInspectable const&,+ muxc::ItemClickEventArgs const& e)+ {+ auto item = e.ClickedItem();+ if (!item) return;+ try+ {+ auto hs = winrt::unbox_value<winrt::hstring>(item);+ std::wstring name(hs);+ AddContextTable(name);+ TablePickerFlyout().Hide();+ }+ catch (...) {}+ });+ });+ }++ // ── Details Tab ────────────────────────────────────++ void DetailsPanel::ShowRow(+ const std::vector<std::wstring>& columnNames,+ const DBModels::TableRow& row)+ {+ currentColumns_ = columnNames;+ currentRow_ = row;+ EmptyState().Visibility(mux::Visibility::Collapsed);+ DetailsScroller().Visibility(mux::Visibility::Visible);+ RebuildFields(columnNames, row);+ }++ void DetailsPanel::ClearRow()+ {+ currentColumns_.clear();+ currentRow_.clear();+ DetailsContainer().Children().Clear();+ DetailsScroller().Visibility(mux::Visibility::Collapsed);+ EmptyState().Visibility(mux::Visibility::Visible);+ }++ void DetailsPanel::DetailsTab_Click(+ winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ if (!DetailsTab() || !AssistantTab()) return;+ DetailsTab().IsChecked(true);+ AssistantTab().IsChecked(false);+ DetailsContent().Visibility(mux::Visibility::Visible);+ AssistantContent().Visibility(mux::Visibility::Collapsed);+ }++ void DetailsPanel::AssistantTab_Click(+ winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ if (!DetailsTab() || !AssistantTab()) return;+ DetailsTab().IsChecked(false);+ AssistantTab().IsChecked(true);+ DetailsContent().Visibility(mux::Visibility::Collapsed);+ AssistantContent().Visibility(mux::Visibility::Visible);+ }++ void DetailsPanel::FieldSearch_TextChanged(+ muxc::AutoSuggestBox const& sender,+ muxc::AutoSuggestBoxTextChangedEventArgs const&)+ {+ if (currentColumns_.empty()) return;++ std::wstring query(sender.Text());+ if (query.empty())+ {+ RebuildFields(currentColumns_, currentRow_);+ return;+ }++ std::wstring queryLower = query;+ std::transform(queryLower.begin(), queryLower.end(), queryLower.begin(), ::towlower);++ std::vector<std::wstring> filtered;+ for (auto& col : currentColumns_)+ {+ std::wstring colLower = col;+ std::transform(colLower.begin(), colLower.end(), colLower.begin(), ::towlower);++ std::wstring val;+ auto it = currentRow_.find(col);+ if (it != currentRow_.end()) val = it->second;+ std::wstring valLower = val;+ std::transform(valLower.begin(), valLower.end(), valLower.begin(), ::towlower);++ if (colLower.find(queryLower) != std::wstring::npos ||+ valLower.find(queryLower) != std::wstring::npos)+ {+ filtered.push_back(col);+ }+ }+ RebuildFields(filtered, currentRow_);+ }++ void DetailsPanel::RebuildFields(+ const std::vector<std::wstring>& columnNames,+ const DBModels::TableRow& row)+ {+ DetailsContainer().Children().Clear();+ for (auto& col : columnNames)+ {+ std::wstring val;+ auto it = row.find(col);+ if (it != row.end()) val = it->second;+ AddField(DetailsContainer(), col, val);+ }+ }++ void DetailsPanel::AddField(+ muxc::StackPanel const& container,+ const std::wstring& label,+ const std::wstring& value)+ {+ muxc::StackPanel field;+ field.Spacing(2.0);+ field.Padding(mux::Thickness{ 0.0, 6.0, 0.0, 0.0 });++ muxc::TextBlock labelText;+ labelText.Text(winrt::hstring(label));+ labelText.FontSize(10.0);+ labelText.Opacity(0.5);+ field.Children().Append(labelText);++ const bool isNull = DBModels::isNullCell(value);++ // Read-only mode (Redis connections): render as a selectable+ // TextBlock wrapped in the same separator layout. No edit handlers,+ // no TextBox, no OnFieldEdited callback. Keeps the read path while+ // removing the destructive SQL-style update path.+ if (readOnly_)+ {+ muxc::TextBlock valueText;+ valueText.Text(winrt::hstring(isNull ? L"NULL" : value));+ valueText.FontSize(12.0);+ valueText.TextWrapping(mux::TextWrapping::Wrap);+ valueText.IsTextSelectionEnabled(true);+ if (isNull || value.empty())+ valueText.Opacity(0.4);+ field.Children().Append(valueText);++ muxc::Border sepRo;+ sepRo.Height(1.0);+ sepRo.Margin(mux::Thickness{ 0.0, 6.0, 0.0, 0.0 });+ sepRo.Background(muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(20, 128, 128, 128)));+ field.Children().Append(sepRo);++ container.Children().Append(field);+ return;+ }++ // Render NULL sentinel as visible empty TextBox with dim opacity.+ // User typing into it sets a real string value; clearing back to empty+ // round-trips to NULL.+ muxc::TextBox valueBox;+ valueBox.Text(winrt::hstring(isNull ? L"" : value));+ valueBox.FontSize(12.0);+ valueBox.TextWrapping(mux::TextWrapping::Wrap);+ valueBox.BorderThickness(mux::Thickness{ 0,0,0,1 });+ valueBox.BorderBrush(muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(30, 128, 128, 128)));+ valueBox.Background(muxm::SolidColorBrush(winrt::Windows::UI::Colors::Transparent()));+ if (isNull || value.empty())+ valueBox.Opacity(0.4);++ // Edit support: highlight on change, save on Enter or focus lost+ std::wstring colName = label;+ std::wstring oldVal = value;++ valueBox.GotFocus([](winrt::Windows::Foundation::IInspectable const& sender,+ mux::RoutedEventArgs const&)+ {+ auto tb = sender.try_as<muxc::TextBox>();+ if (tb)+ {+ tb.Opacity(1.0);+ // Blue border to indicate editable/focused+ tb.BorderBrush(muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(180, 0, 120, 212)));+ }+ });++ // Helper lambda to commit the edit+ auto commitEdit = [this, colName, oldVal](muxc::TextBox const& tb)+ {+ if (!tb) return;+ std::wstring newVal(tb.Text());+ // Empty input -> SQL NULL sentinel+ if (newVal.empty()) newVal = DBModels::nullValue();++ if (DBModels::isNullCell(newVal)) tb.Opacity(0.4);++ // Reset border+ tb.BorderBrush(muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(30, 128, 128, 128)));++ if (newVal != oldVal)+ {+ // Orange border to show "modified"+ tb.BorderBrush(muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(200, 255, 165, 0)));++ currentRow_[colName] = newVal;+ if (OnFieldEdited)+ OnFieldEdited(colName, oldVal, newVal);+ }+ };++ valueBox.KeyDown([commitEdit](winrt::Windows::Foundation::IInspectable const& sender,+ mux::Input::KeyRoutedEventArgs const& e)+ {+ if (e.Key() == winrt::Windows::System::VirtualKey::Enter)+ {+ auto tb = sender.try_as<muxc::TextBox>();+ if (tb) commitEdit(tb);+ e.Handled(true);+ }+ });++ valueBox.LostFocus([commitEdit](winrt::Windows::Foundation::IInspectable const& sender,+ mux::RoutedEventArgs const&)+ {+ auto tb = sender.try_as<muxc::TextBox>();+ if (tb) commitEdit(tb);+ });++ field.Children().Append(valueBox);++ muxc::Border sep;+ sep.Height(1.0);+ sep.Margin(mux::Thickness{ 0.0, 6.0, 0.0, 0.0 });+ sep.Background(muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(20, 128, 128, 128)));+ field.Children().Append(sep);++ container.Children().Append(field);+ }++ // ── Chat / Assistant Tab ───────────────────────────++ void DetailsPanel::SendChatMessage(const std::wstring& text)+ {+ // Show user message+ AddChatBubble(L"user", text);++ // Add to history+ chatHistory_.push_back({ L"user", text });++ // Show loading indicator+ AddChatBubble(L"system", L"Thinking...");++ // Build the effective schema context: base schemaContext_ plus the+ // DDL of any tables the user pinned via the "+" picker. Building+ // here (UI thread) keeps the background thread free of any XAML+ // or callback reentrancy.+ std::wstring effectiveSchema = schemaContext_;+ std::wstring pickedTablesCtx = BuildSelectedTablesContext();+ if (!pickedTablesCtx.empty())+ {+ if (!effectiveSchema.empty()) effectiveSchema += L"\n\n";+ effectiveSchema += pickedTablesCtx;+ }++ // Get dispatcher for UI thread callback+ auto dispatcher = this->DispatcherQueue();+ auto history = chatHistory_;+ auto schema = effectiveSchema;+ auto& aiSvc = aiService_;++ // Run AI call on background thread+ std::thread([this, dispatcher, history, schema, &aiSvc]()+ {+ std::wstring systemPrompt =+ L"You are a helpful database assistant. Help the user with SQL queries and database questions.";+ if (!schema.empty())+ systemPrompt += L"\n\nDatabase schema:\n" + schema;++ auto response = aiSvc.SendChat(history, systemPrompt);++ // Marshal back to UI thread+ dispatcher.TryEnqueue([this, response]()+ {+ // Remove "Thinking..." bubble (last child)+ auto children = ChatMessages().Children();+ if (children.Size() > 0)+ children.RemoveAtEnd();++ // Show response+ AddChatBubble(L"assistant", response);+ chatHistory_.push_back({ L"assistant", response });+ });+ }).detach();+ }++ void DetailsPanel::AddChatBubble(const std::wstring& role, const std::wstring& content)+ {+ bool isUser = (role == L"user");+ bool isSystem = (role == L"system");++ muxc::Border bubble;+ bubble.CornerRadius(mux::CornerRadius{ 8, 8, 8, 8 });+ bubble.Padding(mux::Thickness{ 10, 6, 10, 6 });+ bubble.Margin(mux::Thickness{ 0, 2, 0, 2 });+ bubble.MaxWidth(220.0);+ bubble.HorizontalAlignment(+ isUser ? mux::HorizontalAlignment::Right : mux::HorizontalAlignment::Left);++ if (isUser)+ {+ bubble.Background(muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(255, 0, 120, 212)));+ }+ else if (isSystem)+ {+ bubble.Background(muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(20, 128, 128, 128)));+ }+ else+ {+ bubble.Background(muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(40, 128, 128, 128)));+ }++ muxc::TextBlock txt;+ txt.Text(winrt::hstring(content));+ txt.FontSize(12.0);+ txt.TextWrapping(mux::TextWrapping::Wrap);+ txt.IsTextSelectionEnabled(true);++ if (isUser)+ txt.Foreground(muxm::SolidColorBrush(winrt::Windows::UI::Colors::White()));+ if (isSystem)+ txt.Opacity(0.5);++ bubble.Child(txt);+ ChatMessages().Children().Append(bubble);+ }++ // ── Context table picker ───────────────────────────++ // Populate the flyout ListView from OnRequestTableList, optionally+ // filtered by the search box text. Already-selected tables are not+ // shown (no point picking them twice).+ void DetailsPanel::OpenTablePickerFlyout()+ {+ TablePickerList().Items().Clear();++ if (!OnRequestTableList) return;+ auto tables = OnRequestTableList();+ if (tables.empty()) return;++ std::wstring query(TablePickerSearch().Text());+ std::wstring queryLower = query;+ std::transform(queryLower.begin(), queryLower.end(), queryLower.begin(), ::towlower);++ for (auto& name : tables)+ {+ // Skip already-selected tables+ if (std::find(selectedContextTables_.begin(),+ selectedContextTables_.end(), name) != selectedContextTables_.end())+ continue;++ if (!queryLower.empty())+ {+ std::wstring nameLower = name;+ std::transform(nameLower.begin(), nameLower.end(), nameLower.begin(), ::towlower);+ if (nameLower.find(queryLower) == std::wstring::npos) continue;+ }++ // ListView items are plain strings — easier than wrapping in a+ // custom type. IPropertyValue unboxing in the click handler+ // retrieves the name back.+ TablePickerList().Items().Append(winrt::box_value(winrt::hstring(name)));+ }+ }++ void DetailsPanel::AddContextTable(const std::wstring& tableName)+ {+ if (tableName.empty()) return;+ // Dedupe+ if (std::find(selectedContextTables_.begin(),+ selectedContextTables_.end(), tableName) != selectedContextTables_.end())+ return;+ selectedContextTables_.push_back(tableName);+ RebuildContextChips();+ }++ void DetailsPanel::RemoveContextTable(const std::wstring& tableName)+ {+ auto it = std::find(selectedContextTables_.begin(),+ selectedContextTables_.end(), tableName);+ if (it == selectedContextTables_.end()) return;+ selectedContextTables_.erase(it);+ RebuildContextChips();+ }++ // Render the chips row. Empty list collapses the scroller entirely so+ // the input row sits flush against the divider.+ void DetailsPanel::RebuildContextChips()+ {+ auto container = ChatContextChips();+ container.Children().Clear();++ if (selectedContextTables_.empty())+ {+ ChatContextChipsScroller().Visibility(mux::Visibility::Collapsed);+ return;+ }+ ChatContextChipsScroller().Visibility(mux::Visibility::Visible);++ for (auto const& name : selectedContextTables_)+ {+ muxc::Border chip;+ chip.CornerRadius(mux::CornerRadius{ 10, 10, 10, 10 });+ chip.Padding(mux::Thickness{ 8, 2, 2, 2 });+ chip.Background(muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(40, 0, 120, 212)));+ chip.BorderThickness(mux::Thickness{ 1, 1, 1, 1 });+ chip.BorderBrush(muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(80, 0, 120, 212)));++ muxc::StackPanel sp;+ sp.Orientation(muxc::Orientation::Horizontal);+ sp.Spacing(4.0);+ sp.VerticalAlignment(mux::VerticalAlignment::Center);++ // Small table icon + name+ muxc::FontIcon tblIcon;+ tblIcon.Glyph(L"\xE8C1"); // table glyph+ tblIcon.FontSize(10.0);+ tblIcon.Opacity(0.7);+ sp.Children().Append(tblIcon);++ muxc::TextBlock lbl;+ lbl.Text(winrt::hstring(name));+ lbl.FontSize(11.0);+ lbl.VerticalAlignment(mux::VerticalAlignment::Center);+ sp.Children().Append(lbl);++ // Remove button (×). Captures name by value — no cycle because+ // the lambda doesn't capture the chip Border itself.+ muxc::Button closeBtn;+ closeBtn.Padding(mux::Thickness{ 0, 0, 0, 0 });+ closeBtn.Width(18.0);+ closeBtn.Height(18.0);+ closeBtn.Background(muxm::SolidColorBrush(winrt::Windows::UI::Colors::Transparent()));+ closeBtn.BorderThickness(mux::Thickness{ 0, 0, 0, 0 });+ muxc::FontIcon xIcon;+ xIcon.Glyph(L"\xE711");+ xIcon.FontSize(9.0);+ closeBtn.Content(xIcon);+ std::wstring capturedName = name;+ closeBtn.Click([this, capturedName](+ winrt::Windows::Foundation::IInspectable const&,+ mux::RoutedEventArgs const&)+ {+ RemoveContextTable(capturedName);+ });+ sp.Children().Append(closeBtn);++ chip.Child(sp);+ container.Children().Append(chip);+ }+ }++ // Concatenate the structure (DDL-like text) of every selected table+ // into one block for the system prompt. Empty when nothing is picked+ // or the host never wired OnFetchTableStructure.+ std::wstring DetailsPanel::BuildSelectedTablesContext() const+ {+ if (selectedContextTables_.empty() || !OnFetchTableStructure) return {};++ std::wstring out;+ for (auto const& name : selectedContextTables_)+ {+ std::wstring ddl = OnFetchTableStructure(name);+ if (ddl.empty()) continue;+ if (!out.empty()) out += L"\n\n";+ out += ddl;+ }+ return out;+ }+}diff --git a/windows/Gridex/DetailsPanel.h b/windows/Gridex/DetailsPanel.hnew file mode 100644index 0000000..5b515bd--- /dev/null+++ b/windows/Gridex/DetailsPanel.h@@ -0,0 +1,99 @@+#pragma once++#include "DetailsPanel.g.h"+#include "Models/QueryResult.h"+#include "Models/AiService.h"+#include <vector>+#include <string>+#include <thread>++namespace winrt::Gridex::implementation+{+ struct DetailsPanel : DetailsPanelT<DetailsPanel>+ {+ DetailsPanel();++ // Show field values for the selected row+ void ShowRow(+ const std::vector<std::wstring>& columnNames,+ const DBModels::TableRow& row);++ void ClearRow();++ void DetailsTab_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);+ void AssistantTab_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);+ void FieldSearch_TextChanged(+ winrt::Microsoft::UI::Xaml::Controls::AutoSuggestBox const& sender,+ winrt::Microsoft::UI::Xaml::Controls::AutoSuggestBoxTextChangedEventArgs const& e);++ // Set AI config and schema context+ void SetAiConfig(const DBModels::AiConfig& config) { aiService_.SetConfig(config); }+ void SetSchemaContext(const std::wstring& schema) { schemaContext_ = schema; }++ // Put the details pane in read-only mode. Field values render as+ // selectable TextBlocks instead of TextBoxes, no edit handlers+ // attached. Used for Redis connections where inline edits cannot+ // map to safe Redis commands.+ void SetReadOnly(bool ro) { readOnly_ = ro; }++ // Callback when a field value is edited (columnName, oldValue, newValue)+ std::function<void(const std::wstring&, const std::wstring&, const std::wstring&)> OnFieldEdited;++ // Callback: host executes SQL from AI suggestion+ std::function<DBModels::QueryResult(const std::wstring& sql)> OnExecuteQuery;++ // Callback: host returns list of tables in the current DB/schema.+ // Used to populate the "+" context picker flyout in the chat input.+ std::function<std::vector<std::wstring>()> OnRequestTableList;++ // Callback: host returns a formatted structure/DDL snippet for the+ // given table name. The result is concatenated into the chat+ // system prompt so the AI knows the schema of the tables the user+ // added as context via the "+" button.+ std::function<std::wstring(const std::wstring& tableName)> OnFetchTableStructure;++ private:+ // Details panel state+ std::vector<std::wstring> currentColumns_;+ DBModels::TableRow currentRow_;+ void RebuildFields(+ const std::vector<std::wstring>& columnNames,+ const DBModels::TableRow& row);+ void AddField(+ winrt::Microsoft::UI::Xaml::Controls::StackPanel const& container,+ const std::wstring& label,+ const std::wstring& value);++ bool readOnly_ = false;++ // Chat state+ DBModels::AiService aiService_;+ std::vector<DBModels::ChatMessage> chatHistory_;+ std::wstring schemaContext_;++ // Tables the user picked via "+" to include as context. Kept in+ // insertion order and deduplicated.+ std::vector<std::wstring> selectedContextTables_;++ void SendChatMessage(const std::wstring& text);+ void AddChatBubble(const std::wstring& role, const std::wstring& content);++ // Context picker + chip rendering+ void OpenTablePickerFlyout();+ void AddContextTable(const std::wstring& tableName);+ void RemoveContextTable(const std::wstring& tableName);+ void RebuildContextChips();+ std::wstring BuildSelectedTablesContext() const;+ };+}++namespace winrt::Gridex::factory_implementation+{+ struct DetailsPanel : DetailsPanelT<DetailsPanel, implementation::DetailsPanel>+ {+ };+}diff --git a/windows/Gridex/DetailsPanel.idl b/windows/Gridex/DetailsPanel.idlnew file mode 100644index 0000000..982c12a--- /dev/null+++ b/windows/Gridex/DetailsPanel.idl@@ -0,0 +1,8 @@+namespace Gridex+{+ [default_interface]+ runtimeclass DetailsPanel : Microsoft.UI.Xaml.Controls.UserControl+ {+ DetailsPanel();+ }+}diff --git a/windows/Gridex/DetailsPanel.xaml b/windows/Gridex/DetailsPanel.xamlnew file mode 100644index 0000000..66d9ab0--- /dev/null+++ b/windows/Gridex/DetailsPanel.xaml@@ -0,0 +1,169 @@+<UserControl+ x:Class="Gridex.DetailsPanel"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:local="using:Gridex">++ <Grid Background="{ThemeResource LayerFillColorDefaultBrush}">+ <Grid.RowDefinitions>+ <RowDefinition Height="Auto" />+ <RowDefinition Height="Auto" />+ <RowDefinition Height="Auto" />+ <RowDefinition Height="*" />+ </Grid.RowDefinitions>++ <!-- Tab Header: Details | Assistant -->+ <Grid Grid.Row="0" Padding="0,0,0,0"+ BorderBrush="{ThemeResource DividerStrokeColorDefaultBrush}"+ BorderThickness="0,0,0,1">+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="*" />+ <ColumnDefinition Width="*" />+ </Grid.ColumnDefinitions>++ <ToggleButton x:Name="DetailsTab" Grid.Column="0"+ Content="Details" IsChecked="True"+ HorizontalAlignment="Stretch"+ Padding="8,10"+ Background="Transparent" BorderThickness="0"+ Click="DetailsTab_Click" />+ <ToggleButton x:Name="AssistantTab" Grid.Column="1"+ Content="Assistant"+ HorizontalAlignment="Stretch"+ Padding="8,10"+ Background="Transparent" BorderThickness="0"+ Click="AssistantTab_Click" />+ </Grid>++ <!-- Search bar for fields -->+ <AutoSuggestBox x:Name="FieldSearchBox" Grid.Row="1"+ PlaceholderText="Search field..."+ QueryIcon="Find"+ Margin="8,8,8,4"+ FontSize="12"+ TextChanged="FieldSearch_TextChanged" />++ <!-- Separator -->+ <Border Grid.Row="2" Height="1"+ Background="{ThemeResource DividerStrokeColorDefaultBrush}" />++ <!-- Details Content -->+ <Grid x:Name="DetailsContent" Grid.Row="3">+ <!-- Empty state -->+ <StackPanel x:Name="EmptyState"+ VerticalAlignment="Center" HorizontalAlignment="Center"+ Spacing="6">+ <FontIcon Glyph="" FontSize="32"+ Foreground="{ThemeResource TextFillColorTertiaryBrush}"+ HorizontalAlignment="Center" />+ <TextBlock Text="Select a row to see details"+ FontSize="12" TextWrapping="Wrap"+ HorizontalAlignment="Center" TextAlignment="Center"+ Foreground="{ThemeResource TextFillColorTertiaryBrush}" />+ </StackPanel>++ <!-- Detail fields scroll -->+ <ScrollViewer x:Name="DetailsScroller"+ Visibility="Collapsed"+ VerticalScrollBarVisibility="Auto">+ <StackPanel x:Name="DetailsContainer" Spacing="0" Padding="8,0" />+ </ScrollViewer>+ </Grid>++ <!-- Assistant Content (hidden by default) -->+ <Grid x:Name="AssistantContent" Grid.Row="3" Visibility="Collapsed">+ <Grid.RowDefinitions>+ <RowDefinition Height="*" />+ <RowDefinition Height="Auto" />+ </Grid.RowDefinitions>++ <!-- Chat area placeholder -->+ <ScrollViewer Grid.Row="0" Padding="8">+ <StackPanel x:Name="ChatMessages" Spacing="8">+ <TextBlock Text="Ask about your database..."+ FontSize="12" Opacity="0.4"+ HorizontalAlignment="Center"+ Margin="0,40,0,0" />+ </StackPanel>+ </ScrollViewer>++ <!-- Chat input + context chips -->+ <StackPanel Grid.Row="1" Padding="8"+ BorderBrush="{ThemeResource DividerStrokeColorDefaultBrush}"+ BorderThickness="0,1,0,0"+ Spacing="6">++ <!-- Context chips (selected tables). Single-line horizontal+ scroller — stays collapsed until the user adds a table. -->+ <ScrollViewer x:Name="ChatContextChipsScroller"+ Visibility="Collapsed"+ HorizontalScrollMode="Auto"+ HorizontalScrollBarVisibility="Hidden"+ VerticalScrollMode="Disabled"+ VerticalScrollBarVisibility="Disabled">+ <StackPanel x:Name="ChatContextChips"+ Orientation="Horizontal"+ Spacing="4" />+ </ScrollViewer>++ <!-- Input row: [ + ] [ textbox ] [ send ] -->+ <Grid>+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="*" />+ <ColumnDefinition Width="Auto" />+ </Grid.ColumnDefinitions>++ <!-- "+" context picker button. Flyout hosts a ListView+ populated from the current DB table list. Property+ element (Button.Flyout + Button.Content) declared+ explicitly so the XAML parser doesn't confuse the+ content child with the property-element ordering. -->+ <Button x:Name="AddContextButton" Grid.Column="0"+ Width="32" Height="32" Padding="0"+ Margin="0,0,4,0"+ ToolTipService.ToolTip="Add table as context">+ <Button.Flyout>+ <Flyout x:Name="TablePickerFlyout" Placement="Top">+ <Grid Width="260" Height="360">+ <Grid.RowDefinitions>+ <RowDefinition Height="Auto" />+ <RowDefinition Height="Auto" />+ <RowDefinition Height="*" />+ </Grid.RowDefinitions>+ <TextBlock Grid.Row="0"+ Text="Add table as context"+ FontSize="12"+ FontWeight="SemiBold"+ Margin="0,0,0,6" />+ <AutoSuggestBox x:Name="TablePickerSearch"+ Grid.Row="1"+ PlaceholderText="Search tables..."+ QueryIcon="Find"+ FontSize="12"+ Margin="0,0,0,6" />+ <ListView x:Name="TablePickerList"+ Grid.Row="2"+ SelectionMode="None"+ FontSize="12" />+ </Grid>+ </Flyout>+ </Button.Flyout>+ <Button.Content>+ <FontIcon Glyph="" FontSize="14" />+ </Button.Content>+ </Button>++ <TextBox x:Name="ChatInputBox" Grid.Column="1"+ PlaceholderText="Ask about your database..."+ FontSize="12" />+ <Button x:Name="SendChatButton" Grid.Column="2"+ Margin="4,0,0,0"+ Width="32" Height="32" Padding="0">+ <FontIcon Glyph="" FontSize="14" />+ </Button>+ </Grid>+ </StackPanel>+ </Grid>+ </Grid>+</UserControl>diff --git a/windows/Gridex/DumpRestoreService.cpp b/windows/Gridex/DumpRestoreService.cppnew file mode 100644index 0000000..7ce58a6--- /dev/null+++ b/windows/Gridex/DumpRestoreService.cpp@@ -0,0 +1,501 @@+#include <windows.h>+#include "Models/DumpRestoreService.h"+#include "Models/ImportService.h"+#include <fstream>+#include <chrono>+#include <ctime>+#include <unordered_map>+#include <algorithm>++namespace DBModels+{+ // ── Helpers ──────────────────────────────────────────++ static std::string toUtf8(const std::wstring& w)+ {+ if (w.empty()) return {};+ int sz = WideCharToMultiByte(CP_UTF8, 0, w.c_str(),+ static_cast<int>(w.size()), nullptr, 0, nullptr, nullptr);+ std::string out(sz, '\0');+ WideCharToMultiByte(CP_UTF8, 0, w.c_str(),+ static_cast<int>(w.size()), &out[0], sz, nullptr, nullptr);+ return out;+ }++ // Quote a SQL string literal: 'value with ''embedded'' quotes'+ static std::wstring quoteLiteral(const std::wstring& v)+ {+ std::wstring out;+ out.reserve(v.size() + 2);+ out += L'\'';+ for (wchar_t c : v)+ {+ if (c == L'\'') out += L"''";+ else out += c;+ }+ out += L'\'';+ return out;+ }++ static std::wstring quoteIdent(const std::wstring& name)+ {+ return L"\"" + name + L"\"";+ }++ static std::wstring nowTimestamp()+ {+ auto t = std::time(nullptr);+ std::tm tm{};+ localtime_s(&tm, &t);+ wchar_t buf[64];+ wcsftime(buf, 64, L"%Y-%m-%d %H:%M:%S", &tm);+ return buf;+ }++ enum class ColTypeKind { String, Numeric, Boolean };++ // Map a database type string to a kind (numeric/boolean/string).+ static ColTypeKind classifyType(const std::wstring& dataType)+ {+ // Lowercase copy+ std::wstring t;+ t.reserve(dataType.size());+ for (wchar_t c : dataType) t += static_cast<wchar_t>(towlower(c));++ // Numeric types (PostgreSQL + MySQL + SQLite)+ if (t == L"integer" || t == L"int" || t == L"int4" || t == L"int8" ||+ t == L"int2" || t == L"bigint" || t == L"smallint" ||+ t == L"tinyint" || t == L"mediumint" ||+ t == L"numeric" || t == L"decimal" || t == L"real" ||+ t == L"double precision" || t == L"double" || t == L"float" ||+ t == L"float4" || t == L"float8" || t == L"serial" ||+ t == L"bigserial" || t == L"smallserial")+ return ColTypeKind::Numeric;++ // Boolean+ if (t == L"boolean" || t == L"bool")+ return ColTypeKind::Boolean;++ return ColTypeKind::String;+ }++ // Format a single value based on its column type. SQL NULL sentinel+ // becomes literal "NULL" SQL keyword (no quotes); real strings get quoted.+ static std::wstring formatValue(const std::wstring& val, ColTypeKind kind)+ {+ if (isNullCell(val)) return L"NULL";++ switch (kind)+ {+ case ColTypeKind::Numeric:+ // Empty string for numeric -> NULL (defensive)+ if (val.empty()) return L"NULL";+ return val; // raw, no quotes++ case ColTypeKind::Boolean:+ if (val == L"t" || val == L"true" || val == L"1" ||+ val == L"T" || val == L"TRUE")+ return L"true";+ if (val == L"f" || val == L"false" || val == L"0" ||+ val == L"F" || val == L"FALSE")+ return L"false";+ // Unknown boolean -> NULL (defensive)+ return val.empty() ? L"NULL" : quoteLiteral(val);++ case ColTypeKind::String:+ default:+ return quoteLiteral(val);+ }+ }++ // Returns true if statement has any executable SQL (non-comment, non-empty)+ // after stripping `-- line comments` (respecting single-quoted strings).+ static bool hasExecutableContent(const std::wstring& stmt)+ {+ std::wstring stripped;+ bool inLineComment = false;+ bool inSingleQuote = false;+ for (size_t i = 0; i < stmt.size(); i++)+ {+ wchar_t c = stmt[i];+ if (inLineComment)+ {+ if (c == L'\n') inLineComment = false;+ continue;+ }+ if (inSingleQuote)+ {+ stripped += c;+ if (c == L'\'')+ {+ if (i + 1 < stmt.size() && stmt[i + 1] == L'\'')+ {+ stripped += L'\'';+ i++;+ }+ else inSingleQuote = false;+ }+ continue;+ }+ if (c == L'\'')+ {+ inSingleQuote = true;+ stripped += c;+ continue;+ }+ if (c == L'-' && i + 1 < stmt.size() && stmt[i + 1] == L'-')+ {+ inLineComment = true;+ i++;+ continue;+ }+ stripped += c;+ }+ for (wchar_t c : stripped)+ {+ if (c != L' ' && c != L'\t' && c != L'\r' && c != L'\n' && c != L';')+ return true;+ }+ return false;+ }++ // Build a single INSERT statement for one row+ static std::wstring buildInsertSQL(+ const std::wstring& table,+ const std::vector<std::wstring>& columnNames,+ const std::vector<ColTypeKind>& colKinds,+ const TableRow& row)+ {+ std::wstring sql = L"INSERT INTO " + quoteIdent(table) + L" (";+ for (size_t i = 0; i < columnNames.size(); i++)+ {+ if (i > 0) sql += L", ";+ sql += quoteIdent(columnNames[i]);+ }+ sql += L") VALUES (";+ for (size_t i = 0; i < columnNames.size(); i++)+ {+ if (i > 0) sql += L", ";+ std::wstring val;+ auto it = row.find(columnNames[i]);+ if (it != row.end()) val = it->second;+ ColTypeKind kind = (i < colKinds.size()) ? colKinds[i] : ColTypeKind::String;+ sql += formatValue(val, kind);+ }+ sql += L");\n";+ return sql;+ }++ // Write a UTF-8 wstring chunk to an open ofstream+ static void writeUtf8(std::ofstream& file, const std::wstring& s)+ {+ if (s.empty()) return;+ auto utf8 = toUtf8(s);+ file.write(utf8.c_str(), utf8.size());+ }++ // ── Dump ────────────────────────────────────────────++ DumpResult DumpRestoreService::DumpDatabase(+ std::shared_ptr<DatabaseAdapter> adapter,+ DatabaseType dbType,+ const std::wstring& schema,+ const std::wstring& outputFile,+ int batchSize,+ ProgressCallback progress)+ {+ auto report = [&](const std::wstring& msg) { if (progress) progress(msg); };++ DumpResult result;+ if (!adapter || !adapter->isConnected())+ {+ result.error = L"Not connected";+ report(L"[error] Not connected");+ return result;+ }+ if (batchSize <= 0) batchSize = DEFAULT_BATCH_SIZE;++ std::ofstream file(outputFile, std::ios::binary);+ if (!file.is_open())+ {+ result.error = L"Cannot open output file: " + outputFile;+ return result;+ }++ // UTF-8 BOM for editor compatibility+ file.write("\xEF\xBB\xBF", 3);++ // Adapter-specific syntax+ const bool isMySQL = (dbType == DatabaseType::MySQL);+ const bool isPostgreSQL = (dbType == DatabaseType::PostgreSQL);+ const std::wstring fkOff =+ isMySQL ? L"SET FOREIGN_KEY_CHECKS=0;\n"+ : L""; // PG: handled per-DROP via CASCADE+ const std::wstring fkOn =+ isMySQL ? L"SET FOREIGN_KEY_CHECKS=1;\n"+ : L"";+ const std::wstring dropSuffix =+ isPostgreSQL ? L" CASCADE;\n" : L";\n";+ const std::wstring sep =+ L"-- ----------------------------------------\n";++ try+ {+ // Header+ std::wstring header =+ L"-- Gridex dump\n"+ L"-- Database: " + adapter->currentDatabase() + L"\n"+ L"-- Schema: " + schema + L"\n"+ L"-- Generated: " + nowTimestamp() + L"\n"+ L"-- Batch size: " + std::to_wstring(batchSize) + L"\n\n";+ writeUtf8(file, header);++ // List tables+ auto tables = adapter->listTables(schema);+ report(L"Found " + std::to_wstring(tables.size()) + L" tables in schema '" + schema + L"'");++ // Disable FK checks (MySQL only)+ if (!fkOff.empty())+ {+ writeUtf8(file, L"-- Disable foreign key checks during restore\n");+ writeUtf8(file, fkOff + L"\n");+ }++ int tableIdx = 0;+ for (const auto& tableInfo : tables)+ {+ const auto& tableName = tableInfo.name;+ tableIdx++;+ report(L"[" + std::to_wstring(tableIdx) + L"/" ++ std::to_wstring(tables.size()) + L"] Dumping table: " + tableName);++ writeUtf8(file, sep);+ writeUtf8(file, L"-- Table: " + tableName + L"\n");+ writeUtf8(file, sep);++ // Drop existing — CASCADE for PG to handle FK references+ writeUtf8(file, L"DROP TABLE IF EXISTS " ++ quoteIdent(tableName) + dropSuffix);++ // CREATE TABLE+ std::wstring ddl = adapter->getCreateTableSQL(tableName, schema);+ if (ddl.empty())+ {+ writeUtf8(file, L"-- WARNING: could not generate DDL for " + tableName + L"\n\n");+ continue;+ }+ writeUtf8(file, ddl);+ if (!ddl.empty() && ddl.back() != L';') writeUtf8(file, L";");+ writeUtf8(file, L"\n\n");++ // Get column types so INSERTs use proper formatting+ // (numeric/boolean unquoted, others quoted as strings)+ auto colInfos = adapter->describeTable(tableName, schema);+ std::unordered_map<std::wstring, ColTypeKind> typeByName;+ for (const auto& ci : colInfos)+ typeByName[ci.name] = classifyType(ci.dataType);++ // Stream rows in batches+ int offset = 0;+ int tableRowCount = 0;+ std::vector<ColTypeKind> colKinds; // built from first batch+ while (true)+ {+ auto batch = adapter->fetchRows(+ tableName, schema, batchSize, offset, L"", true);+ if (!batch.success || batch.rows.empty()) break;++ if (colKinds.empty())+ {+ colKinds.reserve(batch.columnNames.size());+ for (const auto& cn : batch.columnNames)+ {+ auto it = typeByName.find(cn);+ colKinds.push_back(it != typeByName.end()+ ? it->second : ColTypeKind::String);+ }+ }++ for (const auto& row : batch.rows)+ {+ writeUtf8(file, buildInsertSQL(+ tableName, batch.columnNames, colKinds, row));+ tableRowCount++;+ result.rowsExported++;+ }++ if (static_cast<int>(batch.rows.size()) < batchSize) break;+ offset += batchSize;+ }++ writeUtf8(file, L"-- " + std::to_wstring(tableRowCount) + L" rows\n\n");+ result.tablesProcessed++;+ report(L" -> " + std::to_wstring(tableRowCount) + L" rows");+ }++ // Re-enable FK checks (MySQL only)+ if (!fkOn.empty()) writeUtf8(file, fkOn);++ report(L"Dump complete: " + std::to_wstring(result.tablesProcessed) ++ L" tables, " + std::to_wstring(result.rowsExported) + L" rows total");+ }+ catch (const DatabaseError& ex)+ {+ auto what = ex.what();+ int sz = MultiByteToWideChar(CP_UTF8, 0, what, -1, nullptr, 0);+ if (sz > 0)+ {+ result.error.resize(sz);+ MultiByteToWideChar(CP_UTF8, 0, what, -1, &result.error[0], sz);+ if (!result.error.empty() && result.error.back() == L'\0')+ result.error.pop_back();+ }+ file.close();+ return result;+ }+ catch (...)+ {+ result.error = L"Unknown error during dump";+ file.close();+ return result;+ }++ file.close();+ result.success = true;+ return result;+ }++ // ── Restore ─────────────────────────────────────────++ RestoreResult DumpRestoreService::RestoreDatabase(+ std::shared_ptr<DatabaseAdapter> adapter,+ const std::wstring& inputFile,+ ProgressCallback progress)+ {+ auto report = [&](const std::wstring& msg) { if (progress) progress(msg); };++ RestoreResult result;+ if (!adapter || !adapter->isConnected())+ {+ result.error = L"Not connected";+ report(L"[error] Not connected");+ return result;+ }++ // Read file+ report(L"Reading file: " + inputFile);+ std::wstring content = ImportService::ReadFileAsWstring(inputFile);+ if (content.empty())+ {+ result.error = L"Cannot read or empty file: " + inputFile;+ report(L"[error] " + result.error);+ return result;+ }++ // Parse SQL statements (reuses existing import parser)+ report(L"Parsing SQL statements...");+ auto parsed = ImportService::ParseSql(content);+ if (!parsed.success)+ {+ result.error = parsed.error;+ report(L"[error] Parse failed: " + parsed.error);+ return result;+ }+ report(L"Parsed " + std::to_wstring(parsed.sqlStatements.size()) + L" statements");++ // Helper to capture first failure context (statement preview + error msg)+ auto captureFailure = [&](const std::wstring& stmt, const std::wstring& errMsg)+ {+ if (!result.error.empty()) return;+ // Truncate statement preview for readability+ std::wstring preview = stmt;+ if (preview.size() > 250) preview = preview.substr(0, 250) + L"...";+ result.error = L"Statement #" + std::to_wstring(result.statementsExecuted + 1) ++ L" failed:\n\n" + preview + L"\n\nError: " + errMsg;+ };++ try+ {+ adapter->beginTransaction();+ report(L"Transaction started");++ int idx = 0;+ int totalStmts = static_cast<int>(parsed.sqlStatements.size());+ for (const auto& stmt : parsed.sqlStatements)+ {+ idx++;+ // Skip statements that contain only comments or whitespace —+ // PostgreSQL returns PGRES_EMPTY_QUERY which our adapter+ // treats as a failure, aborting the whole transaction.+ if (!hasExecutableContent(stmt)) continue;++ // Log occasional progress (every 25 statements + first few)+ if (idx <= 5 || idx % 25 == 0 || idx == totalStmts)+ {+ // Extract first ~60 chars for context+ std::wstring preview;+ for (wchar_t c : stmt)+ {+ if (c == L'\n' || c == L'\r') { if (!preview.empty()) break; continue; }+ preview += c;+ if (preview.size() >= 60) { preview += L"..."; break; }+ }+ report(L"[" + std::to_wstring(idx) + L"/" ++ std::to_wstring(totalStmts) + L"] " + preview);+ }++ try+ {+ auto r = adapter->execute(stmt);+ if (r.success) result.statementsExecuted++;+ else+ {+ result.statementsFailed++;+ captureFailure(stmt, r.error);+ }+ }+ catch (const DatabaseError& ex)+ {+ result.statementsFailed++;+ std::wstring errMsg;+ auto what = ex.what();+ int sz = MultiByteToWideChar(CP_UTF8, 0, what, -1, nullptr, 0);+ if (sz > 0)+ {+ errMsg.resize(sz);+ MultiByteToWideChar(CP_UTF8, 0, what, -1, &errMsg[0], sz);+ if (!errMsg.empty() && errMsg.back() == L'\0') errMsg.pop_back();+ }+ captureFailure(stmt, errMsg);+ }+ catch (...)+ {+ result.statementsFailed++;+ captureFailure(stmt, L"Unknown exception");+ }+ }++ if (result.statementsFailed == 0)+ {+ adapter->commitTransaction();+ result.success = true;+ report(L"Committed. " + std::to_wstring(result.statementsExecuted) ++ L" statements executed successfully.");+ }+ else+ {+ adapter->rollbackTransaction();+ report(L"Rolled back due to " ++ std::to_wstring(result.statementsFailed) + L" failure(s).");+ }+ }+ catch (...)+ {+ try { adapter->rollbackTransaction(); } catch (...) {}+ if (result.error.empty()) result.error = L"Transaction error";+ report(L"[error] Transaction error");+ }++ return result;+ }+}diff --git a/windows/Gridex/ERDiagramService.cpp b/windows/Gridex/ERDiagramService.cppnew file mode 100644index 0000000..b2b11c1--- /dev/null+++ b/windows/Gridex/ERDiagramService.cpp@@ -0,0 +1,436 @@+#include <windows.h>+#include "Models/ERDiagramService.h"+#include <fstream>+#include <sstream>+#include <set>+#include <algorithm>++namespace DBModels+{+ // ── Helpers ──────────────────────────────────────────++ static std::string toUtf8(const std::wstring& w)+ {+ if (w.empty()) return {};+ int sz = WideCharToMultiByte(CP_UTF8, 0, w.c_str(),+ static_cast<int>(w.size()), nullptr, 0, nullptr, nullptr);+ std::string out(sz, '\0');+ WideCharToMultiByte(CP_UTF8, 0, w.c_str(),+ static_cast<int>(w.size()), &out[0], sz, nullptr, nullptr);+ return out;+ }++ static std::wstring fromUtf8(const std::string& s)+ {+ if (s.empty()) return {};+ int sz = MultiByteToWideChar(CP_UTF8, 0, s.c_str(),+ static_cast<int>(s.size()), nullptr, 0);+ std::wstring out(sz, L'\0');+ MultiByteToWideChar(CP_UTF8, 0, s.c_str(),+ static_cast<int>(s.size()), &out[0], sz);+ return out;+ }++ // Replace anything not [A-Za-z0-9_] with '_'. Prefix t_ if starts with digit.+ static std::wstring sanitizeIdentifier(const std::wstring& name)+ {+ std::wstring out;+ out.reserve(name.size());+ for (wchar_t c : name)+ {+ if ((c >= L'a' && c <= L'z') ||+ (c >= L'A' && c <= L'Z') ||+ (c >= L'0' && c <= L'9') ||+ c == L'_')+ out += c;+ else+ out += L'_';+ }+ if (out.empty()) out = L"_";+ if (out[0] >= L'0' && out[0] <= L'9') out = L"t_" + out;+ return out;+ }++ // d2 reserved keywords that conflict with column names like "width",+ // "height", "label". When a SQL column matches one of these, d2 thinks+ // we're setting an attribute and barfs ("non-integer width 'bigint'").+ // Wrap the identifier in double quotes to force literal interpretation.+ static bool isD2Reserved(const std::wstring& name)+ {+ // Lowercase compare since SQL is case-insensitive but d2 is not+ std::wstring lower;+ lower.reserve(name.size());+ for (wchar_t c : name)+ lower += static_cast<wchar_t>(towlower(c));++ static const wchar_t* keywords[] = {+ L"shape", L"width", L"height", L"style", L"near", L"direction",+ L"top", L"left", L"tooltip", L"link", L"icon", L"label",+ L"constraint", L"class", L"classes", L"vars", L"layers",+ L"scenarios", L"steps", L"source-arrowhead", L"target-arrowhead",+ L"grid-rows", L"grid-columns", L"grid-gap",+ L"vertical-gap", L"horizontal-gap"+ };+ for (auto* kw : keywords)+ if (lower == kw) return true;+ return false;+ }++ // Quote a column identifier if it collides with a d2 reserved keyword.+ static std::wstring quoteIfReserved(const std::wstring& name)+ {+ if (isD2Reserved(name))+ return L"\"" + name + L"\"";+ return name;+ }++ // Simplify type strings: "varchar(255)" -> "varchar",+ // "character varying" -> "varchar", strip parens / spaces / casts.+ static std::wstring simplifyType(const std::wstring& dataType)+ {+ if (dataType.empty()) return L"any";++ // Lowercase+ std::wstring t;+ t.reserve(dataType.size());+ for (wchar_t c : dataType) t += static_cast<wchar_t>(towlower(c));++ // Strip parens content: "varchar(255)" -> "varchar"+ auto parenPos = t.find(L'(');+ if (parenPos != std::wstring::npos) t = t.substr(0, parenPos);++ // Strip ::cast: "'foo'::text" not really a type, but defensive+ auto castPos = t.find(L"::");+ if (castPos != std::wstring::npos) t = t.substr(0, castPos);++ // Trim+ while (!t.empty() && t.back() == L' ') t.pop_back();+ while (!t.empty() && t.front() == L' ') t.erase(t.begin());++ // Common rewrites+ if (t == L"character varying") return L"varchar";+ if (t == L"timestamp with time zone") return L"timestamptz";+ if (t == L"timestamp without time zone") return L"timestamp";+ if (t == L"double precision") return L"double";++ // If still has spaces, take first word+ auto sp = t.find(L' ');+ if (sp != std::wstring::npos) t = t.substr(0, sp);++ return t.empty() ? L"any" : t;+ }++ // Locate d2.exe — try MSIX install dir first, then exe-relative dir+ std::wstring ERDiagramService::LocateD2Exe()+ {+ // Try via current process module path (works for both packaged and unpackaged)+ wchar_t buf[MAX_PATH] = {};+ DWORD len = GetModuleFileNameW(nullptr, buf, MAX_PATH);+ if (len > 0 && len < MAX_PATH)+ {+ std::wstring exePath(buf);+ auto slashPos = exePath.find_last_of(L"\\/");+ if (slashPos != std::wstring::npos)+ {+ std::wstring exeDir = exePath.substr(0, slashPos);+ std::wstring candidate = exeDir + L"\\Assets\\d2\\d2.exe";++ // Check existence+ DWORD attrs = GetFileAttributesW(candidate.c_str());+ if (attrs != INVALID_FILE_ATTRIBUTES &&+ !(attrs & FILE_ATTRIBUTE_DIRECTORY))+ return candidate;+ }+ }+ return L"";+ }++ // Build %TEMP%\gridex\<random>.<extension>+ static std::wstring tempPath(const std::wstring& extension)+ {+ wchar_t tmp[MAX_PATH] = {};+ DWORD len = GetTempPathW(MAX_PATH, tmp);+ if (len == 0) return L"";++ std::wstring dir = std::wstring(tmp) + L"gridex";+ CreateDirectoryW(dir.c_str(), nullptr);++ // Random suffix using GetTickCount + counter+ static int counter = 0;+ wchar_t name[64];+ swprintf_s(name, 64, L"\\er_%lu_%d.%s",+ GetTickCount(), counter++, extension.c_str());+ return dir + name;+ }++ // Run d2.exe with input/output paths. Returns exit code.+ static int runD2(const std::wstring& d2Exe,+ const std::wstring& inputPath, const std::wstring& outputPath,+ std::wstring& stderrOut)+ {+ // Build command line:+ // "d2.exe" --layout=elk --theme=300 --bundle --no-xml-tag --pad=20 "in" "out"+ // --bundle inlines fonts/assets, --no-xml-tag drops the <?xml ?> prolog+ // since we inline the SVG into HTML body for WebView2 rendering.+ std::wstring cmd =+ L"\"" + d2Exe + L"\" "+ L"--layout=elk --theme=300 --bundle --no-xml-tag --pad=20 "+ L"\"" + inputPath + L"\" "+ L"\"" + outputPath + L"\"";++ // Pipe for stderr capture+ SECURITY_ATTRIBUTES sa = {};+ sa.nLength = sizeof(sa);+ sa.bInheritHandle = TRUE;++ HANDLE rdErr = nullptr, wrErr = nullptr;+ if (!CreatePipe(&rdErr, &wrErr, &sa, 0))+ return -1;+ SetHandleInformation(rdErr, HANDLE_FLAG_INHERIT, 0);++ STARTUPINFOW si = {};+ si.cb = sizeof(si);+ si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;+ si.wShowWindow = SW_HIDE;+ si.hStdError = wrErr;+ si.hStdOutput = wrErr;+ si.hStdInput = nullptr;++ PROCESS_INFORMATION pi = {};+ std::wstring cmdMutable = cmd; // CreateProcessW needs writable buffer++ BOOL ok = CreateProcessW(+ nullptr,+ &cmdMutable[0],+ nullptr, nullptr,+ TRUE,+ CREATE_NO_WINDOW,+ nullptr, nullptr,+ &si, &pi);++ CloseHandle(wrErr);++ if (!ok)+ {+ CloseHandle(rdErr);+ stderrOut = L"Failed to launch d2.exe: " ++ std::to_wstring(GetLastError());+ return -1;+ }++ // Read stderr until pipe closes+ std::string capturedErr;+ char readBuf[4096];+ DWORD bytesRead = 0;+ while (ReadFile(rdErr, readBuf, sizeof(readBuf), &bytesRead, nullptr)+ && bytesRead > 0)+ {+ capturedErr.append(readBuf, bytesRead);+ }+ CloseHandle(rdErr);++ // Wait up to 30s+ WaitForSingleObject(pi.hProcess, 30000);+ DWORD exitCode = 1;+ GetExitCodeProcess(pi.hProcess, &exitCode);++ CloseHandle(pi.hProcess);+ CloseHandle(pi.hThread);++ stderrOut = fromUtf8(capturedErr);+ return static_cast<int>(exitCode);+ }++ // ── D2 Text Generation ─────────────────────────────++ std::wstring ERDiagramService::GenerateD2Text(+ std::shared_ptr<DatabaseAdapter> adapter,+ const std::wstring& schema,+ ProgressCallback progress)+ {+ auto report = [&](const std::wstring& msg) { if (progress) progress(msg); };++ if (!adapter || !adapter->isConnected()) return L"";++ std::wstringstream ss;+ ss << L"# Gridex ER Diagram for schema " << schema << L"\n";+ ss << L"direction: right\n\n";++ // Collect tables+ std::vector<TableInfo> tables;+ try { tables = adapter->listTables(schema); }+ catch (...) { return L""; }++ report(L"Found " + std::to_wstring(tables.size()) + L" tables in " + schema);++ // Build set of sanitized table names so we can skip orphan FKs+ std::set<std::wstring> tableNameSet;+ for (const auto& t : tables) tableNameSet.insert(t.name);++ // Emit tables with columns+ int idx = 0;+ for (const auto& tableInfo : tables)+ {+ const auto& tableName = tableInfo.name;+ idx++;+ report(L"[" + std::to_wstring(idx) + L"/" ++ std::to_wstring(tables.size()) + L"] " + tableName);++ std::vector<ColumnInfo> cols;+ try { cols = adapter->describeTable(tableName, schema); }+ catch (...) { continue; }++ ss << sanitizeIdentifier(tableName) << L": {\n";+ ss << L" shape: sql_table\n";+ for (const auto& col : cols)+ {+ std::wstring colId = sanitizeIdentifier(col.name);+ std::wstring colKey = quoteIfReserved(colId);+ std::wstring typeId = simplifyType(col.dataType);+ ss << L" " << colKey << L": " << typeId;+ if (col.isPrimaryKey)+ ss << L" {constraint: primary_key}";+ else if (col.isForeignKey)+ ss << L" {constraint: foreign_key}";+ ss << L"\n";+ }+ ss << L"}\n\n";+ }++ // Emit FK relationships+ int relCount = 0;+ for (const auto& tableInfo : tables)+ {+ const auto& tableName = tableInfo.name;+ std::vector<ForeignKeyInfo> fks;+ try { fks = adapter->listForeignKeys(tableName, schema); }+ catch (...) { continue; }++ for (const auto& fk : fks)+ {+ // Skip FKs whose target is outside this schema+ if (tableNameSet.find(fk.referencedTable) == tableNameSet.end())+ continue;++ // FK arrow without label — user prefers clean lines.+ // Quote column identifiers if they collide with d2 keywords.+ ss << sanitizeIdentifier(tableName) << L"."+ << quoteIfReserved(sanitizeIdentifier(fk.column))+ << L" -> "+ << sanitizeIdentifier(fk.referencedTable) << L"."+ << quoteIfReserved(sanitizeIdentifier(fk.referencedColumn))+ << L"\n";+ relCount++;+ }+ }++ report(L"Generated " + std::to_wstring(tables.size()) ++ L" tables, " + std::to_wstring(relCount) + L" relationships");++ return ss.str();+ }++ // ── Full Pipeline ───────────────────────────────────++ ERDiagramResult ERDiagramService::Generate(+ std::shared_ptr<DatabaseAdapter> adapter,+ const std::wstring& schema,+ ProgressCallback progress)+ {+ auto report = [&](const std::wstring& msg) { if (progress) progress(msg); };+ ERDiagramResult result;++ if (!adapter || !adapter->isConnected())+ {+ result.error = L"Not connected";+ return result;+ }++ // 1. Generate D2 text+ result.d2Text = GenerateD2Text(adapter, schema, progress);+ if (result.d2Text.empty())+ {+ result.error = L"No tables found in schema";+ return result;+ }++ // Count tables and relationships from text by scanning+ // ("shape: sql_table" appears once per table, "->" only in FK lines)+ const std::wstring tableMarker = L"shape: sql_table";+ const std::wstring arrow = L"->";+ size_t pos = 0;+ while ((pos = result.d2Text.find(tableMarker, pos)) != std::wstring::npos)+ {+ result.tableCount++;+ pos += tableMarker.size();+ }+ pos = 0;+ while ((pos = result.d2Text.find(arrow, pos)) != std::wstring::npos)+ {+ result.relationshipCount++;+ pos += arrow.size();+ }++ // 2. Locate d2.exe+ std::wstring d2Exe = LocateD2Exe();+ if (d2Exe.empty())+ {+ result.error = L"d2.exe not found. Place it in Assets\\d2\\d2.exe.";+ return result;+ }+ report(L"Using d2.exe at: " + d2Exe);++ // 3. Write D2 text to temp file (UTF-8)+ std::wstring inputPath = tempPath(L"d2");+ std::wstring outputPath = tempPath(L"svg");+ if (inputPath.empty() || outputPath.empty())+ {+ result.error = L"Cannot create temp files";+ return result;+ }++ {+ std::ofstream f(inputPath, std::ios::binary);+ if (!f.is_open())+ {+ result.error = L"Cannot write D2 input file";+ return result;+ }+ auto utf8 = toUtf8(result.d2Text);+ f.write(utf8.c_str(), utf8.size());+ }++ // 4. Run d2.exe+ report(L"Running d2.exe...");+ std::wstring stderrOut;+ int exitCode = runD2(d2Exe, inputPath, outputPath, stderrOut);++ if (exitCode != 0)+ {+ result.error = L"d2.exe failed (exit " + std::to_wstring(exitCode) ++ L"):\n" + stderrOut;+ DeleteFileW(inputPath.c_str());+ return result;+ }++ // 5. Verify output exists+ DWORD outAttrs = GetFileAttributesW(outputPath.c_str());+ if (outAttrs == INVALID_FILE_ATTRIBUTES ||+ (outAttrs & FILE_ATTRIBUTE_DIRECTORY))+ {+ result.error = L"d2.exe did not produce SVG output";+ DeleteFileW(inputPath.c_str());+ return result;+ }++ // SVG goes to WebView2 — no post-processing needed (browser renders text fine).+ result.svgPath = outputPath;+ result.success = true;+ report(L"SVG ready at " + outputPath);++ // Keep input D2 file for debugging? Delete to be tidy.+ DeleteFileW(inputPath.c_str());++ return result;+ }+}diff --git a/windows/Gridex/ExportService.cpp b/windows/Gridex/ExportService.cppnew file mode 100644index 0000000..32a3c4c--- /dev/null+++ b/windows/Gridex/ExportService.cpp@@ -0,0 +1,166 @@+#include <windows.h>+#include "Models/ExportService.h"+#include <fstream>++namespace DBModels+{+ std::string ExportService::toUtf8(const std::wstring& wstr)+ {+ if (wstr.empty()) return {};+ int size = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(),+ static_cast<int>(wstr.size()), nullptr, 0, nullptr, nullptr);+ std::string result(size, '\0');+ WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(),+ static_cast<int>(wstr.size()), &result[0], size, nullptr, nullptr);+ return result;+ }++ std::wstring ExportService::ToCsv(const QueryResult& result)+ {+ std::wstring csv;+ for (size_t i = 0; i < result.columnNames.size(); i++)+ {+ if (i > 0) csv += L',';+ csv += L'"';+ for (wchar_t c : result.columnNames[i])+ {+ if (c == L'"') csv += L"\"\"";+ else csv += c;+ }+ csv += L'"';+ }+ csv += L'\n';+ for (auto& row : result.rows)+ {+ for (size_t i = 0; i < result.columnNames.size(); i++)+ {+ if (i > 0) csv += L',';+ std::wstring val;+ auto it = row.find(result.columnNames[i]);+ if (it != row.end()) val = it->second;+ if (!isNullCell(val))+ {+ csv += L'"';+ for (wchar_t c : val)+ {+ if (c == L'"') csv += L"\"\"";+ else csv += c;+ }+ csv += L'"';+ }+ }+ csv += L'\n';+ }+ return csv;+ }++ std::wstring ExportService::ToJson(const QueryResult& result)+ {+ std::wstring json = L"[\n";+ for (size_t r = 0; r < result.rows.size(); r++)+ {+ auto& row = result.rows[r];+ json += L" {";+ for (size_t c = 0; c < result.columnNames.size(); c++)+ {+ if (c > 0) json += L',';+ json += L'\n';+ auto& colName = result.columnNames[c];+ std::wstring val;+ auto it = row.find(colName);+ if (it != row.end()) val = it->second;+ json += L" \"";+ for (wchar_t ch : colName)+ {+ if (ch == L'"') json += L"\\\"";+ else if (ch == L'\\') json += L"\\\\";+ else json += ch;+ }+ json += L"\": ";+ if (isNullCell(val)) json += L"null";+ else+ {+ json += L'"';+ for (wchar_t ch : val)+ {+ if (ch == L'"') json += L"\\\"";+ else if (ch == L'\\') json += L"\\\\";+ else if (ch == L'\n') json += L"\\n";+ else json += ch;+ }+ json += L'"';+ }+ }+ json += L"\n }";+ if (r + 1 < result.rows.size()) json += L',';+ json += L'\n';+ }+ json += L"]\n";+ return json;+ }++ std::wstring ExportService::ToSqlInsert(+ const QueryResult& result, const std::wstring& tableName)+ {+ std::wstring sql;+ for (auto& row : result.rows)+ {+ sql += L"INSERT INTO \"" + tableName + L"\" (";+ for (size_t i = 0; i < result.columnNames.size(); i++)+ {+ if (i > 0) sql += L", ";+ sql += L'"' + result.columnNames[i] + L'"';+ }+ sql += L") VALUES (";+ for (size_t i = 0; i < result.columnNames.size(); i++)+ {+ if (i > 0) sql += L", ";+ std::wstring val;+ auto it = row.find(result.columnNames[i]);+ if (it != row.end()) val = it->second;+ if (isNullCell(val)) sql += L"NULL";+ else+ {+ sql += L'\'';+ for (wchar_t c : val)+ {+ if (c == L'\'') sql += L"''";+ else sql += c;+ }+ sql += L'\'';+ }+ }+ sql += L");\n";+ }+ return sql;+ }++ // SaveToFile now just writes to disk — no dialog+ bool ExportService::SaveToFile(+ const std::wstring& content,+ const std::wstring& /*defaultFileName*/,+ const std::wstring& /*filterName*/,+ const std::wstring& filterExtension,+ HWND /*hwnd*/)+ {+ // This is now a no-op placeholder — actual saving done via async picker in WorkspacePage+ (void)content; (void)filterExtension;+ return false;+ }++ bool ExportService::WriteToStorageFile(+ const std::wstring& content,+ const std::wstring& filterExtension,+ const std::wstring& filePath)+ {+ std::string utf8 = toUtf8(content);+ std::ofstream file(filePath, std::ios::binary);+ if (!file.is_open()) return false;+ if (filterExtension == L".csv")+ file.write("\xEF\xBB\xBF", 3);+ file.write(utf8.c_str(), utf8.size());+ file.close();+ lastSavedPath_ = filePath;+ return true;+ }+}diff --git a/windows/Gridex/FilterBar.cpp b/windows/Gridex/FilterBar.cppnew file mode 100644index 0000000..084d259--- /dev/null+++ b/windows/Gridex/FilterBar.cpp@@ -0,0 +1,76 @@+#include "pch.h"+#include "xaml-includes.h"+#include "FilterBar.h"+#if __has_include("FilterBar.g.cpp")+#include "FilterBar.g.cpp"+#endif++namespace winrt::Gridex::implementation+{+ namespace mux = winrt::Microsoft::UI::Xaml;+ namespace muxc = winrt::Microsoft::UI::Xaml::Controls;++ FilterBar::FilterBar()+ {+ InitializeComponent();+ }++ void FilterBar::SetColumns(const std::vector<std::wstring>& columnNames)+ {+ columns_ = columnNames;+ ColumnPicker().Items().Clear();+ for (auto& col : columns_)+ {+ muxc::ComboBoxItem item;+ item.Content(winrt::box_value(winrt::hstring(col)));+ ColumnPicker().Items().Append(item);+ }+ if (!columns_.empty())+ ColumnPicker().SelectedIndex(0);+ }++ void FilterBar::ApplyFilter_Click(+ winrt::Windows::Foundation::IInspectable const&,+ mux::RoutedEventArgs const&)+ {+ if (!OnApplyFilter) return;++ FilterCondition cond;++ // Column+ if (ColumnPicker().SelectedItem())+ {+ auto item = ColumnPicker().SelectedItem().try_as<muxc::ComboBoxItem>();+ if (item)+ cond.column = std::wstring(winrt::unbox_value<winrt::hstring>(item.Content()));+ }++ // Operator+ if (OperatorPicker().SelectedItem())+ {+ auto item = OperatorPicker().SelectedItem().try_as<muxc::ComboBoxItem>();+ if (item)+ cond.op = std::wstring(winrt::unbox_value<winrt::hstring>(item.Content()));+ }+ else+ {+ cond.op = L"equals";+ }++ cond.value = std::wstring(FilterValue().Text());+ OnApplyFilter(cond);+ }++ void FilterBar::ClearFilter_Click(+ winrt::Windows::Foundation::IInspectable const&,+ mux::RoutedEventArgs const&)+ {+ FilterValue().Text(L"");+ if (!columns_.empty())+ ColumnPicker().SelectedIndex(0);+ OperatorPicker().SelectedIndex(0);++ if (OnClearFilter)+ OnClearFilter();+ }+}diff --git a/windows/Gridex/FilterBar.h b/windows/Gridex/FilterBar.hnew file mode 100644index 0000000..1e7ca5d--- /dev/null+++ b/windows/Gridex/FilterBar.h@@ -0,0 +1,45 @@+#pragma once++#include "FilterBar.g.h"+#include <functional>+#include <string>+#include <vector>++namespace winrt::Gridex::implementation+{+ struct FilterCondition+ {+ std::wstring column;+ std::wstring op; // equals, contains, starts with, is null, etc.+ std::wstring value;+ };++ struct FilterBar : FilterBarT<FilterBar>+ {+ FilterBar();++ // Populate the column picker from active table columns+ void SetColumns(const std::vector<std::wstring>& columnNames);++ // Callbacks fired by Apply / Clear+ std::function<void(const FilterCondition&)> OnApplyFilter;+ std::function<void()> OnClearFilter;++ void ApplyFilter_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);+ void ClearFilter_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);++ private:+ std::vector<std::wstring> columns_;+ };+}++namespace winrt::Gridex::factory_implementation+{+ struct FilterBar : FilterBarT<FilterBar, implementation::FilterBar>+ {+ };+}diff --git a/windows/Gridex/FilterBar.idl b/windows/Gridex/FilterBar.idlnew file mode 100644index 0000000..f3e549c--- /dev/null+++ b/windows/Gridex/FilterBar.idl@@ -0,0 +1,8 @@+namespace Gridex+{+ [default_interface]+ runtimeclass FilterBar : Microsoft.UI.Xaml.Controls.UserControl+ {+ FilterBar();+ }+}diff --git a/windows/Gridex/FilterBar.xaml b/windows/Gridex/FilterBar.xamlnew file mode 100644index 0000000..8c23c9f--- /dev/null+++ b/windows/Gridex/FilterBar.xaml@@ -0,0 +1,49 @@+<UserControl+ x:Class="Gridex.FilterBar"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:local="using:Gridex">++ <Grid Padding="8,6"+ Background="{ThemeResource LayerFillColorDefaultBrush}"+ BorderBrush="{ThemeResource DividerStrokeColorDefaultBrush}"+ BorderThickness="0,1,0,0">+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="*" />+ <ColumnDefinition Width="Auto" />+ </Grid.ColumnDefinitions>++ <!-- Column picker -->+ <ComboBox Grid.Column="0" x:Name="ColumnPicker"+ PlaceholderText="Column"+ MinWidth="140" Height="28" FontSize="12" />++ <!-- Operator picker -->+ <ComboBox Grid.Column="1" x:Name="OperatorPicker"+ Margin="6,0,0,0" MinWidth="120" Height="28" FontSize="12">+ <ComboBoxItem Content="equals" IsSelected="True" />+ <ComboBoxItem Content="not equals" />+ <ComboBoxItem Content="contains" />+ <ComboBoxItem Content="starts with" />+ <ComboBoxItem Content="is null" />+ <ComboBoxItem Content="is not null" />+ </ComboBox>++ <!-- Value input -->+ <TextBox Grid.Column="2" x:Name="FilterValue"+ Margin="6,0,0,0" MinWidth="180" Height="28"+ FontSize="12" PlaceholderText="Value..." />++ <!-- Apply / Clear -->+ <StackPanel Grid.Column="4" Orientation="Horizontal" Spacing="6">+ <Button Content="Apply" Padding="10,4" FontSize="12"+ Style="{StaticResource AccentButtonStyle}"+ Click="ApplyFilter_Click" />+ <Button Content="Clear" Padding="10,4" FontSize="12"+ Click="ClearFilter_Click" />+ </StackPanel>+ </Grid>+</UserControl>diff --git a/windows/Gridex/Gridex.rc b/windows/Gridex/Gridex.rcnew file mode 100644index 0000000..ea742ca--- /dev/null+++ b/windows/Gridex/Gridex.rc@@ -0,0 +1,10 @@+// Gridex.rc -- Win32 resource script+//+// Embeds the application icon into Gridex.exe so Windows Explorer, task+// bar, Alt+Tab switcher, Desktop / Start menu shortcuts, and ARP (Apps &+// Features) all display the Gridex phoenix mark instead of the default+// blank executable icon.+//+// Resource ID 1 is the convention Windows uses to locate the app icon.++1 ICON "Assets\\Gridex.ico"diff --git a/windows/Gridex/Gridex.vcxproj b/windows/Gridex/Gridex.vcxprojnew file mode 100644index 0000000..22bd6cf--- /dev/null+++ b/windows/Gridex/Gridex.vcxproj@@ -0,0 +1,708 @@+<?xml version="1.0" encoding="utf-8"?>+<Project ToolsVersion="15.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">+ <Import Project="..\packages\Microsoft.Windows.SDK.BuildTools.10.0.28000.1721\build\Microsoft.Windows.SDK.BuildTools.props" Condition="Exists('..\packages\Microsoft.Windows.SDK.BuildTools.10.0.28000.1721\build\Microsoft.Windows.SDK.BuildTools.props')" />+ <Import Project="..\packages\Microsoft.Windows.CppWinRT.2.0.250303.1\build\native\Microsoft.Windows.CppWinRT.props" Condition="Exists('..\packages\Microsoft.Windows.CppWinRT.2.0.250303.1\build\native\Microsoft.Windows.CppWinRT.props')" />+ <Import Project="..\packages\Microsoft.WindowsAppSDK.1.8.260317003\build\native\Microsoft.WindowsAppSDK.props" Condition="Exists('..\packages\Microsoft.WindowsAppSDK.1.8.260317003\build\native\Microsoft.WindowsAppSDK.props')" />+ <Import Project="..\packages\Microsoft.WindowsAppSDK.WinUI.1.8.260224000\build\native\Microsoft.WindowsAppSDK.WinUI.props" Condition="Exists('..\packages\Microsoft.WindowsAppSDK.WinUI.1.8.260224000\build\native\Microsoft.WindowsAppSDK.WinUI.props')" />+ <Import Project="..\packages\Microsoft.WindowsAppSDK.Widgets.1.8.251231004\build\native\Microsoft.WindowsAppSDK.Widgets.props" Condition="Exists('..\packages\Microsoft.WindowsAppSDK.Widgets.1.8.251231004\build\native\Microsoft.WindowsAppSDK.Widgets.props')" />+ <Import Project="..\packages\Microsoft.WindowsAppSDK.Runtime.1.8.260317003\build\native\Microsoft.WindowsAppSDK.Runtime.props" Condition="Exists('..\packages\Microsoft.WindowsAppSDK.Runtime.1.8.260317003\build\native\Microsoft.WindowsAppSDK.Runtime.props')" />+ <Import Project="..\packages\Microsoft.WindowsAppSDK.ML.1.8.2141\build\native\Microsoft.WindowsAppSDK.ML.props" Condition="Exists('..\packages\Microsoft.WindowsAppSDK.ML.1.8.2141\build\native\Microsoft.WindowsAppSDK.ML.props')" />+ <Import Project="..\packages\Microsoft.WindowsAppSDK.AI.1.8.53\build\native\Microsoft.WindowsAppSDK.AI.props" Condition="Exists('..\packages\Microsoft.WindowsAppSDK.AI.1.8.53\build\native\Microsoft.WindowsAppSDK.AI.props')" />+ <Import Project="..\packages\Microsoft.WindowsAppSDK.Foundation.1.8.260222000\build\native\Microsoft.WindowsAppSDK.Foundation.props" Condition="Exists('..\packages\Microsoft.WindowsAppSDK.Foundation.1.8.260222000\build\native\Microsoft.WindowsAppSDK.Foundation.props')" />+ <Import Project="..\packages\Microsoft.WindowsAppSDK.InteractiveExperiences.1.8.260125001\build\native\Microsoft.WindowsAppSDK.InteractiveExperiences.props" Condition="Exists('..\packages\Microsoft.WindowsAppSDK.InteractiveExperiences.1.8.260125001\build\native\Microsoft.WindowsAppSDK.InteractiveExperiences.props')" />+ <Import Project="..\packages\Microsoft.WindowsAppSDK.DWrite.1.8.25122902\build\Microsoft.WindowsAppSDK.DWrite.props" Condition="Exists('..\packages\Microsoft.WindowsAppSDK.DWrite.1.8.25122902\build\Microsoft.WindowsAppSDK.DWrite.props')" />+ <Import Project="..\packages\Microsoft.WindowsAppSDK.Base.1.8.251216001\build\native\Microsoft.WindowsAppSDK.Base.props" Condition="Exists('..\packages\Microsoft.WindowsAppSDK.Base.1.8.251216001\build\native\Microsoft.WindowsAppSDK.Base.props')" />+ <Import Project="..\packages\Microsoft.Windows.SDK.BuildTools.MSIX.1.7.20250829.1\build\Microsoft.Windows.SDK.BuildTools.MSIX.props" Condition="Exists('..\packages\Microsoft.Windows.SDK.BuildTools.MSIX.1.7.20250829.1\build\Microsoft.Windows.SDK.BuildTools.MSIX.props')" />+ <PropertyGroup Label="Globals">+ <CppWinRTOptimized>true</CppWinRTOptimized>+ <CppWinRTRootNamespaceAutoMerge>true</CppWinRTRootNamespaceAutoMerge>+ <MinimalCoreWin>true</MinimalCoreWin>+ <ProjectGuid>{89a0fae9-44a2-4889-9bd1-50998c237d7c}</ProjectGuid>+ <ProjectName>Gridex</ProjectName>+ <RootNamespace>Gridex</RootNamespace>+ <!--+ $(TargetName) should be same as $(RootNamespace) so that the produced binaries (.exe/.pri/etc.)+ have a name that matches the .winmd+ -->+ <TargetName>$(RootNamespace)</TargetName>+ <DefaultLanguage>en-US</DefaultLanguage>+ <MinimumVisualStudioVersion>16.0</MinimumVisualStudioVersion>+ <AppContainerApplication>false</AppContainerApplication>+ <AppxPackage>true</AppxPackage>+ <ApplicationType>Windows Store</ApplicationType>+ <ApplicationTypeRevision>10.0</ApplicationTypeRevision>+ <WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>+ <WindowsTargetPlatformMinVersion>10.0.17763.0</WindowsTargetPlatformMinVersion>+ <UseWinUI>true</UseWinUI>+ <PreferredToolArchitecture>x64</PreferredToolArchitecture>+ <WinUISDKReferences>false</WinUISDKReferences>+ <EnableMsixTooling>true</EnableMsixTooling>+ </PropertyGroup>+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />+ <ItemGroup Label="ProjectConfigurations">+ <ProjectConfiguration Include="Debug|Win32">+ <Configuration>Debug</Configuration>+ <Platform>Win32</Platform>+ </ProjectConfiguration>+ <ProjectConfiguration Include="Debug|x64">+ <Configuration>Debug</Configuration>+ <Platform>x64</Platform>+ </ProjectConfiguration>+ <ProjectConfiguration Include="Debug|ARM64">+ <Configuration>Debug</Configuration>+ <Platform>ARM64</Platform>+ </ProjectConfiguration>+ <ProjectConfiguration Include="Release|Win32">+ <Configuration>Release</Configuration>+ <Platform>Win32</Platform>+ </ProjectConfiguration>+ <ProjectConfiguration Include="Release|x64">+ <Configuration>Release</Configuration>+ <Platform>x64</Platform>+ </ProjectConfiguration>+ <ProjectConfiguration Include="Release|ARM64">+ <Configuration>Release</Configuration>+ <Platform>ARM64</Platform>+ </ProjectConfiguration>+ </ItemGroup>+ <PropertyGroup Label="Configuration">+ <ConfigurationType>Application</ConfigurationType>+ <PlatformToolset Condition="'$(VisualStudioVersion)' >= '18.0'">v145</PlatformToolset>+ <PlatformToolset Condition="'$(VisualStudioVersion)' < '18.0'">v143</PlatformToolset>+ <CharacterSet>Unicode</CharacterSet>+ <DesktopCompatible>true</DesktopCompatible>+ </PropertyGroup>+ <PropertyGroup Condition="'$(Configuration)'=='Debug'" Label="Configuration">+ <UseDebugLibraries>true</UseDebugLibraries>+ <LinkIncremental>true</LinkIncremental>+ </PropertyGroup>+ <PropertyGroup Condition="'$(Configuration)'=='Release'" Label="Configuration">+ <UseDebugLibraries>false</UseDebugLibraries>+ <WholeProgramOptimization>true</WholeProgramOptimization>+ <LinkIncremental>false</LinkIncremental>+ </PropertyGroup>+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />+ <ImportGroup Label="ExtensionSettings">+ </ImportGroup>+ <ImportGroup Label="PropertySheets">+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />+ </ImportGroup>+ <PropertyGroup Label="UserMacros" />+ <ItemDefinitionGroup>+ <ClCompile>+ <PrecompiledHeader>Use</PrecompiledHeader>+ <PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>+ <MultiProcessorCompilation>true</MultiProcessorCompilation>+ <WarningLevel>Level4</WarningLevel>+ <LanguageStandard Condition="'$(VisualStudioVersion)' >= '18.0'">stdcpp20</LanguageStandard>+ <LanguageStandard Condition="'$(VisualStudioVersion)' < '18.0'">stdcpp17</LanguageStandard>+ <AdditionalOptions>%(AdditionalOptions) /bigobj /Zm500</AdditionalOptions>+ <AdditionalIncludeDirectories>$(ProjectDir);C:\vcpkg\installed\x64-windows\include;C:\vcpkg\installed\x64-windows\include\mongocxx\v_noabi;C:\vcpkg\installed\x64-windows\include\bsoncxx\v_noabi;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>+ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>+ </ClCompile>+ <Link>+ <!-- Shared libs — names that are the same in both Debug and Release vcpkg.+ hiredis and mongocxx/bsoncxx have different names per config+ and are added in the config-specific ItemDefinitionGroup below. -->+ <AdditionalDependencies>Shell32.lib;Comdlg32.lib;Advapi32.lib;libpq.lib;libmariadb.lib;sqlite3.lib;libssl.lib;libcrypto.lib;crypt32.lib;ws2_32.lib;odbc32.lib;libssh2.lib;mongoc2.dll.lib;bson2.dll.lib;%(AdditionalDependencies)</AdditionalDependencies>+ </Link>+ </ItemDefinitionGroup>+ <!-- Debug: link against vcpkg debug libs + mongocxx debug variant -->+ <ItemDefinitionGroup Condition="'$(Configuration)'=='Debug'">+ <ClCompile>+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>+ </ClCompile>+ <Link>+ <AdditionalLibraryDirectories>C:\vcpkg\installed\x64-windows\debug\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>+ <AdditionalDependencies>mongocxx-v_noabi-dhi-mdd.lib;bsoncxx-v_noabi-dhi-mdd.lib;hiredisd.lib;%(AdditionalDependencies)</AdditionalDependencies>+ </Link>+ </ItemDefinitionGroup>+ <!-- Release: link against vcpkg release libs + mongocxx release variant -->+ <ItemDefinitionGroup Condition="'$(Configuration)'=='Release'">+ <ClCompile>+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>+ </ClCompile>+ <Link>+ <AdditionalLibraryDirectories>C:\vcpkg\installed\x64-windows\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>+ <AdditionalDependencies>mongocxx-v_noabi-rhi-md.lib;bsoncxx-v_noabi-rhi-md.lib;hiredis.lib;%(AdditionalDependencies)</AdditionalDependencies>+ </Link>+ <Link>+ <EnableCOMDATFolding>true</EnableCOMDATFolding>+ <OptimizeReferences>true</OptimizeReferences>+ </Link>+ </ItemDefinitionGroup>+ <ItemGroup Condition="'$(WindowsPackageType)'!='None' and Exists('Package.appxmanifest')">+ <AppxManifest Include="Package.appxmanifest">+ <SubType>Designer</SubType>+ </AppxManifest>+ </ItemGroup>+ <ItemGroup>+ <Manifest Include="app.manifest" />+ </ItemGroup>+ <ItemGroup>+ <ClInclude Include="Models\ColorTag.h" />+ <ClInclude Include="Models\ConnectionStore.h" />+ <ClInclude Include="Models\SidebarItem.h" />+ <ClInclude Include="Models\ContentTab.h" />+ <ClInclude Include="Models\ColumnInfo.h" />+ <ClInclude Include="Models\TableRow.h" />+ <ClInclude Include="Models\QueryResult.h" />+ <ClInclude Include="Models\WorkspaceState.h" />+ <ClInclude Include="Models\RowValue.h" />+ <ClInclude Include="Models\TableInfo.h" />+ <ClInclude Include="Models\QueryParameter.h" />+ <ClInclude Include="Models\DatabaseAdapter.h" />+ <ClInclude Include="Models\ConnectionManager.h" />+ <ClInclude Include="Models\PostgreSQLAdapter.h" />+ <ClInclude Include="Models\MySQLAdapter.h" />+ <ClInclude Include="Models\SQLiteAdapter.h" />+ <ClInclude Include="Models\RedisAdapter.h" />+ <ClInclude Include="Models\MongoDBAdapter.h" />+ <ClInclude Include="Models\MSSQLAdapter.h" />+ <ClInclude Include="Models\SSHTunnelService.h" />+ <ClInclude Include="Models\ChangeTracker.h" />+ <ClInclude Include="Models\CredentialManager.h" />+ <ClInclude Include="Models\AiService.h" />+ <ClInclude Include="Models\AppSettings.h" />+ <ClInclude Include="Models\DumpRestoreService.h" />+ <ClInclude Include="Models\ERDiagramService.h" />+ <ClInclude Include="Models\ExportService.h" />+ <ClInclude Include="Models\ImportService.h" />+ <ClInclude Include="xaml-includes.h" />+ <ClInclude Include="SettingsPage.h">+ <DependentUpon>SettingsPage.xaml</DependentUpon>+ <SubType>Code</SubType>+ </ClInclude>+ <ClInclude Include="ConnectionCard.h">+ <DependentUpon>ConnectionCard.xaml</DependentUpon>+ <SubType>Code</SubType>+ </ClInclude>+ <ClInclude Include="Models\ConnectionConfig.h" />+ <ClInclude Include="ConnectionFormDialog.h">+ <DependentUpon>ConnectionFormDialog.xaml</DependentUpon>+ <SubType>Code</SubType>+ </ClInclude>+ <ClInclude Include="Models\DatabaseType.h" />+ <ClInclude Include="DatabaseTypePickerDialog.h">+ <DependentUpon>DatabaseTypePickerDialog.xaml</DependentUpon>+ <SubType>Code</SubType>+ </ClInclude>+ <ClInclude Include="DataGridView.h">+ <DependentUpon>DataGridView.xaml</DependentUpon>+ <SubType>Code</SubType>+ </ClInclude>+ <ClInclude Include="DetailsPanel.h">+ <DependentUpon>DetailsPanel.xaml</DependentUpon>+ <SubType>Code</SubType>+ </ClInclude>+ <ClInclude Include="FilterBar.h">+ <DependentUpon>FilterBar.xaml</DependentUpon>+ <SubType>Code</SubType>+ </ClInclude>+ <ClInclude Include="HomePage.h">+ <DependentUpon>HomePage.xaml</DependentUpon>+ <SubType>Code</SubType>+ </ClInclude>+ <ClInclude Include="QueryEditorView.h">+ <DependentUpon>QueryEditorView.xaml</DependentUpon>+ <SubType>Code</SubType>+ </ClInclude>+ <ClInclude Include="SidebarPanel.h">+ <DependentUpon>SidebarPanel.xaml</DependentUpon>+ <SubType>Code</SubType>+ </ClInclude>+ <ClInclude Include="StatusBarControl.h">+ <DependentUpon>StatusBarControl.xaml</DependentUpon>+ <SubType>Code</SubType>+ </ClInclude>+ <ClInclude Include="StructureView.h">+ <DependentUpon>StructureView.xaml</DependentUpon>+ <SubType>Code</SubType>+ </ClInclude>+ <ClInclude Include="TabBarControl.h">+ <DependentUpon>TabBarControl.xaml</DependentUpon>+ <SubType>Code</SubType>+ </ClInclude>+ <ClInclude Include="WorkspacePage.h">+ <DependentUpon>WorkspacePage.xaml</DependentUpon>+ <SubType>Code</SubType>+ </ClInclude>+ <ClInclude Include="pch.h" />+ <ClInclude Include="App.xaml.h">+ <DependentUpon>App.xaml</DependentUpon>+ </ClInclude>+ <ClInclude Include="MainWindow.xaml.h">+ <DependentUpon>MainWindow.xaml</DependentUpon>+ </ClInclude>+ </ItemGroup>+ <ItemGroup>+ <ApplicationDefinition Include="App.xaml" />+ <Page Include="MainWindow.xaml" />+ <Page Include="ConnectionCard.xaml">+ <SubType>Designer</SubType>+ </Page>+ <Page Include="ConnectionFormDialog.xaml">+ <SubType>Designer</SubType>+ </Page>+ <Page Include="DatabaseTypePickerDialog.xaml">+ <SubType>Designer</SubType>+ </Page>+ <Page Include="DataGridView.xaml">+ <SubType>Designer</SubType>+ </Page>+ <Page Include="DetailsPanel.xaml">+ <SubType>Designer</SubType>+ </Page>+ <Page Include="FilterBar.xaml">+ <SubType>Designer</SubType>+ </Page>+ <Page Include="HomePage.xaml">+ <SubType>Designer</SubType>+ </Page>+ <Page Include="QueryEditorView.xaml">+ <SubType>Designer</SubType>+ </Page>+ <Page Include="SidebarPanel.xaml">+ <SubType>Designer</SubType>+ </Page>+ <Page Include="StatusBarControl.xaml">+ <SubType>Designer</SubType>+ </Page>+ <Page Include="StructureView.xaml">+ <SubType>Designer</SubType>+ </Page>+ <Page Include="TabBarControl.xaml">+ <SubType>Designer</SubType>+ </Page>+ <Page Include="WorkspacePage.xaml">+ <SubType>Designer</SubType>+ </Page>+ <Page Include="SettingsPage.xaml">+ <SubType>Designer</SubType>+ </Page>+ </ItemGroup>+ <ItemGroup>+ <ClCompile Include="ConnectionCard.cpp">+ <DependentUpon>ConnectionCard.xaml</DependentUpon>+ <SubType>Code</SubType>+ </ClCompile>+ <ClCompile Include="ConnectionFormDialog.cpp">+ <DependentUpon>ConnectionFormDialog.xaml</DependentUpon>+ <SubType>Code</SubType>+ </ClCompile>+ <ClCompile Include="DatabaseTypePickerDialog.cpp">+ <DependentUpon>DatabaseTypePickerDialog.xaml</DependentUpon>+ <SubType>Code</SubType>+ </ClCompile>+ <ClCompile Include="DataGridView.cpp">+ <DependentUpon>DataGridView.xaml</DependentUpon>+ <SubType>Code</SubType>+ </ClCompile>+ <ClCompile Include="DetailsPanel.cpp">+ <DependentUpon>DetailsPanel.xaml</DependentUpon>+ <SubType>Code</SubType>+ </ClCompile>+ <ClCompile Include="FilterBar.cpp">+ <DependentUpon>FilterBar.xaml</DependentUpon>+ <SubType>Code</SubType>+ </ClCompile>+ <ClCompile Include="HomePage.cpp">+ <DependentUpon>HomePage.xaml</DependentUpon>+ <SubType>Code</SubType>+ </ClCompile>+ <ClCompile Include="QueryEditorView.cpp">+ <DependentUpon>QueryEditorView.xaml</DependentUpon>+ <SubType>Code</SubType>+ </ClCompile>+ <ClCompile Include="SidebarPanel.cpp">+ <DependentUpon>SidebarPanel.xaml</DependentUpon>+ <SubType>Code</SubType>+ </ClCompile>+ <ClCompile Include="StatusBarControl.cpp">+ <DependentUpon>StatusBarControl.xaml</DependentUpon>+ <SubType>Code</SubType>+ </ClCompile>+ <ClCompile Include="StructureView.cpp">+ <DependentUpon>StructureView.xaml</DependentUpon>+ <SubType>Code</SubType>+ </ClCompile>+ <ClCompile Include="TabBarControl.cpp">+ <DependentUpon>TabBarControl.xaml</DependentUpon>+ <SubType>Code</SubType>+ </ClCompile>+ <ClCompile Include="WorkspacePage.cpp">+ <DependentUpon>WorkspacePage.xaml</DependentUpon>+ <SubType>Code</SubType>+ </ClCompile>+ <ClCompile Include="pch.cpp">+ <PrecompiledHeader>Create</PrecompiledHeader>+ </ClCompile>+ <ClCompile Include="App.xaml.cpp">+ <DependentUpon>App.xaml</DependentUpon>+ </ClCompile>+ <ClCompile Include="MainWindow.xaml.cpp">+ <DependentUpon>MainWindow.xaml</DependentUpon>+ </ClCompile>+ <ClCompile Include="$(GeneratedFilesDir)module.g.cpp">+ <PrecompiledHeader>NotUsing</PrecompiledHeader>+ </ClCompile>+ <ClCompile Include="ConnectionManager.cpp">+ <PrecompiledHeader>NotUsing</PrecompiledHeader>+ </ClCompile>+ <ClCompile Include="PostgreSQLAdapter.cpp">+ <PrecompiledHeader>NotUsing</PrecompiledHeader>+ </ClCompile>+ <ClCompile Include="MySQLAdapter.cpp">+ <PrecompiledHeader>NotUsing</PrecompiledHeader>+ </ClCompile>+ <ClCompile Include="SQLiteAdapter.cpp">+ <PrecompiledHeader>NotUsing</PrecompiledHeader>+ </ClCompile>+ <ClCompile Include="RedisAdapter.cpp">+ <PrecompiledHeader>NotUsing</PrecompiledHeader>+ </ClCompile>+ <ClCompile Include="MongoDBAdapter.cpp">+ <PrecompiledHeader>NotUsing</PrecompiledHeader>+ </ClCompile>+ <ClCompile Include="MSSQLAdapter.cpp">+ <PrecompiledHeader>NotUsing</PrecompiledHeader>+ </ClCompile>+ <ClCompile Include="SSHTunnelService.cpp">+ <PrecompiledHeader>NotUsing</PrecompiledHeader>+ </ClCompile>+ <ClCompile Include="MongoDBAdapterQuery.cpp">+ <PrecompiledHeader>NotUsing</PrecompiledHeader>+ </ClCompile>+ <ClCompile Include="CredentialManager.cpp">+ <PrecompiledHeader>NotUsing</PrecompiledHeader>+ </ClCompile>+ <ClCompile Include="AiService.cpp">+ <PrecompiledHeader>NotUsing</PrecompiledHeader>+ </ClCompile>+ <ClCompile Include="ExportService.cpp">+ <PrecompiledHeader>NotUsing</PrecompiledHeader>+ </ClCompile>+ <ClCompile Include="ImportService.cpp">+ <PrecompiledHeader>NotUsing</PrecompiledHeader>+ </ClCompile>+ <ClCompile Include="DumpRestoreService.cpp">+ <PrecompiledHeader>NotUsing</PrecompiledHeader>+ </ClCompile>+ <ClCompile Include="ERDiagramService.cpp">+ <PrecompiledHeader>NotUsing</PrecompiledHeader>+ </ClCompile>+ <ClCompile Include="AppSettings.cpp">+ <PrecompiledHeader>NotUsing</PrecompiledHeader>+ </ClCompile>+ <ClCompile Include="SettingsPage.cpp">+ <DependentUpon>SettingsPage.xaml</DependentUpon>+ <SubType>Code</SubType>+ </ClCompile>+ </ItemGroup>+ <ItemGroup>+ <Midl Include="MainWindow.idl">+ <SubType>Code</SubType>+ <DependentUpon>MainWindow.xaml</DependentUpon>+ </Midl>+ <Midl Include="ConnectionCard.idl">+ <DependentUpon>ConnectionCard.xaml</DependentUpon>+ <SubType>Code</SubType>+ </Midl>+ <Midl Include="ConnectionFormDialog.idl">+ <DependentUpon>ConnectionFormDialog.xaml</DependentUpon>+ <SubType>Code</SubType>+ </Midl>+ <Midl Include="DatabaseTypePickerDialog.idl">+ <DependentUpon>DatabaseTypePickerDialog.xaml</DependentUpon>+ <SubType>Code</SubType>+ </Midl>+ <Midl Include="DataGridView.idl">+ <DependentUpon>DataGridView.xaml</DependentUpon>+ <SubType>Code</SubType>+ </Midl>+ <Midl Include="DetailsPanel.idl">+ <DependentUpon>DetailsPanel.xaml</DependentUpon>+ <SubType>Code</SubType>+ </Midl>+ <Midl Include="FilterBar.idl">+ <DependentUpon>FilterBar.xaml</DependentUpon>+ <SubType>Code</SubType>+ </Midl>+ <Midl Include="HomePage.idl">+ <DependentUpon>HomePage.xaml</DependentUpon>+ <SubType>Code</SubType>+ </Midl>+ <Midl Include="QueryEditorView.idl">+ <DependentUpon>QueryEditorView.xaml</DependentUpon>+ <SubType>Code</SubType>+ </Midl>+ <Midl Include="SidebarPanel.idl">+ <DependentUpon>SidebarPanel.xaml</DependentUpon>+ <SubType>Code</SubType>+ </Midl>+ <Midl Include="StatusBarControl.idl">+ <DependentUpon>StatusBarControl.xaml</DependentUpon>+ <SubType>Code</SubType>+ </Midl>+ <Midl Include="StructureView.idl">+ <DependentUpon>StructureView.xaml</DependentUpon>+ <SubType>Code</SubType>+ </Midl>+ <Midl Include="TabBarControl.idl">+ <DependentUpon>TabBarControl.xaml</DependentUpon>+ <SubType>Code</SubType>+ </Midl>+ <Midl Include="WorkspacePage.idl">+ <DependentUpon>WorkspacePage.xaml</DependentUpon>+ <SubType>Code</SubType>+ </Midl>+ <Midl Include="SettingsPage.idl">+ <DependentUpon>SettingsPage.xaml</DependentUpon>+ <SubType>Code</SubType>+ </Midl>+ </ItemGroup>+ <ItemGroup>+ <Text Include="readme.txt">+ <DeploymentContent>false</DeploymentContent>+ </Text>+ </ItemGroup>+ <ItemGroup>+ <Image Include="Assets\LockScreenLogo.scale-200.png" />+ <Image Include="Assets\SplashScreen.scale-200.png" />+ <Image Include="Assets\Square150x150Logo.scale-200.png" />+ <Image Include="Assets\Square44x44Logo.scale-200.png" />+ <Image Include="Assets\Square44x44Logo.targetsize-24_altform-unplated.png" />+ <Image Include="Assets\StoreLogo.png" />+ <Image Include="Assets\gridex-icon-source.png" />+ <Image Include="Assets\Wide310x150Logo.scale-200.png" />+ </ItemGroup>+ <ItemGroup>+ <ResourceCompile Include="Gridex.rc" />+ <None Include="Assets\Gridex.ico" />+ </ItemGroup>+ <ItemGroup>+ <Content Include="Assets\monaco-editor.html">+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>+ </Content>+ <Content Include="Assets\d2\d2.exe" Condition="Exists('Assets\d2\d2.exe')">+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>+ <DeploymentContent>true</DeploymentContent>+ </Content>+ <Content Include="Assets\d2\LICENSE" Condition="Exists('Assets\d2\LICENSE')">+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>+ <DeploymentContent>true</DeploymentContent>+ </Content>+ <Content Include="Assets\d2\README.txt">+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>+ <DeploymentContent>true</DeploymentContent>+ </Content>+ <Content Include="Assets\THIRD-PARTY-NOTICES.txt">+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>+ <DeploymentContent>true</DeploymentContent>+ </Content>+ <!-- hiredis.dll: vcpkg auto-deploy doesn't pick this up reliably for MSIX+ packaging, so deploy it explicitly. The other vcpkg DLLs (libpq,+ libmariadb, libssl-3-x64, libcrypto-3-x64, sqlite3, zlib1) are+ handled by vcpkg integration's applocal step — DO NOT list them+ here or you get APPX110 duplicate-payload errors. -->+ <Content Include="C:\vcpkg\installed\x64-windows\bin\hiredis.dll" Condition="'$(Configuration)'=='Release'">+ <Link>hiredis.dll</Link>+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>+ <DeploymentContent>true</DeploymentContent>+ </Content>+ <Content Include="C:\vcpkg\installed\x64-windows\debug\bin\hiredisd.dll" Condition="'$(Configuration)'=='Debug'">+ <Link>hiredisd.dll</Link>+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>+ <DeploymentContent>true</DeploymentContent>+ </Content>+ <!-- MongoDB + shared DLLs: config-conditional so Debug links /MDd+ variants and Release links /MD variants. The C driver DLLs+ (mongoc2, bson2) have the SAME filename but different builds;+ the C++ DLLs have different filenames (-dhi-mdd vs -rhi-md).+ Mixing Debug exe with Release DLLs causes ABI mismatch →+ strlen(NULL) crash inside mongoc_uri_parse. -->+ <!-- Release DLLs -->+ <Content Include="C:\vcpkg\installed\x64-windows\bin\mongocxx-v_noabi-rhi-md.dll" Condition="'$(Configuration)'=='Release'">+ <Link>mongocxx-v_noabi-rhi-md.dll</Link>+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>+ <DeploymentContent>true</DeploymentContent>+ </Content>+ <Content Include="C:\vcpkg\installed\x64-windows\bin\bsoncxx-v_noabi-rhi-md.dll" Condition="'$(Configuration)'=='Release'">+ <Link>bsoncxx-v_noabi-rhi-md.dll</Link>+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>+ <DeploymentContent>true</DeploymentContent>+ </Content>+ <Content Include="C:\vcpkg\installed\x64-windows\bin\mongoc2.dll" Condition="'$(Configuration)'=='Release'">+ <Link>mongoc2.dll</Link>+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>+ <DeploymentContent>true</DeploymentContent>+ </Content>+ <Content Include="C:\vcpkg\installed\x64-windows\bin\bson2.dll" Condition="'$(Configuration)'=='Release'">+ <Link>bson2.dll</Link>+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>+ <DeploymentContent>true</DeploymentContent>+ </Content>+ <Content Include="C:\vcpkg\installed\x64-windows\bin\zlib1.dll" Condition="'$(Configuration)'=='Release'">+ <Link>zlib1.dll</Link>+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>+ <DeploymentContent>true</DeploymentContent>+ </Content>+ <!-- Debug DLLs -->+ <Content Include="C:\vcpkg\installed\x64-windows\debug\bin\mongocxx-v_noabi-dhi-mdd.dll" Condition="'$(Configuration)'=='Debug'">+ <Link>mongocxx-v_noabi-dhi-mdd.dll</Link>+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>+ <DeploymentContent>true</DeploymentContent>+ </Content>+ <Content Include="C:\vcpkg\installed\x64-windows\debug\bin\bsoncxx-v_noabi-dhi-mdd.dll" Condition="'$(Configuration)'=='Debug'">+ <Link>bsoncxx-v_noabi-dhi-mdd.dll</Link>+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>+ <DeploymentContent>true</DeploymentContent>+ </Content>+ <Content Include="C:\vcpkg\installed\x64-windows\debug\bin\mongoc2.dll" Condition="'$(Configuration)'=='Debug'">+ <Link>mongoc2.dll</Link>+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>+ <DeploymentContent>true</DeploymentContent>+ </Content>+ <Content Include="C:\vcpkg\installed\x64-windows\debug\bin\bson2.dll" Condition="'$(Configuration)'=='Debug'">+ <Link>bson2.dll</Link>+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>+ <DeploymentContent>true</DeploymentContent>+ </Content>+ <Content Include="C:\vcpkg\installed\x64-windows\debug\bin\zlibd1.dll" Condition="'$(Configuration)'=='Debug'">+ <Link>zlibd1.dll</Link>+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>+ <DeploymentContent>true</DeploymentContent>+ </Content>+ <!-- Remaining vcpkg debug DLLs that applocal may miss in MSIX mode -->+ <Content Include="C:\vcpkg\installed\x64-windows\debug\bin\libpq.dll" Condition="'$(Configuration)'=='Debug'">+ <Link>libpq.dll</Link>+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>+ <DeploymentContent>true</DeploymentContent>+ </Content>+ <Content Include="C:\vcpkg\installed\x64-windows\debug\bin\libmariadb.dll" Condition="'$(Configuration)'=='Debug'">+ <Link>libmariadb.dll</Link>+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>+ <DeploymentContent>true</DeploymentContent>+ </Content>+ <Content Include="C:\vcpkg\installed\x64-windows\debug\bin\sqlite3.dll" Condition="'$(Configuration)'=='Debug'">+ <Link>sqlite3.dll</Link>+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>+ <DeploymentContent>true</DeploymentContent>+ </Content>+ <Content Include="C:\vcpkg\installed\x64-windows\debug\bin\libssl-3-x64.dll" Condition="'$(Configuration)'=='Debug'">+ <Link>libssl-3-x64.dll</Link>+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>+ <DeploymentContent>true</DeploymentContent>+ </Content>+ <Content Include="C:\vcpkg\installed\x64-windows\debug\bin\libcrypto-3-x64.dll" Condition="'$(Configuration)'=='Debug'">+ <Link>libcrypto-3-x64.dll</Link>+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>+ <DeploymentContent>true</DeploymentContent>+ </Content>+ <Content Include="C:\vcpkg\installed\x64-windows\debug\bin\utf8proc.dll" Condition="'$(Configuration)'=='Debug'">+ <Link>utf8proc.dll</Link>+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>+ <DeploymentContent>true</DeploymentContent>+ </Content>+ <Content Include="C:\vcpkg\installed\x64-windows\debug\bin\lz4d.dll" Condition="'$(Configuration)'=='Debug'">+ <Link>lz4d.dll</Link>+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>+ <DeploymentContent>true</DeploymentContent>+ </Content>+ <Content Include="C:\vcpkg\installed\x64-windows\debug\bin\brotlicommon.dll" Condition="'$(Configuration)'=='Debug'">+ <Link>brotlicommon.dll</Link>+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>+ <DeploymentContent>true</DeploymentContent>+ </Content>+ <Content Include="C:\vcpkg\installed\x64-windows\debug\bin\brotlidec.dll" Condition="'$(Configuration)'=='Debug'">+ <Link>brotlidec.dll</Link>+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>+ <DeploymentContent>true</DeploymentContent>+ </Content>+ <Content Include="C:\vcpkg\installed\x64-windows\debug\bin\brotlienc.dll" Condition="'$(Configuration)'=='Debug'">+ <Link>brotlienc.dll</Link>+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>+ <DeploymentContent>true</DeploymentContent>+ </Content>+ <Content Include="C:\vcpkg\installed\x64-windows\debug\bin\legacy.dll" Condition="'$(Configuration)'=='Debug'">+ <Link>legacy.dll</Link>+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>+ <DeploymentContent>true</DeploymentContent>+ </Content>+ <Content Include="C:\vcpkg\installed\x64-windows\debug\bin\libpgtypes.dll" Condition="'$(Configuration)'=='Debug'">+ <Link>libpgtypes.dll</Link>+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>+ <DeploymentContent>true</DeploymentContent>+ </Content>+ </ItemGroup>+ <!--+ Defining the "Msix" ProjectCapability here allows the Single-project MSIX Packaging+ Tools extension to be activated for this project even if the Windows App SDK Nuget+ package has not yet been restored.+ -->+ <ItemGroup Condition="'$(DisableMsixProjectCapabilityAddedByProject)'!='true' and '$(EnableMsixTooling)'=='true'">+ <ProjectCapability Include="Msix" />+ </ItemGroup>+ <!--+ Defining the "HasPackageAndPublishMenuAddedByProject" property here allows the Solution+ Explorer "Package and Publish" context menu entry to be enabled for this project even if+ the Windows App SDK Nuget package has not yet been restored.+ -->+ <ItemGroup>+ <None Include="packages.config" />+ </ItemGroup>+ <PropertyGroup Condition="'$(DisableHasPackageAndPublishMenuAddedByProject)'!='true' and '$(EnableMsixTooling)'=='true'">+ <HasPackageAndPublishMenu>true</HasPackageAndPublishMenu>+ </PropertyGroup>+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />+ <ImportGroup Label="ExtensionTargets">+ <Import Project="..\packages\Microsoft.Web.WebView2.1.0.3179.45\build\native\Microsoft.Web.WebView2.targets" Condition="Exists('..\packages\Microsoft.Web.WebView2.1.0.3179.45\build\native\Microsoft.Web.WebView2.targets')" />+ <Import Project="..\packages\Microsoft.Windows.SDK.BuildTools.MSIX.1.7.20250829.1\build\Microsoft.Windows.SDK.BuildTools.MSIX.targets" Condition="Exists('..\packages\Microsoft.Windows.SDK.BuildTools.MSIX.1.7.20250829.1\build\Microsoft.Windows.SDK.BuildTools.MSIX.targets')" />+ <Import Project="..\packages\Microsoft.WindowsAppSDK.Base.1.8.251216001\build\native\Microsoft.WindowsAppSDK.Base.targets" Condition="Exists('..\packages\Microsoft.WindowsAppSDK.Base.1.8.251216001\build\native\Microsoft.WindowsAppSDK.Base.targets')" />+ <Import Project="..\packages\Microsoft.WindowsAppSDK.DWrite.1.8.25122902\build\Microsoft.WindowsAppSDK.DWrite.targets" Condition="Exists('..\packages\Microsoft.WindowsAppSDK.DWrite.1.8.25122902\build\Microsoft.WindowsAppSDK.DWrite.targets')" />+ <Import Project="..\packages\Microsoft.WindowsAppSDK.InteractiveExperiences.1.8.260125001\build\native\Microsoft.WindowsAppSDK.InteractiveExperiences.targets" Condition="Exists('..\packages\Microsoft.WindowsAppSDK.InteractiveExperiences.1.8.260125001\build\native\Microsoft.WindowsAppSDK.InteractiveExperiences.targets')" />+ <Import Project="..\packages\Microsoft.WindowsAppSDK.Foundation.1.8.260222000\build\native\Microsoft.WindowsAppSDK.Foundation.targets" Condition="Exists('..\packages\Microsoft.WindowsAppSDK.Foundation.1.8.260222000\build\native\Microsoft.WindowsAppSDK.Foundation.targets')" />+ <Import Project="..\packages\Microsoft.WindowsAppSDK.AI.1.8.53\build\native\Microsoft.WindowsAppSDK.AI.targets" Condition="Exists('..\packages\Microsoft.WindowsAppSDK.AI.1.8.53\build\native\Microsoft.WindowsAppSDK.AI.targets')" />+ <Import Project="..\packages\Microsoft.WindowsAppSDK.ML.1.8.2141\build\native\Microsoft.WindowsAppSDK.ML.targets" Condition="Exists('..\packages\Microsoft.WindowsAppSDK.ML.1.8.2141\build\native\Microsoft.WindowsAppSDK.ML.targets')" />+ <Import Project="..\packages\Microsoft.WindowsAppSDK.Runtime.1.8.260317003\build\native\Microsoft.WindowsAppSDK.Runtime.targets" Condition="Exists('..\packages\Microsoft.WindowsAppSDK.Runtime.1.8.260317003\build\native\Microsoft.WindowsAppSDK.Runtime.targets')" />+ <Import Project="..\packages\Microsoft.WindowsAppSDK.Widgets.1.8.251231004\build\native\Microsoft.WindowsAppSDK.Widgets.targets" Condition="Exists('..\packages\Microsoft.WindowsAppSDK.Widgets.1.8.251231004\build\native\Microsoft.WindowsAppSDK.Widgets.targets')" />+ <Import Project="..\packages\Microsoft.WindowsAppSDK.WinUI.1.8.260224000\build\native\Microsoft.WindowsAppSDK.WinUI.targets" Condition="Exists('..\packages\Microsoft.WindowsAppSDK.WinUI.1.8.260224000\build\native\Microsoft.WindowsAppSDK.WinUI.targets')" />+ <Import Project="..\packages\Microsoft.WindowsAppSDK.1.8.260317003\build\native\Microsoft.WindowsAppSDK.targets" Condition="Exists('..\packages\Microsoft.WindowsAppSDK.1.8.260317003\build\native\Microsoft.WindowsAppSDK.targets')" />+ <Import Project="..\packages\Microsoft.Windows.CppWinRT.2.0.250303.1\build\native\Microsoft.Windows.CppWinRT.targets" Condition="Exists('..\packages\Microsoft.Windows.CppWinRT.2.0.250303.1\build\native\Microsoft.Windows.CppWinRT.targets')" />+ <Import Project="..\packages\Microsoft.Windows.SDK.BuildTools.10.0.28000.1721\build\Microsoft.Windows.SDK.BuildTools.targets" Condition="Exists('..\packages\Microsoft.Windows.SDK.BuildTools.10.0.28000.1721\build\Microsoft.Windows.SDK.BuildTools.targets')" />+ <Import Project="..\packages\Microsoft.Windows.ImplementationLibrary.1.0.260126.7\build\native\Microsoft.Windows.ImplementationLibrary.targets" Condition="Exists('..\packages\Microsoft.Windows.ImplementationLibrary.1.0.260126.7\build\native\Microsoft.Windows.ImplementationLibrary.targets')" />+ </ImportGroup>+ <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">+ <PropertyGroup>+ <ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>+ </PropertyGroup>+ <Error Condition="!Exists('..\packages\Microsoft.Web.WebView2.1.0.3179.45\build\native\Microsoft.Web.WebView2.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Web.WebView2.1.0.3179.45\build\native\Microsoft.Web.WebView2.targets'))" />+ <Error Condition="!Exists('..\packages\Microsoft.Windows.SDK.BuildTools.MSIX.1.7.20250829.1\build\Microsoft.Windows.SDK.BuildTools.MSIX.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Windows.SDK.BuildTools.MSIX.1.7.20250829.1\build\Microsoft.Windows.SDK.BuildTools.MSIX.props'))" />+ <Error Condition="!Exists('..\packages\Microsoft.Windows.SDK.BuildTools.MSIX.1.7.20250829.1\build\Microsoft.Windows.SDK.BuildTools.MSIX.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Windows.SDK.BuildTools.MSIX.1.7.20250829.1\build\Microsoft.Windows.SDK.BuildTools.MSIX.targets'))" />+ <Error Condition="!Exists('..\packages\Microsoft.WindowsAppSDK.Base.1.8.251216001\build\native\Microsoft.WindowsAppSDK.Base.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.WindowsAppSDK.Base.1.8.251216001\build\native\Microsoft.WindowsAppSDK.Base.props'))" />+ <Error Condition="!Exists('..\packages\Microsoft.WindowsAppSDK.Base.1.8.251216001\build\native\Microsoft.WindowsAppSDK.Base.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.WindowsAppSDK.Base.1.8.251216001\build\native\Microsoft.WindowsAppSDK.Base.targets'))" />+ <Error Condition="!Exists('..\packages\Microsoft.WindowsAppSDK.DWrite.1.8.25122902\build\Microsoft.WindowsAppSDK.DWrite.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.WindowsAppSDK.DWrite.1.8.25122902\build\Microsoft.WindowsAppSDK.DWrite.props'))" />+ <Error Condition="!Exists('..\packages\Microsoft.WindowsAppSDK.DWrite.1.8.25122902\build\Microsoft.WindowsAppSDK.DWrite.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.WindowsAppSDK.DWrite.1.8.25122902\build\Microsoft.WindowsAppSDK.DWrite.targets'))" />+ <Error Condition="!Exists('..\packages\Microsoft.WindowsAppSDK.InteractiveExperiences.1.8.260125001\build\native\Microsoft.WindowsAppSDK.InteractiveExperiences.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.WindowsAppSDK.InteractiveExperiences.1.8.260125001\build\native\Microsoft.WindowsAppSDK.InteractiveExperiences.props'))" />+ <Error Condition="!Exists('..\packages\Microsoft.WindowsAppSDK.InteractiveExperiences.1.8.260125001\build\native\Microsoft.WindowsAppSDK.InteractiveExperiences.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.WindowsAppSDK.InteractiveExperiences.1.8.260125001\build\native\Microsoft.WindowsAppSDK.InteractiveExperiences.targets'))" />+ <Error Condition="!Exists('..\packages\Microsoft.WindowsAppSDK.Foundation.1.8.260222000\build\native\Microsoft.WindowsAppSDK.Foundation.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.WindowsAppSDK.Foundation.1.8.260222000\build\native\Microsoft.WindowsAppSDK.Foundation.props'))" />+ <Error Condition="!Exists('..\packages\Microsoft.WindowsAppSDK.Foundation.1.8.260222000\build\native\Microsoft.WindowsAppSDK.Foundation.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.WindowsAppSDK.Foundation.1.8.260222000\build\native\Microsoft.WindowsAppSDK.Foundation.targets'))" />+ <Error Condition="!Exists('..\packages\Microsoft.WindowsAppSDK.AI.1.8.53\build\native\Microsoft.WindowsAppSDK.AI.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.WindowsAppSDK.AI.1.8.53\build\native\Microsoft.WindowsAppSDK.AI.props'))" />+ <Error Condition="!Exists('..\packages\Microsoft.WindowsAppSDK.AI.1.8.53\build\native\Microsoft.WindowsAppSDK.AI.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.WindowsAppSDK.AI.1.8.53\build\native\Microsoft.WindowsAppSDK.AI.targets'))" />+ <Error Condition="!Exists('..\packages\Microsoft.WindowsAppSDK.ML.1.8.2141\build\native\Microsoft.WindowsAppSDK.ML.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.WindowsAppSDK.ML.1.8.2141\build\native\Microsoft.WindowsAppSDK.ML.props'))" />+ <Error Condition="!Exists('..\packages\Microsoft.WindowsAppSDK.ML.1.8.2141\build\native\Microsoft.WindowsAppSDK.ML.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.WindowsAppSDK.ML.1.8.2141\build\native\Microsoft.WindowsAppSDK.ML.targets'))" />+ <Error Condition="!Exists('..\packages\Microsoft.WindowsAppSDK.Runtime.1.8.260317003\build\native\Microsoft.WindowsAppSDK.Runtime.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.WindowsAppSDK.Runtime.1.8.260317003\build\native\Microsoft.WindowsAppSDK.Runtime.props'))" />+ <Error Condition="!Exists('..\packages\Microsoft.WindowsAppSDK.Runtime.1.8.260317003\build\native\Microsoft.WindowsAppSDK.Runtime.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.WindowsAppSDK.Runtime.1.8.260317003\build\native\Microsoft.WindowsAppSDK.Runtime.targets'))" />+ <Error Condition="!Exists('..\packages\Microsoft.WindowsAppSDK.Widgets.1.8.251231004\build\native\Microsoft.WindowsAppSDK.Widgets.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.WindowsAppSDK.Widgets.1.8.251231004\build\native\Microsoft.WindowsAppSDK.Widgets.props'))" />+ <Error Condition="!Exists('..\packages\Microsoft.WindowsAppSDK.Widgets.1.8.251231004\build\native\Microsoft.WindowsAppSDK.Widgets.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.WindowsAppSDK.Widgets.1.8.251231004\build\native\Microsoft.WindowsAppSDK.Widgets.targets'))" />+ <Error Condition="!Exists('..\packages\Microsoft.WindowsAppSDK.WinUI.1.8.260224000\build\native\Microsoft.WindowsAppSDK.WinUI.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.WindowsAppSDK.WinUI.1.8.260224000\build\native\Microsoft.WindowsAppSDK.WinUI.props'))" />+ <Error Condition="!Exists('..\packages\Microsoft.WindowsAppSDK.WinUI.1.8.260224000\build\native\Microsoft.WindowsAppSDK.WinUI.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.WindowsAppSDK.WinUI.1.8.260224000\build\native\Microsoft.WindowsAppSDK.WinUI.targets'))" />+ <Error Condition="!Exists('..\packages\Microsoft.WindowsAppSDK.1.8.260317003\build\native\Microsoft.WindowsAppSDK.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.WindowsAppSDK.1.8.260317003\build\native\Microsoft.WindowsAppSDK.props'))" />+ <Error Condition="!Exists('..\packages\Microsoft.WindowsAppSDK.1.8.260317003\build\native\Microsoft.WindowsAppSDK.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.WindowsAppSDK.1.8.260317003\build\native\Microsoft.WindowsAppSDK.targets'))" />+ <Error Condition="!Exists('..\packages\Microsoft.Windows.CppWinRT.2.0.250303.1\build\native\Microsoft.Windows.CppWinRT.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Windows.CppWinRT.2.0.250303.1\build\native\Microsoft.Windows.CppWinRT.props'))" />+ <Error Condition="!Exists('..\packages\Microsoft.Windows.CppWinRT.2.0.250303.1\build\native\Microsoft.Windows.CppWinRT.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Windows.CppWinRT.2.0.250303.1\build\native\Microsoft.Windows.CppWinRT.targets'))" />+ <Error Condition="!Exists('..\packages\Microsoft.Windows.SDK.BuildTools.10.0.28000.1721\build\Microsoft.Windows.SDK.BuildTools.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Windows.SDK.BuildTools.10.0.28000.1721\build\Microsoft.Windows.SDK.BuildTools.props'))" />+ <Error Condition="!Exists('..\packages\Microsoft.Windows.SDK.BuildTools.10.0.28000.1721\build\Microsoft.Windows.SDK.BuildTools.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Windows.SDK.BuildTools.10.0.28000.1721\build\Microsoft.Windows.SDK.BuildTools.targets'))" />+ <Error Condition="!Exists('..\packages\Microsoft.Windows.ImplementationLibrary.1.0.260126.7\build\native\Microsoft.Windows.ImplementationLibrary.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Windows.ImplementationLibrary.1.0.260126.7\build\native\Microsoft.Windows.ImplementationLibrary.targets'))" />+ </Target>+</Project>\ No newline at end of filediff --git a/windows/Gridex/Gridex.vcxproj.filters b/windows/Gridex/Gridex.vcxproj.filtersnew file mode 100644index 0000000..de18551--- /dev/null+++ b/windows/Gridex/Gridex.vcxproj.filters@@ -0,0 +1,306 @@+<?xml version="1.0" encoding="utf-8"?>+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">+ <ItemGroup>+ <ApplicationDefinition Include="App.xaml" />+ </ItemGroup>+ <ItemGroup>+ <Page Include="MainWindow.xaml" />+ <Page Include="HomePage.xaml">+ <Filter>Pages</Filter>+ </Page>+ <Page Include="WorkspacePage.xaml">+ <Filter>Pages</Filter>+ </Page>+ <Page Include="ConnectionCard.xaml">+ <Filter>Controls</Filter>+ </Page>+ <Page Include="DataGridView.xaml">+ <Filter>Controls</Filter>+ </Page>+ <Page Include="DetailsPanel.xaml">+ <Filter>Controls</Filter>+ </Page>+ <Page Include="FilterBar.xaml">+ <Filter>Controls</Filter>+ </Page>+ <Page Include="QueryEditorView.xaml">+ <Filter>Controls</Filter>+ </Page>+ <Page Include="SidebarPanel.xaml">+ <Filter>Controls</Filter>+ </Page>+ <Page Include="StatusBarControl.xaml">+ <Filter>Controls</Filter>+ </Page>+ <Page Include="StructureView.xaml">+ <Filter>Controls</Filter>+ </Page>+ <Page Include="TabBarControl.xaml">+ <Filter>Controls</Filter>+ </Page>+ <Page Include="ConnectionFormDialog.xaml">+ <Filter>Dialogs</Filter>+ </Page>+ <Page Include="DatabaseTypePickerDialog.xaml">+ <Filter>Dialogs</Filter>+ </Page>+ </ItemGroup>+ <ItemGroup>+ <Midl Include="MainWindow.idl" />+ <Midl Include="HomePage.idl">+ <Filter>Pages</Filter>+ </Midl>+ <Midl Include="WorkspacePage.idl">+ <Filter>Pages</Filter>+ </Midl>+ <Midl Include="ConnectionCard.idl">+ <Filter>Controls</Filter>+ </Midl>+ <Midl Include="DataGridView.idl">+ <Filter>Controls</Filter>+ </Midl>+ <Midl Include="DetailsPanel.idl">+ <Filter>Controls</Filter>+ </Midl>+ <Midl Include="FilterBar.idl">+ <Filter>Controls</Filter>+ </Midl>+ <Midl Include="QueryEditorView.idl">+ <Filter>Controls</Filter>+ </Midl>+ <Midl Include="SidebarPanel.idl">+ <Filter>Controls</Filter>+ </Midl>+ <Midl Include="StatusBarControl.idl">+ <Filter>Controls</Filter>+ </Midl>+ <Midl Include="StructureView.idl">+ <Filter>Controls</Filter>+ </Midl>+ <Midl Include="TabBarControl.idl">+ <Filter>Controls</Filter>+ </Midl>+ <Midl Include="ConnectionFormDialog.idl">+ <Filter>Dialogs</Filter>+ </Midl>+ <Midl Include="DatabaseTypePickerDialog.idl">+ <Filter>Dialogs</Filter>+ </Midl>+ </ItemGroup>+ <ItemGroup>+ <ClCompile Include="pch.cpp" />+ <ClCompile Include="$(GeneratedFilesDir)module.g.cpp" />+ <ClCompile Include="HomePage.cpp">+ <Filter>Pages</Filter>+ </ClCompile>+ <ClCompile Include="WorkspacePage.cpp">+ <Filter>Pages</Filter>+ </ClCompile>+ <ClCompile Include="ConnectionCard.cpp">+ <Filter>Controls</Filter>+ </ClCompile>+ <ClCompile Include="DataGridView.cpp">+ <Filter>Controls</Filter>+ </ClCompile>+ <ClCompile Include="DetailsPanel.cpp">+ <Filter>Controls</Filter>+ </ClCompile>+ <ClCompile Include="FilterBar.cpp">+ <Filter>Controls</Filter>+ </ClCompile>+ <ClCompile Include="QueryEditorView.cpp">+ <Filter>Controls</Filter>+ </ClCompile>+ <ClCompile Include="SidebarPanel.cpp">+ <Filter>Controls</Filter>+ </ClCompile>+ <ClCompile Include="StatusBarControl.cpp">+ <Filter>Controls</Filter>+ </ClCompile>+ <ClCompile Include="StructureView.cpp">+ <Filter>Controls</Filter>+ </ClCompile>+ <ClCompile Include="TabBarControl.cpp">+ <Filter>Controls</Filter>+ </ClCompile>+ <ClCompile Include="ConnectionFormDialog.cpp">+ <Filter>Dialogs</Filter>+ </ClCompile>+ <ClCompile Include="DatabaseTypePickerDialog.cpp">+ <Filter>Dialogs</Filter>+ </ClCompile>+ <ClCompile Include="App.xaml.cpp" />+ <ClCompile Include="MainWindow.xaml.cpp" />+ <ClCompile Include="ConnectionManager.cpp">+ <Filter>Data</Filter>+ </ClCompile>+ <ClCompile Include="PostgreSQLAdapter.cpp">+ <Filter>Data</Filter>+ </ClCompile>+ <ClCompile Include="MongoDBAdapter.cpp">+ <Filter>Data</Filter>+ </ClCompile>+ <ClCompile Include="MongoDBAdapterQuery.cpp">+ <Filter>Data</Filter>+ </ClCompile>+ <ClCompile Include="MSSQLAdapter.cpp">+ <Filter>Data</Filter>+ </ClCompile>+ <ClCompile Include="SSHTunnelService.cpp">+ <Filter>Data</Filter>+ </ClCompile>+ </ItemGroup>+ <ItemGroup>+ <ClInclude Include="pch.h" />+ <ClInclude Include="Models\ConnectionConfig.h">+ <Filter>Models</Filter>+ </ClInclude>+ <ClInclude Include="Models\DatabaseType.h">+ <Filter>Models</Filter>+ </ClInclude>+ <ClInclude Include="Models\ColorTag.h">+ <Filter>Models</Filter>+ </ClInclude>+ <ClInclude Include="Models\SidebarItem.h">+ <Filter>Models</Filter>+ </ClInclude>+ <ClInclude Include="Models\ContentTab.h">+ <Filter>Models</Filter>+ </ClInclude>+ <ClInclude Include="Models\ColumnInfo.h">+ <Filter>Models</Filter>+ </ClInclude>+ <ClInclude Include="Models\TableRow.h">+ <Filter>Models</Filter>+ </ClInclude>+ <ClInclude Include="Models\QueryResult.h">+ <Filter>Models</Filter>+ </ClInclude>+ <ClInclude Include="Models\WorkspaceState.h">+ <Filter>Models</Filter>+ </ClInclude>+ <ClInclude Include="Models\RowValue.h">+ <Filter>Models</Filter>+ </ClInclude>+ <ClInclude Include="Models\TableInfo.h">+ <Filter>Models</Filter>+ </ClInclude>+ <ClInclude Include="Models\QueryParameter.h">+ <Filter>Models</Filter>+ </ClInclude>+ <ClInclude Include="Models\DatabaseAdapter.h">+ <Filter>Models</Filter>+ </ClInclude>+ <ClInclude Include="Models\ConnectionManager.h">+ <Filter>Data</Filter>+ </ClInclude>+ <ClInclude Include="Models\MongoDBAdapter.h">+ <Filter>Data</Filter>+ </ClInclude>+ <ClInclude Include="Models\MSSQLAdapter.h">+ <Filter>Data</Filter>+ </ClInclude>+ <ClInclude Include="Models\SSHTunnelService.h">+ <Filter>Data</Filter>+ </ClInclude>+ <ClInclude Include="Models\PostgreSQLAdapter.h">+ <Filter>Data</Filter>+ </ClInclude>+ <ClInclude Include="HomePage.h">+ <Filter>Pages</Filter>+ </ClInclude>+ <ClInclude Include="WorkspacePage.h">+ <Filter>Pages</Filter>+ </ClInclude>+ <ClInclude Include="ConnectionCard.h">+ <Filter>Controls</Filter>+ </ClInclude>+ <ClInclude Include="DataGridView.h">+ <Filter>Controls</Filter>+ </ClInclude>+ <ClInclude Include="DetailsPanel.h">+ <Filter>Controls</Filter>+ </ClInclude>+ <ClInclude Include="FilterBar.h">+ <Filter>Controls</Filter>+ </ClInclude>+ <ClInclude Include="QueryEditorView.h">+ <Filter>Controls</Filter>+ </ClInclude>+ <ClInclude Include="SidebarPanel.h">+ <Filter>Controls</Filter>+ </ClInclude>+ <ClInclude Include="StatusBarControl.h">+ <Filter>Controls</Filter>+ </ClInclude>+ <ClInclude Include="StructureView.h">+ <Filter>Controls</Filter>+ </ClInclude>+ <ClInclude Include="TabBarControl.h">+ <Filter>Controls</Filter>+ </ClInclude>+ <ClInclude Include="ConnectionFormDialog.h">+ <Filter>Dialogs</Filter>+ </ClInclude>+ <ClInclude Include="DatabaseTypePickerDialog.h">+ <Filter>Dialogs</Filter>+ </ClInclude>+ <ClInclude Include="App.xaml.h" />+ <ClInclude Include="MainWindow.xaml.h" />+ </ItemGroup>+ <ItemGroup>+ <Image Include="Assets\Wide310x150Logo.scale-200.png">+ <Filter>Assets</Filter>+ </Image>+ <Image Include="Assets\StoreLogo.png">+ <Filter>Assets</Filter>+ </Image>+ <Image Include="Assets\Square150x150Logo.scale-200.png">+ <Filter>Assets</Filter>+ </Image>+ <Image Include="Assets\Square44x44Logo.targetsize-24_altform-unplated.png">+ <Filter>Assets</Filter>+ </Image>+ <Image Include="Assets\Square44x44Logo.scale-200.png">+ <Filter>Assets</Filter>+ </Image>+ <Image Include="Assets\SplashScreen.scale-200.png">+ <Filter>Assets</Filter>+ </Image>+ <Image Include="Assets\LockScreenLogo.scale-200.png">+ <Filter>Assets</Filter>+ </Image>+ </ItemGroup>+ <ItemGroup>+ <Filter Include="Assets">+ <UniqueIdentifier>{89a0fae9-44a2-4889-9bd1-50998c237d7c}</UniqueIdentifier>+ </Filter>+ <Filter Include="Models">+ <UniqueIdentifier>{826afbb0-1e27-42dc-b2ee-0a92dc58db58}</UniqueIdentifier>+ </Filter>+ <Filter Include="Pages">+ <UniqueIdentifier>{815cae65-a511-4db2-83a5-d04323bab1b3}</UniqueIdentifier>+ </Filter>+ <Filter Include="Controls">+ <UniqueIdentifier>{005f8f76-83ce-4fad-8e7f-ea6d237fb8e8}</UniqueIdentifier>+ </Filter>+ <Filter Include="Dialogs">+ <UniqueIdentifier>{46cc5852-54d0-49ab-924c-2455b85d851f}</UniqueIdentifier>+ </Filter>+ <Filter Include="Data">+ <UniqueIdentifier>{f3a1b2c4-9d8e-4f7a-b3c2-1e5d6a7b8c9d}</UniqueIdentifier>+ </Filter>+ </ItemGroup>+ <ItemGroup>+ <Text Include="readme.txt" />+ </ItemGroup>+ <ItemGroup>+ <Manifest Include="app.manifest" />+ </ItemGroup>+ <ItemGroup>+ <AppxManifest Include="Package.appxmanifest" />+ </ItemGroup>+ <ItemGroup>+ <None Include="packages.config" />+ </ItemGroup>+</Project>diff --git a/windows/Gridex/GridexVersion.h b/windows/Gridex/GridexVersion.hnew file mode 100644index 0000000..d6a86cb--- /dev/null+++ b/windows/Gridex/GridexVersion.h@@ -0,0 +1,23 @@+#pragma once+//+// Gridex version string shown in the About section of SettingsPage.+//+// The actual value lives in `GridexVersion.generated.h`, which is+// (always) written by `windows\scripts\build-unpackaged.ps1` before+// MSBuild runs. The CI workflow (.github/workflows/windows-release.yml)+// passes `-Version <tag>`; local dev builds run without it and get the+// "0.0.0-dev" sentinel so it is obvious the binary is not a tagged+// release.+//+// Why an UNCONDITIONAL include (no __has_include): MSBuild incremental+// builds use the per-file `.tlog` to decide whether a translation unit+// must be recompiled. `.tlog` only records headers that were actually+// pulled in during the last compile, so a conditional include via+// __has_include is invisible to the dependency scanner. That meant+// switching the script between `-Version` and no-Version runs left+// SettingsPage.obj stale -- the UI kept showing the old version. The+// build script now ALWAYS writes the generated header (default value+// `0.0.0-dev`), making the dependency real and the incremental build+// reliable.+//+#include "GridexVersion.generated.h"diff --git a/windows/Gridex/Header.h b/windows/Gridex/Header.hnew file mode 100644index 0000000..6f70f09--- /dev/null+++ b/windows/Gridex/Header.h@@ -0,0 +1 @@+#pragma oncediff --git a/windows/Gridex/HomePage.cpp b/windows/Gridex/HomePage.cppnew file mode 100644index 0000000..71dc35b--- /dev/null+++ b/windows/Gridex/HomePage.cpp@@ -0,0 +1,532 @@+#include "pch.h"+#include "xaml-includes.h"+#include <winrt/Windows.UI.h>+#include <winrt/Windows.UI.Text.h>+#include <winrt/Microsoft.UI.Xaml.Interop.h>+#include <algorithm>+#include "HomePage.h"+#include "Models/AppSettings.h"+#if __has_include("HomePage.g.cpp")+#include "HomePage.g.cpp"+#endif++#include "ConnectionCard.h"+#include "DatabaseTypePickerDialog.h"+#include "ConnectionFormDialog.h"+#include "WorkspacePage.h"+#include "App.xaml.h"+#include "Models/ConnectionStore.h"+#include "Models/ConnectionManager.h"++namespace winrt::Gridex::implementation+{+ namespace mux = winrt::Microsoft::UI::Xaml;+ namespace muxc = winrt::Microsoft::UI::Xaml::Controls;+ namespace muxm = winrt::Microsoft::UI::Xaml::Media;++ HomePage::HomePage()+ {+ InitializeComponent();++ // Load saved connections from disk+ allConnections_ = DBModels::ConnectionStore::Load();+ RefreshList();+ }++ void HomePage::DeleteConnection(const std::wstring& id)+ {+ // Remove from memory+ allConnections_.erase(+ std::remove_if(allConnections_.begin(), allConnections_.end(),+ [&id](const DBModels::ConnectionConfig& c) { return c.id == id; }),+ allConnections_.end());++ // Remove from SQLite+ DBModels::ConnectionStore::Delete(id);++ // Refresh UI+ RefreshList();+ }++ // Test a connection synchronously on the UI thread. Uses Win32 MessageBox+ // for the result — a ContentDialog cannot be shown while the parent edit+ // form ContentDialog is still open (WinUI 3 allows only one at a time).+ void HomePage::TestConnectionAsync(+ const DBModels::ConnectionConfig& config, const std::wstring& password)+ {+ bool success = false;+ std::wstring errorMsg;+ try+ {+ DBModels::ConnectionManager mgr;+ success = mgr.testConnection(config, password);+ if (!success) errorMsg = L"Connection test returned false.";+ }+ catch (const DBModels::DatabaseError& ex)+ {+ auto what = ex.what();+ int sz = MultiByteToWideChar(CP_UTF8, 0, what, -1, nullptr, 0);+ if (sz > 0)+ {+ errorMsg.resize(sz);+ MultiByteToWideChar(CP_UTF8, 0, what, -1, &errorMsg[0], sz);+ if (!errorMsg.empty() && errorMsg.back() == L'\0') errorMsg.pop_back();+ }+ }+ catch (...) { errorMsg = L"Unknown error"; }++ std::wstring title = success ? L"Connection Successful" : L"Connection Failed";+ std::wstring text = success+ ? (L"Successfully connected to " + config.host)+ : errorMsg;++ HWND owner = winrt::Gridex::implementation::App::MainHwnd;+ MessageBoxW(owner, text.c_str(), title.c_str(),+ MB_OK | (success ? MB_ICONINFORMATION : MB_ICONERROR));+ }++ void HomePage::EditConnection(const std::wstring& id)+ {+ // Find the connection in memory+ auto it = std::find_if(allConnections_.begin(), allConnections_.end(),+ [&id](const DBModels::ConnectionConfig& c) { return c.id == id; });+ if (it == allConnections_.end()) return;++ const auto existing = *it;++ // Show ConnectionFormDialog pre-filled with existing values+ muxc::ContentDialog formDialog;+ formDialog.Title(winrt::box_value(winrt::hstring(+ L"Edit " + DBModels::DatabaseTypeDisplayName(existing.databaseType) ++ L" Connection")));+ auto form = winrt::make<ConnectionFormDialog>();+ auto formImpl = form.as<ConnectionFormDialog>();+ formImpl->SetDatabaseType(existing.databaseType);+ formImpl->SetConnectionConfig(existing);+ formDialog.Content(form);+ formDialog.CloseButtonText(L"Cancel");+ formDialog.XamlRoot(this->XamlRoot());+ formDialog.Resources().Insert(+ winrt::box_value(L"ContentDialogMaxWidth"),+ winrt::box_value(800.0));+ formDialog.Resources().Insert(+ winrt::box_value(L"ContentDialogMinWidth"),+ winrt::box_value(720.0));++ // Save — keep original id, overwrite existing record+ formImpl->OnSave = [this, formImpl, formDialog, id]() mutable+ {+ auto config = formImpl->GetConnectionConfig();+ config.id = id; // preserve original id++ // Password comes from form (pre-filled on open). If somehow empty,+ // fall back to stored value to avoid breaking the connection.+ config.password = formImpl->GetPassword();+ if (config.password.empty())+ {+ auto existingIt = std::find_if(+ allConnections_.begin(), allConnections_.end(),+ [&id](const DBModels::ConnectionConfig& c) { return c.id == id; });+ if (existingIt != allConnections_.end())+ config.password = existingIt->password;+ }++ // Update in-memory list+ for (auto& c : allConnections_)+ if (c.id == id) { c = config; break; }++ DBModels::ConnectionStore::Save(config);+ RefreshList();+ formDialog.Hide();+ };++ // Test — validate current form values without saving+ formImpl->OnTest = [this, formImpl, id]()+ {+ auto config = formImpl->GetConnectionConfig();+ config.id = id;+ auto pwd = formImpl->GetPassword();+ if (pwd.empty())+ {+ // Fall back to stored password if user didn't change it+ auto it = std::find_if(allConnections_.begin(), allConnections_.end(),+ [&id](const DBModels::ConnectionConfig& c) { return c.id == id; });+ if (it != allConnections_.end()) pwd = it->password;+ }+ TestConnectionAsync(config, pwd);+ };++ formDialog.ShowAsync();+ }++ void HomePage::AddConnectionCard(const DBModels::ConnectionConfig& config)+ {+ auto card = winrt::make<ConnectionCard>();+ auto cardImpl = card.as<ConnectionCard>();+ cardImpl->SetConnection(config);+ cardImpl->OnDelete = [this](const std::wstring& id)+ {+ DeleteConnection(id);+ };+ cardImpl->OnEdit = [this](const std::wstring& id)+ {+ EditConnection(id);+ };+ card.Tag(winrt::box_value(winrt::hstring(config.id)));+ ConnectionsListView().Items().Append(card);+ }++ void HomePage::RefreshList(const std::wstring& searchQuery)+ {+ ConnectionsListView().Items().Clear();++ auto matches = [&](const DBModels::ConnectionConfig& conn) -> bool+ {+ if (searchQuery.empty()) return true;+ auto toLower = [](std::wstring s)+ {+ std::transform(s.begin(), s.end(), s.begin(), ::towlower);+ return s;+ };+ auto q = toLower(searchQuery);+ return toLower(conn.name).find(q) != std::wstring::npos+ || toLower(conn.host).find(q) != std::wstring::npos+ || toLower(conn.database).find(q) != std::wstring::npos;+ };++ // Collect all group names (from settings + connection memberships)+ auto s = DBModels::AppSettings::Load();+ std::vector<std::wstring> groupNames = s.connectionGroups;+ for (const auto& c : allConnections_)+ {+ if (c.group.empty()) continue;+ auto it = std::find(groupNames.begin(), groupNames.end(), c.group);+ if (it == groupNames.end()) groupNames.push_back(c.group);+ }++ // Render each group section+ for (const auto& groupName : groupNames)+ {+ // Count connections in this group that match search+ int count = 0;+ for (const auto& conn : allConnections_)+ if (conn.group == groupName && matches(conn)) count++;++ // Show group header even if empty (so user sees the group they created)+ AddGroupHeader(groupName, count);+ for (const auto& conn : allConnections_)+ if (conn.group == groupName && matches(conn))+ AddConnectionCard(conn);+ }++ // Ungrouped connections+ bool hasUngrouped = false;+ for (const auto& conn : allConnections_)+ if (conn.group.empty() && matches(conn)) { hasUngrouped = true; break; }++ if (hasUngrouped)+ {+ if (!groupNames.empty())+ {+ int ungroupedCount = 0;+ for (const auto& conn : allConnections_)+ if (conn.group.empty() && matches(conn)) ungroupedCount++;+ AddGroupHeader(L"Ungrouped", ungroupedCount);+ }+ for (const auto& conn : allConnections_)+ if (conn.group.empty() && matches(conn))+ AddConnectionCard(conn);+ }++ UpdateEmptyState();+ }++ // Add a non-clickable group header row to the ListView+ void HomePage::AddGroupHeader(const std::wstring& name, int count)+ {+ muxc::StackPanel header;+ header.Orientation(muxc::Orientation::Horizontal);+ header.Spacing(8.0);+ header.Padding(mux::ThicknessHelper::FromLengths(8, 12, 8, 4));++ muxc::TextBlock folderIcon;+ folderIcon.Text(L"\xE8B7");+ folderIcon.FontFamily(muxm::FontFamily(L"Segoe Fluent Icons,Segoe MDL2 Assets"));+ folderIcon.FontSize(12.0);+ folderIcon.Opacity(0.6);+ folderIcon.VerticalAlignment(mux::VerticalAlignment::Center);+ header.Children().Append(folderIcon);++ muxc::TextBlock nameText;+ nameText.Text(winrt::hstring(name));+ nameText.FontSize(12.0);+ nameText.FontWeight(winrt::Windows::UI::Text::FontWeights::SemiBold());+ nameText.Opacity(0.75);+ nameText.VerticalAlignment(mux::VerticalAlignment::Center);+ header.Children().Append(nameText);++ muxc::TextBlock countText;+ countText.Text(winrt::hstring(L"(" + std::to_wstring(count) + L")"));+ countText.FontSize(11.0);+ countText.Opacity(0.4);+ countText.VerticalAlignment(mux::VerticalAlignment::Center);+ header.Children().Append(countText);++ // No Tag set → ConnectionItem_Click ignores it+ ConnectionsListView().Items().Append(header);+ }++ void HomePage::UpdateEmptyState()+ {+ bool empty = (ConnectionsListView().Items().Size() == 0);+ EmptyState().Visibility(empty ? mux::Visibility::Visible : mux::Visibility::Collapsed);+ ConnectionsListView().Visibility(empty ? mux::Visibility::Collapsed : mux::Visibility::Visible);+ }++ void HomePage::NewConnection_Click(+ winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ ShowNewConnectionFlow();+ }++ void HomePage::ShowNewConnectionFlow()+ {+ muxc::ContentDialog typeDialog;+ typeDialog.Title(winrt::box_value(winrt::hstring(L"New Connection")));+ auto picker = winrt::make<DatabaseTypePickerDialog>();+ typeDialog.Content(picker);+ typeDialog.CloseButtonText(L"Cancel");+ typeDialog.XamlRoot(this->XamlRoot());++ auto pickerImpl = picker.as<DatabaseTypePickerDialog>();+ pickerImpl->OnTypeSelected = [this, typeDialog](DBModels::DatabaseType type) mutable+ {+ typeDialog.Hide();++ muxc::ContentDialog formDialog;+ formDialog.Title(winrt::box_value(winrt::hstring(+ DBModels::DatabaseTypeDisplayName(type) + L" Connection")));+ auto form = winrt::make<ConnectionFormDialog>();+ auto formImpl = form.as<ConnectionFormDialog>();+ formImpl->SetDatabaseType(type);+ formDialog.Content(form);+ formDialog.CloseButtonText(L"Cancel");+ formDialog.XamlRoot(this->XamlRoot());+ // Ensure dialog is wide enough for the form+ formDialog.Resources().Insert(+ winrt::box_value(L"ContentDialogMaxWidth"),+ winrt::box_value(800.0));+ formDialog.Resources().Insert(+ winrt::box_value(L"ContentDialogMinWidth"),+ winrt::box_value(720.0));++ // Wire Save callback — save config + password, persist to disk+ formImpl->OnSave = [this, formImpl, formDialog]() mutable+ {+ auto config = formImpl->GetConnectionConfig();+ config.password = formImpl->GetPassword();+ GUID guid;+ CoCreateGuid(&guid);+ wchar_t guidStr[40];+ StringFromGUID2(guid, guidStr, 40);+ config.id = guidStr;+ allConnections_.push_back(config);+ DBModels::ConnectionStore::Save(config);+ RefreshList();+ formDialog.Hide();+ };++ // Wire Test callback — validate credentials without saving+ formImpl->OnTest = [this, formImpl]()+ {+ auto config = formImpl->GetConnectionConfig();+ auto pwd = formImpl->GetPassword();+ TestConnectionAsync(config, pwd);+ };++ // Wire Connect callback — save + navigate to workspace+ formImpl->OnConnect = [this, formImpl, formDialog]() mutable+ {+ auto config = formImpl->GetConnectionConfig();+ config.password = formImpl->GetPassword();+ GUID guid;+ CoCreateGuid(&guid);+ wchar_t guidStr[40];+ StringFromGUID2(guid, guidStr, 40);+ config.id = guidStr;+ allConnections_.push_back(config);+ DBModels::ConnectionStore::Save(config);+ RefreshList();+ formDialog.Hide();++ // Test connection before navigating to workspace+ auto frame = this->Frame();+ if (frame)+ {+ try+ {+ DBModels::ConnectionManager mgr;+ if (!mgr.testConnection(config, config.password))+ {+ muxc::ContentDialog errDlg;+ errDlg.Title(winrt::box_value(winrt::hstring(L"Connection Failed")));+ errDlg.Content(winrt::box_value(winrt::hstring(+ L"Could not connect to " + config.name ++ L". Check host, port, credentials, and ensure the server is running.")));+ errDlg.CloseButtonText(L"OK");+ errDlg.XamlRoot(this->XamlRoot());+ errDlg.ShowAsync();+ return;+ }+ }+ catch (...) {}++ auto workspace = winrt::make<WorkspacePage>();+ workspace.as<WorkspacePage>()->SetConnection(config, config.password);+ frame.Content(workspace);+ }+ };++ formDialog.ShowAsync();+ };++ typeDialog.ShowAsync();+ }++ void HomePage::NewGroup_Click(+ winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ ShowNewGroupDialogAsync();+ }++ winrt::fire_and_forget HomePage::ShowNewGroupDialogAsync()+ {+ muxc::ContentDialog dialog;+ dialog.Title(winrt::box_value(winrt::hstring(L"New Group")));+ muxc::TextBox input;+ input.PlaceholderText(L"Group name");+ dialog.Content(input);+ dialog.PrimaryButtonText(L"Create");+ dialog.CloseButtonText(L"Cancel");+ dialog.DefaultButton(muxc::ContentDialogButton::Primary);+ dialog.XamlRoot(this->XamlRoot());++ auto result = co_await dialog.ShowAsync();+ if (result != muxc::ContentDialogResult::Primary) co_return;++ std::wstring name(input.Text());+ // Trim whitespace+ while (!name.empty() && (name.back() == L' ' || name.back() == L'\t'))+ name.pop_back();+ size_t start = name.find_first_not_of(L" \t");+ if (start != std::wstring::npos) name = name.substr(start);+ if (name.empty()) co_return;++ // Persist to AppSettings — avoid duplicates (case-insensitive)+ auto s = DBModels::AppSettings::Load();+ auto exists = std::any_of(s.connectionGroups.begin(), s.connectionGroups.end(),+ [&name](const std::wstring& g)+ {+ if (g.size() != name.size()) return false;+ for (size_t i = 0; i < g.size(); i++)+ if (towlower(g[i]) != towlower(name[i])) return false;+ return true;+ });+ if (!exists)+ {+ s.connectionGroups.push_back(name);+ s.Save();+ }++ RefreshList();+ }++ void HomePage::Settings_Click(+ winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ muxc::Frame frame{ nullptr };+ auto fe = this->try_as<mux::FrameworkElement>();+ while (fe)+ {+ if (auto f = fe.try_as<muxc::Frame>()) { frame = f; break; }+ fe = fe.Parent().try_as<mux::FrameworkElement>();+ }+ if (!frame) frame = this->Frame();+ if (!frame) return;++ // Remember this page so Settings' Back button returns here+ auto s = DBModels::AppSettings::Load();+ s.lastPageBeforeSettings = L"Gridex.HomePage";+ s.Save();++ winrt::Windows::UI::Xaml::Interop::TypeName pageType;+ pageType.Name = L"Gridex.SettingsPage";+ pageType.Kind = winrt::Windows::UI::Xaml::Interop::TypeKind::Metadata;+ frame.Navigate(pageType);+ }++ void HomePage::ConnectionItem_Click(+ winrt::Windows::Foundation::IInspectable const&, muxc::ItemClickEventArgs const& e)+ {+ if (!e.ClickedItem()) return;++ // ClickedItem returns the ConnectionCard UserControl+ // Read Tag to find connection id+ winrt::hstring connId;+ if (auto fe = e.ClickedItem().try_as<winrt::Microsoft::UI::Xaml::FrameworkElement>())+ {+ if (auto tag = fe.Tag())+ connId = winrt::unbox_value<winrt::hstring>(tag);+ }++ if (connId.empty()) return;++ // Find the connection config+ DBModels::ConnectionConfig selectedConn;+ bool found = false;+ for (const auto& conn : allConnections_)+ {+ if (conn.id == std::wstring(connId))+ {+ selectedConn = conn;+ found = true;+ break;+ }+ }+ if (!found) return;++ // Test connection BEFORE navigating to workspace. If the test+ // fails, show error on HomePage so the user doesn't land on a+ // blank workspace with an error dialog they have to dismiss.+ auto frame = this->Frame();+ if (!frame) return;++ try+ {+ DBModels::ConnectionManager mgr;+ if (!mgr.testConnection(selectedConn, selectedConn.password))+ {+ muxc::ContentDialog errDlg;+ errDlg.Title(winrt::box_value(winrt::hstring(L"Connection Failed")));+ errDlg.Content(winrt::box_value(winrt::hstring(+ L"Could not connect to " + selectedConn.name ++ L". Check host, port, credentials, and ensure the server is running.")));+ errDlg.CloseButtonText(L"OK");+ errDlg.XamlRoot(this->XamlRoot());+ errDlg.ShowAsync();+ return;+ }+ }+ catch (...) {}++ auto workspace = winrt::make<WorkspacePage>();+ workspace.as<WorkspacePage>()->SetConnection(selectedConn, selectedConn.password);+ frame.Content(workspace);+ }++ void HomePage::SearchBox_TextChanged(+ muxc::AutoSuggestBox const& sender, muxc::AutoSuggestBoxTextChangedEventArgs const&)+ {+ RefreshList(std::wstring(sender.Text()));+ }+}diff --git a/windows/Gridex/HomePage.h b/windows/Gridex/HomePage.hnew file mode 100644index 0000000..befa32f--- /dev/null+++ b/windows/Gridex/HomePage.h@@ -0,0 +1,49 @@+#pragma once++#include "Models/ConnectionConfig.h"+#include <vector>+#include "HomePage.g.h"++namespace winrt::Gridex::implementation+{+ struct HomePage : HomePageT<HomePage>+ {+ HomePage();++ void NewConnection_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);+ void NewGroup_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);+ winrt::fire_and_forget ShowNewGroupDialogAsync();+ void Settings_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);+ void ConnectionItem_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::Controls::ItemClickEventArgs const& e);+ void SearchBox_TextChanged(+ winrt::Microsoft::UI::Xaml::Controls::AutoSuggestBox const& sender,+ winrt::Microsoft::UI::Xaml::Controls::AutoSuggestBoxTextChangedEventArgs const& e);++ private:+ std::vector<DBModels::ConnectionConfig> allConnections_;+ void RefreshList(const std::wstring& searchQuery = L"");+ void UpdateEmptyState();+ void ShowNewConnectionFlow();+ void AddConnectionCard(const DBModels::ConnectionConfig& config);+ void AddGroupHeader(const std::wstring& name, int count);+ void DeleteConnection(const std::wstring& id);+ void EditConnection(const std::wstring& id);+ void TestConnectionAsync(+ const DBModels::ConnectionConfig& config, const std::wstring& password);+ };+}++namespace winrt::Gridex::factory_implementation+{+ struct HomePage : HomePageT<HomePage, implementation::HomePage>+ {+ };+}diff --git a/windows/Gridex/HomePage.idl b/windows/Gridex/HomePage.idlnew file mode 100644index 0000000..af4bf42--- /dev/null+++ b/windows/Gridex/HomePage.idl@@ -0,0 +1,8 @@+namespace Gridex+{+ [default_interface]+ runtimeclass HomePage : Microsoft.UI.Xaml.Controls.Page+ {+ HomePage();+ }+}diff --git a/windows/Gridex/HomePage.xaml b/windows/Gridex/HomePage.xamlnew file mode 100644index 0000000..70b3a57--- /dev/null+++ b/windows/Gridex/HomePage.xaml@@ -0,0 +1,174 @@+<Page+ x:Class="Gridex.HomePage"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ Background="Transparent">++ <Grid>+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="340" />+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="*" />+ </Grid.ColumnDefinitions>++ <!-- Left Sidebar -->+ <Grid Grid.Column="0" Padding="24">+ <Grid.RowDefinitions>+ <RowDefinition Height="*" />+ <RowDefinition Height="Auto" />+ </Grid.RowDefinitions>++ <!-- Branding (centered in available space) -->+ <StackPanel Grid.Row="0"+ VerticalAlignment="Center"+ HorizontalAlignment="Center"+ Spacing="8">+ <Image Source="ms-appx:///Assets/gridex-icon-source.png"+ Width="80" Height="80"+ HorizontalAlignment="Center" />+ <TextBlock Text="Gridex"+ FontSize="36"+ FontWeight="Light"+ HorizontalAlignment="Center"+ Foreground="{ThemeResource TextFillColorPrimaryBrush}" />+ <TextBlock Text="AI-Native Database IDE"+ FontSize="14"+ HorizontalAlignment="Center"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ </StackPanel>++ <!-- Bottom Actions (pinned to bottom like macOS) -->+ <StackPanel Grid.Row="1" Spacing="4">+ <Button HorizontalAlignment="Stretch"+ HorizontalContentAlignment="Left"+ Padding="8,8"+ Background="Transparent"+ BorderThickness="0"+ Click="NewConnection_Click">+ <StackPanel Orientation="Horizontal" Spacing="10">+ <FontIcon Glyph="" FontSize="14"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ <TextBlock Text="New Connection"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ </StackPanel>+ </Button>+ <Button HorizontalAlignment="Stretch"+ HorizontalContentAlignment="Left"+ Padding="8,8"+ Background="Transparent"+ BorderThickness="0"+ Click="NewGroup_Click">+ <StackPanel Orientation="Horizontal" Spacing="10">+ <FontIcon Glyph="" FontSize="14"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ <TextBlock Text="New Group"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ </StackPanel>+ </Button>+ <Button HorizontalAlignment="Stretch"+ HorizontalContentAlignment="Left"+ Padding="8,8"+ Background="Transparent"+ BorderThickness="0"+ Click="Settings_Click">+ <StackPanel Orientation="Horizontal" Spacing="10">+ <FontIcon Glyph="" FontSize="14"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ <TextBlock Text="Settings"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ </StackPanel>+ </Button>+ </StackPanel>+ </Grid>++ <!-- Divider -->+ <Border Grid.Column="1"+ Width="1"+ Background="{ThemeResource DividerStrokeColorDefaultBrush}" />++ <!-- Right Panel — Connections -->+ <Grid Grid.Column="2" Padding="24,24,24,24">+ <Grid.RowDefinitions>+ <RowDefinition Height="Auto" />+ <RowDefinition Height="*" />+ </Grid.RowDefinitions>++ <!-- Search Row: SearchBox + Action Buttons (like macOS) -->+ <Grid Grid.Row="0">+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="*" />+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="Auto" />+ </Grid.ColumnDefinitions>++ <AutoSuggestBox x:Name="SearchBox"+ Grid.Column="0"+ PlaceholderText="Search connections..."+ QueryIcon="Find"+ VerticalAlignment="Center"+ TextChanged="SearchBox_TextChanged" />++ <!-- + New Connection Button -->+ <Button Grid.Column="1"+ Margin="8,0,0,0"+ Width="36" Height="36"+ Padding="0"+ ToolTipService.ToolTip="New Connection"+ Click="NewConnection_Click">+ <FontIcon Glyph="" FontSize="14" />+ </Button>++ <!-- Group Button -->+ <Button Grid.Column="2"+ Margin="4,0,0,0"+ Width="36" Height="36"+ Padding="0"+ ToolTipService.ToolTip="New Group"+ Click="NewGroup_Click">+ <FontIcon Glyph="" FontSize="14" />+ </Button>+ </Grid>++ <!-- Connection List -->+ <ListView x:Name="ConnectionsListView"+ Grid.Row="1"+ Margin="0,16,0,0"+ IsItemClickEnabled="True"+ ItemClick="ConnectionItem_Click"+ SelectionMode="Single">+ <ListView.ItemContainerStyle>+ <Style TargetType="ListViewItem">+ <Setter Property="Padding" Value="0" />+ <Setter Property="Margin" Value="0,0,0,4" />+ <Setter Property="HorizontalContentAlignment" Value="Stretch" />+ </Style>+ </ListView.ItemContainerStyle>+ </ListView>++ <!-- Empty State -->+ <StackPanel x:Name="EmptyState"+ Grid.Row="1"+ VerticalAlignment="Center"+ HorizontalAlignment="Center"+ Spacing="8"+ Visibility="Collapsed">+ <FontIcon Glyph="" FontSize="48"+ Foreground="{ThemeResource TextFillColorTertiaryBrush}"+ HorizontalAlignment="Center" />+ <TextBlock Text="No connections yet"+ FontSize="16"+ HorizontalAlignment="Center"+ Foreground="{ThemeResource TextFillColorTertiaryBrush}" />+ <TextBlock Text="Create your first database connection to get started"+ FontSize="12"+ HorizontalAlignment="Center"+ Foreground="{ThemeResource TextFillColorDisabledBrush}" />+ <Button Content="Create Connection"+ Style="{StaticResource AccentButtonStyle}"+ HorizontalAlignment="Center"+ Margin="0,8,0,0"+ Click="NewConnection_Click" />+ </StackPanel>+ </Grid>+ </Grid>+</Page>diff --git a/windows/Gridex/ImportService.cpp b/windows/Gridex/ImportService.cppnew file mode 100644index 0000000..b1084f2--- /dev/null+++ b/windows/Gridex/ImportService.cpp@@ -0,0 +1,411 @@+#include <windows.h>+#include "Models/ImportService.h"+#include <fstream>+#include <sstream>+#include <algorithm>++namespace DBModels+{+ // ── Helpers ──────────────────────────────────────────++ static std::wstring utf8ToWide(const std::string& utf8)+ {+ if (utf8.empty()) return {};+ int sz = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(),+ static_cast<int>(utf8.size()), nullptr, 0);+ std::wstring result(sz, L'\0');+ MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(),+ static_cast<int>(utf8.size()), &result[0], sz);+ return result;+ }++ static std::wstring trimWs(const std::wstring& s)+ {+ size_t start = s.find_first_not_of(L" \t\r\n");+ if (start == std::wstring::npos) return {};+ size_t end = s.find_last_not_of(L" \t\r\n");+ return s.substr(start, end - start + 1);+ }++ // ── CSV Parser ──────────────────────────────────────++ // RFC 4180 compliant: handles quoted fields, embedded commas, newlines+ static std::vector<std::wstring> parseCsvLine(+ const std::wstring& content, size_t& pos)+ {+ std::vector<std::wstring> fields;+ std::wstring field;+ bool inQuote = false;++ while (pos < content.size())+ {+ wchar_t c = content[pos];++ if (inQuote)+ {+ if (c == L'"')+ {+ // Peek next char for escaped quote ""+ if (pos + 1 < content.size() && content[pos + 1] == L'"')+ {+ field += L'"';+ pos += 2;+ }+ else+ {+ inQuote = false;+ pos++;+ }+ }+ else+ {+ field += c;+ pos++;+ }+ }+ else+ {+ if (c == L'"')+ {+ inQuote = true;+ pos++;+ }+ else if (c == L',')+ {+ fields.push_back(field);+ field.clear();+ pos++;+ }+ else if (c == L'\n')+ {+ pos++;+ break; // End of line+ }+ else if (c == L'\r')+ {+ pos++;+ if (pos < content.size() && content[pos] == L'\n') pos++;+ break; // End of line+ }+ else+ {+ field += c;+ pos++;+ }+ }+ }++ // Last field on line+ fields.push_back(field);+ return fields;+ }++ ImportResult ImportService::ParseCsv(const std::wstring& content)+ {+ ImportResult result;+ if (content.empty())+ {+ result.error = L"File is empty";+ return result;+ }++ // Skip UTF-8 BOM if present+ size_t pos = 0;+ if (content.size() >= 1 && content[0] == 0xFEFF) pos = 1;++ // Parse header row+ result.columnNames = parseCsvLine(content, pos);+ if (result.columnNames.empty())+ {+ result.error = L"No header row found";+ return result;+ }++ // Trim column names+ for (auto& col : result.columnNames)+ col = trimWs(col);++ // Parse data rows+ while (pos < content.size())+ {+ // Skip blank lines+ if (content[pos] == L'\r' || content[pos] == L'\n')+ {+ pos++;+ continue;+ }++ auto fields = parseCsvLine(content, pos);++ // Skip if all fields empty+ bool allEmpty = true;+ for (auto& f : fields)+ if (!f.empty()) { allEmpty = false; break; }+ if (allEmpty) continue;++ TableRow row;+ for (size_t i = 0; i < result.columnNames.size() && i < fields.size(); i++)+ {+ std::wstring val = trimWs(fields[i]);+ // Map empty CSV cells AND the literal text "NULL" to SQL NULL.+ // (Importing CSV is one of the rare places where the literal+ // text "NULL" is conventionally treated as a null marker.)+ if (val.empty() || val == L"NULL")+ row[result.columnNames[i]] = nullValue();+ else+ row[result.columnNames[i]] = val;+ }+ result.rows.push_back(std::move(row));+ }++ result.totalParsed = static_cast<int>(result.rows.size());+ result.success = true;+ return result;+ }++ // ── JSON Parser ─────────────────────────────────────++ // Minimal JSON array-of-objects parser (no external deps)+ // Expects: [{"key":"val", ...}, ...]++ static std::wstring parseJsonString(const std::wstring& json, size_t& pos)+ {+ if (pos >= json.size() || json[pos] != L'"') return {};+ pos++; // skip opening quote+ std::wstring result;+ while (pos < json.size())+ {+ wchar_t c = json[pos];+ if (c == L'\\' && pos + 1 < json.size())+ {+ wchar_t next = json[pos + 1];+ if (next == L'"') { result += L'"'; pos += 2; }+ else if (next == L'\\') { result += L'\\'; pos += 2; }+ else if (next == L'n') { result += L'\n'; pos += 2; }+ else if (next == L't') { result += L'\t'; pos += 2; }+ else if (next == L'/') { result += L'/'; pos += 2; }+ else { result += c; pos++; }+ }+ else if (c == L'"')+ {+ pos++; // skip closing quote+ return result;+ }+ else+ {+ result += c;+ pos++;+ }+ }+ return result;+ }++ static void skipWhitespace(const std::wstring& json, size_t& pos)+ {+ while (pos < json.size() &&+ (json[pos] == L' ' || json[pos] == L'\t' ||+ json[pos] == L'\r' || json[pos] == L'\n'))+ pos++;+ }++ // Parse a JSON value (string, number, null, bool) → wstring cell content.+ // JSON null becomes the SQL NULL sentinel; everything else is the literal text.+ static std::wstring parseJsonValue(const std::wstring& json, size_t& pos)+ {+ skipWhitespace(json, pos);+ if (pos >= json.size()) return nullValue();++ wchar_t c = json[pos];+ if (c == L'"')+ return parseJsonString(json, pos);++ // null+ if (json.compare(pos, 4, L"null") == 0)+ {+ pos += 4;+ return nullValue();+ }+ // true/false+ if (json.compare(pos, 4, L"true") == 0)+ {+ pos += 4;+ return L"true";+ }+ if (json.compare(pos, 5, L"false") == 0)+ {+ pos += 5;+ return L"false";+ }+ // Number: read until delimiter+ std::wstring num;+ while (pos < json.size() &&+ json[pos] != L',' && json[pos] != L'}' &&+ json[pos] != L']' && json[pos] != L' ' &&+ json[pos] != L'\r' && json[pos] != L'\n')+ {+ num += json[pos++];+ }+ return num.empty() ? nullValue() : num;+ }++ ImportResult ImportService::ParseJson(const std::wstring& content)+ {+ ImportResult result;+ if (content.empty())+ {+ result.error = L"File is empty";+ return result;+ }++ size_t pos = 0;+ // Skip BOM+ if (content[0] == 0xFEFF) pos = 1;++ skipWhitespace(content, pos);+ if (pos >= content.size() || content[pos] != L'[')+ {+ result.error = L"Expected JSON array starting with '['";+ return result;+ }+ pos++; // skip '['++ // Collect unique column names in order+ std::vector<std::wstring> orderedCols;+ auto addCol = [&](const std::wstring& name) {+ for (auto& c : orderedCols)+ if (c == name) return;+ orderedCols.push_back(name);+ };++ // Parse objects+ while (pos < content.size())+ {+ skipWhitespace(content, pos);+ if (pos >= content.size() || content[pos] == L']') break;+ if (content[pos] == L',') { pos++; continue; }+ if (content[pos] != L'{')+ {+ result.error = L"Expected '{' at position " + std::to_wstring(pos);+ return result;+ }+ pos++; // skip '{'++ TableRow row;+ while (pos < content.size())+ {+ skipWhitespace(content, pos);+ if (pos >= content.size() || content[pos] == L'}') { pos++; break; }+ if (content[pos] == L',') { pos++; continue; }++ std::wstring key = parseJsonString(content, pos);+ skipWhitespace(content, pos);+ if (pos < content.size() && content[pos] == L':') pos++;++ std::wstring val = parseJsonValue(content, pos);+ row[key] = val;+ addCol(key);+ }+ result.rows.push_back(std::move(row));+ }++ result.columnNames = orderedCols;+ result.totalParsed = static_cast<int>(result.rows.size());+ result.success = true;+ return result;+ }++ // ── SQL Parser ──────────────────────────────────────++ ImportResult ImportService::ParseSql(const std::wstring& content)+ {+ ImportResult result;+ if (content.empty())+ {+ result.error = L"File is empty";+ return result;+ }++ // Split by semicolons, respecting single-quoted strings+ std::wstring stmt;+ bool inQuote = false;++ for (size_t i = 0; i < content.size(); i++)+ {+ wchar_t c = content[i];+ if (c == L'\'' && !inQuote)+ {+ inQuote = true;+ stmt += c;+ }+ else if (c == L'\'' && inQuote)+ {+ // Check escaped quote ''+ if (i + 1 < content.size() && content[i + 1] == L'\'')+ {+ stmt += L"''";+ i++;+ }+ else+ {+ inQuote = false;+ stmt += c;+ }+ }+ else if (c == L';' && !inQuote)+ {+ auto trimmed = trimWs(stmt);+ if (!trimmed.empty())+ result.sqlStatements.push_back(trimmed + L";");+ stmt.clear();+ }+ else+ {+ stmt += c;+ }+ }++ // Last statement without trailing semicolon+ auto trimmed = trimWs(stmt);+ if (!trimmed.empty())+ result.sqlStatements.push_back(trimmed + L";");++ result.totalParsed = static_cast<int>(result.sqlStatements.size());+ result.success = (result.totalParsed > 0);+ if (!result.success)+ result.error = L"No SQL statements found";+ return result;+ }++ // ── File I/O ────────────────────────────────────────++ std::wstring ImportService::ReadFileAsWstring(const std::wstring& filePath)+ {+ std::ifstream file(filePath, std::ios::binary);+ if (!file.is_open()) return {};++ std::string bytes(+ (std::istreambuf_iterator<char>(file)),+ std::istreambuf_iterator<char>());+ file.close();++ // Strip UTF-8 BOM+ if (bytes.size() >= 3 &&+ bytes[0] == '\xEF' && bytes[1] == '\xBB' && bytes[2] == '\xBF')+ bytes = bytes.substr(3);++ return utf8ToWide(bytes);+ }++ std::wstring ImportService::DetectFormat(const std::wstring& filename)+ {+ auto dotPos = filename.rfind(L'.');+ if (dotPos == std::wstring::npos) return L"";+ std::wstring ext = filename.substr(dotPos);+ // Lowercase+ for (auto& c : ext) c = towlower(c);+ if (ext == L".csv") return L"csv";+ if (ext == L".json") return L"json";+ if (ext == L".sql") return L"sql";+ return L"";+ }+}diff --git a/windows/Gridex/MSSQLAdapter.cpp b/windows/Gridex/MSSQLAdapter.cppnew file mode 100644index 0000000..e49377c--- /dev/null+++ b/windows/Gridex/MSSQLAdapter.cpp@@ -0,0 +1,748 @@+// MSSQLAdapter.cpp — SQL Server connection, query execution, schema+// inspection, CRUD, and transactions via Windows ODBC API.+//+// Zero external dependencies: uses sql.h / sqlext.h from Windows SDK+// and links against odbc32.lib (ships with every Windows install).++#include <windows.h>+#include <sql.h>+#include <sqlext.h>+#include "Models/MSSQLAdapter.h"++#include <algorithm>+#include <chrono>+#include <set>+#include <sstream>++namespace DBModels+{+ // ── UTF-8 helpers ─────────────────────────────────────────+ std::string MSSQLAdapter::toUtf8(const std::wstring& s)+ {+ if (s.empty()) return {};+ int sz = WideCharToMultiByte(CP_UTF8, 0, s.c_str(),+ static_cast<int>(s.size()), nullptr, 0, nullptr, nullptr);+ std::string out(sz, '\0');+ WideCharToMultiByte(CP_UTF8, 0, s.c_str(),+ static_cast<int>(s.size()), &out[0], sz, nullptr, nullptr);+ return out;+ }++ std::wstring MSSQLAdapter::fromUtf8(const std::string& s)+ {+ if (s.empty()) return {};+ int sz = MultiByteToWideChar(CP_UTF8, 0, s.c_str(),+ static_cast<int>(s.size()), nullptr, 0);+ std::wstring out(sz, L'\0');+ MultiByteToWideChar(CP_UTF8, 0, s.c_str(),+ static_cast<int>(s.size()), &out[0], sz);+ return out;+ }++ // SQL Server uses [bracket] quoting for identifiers+ std::string MSSQLAdapter::quoteIdentifier(const std::wstring& name)+ {+ auto utf8 = toUtf8(name);+ std::string escaped;+ escaped.reserve(utf8.size() + 2);+ escaped += '[';+ for (char c : utf8)+ {+ if (c == ']') escaped += "]]";+ else escaped += c;+ }+ escaped += ']';+ return escaped;+ }++ // SQL Server uses N'...' for Unicode string literals+ std::string MSSQLAdapter::quoteLiteral(const std::wstring& value)+ {+ auto utf8 = toUtf8(value);+ std::string escaped;+ escaped.reserve(utf8.size() + 3);+ escaped += "N'";+ for (char c : utf8)+ {+ if (c == '\'') escaped += "''";+ else escaped += c;+ }+ escaped += '\'';+ return escaped;+ }++ void MSSQLAdapter::ensureConnected() const+ {+ if (!connected_ || !hDbc_)+ throw DatabaseError(DatabaseError::Code::ConnectionFailed, "Not connected to SQL Server");+ }++ // Extract diagnostic message from an ODBC handle+ std::string MSSQLAdapter::odbcError(short handleType, void* handle)+ {+ SQLWCHAR state[6], msg[1024];+ SQLINTEGER nativeErr;+ SQLSMALLINT msgLen;+ if (SQLGetDiagRecW(handleType, handle, 1, state, &nativeErr,+ msg, 1024, &msgLen) == SQL_SUCCESS)+ {+ return toUtf8(std::wstring(msg, msgLen));+ }+ return "Unknown ODBC error";+ }++ // Try ODBC drivers in preference order+ std::string MSSQLAdapter::findDriver()+ {+ // Check available drivers via SQLDrivers+ SQLHENV env;+ if (SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env) != SQL_SUCCESS)+ return "{ODBC Driver 18 for SQL Server}"; // fallback guess++ SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0);++ const char* candidates[] = {+ "ODBC Driver 18 for SQL Server",+ "ODBC Driver 17 for SQL Server",+ "SQL Server"+ };++ SQLWCHAR driverDesc[256], driverAttr[256];+ SQLSMALLINT descLen, attrLen;+ SQLUSMALLINT dir = SQL_FETCH_FIRST;++ std::string found;+ while (SQLDriversW(env, dir, driverDesc, 256, &descLen,+ driverAttr, 256, &attrLen) == SQL_SUCCESS)+ {+ auto name = toUtf8(std::wstring(driverDesc, descLen));+ for (auto& c : candidates)+ {+ if (name == c && found.empty())+ {+ found = std::string("{") + c + "}";+ break;+ }+ }+ dir = SQL_FETCH_NEXT;+ }+ SQLFreeHandle(SQL_HANDLE_ENV, env);+ return found.empty() ? "{ODBC Driver 18 for SQL Server}" : found;+ }++ // ── Constructor / Destructor ───────────────────────────────+ MSSQLAdapter::MSSQLAdapter() = default;++ MSSQLAdapter::~MSSQLAdapter()+ {+ disconnect();+ }++ // ── Connection ────────────────────────────────────────────+ void MSSQLAdapter::connect(+ const ConnectionConfig& config, const std::wstring& password)+ {+ disconnect();++ auto driver = findDriver();+ auto host = toUtf8(config.host.empty() ? L"127.0.0.1" : config.host);+ auto db = toUtf8(config.database.empty() ? L"master" : config.database);+ auto user = toUtf8(config.username.empty() ? L"sa" : config.username);+ auto pass = toUtf8(password);++ // Build ODBC connection string+ std::ostringstream cs;+ cs << "DRIVER=" << driver << ";";+ cs << "SERVER=" << host << "," << (config.port > 0 ? config.port : 1433) << ";";+ cs << "DATABASE=" << db << ";";+ cs << "UID=" << user << ";";+ cs << "PWD=" << pass << ";";++ // SSL/Encryption.+ // The legacy "{SQL Server}" driver (shipped with Windows since+ // 2000) does NOT understand Encrypt= or TrustServerCertificate=+ // and throws "[DBNETLIB]SSL Security error" if we include them.+ // Only emit encryption flags for modern ODBC Driver 17/18+.+ bool isModernDriver = (driver.find("ODBC Driver") != std::string::npos);+ if (isModernDriver)+ {+ switch (config.sslMode)+ {+ case SSLMode::Disabled:+ cs << "Encrypt=no;";+ break;+ case SSLMode::Required:+ case SSLMode::VerifyCA:+ case SSLMode::VerifyIdentity:+ cs << "Encrypt=yes;TrustServerCertificate=no;";+ break;+ default: // Preferred+ cs << "Encrypt=yes;TrustServerCertificate=yes;";+ break;+ }+ }++ cs << "Connection Timeout=15;";++ auto connStr = cs.str();+ auto wConnStr = fromUtf8(connStr);++ // Allocate ODBC environment+ if (SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &hEnv_) != SQL_SUCCESS)+ throw DatabaseError(DatabaseError::Code::ConnectionFailed, "SQLAllocHandle(ENV) failed");+ SQLSetEnvAttr(hEnv_, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0);++ // Allocate connection+ if (SQLAllocHandle(SQL_HANDLE_DBC, hEnv_, &hDbc_) != SQL_SUCCESS)+ {+ SQLFreeHandle(SQL_HANDLE_ENV, hEnv_); hEnv_ = nullptr;+ throw DatabaseError(DatabaseError::Code::ConnectionFailed, "SQLAllocHandle(DBC) failed");+ }++ // Connect+ SQLWCHAR outStr[1024];+ SQLSMALLINT outLen;+ auto rc = SQLDriverConnectW(hDbc_, nullptr,+ (SQLWCHAR*)wConnStr.c_str(), SQL_NTS,+ outStr, 1024, &outLen, SQL_DRIVER_NOPROMPT);++ if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)+ {+ auto err = odbcError(SQL_HANDLE_DBC, hDbc_);+ SQLFreeHandle(SQL_HANDLE_DBC, hDbc_); hDbc_ = nullptr;+ SQLFreeHandle(SQL_HANDLE_ENV, hEnv_); hEnv_ = nullptr;+ throw DatabaseError(DatabaseError::Code::ConnectionFailed,+ "SQL Server connection failed: " + err);+ }++ connected_ = true;+ currentDb_ = db;+ }++ void MSSQLAdapter::disconnect()+ {+ if (hDbc_)+ {+ if (connected_) SQLDisconnect(hDbc_);+ SQLFreeHandle(SQL_HANDLE_DBC, hDbc_);+ hDbc_ = nullptr;+ }+ if (hEnv_)+ {+ SQLFreeHandle(SQL_HANDLE_ENV, hEnv_);+ hEnv_ = nullptr;+ }+ connected_ = false;+ currentDb_.clear();+ }++ bool MSSQLAdapter::testConnection(+ const ConnectionConfig& config, const std::wstring& password)+ {+ try+ {+ connect(config, password);+ auto r = executeInternal("SELECT 1");+ disconnect();+ return r.success;+ }+ catch (...) { disconnect(); return false; }+ }++ bool MSSQLAdapter::isConnected() const+ {+ return connected_ && hDbc_ != nullptr;+ }++ // ── Query Execution ───────────────────────────────────────+ QueryResult MSSQLAdapter::executeInternal(const std::string& sql)+ {+ ensureConnected();++ SQLHSTMT hStmt = nullptr;+ if (SQLAllocHandle(SQL_HANDLE_STMT, hDbc_, &hStmt) != SQL_SUCCESS)+ throw DatabaseError(DatabaseError::Code::QueryFailed, "SQLAllocHandle(STMT) failed");++ auto wSql = fromUtf8(sql);++ auto start = std::chrono::high_resolution_clock::now();+ auto rc = SQLExecDirectW(hStmt, (SQLWCHAR*)wSql.c_str(), SQL_NTS);+ auto end = std::chrono::high_resolution_clock::now();++ QueryResult result;+ result.sql = fromUtf8(sql);+ result.executionTimeMs =+ std::chrono::duration<double, std::milli>(end - start).count();++ if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO && rc != SQL_NO_DATA)+ {+ result.success = false;+ result.error = fromUtf8(odbcError(SQL_HANDLE_STMT, hStmt));+ SQLFreeHandle(SQL_HANDLE_STMT, hStmt);+ return result;+ }++ // Check if result set exists+ SQLSMALLINT nCols = 0;+ SQLNumResultCols(hStmt, &nCols);++ if (nCols > 0)+ {+ // SELECT-type query — fetch column names+ result.columnNames.reserve(nCols);+ result.columnTypes.reserve(nCols);+ for (SQLSMALLINT i = 1; i <= nCols; i++)+ {+ SQLWCHAR colName[256];+ SQLSMALLINT nameLen, dataType, decDigits, nullable;+ SQLULEN colSize;+ SQLDescribeColW(hStmt, i, colName, 256, &nameLen,+ &dataType, &colSize, &decDigits, &nullable);+ result.columnNames.push_back(std::wstring(colName, nameLen));+ result.columnTypes.push_back(std::to_wstring(dataType));+ }++ // Fetch rows+ while (SQLFetch(hStmt) == SQL_SUCCESS)+ {+ TableRow row;+ row.reserve(nCols);+ for (SQLSMALLINT i = 1; i <= nCols; i++)+ {+ SQLWCHAR buf[4096];+ SQLLEN indicator;+ auto fetchRc = SQLGetData(hStmt, i, SQL_C_WCHAR,+ buf, sizeof(buf), &indicator);++ const auto& colName = result.columnNames[i - 1];+ if (indicator == SQL_NULL_DATA)+ row.emplace(colName, nullValue());+ else if (fetchRc == SQL_SUCCESS || fetchRc == SQL_SUCCESS_WITH_INFO)+ row.emplace(colName, std::wstring(buf));+ else+ row.emplace(colName, L"");+ }+ result.rows.push_back(std::move(row));+ }+ result.totalRows = static_cast<int>(result.rows.size());+ result.success = true;+ }+ else+ {+ // DML: count affected rows+ SQLLEN rowCount = 0;+ SQLRowCount(hStmt, &rowCount);+ result.totalRows = static_cast<int>(rowCount);+ result.success = true;+ }++ SQLFreeHandle(SQL_HANDLE_STMT, hStmt);+ return result;+ }++ QueryResult MSSQLAdapter::execute(const std::wstring& sql)+ {+ return executeInternal(toUtf8(sql));+ }++ QueryResult MSSQLAdapter::fetchRows(+ const std::wstring& table, const std::wstring& schema,+ int limit, int offset,+ const std::wstring& orderBy, bool ascending)+ {+ auto sch = schema.empty() ? L"dbo" : schema;+ std::string sql = "SELECT * FROM " ++ quoteIdentifier(sch) + "." + quoteIdentifier(table);++ // OFFSET/FETCH requires ORDER BY in SQL Server+ if (!orderBy.empty())+ sql += " ORDER BY " + quoteIdentifier(orderBy) + (ascending ? " ASC" : " DESC");+ else+ sql += " ORDER BY (SELECT NULL)";++ sql += " OFFSET " + std::to_string(offset) + " ROWS";+ sql += " FETCH NEXT " + std::to_string(limit) + " ROWS ONLY";++ auto result = executeInternal(sql);++ // Get total row count for pagination+ std::string countSql = "SELECT COUNT(*) FROM " ++ quoteIdentifier(sch) + "." + quoteIdentifier(table);+ auto countResult = executeInternal(countSql);+ if (countResult.success && !countResult.rows.empty())+ {+ auto& firstRow = countResult.rows[0];+ if (!firstRow.empty())+ result.totalRows = std::stoi(toUtf8(firstRow.begin()->second));+ }++ result.currentPage = (limit > 0) ? (offset / limit) + 1 : 1;+ result.pageSize = limit;+ return result;+ }++ // ── Schema Inspection ─────────────────────────────────────+ std::vector<std::wstring> MSSQLAdapter::listDatabases()+ {+ auto result = executeInternal(+ "SELECT name FROM sys.databases "+ "WHERE name NOT IN ('master','tempdb','model','msdb') "+ "ORDER BY name");+ std::vector<std::wstring> dbs;+ for (auto& row : result.rows)+ {+ auto it = row.find(L"name");+ if (it != row.end()) dbs.push_back(it->second);+ }+ return dbs;+ }++ std::vector<std::wstring> MSSQLAdapter::listSchemas()+ {+ auto result = executeInternal(+ "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA "+ "WHERE SCHEMA_NAME NOT IN ("+ "'sys','INFORMATION_SCHEMA','guest','db_owner','db_accessadmin',"+ "'db_securityadmin','db_ddladmin','db_backupoperator',"+ "'db_datareader','db_datawriter','db_denydatareader','db_denydatawriter'"+ ") ORDER BY SCHEMA_NAME");+ std::vector<std::wstring> schemas;+ for (auto& row : result.rows)+ {+ auto it = row.find(L"SCHEMA_NAME");+ if (it != row.end()) schemas.push_back(it->second);+ }+ return schemas;+ }++ std::vector<TableInfo> MSSQLAdapter::listTables(const std::wstring& schema)+ {+ auto sch = schema.empty() ? "dbo" : toUtf8(schema);+ auto result = executeInternal(+ "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES "+ "WHERE TABLE_SCHEMA = '" + sch + "' AND TABLE_TYPE = 'BASE TABLE' "+ "ORDER BY TABLE_NAME");+ std::vector<TableInfo> tables;+ for (auto& row : result.rows)+ {+ TableInfo t;+ auto it = row.find(L"TABLE_NAME");+ if (it != row.end()) t.name = it->second;+ t.type = L"table";+ tables.push_back(t);+ }+ return tables;+ }++ std::vector<TableInfo> MSSQLAdapter::listViews(const std::wstring& schema)+ {+ auto sch = schema.empty() ? "dbo" : toUtf8(schema);+ auto result = executeInternal(+ "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS "+ "WHERE TABLE_SCHEMA = '" + sch + "' "+ "ORDER BY TABLE_NAME");+ std::vector<TableInfo> views;+ for (auto& row : result.rows)+ {+ TableInfo t;+ auto it = row.find(L"TABLE_NAME");+ if (it != row.end()) t.name = it->second;+ t.type = L"view";+ views.push_back(t);+ }+ return views;+ }++ std::vector<ColumnInfo> MSSQLAdapter::describeTable(+ const std::wstring& table, const std::wstring& schema)+ {+ auto sch = schema.empty() ? "dbo" : toUtf8(schema);+ auto tbl = toUtf8(table);++ // Column metadata+ auto result = executeInternal(+ "SELECT c.COLUMN_NAME, c.DATA_TYPE, c.IS_NULLABLE, "+ "c.COLUMN_DEFAULT, c.CHARACTER_MAXIMUM_LENGTH, c.ORDINAL_POSITION, "+ "COLUMNPROPERTY(OBJECT_ID('" + sch + "." + tbl + "'), c.COLUMN_NAME, 'IsIdentity') AS is_identity "+ "FROM INFORMATION_SCHEMA.COLUMNS c "+ "WHERE c.TABLE_SCHEMA = '" + sch + "' AND c.TABLE_NAME = '" + tbl + "' "+ "ORDER BY c.ORDINAL_POSITION");++ // Primary key columns+ auto pkResult = executeInternal(+ "SELECT ku.COLUMN_NAME "+ "FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc "+ "JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE ku "+ " ON tc.CONSTRAINT_NAME = ku.CONSTRAINT_NAME "+ "WHERE tc.TABLE_SCHEMA = '" + sch + "' "+ " AND tc.TABLE_NAME = '" + tbl + "' "+ " AND tc.CONSTRAINT_TYPE = 'PRIMARY KEY'");++ std::set<std::wstring> pkCols;+ for (auto& row : pkResult.rows)+ {+ auto it = row.find(L"COLUMN_NAME");+ if (it != row.end()) pkCols.insert(it->second);+ }++ std::vector<ColumnInfo> cols;+ for (auto& row : result.rows)+ {+ ColumnInfo col;+ auto nameIt = row.find(L"COLUMN_NAME");+ if (nameIt != row.end()) col.name = nameIt->second;++ auto typeIt = row.find(L"DATA_TYPE");+ if (typeIt != row.end()) col.dataType = typeIt->second;++ // Append length for char types+ auto lenIt = row.find(L"CHARACTER_MAXIMUM_LENGTH");+ if (lenIt != row.end() && !isNullCell(lenIt->second) && !lenIt->second.empty())+ {+ if (lenIt->second == L"-1")+ col.dataType += L"(MAX)";+ else+ col.dataType += L"(" + lenIt->second + L")";+ }++ auto nullIt = row.find(L"IS_NULLABLE");+ col.nullable = (nullIt != row.end() && nullIt->second == L"YES");++ auto defIt = row.find(L"COLUMN_DEFAULT");+ if (defIt != row.end() && !isNullCell(defIt->second))+ col.defaultValue = defIt->second;++ col.isPrimaryKey = pkCols.count(col.name) > 0;++ auto identIt = row.find(L"is_identity");+ if (identIt != row.end() && identIt->second == L"1")+ col.comment = L"IDENTITY";++ auto ordIt = row.find(L"ORDINAL_POSITION");+ if (ordIt != row.end())+ try { col.ordinalPosition = std::stoi(toUtf8(ordIt->second)); } catch (...) {}++ cols.push_back(col);+ }+ return cols;+ }++ std::vector<IndexInfo> MSSQLAdapter::listIndexes(+ const std::wstring& table, const std::wstring& schema)+ {+ // Stub — can be enhanced with sys.indexes + sys.index_columns+ return {};+ }++ std::vector<ForeignKeyInfo> MSSQLAdapter::listForeignKeys(+ const std::wstring& table, const std::wstring& schema)+ {+ auto sch = schema.empty() ? "dbo" : toUtf8(schema);+ auto tbl = toUtf8(table);++ auto result = executeInternal(+ "SELECT "+ " fk.CONSTRAINT_NAME, "+ " cu.COLUMN_NAME, "+ " pk.TABLE_SCHEMA AS ref_schema, "+ " pk.TABLE_NAME AS ref_table, "+ " pt.COLUMN_NAME AS ref_column "+ "FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS fk "+ "JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE cu "+ " ON fk.CONSTRAINT_NAME = cu.CONSTRAINT_NAME "+ "JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk "+ " ON fk.UNIQUE_CONSTRAINT_NAME = pk.CONSTRAINT_NAME "+ "JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE pt "+ " ON pk.CONSTRAINT_NAME = pt.CONSTRAINT_NAME "+ "WHERE cu.TABLE_SCHEMA = '" + sch + "' "+ " AND cu.TABLE_NAME = '" + tbl + "'");++ std::vector<ForeignKeyInfo> fks;+ for (auto& row : result.rows)+ {+ ForeignKeyInfo fk;+ auto it = row.find(L"CONSTRAINT_NAME");+ if (it != row.end()) fk.name = it->second;+ it = row.find(L"COLUMN_NAME");+ if (it != row.end()) fk.column = it->second;+ it = row.find(L"ref_table");+ if (it != row.end()) fk.referencedTable = it->second;+ it = row.find(L"ref_column");+ if (it != row.end()) fk.referencedColumn = it->second;+ fks.push_back(fk);+ }+ return fks;+ }++ std::vector<std::wstring> MSSQLAdapter::listFunctions(const std::wstring& schema)+ {+ auto sch = schema.empty() ? "dbo" : toUtf8(schema);+ // Return BOTH functions and stored procedures — sidebar shows+ // them under "Functions" group. The ROUTINE_TYPE prefix lets+ // users tell them apart at a glance.+ auto result = executeInternal(+ "SELECT ROUTINE_NAME, ROUTINE_TYPE FROM INFORMATION_SCHEMA.ROUTINES "+ "WHERE ROUTINE_SCHEMA = '" + sch + "' "+ "ORDER BY ROUTINE_TYPE, ROUTINE_NAME");+ std::vector<std::wstring> funcs;+ for (auto& row : result.rows)+ {+ auto nameIt = row.find(L"ROUTINE_NAME");+ auto typeIt = row.find(L"ROUTINE_TYPE");+ if (nameIt == row.end()) continue;+ // Prefix with [SP] or [FN] so user can distinguish+ std::wstring prefix;+ if (typeIt != row.end() && typeIt->second == L"PROCEDURE")+ prefix = L"[SP] ";+ else if (typeIt != row.end() && typeIt->second == L"FUNCTION")+ prefix = L"[FN] ";+ funcs.push_back(prefix + nameIt->second);+ }+ return funcs;+ }++ std::wstring MSSQLAdapter::getFunctionSource(+ const std::wstring& name, const std::wstring& schema)+ {+ auto sch = schema.empty() ? "dbo" : toUtf8(schema);+ auto result = executeInternal(+ "SELECT ROUTINE_DEFINITION FROM INFORMATION_SCHEMA.ROUTINES "+ "WHERE ROUTINE_SCHEMA = '" + sch + "' "+ " AND ROUTINE_NAME = '" + toUtf8(name) + "'");+ if (!result.rows.empty())+ {+ auto it = result.rows[0].find(L"ROUTINE_DEFINITION");+ if (it != result.rows[0].end()) return it->second;+ }+ return {};+ }++ std::wstring MSSQLAdapter::getCreateTableSQL(+ const std::wstring& table, const std::wstring& schema)+ {+ // Best-effort reconstruct from column metadata+ auto cols = describeTable(table, schema);+ if (cols.empty()) return {};++ auto sch = schema.empty() ? L"dbo" : schema;+ std::wstring sql = L"CREATE TABLE [" + sch + L"].[" + table + L"] (\n";+ for (size_t i = 0; i < cols.size(); i++)+ {+ auto& c = cols[i];+ sql += L" [" + c.name + L"] " + c.dataType;+ if (c.comment == L"IDENTITY") sql += L" IDENTITY(1,1)";+ if (!c.nullable) sql += L" NOT NULL";+ if (!c.defaultValue.empty()) sql += L" DEFAULT " + c.defaultValue;+ if (i + 1 < cols.size()) sql += L",";+ sql += L"\n";+ }+ sql += L")";+ return sql;+ }++ // ── Data Manipulation ─────────────────────────────────────+ QueryResult MSSQLAdapter::insertRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& values)+ {+ auto sch = schema.empty() ? L"dbo" : schema;+ std::string sql = "INSERT INTO " ++ quoteIdentifier(sch) + "." + quoteIdentifier(table) + " (";+ std::string vals = "VALUES (";+ bool first = true;+ for (auto& [col, val] : values)+ {+ if (isNullCell(val)) continue;+ if (!first) { sql += ", "; vals += ", "; }+ sql += quoteIdentifier(col);+ vals += quoteLiteral(val);+ first = false;+ }+ sql += ") " + vals + ")";+ return executeInternal(sql);+ }++ QueryResult MSSQLAdapter::updateRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& setValues, const TableRow& whereValues)+ {+ auto sch = schema.empty() ? L"dbo" : schema;+ std::string sql = "UPDATE " ++ quoteIdentifier(sch) + "." + quoteIdentifier(table) + " SET ";+ bool first = true;+ for (auto& [col, val] : setValues)+ {+ if (!first) sql += ", ";+ sql += quoteIdentifier(col) + " = ";+ sql += isNullCell(val) ? "NULL" : quoteLiteral(val);+ first = false;+ }+ sql += " WHERE ";+ first = true;+ for (auto& [col, val] : whereValues)+ {+ if (!first) sql += " AND ";+ sql += quoteIdentifier(col) + " = " + quoteLiteral(val);+ first = false;+ }+ return executeInternal(sql);+ }++ QueryResult MSSQLAdapter::deleteRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& whereValues)+ {+ auto sch = schema.empty() ? L"dbo" : schema;+ std::string sql = "DELETE FROM " ++ quoteIdentifier(sch) + "." + quoteIdentifier(table) + " WHERE ";+ bool first = true;+ for (auto& [col, val] : whereValues)+ {+ if (!first) sql += " AND ";+ sql += quoteIdentifier(col) + " = " + quoteLiteral(val);+ first = false;+ }+ return executeInternal(sql);+ }++ // ── Transactions ──────────────────────────────────────────+ void MSSQLAdapter::beginTransaction()+ {+ ensureConnected();+ executeInternal("BEGIN TRANSACTION");+ }++ void MSSQLAdapter::commitTransaction()+ {+ ensureConnected();+ executeInternal("COMMIT");+ }++ void MSSQLAdapter::rollbackTransaction()+ {+ ensureConnected();+ executeInternal("ROLLBACK");+ }++ // ── Server Info ───────────────────────────────────────────+ std::wstring MSSQLAdapter::serverVersion()+ {+ try+ {+ auto result = executeInternal(+ "SELECT SERVERPROPERTY('ProductVersion') AS ver");+ if (!result.rows.empty())+ {+ auto it = result.rows[0].find(L"ver");+ if (it != result.rows[0].end()) return it->second;+ }+ }+ catch (...) {}+ return L"Unknown";+ }++ std::wstring MSSQLAdapter::currentDatabase()+ {+ return fromUtf8(currentDb_);+ }+}diff --git a/windows/Gridex/MainWindow.idl b/windows/Gridex/MainWindow.idlnew file mode 100644index 0000000..6908929--- /dev/null+++ b/windows/Gridex/MainWindow.idl@@ -0,0 +1,8 @@+namespace Gridex+{+ [default_interface]+ runtimeclass MainWindow : Microsoft.UI.Xaml.Window+ {+ MainWindow();+ }+}diff --git a/windows/Gridex/MainWindow.xaml b/windows/Gridex/MainWindow.xamlnew file mode 100644index 0000000..59fddf9--- /dev/null+++ b/windows/Gridex/MainWindow.xaml@@ -0,0 +1,16 @@+<?xml version="1.0" encoding="utf-8"?>+<Window+ x:Class="Gridex.MainWindow"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:local="using:Gridex"+ Title="Gridex">++ <Window.SystemBackdrop>+ <MicaBackdrop />+ </Window.SystemBackdrop>++ <Grid Background="Transparent">+ <Frame x:Name="ContentFrame" />+ </Grid>+</Window>diff --git a/windows/Gridex/MainWindow.xaml.cpp b/windows/Gridex/MainWindow.xaml.cppnew file mode 100644index 0000000..4247cc7--- /dev/null+++ b/windows/Gridex/MainWindow.xaml.cpp@@ -0,0 +1,125 @@+#include "pch.h"+#include "xaml-includes.h"+#include <winrt/Microsoft.UI.Windowing.h>+#include <winrt/Microsoft.UI.Xaml.Interop.h>+#include <winrt/Microsoft.UI.Interop.h>+#include <winrt/Windows.System.h>+#include "MainWindow.xaml.h"+#if __has_include("MainWindow.g.cpp")+#include "MainWindow.g.cpp"+#endif++#include "HomePage.h"+#include "WorkspacePage.h"+#include "Models/AppSettings.h"++namespace winrt::Gridex::implementation+{+ namespace mux = winrt::Microsoft::UI::Xaml;++ MainWindow::MainWindow()+ {+ this->Activated([this](auto const&, auto const&)+ {+ static bool initialized = false;+ if (initialized) return;+ initialized = true;++ auto appWindow = this->AppWindow();+ appWindow.Resize(winrt::Windows::Graphics::SizeInt32{ 1280, 800 });++ // Title-bar icon. Gridex.rc embeds the phoenix .ico as+ // resource ID 1 inside Gridex.exe; WinUI 3 does not pick+ // that up for the AppWindow title bar automatically, so we+ // load the HICON from our own module and hand it back to+ // WinUI via the Win32 interop IconId bridge.+ if (HICON hIcon = ::LoadIconW(::GetModuleHandleW(nullptr),+ MAKEINTRESOURCEW(1)))+ {+ try+ {+ auto iconId = winrt::Microsoft::UI::GetIconIdFromIcon(hIcon);+ appWindow.SetIcon(iconId);+ }+ catch (...) { /* best effort -- ignore failure */ }+ }++ if (auto content = this->Content().try_as<mux::FrameworkElement>())+ {+ content.RequestedTheme(mux::ElementTheme::Dark);++ // Wire keyboard shortcuts in code-behind (no XAML accelerators = no tooltip leak)+ auto settingsAccel = mux::Input::KeyboardAccelerator();+ settingsAccel.Key(winrt::Windows::System::VirtualKey::P);+ settingsAccel.Modifiers(static_cast<winrt::Windows::System::VirtualKeyModifiers>(+ static_cast<uint32_t>(winrt::Windows::System::VirtualKeyModifiers::Control) |+ static_cast<uint32_t>(winrt::Windows::System::VirtualKeyModifiers::Shift)));+ settingsAccel.Invoked([this](auto&&, mux::Input::KeyboardAcceleratorInvokedEventArgs const& args)+ {+ // Remember current page for Back button+ auto s = DBModels::AppSettings::Load();+ auto currentContent = ContentFrame().Content();+ if (currentContent.try_as<winrt::Gridex::WorkspacePage>())+ s.lastPageBeforeSettings = L"Gridex.WorkspacePage";+ else if (currentContent.try_as<winrt::Gridex::HomePage>())+ s.lastPageBeforeSettings = L"Gridex.HomePage";+ s.Save();++ NavigateTo(L"Gridex.SettingsPage");+ args.Handled(true);+ });+ content.KeyboardAccelerators().Append(settingsAccel);++ auto homeAccel = mux::Input::KeyboardAccelerator();+ homeAccel.Key(winrt::Windows::System::VirtualKey::H);+ homeAccel.Modifiers(winrt::Windows::System::VirtualKeyModifiers::Control);+ homeAccel.Invoked([this](auto&&, mux::Input::KeyboardAcceleratorInvokedEventArgs const& args)+ {+ NavigateTo(L"Gridex.HomePage");+ args.Handled(true);+ });+ content.KeyboardAccelerators().Append(homeAccel);+ }++ NavigateTo(L"Gridex.HomePage");+ });+ }++ void MainWindow::NavigateTo(const wchar_t* pageTypeName)+ {+ winrt::Windows::UI::Xaml::Interop::TypeName pageType;+ pageType.Name = pageTypeName;+ pageType.Kind = winrt::Windows::UI::Xaml::Interop::TypeKind::Metadata;+ ContentFrame().Navigate(pageType);+ }++ void MainWindow::SettingsAccelerator_Invoked(+ mux::Input::KeyboardAccelerator const&,+ mux::Input::KeyboardAcceleratorInvokedEventArgs const& args)+ {+ NavigateTo(L"Gridex.SettingsPage");+ args.Handled(true);+ }++ void MainWindow::NewQueryAccelerator_Invoked(+ mux::Input::KeyboardAccelerator const&,+ mux::Input::KeyboardAcceleratorInvokedEventArgs const& args)+ {+ args.Handled(true);+ }++ void MainWindow::CloseTabAccelerator_Invoked(+ mux::Input::KeyboardAccelerator const&,+ mux::Input::KeyboardAcceleratorInvokedEventArgs const& args)+ {+ args.Handled(true);+ }++ void MainWindow::HomeAccelerator_Invoked(+ mux::Input::KeyboardAccelerator const&,+ mux::Input::KeyboardAcceleratorInvokedEventArgs const& args)+ {+ NavigateTo(L"Gridex.HomePage");+ args.Handled(true);+ }+}diff --git a/windows/Gridex/MainWindow.xaml.h b/windows/Gridex/MainWindow.xaml.hnew file mode 100644index 0000000..0144689--- /dev/null+++ b/windows/Gridex/MainWindow.xaml.h@@ -0,0 +1,34 @@+#pragma once++#include "MainWindow.g.h"++namespace winrt::Gridex::implementation+{+ struct MainWindow : MainWindowT<MainWindow>+ {+ MainWindow();++ void SettingsAccelerator_Invoked(+ winrt::Microsoft::UI::Xaml::Input::KeyboardAccelerator const& sender,+ winrt::Microsoft::UI::Xaml::Input::KeyboardAcceleratorInvokedEventArgs const& args);+ void NewQueryAccelerator_Invoked(+ winrt::Microsoft::UI::Xaml::Input::KeyboardAccelerator const& sender,+ winrt::Microsoft::UI::Xaml::Input::KeyboardAcceleratorInvokedEventArgs const& args);+ void CloseTabAccelerator_Invoked(+ winrt::Microsoft::UI::Xaml::Input::KeyboardAccelerator const& sender,+ winrt::Microsoft::UI::Xaml::Input::KeyboardAcceleratorInvokedEventArgs const& args);+ void HomeAccelerator_Invoked(+ winrt::Microsoft::UI::Xaml::Input::KeyboardAccelerator const& sender,+ winrt::Microsoft::UI::Xaml::Input::KeyboardAcceleratorInvokedEventArgs const& args);++ private:+ void NavigateTo(const wchar_t* pageTypeName);+ };+}++namespace winrt::Gridex::factory_implementation+{+ struct MainWindow : MainWindowT<MainWindow, implementation::MainWindow>+ {+ };+}diff --git a/windows/Gridex/Models/AiService.h b/windows/Gridex/Models/AiService.hnew file mode 100644index 0000000..0242691--- /dev/null+++ b/windows/Gridex/Models/AiService.h@@ -0,0 +1,77 @@+#pragma once+#include <string>+#include <vector>+#include <functional>+#include <map>++namespace DBModels+{+ // Index order is persisted in settings (aiProviderIndex) and bound to+ // the SettingsPage ComboBox. NEVER reorder existing entries — only+ // append new providers at the end.+ enum class AiProvider+ {+ Anthropic = 0,+ OpenAI = 1,+ Ollama = 2,+ Gemini = 3,+ OpenRouter = 4,+ };++ struct AiConfig+ {+ AiProvider provider = AiProvider::Anthropic;+ std::wstring apiKey;+ std::wstring model; // e.g. "claude-sonnet-4-20250514", "gpt-4o", "llama3", "gemini-2.0-flash"+ std::wstring ollamaEndpoint; // e.g. "http://localhost:11434"+ };++ struct ChatMessage+ {+ std::wstring role; // "user", "assistant", "system"+ std::wstring content;+ };++ // AI service for text-to-SQL and chat interactions+ class AiService+ {+ public:+ void SetConfig(const AiConfig& config) { config_ = config; }+ const AiConfig& GetConfig() const { return config_; }++ // Send chat completion request (blocking)+ // Returns assistant response+ std::wstring SendChat(+ const std::vector<ChatMessage>& messages,+ const std::wstring& systemPrompt = L"");++ // Convenience: text-to-SQL with schema context+ std::wstring TextToSql(+ const std::wstring& naturalLanguage,+ const std::wstring& schemaDescription);++ private:+ AiConfig config_;++ // Provider-specific HTTP calls+ std::wstring CallAnthropic(+ const std::vector<ChatMessage>& messages,+ const std::wstring& systemPrompt);+ std::wstring CallOpenAI(+ const std::vector<ChatMessage>& messages,+ const std::wstring& systemPrompt);+ std::wstring CallOllama(+ const std::vector<ChatMessage>& messages,+ const std::wstring& systemPrompt);+ std::wstring CallGemini(+ const std::vector<ChatMessage>& messages,+ const std::wstring& systemPrompt);+ std::wstring CallOpenRouter(+ const std::vector<ChatMessage>& messages,+ const std::wstring& systemPrompt);++ // UTF-8 helpers+ static std::string toUtf8(const std::wstring& wstr);+ static std::wstring fromUtf8(const std::string& str);+ };+}diff --git a/windows/Gridex/Models/AppSettings.h b/windows/Gridex/Models/AppSettings.hnew file mode 100644index 0000000..402da1d--- /dev/null+++ b/windows/Gridex/Models/AppSettings.h@@ -0,0 +1,38 @@+#pragma once+#include <string>+#include <vector>++namespace DBModels+{+ // Persisted app settings — JSON file in %LOCALAPPDATA%\Gridex\settings.json+ struct AppSettings+ {+ // Appearance+ int themeIndex = 0; // 0=System, 1=Light, 2=Dark++ // AI+ int aiProviderIndex = 0; // 0=Anthropic, 1=OpenAI, 2=Ollama+ std::wstring aiApiKey;+ std::wstring aiModel;+ std::wstring ollamaEndpoint;++ // Editor+ int editorFontSize = 13;+ int rowLimit = 100;++ // Navigation state (for back button)+ std::wstring lastPageBeforeSettings; // e.g. "Gridex.WorkspacePage"++ // Connection groups (user-defined labels)+ std::vector<std::wstring> connectionGroups;++ // Load from file (returns default if file missing)+ static AppSettings Load();++ // Save to file+ bool Save() const;++ private:+ static std::wstring GetSettingsPath();+ };+}diff --git a/windows/Gridex/Models/ChangeTracker.h b/windows/Gridex/Models/ChangeTracker.hnew file mode 100644index 0000000..a791499--- /dev/null+++ b/windows/Gridex/Models/ChangeTracker.h@@ -0,0 +1,237 @@+#pragma once+#include <string>+#include <vector>+#include <set>+#include <algorithm>+#include "TableRow.h"+#include "DatabaseType.h"++namespace DBModels+{+ enum class EditType { Insert, Update, Delete };++ struct PendingEdit+ {+ EditType type;+ int rowIndex = -1; // -1 for inserts (new rows)+ std::wstring column; // for Update only+ std::wstring oldValue; // for Update only+ std::wstring newValue; // for Update only+ TableRow primaryKey; // WHERE clause for update/delete+ TableRow insertValues; // full row for inserts+ };++ // Tracks pending INSERT/UPDATE/DELETE changes before commit+ class ChangeTracker+ {+ public:+ void trackInsert(const TableRow& values, int rowIndex = -1)+ {+ PendingEdit edit;+ edit.type = EditType::Insert;+ edit.rowIndex = rowIndex;+ edit.insertValues = values;+ edits_.push_back(edit);+ }++ void trackUpdate(int rowIndex, const std::wstring& column,+ const std::wstring& oldValue, const std::wstring& newValue,+ const TableRow& primaryKey)+ {+ // If reverting to original, skip+ if (oldValue == newValue) return;++ // If this row is a pending INSERT, update the insert values directly+ // (no separate UPDATE needed — just modify the INSERT data)+ for (auto& e : edits_)+ {+ if (e.type == EditType::Insert && e.rowIndex == rowIndex)+ {+ if (!isNullCell(newValue) && !newValue.empty())+ e.insertValues[column] = newValue;+ else+ e.insertValues.erase(column); // NULL = omit from INSERT+ return;+ }+ }++ // Merge: overwrite existing UPDATE for same row+column+ for (auto& e : edits_)+ {+ if (e.type == EditType::Update && e.rowIndex == rowIndex && e.column == column)+ {+ if (newValue == e.oldValue)+ {+ // Reverted to original — remove edit+ edits_.erase(std::remove_if(edits_.begin(), edits_.end(),+ [&](const PendingEdit& x) { return &x == &e; }), edits_.end());+ }+ else+ {+ e.newValue = newValue;+ }+ return;+ }+ }++ PendingEdit edit;+ edit.type = EditType::Update;+ edit.rowIndex = rowIndex;+ edit.column = column;+ edit.oldValue = oldValue;+ edit.newValue = newValue;+ edit.primaryKey = primaryKey;+ edits_.push_back(edit);+ }++ void trackDelete(int rowIndex, const TableRow& primaryKey)+ {+ // Remove any pending updates for this row+ edits_.erase(std::remove_if(edits_.begin(), edits_.end(),+ [rowIndex](const PendingEdit& e) {+ return e.type == EditType::Update && e.rowIndex == rowIndex;+ }), edits_.end());++ PendingEdit edit;+ edit.type = EditType::Delete;+ edit.rowIndex = rowIndex;+ edit.primaryKey = primaryKey;+ edits_.push_back(edit);+ }++ void discardAll()+ {+ edits_.clear();+ }++ bool hasChanges() const { return !edits_.empty(); }+ int changeCount() const { return static_cast<int>(edits_.size()); }++ const std::vector<PendingEdit>& pendingEdits() const { return edits_; }++ std::set<int> deletedRowIndices() const+ {+ std::set<int> indices;+ for (auto& e : edits_)+ if (e.type == EditType::Delete && e.rowIndex >= 0)+ indices.insert(e.rowIndex);+ return indices;+ }++ // Generate SQL statements for all pending changes+ std::vector<std::wstring> generateSQL(+ const std::wstring& table,+ const std::wstring& schema,+ DatabaseType dbType) const+ {+ std::vector<std::wstring> statements;++ for (auto& edit : edits_)+ {+ switch (edit.type)+ {+ case EditType::Insert:+ statements.push_back(generateInsert(table, schema, edit, dbType));+ break;+ case EditType::Update:+ statements.push_back(generateUpdate(table, schema, edit, dbType));+ break;+ case EditType::Delete:+ statements.push_back(generateDelete(table, schema, edit, dbType));+ break;+ }+ }+ return statements;+ }++ private:+ std::vector<PendingEdit> edits_;++ static std::wstring quoteId(const std::wstring& name, DatabaseType dbType)+ {+ if (dbType == DatabaseType::MySQL)+ return L"`" + name + L"`";+ return L"\"" + name + L"\""; // PostgreSQL, SQLite+ }++ static std::wstring quoteLit(const std::wstring& value)+ {+ if (isNullCell(value)) return L"NULL";+ std::wstring escaped;+ escaped += L'\'';+ for (wchar_t c : value)+ {+ if (c == L'\'') escaped += L"''";+ else escaped += c;+ }+ escaped += L'\'';+ return escaped;+ }++ static std::wstring qualifiedTable(const std::wstring& table,+ const std::wstring& schema,+ DatabaseType dbType)+ {+ if (dbType == DatabaseType::SQLite || schema.empty())+ return quoteId(table, dbType);+ return quoteId(schema, dbType) + L"." + quoteId(table, dbType);+ }++ static std::wstring buildWhere(const TableRow& pk, DatabaseType dbType)+ {+ std::wstring where;+ bool first = true;+ for (auto& [col, val] : pk)+ {+ if (!first) where += L" AND ";+ where += quoteId(col, dbType);+ if (isNullCell(val))+ where += L" IS NULL";+ else+ where += L" = " + quoteLit(val);+ first = false;+ }+ return where;+ }++ static std::wstring generateInsert(const std::wstring& table,+ const std::wstring& schema,+ const PendingEdit& edit,+ DatabaseType dbType)+ {+ std::wstring sql = L"INSERT INTO " + qualifiedTable(table, schema, dbType) + L" (";+ std::wstring vals;+ bool first = true;+ for (auto& [col, val] : edit.insertValues)+ {+ if (!first) { sql += L", "; vals += L", "; }+ sql += quoteId(col, dbType);+ vals += quoteLit(val);+ first = false;+ }+ sql += L") VALUES (" + vals + L")";+ return sql;+ }++ static std::wstring generateUpdate(const std::wstring& table,+ const std::wstring& schema,+ const PendingEdit& edit,+ DatabaseType dbType)+ {+ std::wstring sql = L"UPDATE " + qualifiedTable(table, schema, dbType) + L" SET ";+ sql += quoteId(edit.column, dbType) + L" = " + quoteLit(edit.newValue);+ sql += L" WHERE " + buildWhere(edit.primaryKey, dbType);+ return sql;+ }++ static std::wstring generateDelete(const std::wstring& table,+ const std::wstring& schema,+ const PendingEdit& edit,+ DatabaseType dbType)+ {+ std::wstring sql = L"DELETE FROM " + qualifiedTable(table, schema, dbType);+ sql += L" WHERE " + buildWhere(edit.primaryKey, dbType);+ return sql;+ }+ };+}diff --git a/windows/Gridex/Models/ColorTag.h b/windows/Gridex/Models/ColorTag.hnew file mode 100644index 0000000..e228e72--- /dev/null+++ b/windows/Gridex/Models/ColorTag.h@@ -0,0 +1,44 @@+#pragma once+#include <string>+#include <cstdint>+#include <array>++namespace DBModels+{+ enum class ColorTag+ {+ Red,+ Orange,+ Green,+ Blue,+ Purple,+ Gray+ };++ struct ColorTagInfo+ {+ ColorTag tag;+ std::wstring hint;+ uint8_t r, g, b;+ };++ inline constexpr size_t COLOR_TAG_COUNT = 6;++ inline const std::array<ColorTagInfo, COLOR_TAG_COUNT>& GetColorTags()+ {+ static const std::array<ColorTagInfo, COLOR_TAG_COUNT> tags = {{+ { ColorTag::Red, L"Production", 226, 75, 74 },+ { ColorTag::Orange, L"Staging", 239, 159, 39 },+ { ColorTag::Green, L"Development", 99, 153, 34 },+ { ColorTag::Blue, L"Local", 55, 138, 221 },+ { ColorTag::Purple, L"Custom", 83, 74, 183 },+ { ColorTag::Gray, L"Other", 128, 128, 128 },+ }};+ return tags;+ }++ inline const ColorTagInfo& GetColorTagInfo(ColorTag tag)+ {+ return GetColorTags()[static_cast<size_t>(tag)];+ }+}diff --git a/windows/Gridex/Models/ColumnInfo.h b/windows/Gridex/Models/ColumnInfo.hnew file mode 100644index 0000000..dff57a7--- /dev/null+++ b/windows/Gridex/Models/ColumnInfo.h@@ -0,0 +1,48 @@+#pragma once+#include <string>+#include <optional>++namespace DBModels+{+ struct ColumnInfo+ {+ std::wstring name;+ std::wstring dataType;+ bool nullable = true;+ std::wstring defaultValue;+ bool isPrimaryKey = false;+ bool isForeignKey = false;+ std::wstring fkReferencedTable;+ std::wstring fkReferencedColumn;+ std::wstring comment;+ int ordinalPosition = 0;+ };++ struct IndexInfo+ {+ std::wstring name;+ std::wstring columns; // comma-separated+ bool isUnique = false;+ std::wstring algorithm; // BTREE, HASH, etc.+ std::wstring condition;+ bool isPrimary = false;+ };++ struct ForeignKeyInfo+ {+ std::wstring name;+ std::wstring column;+ std::wstring referencedTable;+ std::wstring referencedColumn;+ std::wstring onUpdate; // CASCADE, SET NULL, RESTRICT, etc.+ std::wstring onDelete;+ };++ struct ConstraintInfo+ {+ std::wstring name;+ std::wstring type; // PRIMARY KEY, UNIQUE, CHECK, FOREIGN KEY+ std::wstring columns; // comma-separated+ std::wstring definition;+ };+}diff --git a/windows/Gridex/Models/ConnectionConfig b/windows/Gridex/Models/ConnectionConfignew file mode 100644index 0000000..6f70f09--- /dev/null+++ b/windows/Gridex/Models/ConnectionConfig@@ -0,0 +1 @@+#pragma oncediff --git a/windows/Gridex/Models/ConnectionConfig.h b/windows/Gridex/Models/ConnectionConfig.hnew file mode 100644index 0000000..605ad44--- /dev/null+++ b/windows/Gridex/Models/ConnectionConfig.h@@ -0,0 +1,78 @@+#pragma once+#include <string>+#include <optional>+#include <cstdint>+#include "DatabaseType.h"+#include "ColorTag.h"++namespace DBModels+{+ enum class SSHAuthMethod+ {+ Password,+ PrivateKey,+ KeyWithPassphrase+ };++ enum class SSLMode+ {+ Preferred,+ Disabled,+ Required,+ VerifyCA,+ VerifyIdentity+ };++ struct SSHTunnelConfig+ {+ std::wstring host;+ uint16_t port = 22;+ std::wstring username;+ std::wstring password; // SSH password (separate from DB password)+ SSHAuthMethod authMethod = SSHAuthMethod::Password;+ std::wstring keyPath;+ };++ struct ConnectionConfig+ {+ std::wstring id;+ std::wstring name;+ DatabaseType databaseType = DatabaseType::PostgreSQL;+ std::wstring host;+ uint16_t port = 5432;+ std::wstring database;+ std::wstring username;+ std::wstring password; // stored encrypted in JSON via DPAPI+ bool sslEnabled = false;+ SSLMode sslMode = SSLMode::Preferred;+ std::optional<ColorTag> colorTag;+ std::wstring group;+ std::wstring filePath; // SQLite file path+ std::wstring connectionUri; // MongoDB URI (mongodb:// or mongodb+srv://)+ // Arbitrary URI query params for MongoDB form-based connections.+ // Appended as ?key=val&key=val when building the URI from+ // host/port/user/pass fields. Common values:+ // authSource=admin+ // replicaSet=rs0+ // tls=true+ // authMechanism=SCRAM-SHA-256+ std::wstring mongoOptions;+ std::optional<SSHTunnelConfig> sshConfig;++ std::wstring subtitle() const+ {+ if (databaseType == DatabaseType::SQLite)+ return filePath.empty() ? L"No file selected" : filePath;+ // MongoDB: show truncated URI if provided+ if (databaseType == DatabaseType::MongoDB && !connectionUri.empty())+ {+ auto uri = connectionUri;+ return uri.size() > 60 ? uri.substr(0, 57) + L"..." : uri;+ }+ std::wstring result = host;+ if (port > 0) result += L":" + std::to_wstring(port);+ if (!database.empty()) result += L"/" + database;+ return result.empty() ? L"Not configured" : result;+ }+ };+}diff --git a/windows/Gridex/Models/ConnectionManager.h b/windows/Gridex/Models/ConnectionManager.hnew file mode 100644index 0000000..3400156--- /dev/null+++ b/windows/Gridex/Models/ConnectionManager.h@@ -0,0 +1,63 @@+#pragma once+#include <memory>+#include <string>+#include <vector>+#include <chrono>+#include "DatabaseAdapter.h"+#include "ConnectionConfig.h"+#include "SSHTunnelService.h"++namespace DBModels+{+ // Query log entry for the console log panel+ struct QueryLogEntry+ {+ std::wstring sql;+ std::wstring status; // "success", "error"+ int rowCount = 0;+ double durationMs = 0.0; // Exec — driver blocking call wall-clock+ double renderDurationMs = 0.0; // Render — UI grid build (0 if no UI render)+ std::chrono::system_clock::time_point timestamp;+ std::wstring error;+ };++ class ConnectionManager+ {+ public:+ // Connect to a database, returns the adapter+ std::shared_ptr<DatabaseAdapter> connect(+ const ConnectionConfig& config,+ const std::wstring& password);++ // Disconnect current connection+ void disconnect();++ // Test a connection without keeping it open+ bool testConnection(+ const ConnectionConfig& config,+ const std::wstring& password);++ // Get the active adapter (nullptr if not connected)+ std::shared_ptr<DatabaseAdapter> getActiveAdapter() const { return activeAdapter_; }++ // Check if connected+ bool isConnected() const { return activeAdapter_ && activeAdapter_->isConnected(); }++ // Get current connection config+ const ConnectionConfig& getConfig() const { return activeConfig_; }++ // Query log+ const std::vector<QueryLogEntry>& getQueryLog() const { return queryLog_; }+ void addQueryLog(const QueryLogEntry& entry) { queryLog_.push_back(entry); }+ void clearQueryLog() { queryLog_.clear(); }++ private:+ std::shared_ptr<DatabaseAdapter> activeAdapter_;+ ConnectionConfig activeConfig_;+ std::vector<QueryLogEntry> queryLog_;+ std::unique_ptr<SSHTunnelService> sshTunnel_;++ // Factory: create adapter based on database type+ std::shared_ptr<DatabaseAdapter> createAdapter(DatabaseType type);+ };+}diff --git a/windows/Gridex/Models/ConnectionStore.h b/windows/Gridex/Models/ConnectionStore.hnew file mode 100644index 0000000..51f547b--- /dev/null+++ b/windows/Gridex/Models/ConnectionStore.h@@ -0,0 +1,321 @@+#pragma once+#include <string>+#include <vector>+#include <ShlObj.h>+#include <sqlite3.h>+#include <wincrypt.h>+#include "ConnectionConfig.h"++#pragma comment(lib, "Crypt32.lib")++namespace DBModels+{+ class ConnectionStore+ {+ public:+ // Load all saved connections+ static std::vector<ConnectionConfig> Load()+ {+ auto dbPath = GetDbPath();+ sqlite3* db = nullptr;+ if (sqlite3_open16(dbPath.c_str(), &db) != SQLITE_OK)+ return {};++ EnsureTable(db);++ std::vector<ConnectionConfig> results;+ const char* sql =+ "SELECT id, name, type, host, port, database_name, username, "+ "password_enc, ssl_enabled, ssl_mode, color_tag, grp, file_path, "+ "sort_order, created_at, last_connected_at, connection_uri, "+ "mongo_options, "+ "ssh_host, ssh_port, ssh_username, ssh_password_enc, "+ "ssh_auth_method, ssh_key_path "+ "FROM connections ORDER BY sort_order, name";++ sqlite3_stmt* stmt = nullptr;+ if (sqlite3_prepare_v2(db, sql, -1, &stmt, nullptr) == SQLITE_OK)+ {+ while (sqlite3_step(stmt) == SQLITE_ROW)+ {+ ConnectionConfig c;+ c.id = ColText16(stmt, 0);+ c.name = ColText16(stmt, 1);+ c.databaseType = static_cast<DatabaseType>(sqlite3_column_int(stmt, 2));+ c.host = ColText16(stmt, 3);+ c.port = static_cast<uint16_t>(sqlite3_column_int(stmt, 4));+ c.database = ColText16(stmt, 5);+ c.username = ColText16(stmt, 6);+ c.password = DecryptPassword(ColText8(stmt, 7));+ c.sslEnabled = sqlite3_column_int(stmt, 8) != 0;+ c.sslMode = static_cast<SSLMode>(sqlite3_column_int(stmt, 9));+ int ct = sqlite3_column_int(stmt, 10);+ if (ct >= 0) c.colorTag = static_cast<ColorTag>(ct);+ c.group = ColText16(stmt, 11);+ c.filePath = ColText16(stmt, 12);+ // Column 16-17: MongoDB fields+ c.connectionUri = ColText16(stmt, 16);+ c.mongoOptions = ColText16(stmt, 17);+ // Column 18-23: SSH tunnel fields+ {+ auto sshHost = ColText16(stmt, 18);+ if (!sshHost.empty())+ {+ SSHTunnelConfig ssh;+ ssh.host = sshHost;+ ssh.port = static_cast<uint16_t>(sqlite3_column_int(stmt, 19));+ if (ssh.port == 0) ssh.port = 22;+ ssh.username = ColText16(stmt, 20);+ ssh.password = DecryptPassword(ColText8(stmt, 21));+ ssh.authMethod = static_cast<SSHAuthMethod>(sqlite3_column_int(stmt, 22));+ ssh.keyPath = ColText16(stmt, 23);+ c.sshConfig = ssh;+ }+ }+ results.push_back(c);+ }+ sqlite3_finalize(stmt);+ }++ sqlite3_close(db);+ return results;+ }++ // Save (insert or update) a single connection+ static void Save(const ConnectionConfig& c)+ {+ auto dbPath = GetDbPath();+ sqlite3* db = nullptr;+ if (sqlite3_open16(dbPath.c_str(), &db) != SQLITE_OK)+ return;++ EnsureTable(db);++ const char* sql =+ "INSERT OR REPLACE INTO connections "+ "(id, name, type, host, port, database_name, username, "+ "password_enc, ssl_enabled, ssl_mode, color_tag, grp, file_path, "+ "sort_order, created_at, last_connected_at, connection_uri, "+ "mongo_options, "+ "ssh_host, ssh_port, ssh_username, ssh_password_enc, "+ "ssh_auth_method, ssh_key_path) "+ "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,0, "+ "COALESCE((SELECT created_at FROM connections WHERE id=?), datetime('now')), "+ "datetime('now'), ?, ?, ?,?,?,?,?,?)";++ sqlite3_stmt* stmt = nullptr;+ if (sqlite3_prepare_v2(db, sql, -1, &stmt, nullptr) == SQLITE_OK)+ {+ auto id8 = ToUtf8(c.id);+ BindText(stmt, 1, id8);+ BindText(stmt, 2, ToUtf8(c.name));+ sqlite3_bind_int(stmt, 3, static_cast<int>(c.databaseType));+ BindText(stmt, 4, ToUtf8(c.host));+ sqlite3_bind_int(stmt, 5, c.port);+ BindText(stmt, 6, ToUtf8(c.database));+ BindText(stmt, 7, ToUtf8(c.username));+ BindText(stmt, 8, EncryptPassword(c.password));+ sqlite3_bind_int(stmt, 9, c.sslEnabled ? 1 : 0);+ sqlite3_bind_int(stmt, 10, static_cast<int>(c.sslMode));+ sqlite3_bind_int(stmt, 11, c.colorTag.has_value()+ ? static_cast<int>(c.colorTag.value()) : -1);+ BindText(stmt, 12, ToUtf8(c.group));+ BindText(stmt, 13, ToUtf8(c.filePath));+ BindText(stmt, 14, id8); // for COALESCE created_at+ BindText(stmt, 15, ToUtf8(c.connectionUri)); // MongoDB URI+ BindText(stmt, 16, ToUtf8(c.mongoOptions)); // MongoDB options+ // SSH tunnel fields (17-22)+ if (c.sshConfig.has_value())+ {+ BindText(stmt, 17, ToUtf8(c.sshConfig->host));+ sqlite3_bind_int(stmt, 18, c.sshConfig->port);+ BindText(stmt, 19, ToUtf8(c.sshConfig->username));+ BindText(stmt, 20, EncryptPassword(c.sshConfig->password));+ sqlite3_bind_int(stmt, 21, static_cast<int>(c.sshConfig->authMethod));+ BindText(stmt, 22, ToUtf8(c.sshConfig->keyPath));+ }+ else+ {+ BindText(stmt, 17, "");+ sqlite3_bind_int(stmt, 18, 0);+ BindText(stmt, 19, "");+ BindText(stmt, 20, "");+ sqlite3_bind_int(stmt, 21, 0);+ BindText(stmt, 22, "");+ }+ sqlite3_step(stmt);+ sqlite3_finalize(stmt);+ }++ sqlite3_close(db);+ }++ // Save all connections (bulk)+ static void SaveAll(const std::vector<ConnectionConfig>& connections)+ {+ for (auto& c : connections)+ Save(c);+ }++ // Delete a connection by id+ static void Delete(const std::wstring& id)+ {+ auto dbPath = GetDbPath();+ sqlite3* db = nullptr;+ if (sqlite3_open16(dbPath.c_str(), &db) != SQLITE_OK)+ return;++ const char* sql = "DELETE FROM connections WHERE id=?";+ sqlite3_stmt* stmt = nullptr;+ if (sqlite3_prepare_v2(db, sql, -1, &stmt, nullptr) == SQLITE_OK)+ {+ BindText(stmt, 1, ToUtf8(id));+ sqlite3_step(stmt);+ sqlite3_finalize(stmt);+ }+ sqlite3_close(db);+ }++ private:+ static void EnsureTable(sqlite3* db)+ {+ const char* sql =+ "CREATE TABLE IF NOT EXISTS connections ("+ " id TEXT PRIMARY KEY,"+ " name TEXT NOT NULL,"+ " type INTEGER NOT NULL DEFAULT 0,"+ " host TEXT DEFAULT '',"+ " port INTEGER DEFAULT 5432,"+ " database_name TEXT DEFAULT '',"+ " username TEXT DEFAULT '',"+ " password_enc TEXT DEFAULT '',"+ " ssl_enabled INTEGER DEFAULT 0,"+ " ssl_mode INTEGER DEFAULT 0,"+ " color_tag INTEGER DEFAULT -1,"+ " grp TEXT DEFAULT '',"+ " file_path TEXT DEFAULT '',"+ " sort_order INTEGER DEFAULT 0,"+ " created_at TEXT DEFAULT (datetime('now')),"+ " last_connected_at TEXT,"+ " connection_uri TEXT DEFAULT ''"+ ")";+ sqlite3_exec(db, sql, nullptr, nullptr, nullptr);++ // Migration: add connection_uri + mongo_options for MongoDB support+ sqlite3_exec(db,+ "ALTER TABLE connections ADD COLUMN connection_uri TEXT DEFAULT ''",+ nullptr, nullptr, nullptr);+ sqlite3_exec(db,+ "ALTER TABLE connections ADD COLUMN mongo_options TEXT DEFAULT ''",+ nullptr, nullptr, nullptr);+ // Migration: SSH tunnel fields+ sqlite3_exec(db, "ALTER TABLE connections ADD COLUMN ssh_host TEXT DEFAULT ''", nullptr, nullptr, nullptr);+ sqlite3_exec(db, "ALTER TABLE connections ADD COLUMN ssh_port INTEGER DEFAULT 22", nullptr, nullptr, nullptr);+ sqlite3_exec(db, "ALTER TABLE connections ADD COLUMN ssh_username TEXT DEFAULT ''", nullptr, nullptr, nullptr);+ sqlite3_exec(db, "ALTER TABLE connections ADD COLUMN ssh_password_enc TEXT DEFAULT ''", nullptr, nullptr, nullptr);+ sqlite3_exec(db, "ALTER TABLE connections ADD COLUMN ssh_auth_method INTEGER DEFAULT 0", nullptr, nullptr, nullptr);+ sqlite3_exec(db, "ALTER TABLE connections ADD COLUMN ssh_key_path TEXT DEFAULT ''", nullptr, nullptr, nullptr);+ }++ static std::wstring GetDbPath()+ {+ wchar_t* appData = nullptr;+ SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &appData);+ std::wstring dir = std::wstring(appData) + L"\\Gridex";+ CoTaskMemFree(appData);+ CreateDirectoryW(dir.c_str(), nullptr);+ return dir + L"\\gridex.db";+ }++ // ── DPAPI password encryption ───────────────+ static std::string EncryptPassword(const std::wstring& password)+ {+ if (password.empty()) return "";+ std::string utf8 = ToUtf8(password);++ DATA_BLOB input;+ input.pbData = reinterpret_cast<BYTE*>(utf8.data());+ input.cbData = static_cast<DWORD>(utf8.size());++ DATA_BLOB output = {};+ if (!CryptProtectData(&input, nullptr, nullptr, nullptr, nullptr, 0, &output))+ return "";++ // Encode as hex+ std::string hex;+ hex.reserve(output.cbData * 2);+ for (DWORD i = 0; i < output.cbData; i++)+ {+ char buf[3];+ snprintf(buf, sizeof(buf), "%02x", output.pbData[i]);+ hex += buf;+ }+ LocalFree(output.pbData);+ return hex;+ }++ static std::wstring DecryptPassword(const std::string& hexEnc)+ {+ if (hexEnc.empty()) return L"";++ // Decode hex+ std::vector<BYTE> bytes;+ bytes.reserve(hexEnc.size() / 2);+ for (size_t i = 0; i + 1 < hexEnc.size(); i += 2)+ {+ BYTE b = static_cast<BYTE>(std::stoi(hexEnc.substr(i, 2), nullptr, 16));+ bytes.push_back(b);+ }++ DATA_BLOB input;+ input.pbData = bytes.data();+ input.cbData = static_cast<DWORD>(bytes.size());++ DATA_BLOB output = {};+ if (!CryptUnprotectData(&input, nullptr, nullptr, nullptr, nullptr, 0, &output))+ return L"";++ std::string utf8(reinterpret_cast<char*>(output.pbData), output.cbData);+ LocalFree(output.pbData);+ return FromUtf8(utf8);+ }++ // ── Helpers ─────────────────────────────────+ static std::string ToUtf8(const std::wstring& w)+ {+ if (w.empty()) return {};+ int sz = WideCharToMultiByte(CP_UTF8, 0, w.c_str(), (int)w.size(), nullptr, 0, nullptr, nullptr);+ std::string r(sz, '\0');+ WideCharToMultiByte(CP_UTF8, 0, w.c_str(), (int)w.size(), &r[0], sz, nullptr, nullptr);+ return r;+ }++ static std::wstring FromUtf8(const std::string& s)+ {+ if (s.empty()) return {};+ int sz = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), (int)s.size(), nullptr, 0);+ std::wstring r(sz, L'\0');+ MultiByteToWideChar(CP_UTF8, 0, s.c_str(), (int)s.size(), &r[0], sz);+ return r;+ }++ static std::wstring ColText16(sqlite3_stmt* stmt, int col)+ {+ auto* text = sqlite3_column_text(stmt, col);+ if (!text) return L"";+ return FromUtf8(reinterpret_cast<const char*>(text));+ }++ static std::string ColText8(sqlite3_stmt* stmt, int col)+ {+ auto* text = sqlite3_column_text(stmt, col);+ if (!text) return "";+ return reinterpret_cast<const char*>(text);+ }++ static void BindText(sqlite3_stmt* stmt, int idx, const std::string& val)+ {+ sqlite3_bind_text(stmt, idx, val.c_str(), (int)val.size(), SQLITE_TRANSIENT);+ }+ };+}diff --git a/windows/Gridex/Models/ContentTab.h b/windows/Gridex/Models/ContentTab.hnew file mode 100644index 0000000..8433a43--- /dev/null+++ b/windows/Gridex/Models/ContentTab.h@@ -0,0 +1,48 @@+#pragma once+#include <string>+#include <optional>+#include "QueryResult.h"+#include "ColumnInfo.h"++namespace DBModels+{+ enum class TabType+ {+ DataGrid,+ QueryEditor,+ TableStructure,+ TableList,+ FunctionDetail,+ ERDiagram+ };++ struct ContentTab+ {+ std::wstring id;+ TabType type = TabType::DataGrid;+ std::wstring title;+ std::wstring tableName;+ std::wstring schema;+ std::wstring databaseName;+ bool isActive = false;+ bool isDirty = false;++ // Cached data per tab (so switching tabs restores state)+ std::optional<QueryResult> cachedData;+ std::vector<ColumnInfo> cachedColumns;+ std::vector<IndexInfo> cachedIndexes;+ std::vector<ForeignKeyInfo> cachedForeignKeys;+ int cachedPage = 0;++ // Query editor SQL text (only used when type == QueryEditor).+ // Saved on tab switch so each query tab has its own content+ // instead of sharing the single QueryEditorView text box.+ std::wstring cachedSql;++ // ER Diagram tab payload (only used when type == ERDiagram)+ std::wstring erD2Text;+ std::wstring erSvgPath;+ int erTableCount = 0;+ int erRelationshipCount = 0;+ };+}diff --git a/windows/Gridex/Models/CredentialManager.h b/windows/Gridex/Models/CredentialManager.hnew file mode 100644index 0000000..2dc99c8--- /dev/null+++ b/windows/Gridex/Models/CredentialManager.h@@ -0,0 +1,28 @@+#pragma once+#include <string>++namespace DBModels+{+ // Wrapper around Windows Credential Manager (CredRead/CredWrite/CredDelete)+ // Stores connection passwords securely using DPAPI+ class CredentialManager+ {+ public:+ // Save password for a connection ID+ static bool Save(const std::wstring& connectionId, const std::wstring& password);++ // Load password for a connection ID (returns empty if not found)+ static std::wstring Load(const std::wstring& connectionId);++ // Remove stored password for a connection ID+ static bool Remove(const std::wstring& connectionId);++ // Check if credentials exist for a connection ID+ static bool Exists(const std::wstring& connectionId);++ private:+ // Prefix for all credential target names+ static std::wstring TargetName(const std::wstring& connectionId);+ static constexpr const wchar_t* TARGET_PREFIX = L"Gridex:";+ };+}diff --git a/windows/Gridex/Models/DatabaseAdapter.h b/windows/Gridex/Models/DatabaseAdapter.hnew file mode 100644index 0000000..11a2065--- /dev/null+++ b/windows/Gridex/Models/DatabaseAdapter.h@@ -0,0 +1,101 @@+#pragma once+#include <string>+#include <vector>+#include <memory>+#include <stdexcept>+#include "ConnectionConfig.h"+#include "ColumnInfo.h"+#include "TableRow.h"+#include "QueryResult.h"+#include "TableInfo.h"+#include "RowValue.h"++namespace DBModels+{+ // Error type for database operations+ class DatabaseError : public std::runtime_error+ {+ public:+ enum class Code+ {+ ConnectionFailed, ConnectionTimeout, AuthenticationFailed,+ SSLRequired, DatabaseNotFound,+ QueryFailed, QueryCancelled, QueryTimeout, InvalidSQL,+ SSHFailed, SSHAuthFailed, SSHTunnelFailed,+ SchemaLoadFailed, TableNotFound,+ TransactionFailed, PermissionDenied, Unknown+ };++ Code code;++ DatabaseError(Code c, const std::string& msg)+ : std::runtime_error(msg), code(c) {}+ };++ // Abstract database adapter interface+ class DatabaseAdapter+ {+ public:+ virtual ~DatabaseAdapter() = default;++ // ── Connection ──────────────────────────────+ virtual void connect(const ConnectionConfig& config, const std::wstring& password) = 0;+ virtual void disconnect() = 0;+ virtual bool testConnection(const ConnectionConfig& config, const std::wstring& password) = 0;+ virtual bool isConnected() const = 0;++ // ── Query Execution ─────────────────────────+ virtual QueryResult execute(const std::wstring& sql) = 0;+ virtual QueryResult fetchRows(+ const std::wstring& table,+ const std::wstring& schema,+ int limit = 100,+ int offset = 0,+ const std::wstring& orderBy = L"",+ bool ascending = true) = 0;++ // ── Schema Inspection ───────────────────────+ virtual std::vector<std::wstring> listDatabases() = 0;+ virtual std::vector<std::wstring> listSchemas() = 0;+ virtual std::vector<TableInfo> listTables(const std::wstring& schema) = 0;+ virtual std::vector<TableInfo> listViews(const std::wstring& schema) = 0;+ virtual std::vector<ColumnInfo> describeTable(+ const std::wstring& table, const std::wstring& schema) = 0;+ virtual std::vector<IndexInfo> listIndexes(+ const std::wstring& table, const std::wstring& schema) = 0;+ virtual std::vector<ForeignKeyInfo> listForeignKeys(+ const std::wstring& table, const std::wstring& schema) = 0;+ virtual std::vector<std::wstring> listFunctions(const std::wstring& schema) = 0;+ virtual std::wstring getFunctionSource(+ const std::wstring& name, const std::wstring& schema) = 0;++ // Return CREATE TABLE DDL for a single table (no trailing semicolon)+ virtual std::wstring getCreateTableSQL(+ const std::wstring& table, const std::wstring& schema) = 0;++ // ── Data Manipulation ───────────────────────+ virtual QueryResult insertRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& values) = 0;+ virtual QueryResult updateRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& setValues, const TableRow& whereValues) = 0;+ virtual QueryResult deleteRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& whereValues) = 0;++ // ── Transactions ────────────────────────────+ virtual void beginTransaction() = 0;+ virtual void commitTransaction() = 0;+ virtual void rollbackTransaction() = 0;++ // ── Server Info ─────────────────────────────+ virtual std::wstring serverVersion() = 0;+ virtual std::wstring currentDatabase() = 0;++ // ── Adapter-specific tuning (default: no-op) ───+ // Redis uses this to set the SCAN MATCH pattern for fetchRows.+ // SQL adapters ignore it. Pass "*" or empty to disable filtering.+ virtual void setSearchPattern(const std::wstring& /*pattern*/) {}+ };+}diff --git a/windows/Gridex/Models/DatabaseType.h b/windows/Gridex/Models/DatabaseType.hnew file mode 100644index 0000000..b82158b--- /dev/null+++ b/windows/Gridex/Models/DatabaseType.h@@ -0,0 +1,112 @@+#pragma once+#include <string>+#include <vector>+#include <cstdint>++namespace DBModels+{+ enum class DatabaseType+ {+ PostgreSQL,+ MySQL,+ SQLite,+ Redis,+ MongoDB,+ MSSQLServer+ };++ inline std::wstring DatabaseTypeDisplayName(DatabaseType type)+ {+ switch (type)+ {+ case DatabaseType::PostgreSQL: return L"PostgreSQL";+ case DatabaseType::MySQL: return L"MySQL";+ case DatabaseType::SQLite: return L"SQLite";+ case DatabaseType::Redis: return L"Redis";+ case DatabaseType::MongoDB: return L"MongoDB";+ case DatabaseType::MSSQLServer: return L"SQL Server";+ default: return L"Unknown";+ }+ }++ inline uint16_t DatabaseTypeDefaultPort(DatabaseType type)+ {+ switch (type)+ {+ case DatabaseType::PostgreSQL: return 5432;+ case DatabaseType::MySQL: return 3306;+ case DatabaseType::Redis: return 6379;+ case DatabaseType::MongoDB: return 27017;+ case DatabaseType::MSSQLServer: return 1433;+ default: return 0;+ }+ }++ // Common column types per database engine+ inline std::vector<std::wstring> ColumnTypesForDB(DatabaseType type)+ {+ switch (type)+ {+ case DatabaseType::PostgreSQL:+ return {+ L"bigint", L"bigserial", L"boolean", L"bytea", L"char",+ L"cidr", L"date", L"decimal", L"double precision", L"inet",+ L"integer", L"interval", L"json", L"jsonb", L"macaddr",+ L"money", L"numeric", L"real", L"serial", L"smallint",+ L"smallserial", L"text", L"time", L"time with time zone",+ L"timestamp", L"timestamp with time zone", L"uuid",+ L"varchar", L"varchar(255)", L"xml"+ };+ case DatabaseType::MySQL:+ return {+ L"bigint", L"binary", L"bit", L"blob", L"boolean", L"char",+ L"date", L"datetime", L"decimal", L"double", L"enum",+ L"float", L"int", L"json", L"longblob", L"longtext",+ L"mediumint", L"mediumtext", L"set", L"smallint", L"text",+ L"time", L"timestamp", L"tinyint", L"tinytext",+ L"varbinary", L"varchar(255)"+ };+ case DatabaseType::SQLite:+ return {+ L"BLOB", L"INTEGER", L"NUMERIC", L"REAL", L"TEXT"+ };+ case DatabaseType::Redis:+ // Redis virtual columns — types are fixed for the Keys table+ return {+ L"string", L"list", L"hash", L"set", L"zset", L"stream"+ };+ case DatabaseType::MongoDB:+ return {+ L"String", L"Int32", L"Int64", L"Double", L"Boolean",+ L"Date", L"ObjectId", L"Array", L"Object", L"Binary"+ };+ case DatabaseType::MSSQLServer:+ return {+ L"bigint", L"bit", L"char", L"date", L"datetime",+ L"datetime2", L"decimal", L"float", L"int", L"money",+ L"nchar", L"ntext", L"numeric", L"nvarchar(255)",+ L"nvarchar(MAX)", L"real", L"smalldatetime", L"smallint",+ L"smallmoney", L"text", L"time", L"tinyint",+ L"uniqueidentifier", L"varbinary", L"varchar(255)",+ L"varchar(MAX)", L"xml"+ };+ default:+ return { L"text", L"integer", L"boolean" };+ }+ }++ // Glyph codes for Segoe MDL2 Assets font+ inline std::wstring DatabaseTypeGlyph(DatabaseType type)+ {+ switch (type)+ {+ case DatabaseType::PostgreSQL: return L"\xE968";+ case DatabaseType::MySQL: return L"\xE968";+ case DatabaseType::SQLite: return L"\xE8E5";+ case DatabaseType::Redis: return L"\xE8D7"; // Permissions/Key+ case DatabaseType::MongoDB: return L"\xE943"; // Globe/Document DB+ case DatabaseType::MSSQLServer: return L"\xE968"; // Database+ default: return L"\xE774";+ }+ }+}diff --git a/windows/Gridex/Models/DumpRestoreService.h b/windows/Gridex/Models/DumpRestoreService.hnew file mode 100644index 0000000..d5ba08d--- /dev/null+++ b/windows/Gridex/Models/DumpRestoreService.h@@ -0,0 +1,57 @@+#pragma once+#include <string>+#include <memory>+#include <functional>+#include "DatabaseAdapter.h"+#include "DatabaseType.h"++namespace DBModels+{+ // Called from background thread with a single progress message line.+ // Implementation must be thread-safe and not touch WinRT UI directly.+ using ProgressCallback = std::function<void(const std::wstring&)>;++ struct DumpResult+ {+ bool success = false;+ int tablesProcessed = 0;+ int rowsExported = 0;+ std::wstring error;+ };++ struct RestoreResult+ {+ bool success = false;+ int statementsExecuted = 0;+ int statementsFailed = 0;+ std::wstring error;+ };++ // Database-level dump and restore. Uses batched LIMIT/OFFSET reads to keep+ // memory bounded regardless of table size; rows are streamed to disk+ // immediately rather than accumulated in memory.+ class DumpRestoreService+ {+ public:+ static constexpr int DEFAULT_BATCH_SIZE = 1000;++ // Dump every table in `schema` to a single .sql file.+ // batchSize: number of rows fetched per LIMIT/OFFSET round-trip.+ // dbType: needed for emitting correct DROP CASCADE / FK directives.+ // progress: optional callback for status updates (called from caller's thread).+ static DumpResult DumpDatabase(+ std::shared_ptr<DatabaseAdapter> adapter,+ DatabaseType dbType,+ const std::wstring& schema,+ const std::wstring& outputFile,+ int batchSize = DEFAULT_BATCH_SIZE,+ ProgressCallback progress = nullptr);++ // Read .sql file and execute every statement against `adapter`.+ // Wraps in a transaction; rolls back on any failure.+ static RestoreResult RestoreDatabase(+ std::shared_ptr<DatabaseAdapter> adapter,+ const std::wstring& inputFile,+ ProgressCallback progress = nullptr);+ };+}diff --git a/windows/Gridex/Models/ERDiagramService.h b/windows/Gridex/Models/ERDiagramService.hnew file mode 100644index 0000000..d5580f8--- /dev/null+++ b/windows/Gridex/Models/ERDiagramService.h@@ -0,0 +1,40 @@+#pragma once+#include <string>+#include <memory>+#include "DatabaseAdapter.h"+#include "DumpRestoreService.h" // ProgressCallback++namespace DBModels+{+ struct ERDiagramResult+ {+ bool success = false;+ std::wstring d2Text; // Generated D2 source+ std::wstring svgPath; // Path to rendered SVG file in temp dir+ int tableCount = 0;+ int relationshipCount = 0;+ std::wstring error; // Subprocess stderr or generation error+ };++ // Generate ER diagram from schema using D2 declarative format.+ // Renders via bundled d2.exe (Assets/d2/d2.exe) -> SVG file in temp dir.+ // Native rendering via WinUI 3 SvgImageSource on caller side.+ class ERDiagramService+ {+ public:+ // Full pipeline: introspect schema -> generate D2 -> run d2.exe -> SVG path+ static ERDiagramResult Generate(+ std::shared_ptr<DatabaseAdapter> adapter,+ const std::wstring& schema,+ ProgressCallback progress = nullptr);++ // Just the D2 text without rendering — used by Copy D2 button+ static std::wstring GenerateD2Text(+ std::shared_ptr<DatabaseAdapter> adapter,+ const std::wstring& schema,+ ProgressCallback progress = nullptr);++ // Resolve d2.exe path (Package.Current install dir or exe dir)+ static std::wstring LocateD2Exe();+ };+}diff --git a/windows/Gridex/Models/ExportService.h b/windows/Gridex/Models/ExportService.hnew file mode 100644index 0000000..2dd6e59--- /dev/null+++ b/windows/Gridex/Models/ExportService.h@@ -0,0 +1,42 @@+#pragma once+#include <string>+#include "QueryResult.h"++namespace DBModels+{+ // Export query results to CSV, JSON, or SQL+ class ExportService+ {+ public:+ // Export to CSV string+ static std::wstring ToCsv(const QueryResult& result);++ // Export to JSON array string+ static std::wstring ToJson(const QueryResult& result);++ // Export to SQL INSERT statements+ static std::wstring ToSqlInsert(+ const QueryResult& result,+ const std::wstring& tableName);++ // Write content to a file path (no dialog — caller handles picker)+ static bool WriteToStorageFile(+ const std::wstring& content,+ const std::wstring& filterExtension,+ const std::wstring& filePath);++ // Legacy — no-op now+ static bool SaveToFile(+ const std::wstring& content,+ const std::wstring& defaultFileName,+ const std::wstring& filterName,+ const std::wstring& filterExtension,+ HWND hwnd = nullptr);++ static std::wstring GetLastSavedPath() { return lastSavedPath_; }++ private:+ static std::string toUtf8(const std::wstring& wstr);+ static inline std::wstring lastSavedPath_;+ };+}diff --git a/windows/Gridex/Models/ImportService.h b/windows/Gridex/Models/ImportService.hnew file mode 100644index 0000000..336112a--- /dev/null+++ b/windows/Gridex/Models/ImportService.h@@ -0,0 +1,37 @@+#pragma once+#include <string>+#include <vector>+#include "TableRow.h"++namespace DBModels+{+ struct ImportResult+ {+ std::vector<std::wstring> columnNames;+ std::vector<TableRow> rows; // CSV/JSON parsed rows+ std::vector<std::wstring> sqlStatements; // SQL parsed statements+ int totalParsed = 0;+ std::wstring error;+ bool success = false;+ };++ // Parse CSV/JSON/SQL files into importable data+ class ImportService+ {+ public:+ // Parse CSV content → column names + rows+ static ImportResult ParseCsv(const std::wstring& content);++ // Parse JSON array content → column names + rows+ static ImportResult ParseJson(const std::wstring& content);++ // Parse SQL file → individual statements+ static ImportResult ParseSql(const std::wstring& content);++ // Read file from disk as wstring (UTF-8 → wide)+ static std::wstring ReadFileAsWstring(const std::wstring& filePath);++ // Detect format from file extension+ static std::wstring DetectFormat(const std::wstring& filename);+ };+}diff --git a/windows/Gridex/Models/MSSQLAdapter.h b/windows/Gridex/Models/MSSQLAdapter.hnew file mode 100644index 0000000..e40fc3c--- /dev/null+++ b/windows/Gridex/Models/MSSQLAdapter.h@@ -0,0 +1,100 @@+#pragma once+// MSSQLAdapter — SQL Server support via Windows ODBC API.+//+// Uses the built-in ODBC driver stack (sql.h / sqlext.h) with zero+// external dependencies. Requires "ODBC Driver 18 for SQL Server"+// (or 17, or the legacy "SQL Server" driver) installed on the machine.+//+// Identifier quoting: [schema].[table] (bracket style)+// String literals: N'value' (Unicode prefix)+// Pagination: OFFSET/FETCH NEXT (requires ORDER BY)+// Default schema: dbo (not "public")++#include "DatabaseAdapter.h"+#include <memory>+#include <string>+#include <vector>++// Forward-declare ODBC handle types to avoid including <sql.h> in the+// header (it pulls in windows.h macros that conflict with WinRT).+typedef void* SQLHENV;+typedef void* SQLHDBC;++namespace DBModels+{+ class MSSQLAdapter : public DatabaseAdapter+ {+ public:+ MSSQLAdapter();+ ~MSSQLAdapter() override;++ // ── Connection ──────────────────────────────+ void connect(const ConnectionConfig& config, const std::wstring& password) override;+ void disconnect() override;+ bool testConnection(const ConnectionConfig& config, const std::wstring& password) override;+ bool isConnected() const override;++ // ── Query Execution ─────────────────────────+ QueryResult execute(const std::wstring& sql) override;+ QueryResult fetchRows(+ const std::wstring& table, const std::wstring& schema,+ int limit, int offset,+ const std::wstring& orderBy, bool ascending) override;++ // ── Schema Inspection ───────────────────────+ std::vector<std::wstring> listDatabases() override;+ std::vector<std::wstring> listSchemas() override;+ std::vector<TableInfo> listTables(const std::wstring& schema) override;+ std::vector<TableInfo> listViews(const std::wstring& schema) override;+ std::vector<ColumnInfo> describeTable(+ const std::wstring& table, const std::wstring& schema) override;+ std::vector<IndexInfo> listIndexes(+ const std::wstring& table, const std::wstring& schema) override;+ std::vector<ForeignKeyInfo> listForeignKeys(+ const std::wstring& table, const std::wstring& schema) override;+ std::vector<std::wstring> listFunctions(const std::wstring& schema) override;+ std::wstring getFunctionSource(+ const std::wstring& name, const std::wstring& schema) override;+ std::wstring getCreateTableSQL(+ const std::wstring& table, const std::wstring& schema) override;++ // ── Data Manipulation ───────────────────────+ QueryResult insertRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& values) override;+ QueryResult updateRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& setValues, const TableRow& whereValues) override;+ QueryResult deleteRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& whereValues) override;++ // ── Transactions ────────────────────────────+ void beginTransaction() override;+ void commitTransaction() override;+ void rollbackTransaction() override;++ // ── Server Info ─────────────────────────────+ std::wstring serverVersion() override;+ std::wstring currentDatabase() override;++ private:+ SQLHENV hEnv_ = nullptr;+ SQLHDBC hDbc_ = nullptr;+ bool connected_ = false;+ std::string currentDb_;++ // ── Helpers ─────────────────────────────────+ static std::string toUtf8(const std::wstring& s);+ static std::wstring fromUtf8(const std::string& s);+ static std::string quoteIdentifier(const std::wstring& name);+ static std::string quoteLiteral(const std::wstring& value);+ void ensureConnected() const;+ QueryResult executeInternal(const std::string& sql);++ // Try available ODBC drivers in order of preference+ static std::string findDriver();+ // Extract ODBC error message from handle+ static std::string odbcError(short handleType, void* handle);+ };+}diff --git a/windows/Gridex/Models/MongoDBAdapter.h b/windows/Gridex/Models/MongoDBAdapter.hnew file mode 100644index 0000000..3bc5c80--- /dev/null+++ b/windows/Gridex/Models/MongoDBAdapter.h@@ -0,0 +1,148 @@+#pragma once+// MongoDBAdapter — maps MongoDB document store into the relational+// DatabaseAdapter interface so the sidebar, data grid, and query editor+// can treat MongoDB like any other database engine.+//+// Virtual schema mapping:+// • listDatabases() → server database list+// • listSchemas() → single item = current database name+// • listTables() → collection names within database+// • describeTable() → sample N documents, union top-level fields+// • fetchRows() → find() with skip/limit, flatten docs to columns+// • execute() → parse pseudo-shell syntax: db.coll.method({json})+//+// mongocxx is already RAII (client, database, cursor), so no custom+// deleters needed (unlike hiredis in RedisAdapter).++#include "DatabaseAdapter.h"+#include <memory>+#include <string>+#include <vector>+#include <unordered_map>++// Forward-declare mongocxx types to keep this header lightweight.+// The implementation files include the actual mongocxx headers.+namespace mongocxx { inline namespace v_noabi {+ class instance;+ class client;+ class database;+ class client_session;+}}++namespace DBModels+{+ class MongoDBAdapter : public DatabaseAdapter+ {+ public:+ MongoDBAdapter();+ ~MongoDBAdapter() override;++ // ── Connection ──────────────────────────────+ void connect(const ConnectionConfig& config, const std::wstring& password) override;+ void disconnect() override;+ bool testConnection(const ConnectionConfig& config, const std::wstring& password) override;+ bool isConnected() const override;++ // ── Query Execution ─────────────────────────+ // Accepts pseudo-shell syntax: db.collection.method({json})+ // Supported methods: find, insertOne, updateOne, deleteOne, aggregate, count+ // Fallback: raw runCommand JSON+ QueryResult execute(const std::wstring& sql) override;+ QueryResult fetchRows(+ const std::wstring& table, const std::wstring& schema,+ int limit, int offset,+ const std::wstring& orderBy, bool ascending) override;++ // ── Schema Inspection ───────────────────────+ std::vector<std::wstring> listDatabases() override;+ std::vector<std::wstring> listSchemas() override;+ std::vector<TableInfo> listTables(const std::wstring& schema) override;+ std::vector<TableInfo> listViews(const std::wstring& schema) override;+ std::vector<ColumnInfo> describeTable(+ const std::wstring& table, const std::wstring& schema) override;+ std::vector<IndexInfo> listIndexes(+ const std::wstring& table, const std::wstring& schema) override;+ std::vector<ForeignKeyInfo> listForeignKeys(+ const std::wstring& table, const std::wstring& schema) override;+ std::vector<std::wstring> listFunctions(const std::wstring& schema) override;+ std::wstring getFunctionSource(+ const std::wstring& name, const std::wstring& schema) override;+ std::wstring getCreateTableSQL(+ const std::wstring& table, const std::wstring& schema) override;++ // ── Data Manipulation ───────────────────────+ QueryResult insertRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& values) override;+ QueryResult updateRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& setValues, const TableRow& whereValues) override;+ QueryResult deleteRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& whereValues) override;++ // ── Transactions (MongoDB 4.0+ replica set) ─+ void beginTransaction() override;+ void commitTransaction() override;+ void rollbackTransaction() override;++ // ── Server Info ─────────────────────────────+ std::wstring serverVersion() override;+ std::wstring currentDatabase() override;++ private:+ // mongocxx instance must outlive all other driver objects.+ // Shared across all MongoDBAdapter instances via static init.+ static void ensureInstance();++ // Owned driver objects+ std::unique_ptr<mongocxx::client> client_;+ std::string currentDbName_;+ ConnectionConfig lastConfig_;+ std::wstring lastPassword_;+ bool connected_ = false;++ // Active transaction session (nullptr when no transaction)+ std::unique_ptr<mongocxx::client_session> session_;++ // ── Schema cache ────────────────────────────+ // Cache sampled column info per collection to avoid re-scanning+ // on every describeTable call. Cleared on disconnect.+ std::unordered_map<std::string, std::vector<ColumnInfo>> schemaCache_;++ // ── Private helpers ─────────────────────────+ // Build a mongocxx::uri string from config fields (host/port/user/pass/db)+ std::string buildUriString(const ConnectionConfig& config,+ const std::wstring& password);+ // Get database object for a given schema name+ mongocxx::database getDatabase(const std::wstring& schema);+ // Sample N documents from a collection and infer field types+ std::vector<ColumnInfo> sampleFields(const std::wstring& collection,+ const std::wstring& schema,+ int sampleSize = 100);+ // Map BSON type code to human-readable type name+ static std::wstring bsonTypeName(int bsonType);+ // Flatten a BSON document's top-level fields into a TableRow+ static TableRow flattenDocument(const void* bsonView,+ const std::vector<ColumnInfo>& columns);++ // ── Parse helpers for execute() ─────────────+ // Parse "db.collection.method({json})" → (collection, method, jsonArg)+ struct ParsedCommand+ {+ std::string collection;+ std::string method;+ std::string jsonArg;+ };+ static bool parseShellCommand(const std::string& input, ParsedCommand& out);++ // Execute a parsed command and return result+ QueryResult executeCommand(const ParsedCommand& cmd);+ // Execute raw runCommand JSON+ QueryResult executeRunCommand(const std::string& json);++ // ── UTF-8 helpers ───────────────────────────+ static std::string toUtf8(const std::wstring& s);+ static std::wstring fromUtf8(const std::string& s);+ };+}diff --git a/windows/Gridex/Models/MySQLAdapter.h b/windows/Gridex/Models/MySQLAdapter.hnew file mode 100644index 0000000..dbd5bee--- /dev/null+++ b/windows/Gridex/Models/MySQLAdapter.h@@ -0,0 +1,78 @@+#pragma once+#include "DatabaseAdapter.h"+#include <string>++// Forward declare MariaDB/MySQL C API types+struct st_mysql;+typedef struct st_mysql MYSQL;++namespace DBModels+{+ class MySQLAdapter : public DatabaseAdapter+ {+ public:+ MySQLAdapter();+ ~MySQLAdapter() override;++ // Connection+ void connect(const ConnectionConfig& config, const std::wstring& password) override;+ void disconnect() override;+ bool testConnection(const ConnectionConfig& config, const std::wstring& password) override;+ bool isConnected() const override;++ // Query Execution+ QueryResult execute(const std::wstring& sql) override;+ QueryResult fetchRows(+ const std::wstring& table, const std::wstring& schema,+ int limit, int offset,+ const std::wstring& orderBy, bool ascending) override;++ // Schema Inspection+ std::vector<std::wstring> listDatabases() override;+ std::vector<std::wstring> listSchemas() override;+ std::vector<TableInfo> listTables(const std::wstring& schema) override;+ std::vector<TableInfo> listViews(const std::wstring& schema) override;+ std::vector<ColumnInfo> describeTable(+ const std::wstring& table, const std::wstring& schema) override;+ std::vector<IndexInfo> listIndexes(+ const std::wstring& table, const std::wstring& schema) override;+ std::vector<ForeignKeyInfo> listForeignKeys(+ const std::wstring& table, const std::wstring& schema) override;+ std::vector<std::wstring> listFunctions(const std::wstring& schema) override;+ std::wstring getFunctionSource(+ const std::wstring& name, const std::wstring& schema) override;+ std::wstring getCreateTableSQL(+ const std::wstring& table, const std::wstring& schema) override;++ // Data Manipulation+ QueryResult insertRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& values) override;+ QueryResult updateRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& setValues, const TableRow& whereValues) override;+ QueryResult deleteRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& whereValues) override;++ // Transactions+ void beginTransaction() override;+ void commitTransaction() override;+ void rollbackTransaction() override;++ // Server Info+ std::wstring serverVersion() override;+ std::wstring currentDatabase() override;++ private:+ MYSQL* conn_ = nullptr;+ bool connected_ = false;++ static std::string toUtf8(const std::wstring& wstr);+ static std::wstring fromUtf8(const std::string& str);+ static std::string quoteIdentifier(const std::wstring& name);+ static std::string quoteLiteral(const std::wstring& value);+ void ensureConnected() const;+ QueryResult executeInternal(const std::string& sql);+ };+}diff --git a/windows/Gridex/Models/PostgreSQLAdapter.h b/windows/Gridex/Models/PostgreSQLAdapter.hnew file mode 100644index 0000000..2b0e8cd--- /dev/null+++ b/windows/Gridex/Models/PostgreSQLAdapter.h@@ -0,0 +1,84 @@+#pragma once+#include "DatabaseAdapter.h"+#include <string>++// Forward declare libpq types to avoid including libpq-fe.h in header+struct pg_conn;+typedef struct pg_conn PGconn;++namespace DBModels+{+ class PostgreSQLAdapter : public DatabaseAdapter+ {+ public:+ PostgreSQLAdapter();+ ~PostgreSQLAdapter() override;++ // ── Connection ──────────────────────────────+ void connect(const ConnectionConfig& config, const std::wstring& password) override;+ void disconnect() override;+ bool testConnection(const ConnectionConfig& config, const std::wstring& password) override;+ bool isConnected() const override;++ // ── Query Execution ─────────────────────────+ QueryResult execute(const std::wstring& sql) override;+ QueryResult fetchRows(+ const std::wstring& table, const std::wstring& schema,+ int limit, int offset,+ const std::wstring& orderBy, bool ascending) override;++ // ── Schema Inspection ───────────────────────+ std::vector<std::wstring> listDatabases() override;+ std::vector<std::wstring> listSchemas() override;+ std::vector<TableInfo> listTables(const std::wstring& schema) override;+ std::vector<TableInfo> listViews(const std::wstring& schema) override;+ std::vector<ColumnInfo> describeTable(+ const std::wstring& table, const std::wstring& schema) override;+ std::vector<IndexInfo> listIndexes(+ const std::wstring& table, const std::wstring& schema) override;+ std::vector<ForeignKeyInfo> listForeignKeys(+ const std::wstring& table, const std::wstring& schema) override;+ std::vector<std::wstring> listFunctions(const std::wstring& schema) override;+ std::wstring getFunctionSource(+ const std::wstring& name, const std::wstring& schema) override;+ std::wstring getCreateTableSQL(+ const std::wstring& table, const std::wstring& schema) override;++ // ── Data Manipulation ───────────────────────+ QueryResult insertRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& values) override;+ QueryResult updateRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& setValues, const TableRow& whereValues) override;+ QueryResult deleteRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& whereValues) override;++ // ── Transactions ────────────────────────────+ void beginTransaction() override;+ void commitTransaction() override;+ void rollbackTransaction() override;++ // ── Server Info ─────────────────────────────+ std::wstring serverVersion() override;+ std::wstring currentDatabase() override;++ private:+ PGconn* conn_ = nullptr;+ bool connected_ = false;++ // Helper: convert wstring to UTF-8 for libpq+ static std::string toUtf8(const std::wstring& wstr);+ // Helper: convert UTF-8 to wstring+ static std::wstring fromUtf8(const std::string& str);+ // Helper: quote identifier (double-quotes)+ static std::string quoteIdentifier(const std::wstring& name);+ // Helper: quote literal (single-quotes with escaping)+ static std::string quoteLiteral(const std::wstring& value);+ // Helper: ensure connected, throw if not+ void ensureConnected() const;+ // Helper: execute a query and return result, throw on error+ QueryResult executeInternal(const std::string& sql);+ };+}diff --git a/windows/Gridex/Models/QueryParameter.h b/windows/Gridex/Models/QueryParameter.hnew file mode 100644index 0000000..01993f7--- /dev/null+++ b/windows/Gridex/Models/QueryParameter.h@@ -0,0 +1,12 @@+#pragma once+#include <string>+#include "RowValue.h"++namespace DBModels+{+ struct QueryParameter+ {+ std::wstring name;+ RowValue value;+ };+}diff --git a/windows/Gridex/Models/QueryResult.h b/windows/Gridex/Models/QueryResult.hnew file mode 100644index 0000000..f3db964--- /dev/null+++ b/windows/Gridex/Models/QueryResult.h@@ -0,0 +1,30 @@+#pragma once+#include <string>+#include <vector>+#include "ColumnInfo.h"+#include "TableRow.h"++namespace DBModels+{+ struct QueryResult+ {+ std::vector<std::wstring> columnNames;+ std::vector<std::wstring> columnTypes;+ std::vector<TableRow> rows;+ int totalRows = 0;+ int currentPage = 1;+ int pageSize = 100;+ // Wall-clock of the blocking driver call (PQexec / mysql_real_query).+ // Includes SQL send, server execution, and result byte transfer.+ double executionTimeMs = 0.0;+ std::wstring error;+ std::wstring sql;+ bool success = true;++ int totalPages() const+ {+ if (pageSize <= 0) return 1;+ return (totalRows + pageSize - 1) / pageSize;+ }+ };+}diff --git a/windows/Gridex/Models/RedisAdapter.h b/windows/Gridex/Models/RedisAdapter.hnew file mode 100644index 0000000..e2d96cf--- /dev/null+++ b/windows/Gridex/Models/RedisAdapter.h@@ -0,0 +1,152 @@+#pragma once+// RedisAdapter — maps Redis key-value store into the relational DatabaseAdapter+// interface so the rest of the app (sidebar, data grid, query editor) can treat+// Redis like any other database engine.+//+// Virtual schema:+// • schemas = "db0".."db15" (Redis logical databases)+// • each schema has one table named "Keys"+// • columns: key, type, value, ttl+// • SCAN-based pagination in fetchRows()+// • execute() accepts raw Redis commands (space-separated, with quoted strings)+//+// Hiredis safety wrappers (addresses the weak points of the C API):+// • RAII via unique_ptr with custom deleters → no manual freeReplyObject leaks+// • Auto-reconnect: ensureConnected() rebuilds context if disconnected+// • Binary-safe: all commands sent via redisCommandArgv() with explicit lengths+// so user input cannot inject format specifiers+// • Type-safe reply helpers throw DatabaseError on REDIS_REPLY_ERROR++#include "DatabaseAdapter.h"+#include <memory>+#include <string>+#include <vector>++// Forward declare hiredis types so the public header doesn't pull in <hiredis/hiredis.h>+struct redisContext;+struct redisReply;++namespace DBModels+{+ // ── RAII wrappers ────────────────────────────────────────────+ // Custom deleters use C linkage but we wrap them in lambdas/free+ // functions invoked by unique_ptr's deleter type to avoid pulling+ // in the hiredis headers here.+ struct RedisContextDeleter { void operator()(redisContext* ctx) const noexcept; };+ struct RedisReplyDeleter { void operator()(redisReply* reply) const noexcept; };++ using RedisContextPtr = std::unique_ptr<redisContext, RedisContextDeleter>;+ using RedisReplyPtr = std::unique_ptr<redisReply, RedisReplyDeleter>;++ class RedisAdapter : public DatabaseAdapter+ {+ public:+ RedisAdapter();+ ~RedisAdapter() override;++ // ── Connection ──────────────────────────────+ void connect(const ConnectionConfig& config, const std::wstring& password) override;+ void disconnect() override;+ bool testConnection(const ConnectionConfig& config, const std::wstring& password) override;+ bool isConnected() const override;++ // ── Query Execution ─────────────────────────+ // Accepts a raw Redis command line (e.g. "SET foo bar", "HGETALL myhash").+ QueryResult execute(const std::wstring& sql) override;+ QueryResult fetchRows(+ const std::wstring& table, const std::wstring& schema,+ int limit, int offset,+ const std::wstring& orderBy, bool ascending) override;++ // ── Schema Inspection ───────────────────────+ std::vector<std::wstring> listDatabases() override;+ std::vector<std::wstring> listSchemas() override;+ std::vector<TableInfo> listTables(const std::wstring& schema) override;+ std::vector<TableInfo> listViews(const std::wstring& schema) override;+ std::vector<ColumnInfo> describeTable(+ const std::wstring& table, const std::wstring& schema) override;+ std::vector<IndexInfo> listIndexes(+ const std::wstring& table, const std::wstring& schema) override;+ std::vector<ForeignKeyInfo> listForeignKeys(+ const std::wstring& table, const std::wstring& schema) override;+ std::vector<std::wstring> listFunctions(const std::wstring& schema) override;+ std::wstring getFunctionSource(+ const std::wstring& name, const std::wstring& schema) override;+ std::wstring getCreateTableSQL(+ const std::wstring& table, const std::wstring& schema) override;++ // ── Data Manipulation ───────────────────────+ // insertRow expects "key" + "value" cells. type defaults to string if missing.+ QueryResult insertRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& values) override;+ // updateRow: when WHERE has key, supports updating value (SET) or ttl (EXPIRE/PERSIST).+ QueryResult updateRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& setValues, const TableRow& whereValues) override;+ // deleteRow: WHERE must contain "key" — issues DEL.+ QueryResult deleteRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& whereValues) override;++ // ── Transactions (Redis MULTI/EXEC/DISCARD) ─+ void beginTransaction() override;+ void commitTransaction() override;+ void rollbackTransaction() override;++ // ── Server Info ─────────────────────────────+ std::wstring serverVersion() override;+ std::wstring currentDatabase() override;++ // SCAN MATCH pattern for the next fetchRows call. Empty / "*" = all keys.+ void setSearchPattern(const std::wstring& pattern) override;++ private:+ // Cached connection context — null when disconnected+ RedisContextPtr context_;+ // Last config + password used so ensureConnected() can rebuild on failure+ ConnectionConfig lastConfig_;+ std::wstring lastPassword_;+ // Currently selected logical DB (0-15 typically)+ int currentDb_ = 0;+ // Active SCAN MATCH pattern. "*" matches all keys.+ std::string searchPattern_ = "*";++ // ── Private helpers ─────────────────────────+ // Build a fresh context (open TCP, AUTH, SELECT db, optionally TLS).+ // Throws DatabaseError on failure.+ RedisContextPtr buildContext(const ConnectionConfig& config,+ const std::wstring& password);+ // Verify context is alive; if not, rebuild from lastConfig_/lastPassword_.+ void ensureConnected();+ // Send a command via redisCommandArgv (binary-safe, no printf injection).+ // Returns owned reply or throws on connection/error reply.+ RedisReplyPtr sendArgv(const std::vector<std::string>& argv);+ // Convenience overload for variable arg count+ RedisReplyPtr sendCommand(std::initializer_list<std::string> args);+ // Pipeline a batch of commands: append all, then drain replies. Returns+ // one owned reply per input command, in order. Reduces N round-trips+ // to 1 (or 2 with the trailing flush). Throws on connection failure;+ // individual REDIS_REPLY_ERROR replies are returned untouched so the+ // caller can decide what to do per command.+ std::vector<RedisReplyPtr> pipelineArgv(+ const std::vector<std::vector<std::string>>& commands);+ // Throw if reply is null or REDIS_REPLY_ERROR+ void checkReply(redisReply* reply, const char* commandHint);++ // Parse a "SELECT n" embedded in fetchRows schema name like "db5"+ static int parseDbFromSchema(const std::wstring& schema);+ // Tokenize a command line, respecting double / single quotes+ static std::vector<std::string> tokenizeCommand(const std::wstring& sql);+ // Format a list/set/zset/hash reply into a single preview string+ static std::wstring formatPreview(redisReply* reply);+ // Convert reply to wstring (for cells / single value display)+ static std::wstring replyToWString(redisReply* reply);+ // Build a QueryResult from one or more rows we already filled+ static QueryResult makeKeysResult(+ const std::vector<TableRow>& rows, double elapsedMs);++ static std::string toUtf8(const std::wstring& s);+ static std::wstring fromUtf8(const std::string& s);+ };+}diff --git a/windows/Gridex/Models/RowValue.h b/windows/Gridex/Models/RowValue.hnew file mode 100644index 0000000..7d9870c--- /dev/null+++ b/windows/Gridex/Models/RowValue.h@@ -0,0 +1,34 @@+#pragma once+#include <string>+#include <optional>++namespace DBModels+{+ enum class ValueType+ {+ String, Integer, Float, Boolean, Null, Binary, Json, Date, Timestamp+ };++ struct RowValue+ {+ std::wstring text;+ ValueType type = ValueType::String;+ bool isNull = false;++ RowValue() : isNull(true), type(ValueType::Null) {}+ RowValue(const std::wstring& val) : text(val), type(ValueType::String), isNull(false) {}+ RowValue(const std::wstring& val, ValueType t) : text(val), type(t), isNull(false) {}++ static RowValue null() { return RowValue(); }+ static RowValue fromString(const std::wstring& val) { return RowValue(val); }+ static RowValue fromInt(int64_t val) { return RowValue(std::to_wstring(val), ValueType::Integer); }+ static RowValue fromDouble(double val) { return RowValue(std::to_wstring(val), ValueType::Float); }+ static RowValue fromBool(bool val) { return RowValue(val ? L"true" : L"false", ValueType::Boolean); }++ std::wstring displayValue() const+ {+ if (isNull) return L"NULL";+ return text;+ }+ };+}diff --git a/windows/Gridex/Models/SQLiteAdapter.h b/windows/Gridex/Models/SQLiteAdapter.hnew file mode 100644index 0000000..2bd65bf--- /dev/null+++ b/windows/Gridex/Models/SQLiteAdapter.h@@ -0,0 +1,78 @@+#pragma once+#include "DatabaseAdapter.h"+#include <string>++// Forward declare sqlite3 types+struct sqlite3;++namespace DBModels+{+ class SQLiteAdapter : public DatabaseAdapter+ {+ public:+ SQLiteAdapter();+ ~SQLiteAdapter() override;++ // Connection+ void connect(const ConnectionConfig& config, const std::wstring& password) override;+ void disconnect() override;+ bool testConnection(const ConnectionConfig& config, const std::wstring& password) override;+ bool isConnected() const override;++ // Query Execution+ QueryResult execute(const std::wstring& sql) override;+ QueryResult fetchRows(+ const std::wstring& table, const std::wstring& schema,+ int limit, int offset,+ const std::wstring& orderBy, bool ascending) override;++ // Schema Inspection+ std::vector<std::wstring> listDatabases() override;+ std::vector<std::wstring> listSchemas() override;+ std::vector<TableInfo> listTables(const std::wstring& schema) override;+ std::vector<TableInfo> listViews(const std::wstring& schema) override;+ std::vector<ColumnInfo> describeTable(+ const std::wstring& table, const std::wstring& schema) override;+ std::vector<IndexInfo> listIndexes(+ const std::wstring& table, const std::wstring& schema) override;+ std::vector<ForeignKeyInfo> listForeignKeys(+ const std::wstring& table, const std::wstring& schema) override;+ std::vector<std::wstring> listFunctions(const std::wstring& schema) override;+ std::wstring getFunctionSource(+ const std::wstring& name, const std::wstring& schema) override;+ std::wstring getCreateTableSQL(+ const std::wstring& table, const std::wstring& schema) override;++ // Data Manipulation+ QueryResult insertRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& values) override;+ QueryResult updateRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& setValues, const TableRow& whereValues) override;+ QueryResult deleteRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& whereValues) override;++ // Transactions+ void beginTransaction() override;+ void commitTransaction() override;+ void rollbackTransaction() override;++ // Server Info+ std::wstring serverVersion() override;+ std::wstring currentDatabase() override;++ private:+ sqlite3* db_ = nullptr;+ bool connected_ = false;+ std::wstring filePath_;++ static std::string toUtf8(const std::wstring& wstr);+ static std::wstring fromUtf8(const std::string& str);+ static std::string quoteIdentifier(const std::wstring& name);+ static std::string quoteLiteral(const std::wstring& value);+ void ensureConnected() const;+ QueryResult executeInternal(const std::string& sql);+ };+}diff --git a/windows/Gridex/Models/SSHTunnelService.h b/windows/Gridex/Models/SSHTunnelService.hnew file mode 100644index 0000000..342f77f--- /dev/null+++ b/windows/Gridex/Models/SSHTunnelService.h@@ -0,0 +1,62 @@+#pragma once+// SSHTunnelService — local port forwarding via libssh2.+//+// Creates a TCP listener on localhost:<freePort> and forwards all+// incoming connections through an SSH tunnel to remoteHost:remotePort.+// The DB adapter then connects to localhost:<freePort> instead of+// the remote database host directly.+//+// Lifecycle:+// 1. establish(config, remoteHost, remotePort) → returns localPort+// 2. DB adapter connects to 127.0.0.1:localPort+// 3. close() tears down tunnel + SSH session+//+// Auth: password and private-key (PEM/OpenSSH format).+// Thread: tunnel runs a forwarding loop on a background std::thread.++#include "ConnectionConfig.h"+#include <string>+#include <thread>+#include <atomic>+#include <cstdint>++// Forward-declare libssh2 types+typedef struct _LIBSSH2_SESSION LIBSSH2_SESSION;++namespace DBModels+{+ class SSHTunnelService+ {+ public:+ SSHTunnelService();+ ~SSHTunnelService();++ // Open SSH tunnel. Returns the local port to connect DB to.+ // Throws DatabaseError on failure.+ uint16_t establish(+ const SSHTunnelConfig& config,+ const std::wstring& sshPassword,+ const std::string& remoteHost,+ int remotePort);++ // Close tunnel and free resources.+ void close();++ bool isActive() const { return active_.load(); }+ uint16_t localPort() const { return localPort_; }++ private:+ LIBSSH2_SESSION* session_ = nullptr;+ uintptr_t sshSock_ = ~0ULL; // SOCKET (INVALID_SOCKET)+ uintptr_t listenSock_ = ~0ULL;+ uint16_t localPort_ = 0;+ std::string remoteHost_;+ int remotePort_ = 0;+ std::atomic<bool> active_{false};+ std::thread forwardThread_;++ void forwardLoop();+ static uint16_t findFreePort();+ static std::string toUtf8(const std::wstring& s);+ };+}diff --git a/windows/Gridex/Models/SidebarItem.h b/windows/Gridex/Models/SidebarItem.hnew file mode 100644index 0000000..df45180--- /dev/null+++ b/windows/Gridex/Models/SidebarItem.h@@ -0,0 +1,42 @@+#pragma once+#include <string>+#include <vector>+#include <memory>++namespace DBModels+{+ enum class SidebarItemType+ {+ Connection, Database, Schema, Group,+ Table, View, MaterializedView, Function, EnumType+ };++ struct SidebarItem+ {+ std::wstring id;+ std::wstring title;+ SidebarItemType type;+ std::wstring icon; // Segoe Fluent Icons glyph+ std::vector<SidebarItem> children;+ bool isExpanded = false;+ int count = 0; // badge count for groups+ std::wstring schema; // parent schema name+ };++ // Icon glyphs for sidebar items+ inline std::wstring SidebarItemIcon(SidebarItemType type)+ {+ switch (type)+ {+ case SidebarItemType::Database: return L"\xE968"; // Database+ case SidebarItemType::Schema: return L"\xE8B7"; // Folder+ case SidebarItemType::Group: return L"\xE8B7"; // Folder+ case SidebarItemType::Table: return L"\xE80A"; // Table+ case SidebarItemType::View: return L"\xE7B3"; // Eye+ case SidebarItemType::MaterializedView: return L"\xE7B3";+ case SidebarItemType::Function: return L"\xE943"; // Code+ case SidebarItemType::EnumType: return L"\xE8FD"; // List+ default: return L"\xE8B7";+ }+ }+}diff --git a/windows/Gridex/Models/TableInfo.h b/windows/Gridex/Models/TableInfo.hnew file mode 100644index 0000000..521e9bd--- /dev/null+++ b/windows/Gridex/Models/TableInfo.h@@ -0,0 +1,16 @@+#pragma once+#include <string>++namespace DBModels+{+ struct TableInfo+ {+ std::wstring name;+ std::wstring schema;+ std::wstring type; // "table", "view", "materialized_view"+ std::wstring owner;+ int64_t estimatedRows = 0;+ int64_t sizeBytes = 0;+ std::wstring comment;+ };+}diff --git a/windows/Gridex/Models/TableRow.h b/windows/Gridex/Models/TableRow.hnew file mode 100644index 0000000..988a3ca--- /dev/null+++ b/windows/Gridex/Models/TableRow.h@@ -0,0 +1,38 @@+#pragma once+#include <string>+#include <vector>+#include <unordered_map>++namespace DBModels+{+ // A single cell value (string representation)+ using CellValue = std::wstring;++ // A row is a map of column name -> value+ using TableRow = std::unordered_map<std::wstring, CellValue>;++ // ── SQL NULL sentinel ───────────────────────────────+ //+ // TableRow values are wstrings, which can't naturally distinguish a SQL+ // NULL from a literal string "NULL" typed into a varchar cell. Adapters+ // emit `nullValue()` for SQL NULL — a sentinel containing control chars+ // that user input cannot produce — and consumers test with `isNullCell()`+ // before deciding whether to render "NULL" / emit IS NULL / write JSON null.+ //+ // Display formatting (DataGridView, ExportService, ChangeTracker) maps the+ // sentinel back to the visible string "NULL" so the UI/SQL output looks+ // the same as before. The difference: a user who types the literal text+ // "NULL" now gets a real string, not a NULL.+ inline constexpr const wchar_t* kNullMarker = L"\x01\x02__GRIDEX_NULL__\x02\x01";++ inline const std::wstring& nullValue()+ {+ static const std::wstring v{ kNullMarker };+ return v;+ }++ inline bool isNullCell(const std::wstring& v)+ {+ return v == kNullMarker;+ }+}diff --git a/windows/Gridex/Models/WorkspaceState.h b/windows/Gridex/Models/WorkspaceState.hnew file mode 100644index 0000000..181f098--- /dev/null+++ b/windows/Gridex/Models/WorkspaceState.h@@ -0,0 +1,48 @@+#pragma once+#include <string>+#include <vector>+#include <optional>+#include "ContentTab.h"+#include "SidebarItem.h"+#include "ColumnInfo.h"+#include "QueryResult.h"+#include "ConnectionConfig.h"++namespace DBModels+{+ struct WorkspaceState+ {+ ConnectionConfig connection;+ std::vector<ContentTab> tabs;+ std::wstring activeTabId;+ std::vector<SidebarItem> sidebarItems;+ bool sidebarVisible = true;+ bool detailsPanelVisible = true;++ // Status bar. Two-way split so a slow UI build on a wide table+ // does not get mis-attributed to a slow SQL query:+ // Exec = driver blocking call wall-clock (SQL send, server+ // execution, result bytes delivered to the client).+ // Render = DataGridView::SetData cost on the UI thread+ // (StackPanel + TextBlock construction).+ std::wstring statusConnection;+ std::wstring statusSchema;+ int statusRowCount = 0;+ double statusQueryTimeMs = 0.0; // Exec (driver wall-clock)+ double statusRenderTimeMs = 0.0; // Render (UI build)++ // Current view data (for active tab)+ QueryResult currentData;+ std::vector<ColumnInfo> currentColumns;+ std::vector<IndexInfo> currentIndexes;+ std::vector<ForeignKeyInfo> currentForeignKeys;+ std::vector<ConstraintInfo> currentConstraints;++ // Pagination+ int currentPage = 0;+ int pageSize = 100;++ // Selected row details+ std::optional<int> selectedRowIndex;+ };+}diff --git a/windows/Gridex/MongoDBAdapter.cpp b/windows/Gridex/MongoDBAdapter.cppnew file mode 100644index 0000000..92e8fda--- /dev/null+++ b/windows/Gridex/MongoDBAdapter.cpp@@ -0,0 +1,512 @@+// MongoDBAdapter.cpp — connection lifecycle, schema inspection, server info.+//+// Query execution and CRUD operations are in MongoDBAdapterQuery.cpp+// to keep each file under 200 lines per project modularization rules.++// NOMINMAX prevents <windows.h> from defining min/max macros that collide+// with std::numeric_limits::max() used inside bsoncxx/mongocxx headers.+#ifndef NOMINMAX+#define NOMINMAX+#endif+#include <windows.h>+#include "Models/MongoDBAdapter.h"++#include <mongocxx/instance.hpp>+#include <mongocxx/client.hpp>+#include <mongocxx/database.hpp>+#include <mongocxx/uri.hpp>+#include <bsoncxx/builder/basic/document.hpp>+#include <bsoncxx/builder/basic/kvp.hpp>+#include <bsoncxx/json.hpp>+#include <bsoncxx/types.hpp>++#include <algorithm>+#include <chrono>+#include <iomanip>+#include <mutex>+#include <set>+#include <sstream>++namespace DBModels+{+ using bsoncxx::builder::basic::kvp;+ using bsoncxx::builder::basic::make_document;++ // ── Static instance (singleton, required by mongocxx) ─────+ static std::once_flag s_instanceFlag;+ static std::unique_ptr<mongocxx::instance> s_instance;++ void MongoDBAdapter::ensureInstance()+ {+ std::call_once(s_instanceFlag, []() {+ s_instance = std::make_unique<mongocxx::instance>();+ });+ }++ // ── ctor / dtor ───────────────────────────────────────────+ MongoDBAdapter::MongoDBAdapter() { ensureInstance(); }+ MongoDBAdapter::~MongoDBAdapter() { disconnect(); }++ // ── UTF-8 helpers ─────────────────────────────────────────+ std::string MongoDBAdapter::toUtf8(const std::wstring& s)+ {+ if (s.empty()) return {};+ int sz = WideCharToMultiByte(CP_UTF8, 0, s.c_str(),+ static_cast<int>(s.size()), nullptr, 0, nullptr, nullptr);+ std::string out(sz, '\0');+ WideCharToMultiByte(CP_UTF8, 0, s.c_str(),+ static_cast<int>(s.size()), &out[0], sz, nullptr, nullptr);+ return out;+ }++ std::wstring MongoDBAdapter::fromUtf8(const std::string& s)+ {+ if (s.empty()) return {};+ int sz = MultiByteToWideChar(CP_UTF8, 0, s.c_str(),+ static_cast<int>(s.size()), nullptr, 0);+ std::wstring out(sz, L'\0');+ MultiByteToWideChar(CP_UTF8, 0, s.c_str(),+ static_cast<int>(s.size()), &out[0], sz);+ return out;+ }++ // ── URI builder ───────────────────────────────────────────+ std::string MongoDBAdapter::buildUriString(+ const ConnectionConfig& config, const std::wstring& password)+ {+ // If user provided a full URI, use it — but ensure it has a+ // /database path. libmongoc's URI parser stores the database+ // field as a raw C string that is NULL when no path segment is+ // present, and downstream code calls strlen(NULL) → crash.+ // Append "/test" (MongoDB's default DB) when the URI has no+ // path after the host:port authority section.+ if (!config.connectionUri.empty())+ {+ auto raw = toUtf8(config.connectionUri);++ // Find the authority end: after "mongodb://" or "mongodb+srv://",+ // skip past user:pass@host:port. The first '/' after the+ // authority is the database path. If there's no '/' after the+ // scheme's "://", the URI has no database → append "/test".+ // Also handle "...host:port?" (query params, no path).+ auto schemeEnd = raw.find("://");+ if (schemeEnd != std::string::npos)+ {+ auto afterScheme = schemeEnd + 3; // skip "://"+ auto slashPos = raw.find('/', afterScheme);+ auto queryPos = raw.find('?', afterScheme);++ if (slashPos == std::string::npos)+ {+ // No /database at all — insert "/test" before query+ if (queryPos != std::string::npos)+ raw.insert(queryPos, "/test");+ else+ raw += "/test";+ }+ else if (slashPos + 1 == raw.size() ||+ slashPos + 1 == queryPos)+ {+ // Trailing "/" with no database name (e.g. "...host:27017/")+ raw.insert(slashPos + 1, "test");+ }+ }+ return raw;+ }++ // Build mongodb://user:pass@host:port/db+ // URL-encode user/pass so special chars (@, :, /, %) don't break the URI.+ auto urlEncode = [](const std::string& s) -> std::string {+ std::ostringstream enc;+ for (unsigned char c : s)+ {+ if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~')+ enc << c;+ else+ {+ enc << '%' << std::uppercase;+ enc << std::hex << std::setw(2) << std::setfill('0') << (int)c;+ }+ }+ return enc.str();+ };++ std::ostringstream uri;+ uri << "mongodb://";+ auto user = toUtf8(config.username);+ auto pass = toUtf8(password);+ if (!user.empty())+ {+ uri << urlEncode(user);+ if (!pass.empty()) uri << ":" << urlEncode(pass);+ uri << "@";+ }+ auto host = toUtf8(config.host.empty() ? L"127.0.0.1" : config.host);+ uri << host << ":" << (config.port > 0 ? config.port : 27017);++ // ALWAYS include a /database path in the URI. libmongoc's URI+ // parser stores the database field as a raw C string that may+ // be NULL when no path is present. Downstream code (e.g.+ // mongoc_uri_get_database) then passes NULL to strlen and+ // crashes with an access violation. Using "test" (MongoDB's+ // default database) avoids the null and matches the server's+ // own fallback when no database is specified.+ auto db = toUtf8(config.database);+ uri << "/" << (db.empty() ? "test" : db);++ // Append URI query options (authSource, replicaSet, tls, etc.)+ // entered in the "Options" form field. User types key=val pairs+ // separated by & — we prepend ? and attach.+ auto opts = toUtf8(config.mongoOptions);+ if (!opts.empty())+ {+ // Strip leading ? or & if user accidentally included it+ if (opts.front() == '?' || opts.front() == '&')+ opts = opts.substr(1);+ if (!opts.empty())+ uri << "?" << opts;+ }+ return uri.str();+ }++ // ── Connection lifecycle ──────────────────────────────────+ void MongoDBAdapter::connect(+ const ConnectionConfig& config, const std::wstring& password)+ {+ disconnect();+ lastConfig_ = config;+ lastPassword_ = password;++ try+ {+ auto uriStr = buildUriString(config, password);+ mongocxx::uri uri{uriStr};+ client_ = std::make_unique<mongocxx::client>(uri);++ // Determine database name from (in priority order):+ // 1. config.database form field+ // 2. URI path segment (parsed manually — mongocxx::uri::database()+ // can return empty due to ABI mismatch in Debug builds)+ // 3. fallback "test"+ currentDbName_ = toUtf8(config.database);+ if (currentDbName_.empty())+ {+ // Manual parse: extract /database from URI string.+ // URI format: mongodb://[user:pass@]host[:port]/DATABASE[?opts]+ auto schemeEnd = uriStr.find("://");+ if (schemeEnd != std::string::npos)+ {+ auto afterScheme = schemeEnd + 3;+ auto slashPos = uriStr.find('/', afterScheme);+ if (slashPos != std::string::npos && slashPos + 1 < uriStr.size())+ {+ auto dbStart = slashPos + 1;+ auto dbEnd = uriStr.find('?', dbStart);+ auto dbName = (dbEnd != std::string::npos)+ ? uriStr.substr(dbStart, dbEnd - dbStart)+ : uriStr.substr(dbStart);+ if (!dbName.empty())+ currentDbName_ = dbName;+ }+ }+ }+ if (currentDbName_.empty())+ currentDbName_ = "test";++ // Ping to verify connection is alive+ auto db = (*client_)[currentDbName_];+ db.run_command(make_document(kvp("ping", 1)));+ connected_ = true;+ }+ catch (const std::exception& ex)+ {+ client_.reset();+ connected_ = false;+ throw DatabaseError(DatabaseError::Code::ConnectionFailed,+ std::string("MongoDB connection failed: ") + ex.what());+ }+ }++ void MongoDBAdapter::disconnect()+ {+ session_.reset();+ client_.reset();+ connected_ = false;+ schemaCache_.clear();+ }++ bool MongoDBAdapter::testConnection(+ const ConnectionConfig& config, const std::wstring& password)+ {+ try+ {+ auto uriStr = buildUriString(config, password);+ mongocxx::uri uri{uriStr};+ mongocxx::client tempClient{uri};++ auto dbName = toUtf8(config.database);+ if (dbName.empty())+ {+ // Manual parse DB from URI (same logic as connect)+ auto schemeEnd = uriStr.find("://");+ if (schemeEnd != std::string::npos)+ {+ auto afterScheme = schemeEnd + 3;+ auto slashPos = uriStr.find('/', afterScheme);+ if (slashPos != std::string::npos && slashPos + 1 < uriStr.size())+ {+ auto dbStart = slashPos + 1;+ auto dbEnd = uriStr.find('?', dbStart);+ dbName = (dbEnd != std::string::npos)+ ? uriStr.substr(dbStart, dbEnd - dbStart)+ : uriStr.substr(dbStart);+ }+ }+ }+ if (dbName.empty()) dbName = "test";++ auto db = tempClient[dbName];+ db.run_command(make_document(kvp("ping", 1)));+ return true;+ }+ catch (...) { return false; }+ }++ bool MongoDBAdapter::isConnected() const+ {+ return connected_ && client_ != nullptr;+ }++ // ── Helper: get database by schema name ───────────────────+ mongocxx::database MongoDBAdapter::getDatabase(const std::wstring& schema)+ {+ auto name = schema.empty() ? currentDbName_ : toUtf8(schema);+ return (*client_)[name];+ }++ // ── Schema Inspection ─────────────────────────────────────+ std::vector<std::wstring> MongoDBAdapter::listDatabases()+ {+ if (!isConnected())+ throw DatabaseError(DatabaseError::Code::ConnectionFailed, "Not connected");+ auto names = client_->list_database_names();+ std::vector<std::wstring> result;+ result.reserve(names.size());+ for (auto& n : names) result.push_back(fromUtf8(n));+ return result;+ }++ std::vector<std::wstring> MongoDBAdapter::listSchemas()+ {+ // MongoDB has no schema concept between database and collection.+ // Return the current database name as the single "schema".+ return { fromUtf8(currentDbName_) };+ }++ std::vector<TableInfo> MongoDBAdapter::listTables(const std::wstring& schema)+ {+ auto db = getDatabase(schema);+ auto names = db.list_collection_names();+ std::vector<TableInfo> result;+ for (auto& n : names)+ {+ TableInfo t;+ t.name = fromUtf8(n);+ t.type = L"collection";+ result.push_back(t);+ }+ // Sort alphabetically+ std::sort(result.begin(), result.end(),+ [](const TableInfo& a, const TableInfo& b) { return a.name < b.name; });+ return result;+ }++ std::vector<TableInfo> MongoDBAdapter::listViews(const std::wstring& schema)+ {+ // MongoDB views appear in list_collections with type "view"+ auto db = getDatabase(schema);+ auto filter = make_document(kvp("type", "view"));+ auto cursor = db.list_collections(filter.view());+ std::vector<TableInfo> result;+ for (auto& doc : cursor)+ {+ TableInfo t;+ auto nameEl = doc["name"];+ if (nameEl) t.name = fromUtf8(std::string(nameEl.get_string().value));+ t.type = L"view";+ result.push_back(t);+ }+ return result;+ }++ // ── BSON type name mapping ────────────────────────────────+ std::wstring MongoDBAdapter::bsonTypeName(int bsonType)+ {+ // BSON type codes: https://bsonspec.org/spec.html+ switch (bsonType)+ {+ case 1: return L"Double";+ case 2: return L"String";+ case 3: return L"Object";+ case 4: return L"Array";+ case 5: return L"Binary";+ case 7: return L"ObjectId";+ case 8: return L"Boolean";+ case 9: return L"Date";+ case 10: return L"Null";+ case 16: return L"Int32";+ case 18: return L"Int64";+ case 19: return L"Decimal128";+ default: return L"Unknown";+ }+ }++ std::vector<ColumnInfo> MongoDBAdapter::sampleFields(+ const std::wstring& collection, const std::wstring& schema, int sampleSize)+ {+ auto db = getDatabase(schema);+ auto coll = db[toUtf8(collection)];++ // Sample documents to discover field names and types+ mongocxx::v_noabi::options::find opts;+ opts.limit(sampleSize);++ auto cursor = coll.find({}, opts);++ // Track field names in insertion order, and count BSON types per field+ std::vector<std::string> fieldOrder;+ std::set<std::string> fieldSeen;+ // field -> { bsonType -> count }+ std::unordered_map<std::string, std::unordered_map<int, int>> fieldTypeCounts;++ for (auto& doc : cursor)+ {+ for (auto& elem : doc)+ {+ std::string key(elem.key());+ if (fieldSeen.insert(key).second)+ fieldOrder.push_back(key);+ int btype = static_cast<int>(elem.type());+ fieldTypeCounts[key][btype]++;+ }+ }++ // Ensure _id is always first+ auto idIt = std::find(fieldOrder.begin(), fieldOrder.end(), "_id");+ if (idIt != fieldOrder.end() && idIt != fieldOrder.begin())+ {+ fieldOrder.erase(idIt);+ fieldOrder.insert(fieldOrder.begin(), "_id");+ }++ // Build ColumnInfo from sampled data+ std::vector<ColumnInfo> columns;+ for (auto& field : fieldOrder)+ {+ ColumnInfo col;+ col.name = fromUtf8(field);+ col.isPrimaryKey = (field == "_id");+ col.nullable = (field != "_id");++ // Pick the majority BSON type for this field+ auto& counts = fieldTypeCounts[field];+ int maxCount = 0;+ int majorType = 2; // default String+ for (auto& [btype, cnt] : counts)+ {+ if (cnt > maxCount) { maxCount = cnt; majorType = btype; }+ }+ col.dataType = bsonTypeName(majorType);+ columns.push_back(col);+ }++ return columns;+ }++ std::vector<ColumnInfo> MongoDBAdapter::describeTable(+ const std::wstring& table, const std::wstring& schema)+ {+ auto key = toUtf8(schema) + "." + toUtf8(table);+ auto it = schemaCache_.find(key);+ if (it != schemaCache_.end())+ return it->second;++ auto cols = sampleFields(table, schema);+ schemaCache_[key] = cols;+ return cols;+ }++ std::vector<IndexInfo> MongoDBAdapter::listIndexes(+ const std::wstring& table, const std::wstring& schema)+ {+ auto db = getDatabase(schema);+ auto coll = db[toUtf8(table)];+ auto cursor = coll.list_indexes();++ std::vector<IndexInfo> result;+ for (auto& doc : cursor)+ {+ IndexInfo idx;+ if (auto n = doc["name"]) idx.name = fromUtf8(std::string(n.get_string().value));+ idx.isUnique = false;+ if (auto u = doc["unique"]) idx.isUnique = u.get_bool().value;++ // Extract key fields (IndexInfo.columns is comma-separated wstring)+ if (auto keyDoc = doc["key"])+ {+ for (auto& k : keyDoc.get_document().value)+ {+ if (!idx.columns.empty()) idx.columns += L",";+ idx.columns += fromUtf8(std::string(k.key()));+ }+ }+ result.push_back(idx);+ }+ return result;+ }++ std::vector<ForeignKeyInfo> MongoDBAdapter::listForeignKeys(+ const std::wstring&, const std::wstring&)+ {+ return {}; // MongoDB has no foreign key constraints+ }++ std::vector<std::wstring> MongoDBAdapter::listFunctions(const std::wstring&)+ {+ return {}; // MongoDB has no stored functions in the SQL sense+ }++ std::wstring MongoDBAdapter::getFunctionSource(const std::wstring&, const std::wstring&)+ {+ return L"";+ }++ std::wstring MongoDBAdapter::getCreateTableSQL(+ const std::wstring& table, const std::wstring&)+ {+ // Return pseudo-DDL for MongoDB collection creation+ return L"db.createCollection(\"" + table + L"\")";+ }++ // ── Server Info ───────────────────────────────────────────+ std::wstring MongoDBAdapter::serverVersion()+ {+ if (!isConnected()) return L"";+ try+ {+ // Use buildInfo instead of serverStatus — doesn't require admin privileges+ auto db = (*client_)[currentDbName_];+ auto result = db.run_command(make_document(kvp("buildInfo", 1)));+ auto view = result.view();+ if (auto ver = view["version"])+ return fromUtf8(std::string(ver.get_string().value));+ }+ catch (...) {}+ return L"Unknown";+ }++ std::wstring MongoDBAdapter::currentDatabase()+ {+ return fromUtf8(currentDbName_);+ }+}diff --git a/windows/Gridex/MongoDBAdapterQuery.cpp b/windows/Gridex/MongoDBAdapterQuery.cppnew file mode 100644index 0000000..98c3dff--- /dev/null+++ b/windows/Gridex/MongoDBAdapterQuery.cpp@@ -0,0 +1,493 @@+// MongoDBAdapterQuery.cpp — query execution, CRUD, transactions, fetchRows.+//+// Split from MongoDBAdapter.cpp to keep each file under 200 lines.+// Connection lifecycle and schema inspection live in MongoDBAdapter.cpp.++// NOMINMAX prevents <windows.h> from defining min/max macros that collide+// with std::numeric_limits::max() used inside bsoncxx/mongocxx headers.+#ifndef NOMINMAX+#define NOMINMAX+#endif+#include <windows.h>+#include "Models/MongoDBAdapter.h"++#include <mongocxx/client.hpp>+#include <mongocxx/database.hpp>+#include <mongocxx/collection.hpp>+#include <mongocxx/options/find.hpp>+#include <mongocxx/client_session.hpp>+#include <bsoncxx/builder/basic/document.hpp>+#include <bsoncxx/builder/basic/kvp.hpp>+#include <bsoncxx/json.hpp>+#include <bsoncxx/types.hpp>++#include <chrono>+#include <regex>+#include <sstream>++namespace DBModels+{+ using bsoncxx::builder::basic::kvp;+ using bsoncxx::builder::basic::make_document;++ // ── Flatten BSON document to TableRow ──────────────────────+ TableRow MongoDBAdapter::flattenDocument(+ const void* bsonViewPtr, const std::vector<ColumnInfo>& columns)+ {+ auto& view = *static_cast<const bsoncxx::document::view*>(bsonViewPtr);+ TableRow row;+ for (auto& col : columns)+ {+ auto key = toUtf8(col.name);+ auto elem = view[key];+ if (!elem)+ {+ row[col.name] = L"";+ continue;+ }++ std::wstring val;+ switch (elem.type())+ {+ case bsoncxx::type::k_string:+ val = fromUtf8(std::string(elem.get_string().value));+ break;+ case bsoncxx::type::k_int32:+ val = std::to_wstring(elem.get_int32().value);+ break;+ case bsoncxx::type::k_int64:+ val = std::to_wstring(elem.get_int64().value);+ break;+ case bsoncxx::type::k_double:+ val = std::to_wstring(elem.get_double().value);+ break;+ case bsoncxx::type::k_bool:+ val = elem.get_bool().value ? L"true" : L"false";+ break;+ case bsoncxx::type::k_oid:+ val = fromUtf8(elem.get_oid().value.to_string());+ break;+ case bsoncxx::type::k_null:+ val = L"null";+ break;+ case bsoncxx::type::k_date:+ {+ auto ms = elem.get_date().value.count();+ val = L"Date(" + std::to_wstring(ms) + L")";+ break;+ }+ case bsoncxx::type::k_document:+ val = fromUtf8(bsoncxx::to_json(elem.get_document().value));+ break;+ case bsoncxx::type::k_array:+ val = fromUtf8(bsoncxx::to_json(elem.get_array().value));+ break;+ default:+ {+ // Wrap value in a temp doc to convert via to_json+ auto tmp = make_document(kvp("v", elem.get_value()));+ auto json = bsoncxx::to_json(tmp.view());+ // Extract just the value part (after "v" : )+ auto pos = json.find(':');+ if (pos != std::string::npos)+ val = fromUtf8(json.substr(pos + 2, json.size() - pos - 3));+ else+ val = fromUtf8(json);+ break;+ }+ }+ row[col.name] = val;+ }+ return row;+ }++ // ── fetchRows ─────────────────────────────────────────────+ QueryResult MongoDBAdapter::fetchRows(+ const std::wstring& table, const std::wstring& schema,+ int limit, int offset,+ const std::wstring& orderBy, bool ascending)+ {+ if (!isConnected())+ throw DatabaseError(DatabaseError::Code::ConnectionFailed, "Not connected");++ auto start = std::chrono::steady_clock::now();+ auto db = getDatabase(schema);+ auto coll = db[toUtf8(table)];++ // Get column info (cached after first call)+ auto columns = describeTable(table, schema);++ mongocxx::v_noabi::options::find opts;+ opts.skip(offset);+ opts.limit(limit);+ if (!orderBy.empty())+ opts.sort(make_document(kvp(toUtf8(orderBy), ascending ? 1 : -1)));++ auto cursor = coll.find({}, opts);++ QueryResult result;+ for (auto& col : columns) result.columnNames.push_back(col.name);++ for (auto& doc : cursor)+ {+ bsoncxx::document::view v = doc;+ result.rows.push_back(flattenDocument(&v, columns));+ }++ auto end = std::chrono::steady_clock::now();+ result.totalRows = static_cast<int>(result.rows.size());+ result.executionTimeMs = std::chrono::duration<double, std::milli>(end - start).count();+ return result;+ }++ // ── Parse shell command syntax ────────────────────────────+ // Pattern: db.collectionName.method({json}) or db.collectionName.method()+ bool MongoDBAdapter::parseShellCommand(const std::string& input, ParsedCommand& out)+ {+ // Regex: db\.(\w+)\.(\w+)\(([\s\S]*)\)+ static const std::regex re(+ R"(db\.(\w+)\.(\w+)\(([\s\S]*)\)\s*$)",+ std::regex::optimize);+ std::smatch m;+ if (!std::regex_search(input, m, re)) return false;+ out.collection = m[1].str();+ out.method = m[2].str();+ out.jsonArg = m[3].str();+ // Trim whitespace from jsonArg+ auto& a = out.jsonArg;+ while (!a.empty() && (a.front() == ' ' || a.front() == '\n')) a.erase(a.begin());+ while (!a.empty() && (a.back() == ' ' || a.back() == '\n')) a.pop_back();+ return true;+ }++ // ── execute() — main entry point for query editor ─────────+ QueryResult MongoDBAdapter::execute(const std::wstring& sql)+ {+ if (!isConnected())+ throw DatabaseError(DatabaseError::Code::ConnectionFailed, "Not connected");++ auto input = toUtf8(sql);+ // Trim leading/trailing whitespace+ while (!input.empty() && input.front() == ' ') input.erase(input.begin());+ while (!input.empty() && input.back() == ' ') input.pop_back();++ ParsedCommand cmd;+ if (parseShellCommand(input, cmd))+ return executeCommand(cmd);++ // Fallback: treat as raw runCommand JSON+ return executeRunCommand(input);+ }++ QueryResult MongoDBAdapter::executeCommand(const ParsedCommand& cmd)+ {+ auto start = std::chrono::steady_clock::now();+ auto db = (*client_)[currentDbName_];+ auto coll = db[cmd.collection];+ QueryResult result;++ if (cmd.method == "find")+ {+ auto filter = cmd.jsonArg.empty()+ ? bsoncxx::document::value(make_document())+ : bsoncxx::from_json(cmd.jsonArg);+ auto cursor = coll.find(filter.view());+ // Discover columns from first batch of results+ std::vector<ColumnInfo> cols;+ std::vector<bsoncxx::document::value> docs;+ for (auto& doc : cursor)+ docs.push_back(bsoncxx::document::value(doc));++ if (!docs.empty())+ {+ // Use describe to get column info+ cols = describeTable(fromUtf8(cmd.collection), fromUtf8(currentDbName_));+ for (auto& c : cols) result.columnNames.push_back(c.name);+ for (auto& d : docs)+ {+ bsoncxx::document::view v = d.view();+ result.rows.push_back(flattenDocument(&v, cols));+ }+ }+ }+ else if (cmd.method == "insertOne")+ {+ auto doc = bsoncxx::from_json(cmd.jsonArg);+ auto res = coll.insert_one(doc.view());+ result.columnNames = { L"insertedId" };+ TableRow row;+ if (res)+ row[L"insertedId"] = fromUtf8(res->inserted_id().get_oid().value.to_string());+ result.rows.push_back(row);+ // Invalidate schema cache for this collection+ schemaCache_.erase(currentDbName_ + "." + cmd.collection);+ }+ else if (cmd.method == "updateOne")+ {+ // Expect two JSON args separated by comma: filter, update+ // Parse: {filter}, {update}+ auto args = cmd.jsonArg;+ // Find the split point between two JSON objects+ int braceDepth = 0;+ size_t splitPos = std::string::npos;+ for (size_t i = 0; i < args.size(); i++)+ {+ if (args[i] == '{') braceDepth++;+ else if (args[i] == '}') braceDepth--;+ if (braceDepth == 0 && i > 0)+ {+ // Find next comma after closing brace+ auto next = args.find(',', i + 1);+ if (next != std::string::npos) { splitPos = next; break; }+ }+ }+ if (splitPos == std::string::npos)+ throw DatabaseError(DatabaseError::Code::InvalidSQL,+ "updateOne requires: db.coll.updateOne({filter}, {update})");++ auto filterStr = args.substr(0, splitPos);+ auto updateStr = args.substr(splitPos + 1);+ // Trim whitespace+ while (!updateStr.empty() && updateStr.front() == ' ') updateStr.erase(updateStr.begin());++ auto filter = bsoncxx::from_json(filterStr);+ auto update = bsoncxx::from_json(updateStr);+ auto res = coll.update_one(filter.view(), update.view());++ result.columnNames = { L"matchedCount", L"modifiedCount" };+ TableRow row;+ row[L"matchedCount"] = std::to_wstring(res ? res->matched_count() : 0);+ row[L"modifiedCount"] = std::to_wstring(res ? res->modified_count() : 0);+ result.rows.push_back(row);+ }+ else if (cmd.method == "deleteOne")+ {+ auto filter = bsoncxx::from_json(cmd.jsonArg);+ auto res = coll.delete_one(filter.view());+ result.columnNames = { L"deletedCount" };+ TableRow row;+ row[L"deletedCount"] = std::to_wstring(res ? res->deleted_count() : 0);+ result.rows.push_back(row);+ }+ else if (cmd.method == "aggregate")+ {+ // jsonArg should be a JSON array: [{$match:...}, {$group:...}]+ auto pipeline = bsoncxx::from_json(cmd.jsonArg);++ // Build pipeline from array+ mongocxx::pipeline pipe;+ for (auto& stage : pipeline.view())+ pipe.append_stage(stage.get_document().value);++ auto cursor = coll.aggregate(pipe);+ bool first = true;+ for (auto& doc : cursor)+ {+ if (first)+ {+ for (auto& elem : doc)+ result.columnNames.push_back(fromUtf8(std::string(elem.key())));+ first = false;+ }+ TableRow row;+ for (auto& elem : doc)+ {+ // Wrap element value in a temp document to use to_json+ auto tmp = make_document(kvp("v", elem.get_value()));+ auto json = bsoncxx::to_json(tmp.view());+ auto pos = json.find(':');+ std::wstring val;+ if (pos != std::string::npos)+ val = fromUtf8(json.substr(pos + 2, json.size() - pos - 3));+ else+ val = fromUtf8(json);+ row[fromUtf8(std::string(elem.key()))] = val;+ }+ result.rows.push_back(row);+ }+ }+ else if (cmd.method == "count")+ {+ auto filter = cmd.jsonArg.empty()+ ? bsoncxx::document::value(make_document())+ : bsoncxx::from_json(cmd.jsonArg);+ auto count = coll.count_documents(filter.view());+ result.columnNames = { L"count" };+ TableRow row;+ row[L"count"] = std::to_wstring(count);+ result.rows.push_back(row);+ }+ else+ {+ throw DatabaseError(DatabaseError::Code::InvalidSQL,+ "Unsupported method: " + cmd.method ++ ". Supported: find, insertOne, updateOne, deleteOne, aggregate, count");+ }++ auto end = std::chrono::steady_clock::now();+ result.totalRows = static_cast<int>(result.rows.size());+ result.executionTimeMs = std::chrono::duration<double, std::milli>(end - start).count();+ return result;+ }++ QueryResult MongoDBAdapter::executeRunCommand(const std::string& json)+ {+ auto start = std::chrono::steady_clock::now();+ auto db = (*client_)[currentDbName_];+ auto cmdDoc = bsoncxx::from_json(json);+ auto res = db.run_command(cmdDoc.view());++ QueryResult result;+ result.columnNames = { L"result" };+ TableRow row;+ row[L"result"] = fromUtf8(bsoncxx::to_json(res.view()));+ result.rows.push_back(row);++ auto end = std::chrono::steady_clock::now();+ result.totalRows = 1;+ result.executionTimeMs = std::chrono::duration<double, std::milli>(end - start).count();+ return result;+ }++ // Helper: append a filter value for _id. ObjectId is a 24-char hex+ // string produced by flattenDocument (oid.to_string()). Attempt to+ // construct bsoncxx::oid first; if the value is not a valid ObjectId+ // (e.g. string _id, integer _id), fall back to matching as a plain+ // string. This prevents "could not parse Object ID string" errors.+ static void appendIdFilter(+ bsoncxx::builder::basic::document& filter,+ const std::string& key, const std::string& val)+ {+ if (key == "_id")+ {+ try+ {+ filter.append(kvp(key, bsoncxx::oid(val)));+ return;+ }+ catch (...) {}+ filter.append(kvp(key, val));+ }+ else+ {+ filter.append(kvp(key, val));+ }+ }++ // ── CRUD operations (used by data grid inline editing) ────+ QueryResult MongoDBAdapter::insertRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& values)+ {+ auto db = getDatabase(schema);+ auto coll = db[toUtf8(table)];++ bsoncxx::builder::basic::document builder;+ for (auto& [col, val] : values)+ builder.append(kvp(toUtf8(col), toUtf8(val)));++ auto res = coll.insert_one(builder.extract());+ // Invalidate schema cache+ schemaCache_.erase(toUtf8(schema) + "." + toUtf8(table));++ QueryResult result;+ result.totalRows = res ? 1 : 0;+ return result;+ }++ QueryResult MongoDBAdapter::updateRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& setValues, const TableRow& whereValues)+ {+ auto db = getDatabase(schema);+ auto coll = db[toUtf8(table)];++ // Build filter from whereValues (typically _id)+ bsoncxx::builder::basic::document filter;+ for (auto& [col, val] : whereValues)+ appendIdFilter(filter, toUtf8(col), toUtf8(val));++ // Build $set from setValues+ bsoncxx::builder::basic::document setDoc;+ for (auto& [col, val] : setValues)+ setDoc.append(kvp(toUtf8(col), toUtf8(val)));++ auto update = make_document(kvp("$set", setDoc.extract()));+ auto res = coll.update_one(filter.extract(), update.view());++ QueryResult result;+ result.totalRows = res ? static_cast<int>(res->modified_count()) : 0;+ return result;+ }++ QueryResult MongoDBAdapter::deleteRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& whereValues)+ {+ auto db = getDatabase(schema);+ auto coll = db[toUtf8(table)];++ bsoncxx::builder::basic::document filter;+ for (auto& [col, val] : whereValues)+ appendIdFilter(filter, toUtf8(col), toUtf8(val));++ auto res = coll.delete_one(filter.extract());+ QueryResult result;+ result.totalRows = res ? static_cast<int>(res->deleted_count()) : 0;+ return result;+ }++ // ── Transactions (MongoDB 4.0+ replica set required) ──────+ void MongoDBAdapter::beginTransaction()+ {+ if (!isConnected())+ throw DatabaseError(DatabaseError::Code::TransactionFailed, "Not connected");+ try+ {+ session_ = std::make_unique<mongocxx::client_session>(+ client_->start_session());+ session_->start_transaction();+ }+ catch (const std::exception& ex)+ {+ session_.reset();+ throw DatabaseError(DatabaseError::Code::TransactionFailed,+ std::string("Failed to start transaction (requires MongoDB 4.0+ "+ "replica set): ") + ex.what());+ }+ }++ void MongoDBAdapter::commitTransaction()+ {+ if (!session_)+ throw DatabaseError(DatabaseError::Code::TransactionFailed, "No active transaction");+ try+ {+ session_->commit_transaction();+ session_.reset();+ }+ catch (const std::exception& ex)+ {+ session_.reset();+ throw DatabaseError(DatabaseError::Code::TransactionFailed,+ std::string("Commit failed: ") + ex.what());+ }+ }++ void MongoDBAdapter::rollbackTransaction()+ {+ if (!session_)+ throw DatabaseError(DatabaseError::Code::TransactionFailed, "No active transaction");+ try+ {+ session_->abort_transaction();+ session_.reset();+ }+ catch (const std::exception& ex)+ {+ session_.reset();+ throw DatabaseError(DatabaseError::Code::TransactionFailed,+ std::string("Rollback failed: ") + ex.what());+ }+ }+}diff --git a/windows/Gridex/MySQLAdapter.cpp b/windows/Gridex/MySQLAdapter.cppnew file mode 100644index 0000000..ecc77ce--- /dev/null+++ b/windows/Gridex/MySQLAdapter.cpp@@ -0,0 +1,557 @@+#include <windows.h>+#include "Models/MySQLAdapter.h"+#include <mysql/mysql.h>+#include <chrono>++namespace DBModels+{+ // ── UTF-8 helpers (same pattern as PostgreSQLAdapter) ──+ std::string MySQLAdapter::toUtf8(const std::wstring& wstr)+ {+ if (wstr.empty()) return {};+ int size = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(),+ static_cast<int>(wstr.size()), nullptr, 0, nullptr, nullptr);+ std::string result(size, '\0');+ WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(),+ static_cast<int>(wstr.size()), &result[0], size, nullptr, nullptr);+ return result;+ }++ std::wstring MySQLAdapter::fromUtf8(const std::string& str)+ {+ if (str.empty()) return {};+ int size = MultiByteToWideChar(CP_UTF8, 0, str.c_str(),+ static_cast<int>(str.size()), nullptr, 0);+ std::wstring result(size, L'\0');+ MultiByteToWideChar(CP_UTF8, 0, str.c_str(),+ static_cast<int>(str.size()), &result[0], size);+ return result;+ }++ std::string MySQLAdapter::quoteIdentifier(const std::wstring& name)+ {+ return "`" + toUtf8(name) + "`";+ }++ std::string MySQLAdapter::quoteLiteral(const std::wstring& value)+ {+ std::string utf8 = toUtf8(value);+ std::string escaped;+ escaped.reserve(utf8.size() + 2);+ escaped += '\'';+ for (char c : utf8)+ {+ if (c == '\'') escaped += "''";+ else if (c == '\\') escaped += "\\\\";+ else escaped += c;+ }+ escaped += '\'';+ return escaped;+ }++ void MySQLAdapter::ensureConnected() const+ {+ if (!connected_ || !conn_)+ throw DatabaseError(DatabaseError::Code::ConnectionFailed, "Not connected to MySQL");+ }++ // ── Constructor / Destructor ────────────────────+ MySQLAdapter::MySQLAdapter() = default;++ MySQLAdapter::~MySQLAdapter()+ {+ if (conn_)+ {+ mysql_close(conn_);+ conn_ = nullptr;+ }+ }++ // ── Connection ──────────────────────────────────+ void MySQLAdapter::connect(const ConnectionConfig& config, const std::wstring& password)+ {+ disconnect();++ conn_ = mysql_init(nullptr);+ if (!conn_)+ throw DatabaseError(DatabaseError::Code::ConnectionFailed, "mysql_init() failed");++ // Set connection timeout+ unsigned int timeout = 10;+ mysql_options(conn_, MYSQL_OPT_CONNECT_TIMEOUT, &timeout);++ // Set UTF-8+ mysql_options(conn_, MYSQL_SET_CHARSET_NAME, "utf8mb4");++ // SSL — respect sslMode: Preferred/Required skip cert verification+ // (common for self-signed certs); VerifyCA/VerifyIdentity enforce it.+ if (config.sslMode != DBModels::SSLMode::Disabled)+ {+ mysql_ssl_set(conn_, nullptr, nullptr, nullptr, nullptr, nullptr);++ bool verifyCert =+ (config.sslMode == DBModels::SSLMode::VerifyCA ||+ config.sslMode == DBModels::SSLMode::VerifyIdentity);+ unsigned char verify = verifyCert ? 1 : 0;+ mysql_options(conn_, MYSQL_OPT_SSL_VERIFY_SERVER_CERT, &verify);+ }++ auto host = toUtf8(config.host);+ auto user = toUtf8(config.username);+ auto pass = toUtf8(password);+ auto db = toUtf8(config.database);++ MYSQL* result = mysql_real_connect(+ conn_,+ host.c_str(),+ user.c_str(),+ pass.empty() ? nullptr : pass.c_str(),+ db.empty() ? nullptr : db.c_str(),+ config.port,+ nullptr, // unix socket+ CLIENT_MULTI_STATEMENTS+ );++ if (!result)+ {+ std::string err = mysql_error(conn_);+ mysql_close(conn_);+ conn_ = nullptr;+ throw DatabaseError(DatabaseError::Code::ConnectionFailed, err);+ }++ connected_ = true;+ }++ void MySQLAdapter::disconnect()+ {+ if (conn_)+ {+ mysql_close(conn_);+ conn_ = nullptr;+ }+ connected_ = false;+ }++ bool MySQLAdapter::testConnection(const ConnectionConfig& config, const std::wstring& password)+ {+ try+ {+ connect(config, password);+ auto result = execute(L"SELECT 1");+ disconnect();+ return result.success;+ }+ catch (...)+ {+ disconnect();+ return false;+ }+ }++ bool MySQLAdapter::isConnected() const { return connected_ && conn_; }++ // ── Query Execution ─────────────────────────────+ QueryResult MySQLAdapter::executeInternal(const std::string& sql)+ {+ ensureConnected();++ auto start = std::chrono::high_resolution_clock::now();+ int rc = mysql_real_query(conn_, sql.c_str(), static_cast<unsigned long>(sql.size()));+ auto end = std::chrono::high_resolution_clock::now();+ double durationMs = std::chrono::duration<double, std::milli>(end - start).count();++ QueryResult result;+ result.sql = fromUtf8(sql);+ result.executionTimeMs = durationMs;++ if (rc != 0)+ {+ result.success = false;+ result.error = fromUtf8(mysql_error(conn_));+ return result;+ }++ MYSQL_RES* res = mysql_store_result(conn_);+ if (res)+ {+ unsigned int nCols = mysql_num_fields(res);+ MYSQL_FIELD* fields = mysql_fetch_fields(res);++ // Pre-reserve to avoid vector reallocation+ result.columnNames.reserve(nCols);+ result.columnTypes.reserve(nCols);+ for (unsigned int c = 0; c < nCols; c++)+ {+ result.columnNames.push_back(fromUtf8(fields[c].name));+ result.columnTypes.push_back(fromUtf8(fields[c].name)); // simplified+ }++ // PERFORMANCE: pre-reserve, const-ref colName, move-construct rows+ // (matches PostgreSQLAdapter optimization)+ const auto totalRows = mysql_num_rows(res);+ result.rows.reserve(static_cast<size_t>(totalRows));+ MYSQL_ROW row;+ while ((row = mysql_fetch_row(res)))+ {+ unsigned long* lengths = mysql_fetch_lengths(res);+ TableRow tableRow;+ tableRow.reserve(nCols);+ for (unsigned int c = 0; c < nCols; c++)+ {+ const std::wstring& colName = result.columnNames[c];+ if (row[c])+ tableRow.emplace(colName, fromUtf8(std::string(row[c], lengths[c])));+ else+ tableRow.emplace(colName, nullValue());+ }+ result.rows.push_back(std::move(tableRow));+ }++ result.totalRows = static_cast<int>(mysql_num_rows(res));+ result.success = true;+ mysql_free_result(res);+ }+ else+ {+ // No result set — DML statement+ my_ulonglong affected = mysql_affected_rows(conn_);+ result.totalRows = static_cast<int>(affected);+ result.success = true;+ }++ // Clear any remaining result sets (CLIENT_MULTI_STATEMENTS)+ while (mysql_next_result(conn_) == 0)+ {+ MYSQL_RES* extra = mysql_store_result(conn_);+ if (extra) mysql_free_result(extra);+ }++ return result;+ }++ QueryResult MySQLAdapter::execute(const std::wstring& sql)+ {+ return executeInternal(toUtf8(sql));+ }++ QueryResult MySQLAdapter::fetchRows(+ const std::wstring& table, const std::wstring& schema,+ int limit, int offset,+ const std::wstring& orderBy, bool ascending)+ {+ // MySQL uses database name instead of schema+ std::string sql = "SELECT * FROM " + quoteIdentifier(schema) + "." + quoteIdentifier(table);+ if (!orderBy.empty())+ sql += " ORDER BY " + quoteIdentifier(orderBy) + (ascending ? " ASC" : " DESC");+ sql += " LIMIT " + std::to_string(limit) + " OFFSET " + std::to_string(offset);++ auto result = executeInternal(sql);++ // Get total count+ std::string countSql = "SELECT COUNT(*) AS cnt FROM " ++ quoteIdentifier(schema) + "." + quoteIdentifier(table);+ auto countResult = executeInternal(countSql);+ if (countResult.success && !countResult.rows.empty())+ {+ auto it = countResult.rows[0].find(L"cnt");+ if (it != countResult.rows[0].end() && !isNullCell(it->second))+ result.totalRows = std::stoi(toUtf8(it->second));+ }++ result.currentPage = (offset / limit) + 1;+ result.pageSize = limit;+ return result;+ }++ // ── Schema Inspection ───────────────────────────+ std::vector<std::wstring> MySQLAdapter::listDatabases()+ {+ auto result = executeInternal("SHOW DATABASES");+ std::vector<std::wstring> dbs;+ for (auto& row : result.rows)+ {+ auto it = row.find(L"Database");+ if (it != row.end()) dbs.push_back(it->second);+ }+ return dbs;+ }++ std::vector<std::wstring> MySQLAdapter::listSchemas()+ {+ return listDatabases(); // MySQL schemas = databases+ }++ std::vector<TableInfo> MySQLAdapter::listTables(const std::wstring& schema)+ {+ std::string sql =+ "SELECT TABLE_NAME, TABLE_COMMENT, TABLE_ROWS, DATA_LENGTH + INDEX_LENGTH AS size_bytes "+ "FROM INFORMATION_SCHEMA.TABLES "+ "WHERE TABLE_SCHEMA = " + quoteLiteral(schema) ++ " AND TABLE_TYPE = 'BASE TABLE' ORDER BY TABLE_NAME";++ auto result = executeInternal(sql);+ std::vector<TableInfo> tables;+ for (auto& row : result.rows)+ {+ TableInfo info;+ info.name = row[L"TABLE_NAME"];+ info.schema = schema;+ info.type = L"table";+ info.comment = row[L"TABLE_COMMENT"];+ auto estIt = row.find(L"TABLE_ROWS");+ if (estIt != row.end() && !isNullCell(estIt->second))+ info.estimatedRows = std::stoll(toUtf8(estIt->second));+ auto sizeIt = row.find(L"size_bytes");+ if (sizeIt != row.end() && !isNullCell(sizeIt->second))+ info.sizeBytes = std::stoll(toUtf8(sizeIt->second));+ tables.push_back(info);+ }+ return tables;+ }++ std::vector<TableInfo> MySQLAdapter::listViews(const std::wstring& schema)+ {+ std::string sql =+ "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS "+ "WHERE TABLE_SCHEMA = " + quoteLiteral(schema) + " ORDER BY TABLE_NAME";++ auto result = executeInternal(sql);+ std::vector<TableInfo> views;+ for (auto& row : result.rows)+ {+ TableInfo info;+ info.name = row[L"TABLE_NAME"];+ info.schema = schema;+ info.type = L"view";+ views.push_back(info);+ }+ return views;+ }++ std::vector<ColumnInfo> MySQLAdapter::describeTable(+ const std::wstring& table, const std::wstring& schema)+ {+ std::string sql =+ "SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_DEFAULT, "+ "COLUMN_KEY, ORDINAL_POSITION, COLUMN_COMMENT "+ "FROM INFORMATION_SCHEMA.COLUMNS "+ "WHERE TABLE_SCHEMA = " + quoteLiteral(schema) ++ " AND TABLE_NAME = " + quoteLiteral(table) ++ " ORDER BY ORDINAL_POSITION";++ auto result = executeInternal(sql);+ std::vector<ColumnInfo> columns;+ for (auto& row : result.rows)+ {+ ColumnInfo col;+ col.name = row[L"COLUMN_NAME"];+ col.dataType = row[L"COLUMN_TYPE"];+ col.nullable = (row[L"IS_NULLABLE"] == L"YES");+ col.defaultValue = !isNullCell(row[L"COLUMN_DEFAULT"]) ? row[L"COLUMN_DEFAULT"] : L"";+ col.isPrimaryKey = (row[L"COLUMN_KEY"] == L"PRI");+ col.comment = row[L"COLUMN_COMMENT"];+ auto ordIt = row.find(L"ORDINAL_POSITION");+ if (ordIt != row.end() && !isNullCell(ordIt->second))+ col.ordinalPosition = std::stoi(toUtf8(ordIt->second));+ columns.push_back(col);+ }++ // Mark FK columns+ auto fks = listForeignKeys(table, schema);+ for (auto& fk : fks)+ for (auto& col : columns)+ if (col.name == fk.column)+ {+ col.isForeignKey = true;+ col.fkReferencedTable = fk.referencedTable;+ col.fkReferencedColumn = fk.referencedColumn;+ }++ return columns;+ }++ std::vector<IndexInfo> MySQLAdapter::listIndexes(+ const std::wstring& table, const std::wstring& schema)+ {+ std::string sql =+ "SELECT INDEX_NAME, GROUP_CONCAT(COLUMN_NAME ORDER BY SEQ_IN_INDEX) AS columns, "+ "NOT NON_UNIQUE AS is_unique, INDEX_TYPE AS algorithm "+ "FROM INFORMATION_SCHEMA.STATISTICS "+ "WHERE TABLE_SCHEMA = " + quoteLiteral(schema) ++ " AND TABLE_NAME = " + quoteLiteral(table) ++ " GROUP BY INDEX_NAME, NON_UNIQUE, INDEX_TYPE ORDER BY INDEX_NAME";++ auto result = executeInternal(sql);+ std::vector<IndexInfo> indexes;+ for (auto& row : result.rows)+ {+ IndexInfo idx;+ idx.name = row[L"INDEX_NAME"];+ idx.columns = row[L"columns"];+ idx.isUnique = (row[L"is_unique"] == L"1");+ idx.isPrimary = (idx.name == L"PRIMARY");+ idx.algorithm = row[L"algorithm"];+ indexes.push_back(idx);+ }+ return indexes;+ }++ std::vector<ForeignKeyInfo> MySQLAdapter::listForeignKeys(+ const std::wstring& table, const std::wstring& schema)+ {+ std::string sql =+ "SELECT CONSTRAINT_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME, "+ "REFERENCED_COLUMN_NAME "+ "FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE "+ "WHERE TABLE_SCHEMA = " + quoteLiteral(schema) ++ " AND TABLE_NAME = " + quoteLiteral(table) ++ " AND REFERENCED_TABLE_NAME IS NOT NULL ORDER BY CONSTRAINT_NAME";++ auto result = executeInternal(sql);+ std::vector<ForeignKeyInfo> fks;+ for (auto& row : result.rows)+ {+ ForeignKeyInfo fk;+ fk.name = row[L"CONSTRAINT_NAME"];+ fk.column = row[L"COLUMN_NAME"];+ fk.referencedTable = row[L"REFERENCED_TABLE_NAME"];+ fk.referencedColumn = row[L"REFERENCED_COLUMN_NAME"];+ fk.onUpdate = L"RESTRICT";+ fk.onDelete = L"RESTRICT";+ fks.push_back(fk);+ }+ return fks;+ }++ std::vector<std::wstring> MySQLAdapter::listFunctions(const std::wstring& schema)+ {+ std::string sql =+ "SELECT ROUTINE_NAME FROM INFORMATION_SCHEMA.ROUTINES "+ "WHERE ROUTINE_SCHEMA = " + quoteLiteral(schema) ++ " AND ROUTINE_TYPE = 'FUNCTION' ORDER BY ROUTINE_NAME";++ auto result = executeInternal(sql);+ std::vector<std::wstring> funcs;+ for (auto& row : result.rows)+ {+ auto it = row.find(L"ROUTINE_NAME");+ if (it != row.end()) funcs.push_back(it->second);+ }+ return funcs;+ }++ std::wstring MySQLAdapter::getFunctionSource(+ const std::wstring& name, const std::wstring& schema)+ {+ std::string sql = "SHOW CREATE FUNCTION " + quoteIdentifier(schema) + "." + quoteIdentifier(name);+ auto result = executeInternal(sql);+ if (!result.rows.empty())+ {+ auto it = result.rows[0].find(L"Create Function");+ if (it != result.rows[0].end()) return it->second;+ }+ return L"";+ }++ std::wstring MySQLAdapter::getCreateTableSQL(+ const std::wstring& table, const std::wstring& schema)+ {+ std::string sql = "SHOW CREATE TABLE " ++ quoteIdentifier(schema) + "." + quoteIdentifier(table);+ auto result = executeInternal(sql);+ if (!result.rows.empty())+ {+ auto it = result.rows[0].find(L"Create Table");+ if (it != result.rows[0].end()) return it->second;+ }+ return L"";+ }++ // ── DML ─────────────────────────────────────────+ QueryResult MySQLAdapter::insertRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& values)+ {+ std::string sql = "INSERT INTO " + quoteIdentifier(schema) + "." + quoteIdentifier(table) + " (";+ std::string valsSql;+ bool first = true;+ for (auto& [col, val] : values)+ {+ if (!first) { sql += ", "; valsSql += ", "; }+ sql += quoteIdentifier(col);+ valsSql += isNullCell(val) ? "NULL" : quoteLiteral(val);+ first = false;+ }+ sql += ") VALUES (" + valsSql + ")";+ return executeInternal(sql);+ }++ QueryResult MySQLAdapter::updateRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& setValues, const TableRow& whereValues)+ {+ std::string sql = "UPDATE " + quoteIdentifier(schema) + "." + quoteIdentifier(table) + " SET ";+ bool first = true;+ for (auto& [col, val] : setValues)+ {+ if (!first) sql += ", ";+ sql += quoteIdentifier(col) + " = " + (isNullCell(val) ? "NULL" : quoteLiteral(val));+ first = false;+ }+ sql += " WHERE ";+ first = true;+ for (auto& [col, val] : whereValues)+ {+ if (!first) sql += " AND ";+ if (isNullCell(val))+ sql += quoteIdentifier(col) + " IS NULL";+ else+ sql += quoteIdentifier(col) + " = " + quoteLiteral(val);+ first = false;+ }+ return executeInternal(sql);+ }++ QueryResult MySQLAdapter::deleteRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& whereValues)+ {+ std::string sql = "DELETE FROM " + quoteIdentifier(schema) + "." + quoteIdentifier(table) + " WHERE ";+ bool first = true;+ for (auto& [col, val] : whereValues)+ {+ if (!first) sql += " AND ";+ if (isNullCell(val))+ sql += quoteIdentifier(col) + " IS NULL";+ else+ sql += quoteIdentifier(col) + " = " + quoteLiteral(val);+ first = false;+ }+ return executeInternal(sql);+ }++ // ── Transactions ────────────────────────────────+ void MySQLAdapter::beginTransaction() { executeInternal("START TRANSACTION"); }+ void MySQLAdapter::commitTransaction() { executeInternal("COMMIT"); }+ void MySQLAdapter::rollbackTransaction() { executeInternal("ROLLBACK"); }++ // ── Server Info ─────────────────────────────────+ std::wstring MySQLAdapter::serverVersion()+ {+ ensureConnected();+ const char* ver = mysql_get_server_info(conn_);+ return ver ? fromUtf8(ver) : L"Unknown";+ }++ std::wstring MySQLAdapter::currentDatabase()+ {+ auto result = executeInternal("SELECT DATABASE() AS db");+ if (!result.rows.empty())+ {+ auto it = result.rows[0].find(L"db");+ if (it != result.rows[0].end()) return it->second;+ }+ return L"";+ }+}diff --git a/windows/Gridex/Package.appxmanifest b/windows/Gridex/Package.appxmanifestnew file mode 100644index 0000000..9b9ac27--- /dev/null+++ b/windows/Gridex/Package.appxmanifest@@ -0,0 +1,53 @@+<?xml version="1.0" encoding="utf-8"?>++<Package+ xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"+ xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"+ xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"+ xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"+ xmlns:systemai="http://schemas.microsoft.com/appx/manifest/systemai/windows10"+ IgnorableNamespaces="uap rescap systemai">++ <Identity+ Name="e3a6ab8b-b6dc-491b-9003-956f7fb937e8"+ Publisher="CN=dang1"+ Version="1.0.0.0" />++ <mp:PhoneIdentity PhoneProductId="e3a6ab8b-b6dc-491b-9003-956f7fb937e8" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>++ <Properties>+ <DisplayName>Gridex</DisplayName>+ <PublisherDisplayName>dang1</PublisherDisplayName>+ <Logo>Assets\StoreLogo.png</Logo>+ </Properties>++ <Dependencies>+ <TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.17763.0" MaxVersionTested="10.0.26226.0" />+ <TargetDeviceFamily Name="Windows.Desktop" MinVersion="10.0.17763.0" MaxVersionTested="10.0.26226.0" />+ </Dependencies>++ <Resources>+ <Resource Language="x-generate"/>+ </Resources>++ <Applications>+ <Application Id="App"+ Executable="$targetnametoken$.exe"+ EntryPoint="$targetentrypoint$">+ <uap:VisualElements+ DisplayName="Gridex"+ Description="Gridex - AI-Native Database IDE"+ BackgroundColor="transparent"+ Square150x150Logo="Assets\Square150x150Logo.png"+ Square44x44Logo="Assets\Square44x44Logo.png">+ <uap:DefaultTile Wide310x150Logo="Assets\Wide310x150Logo.png" />+ <uap:SplashScreen Image="Assets\SplashScreen.png" />+ </uap:VisualElements>+ </Application>+ </Applications>++ <Capabilities>+ <rescap:Capability Name="runFullTrust" />+ <systemai:Capability Name="systemAIModels"/>+ </Capabilities>+</Package>diff --git a/windows/Gridex/PostgreSQLAdapter.cpp b/windows/Gridex/PostgreSQLAdapter.cppnew file mode 100644index 0000000..a4aa604--- /dev/null+++ b/windows/Gridex/PostgreSQLAdapter.cpp@@ -0,0 +1,657 @@+#include <windows.h>+#include "Models/PostgreSQLAdapter.h"+#include <libpq-fe.h>+#include <algorithm>+#include <chrono>+#include <codecvt>+#include <locale>++namespace DBModels+{+ // ── UTF-8 <-> wstring helpers ─────────────────────+ std::string PostgreSQLAdapter::toUtf8(const std::wstring& wstr)+ {+ if (wstr.empty()) return {};+ int size = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(),+ static_cast<int>(wstr.size()), nullptr, 0, nullptr, nullptr);+ std::string result(size, '\0');+ WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(),+ static_cast<int>(wstr.size()), &result[0], size, nullptr, nullptr);+ return result;+ }++ std::wstring PostgreSQLAdapter::fromUtf8(const std::string& str)+ {+ if (str.empty()) return {};+ int size = MultiByteToWideChar(CP_UTF8, 0, str.c_str(),+ static_cast<int>(str.size()), nullptr, 0);+ std::wstring result(size, L'\0');+ MultiByteToWideChar(CP_UTF8, 0, str.c_str(),+ static_cast<int>(str.size()), &result[0], size);+ return result;+ }++ std::string PostgreSQLAdapter::quoteIdentifier(const std::wstring& name)+ {+ return "\"" + toUtf8(name) + "\"";+ }++ std::string PostgreSQLAdapter::quoteLiteral(const std::wstring& value)+ {+ std::string utf8 = toUtf8(value);+ std::string escaped;+ escaped.reserve(utf8.size() + 2);+ escaped += '\'';+ for (char c : utf8)+ {+ if (c == '\'') escaped += "''";+ else escaped += c;+ }+ escaped += '\'';+ return escaped;+ }++ void PostgreSQLAdapter::ensureConnected() const+ {+ if (!connected_ || !conn_)+ throw DatabaseError(DatabaseError::Code::ConnectionFailed, "Not connected to database");+ }++ // ── Constructor / Destructor ────────────────────+ PostgreSQLAdapter::PostgreSQLAdapter() = default;++ PostgreSQLAdapter::~PostgreSQLAdapter()+ {+ if (conn_)+ {+ PQfinish(conn_);+ conn_ = nullptr;+ }+ }++ // ── Connection ──────────────────────────────────+ void PostgreSQLAdapter::connect(const ConnectionConfig& config, const std::wstring& password)+ {+ disconnect();++ // Build connection string+ std::string connStr;+ connStr += "host=" + toUtf8(config.host);+ connStr += " port=" + std::to_string(config.port);+ connStr += " dbname=" + toUtf8(config.database);+ connStr += " user=" + toUtf8(config.username);+ if (!password.empty())+ connStr += " password=" + toUtf8(password);++ // SSL mode+ switch (config.sslMode)+ {+ case SSLMode::Disabled: connStr += " sslmode=disable"; break;+ case SSLMode::Preferred: connStr += " sslmode=prefer"; break;+ case SSLMode::Required: connStr += " sslmode=require"; break;+ case SSLMode::VerifyCA: connStr += " sslmode=verify-ca"; break;+ case SSLMode::VerifyIdentity: connStr += " sslmode=verify-full"; break;+ }++ connStr += " connect_timeout=10";++ conn_ = PQconnectdb(connStr.c_str());+ if (PQstatus(conn_) != CONNECTION_OK)+ {+ std::string err = PQerrorMessage(conn_);+ PQfinish(conn_);+ conn_ = nullptr;+ throw DatabaseError(DatabaseError::Code::ConnectionFailed, err);+ }++ connected_ = true;++ // Set UTF-8 encoding+ PQsetClientEncoding(conn_, "UTF8");+ }++ void PostgreSQLAdapter::disconnect()+ {+ if (conn_)+ {+ PQfinish(conn_);+ conn_ = nullptr;+ }+ connected_ = false;+ }++ bool PostgreSQLAdapter::testConnection(const ConnectionConfig& config, const std::wstring& password)+ {+ try+ {+ connect(config, password);+ auto result = execute(L"SELECT 1");+ disconnect();+ return result.success;+ }+ catch (...)+ {+ disconnect();+ return false;+ }+ }++ bool PostgreSQLAdapter::isConnected() const { return connected_ && conn_; }++ // ── Query Execution ─────────────────────────────+ QueryResult PostgreSQLAdapter::executeInternal(const std::string& sql)+ {+ ensureConnected();++ auto start = std::chrono::high_resolution_clock::now();++ PGresult* pgResult = PQexec(conn_, sql.c_str());+ auto end = std::chrono::high_resolution_clock::now();+ double durationMs = std::chrono::duration<double, std::milli>(end - start).count();++ QueryResult result;+ result.sql = fromUtf8(sql);+ result.executionTimeMs = durationMs;++ ExecStatusType status = PQresultStatus(pgResult);++ if (status == PGRES_TUPLES_OK)+ {+ int nCols = PQnfields(pgResult);+ int nRows = PQntuples(pgResult);++ // Column names and types — pre-reserve to avoid reallocation+ result.columnNames.reserve(nCols);+ result.columnTypes.reserve(nCols);+ for (int c = 0; c < nCols; c++)+ {+ result.columnNames.push_back(fromUtf8(PQfname(pgResult, c)));+ // Store OID as string; resolve to type name later if needed+ Oid typeOid = PQftype(pgResult, c);+ result.columnTypes.push_back(std::to_wstring(typeOid));+ }++ // PERFORMANCE: pre-reserve rows vector + pre-reserve each row's+ // hash buckets, capture column name by const-ref (no per-cell copy),+ // and move-construct the row into the result (no map deep-copy).+ // This is the dominant cost on wide tables (100rows x 30cols).+ result.rows.reserve(nRows);+ for (int r = 0; r < nRows; r++)+ {+ TableRow row;+ row.reserve(nCols);+ for (int c = 0; c < nCols; c++)+ {+ const std::wstring& colName = result.columnNames[c];+ if (PQgetisnull(pgResult, r, c))+ row.emplace(colName, nullValue());+ else+ row.emplace(colName, fromUtf8(PQgetvalue(pgResult, r, c)));+ }+ result.rows.push_back(std::move(row));+ }++ result.totalRows = nRows;+ result.success = true;+ }+ else if (status == PGRES_COMMAND_OK)+ {+ // DML: INSERT/UPDATE/DELETE — no result rows+ const char* affected = PQcmdTuples(pgResult);+ if (affected && *affected)+ result.totalRows = std::stoi(affected);+ result.success = true;+ }+ else+ {+ result.success = false;+ result.error = fromUtf8(PQresultErrorMessage(pgResult));+ }++ PQclear(pgResult);+ return result;+ }++ QueryResult PostgreSQLAdapter::execute(const std::wstring& sql)+ {+ return executeInternal(toUtf8(sql));+ }++ QueryResult PostgreSQLAdapter::fetchRows(+ const std::wstring& table, const std::wstring& schema,+ int limit, int offset,+ const std::wstring& orderBy, bool ascending)+ {+ std::string sql = "SELECT * FROM " + quoteIdentifier(schema) + "." + quoteIdentifier(table);+ if (!orderBy.empty())+ sql += " ORDER BY " + quoteIdentifier(orderBy) + (ascending ? " ASC" : " DESC");+ sql += " LIMIT " + std::to_string(limit) + " OFFSET " + std::to_string(offset);++ auto result = executeInternal(sql);++ // Get total row count for pagination metadata+ std::string countSql = "SELECT COUNT(*) FROM " + quoteIdentifier(schema) + "." + quoteIdentifier(table);+ auto countResult = executeInternal(countSql);+ if (countResult.success && !countResult.rows.empty())+ {+ auto& firstRow = countResult.rows[0];+ auto it = firstRow.find(L"count");+ if (it != firstRow.end())+ result.totalRows = std::stoi(toUtf8(it->second));+ }++ result.currentPage = (offset / limit) + 1;+ result.pageSize = limit;+ return result;+ }++ // ── Schema Inspection ───────────────────────────+ std::vector<std::wstring> PostgreSQLAdapter::listDatabases()+ {+ auto result = executeInternal(+ "SELECT datname FROM pg_database WHERE datistemplate = false ORDER BY datname");+ std::vector<std::wstring> dbs;+ for (auto& row : result.rows)+ {+ auto it = row.find(L"datname");+ if (it != row.end()) dbs.push_back(it->second);+ }+ return dbs;+ }++ std::vector<std::wstring> PostgreSQLAdapter::listSchemas()+ {+ auto result = executeInternal(+ "SELECT schema_name FROM information_schema.schemata "+ "WHERE schema_name NOT IN ('pg_catalog','information_schema','pg_toast') "+ "ORDER BY schema_name");+ std::vector<std::wstring> schemas;+ for (auto& row : result.rows)+ {+ auto it = row.find(L"schema_name");+ if (it != row.end()) schemas.push_back(it->second);+ }+ return schemas;+ }++ std::vector<TableInfo> PostgreSQLAdapter::listTables(const std::wstring& schema)+ {+ std::string sql =+ "SELECT c.relname AS name, n.nspname AS schema, "+ "pg_catalog.obj_description(c.oid) AS comment, "+ "c.reltuples::bigint AS estimated_rows, "+ "pg_total_relation_size(c.oid) AS size_bytes "+ "FROM pg_class c "+ "JOIN pg_namespace n ON n.oid = c.relnamespace "+ "WHERE c.relkind = 'r' AND n.nspname = " + quoteLiteral(schema) ++ " ORDER BY c.relname";++ auto result = executeInternal(sql);+ std::vector<TableInfo> tables;+ for (auto& row : result.rows)+ {+ TableInfo info;+ info.name = row[L"name"];+ info.schema = row[L"schema"];+ info.type = L"table";+ info.comment = row[L"comment"];+ auto estIt = row.find(L"estimated_rows");+ if (estIt != row.end() && !isNullCell(estIt->second))+ info.estimatedRows = std::stoll(toUtf8(estIt->second));+ auto sizeIt = row.find(L"size_bytes");+ if (sizeIt != row.end() && !isNullCell(sizeIt->second))+ info.sizeBytes = std::stoll(toUtf8(sizeIt->second));+ tables.push_back(info);+ }+ return tables;+ }++ std::vector<TableInfo> PostgreSQLAdapter::listViews(const std::wstring& schema)+ {+ std::string sql =+ "SELECT c.relname AS name, n.nspname AS schema, "+ "pg_catalog.obj_description(c.oid) AS comment "+ "FROM pg_class c "+ "JOIN pg_namespace n ON n.oid = c.relnamespace "+ "WHERE c.relkind IN ('v','m') AND n.nspname = " + quoteLiteral(schema) ++ " ORDER BY c.relname";++ auto result = executeInternal(sql);+ std::vector<TableInfo> views;+ for (auto& row : result.rows)+ {+ TableInfo info;+ info.name = row[L"name"];+ info.schema = row[L"schema"];+ info.type = L"view";+ views.push_back(info);+ }+ return views;+ }++ std::vector<ColumnInfo> PostgreSQLAdapter::describeTable(+ const std::wstring& table, const std::wstring& schema)+ {+ std::string sql =+ "SELECT c.column_name, c.data_type, c.is_nullable, c.column_default, "+ "c.ordinal_position, c.udt_name, c.character_maximum_length, "+ "c.numeric_precision, c.numeric_scale, "+ "CASE WHEN pk.column_name IS NOT NULL THEN true ELSE false END AS is_pk "+ "FROM information_schema.columns c "+ "LEFT JOIN ("+ " SELECT ku.column_name "+ " FROM information_schema.table_constraints tc "+ " JOIN information_schema.key_column_usage ku ON tc.constraint_name = ku.constraint_name "+ " WHERE tc.constraint_type = 'PRIMARY KEY' "+ " AND tc.table_name = " + quoteLiteral(table) ++ " AND tc.table_schema = " + quoteLiteral(schema) ++ ") pk ON pk.column_name = c.column_name "+ "WHERE c.table_name = " + quoteLiteral(table) ++ " AND c.table_schema = " + quoteLiteral(schema) ++ " ORDER BY c.ordinal_position";++ auto result = executeInternal(sql);+ std::vector<ColumnInfo> columns;+ for (auto& row : result.rows)+ {+ ColumnInfo col;+ col.name = row[L"column_name"];++ // Build display type (e.g. "varchar(255)", "numeric(12,2)")+ std::wstring udtName = row[L"udt_name"];+ std::wstring dataType = row[L"data_type"];+ if (dataType == L"character varying")+ {+ auto maxLen = row[L"character_maximum_length"];+ col.dataType = !isNullCell(maxLen)+ ? std::wstring(L"varchar(") + maxLen + L")"+ : L"varchar";+ }+ else if (dataType == L"numeric")+ {+ auto prec = row[L"numeric_precision"];+ auto scale = row[L"numeric_scale"];+ col.dataType = !isNullCell(prec)+ ? std::wstring(L"numeric(") + prec + L"," + scale + L")"+ : L"numeric";+ }+ else if (dataType == L"USER-DEFINED")+ {+ col.dataType = udtName;+ }+ else+ {+ col.dataType = dataType;+ }++ col.nullable = (row[L"is_nullable"] == L"YES");+ col.defaultValue = !isNullCell(row[L"column_default"]) ? row[L"column_default"] : L"";+ col.isPrimaryKey = (row[L"is_pk"] == L"t" || row[L"is_pk"] == L"true");+ auto ordIt = row.find(L"ordinal_position");+ if (ordIt != row.end() && !isNullCell(ordIt->second))+ col.ordinalPosition = std::stoi(toUtf8(ordIt->second));+ columns.push_back(col);+ }++ // Mark FK columns using listForeignKeys+ auto fks = listForeignKeys(table, schema);+ for (auto& fk : fks)+ {+ for (auto& col : columns)+ {+ if (col.name == fk.column)+ {+ col.isForeignKey = true;+ col.fkReferencedTable = fk.referencedTable;+ col.fkReferencedColumn = fk.referencedColumn;+ }+ }+ }++ return columns;+ }++ std::vector<IndexInfo> PostgreSQLAdapter::listIndexes(+ const std::wstring& table, const std::wstring& schema)+ {+ std::string sql =+ "SELECT i.relname AS index_name, "+ "am.amname AS algorithm, "+ "ix.indisunique AS is_unique, "+ "ix.indisprimary AS is_primary, "+ "array_to_string(ARRAY("+ " SELECT a.attname FROM unnest(ix.indkey) WITH ORDINALITY AS k(attnum, ord) "+ " JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum "+ " ORDER BY k.ord"+ "), ', ') AS columns "+ "FROM pg_class t "+ "JOIN pg_namespace n ON n.oid = t.relnamespace "+ "JOIN pg_index ix ON t.oid = ix.indrelid "+ "JOIN pg_class i ON i.oid = ix.indexrelid "+ "JOIN pg_am am ON am.oid = i.relam "+ "WHERE t.relname = " + quoteLiteral(table) ++ " AND n.nspname = " + quoteLiteral(schema) ++ " ORDER BY i.relname";++ auto result = executeInternal(sql);+ std::vector<IndexInfo> indexes;+ for (auto& row : result.rows)+ {+ IndexInfo idx;+ idx.name = row[L"index_name"];+ idx.columns = row[L"columns"];+ idx.isUnique = (row[L"is_unique"] == L"t");+ idx.isPrimary = (row[L"is_primary"] == L"t");+ idx.algorithm = row[L"algorithm"];+ indexes.push_back(idx);+ }+ return indexes;+ }++ std::vector<ForeignKeyInfo> PostgreSQLAdapter::listForeignKeys(+ const std::wstring& table, const std::wstring& schema)+ {+ std::string sql =+ "SELECT conname AS name, "+ "a.attname AS column_name, "+ "cf.relname AS ref_table, "+ "af.attname AS ref_column, "+ "CASE confupdtype WHEN 'c' THEN 'CASCADE' WHEN 'n' THEN 'SET NULL' "+ " WHEN 'd' THEN 'SET DEFAULT' WHEN 'r' THEN 'RESTRICT' ELSE 'NO ACTION' END AS on_update, "+ "CASE confdeltype WHEN 'c' THEN 'CASCADE' WHEN 'n' THEN 'SET NULL' "+ " WHEN 'd' THEN 'SET DEFAULT' WHEN 'r' THEN 'RESTRICT' ELSE 'NO ACTION' END AS on_delete "+ "FROM pg_constraint co "+ "JOIN pg_class c ON c.oid = co.conrelid "+ "JOIN pg_namespace n ON n.oid = c.relnamespace "+ "JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = ANY(co.conkey) "+ "JOIN pg_class cf ON cf.oid = co.confrelid "+ "JOIN pg_attribute af ON af.attrelid = cf.oid AND af.attnum = ANY(co.confkey) "+ "WHERE co.contype = 'f' "+ "AND c.relname = " + quoteLiteral(table) ++ " AND n.nspname = " + quoteLiteral(schema) ++ " ORDER BY conname";++ auto result = executeInternal(sql);+ std::vector<ForeignKeyInfo> fks;+ for (auto& row : result.rows)+ {+ ForeignKeyInfo fk;+ fk.name = row[L"name"];+ fk.column = row[L"column_name"];+ fk.referencedTable = row[L"ref_table"];+ fk.referencedColumn = row[L"ref_column"];+ fk.onUpdate = row[L"on_update"];+ fk.onDelete = row[L"on_delete"];+ fks.push_back(fk);+ }+ return fks;+ }++ std::vector<std::wstring> PostgreSQLAdapter::listFunctions(const std::wstring& schema)+ {+ std::string sql =+ "SELECT p.proname AS name "+ "FROM pg_proc p "+ "JOIN pg_namespace n ON n.oid = p.pronamespace "+ "WHERE n.nspname = " + quoteLiteral(schema) ++ " AND p.prokind = 'f' "+ "ORDER BY p.proname";++ auto result = executeInternal(sql);+ std::vector<std::wstring> funcs;+ for (auto& row : result.rows)+ {+ auto it = row.find(L"name");+ if (it != row.end()) funcs.push_back(it->second);+ }+ return funcs;+ }++ std::wstring PostgreSQLAdapter::getFunctionSource(+ const std::wstring& name, const std::wstring& schema)+ {+ std::string sql =+ "SELECT pg_get_functiondef(p.oid) AS source "+ "FROM pg_proc p "+ "JOIN pg_namespace n ON n.oid = p.pronamespace "+ "WHERE p.proname = " + quoteLiteral(name) ++ " AND n.nspname = " + quoteLiteral(schema) ++ " LIMIT 1";++ auto result = executeInternal(sql);+ if (!result.rows.empty())+ {+ auto it = result.rows[0].find(L"source");+ if (it != result.rows[0].end()) return it->second;+ }+ return L"";+ }++ std::wstring PostgreSQLAdapter::getCreateTableSQL(+ const std::wstring& table, const std::wstring& schema)+ {+ // Build DDL from describeTable output — basic columns + NOT NULL + DEFAULT + PK+ auto columns = describeTable(table, schema);+ if (columns.empty()) return L"";++ std::wstring sql = L"CREATE TABLE \"" + schema + L"\".\"" + table + L"\" (\n";+ std::vector<std::wstring> pkCols;+ for (size_t i = 0; i < columns.size(); i++)+ {+ const auto& col = columns[i];+ sql += L" \"" + col.name + L"\" " + col.dataType;+ if (!col.nullable) sql += L" NOT NULL";+ if (!col.defaultValue.empty())+ sql += L" DEFAULT " + col.defaultValue;+ if (i + 1 < columns.size() || std::any_of(columns.begin(), columns.end(),+ [](const ColumnInfo& c) { return c.isPrimaryKey; }))+ sql += L",";+ sql += L"\n";+ if (col.isPrimaryKey) pkCols.push_back(col.name);+ }+ if (!pkCols.empty())+ {+ sql += L" PRIMARY KEY (";+ for (size_t i = 0; i < pkCols.size(); i++)+ {+ if (i > 0) sql += L", ";+ sql += L"\"" + pkCols[i] + L"\"";+ }+ sql += L")\n";+ }+ sql += L")";+ return sql;+ }++ // ── DML ─────────────────────────────────────────+ QueryResult PostgreSQLAdapter::insertRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& values)+ {+ std::string sql = "INSERT INTO " + quoteIdentifier(schema) + "." + quoteIdentifier(table) + " (";+ std::string valsSql;+ bool first = true;+ for (auto& [col, val] : values)+ {+ if (!first) { sql += ", "; valsSql += ", "; }+ sql += quoteIdentifier(col);+ valsSql += isNullCell(val) ? "NULL" : quoteLiteral(val);+ first = false;+ }+ sql += ") VALUES (" + valsSql + ")";+ return executeInternal(sql);+ }++ QueryResult PostgreSQLAdapter::updateRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& setValues, const TableRow& whereValues)+ {+ std::string sql = "UPDATE " + quoteIdentifier(schema) + "." + quoteIdentifier(table) + " SET ";+ bool first = true;+ for (auto& [col, val] : setValues)+ {+ if (!first) sql += ", ";+ sql += quoteIdentifier(col) + " = " + (isNullCell(val) ? "NULL" : quoteLiteral(val));+ first = false;+ }+ sql += " WHERE ";+ first = true;+ for (auto& [col, val] : whereValues)+ {+ if (!first) sql += " AND ";+ // Correct SQL for NULL match is IS NULL, not = NULL+ if (isNullCell(val))+ sql += quoteIdentifier(col) + " IS NULL";+ else+ sql += quoteIdentifier(col) + " = " + quoteLiteral(val);+ first = false;+ }+ return executeInternal(sql);+ }++ QueryResult PostgreSQLAdapter::deleteRow(+ const std::wstring& table, const std::wstring& schema,+ const TableRow& whereValues)+ {+ std::string sql = "DELETE FROM " + quoteIdentifier(schema) + "." + quoteIdentifier(table) + " WHERE ";+ bool first = true;+ for (auto& [col, val] : whereValues)+ {+ if (!first) sql += " AND ";+ if (isNullCell(val))+ sql += quoteIdentifier(col) + " IS NULL";+ else+ sql += quoteIdentifier(col) + " = " + quoteLiteral(val);+ first = false;+ }+ return executeInternal(sql);+ }++ // ── Transactions ────────────────────────────────+ void PostgreSQLAdapter::beginTransaction() { executeInternal("BEGIN"); }+ void PostgreSQLAdapter::commitTransaction() { executeInternal("COMMIT"); }+ void PostgreSQLAdapter::rollbackTransaction() { executeInternal("ROLLBACK"); }++ // ── Server Info ─────────────────────────────────+ std::wstring PostgreSQLAdapter::serverVersion()+ {+ auto result = executeInternal("SHOW server_version");+ if (!result.rows.empty())+ {+ auto it = result.rows[0].find(L"server_version");+ if (it != result.rows[0].end()) return it->second;+ }+ return L"Unknown";+ }++ std::wstring PostgreSQLAdapter::currentDatabase()+ {+ auto result = executeInternal("SELECT current_database()");+ if (!result.rows.empty())+ {+ auto it = result.rows[0].find(L"current_database");+ if (it != result.rows[0].end()) return it->second;+ }+ return L"";+ }+}diff --git a/windows/Gridex/QueryEditorView.cpp b/windows/Gridex/QueryEditorView.cppnew file mode 100644index 0000000..46d9bac--- /dev/null+++ b/windows/Gridex/QueryEditorView.cpp@@ -0,0 +1,670 @@+#include "pch.h"+#include "xaml-includes.h"+#include <winrt/Windows.UI.Text.h>+#include <winrt/Windows.UI.Core.h>+#include <winrt/Windows.System.h>+#include <winrt/Microsoft.UI.Input.h>+#include "QueryEditorView.h"+#if __has_include("QueryEditorView.g.cpp")+#include "QueryEditorView.g.cpp"+#endif++namespace winrt::Gridex::implementation+{+ namespace mux = winrt::Microsoft::UI::Xaml;+ namespace muxc = winrt::Microsoft::UI::Xaml::Controls;+ namespace muxm = winrt::Microsoft::UI::Xaml::Media;++ // SQL keywords for autocomplete+ const std::vector<std::wstring>& QueryEditorView::SqlKeywords()+ {+ static std::vector<std::wstring> kw = {+ L"SELECT", L"FROM", L"WHERE", L"AND", L"OR", L"NOT", L"IN",+ L"JOIN", L"LEFT JOIN", L"RIGHT JOIN", L"INNER JOIN", L"OUTER JOIN",+ L"ON", L"AS", L"GROUP BY", L"ORDER BY", L"HAVING", L"LIMIT", L"OFFSET",+ L"INSERT INTO", L"VALUES", L"UPDATE", L"SET", L"DELETE FROM",+ L"CREATE TABLE", L"ALTER TABLE", L"DROP TABLE",+ L"DISTINCT", L"COUNT", L"SUM", L"AVG", L"MIN", L"MAX",+ L"IS NULL", L"IS NOT NULL", L"LIKE", L"BETWEEN", L"EXISTS",+ L"CASE", L"WHEN", L"THEN", L"ELSE", L"END",+ L"ASC", L"DESC", L"UNION", L"UNION ALL",+ L"PRIMARY KEY", L"FOREIGN KEY", L"REFERENCES", L"DEFAULT",+ L"NOT NULL", L"UNIQUE", L"INDEX", L"CASCADE",+ L"BEGIN", L"COMMIT", L"ROLLBACK",+ L"TRUE", L"FALSE", L"NULL",+ L"COALESCE", L"NULLIF", L"CAST", L"EXTRACT",+ L"NOW()", L"CURRENT_TIMESTAMP", L"CURRENT_DATE",+ };+ return kw;+ }++ QueryEditorView::QueryEditorView()+ {+ InitializeComponent();++ this->Loaded([this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ EnsureEditorCreated();+ });++ this->RegisterPropertyChangedCallback(+ mux::UIElement::VisibilityProperty(),+ [this](mux::DependencyObject const&, mux::DependencyProperty const&)+ {+ if (this->Visibility() == mux::Visibility::Visible)+ EnsureEditorCreated();+ });+ }++ void QueryEditorView::EnsureEditorCreated()+ {+ if (editorCreated_) return;+ editorCreated_ = true;++ // Wire buttons+ RunQueryButton().Click(+ [this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ { RunQuery_Click({}, {}); });+ FormatQueryButton().Click(+ [this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ { FormatQuery_Click({}, {}); });+ ClearEditorButton().Click(+ [this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ { ClearEditor_Click({}, {}); });++ // Create SQL editor TextBox+ sqlEditor_ = muxc::TextBox();+ sqlEditor_.AcceptsReturn(true);+ sqlEditor_.TextWrapping(mux::TextWrapping::NoWrap);+ sqlEditor_.FontFamily(mux::Media::FontFamily(L"Cascadia Code,Consolas,monospace"));+ sqlEditor_.FontSize(13.0);+ sqlEditor_.PlaceholderText(L"-- Write SQL here... (Ctrl+Enter to run, Ctrl+Space for suggestions)");+ sqlEditor_.HorizontalAlignment(mux::HorizontalAlignment::Stretch);+ sqlEditor_.VerticalAlignment(mux::VerticalAlignment::Stretch);+ sqlEditor_.Padding(mux::Thickness{ 12, 8, 12, 8 });+ sqlEditor_.BorderThickness(mux::Thickness{ 0,0,0,0 });+ sqlEditor_.Background(muxm::SolidColorBrush(winrt::Windows::UI::Colors::Transparent()));++ // Text changed → trigger autocomplete+ sqlEditor_.TextChanged(+ [this](winrt::Windows::Foundation::IInspectable const&, muxc::TextChangedEventArgs const&)+ {+ if (!suppressTextChange_)+ OnEditorTextChanged();+ });++ // Key handling: use PreviewKeyDown to intercept BEFORE TextBox processes Enter+ sqlEditor_.PreviewKeyDown(+ [this](winrt::Windows::Foundation::IInspectable const&, mux::Input::KeyRoutedEventArgs const& e)+ {+ auto ctrlState = winrt::Microsoft::UI::Input::InputKeyboardSource::GetKeyStateForCurrentThread(+ winrt::Windows::System::VirtualKey::Control);+ bool ctrlDown = (static_cast<int>(ctrlState) &+ static_cast<int>(winrt::Windows::UI::Core::CoreVirtualKeyStates::Down)) != 0;++ if (e.Key() == winrt::Windows::System::VirtualKey::Enter && ctrlDown)+ {+ ExecuteCurrentQuery();+ e.Handled(true);+ return;+ }++ if (e.Key() == winrt::Windows::System::VirtualKey::Space && ctrlDown)+ {+ // Force show ALL suggestions based on context+ ForceShowSuggestions();+ e.Handled(true);+ return;+ }++ // If suggest popup visible, handle navigation+ if (SuggestPopup().Visibility() == mux::Visibility::Visible)+ {+ if (e.Key() == winrt::Windows::System::VirtualKey::Escape)+ {+ HideSuggestions();+ e.Handled(true);+ return;+ }+ if (e.Key() == winrt::Windows::System::VirtualKey::Tab ||+ (e.Key() == winrt::Windows::System::VirtualKey::Enter && !ctrlDown))+ {+ // Apply selected suggestion+ auto selected = SuggestList().SelectedItem();+ if (selected)+ {+ auto item = selected.try_as<muxc::TextBlock>();+ if (item)+ ApplySuggestion(std::wstring(item.Text()));+ }+ else if (SuggestList().Items().Size() > 0)+ {+ // Apply first item+ auto first = SuggestList().Items().GetAt(0).try_as<muxc::TextBlock>();+ if (first)+ ApplySuggestion(std::wstring(first.Text()));+ }+ HideSuggestions();+ e.Handled(true);+ return;+ }+ if (e.Key() == winrt::Windows::System::VirtualKey::Down)+ {+ int idx = SuggestList().SelectedIndex();+ if (idx < static_cast<int>(SuggestList().Items().Size()) - 1)+ SuggestList().SelectedIndex(idx + 1);+ e.Handled(true);+ return;+ }+ if (e.Key() == winrt::Windows::System::VirtualKey::Up)+ {+ int idx = SuggestList().SelectedIndex();+ if (idx > 0) SuggestList().SelectedIndex(idx - 1);+ e.Handled(true);+ return;+ }+ }+ });++ EditorContainer().Children().InsertAt(0, sqlEditor_); // Insert before popup+ editorReady_ = true;++ // Wire suggest list item click+ SuggestList().ItemClick(+ [this](winrt::Windows::Foundation::IInspectable const&, muxc::ItemClickEventArgs const& e)+ {+ auto item = e.ClickedItem().try_as<muxc::TextBlock>();+ if (item)+ ApplySuggestion(std::wstring(item.Text()));+ HideSuggestions();+ });++ if (!pendingSql_.empty())+ {+ sqlEditor_.Text(winrt::hstring(pendingSql_));+ pendingSql_.clear();+ }+ }++ // ── Autocomplete logic ─────────────────────────────++ std::wstring QueryEditorView::GetCurrentWord() const+ {+ if (!sqlEditor_) return L"";+ std::wstring text(sqlEditor_.Text());+ int pos = sqlEditor_.SelectionStart();+ if (pos <= 0 || pos > static_cast<int>(text.size())) return L"";++ // Walk backwards from cursor to find word start+ int start = pos - 1;+ while (start >= 0 && text[start] != L' ' && text[start] != L'\n' &&+ text[start] != L'\r' && text[start] != L'\t' &&+ text[start] != L'(' && text[start] != L')' &&+ text[start] != L',' && text[start] != L';')+ {+ start--;+ }+ start++;++ if (start >= pos) return L"";+ return text.substr(start, pos - start);+ }++ void QueryEditorView::ForceShowSuggestions()+ {+ std::wstring currentWord = GetCurrentWord();+ std::wstring prefix = currentWord;+ std::transform(prefix.begin(), prefix.end(), prefix.begin(), ::towlower);++ std::wstring prevKw = GetPreviousKeyword();+ // If current word is empty, use previous keyword as context directly+ if (currentWord.empty() && !prevKw.empty())+ {+ // After space — context determines what to show+ }++ bool wantTables = (prevKw == L"FROM" || prevKw == L"JOIN" || prevKw == L"INTO" ||+ prevKw == L"UPDATE" || prevKw == L"TABLE");+ bool wantColumns = (prevKw == L"SELECT" || prevKw == L"WHERE" || prevKw == L"AND" ||+ prevKw == L"OR" || prevKw == L"ON" || prevKw == L"SET" ||+ prevKw == L"BY" || prevKw == L"HAVING" || prevKw == L"DISTINCT");++ std::vector<std::wstring> matches;++ if (wantTables || (!wantColumns && !wantTables))+ {+ for (auto& t : schemaTableNames_)+ {+ if (prefix.empty() || [&]() {+ std::wstring lower = t;+ std::transform(lower.begin(), lower.end(), lower.begin(), ::towlower);+ return lower.find(prefix) == 0;+ }())+ matches.push_back(t);+ }+ }++ if (wantColumns || (!wantColumns && !wantTables))+ {+ for (auto& c : schemaColumnNames_)+ {+ if (prefix.empty() || [&]() {+ std::wstring lower = c;+ std::transform(lower.begin(), lower.end(), lower.begin(), ::towlower);+ return lower.find(prefix) == 0;+ }())+ matches.push_back(c);+ }+ }++ // Functions+ for (auto& f : schemaFunctionNames_)+ {+ if (prefix.empty() || [&]() {+ std::wstring lower = f;+ std::transform(lower.begin(), lower.end(), lower.begin(), ::towlower);+ return lower.find(prefix) == 0;+ }())+ matches.push_back(f);+ }++ // Keywords (limit to 10 when showing all)+ int kwCount = 0;+ for (auto& kw : SqlKeywords())+ {+ if (kwCount >= 10) break;+ if (prefix.empty() || [&]() {+ std::wstring lower = kw;+ std::transform(lower.begin(), lower.end(), lower.begin(), ::towlower);+ return lower.find(prefix) == 0;+ }())+ {+ matches.push_back(kw);+ kwCount++;+ }+ }++ if (!matches.empty())+ ShowSuggestions(matches);+ }++ // Determine SQL context keyword before current word+ std::wstring QueryEditorView::GetPreviousKeyword() const+ {+ if (!sqlEditor_) return L"";+ std::wstring text(sqlEditor_.Text());+ int pos = sqlEditor_.SelectionStart();++ // Skip current word backwards+ int i = pos - 1;+ while (i >= 0 && text[i] != L' ' && text[i] != L'\n' && text[i] != L'\t') i--;+ // Skip whitespace+ while (i >= 0 && (text[i] == L' ' || text[i] == L'\n' || text[i] == L'\t' || text[i] == L'\r')) i--;+ // Read previous word+ int end = i + 1;+ while (i >= 0 && text[i] != L' ' && text[i] != L'\n' && text[i] != L'\t' &&+ text[i] != L'(' && text[i] != L')' && text[i] != L',' && text[i] != L';') i--;+ i++;++ if (i >= end) return L"";+ std::wstring kw = text.substr(i, end - i);+ std::transform(kw.begin(), kw.end(), kw.begin(), ::towupper);+ return kw;+ }++ void QueryEditorView::OnEditorTextChanged()+ {+ std::wstring currentWord = GetCurrentWord();+ if (currentWord.empty())+ {+ HideSuggestions();+ return;+ }++ std::wstring prefix = currentWord;+ std::transform(prefix.begin(), prefix.end(), prefix.begin(), ::towlower);++ // Determine context from previous keyword+ std::wstring prevKw = GetPreviousKeyword();+ bool wantTables = (prevKw == L"FROM" || prevKw == L"JOIN" || prevKw == L"INTO" ||+ prevKw == L"UPDATE" || prevKw == L"TABLE");+ bool wantColumns = (prevKw == L"SELECT" || prevKw == L"WHERE" || prevKw == L"AND" ||+ prevKw == L"OR" || prevKw == L"ON" || prevKw == L"SET" ||+ prevKw == L"BY" || prevKw == L"HAVING" || prevKw == L"DISTINCT");++ std::vector<std::wstring> matches;++ // Context-aware: prioritize relevant items+ if (wantTables)+ {+ for (auto& t : schemaTableNames_)+ {+ std::wstring lower = t;+ std::transform(lower.begin(), lower.end(), lower.begin(), ::towlower);+ if (lower.find(prefix) == 0) matches.push_back(t);+ }+ }++ if (wantColumns)+ {+ for (auto& c : schemaColumnNames_)+ {+ std::wstring lower = c;+ std::transform(lower.begin(), lower.end(), lower.begin(), ::towlower);+ if (lower.find(prefix) == 0) matches.push_back(c);+ }+ }++ // Always suggest matching tables/columns/functions if no context match yet+ if (!wantTables && !wantColumns)+ {+ for (auto& t : schemaTableNames_)+ {+ std::wstring lower = t;+ std::transform(lower.begin(), lower.end(), lower.begin(), ::towlower);+ if (lower.find(prefix) == 0) matches.push_back(t);+ }+ for (auto& c : schemaColumnNames_)+ {+ std::wstring lower = c;+ std::transform(lower.begin(), lower.end(), lower.begin(), ::towlower);+ if (lower.find(prefix) == 0) matches.push_back(c);+ }+ }++ // Functions+ for (auto& f : schemaFunctionNames_)+ {+ std::wstring lower = f;+ std::transform(lower.begin(), lower.end(), lower.begin(), ::towlower);+ if (lower.find(prefix) == 0) matches.push_back(f);+ }++ // SQL keywords (always)+ for (auto& kw : SqlKeywords())+ {+ std::wstring lower = kw;+ std::transform(lower.begin(), lower.end(), lower.begin(), ::towlower);+ if (lower.find(prefix) == 0 && matches.size() < 10)+ matches.push_back(kw);+ }++ if (matches.empty() || matches.size() > 15)+ {+ HideSuggestions();+ return;+ }++ ShowSuggestions(matches);+ }++ void QueryEditorView::ShowSuggestions(const std::vector<std::wstring>& items)+ {+ SuggestList().Items().Clear();+ for (auto& item : items)+ {+ muxc::TextBlock tb;+ // Check if has icon prefix (unicode char + space)+ if (item.size() > 2 && item[1] == L' ' && item[0] > 0xE000)+ {+ // Strip icon for display, just show text+ tb.Text(winrt::hstring(item.substr(2)));+ }+ else+ {+ tb.Text(winrt::hstring(item));+ }+ tb.FontSize(12.0);+ tb.FontFamily(mux::Media::FontFamily(L"Cascadia Code,Consolas,monospace"));+ tb.Padding(mux::Thickness{ 8, 3, 8, 3 });+ SuggestList().Items().Append(tb);+ }+ if (SuggestList().Items().Size() > 0)+ SuggestList().SelectedIndex(0);+ SuggestPopup().Visibility(mux::Visibility::Visible);+ }++ void QueryEditorView::HideSuggestions()+ {+ SuggestPopup().Visibility(mux::Visibility::Collapsed);+ }++ void QueryEditorView::ApplySuggestion(const std::wstring& text)+ {+ if (!sqlEditor_) return;++ std::wstring fullText(sqlEditor_.Text());+ int cursorPos = sqlEditor_.SelectionStart();++ // Find current word boundaries+ int start = cursorPos - 1;+ while (start >= 0 && fullText[start] != L' ' && fullText[start] != L'\n' &&+ fullText[start] != L'\r' && fullText[start] != L'\t' &&+ fullText[start] != L'(' && fullText[start] != L')' &&+ fullText[start] != L',' && fullText[start] != L';')+ {+ start--;+ }+ start++;++ // Replace current word with suggestion+ suppressTextChange_ = true;+ std::wstring newText = fullText.substr(0, start) + text + fullText.substr(cursorPos);+ sqlEditor_.Text(winrt::hstring(newText));+ sqlEditor_.SelectionStart(static_cast<int32_t>(start + text.size()));+ sqlEditor_.SelectionLength(0);+ suppressTextChange_ = false;++ sqlEditor_.Focus(mux::FocusState::Programmatic);+ }++ void QueryEditorView::SetSchemaCompletions(+ const std::vector<std::wstring>& tables,+ const std::vector<std::wstring>& columns,+ const std::vector<std::wstring>& functions)+ {+ schemaTableNames_ = tables;+ schemaColumnNames_ = columns;+ schemaFunctionNames_ = functions;+ }++ // ── Core methods ───────────────────────────────────++ void QueryEditorView::ExecuteCurrentQuery()+ {+ if (!sqlEditor_) return;+ std::wstring sql(sqlEditor_.Text());+ if (sql.empty()) return;+ HideSuggestions();++ QueryStatusText().Text(L"Running...");++ if (OnExecuteQuery)+ {+ lastResult_ = OnExecuteQuery(sql);+ if (lastResult_.success)+ ShowResult(lastResult_);+ else+ ShowError(lastResult_.error);+ }+ }++ void QueryEditorView::SetSql(const std::wstring& sql)+ {+ if (sqlEditor_)+ {+ suppressTextChange_ = true;+ sqlEditor_.Text(winrt::hstring(sql));+ suppressTextChange_ = false;+ }+ else+ pendingSql_ = sql;+ }++ std::wstring QueryEditorView::GetSql() const+ {+ if (sqlEditor_)+ return std::wstring(sqlEditor_.Text());+ return pendingSql_;+ }++ winrt::Windows::Foundation::IAsyncAction QueryEditorView::RunScript(winrt::hstring)+ {+ co_return;+ }++ void QueryEditorView::RunQuery_Click(+ winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ ExecuteCurrentQuery();+ }++ void QueryEditorView::FormatQuery_Click(+ winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ if (!sqlEditor_) return;+ std::wstring sql(sqlEditor_.Text());+ std::vector<std::pair<std::wstring, std::wstring>> keywords = {+ {L"select ", L"SELECT "}, {L"from ", L"FROM "}, {L"where ", L"WHERE "},+ {L"and ", L"AND "}, {L"or ", L"OR "}, {L"join ", L"JOIN "},+ {L"left ", L"LEFT "}, {L"right ", L"RIGHT "}, {L"inner ", L"INNER "},+ {L"outer ", L"OUTER "}, {L"on ", L"ON "}, {L"group by ", L"GROUP BY "},+ {L"order by ", L"ORDER BY "}, {L"having ", L"HAVING "},+ {L"insert into ", L"INSERT INTO "}, {L"values ", L"VALUES "},+ {L"update ", L"UPDATE "}, {L"set ", L"SET "},+ {L"delete from ", L"DELETE FROM "}, {L"create table ", L"CREATE TABLE "},+ {L"alter table ", L"ALTER TABLE "}, {L"drop table ", L"DROP TABLE "},+ {L"limit ", L"LIMIT "}, {L"offset ", L"OFFSET "},+ {L"as ", L"AS "}, {L"distinct ", L"DISTINCT "},+ {L"not ", L"NOT "}, {L"in ", L"IN "}, {L"is ", L"IS "},+ {L"null", L"NULL"}, {L"like ", L"LIKE "},+ };+ for (auto& [lower, upper] : keywords)+ {+ size_t pos = 0;+ std::wstring sqlLower = sql;+ std::transform(sqlLower.begin(), sqlLower.end(), sqlLower.begin(), ::towlower);+ while ((pos = sqlLower.find(lower, pos)) != std::wstring::npos)+ {+ sql.replace(pos, lower.size(), upper);+ sqlLower.replace(pos, lower.size(), upper);+ pos += upper.size();+ }+ }+ suppressTextChange_ = true;+ sqlEditor_.Text(winrt::hstring(sql));+ suppressTextChange_ = false;+ }++ void QueryEditorView::ClearEditor_Click(+ winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ if (sqlEditor_)+ {+ suppressTextChange_ = true;+ sqlEditor_.Text(L"");+ suppressTextChange_ = false;+ }+ HideSuggestions();+ }++ // ── Results display ────────────────────────────────++ void QueryEditorView::ShowResult(const DBModels::QueryResult& result)+ {+ ResultsContainer().Children().Clear();++ std::wstring status = std::to_wstring(result.totalRows) + L" rows \u00B7 " ++ std::to_wstring(static_cast<int>(result.executionTimeMs)) + L" ms";+ QueryStatusText().Text(winrt::hstring(status));+ ResultsHeader().Visibility(mux::Visibility::Visible);+ ResultsSummaryText().Text(winrt::hstring(status));++ if (result.columnNames.empty()) return;++ size_t nCols = result.columnNames.size();+ double colWidth = 150.0;+ double availWidth = this->ActualWidth() - 20.0;+ if (availWidth > 0 && nCols > 0)+ {+ colWidth = availWidth / static_cast<double>(nCols);+ if (colWidth < 80.0) colWidth = 80.0;+ if (colWidth > 400.0) colWidth = 400.0;+ }++ muxc::StackPanel headerRow;+ headerRow.Orientation(muxc::Orientation::Horizontal);+ headerRow.Background(muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(15, 128, 128, 128)));+ for (auto& col : result.columnNames)+ {+ muxc::Border cell;+ cell.Width(colWidth);+ cell.Padding(mux::Thickness{ 8, 4, 8, 4 });+ cell.BorderBrush(muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(40, 128, 128, 128)));+ cell.BorderThickness(mux::Thickness{ 0, 0, 1, 1 });+ muxc::TextBlock lbl;+ lbl.Text(winrt::hstring(col));+ lbl.FontSize(11.0);+ lbl.FontWeight(winrt::Windows::UI::Text::FontWeights::SemiBold());+ lbl.TextTrimming(mux::TextTrimming::CharacterEllipsis);+ cell.Child(lbl);+ headerRow.Children().Append(cell);+ }+ ResultsContainer().Children().Append(headerRow);++ for (int i = 0; i < static_cast<int>(result.rows.size()); i++)+ {+ auto& row = result.rows[i];+ muxc::StackPanel rowPanel;+ rowPanel.Orientation(muxc::Orientation::Horizontal);+ if (i % 2 == 1)+ rowPanel.Background(muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(8, 128, 128, 128)));++ for (auto& col : result.columnNames)+ {+ std::wstring val;+ auto it = row.find(col);+ if (it != row.end()) val = it->second;+ // Render NULL sentinel as visible "NULL" with dim opacity+ const bool isNull = DBModels::isNullCell(val);+ const std::wstring display = isNull ? std::wstring(L"NULL") : val;++ muxc::Border cell;+ cell.Width(colWidth);+ cell.Padding(mux::Thickness{ 8, 4, 8, 4 });+ cell.BorderBrush(muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(20, 128, 128, 128)));+ cell.BorderThickness(mux::Thickness{ 0, 0, 1, 0 });+ muxc::TextBlock lbl;+ lbl.Text(winrt::hstring(display));+ lbl.FontSize(12.0);+ lbl.IsTextSelectionEnabled(true);+ lbl.TextTrimming(mux::TextTrimming::CharacterEllipsis);+ if (isNull || val.empty()) lbl.Opacity(0.4);+ cell.Child(lbl);+ rowPanel.Children().Append(cell);+ }+ ResultsContainer().Children().Append(rowPanel);+ }+ }++ void QueryEditorView::ShowError(const std::wstring& message)+ {+ ResultsContainer().Children().Clear();+ QueryStatusText().Text(L"Error");+ ResultsHeader().Visibility(mux::Visibility::Collapsed);++ muxc::TextBlock errText;+ errText.Text(winrt::hstring(message));+ errText.FontSize(12.0);+ errText.Padding(mux::Thickness{ 12, 8, 12, 8 });+ errText.Foreground(muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(255, 196, 43, 28)));+ errText.TextWrapping(mux::TextWrapping::Wrap);+ errText.IsTextSelectionEnabled(true);+ ResultsContainer().Children().Append(errText);+ }+}diff --git a/windows/Gridex/QueryEditorView.h b/windows/Gridex/QueryEditorView.hnew file mode 100644index 0000000..be994d7--- /dev/null+++ b/windows/Gridex/QueryEditorView.h@@ -0,0 +1,74 @@+#pragma once++#include "QueryEditorView.g.h"+#include "Models/QueryResult.h"+#include <functional>++namespace winrt::Gridex::implementation+{+ struct QueryEditorView : QueryEditorViewT<QueryEditorView>+ {+ QueryEditorView();++ void RunQuery_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);+ void FormatQuery_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);+ void ClearEditor_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);++ std::function<DBModels::QueryResult(const std::wstring& sql)> OnExecuteQuery;++ void SetSql(const std::wstring& sql);+ std::wstring GetSql() const;++ // Set table/column/function names for autocomplete suggestions+ void SetSchemaCompletions(+ const std::vector<std::wstring>& tables,+ const std::vector<std::wstring>& columns,+ const std::vector<std::wstring>& functions);++ private:+ DBModels::QueryResult lastResult_;+ winrt::Microsoft::UI::Xaml::Controls::TextBox sqlEditor_{ nullptr };+ winrt::Microsoft::UI::Xaml::Controls::ListView suggestList_{ nullptr };+ winrt::Microsoft::UI::Xaml::Controls::Border suggestPopup_{ nullptr };+ bool editorReady_ = false;+ bool editorCreated_ = false;+ bool buttonsWired_ = false;+ bool suppressTextChange_ = false;+ std::wstring pendingSql_;++ // Autocomplete data+ std::vector<std::wstring> schemaTableNames_;+ std::vector<std::wstring> schemaColumnNames_;+ std::vector<std::wstring> schemaFunctionNames_;++ // SQL keywords for suggestion+ static const std::vector<std::wstring>& SqlKeywords();++ void EnsureEditorCreated();+ void ExecuteCurrentQuery();+ void ShowResult(const DBModels::QueryResult& result);+ void ShowError(const std::wstring& message);+ void OnEditorTextChanged();+ void ForceShowSuggestions();+ void ShowSuggestions(const std::vector<std::wstring>& items);+ void HideSuggestions();+ void ApplySuggestion(const std::wstring& text);+ std::wstring GetCurrentWord() const;+ std::wstring GetPreviousKeyword() const;++ winrt::Windows::Foundation::IAsyncAction RunScript(winrt::hstring script);+ };+}++namespace winrt::Gridex::factory_implementation+{+ struct QueryEditorView : QueryEditorViewT<QueryEditorView, implementation::QueryEditorView>+ {+ };+}diff --git a/windows/Gridex/QueryEditorView.idl b/windows/Gridex/QueryEditorView.idlnew file mode 100644index 0000000..bd5147d--- /dev/null+++ b/windows/Gridex/QueryEditorView.idl@@ -0,0 +1,8 @@+namespace Gridex+{+ [default_interface]+ runtimeclass QueryEditorView : Microsoft.UI.Xaml.Controls.UserControl+ {+ QueryEditorView();+ }+}diff --git a/windows/Gridex/QueryEditorView.xaml b/windows/Gridex/QueryEditorView.xamlnew file mode 100644index 0000000..e916938--- /dev/null+++ b/windows/Gridex/QueryEditorView.xaml@@ -0,0 +1,96 @@+<UserControl+ x:Class="Gridex.QueryEditorView"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:local="using:Gridex">++ <Grid>+ <Grid.RowDefinitions>+ <RowDefinition Height="Auto" />+ <RowDefinition Height="*" />+ <RowDefinition Height="Auto" />+ <RowDefinition Height="*" />+ </Grid.RowDefinitions>++ <!-- Toolbar -->+ <Grid Grid.Row="0" Padding="8,4"+ Background="{ThemeResource LayerFillColorDefaultBrush}"+ BorderBrush="{ThemeResource DividerStrokeColorDefaultBrush}"+ BorderThickness="0,0,0,1">+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="*" />+ <ColumnDefinition Width="Auto" />+ </Grid.ColumnDefinitions>++ <Button x:Name="RunQueryButton" Grid.Column="0" Content="Run" Padding="16,4"+ Style="{StaticResource AccentButtonStyle}"+ ToolTipService.ToolTip="Execute (Ctrl+Enter)" />+ <Button x:Name="FormatQueryButton" Grid.Column="1" Margin="4,0,0,0" Padding="8,4"+ Background="Transparent" BorderThickness="0"+ ToolTipService.ToolTip="Format SQL">+ <FontIcon Glyph="" FontSize="14" />+ </Button>+ <Button x:Name="ClearEditorButton" Grid.Column="2" Margin="4,0,0,0" Padding="8,4"+ Background="Transparent" BorderThickness="0"+ ToolTipService.ToolTip="Clear">+ <FontIcon Glyph="" FontSize="14" />+ </Button>++ <TextBlock Grid.Column="4" x:Name="QueryStatusText"+ FontSize="11" VerticalAlignment="Center"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ </Grid>++ <!-- SQL Editor + Suggest Popup overlay -->+ <Grid Grid.Row="1" x:Name="EditorContainer" MinHeight="150">+ <!-- TextBox created in code-behind -->+ <!-- Suggest popup overlaid at bottom-left of editor -->+ <Border x:Name="SuggestPopup" Visibility="Collapsed"+ VerticalAlignment="Top" HorizontalAlignment="Left"+ Margin="50,30,0,0" MaxHeight="200" MinWidth="220" MaxWidth="350"+ Background="{ThemeResource AcrylicBackgroundFillColorDefaultBrush}"+ BorderBrush="{ThemeResource SurfaceStrokeColorDefaultBrush}"+ BorderThickness="1" CornerRadius="6"+ Padding="0" Canvas.ZIndex="100">+ <ListView x:Name="SuggestList" SelectionMode="Single"+ IsItemClickEnabled="True" MaxHeight="196"+ Padding="2" />+ </Border>+ </Grid>++ <!-- Splitter -->+ <Grid Grid.Row="2" Height="6"+ Background="{ThemeResource LayerFillColorDefaultBrush}"+ BorderBrush="{ThemeResource DividerStrokeColorDefaultBrush}"+ BorderThickness="0,1,0,1">+ <Border HorizontalAlignment="Center" VerticalAlignment="Center"+ Width="32" Height="2" CornerRadius="1"+ Background="{ThemeResource TextFillColorDisabledBrush}" />+ </Grid>++ <!-- Results -->+ <Grid Grid.Row="3">+ <Grid.RowDefinitions>+ <RowDefinition Height="Auto" />+ <RowDefinition Height="*" />+ </Grid.RowDefinitions>++ <Grid Grid.Row="0" Padding="8,4"+ Background="{ThemeResource LayerFillColorDefaultBrush}"+ BorderBrush="{ThemeResource DividerStrokeColorDefaultBrush}"+ BorderThickness="0,0,0,1"+ Visibility="Collapsed" x:Name="ResultsHeader">+ <TextBlock x:Name="ResultsSummaryText" FontSize="11"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ </Grid>++ <ScrollViewer Grid.Row="1" HorizontalScrollBarVisibility="Auto"+ VerticalScrollBarVisibility="Auto">+ <StackPanel x:Name="ResultsContainer" Spacing="0" />+ </ScrollViewer>+ </Grid>+ </Grid>+</UserControl>diff --git a/windows/Gridex/RedisAdapter.cpp b/windows/Gridex/RedisAdapter.cppnew file mode 100644index 0000000..4cf0dd8--- /dev/null+++ b/windows/Gridex/RedisAdapter.cpp@@ -0,0 +1,849 @@+// RedisAdapter.cpp — implementation of Redis support via hiredis.+//+// Design notes:+// • All commands go through sendArgv() which uses redisCommandArgv with+// explicit (cmd, argv, argvlen) — fully binary-safe, no printf format+// injection possible.+// • Replies are owned by RedisReplyPtr (unique_ptr with freeReplyObject+// deleter) so they can never leak even on exception paths.+// • The context is similarly wrapped in RedisContextPtr.+// • ensureConnected() detects a stale/disconnected context and silently+// rebuilds from the cached config + password — restores the connection+// transparently after Redis restarts or idle TCP timeouts.+// • A virtual "Keys" table per logical DB lets the rest of the app reuse+// the existing sidebar / data grid plumbing.++#include <windows.h>+#include "Models/RedisAdapter.h"++// hiredis sds.h uses GCC zero-length array extension which MSVC /W4 warns+// about (C4200). Suppress only for the hiredis include — it's harmless and+// the lib is third-party we don't want to patch.+#pragma warning(push)+#pragma warning(disable: 4200)+#include <hiredis/hiredis.h>+#pragma warning(pop)++#include <algorithm>+#include <chrono>+#include <cstring>+#include <sstream>+#include <stdexcept>++namespace DBModels+{+ // ── RAII deleter implementations ───────────────────────────+ void RedisContextDeleter::operator()(redisContext* ctx) const noexcept+ {+ if (ctx) redisFree(ctx);+ }++ void RedisReplyDeleter::operator()(redisReply* reply) const noexcept+ {+ if (reply) freeReplyObject(reply);+ }++ // ── ctor / dtor ────────────────────────────────────────────+ RedisAdapter::RedisAdapter() = default;++ RedisAdapter::~RedisAdapter()+ {+ // unique_ptr handles cleanup; explicit nothing-to-do here+ }++ // ── UTF-8 helpers ──────────────────────────────────────────+ std::string RedisAdapter::toUtf8(const std::wstring& s)+ {+ if (s.empty()) return {};+ int sz = WideCharToMultiByte(CP_UTF8, 0, s.c_str(),+ static_cast<int>(s.size()), nullptr, 0, nullptr, nullptr);+ std::string out(sz, '\0');+ WideCharToMultiByte(CP_UTF8, 0, s.c_str(),+ static_cast<int>(s.size()), &out[0], sz, nullptr, nullptr);+ return out;+ }++ std::wstring RedisAdapter::fromUtf8(const std::string& s)+ {+ if (s.empty()) return {};+ int sz = MultiByteToWideChar(CP_UTF8, 0, s.c_str(),+ static_cast<int>(s.size()), nullptr, 0);+ std::wstring out(sz, L'\0');+ MultiByteToWideChar(CP_UTF8, 0, s.c_str(),+ static_cast<int>(s.size()), &out[0], sz);+ return out;+ }++ // ── Connection lifecycle ───────────────────────────────────+ RedisContextPtr RedisAdapter::buildContext(+ const ConnectionConfig& config, const std::wstring& password)+ {+ // Connect with a 5-second timeout so a dead host fails fast.+ struct timeval tv;+ tv.tv_sec = 5;+ tv.tv_usec = 0;++ std::string host = toUtf8(config.host.empty() ? L"127.0.0.1" : config.host);+ int port = config.port > 0 ? config.port : 6379;++ redisContext* raw = redisConnectWithTimeout(host.c_str(), port, tv);+ RedisContextPtr ctx(raw);++ if (!ctx || ctx->err)+ {+ std::string err = ctx ? ctx->errstr : "alloc failed";+ throw DatabaseError(DatabaseError::Code::ConnectionFailed,+ "Redis connection failed: " + err);+ }++ // Set socket read timeout too so a hung server doesn't freeze the UI thread+ redisSetTimeout(ctx.get(), tv);++ // AUTH if password supplied+ if (!password.empty())+ {+ std::string pwd = toUtf8(password);+ const char* argv[] = { "AUTH", pwd.c_str() };+ size_t argvlen[] = { 4, pwd.size() };+ redisReply* raw_r = static_cast<redisReply*>(+ redisCommandArgv(ctx.get(), 2, argv, argvlen));+ RedisReplyPtr reply(raw_r);+ if (!reply || reply->type == REDIS_REPLY_ERROR)+ {+ std::string err = reply ? reply->str : "AUTH failed";+ throw DatabaseError(DatabaseError::Code::AuthenticationFailed,+ "Redis AUTH failed: " + err);+ }+ }++ // SELECT the requested DB. Accept both pure numeric strings ("5")+ // and the normalized "db<N>" label (e.g. "db5") that WorkspacePage+ // puts in config.database once a Redis connection has been set up.+ int db = 0;+ if (!config.database.empty())+ {+ std::wstring d = config.database;+ if (d.size() > 2 && d[0] == L'd' && d[1] == L'b')+ d = d.substr(2);+ try { db = std::stoi(d); } catch (...) { db = 0; }+ }+ if (db != 0)+ {+ std::string dbStr = std::to_string(db);+ const char* argv[] = { "SELECT", dbStr.c_str() };+ size_t argvlen[] = { 6, dbStr.size() };+ redisReply* raw_r = static_cast<redisReply*>(+ redisCommandArgv(ctx.get(), 2, argv, argvlen));+ RedisReplyPtr reply(raw_r);+ if (!reply || reply->type == REDIS_REPLY_ERROR)+ {+ std::string err = reply ? reply->str : "SELECT failed";+ throw DatabaseError(DatabaseError::Code::DatabaseNotFound,+ "Redis SELECT failed: " + err);+ }+ }+ currentDb_ = db;++ return ctx;+ }++ void RedisAdapter::connect(+ const ConnectionConfig& config, const std::wstring& password)+ {+ // Cache for auto-reconnect+ lastConfig_ = config;+ lastPassword_ = password;+ context_ = buildContext(config, password);+ }++ void RedisAdapter::disconnect()+ {+ context_.reset();+ }++ bool RedisAdapter::testConnection(+ const ConnectionConfig& config, const std::wstring& password)+ {+ // Build a temporary context, PING, and let RAII clean up.+ try+ {+ auto ctx = buildContext(config, password);+ const char* argv[] = { "PING" };+ size_t argvlen[] = { 4 };+ redisReply* raw = static_cast<redisReply*>(+ redisCommandArgv(ctx.get(), 1, argv, argvlen));+ RedisReplyPtr reply(raw);+ return reply &&+ (reply->type == REDIS_REPLY_STATUS ||+ reply->type == REDIS_REPLY_STRING);+ }+ catch (...)+ {+ return false;+ }+ }++ bool RedisAdapter::isConnected() const+ {+ return context_ && !context_->err;+ }++ void RedisAdapter::ensureConnected()+ {+ if (context_ && !context_->err) return;+ // Stale or never connected → rebuild from cached config+ context_ = buildContext(lastConfig_, lastPassword_);+ }++ // ── Reply helpers ──────────────────────────────────────────+ void RedisAdapter::checkReply(redisReply* reply, const char* hint)+ {+ if (!reply)+ {+ std::string err = context_ ? context_->errstr : "no reply";+ // Reset context so the next call triggers reconnect+ context_.reset();+ throw DatabaseError(DatabaseError::Code::QueryFailed,+ std::string(hint) + ": " + err);+ }+ if (reply->type == REDIS_REPLY_ERROR)+ {+ throw DatabaseError(DatabaseError::Code::QueryFailed,+ std::string(hint) + ": " + std::string(reply->str, reply->len));+ }+ }++ RedisReplyPtr RedisAdapter::sendArgv(const std::vector<std::string>& argv)+ {+ ensureConnected();++ std::vector<const char*> rawArgs;+ std::vector<size_t> argLens;+ rawArgs.reserve(argv.size());+ argLens.reserve(argv.size());+ for (const auto& a : argv)+ {+ rawArgs.push_back(a.c_str());+ argLens.push_back(a.size());+ }++ redisReply* raw = static_cast<redisReply*>(+ redisCommandArgv(context_.get(),+ static_cast<int>(rawArgs.size()),+ rawArgs.data(), argLens.data()));+ RedisReplyPtr reply(raw);++ // If reply is null, the connection is broken. Try ONE auto-reconnect + retry.+ if (!reply && context_ && context_->err)+ {+ context_.reset();+ ensureConnected();+ raw = static_cast<redisReply*>(+ redisCommandArgv(context_.get(),+ static_cast<int>(rawArgs.size()),+ rawArgs.data(), argLens.data()));+ reply.reset(raw);+ }++ checkReply(reply.get(), argv.empty() ? "REDIS" : argv[0].c_str());+ return reply;+ }++ RedisReplyPtr RedisAdapter::sendCommand(std::initializer_list<std::string> args)+ {+ return sendArgv(std::vector<std::string>(args));+ }++ std::vector<RedisReplyPtr> RedisAdapter::pipelineArgv(+ const std::vector<std::vector<std::string>>& commands)+ {+ std::vector<RedisReplyPtr> replies;+ replies.reserve(commands.size());+ if (commands.empty()) return replies;++ ensureConnected();++ // Phase A: queue every command into the output buffer (no I/O yet)+ for (const auto& argv : commands)+ {+ std::vector<const char*> rawArgs;+ std::vector<size_t> argLens;+ rawArgs.reserve(argv.size());+ argLens.reserve(argv.size());+ for (const auto& a : argv)+ {+ rawArgs.push_back(a.c_str());+ argLens.push_back(a.size());+ }+ int rc = redisAppendCommandArgv(context_.get(),+ static_cast<int>(rawArgs.size()),+ rawArgs.data(), argLens.data());+ if (rc != REDIS_OK)+ {+ std::string err = context_ ? context_->errstr : "append failed";+ context_.reset();+ throw DatabaseError(DatabaseError::Code::QueryFailed,+ "Redis pipeline append failed: " + err);+ }+ }++ // Phase B: drain replies in order. The first redisGetReply triggers+ // the actual socket flush + reads, so this is where we pay the+ // network round-trip cost — exactly ONE round-trip for the whole batch.+ for (size_t i = 0; i < commands.size(); ++i)+ {+ void* raw = nullptr;+ int rc = redisGetReply(context_.get(), &raw);+ if (rc != REDIS_OK)+ {+ std::string err = context_ ? context_->errstr : "getReply failed";+ context_.reset();+ throw DatabaseError(DatabaseError::Code::QueryFailed,+ "Redis pipeline read failed: " + err);+ }+ replies.emplace_back(static_cast<redisReply*>(raw));+ }+ return replies;+ }++ // ── Schema parsing ─────────────────────────────────────────+ int RedisAdapter::parseDbFromSchema(const std::wstring& schema)+ {+ // schema like "db0" .. "db15"+ if (schema.size() > 2 && schema[0] == L'd' && schema[1] == L'b')+ {+ try { return std::stoi(schema.substr(2)); }+ catch (...) {}+ }+ return 0;+ }++ // ── Command line tokenizer (handles quoted strings) ────────+ std::vector<std::string> RedisAdapter::tokenizeCommand(const std::wstring& sql)+ {+ std::vector<std::string> tokens;+ std::wstring current;+ wchar_t inQuote = 0;+ for (wchar_t c : sql)+ {+ if (inQuote)+ {+ if (c == inQuote) inQuote = 0;+ else current += c;+ }+ else if (c == L'"' || c == L'\'')+ {+ inQuote = c;+ }+ else if (c == L' ' || c == L'\t' || c == L'\r' || c == L'\n')+ {+ if (!current.empty())+ {+ tokens.push_back(toUtf8(current));+ current.clear();+ }+ }+ else+ {+ current += c;+ }+ }+ if (!current.empty()) tokens.push_back(toUtf8(current));+ return tokens;+ }++ // ── Reply → wstring helpers ────────────────────────────────+ std::wstring RedisAdapter::replyToWString(redisReply* reply)+ {+ if (!reply) return L"";+ switch (reply->type)+ {+ case REDIS_REPLY_STRING:+ case REDIS_REPLY_STATUS:+ case REDIS_REPLY_ERROR:+ return fromUtf8(std::string(reply->str, reply->len));+ case REDIS_REPLY_INTEGER:+ return std::to_wstring(reply->integer);+ case REDIS_REPLY_NIL:+ return L"";+ case REDIS_REPLY_ARRAY:+ return formatPreview(reply);+ default:+ return L"";+ }+ }++ std::wstring RedisAdapter::formatPreview(redisReply* reply)+ {+ // Full array dump, no truncation. Earlier version capped at 10+ // elements and appended "... (N total)" for display purposes, but+ // that stored the lossy preview in the TableRow and destroyed the+ // original payload: opening the cell for inline edit showed the+ // preview text, and saving would call SET with the preview string,+ // overwriting the real hash/list/set value.+ //+ // The grid already trims each cell to MAX_CELL_DISPLAY_CHARS at+ // render time (DataGridView builds a preview for the visual cell+ // without touching data_.rows), and the details side-panel shows+ // the full value, so readability is unaffected while edits now+ // operate on the real data.+ if (!reply || reply->type != REDIS_REPLY_ARRAY) return L"";+ std::wstring out = L"[";+ for (size_t i = 0; i < reply->elements; ++i)+ {+ if (i > 0) out += L", ";+ out += replyToWString(reply->element[i]);+ }+ out += L"]";+ return out;+ }++ // ── Schema inspection ──────────────────────────────────────+ std::vector<std::wstring> RedisAdapter::listDatabases()+ {+ // Redis exposes 16 logical DBs by default (0-15)+ std::vector<std::wstring> out;+ for (int i = 0; i < 16; ++i)+ out.push_back(L"db" + std::to_wstring(i));+ return out;+ }++ std::vector<std::wstring> RedisAdapter::listSchemas()+ {+ return listDatabases();+ }++ std::vector<TableInfo> RedisAdapter::listTables(const std::wstring& schema)+ {+ // Switch to the requested DB so DBSIZE reflects the right one+ int db = parseDbFromSchema(schema);+ if (db != currentDb_)+ {+ std::string dbStr = std::to_string(db);+ sendArgv({ "SELECT", dbStr });+ currentDb_ = db;+ }++ TableInfo keys;+ keys.name = L"Keys";+ keys.schema = schema;+ keys.type = L"table";++ // Get an estimated row count via DBSIZE+ try+ {+ auto reply = sendArgv({ "DBSIZE" });+ if (reply && reply->type == REDIS_REPLY_INTEGER)+ keys.estimatedRows = reply->integer;+ }+ catch (...) { /* ignore — keys.estimatedRows stays 0 */ }++ return { keys };+ }++ std::vector<TableInfo> RedisAdapter::listViews(const std::wstring& /*schema*/)+ {+ return {};+ }++ std::vector<ColumnInfo> RedisAdapter::describeTable(+ const std::wstring& /*table*/, const std::wstring& /*schema*/)+ {+ // Virtual columns for the Keys pseudo-table+ std::vector<ColumnInfo> cols;+ ColumnInfo keyCol;+ keyCol.name = L"key"; keyCol.dataType = L"string";+ keyCol.nullable = false; keyCol.isPrimaryKey = true;+ keyCol.ordinalPosition = 1;+ cols.push_back(keyCol);++ ColumnInfo typeCol;+ typeCol.name = L"type"; typeCol.dataType = L"string";+ typeCol.nullable = false; typeCol.ordinalPosition = 2;+ cols.push_back(typeCol);++ ColumnInfo valueCol;+ valueCol.name = L"value"; valueCol.dataType = L"string";+ valueCol.nullable = true; valueCol.ordinalPosition = 3;+ cols.push_back(valueCol);++ ColumnInfo ttlCol;+ ttlCol.name = L"ttl"; ttlCol.dataType = L"integer";+ ttlCol.nullable = true; ttlCol.ordinalPosition = 4;+ cols.push_back(ttlCol);++ return cols;+ }++ std::vector<IndexInfo> RedisAdapter::listIndexes(+ const std::wstring& /*table*/, const std::wstring& /*schema*/)+ {+ return {};+ }++ std::vector<ForeignKeyInfo> RedisAdapter::listForeignKeys(+ const std::wstring& /*table*/, const std::wstring& /*schema*/)+ {+ return {};+ }++ std::vector<std::wstring> RedisAdapter::listFunctions(const std::wstring& /*schema*/)+ {+ return {};+ }++ std::wstring RedisAdapter::getFunctionSource(+ const std::wstring& /*name*/, const std::wstring& /*schema*/)+ {+ return L"";+ }++ std::wstring RedisAdapter::getCreateTableSQL(+ const std::wstring& /*table*/, const std::wstring& /*schema*/)+ {+ // Not real DDL — descriptive only so the UI has something to display+ return L"-- Redis virtual table\n"+ L"CREATE TABLE Keys (\n"+ L" key string PRIMARY KEY,\n"+ L" type string NOT NULL,\n"+ L" value string,\n"+ L" ttl integer\n"+ L");";+ }++ // ── Build a QueryResult holding key/type/value/ttl rows ────+ QueryResult RedisAdapter::makeKeysResult(+ const std::vector<TableRow>& rows, double elapsedMs)+ {+ QueryResult result;+ result.columnNames = { L"key", L"type", L"value", L"ttl" };+ result.columnTypes = { L"string", L"string", L"string", L"integer" };+ result.rows = rows;+ result.totalRows = static_cast<int>(rows.size());+ result.executionTimeMs = elapsedMs;+ result.success = true;+ return result;+ }++ // ── fetchRows: SCAN-based pagination ───────────────────────+ QueryResult RedisAdapter::fetchRows(+ const std::wstring& /*table*/, const std::wstring& schema,+ int limit, int offset,+ const std::wstring& /*orderBy*/, bool /*ascending*/)+ {+ auto t0 = std::chrono::steady_clock::now();++ // Switch DB if schema indicates a different one+ int db = parseDbFromSchema(schema);+ if (db != currentDb_)+ {+ sendArgv({ "SELECT", std::to_string(db) });+ currentDb_ = db;+ }++ // Phase 1: SCAN to collect all keys, using current MATCH pattern+ // (set via setSearchPattern; defaults to "*")+ std::vector<std::string> allKeys;+ std::string cursor = "0";+ const std::string& pattern = searchPattern_;+ do+ {+ auto reply = sendArgv({ "SCAN", cursor, "MATCH", pattern, "COUNT", "500" });+ if (!reply || reply->type != REDIS_REPLY_ARRAY || reply->elements != 2)+ break;++ // element[0] = next cursor, element[1] = array of keys+ redisReply* curEl = reply->element[0];+ redisReply* keysEl = reply->element[1];++ if (curEl && curEl->type == REDIS_REPLY_STRING)+ cursor.assign(curEl->str, curEl->len);+ else+ cursor = "0";++ if (keysEl && keysEl->type == REDIS_REPLY_ARRAY)+ {+ for (size_t i = 0; i < keysEl->elements; ++i)+ {+ redisReply* k = keysEl->element[i];+ if (k && k->type == REDIS_REPLY_STRING)+ allKeys.emplace_back(k->str, k->len);+ }+ }+ } while (cursor != "0" && allKeys.size() < static_cast<size_t>(offset + limit + 1000));++ // Sort for stable pagination+ std::sort(allKeys.begin(), allKeys.end());++ // Apply offset/limit+ std::vector<std::string> paged;+ for (size_t i = static_cast<size_t>(offset);+ i < allKeys.size() && paged.size() < static_cast<size_t>(limit); ++i)+ {+ paged.push_back(allKeys[i]);+ }++ // Phase 2: TYPE + TTL pipelined as ONE batch (2N commands, 1 round-trip)+ // Without pipelining this was 8s for 300 keys (sequential round-trips).+ std::vector<std::vector<std::string>> typeAndTtl;+ typeAndTtl.reserve(paged.size() * 2);+ for (const auto& key : paged)+ {+ typeAndTtl.push_back({ "TYPE", key });+ typeAndTtl.push_back({ "TTL", key });+ }+ std::vector<RedisReplyPtr> typeTtlReplies;+ try { typeTtlReplies = pipelineArgv(typeAndTtl); }+ catch (...) { typeTtlReplies.clear(); }++ std::vector<std::string> types(paged.size(), "string");+ std::vector<long long> ttls(paged.size(), -1);+ for (size_t i = 0; i < paged.size(); ++i)+ {+ redisReply* tr = (i * 2 < typeTtlReplies.size()) ? typeTtlReplies[i * 2].get() : nullptr;+ redisReply* lr = (i * 2 + 1 < typeTtlReplies.size()) ? typeTtlReplies[i * 2 + 1].get() : nullptr;+ if (tr && tr->type == REDIS_REPLY_STATUS)+ types[i].assign(tr->str, tr->len);+ if (lr && lr->type == REDIS_REPLY_INTEGER)+ ttls[i] = lr->integer;+ }++ // Phase 3: pipelined value lookups (one command per key, N commands, 1 round-trip)+ std::vector<std::vector<std::string>> valueCmds;+ valueCmds.reserve(paged.size());+ for (size_t i = 0; i < paged.size(); ++i)+ {+ const std::string& key = paged[i];+ const std::string& t = types[i];+ if (t == "string") valueCmds.push_back({ "GET", key });+ else if (t == "list") valueCmds.push_back({ "LRANGE", key, "0", "99" });+ else if (t == "set") valueCmds.push_back({ "SMEMBERS", key });+ else if (t == "zset") valueCmds.push_back({ "ZRANGE", key, "0", "99", "WITHSCORES" });+ else if (t == "hash") valueCmds.push_back({ "HGETALL", key });+ else valueCmds.push_back({ "TYPE", key }); // harmless placeholder+ }+ std::vector<RedisReplyPtr> valueReplies;+ try { valueReplies = pipelineArgv(valueCmds); }+ catch (...) { valueReplies.clear(); }++ // Assemble rows+ std::vector<TableRow> rows;+ rows.reserve(paged.size());+ for (size_t i = 0; i < paged.size(); ++i)+ {+ const std::string& key = paged[i];+ const std::string& t = types[i];+ redisReply* vr = (i < valueReplies.size()) ? valueReplies[i].get() : nullptr;++ std::wstring value;+ if (!vr) value = L"";+ else if (t == "string") value = replyToWString(vr);+ else if (t == "list" || t == "set" || t == "zset" || t == "hash")+ value = formatPreview(vr);+ else value = L"(" + fromUtf8(t) + L")";++ TableRow row;+ row[L"key"] = fromUtf8(key);+ row[L"type"] = fromUtf8(t);+ row[L"value"] = value;+ row[L"ttl"] = (ttls[i] < 0) ? L"" : std::to_wstring(ttls[i]);+ rows.push_back(std::move(row));+ }++ auto t1 = std::chrono::steady_clock::now();+ double elapsed = std::chrono::duration<double, std::milli>(t1 - t0).count();++ QueryResult result = makeKeysResult(rows, elapsed);+ // Override totalRows with the FULL key count, not just the page+ result.totalRows = static_cast<int>(allKeys.size());+ result.currentPage = (limit > 0 ? offset / limit + 1 : 1);+ result.pageSize = limit;+ return result;+ }++ // ── Execute raw Redis command ──────────────────────────────+ QueryResult RedisAdapter::execute(const std::wstring& sql)+ {+ auto t0 = std::chrono::steady_clock::now();++ QueryResult result;+ result.sql = sql;++ auto tokens = tokenizeCommand(sql);+ if (tokens.empty())+ {+ result.success = false;+ result.error = L"Empty command";+ return result;+ }++ try+ {+ auto reply = sendArgv(tokens);+ // Build a one-row, one-column result containing the reply preview+ result.columnNames = { L"result" };+ result.columnTypes = { L"string" };+ TableRow row;+ row[L"result"] = replyToWString(reply.get());+ result.rows.push_back(row);+ result.totalRows = 1;+ result.success = true;+ }+ catch (const DatabaseError& e)+ {+ result.success = false;+ result.error = fromUtf8(e.what());+ }++ auto t1 = std::chrono::steady_clock::now();+ result.executionTimeMs =+ std::chrono::duration<double, std::milli>(t1 - t0).count();+ return result;+ }++ // ── Data manipulation ──────────────────────────────────────+ QueryResult RedisAdapter::insertRow(+ const std::wstring& /*table*/, const std::wstring& /*schema*/,+ const TableRow& values)+ {+ QueryResult result;+ auto keyIt = values.find(L"key");+ if (keyIt == values.end() || keyIt->second.empty())+ {+ result.success = false;+ result.error = L"Missing 'key' field";+ return result;+ }+ std::string key = toUtf8(keyIt->second);++ auto valIt = values.find(L"value");+ std::string val = (valIt != values.end()) ? toUtf8(valIt->second) : "";++ try+ {+ sendArgv({ "SET", key, val });+ result.success = true;+ }+ catch (const DatabaseError& e)+ {+ result.success = false;+ result.error = fromUtf8(e.what());+ }+ return result;+ }++ QueryResult RedisAdapter::updateRow(+ const std::wstring& /*table*/, const std::wstring& /*schema*/,+ const TableRow& setValues, const TableRow& whereValues)+ {+ QueryResult result;+ auto keyIt = whereValues.find(L"key");+ if (keyIt == whereValues.end() || keyIt->second.empty())+ {+ result.success = false;+ result.error = L"Missing 'key' in WHERE";+ return result;+ }+ std::string key = toUtf8(keyIt->second);++ try+ {+ // Update value via SET if 'value' is in setValues+ auto valIt = setValues.find(L"value");+ if (valIt != setValues.end())+ {+ sendArgv({ "SET", key, toUtf8(valIt->second) });+ }+ // Update TTL via EXPIRE / PERSIST if 'ttl' is in setValues+ auto ttlIt = setValues.find(L"ttl");+ if (ttlIt != setValues.end())+ {+ if (ttlIt->second.empty())+ {+ sendArgv({ "PERSIST", key });+ }+ else+ {+ sendArgv({ "EXPIRE", key, toUtf8(ttlIt->second) });+ }+ }+ result.success = true;+ }+ catch (const DatabaseError& e)+ {+ result.success = false;+ result.error = fromUtf8(e.what());+ }+ return result;+ }++ QueryResult RedisAdapter::deleteRow(+ const std::wstring& /*table*/, const std::wstring& /*schema*/,+ const TableRow& whereValues)+ {+ QueryResult result;+ auto keyIt = whereValues.find(L"key");+ if (keyIt == whereValues.end() || keyIt->second.empty())+ {+ result.success = false;+ result.error = L"Missing 'key' in WHERE";+ return result;+ }+ try+ {+ sendArgv({ "DEL", toUtf8(keyIt->second) });+ result.success = true;+ }+ catch (const DatabaseError& e)+ {+ result.success = false;+ result.error = fromUtf8(e.what());+ }+ return result;+ }++ // ── Transactions ───────────────────────────────────────────+ void RedisAdapter::beginTransaction() { sendArgv({ "MULTI" }); }+ void RedisAdapter::commitTransaction() { sendArgv({ "EXEC" }); }+ void RedisAdapter::rollbackTransaction(){ sendArgv({ "DISCARD" }); }++ // ── Server info ────────────────────────────────────────────+ std::wstring RedisAdapter::serverVersion()+ {+ try+ {+ auto reply = sendArgv({ "INFO", "server" });+ if (reply && reply->type == REDIS_REPLY_STRING)+ {+ std::string info(reply->str, reply->len);+ // Look for "redis_version:" line+ auto pos = info.find("redis_version:");+ if (pos != std::string::npos)+ {+ auto end = info.find('\r', pos);+ if (end == std::string::npos) end = info.find('\n', pos);+ if (end != std::string::npos)+ return fromUtf8(info.substr(pos + 14, end - pos - 14));+ }+ }+ }+ catch (...) {}+ return L"Redis";+ }++ std::wstring RedisAdapter::currentDatabase()+ {+ return L"db" + std::to_wstring(currentDb_);+ }++ void RedisAdapter::setSearchPattern(const std::wstring& pattern)+ {+ // Empty or whitespace pattern means "match all"+ std::wstring trimmed = pattern;+ while (!trimmed.empty() && (trimmed.front() == L' ' || trimmed.front() == L'\t'))+ trimmed.erase(trimmed.begin());+ while (!trimmed.empty() && (trimmed.back() == L' ' || trimmed.back() == L'\t'))+ trimmed.pop_back();+ searchPattern_ = trimmed.empty() ? "*" : toUtf8(trimmed);+ }+}diff --git a/windows/Gridex/SQLiteAdapter.cpp b/windows/Gridex/SQLiteAdapter.cppnew file mode 100644index 0000000..9cc03e3--- /dev/null+++ b/windows/Gridex/SQLiteAdapter.cpp@@ -0,0 +1,468 @@+#include <windows.h>+#include "Models/SQLiteAdapter.h"+#include <sqlite3.h>+#include <chrono>++namespace DBModels+{+ // ── UTF-8 helpers ───────────────────────────────+ std::string SQLiteAdapter::toUtf8(const std::wstring& wstr)+ {+ if (wstr.empty()) return {};+ int size = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(),+ static_cast<int>(wstr.size()), nullptr, 0, nullptr, nullptr);+ std::string result(size, '\0');+ WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(),+ static_cast<int>(wstr.size()), &result[0], size, nullptr, nullptr);+ return result;+ }++ std::wstring SQLiteAdapter::fromUtf8(const std::string& str)+ {+ if (str.empty()) return {};+ int size = MultiByteToWideChar(CP_UTF8, 0, str.c_str(),+ static_cast<int>(str.size()), nullptr, 0);+ std::wstring result(size, L'\0');+ MultiByteToWideChar(CP_UTF8, 0, str.c_str(),+ static_cast<int>(str.size()), &result[0], size);+ return result;+ }++ std::string SQLiteAdapter::quoteIdentifier(const std::wstring& name)+ {+ return "\"" + toUtf8(name) + "\"";+ }++ std::string SQLiteAdapter::quoteLiteral(const std::wstring& value)+ {+ std::string utf8 = toUtf8(value);+ std::string escaped;+ escaped.reserve(utf8.size() + 2);+ escaped += '\'';+ for (char c : utf8)+ {+ if (c == '\'') escaped += "''";+ else escaped += c;+ }+ escaped += '\'';+ return escaped;+ }++ void SQLiteAdapter::ensureConnected() const+ {+ if (!connected_ || !db_)+ throw DatabaseError(DatabaseError::Code::ConnectionFailed, "Not connected to SQLite database");+ }++ // ── Constructor / Destructor ────────────────────+ SQLiteAdapter::SQLiteAdapter() = default;++ SQLiteAdapter::~SQLiteAdapter()+ {+ if (db_)+ {+ sqlite3_close(db_);+ db_ = nullptr;+ }+ }++ // ── Connection ──────────────────────────────────+ void SQLiteAdapter::connect(const ConnectionConfig& config, const std::wstring& /*password*/)+ {+ disconnect();++ filePath_ = config.filePath;+ std::string path = toUtf8(filePath_);++ int rc = sqlite3_open(path.c_str(), &db_);+ if (rc != SQLITE_OK)+ {+ std::string err = db_ ? sqlite3_errmsg(db_) : "sqlite3_open failed";+ if (db_) { sqlite3_close(db_); db_ = nullptr; }+ throw DatabaseError(DatabaseError::Code::ConnectionFailed, err);+ }++ connected_ = true;++ // Enable WAL mode and foreign keys+ executeInternal("PRAGMA journal_mode=WAL");+ executeInternal("PRAGMA foreign_keys=ON");+ }++ void SQLiteAdapter::disconnect()+ {+ if (db_)+ {+ sqlite3_close(db_);+ db_ = nullptr;+ }+ connected_ = false;+ }++ bool SQLiteAdapter::testConnection(const ConnectionConfig& config, const std::wstring& password)+ {+ try+ {+ connect(config, password);+ auto result = execute(L"SELECT 1");+ disconnect();+ return result.success;+ }+ catch (...)+ {+ disconnect();+ return false;+ }+ }++ bool SQLiteAdapter::isConnected() const { return connected_ && db_; }++ // ── Query Execution ─────────────────────────────+ QueryResult SQLiteAdapter::executeInternal(const std::string& sql)+ {+ ensureConnected();++ auto start = std::chrono::high_resolution_clock::now();++ QueryResult result;+ result.sql = fromUtf8(sql);++ sqlite3_stmt* stmt = nullptr;+ int rc = sqlite3_prepare_v2(db_, sql.c_str(), static_cast<int>(sql.size()), &stmt, nullptr);+ if (rc != SQLITE_OK)+ {+ result.success = false;+ result.error = fromUtf8(sqlite3_errmsg(db_));+ auto end = std::chrono::high_resolution_clock::now();+ result.executionTimeMs = std::chrono::duration<double, std::milli>(end - start).count();+ return result;+ }++ // Get column info+ int nCols = sqlite3_column_count(stmt);+ result.columnNames.reserve(nCols);+ result.columnTypes.reserve(nCols);+ for (int c = 0; c < nCols; c++)+ {+ const char* name = sqlite3_column_name(stmt, c);+ result.columnNames.push_back(fromUtf8(name ? name : ""));+ const char* type = sqlite3_column_decltype(stmt, c);+ result.columnTypes.push_back(fromUtf8(type ? type : "TEXT"));+ }++ // Execute and fetch rows.+ // PERFORMANCE: pre-reserve hash buckets per row, capture colName by+ // const-ref (no per-cell wstring copy), move-construct rows into vector+ // (matches PostgreSQL/MySQL adapter optimization).+ while ((rc = sqlite3_step(stmt)) == SQLITE_ROW)+ {+ TableRow row;+ row.reserve(nCols);+ for (int c = 0; c < nCols; c++)+ {+ const std::wstring& colName = result.columnNames[c];+ if (sqlite3_column_type(stmt, c) == SQLITE_NULL)+ {+ row.emplace(colName, nullValue());+ }+ else+ {+ const char* text = reinterpret_cast<const char*>(sqlite3_column_text(stmt, c));+ row.emplace(colName, text ? fromUtf8(text) : L"");+ }+ }+ result.rows.push_back(std::move(row));+ }++ auto end = std::chrono::high_resolution_clock::now();+ result.executionTimeMs = std::chrono::duration<double, std::milli>(end - start).count();++ if (rc == SQLITE_DONE)+ {+ result.success = true;+ if (nCols > 0)+ result.totalRows = static_cast<int>(result.rows.size());+ else+ result.totalRows = sqlite3_changes(db_);+ }+ else+ {+ result.success = false;+ result.error = fromUtf8(sqlite3_errmsg(db_));+ }++ sqlite3_finalize(stmt);+ return result;+ }++ QueryResult SQLiteAdapter::execute(const std::wstring& sql)+ {+ return executeInternal(toUtf8(sql));+ }++ QueryResult SQLiteAdapter::fetchRows(+ const std::wstring& table, const std::wstring& /*schema*/,+ int limit, int offset,+ const std::wstring& orderBy, bool ascending)+ {+ // SQLite has no schema concept — table name only+ std::string sql = "SELECT * FROM " + quoteIdentifier(table);+ if (!orderBy.empty())+ sql += " ORDER BY " + quoteIdentifier(orderBy) + (ascending ? " ASC" : " DESC");+ sql += " LIMIT " + std::to_string(limit) + " OFFSET " + std::to_string(offset);++ auto result = executeInternal(sql);++ // Get total count+ std::string countSql = "SELECT COUNT(*) AS cnt FROM " + quoteIdentifier(table);+ auto countResult = executeInternal(countSql);+ if (countResult.success && !countResult.rows.empty())+ {+ auto it = countResult.rows[0].find(L"cnt");+ if (it != countResult.rows[0].end() && !isNullCell(it->second))+ result.totalRows = std::stoi(toUtf8(it->second));+ }++ result.currentPage = (offset / limit) + 1;+ result.pageSize = limit;+ return result;+ }++ // ── Schema Inspection ───────────────────────────+ std::vector<std::wstring> SQLiteAdapter::listDatabases()+ {+ // SQLite is single-database — return file name+ std::vector<std::wstring> dbs;+ if (!filePath_.empty())+ {+ auto pos = filePath_.find_last_of(L"\\/");+ dbs.push_back(pos != std::wstring::npos ? filePath_.substr(pos + 1) : filePath_);+ }+ return dbs;+ }++ std::vector<std::wstring> SQLiteAdapter::listSchemas()+ {+ return { L"main" }; // SQLite default schema+ }++ std::vector<TableInfo> SQLiteAdapter::listTables(const std::wstring& /*schema*/)+ {+ auto result = executeInternal(+ "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name");+ std::vector<TableInfo> tables;+ for (auto& row : result.rows)+ {+ TableInfo info;+ info.name = row[L"name"];+ info.schema = L"main";+ info.type = L"table";+ tables.push_back(info);+ }+ return tables;+ }++ std::vector<TableInfo> SQLiteAdapter::listViews(const std::wstring& /*schema*/)+ {+ auto result = executeInternal(+ "SELECT name FROM sqlite_master WHERE type='view' ORDER BY name");+ std::vector<TableInfo> views;+ for (auto& row : result.rows)+ {+ TableInfo info;+ info.name = row[L"name"];+ info.schema = L"main";+ info.type = L"view";+ views.push_back(info);+ }+ return views;+ }++ std::vector<ColumnInfo> SQLiteAdapter::describeTable(+ const std::wstring& table, const std::wstring& /*schema*/)+ {+ std::string sql = "PRAGMA table_info(" + quoteIdentifier(table) + ")";+ auto result = executeInternal(sql);+ std::vector<ColumnInfo> columns;+ for (auto& row : result.rows)+ {+ ColumnInfo col;+ col.name = row[L"name"];+ col.dataType = row[L"type"];+ col.nullable = (row[L"notnull"] == L"0");+ col.defaultValue = !isNullCell(row[L"dflt_value"]) ? row[L"dflt_value"] : L"";+ col.isPrimaryKey = (row[L"pk"] != L"0");+ auto cidIt = row.find(L"cid");+ if (cidIt != row.end() && !isNullCell(cidIt->second))+ col.ordinalPosition = std::stoi(toUtf8(cidIt->second)) + 1;+ columns.push_back(col);+ }++ // Mark FK columns+ auto fks = listForeignKeys(table, L"main");+ for (auto& fk : fks)+ for (auto& col : columns)+ if (col.name == fk.column)+ {+ col.isForeignKey = true;+ col.fkReferencedTable = fk.referencedTable;+ col.fkReferencedColumn = fk.referencedColumn;+ }++ return columns;+ }++ std::vector<IndexInfo> SQLiteAdapter::listIndexes(+ const std::wstring& table, const std::wstring& /*schema*/)+ {+ std::string sql = "PRAGMA index_list(" + quoteIdentifier(table) + ")";+ auto result = executeInternal(sql);+ std::vector<IndexInfo> indexes;+ for (auto& row : result.rows)+ {+ IndexInfo idx;+ idx.name = row[L"name"];+ idx.isUnique = (row[L"unique"] == L"1");+ idx.algorithm = L"BTREE";++ // Get columns for this index+ std::string colSql = "PRAGMA index_info(" + quoteIdentifier(idx.name) + ")";+ auto colResult = executeInternal(colSql);+ std::wstring cols;+ for (auto& cr : colResult.rows)+ {+ if (!cols.empty()) cols += L", ";+ cols += cr[L"name"];+ }+ idx.columns = cols;+ indexes.push_back(idx);+ }+ return indexes;+ }++ std::vector<ForeignKeyInfo> SQLiteAdapter::listForeignKeys(+ const std::wstring& table, const std::wstring& /*schema*/)+ {+ std::string sql = "PRAGMA foreign_key_list(" + quoteIdentifier(table) + ")";+ auto result = executeInternal(sql);+ std::vector<ForeignKeyInfo> fks;+ for (auto& row : result.rows)+ {+ ForeignKeyInfo fk;+ fk.name = std::wstring(L"fk_") + row[L"id"];+ fk.column = row[L"from"];+ fk.referencedTable = row[L"table"];+ fk.referencedColumn = row[L"to"];+ fk.onUpdate = row[L"on_update"];+ fk.onDelete = row[L"on_delete"];+ fks.push_back(fk);+ }+ return fks;+ }++ std::vector<std::wstring> SQLiteAdapter::listFunctions(const std::wstring& /*schema*/)+ {+ return {}; // SQLite has no user-defined functions via SQL+ }++ std::wstring SQLiteAdapter::getFunctionSource(+ const std::wstring& /*name*/, const std::wstring& /*schema*/)+ {+ return L""; // Not applicable for SQLite+ }++ std::wstring SQLiteAdapter::getCreateTableSQL(+ const std::wstring& table, const std::wstring& /*schema*/)+ {+ // sqlite_master stores the original CREATE TABLE statement+ std::string sql =+ "SELECT sql FROM sqlite_master WHERE type='table' AND name=" ++ quoteLiteral(table);+ auto result = execute(fromUtf8(sql));+ if (!result.rows.empty())+ {+ auto it = result.rows[0].find(L"sql");+ if (it != result.rows[0].end()) return it->second;+ }+ return L"";+ }++ // ── DML ─────────────────────────────────────────+ QueryResult SQLiteAdapter::insertRow(+ const std::wstring& table, const std::wstring& /*schema*/,+ const TableRow& values)+ {+ std::string sql = "INSERT INTO " + quoteIdentifier(table) + " (";+ std::string valsSql;+ bool first = true;+ for (auto& [col, val] : values)+ {+ if (!first) { sql += ", "; valsSql += ", "; }+ sql += quoteIdentifier(col);+ valsSql += isNullCell(val) ? "NULL" : quoteLiteral(val);+ first = false;+ }+ sql += ") VALUES (" + valsSql + ")";+ return executeInternal(sql);+ }++ QueryResult SQLiteAdapter::updateRow(+ const std::wstring& table, const std::wstring& /*schema*/,+ const TableRow& setValues, const TableRow& whereValues)+ {+ std::string sql = "UPDATE " + quoteIdentifier(table) + " SET ";+ bool first = true;+ for (auto& [col, val] : setValues)+ {+ if (!first) sql += ", ";+ sql += quoteIdentifier(col) + " = " + (isNullCell(val) ? "NULL" : quoteLiteral(val));+ first = false;+ }+ sql += " WHERE ";+ first = true;+ for (auto& [col, val] : whereValues)+ {+ if (!first) sql += " AND ";+ if (isNullCell(val))+ sql += quoteIdentifier(col) + " IS NULL";+ else+ sql += quoteIdentifier(col) + " = " + quoteLiteral(val);+ first = false;+ }+ return executeInternal(sql);+ }++ QueryResult SQLiteAdapter::deleteRow(+ const std::wstring& table, const std::wstring& /*schema*/,+ const TableRow& whereValues)+ {+ std::string sql = "DELETE FROM " + quoteIdentifier(table) + " WHERE ";+ bool first = true;+ for (auto& [col, val] : whereValues)+ {+ if (!first) sql += " AND ";+ if (isNullCell(val))+ sql += quoteIdentifier(col) + " IS NULL";+ else+ sql += quoteIdentifier(col) + " = " + quoteLiteral(val);+ first = false;+ }+ return executeInternal(sql);+ }++ // ── Transactions ────────────────────────────────+ void SQLiteAdapter::beginTransaction() { executeInternal("BEGIN TRANSACTION"); }+ void SQLiteAdapter::commitTransaction() { executeInternal("COMMIT"); }+ void SQLiteAdapter::rollbackTransaction() { executeInternal("ROLLBACK"); }++ // ── Server Info ─────────────────────────────────+ std::wstring SQLiteAdapter::serverVersion()+ {+ return fromUtf8(sqlite3_libversion());+ }++ std::wstring SQLiteAdapter::currentDatabase()+ {+ return filePath_;+ }+}diff --git a/windows/Gridex/SSHTunnelService.cpp b/windows/Gridex/SSHTunnelService.cppnew file mode 100644index 0000000..78693b1--- /dev/null+++ b/windows/Gridex/SSHTunnelService.cpp@@ -0,0 +1,324 @@+// SSHTunnelService.cpp — SSH local port forwarding via libssh2.+//+// Opens an SSH connection, binds a local TCP socket on a free port,+// and forwards traffic through the SSH channel to the remote DB host.+// The forwarding loop runs on a detached background thread and stops+// when close() sets active_ = false.++#include <winsock2.h>+#include <ws2tcpip.h>+#include <windows.h>+#include <libssh2.h>+#include "Models/SSHTunnelService.h"+#include "Models/DatabaseAdapter.h"++#include <fstream>+#include <vector>++#pragma comment(lib, "ws2_32.lib")++namespace DBModels+{+ // ── Helpers ───────────────────────────────────────────────+ std::string SSHTunnelService::toUtf8(const std::wstring& s)+ {+ if (s.empty()) return {};+ int sz = WideCharToMultiByte(CP_UTF8, 0, s.c_str(),+ static_cast<int>(s.size()), nullptr, 0, nullptr, nullptr);+ std::string out(sz, '\0');+ WideCharToMultiByte(CP_UTF8, 0, s.c_str(),+ static_cast<int>(s.size()), &out[0], sz, nullptr, nullptr);+ return out;+ }++ uint16_t SSHTunnelService::findFreePort()+ {+ SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);+ if (s == INVALID_SOCKET) return 0;++ sockaddr_in addr{};+ addr.sin_family = AF_INET;+ addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);+ addr.sin_port = 0; // OS picks free port++ if (bind(s, (sockaddr*)&addr, sizeof(addr)) != 0)+ {+ closesocket(s);+ return 0;+ }++ int addrLen = sizeof(addr);+ getsockname(s, (sockaddr*)&addr, &addrLen);+ uint16_t port = ntohs(addr.sin_port);+ closesocket(s);+ return port;+ }++ // ── Constructor / Destructor ──────────────────────────────+ SSHTunnelService::SSHTunnelService()+ {+ // Ensure Winsock is initialized (safe to call multiple times)+ WSADATA wsa;+ WSAStartup(MAKEWORD(2, 2), &wsa);+ }++ SSHTunnelService::~SSHTunnelService()+ {+ close();+ }++ // ── Establish tunnel ─────────────────────────────────────+ uint16_t SSHTunnelService::establish(+ const SSHTunnelConfig& config,+ const std::wstring& sshPassword,+ const std::string& remoteHost,+ int remotePort)+ {+ close(); // tear down any existing tunnel++ remoteHost_ = remoteHost;+ remotePort_ = remotePort;++ auto sshHost = toUtf8(config.host.empty() ? L"127.0.0.1" : config.host);+ auto sshUser = toUtf8(config.username);+ auto sshPass = toUtf8(sshPassword);+ auto sshKeyPath = toUtf8(config.keyPath);+ int sshPort = config.port > 0 ? config.port : 22;++ // 1. TCP connect to SSH server+ struct addrinfo hints{}, *res = nullptr;+ hints.ai_family = AF_INET;+ hints.ai_socktype = SOCK_STREAM;++ if (getaddrinfo(sshHost.c_str(), std::to_string(sshPort).c_str(),+ &hints, &res) != 0 || !res)+ {+ throw DatabaseError(DatabaseError::Code::SSHTunnelFailed,+ "Cannot resolve SSH host: " + sshHost);+ }++ SOCKET sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);+ if (sock == INVALID_SOCKET)+ {+ freeaddrinfo(res);+ throw DatabaseError(DatabaseError::Code::SSHTunnelFailed,+ "Cannot create socket for SSH");+ }++ // Set 15-second connect timeout+ DWORD timeout = 15000;+ setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));+ setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (char*)&timeout, sizeof(timeout));++ if (::connect(sock, res->ai_addr, (int)res->ai_addrlen) != 0)+ {+ closesocket(sock);+ freeaddrinfo(res);+ throw DatabaseError(DatabaseError::Code::SSHTunnelFailed,+ "Cannot connect to SSH server " + sshHost + ":" + std::to_string(sshPort));+ }+ freeaddrinfo(res);+ sshSock_ = static_cast<uintptr_t>(sock);++ // 2. Initialize libssh2 session+ libssh2_init(0);+ session_ = libssh2_session_init();+ if (!session_)+ {+ closesocket(sock);+ sshSock_ = ~0ULL;+ throw DatabaseError(DatabaseError::Code::SSHTunnelFailed,+ "libssh2_session_init failed");+ }++ // Set blocking mode for handshake+ libssh2_session_set_blocking(session_, 1);++ if (libssh2_session_handshake(session_, (libssh2_socket_t)sock) != 0)+ {+ char* errMsg = nullptr;+ libssh2_session_last_error(session_, &errMsg, nullptr, 0);+ std::string err = errMsg ? errMsg : "SSH handshake failed";+ libssh2_session_free(session_); session_ = nullptr;+ closesocket(sock); sshSock_ = ~0ULL;+ throw DatabaseError(DatabaseError::Code::SSHTunnelFailed, err);+ }++ // 3. Authenticate+ int authRc = -1;+ if (config.authMethod == SSHAuthMethod::Password || sshKeyPath.empty())+ {+ // Password auth+ authRc = libssh2_userauth_password(session_,+ sshUser.c_str(), sshPass.c_str());+ }+ else+ {+ // Key-based auth (PrivateKey or KeyWithPassphrase)+ const char* passphrase = sshPass.empty() ? nullptr : sshPass.c_str();+ authRc = libssh2_userauth_publickey_fromfile(session_,+ sshUser.c_str(),+ nullptr, // public key (auto-derive from private)+ sshKeyPath.c_str(),+ passphrase);+ }++ if (authRc != 0)+ {+ char* errMsg = nullptr;+ libssh2_session_last_error(session_, &errMsg, nullptr, 0);+ std::string err = errMsg ? errMsg : "SSH authentication failed";+ libssh2_session_disconnect(session_, "auth failed");+ libssh2_session_free(session_); session_ = nullptr;+ closesocket(sock); sshSock_ = ~0ULL;+ throw DatabaseError(DatabaseError::Code::SSHTunnelFailed, err);+ }++ // 4. Bind local listener+ localPort_ = findFreePort();+ if (localPort_ == 0)+ {+ libssh2_session_disconnect(session_, "no free port");+ libssh2_session_free(session_); session_ = nullptr;+ closesocket(sock); sshSock_ = ~0ULL;+ throw DatabaseError(DatabaseError::Code::SSHTunnelFailed,+ "Cannot find free local port for SSH tunnel");+ }++ SOCKET lsock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);+ sockaddr_in laddr{};+ laddr.sin_family = AF_INET;+ laddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);+ laddr.sin_port = htons(localPort_);++ if (bind(lsock, (sockaddr*)&laddr, sizeof(laddr)) != 0 ||+ listen(lsock, 1) != 0)+ {+ closesocket(lsock);+ libssh2_session_disconnect(session_, "bind failed");+ libssh2_session_free(session_); session_ = nullptr;+ closesocket(sock); sshSock_ = ~0ULL;+ throw DatabaseError(DatabaseError::Code::SSHTunnelFailed,+ "Cannot bind local port " + std::to_string(localPort_));+ }+ listenSock_ = static_cast<uintptr_t>(lsock);++ // 5. Start forwarding thread+ active_ = true;+ forwardThread_ = std::thread(&SSHTunnelService::forwardLoop, this);++ return localPort_;+ }++ // ── Forward loop (background thread) ─────────────────────+ void SSHTunnelService::forwardLoop()+ {+ SOCKET lsock = static_cast<SOCKET>(listenSock_);++ while (active_)+ {+ // Non-blocking accept with 1-second timeout via select+ fd_set fds;+ FD_ZERO(&fds);+ FD_SET(lsock, &fds);+ timeval tv{1, 0};++ int sel = select(0, &fds, nullptr, nullptr, &tv);+ if (sel <= 0) continue;++ sockaddr_in clientAddr{};+ int clientLen = sizeof(clientAddr);+ SOCKET clientSock = accept(lsock, (sockaddr*)&clientAddr, &clientLen);+ if (clientSock == INVALID_SOCKET) continue;++ // Open SSH direct-tcpip channel to remote DB+ LIBSSH2_CHANNEL* channel = libssh2_channel_direct_tcpip(+ session_, remoteHost_.c_str(), remotePort_);++ if (!channel)+ {+ closesocket(clientSock);+ continue;+ }++ // Bidirectional forward until either side closes+ libssh2_session_set_blocking(session_, 0);+ char buf[16384];++ while (active_)+ {+ // Client → SSH channel+ fd_set rds;+ FD_ZERO(&rds);+ FD_SET(clientSock, &rds);+ timeval poll{0, 100000}; // 100ms++ if (select(0, &rds, nullptr, nullptr, &poll) > 0)+ {+ int n = recv(clientSock, buf, sizeof(buf), 0);+ if (n <= 0) break;+ // Write all to channel+ int written = 0;+ while (written < n)+ {+ int w = libssh2_channel_write(channel, buf + written, n - written);+ if (w == LIBSSH2_ERROR_EAGAIN) { Sleep(1); continue; }+ if (w < 0) goto done;+ written += w;+ }+ }++ // SSH channel → Client+ for (;;)+ {+ int n = libssh2_channel_read(channel, buf, sizeof(buf));+ if (n == LIBSSH2_ERROR_EAGAIN) break;+ if (n <= 0) goto done;+ send(clientSock, buf, n, 0);+ }++ if (libssh2_channel_eof(channel)) break;+ }++ done:+ libssh2_channel_close(channel);+ libssh2_channel_free(channel);+ closesocket(clientSock);++ // Reset to blocking for next channel open+ if (session_)+ libssh2_session_set_blocking(session_, 1);+ }+ }++ // ── Close tunnel ─────────────────────────────────────────+ void SSHTunnelService::close()+ {+ active_ = false;++ // Close listen socket to unblock accept in forwardLoop+ if (listenSock_ != ~0ULL)+ {+ closesocket(static_cast<SOCKET>(listenSock_));+ listenSock_ = ~0ULL;+ }++ if (forwardThread_.joinable())+ forwardThread_.join();++ if (session_)+ {+ libssh2_session_disconnect(session_, "Normal shutdown");+ libssh2_session_free(session_);+ session_ = nullptr;+ }++ if (sshSock_ != ~0ULL)+ {+ closesocket(static_cast<SOCKET>(sshSock_));+ sshSock_ = ~0ULL;+ }++ localPort_ = 0;+ }+}diff --git a/windows/Gridex/SettingsPage.cpp b/windows/Gridex/SettingsPage.cppnew file mode 100644index 0000000..49f1c8b--- /dev/null+++ b/windows/Gridex/SettingsPage.cpp@@ -0,0 +1,128 @@+#include "pch.h"+#include "xaml-includes.h"+#include <winrt/Microsoft.UI.Xaml.Interop.h>+#include <shellapi.h>+#include "SettingsPage.h"+#include "Models/AppSettings.h"+#include "GridexVersion.h"+#if __has_include("SettingsPage.g.cpp")+#include "SettingsPage.g.cpp"+#endif++namespace winrt::Gridex::implementation+{+ namespace mux = winrt::Microsoft::UI::Xaml;+ namespace muxc = winrt::Microsoft::UI::Xaml::Controls;++ SettingsPage::SettingsPage()+ {+ InitializeComponent();++ this->Loaded([this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ // Stamp the build version into the About section. GRIDEX_VERSION+ // comes from GridexVersion.h which pulls the CI-generated header+ // when present (release builds) or falls back to "0.0.0-dev".+ VersionText().Text(winrt::hstring(L"Version " GRIDEX_VERSION));++ // Load persisted settings into UI+ auto s = DBModels::AppSettings::Load();+ ThemeCombo().SelectedIndex(s.themeIndex);+ AiProviderCombo().SelectedIndex(s.aiProviderIndex);+ ApiKeyBox().Password(winrt::hstring(s.aiApiKey));+ ModelBox().Text(winrt::hstring(s.aiModel));+ OllamaEndpointBox().Text(winrt::hstring(s.ollamaEndpoint));+ EditorFontSizeBox().Value(static_cast<double>(s.editorFontSize));+ RowLimitBox().Value(static_cast<double>(s.rowLimit));++ ThemeCombo().SelectionChanged(+ [this](winrt::Windows::Foundation::IInspectable const&, muxc::SelectionChangedEventArgs const&)+ {+ // Inline: SelectionChangedEventArgs cannot be default-constructed+ int index = ThemeCombo().SelectedIndex();+ auto root = this->XamlRoot();+ if (!root) return;+ auto fe = root.Content().try_as<mux::FrameworkElement>();+ if (!fe) return;+ switch (index)+ {+ case 0: fe.RequestedTheme(mux::ElementTheme::Default); break;+ case 1: fe.RequestedTheme(mux::ElementTheme::Light); break;+ case 2: fe.RequestedTheme(mux::ElementTheme::Dark); break;+ }+ });+ SaveAiButton().Click(+ [this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ SaveAiSettings_Click({}, {});+ });++ // View Open Source Licenses — open THIRD-PARTY-NOTICES.txt+ // bundled in Assets/ via the system default text editor.+ ViewLicensesButton().Click(+ [](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ wchar_t exePath[MAX_PATH] = {};+ GetModuleFileNameW(nullptr, exePath, MAX_PATH);+ std::wstring exeDir(exePath);+ auto slash = exeDir.find_last_of(L"\\/");+ if (slash != std::wstring::npos) exeDir = exeDir.substr(0, slash);+ std::wstring noticesPath = exeDir + L"\\Assets\\THIRD-PARTY-NOTICES.txt";+ ShellExecuteW(nullptr, L"open", noticesPath.c_str(),+ nullptr, nullptr, SW_SHOWNORMAL);+ });++ // Back button — navigate back to the page user came from+ BackBtn().Click(+ [this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ muxc::Frame frame{ nullptr };+ auto fe = this->try_as<mux::FrameworkElement>();+ while (fe)+ {+ if (auto f = fe.try_as<muxc::Frame>()) { frame = f; break; }+ fe = fe.Parent().try_as<mux::FrameworkElement>();+ }+ if (!frame) frame = this->Frame();+ if (!frame) return;++ // Read stored previous page (defaults to HomePage)+ auto saved = DBModels::AppSettings::Load();+ std::wstring targetPage = saved.lastPageBeforeSettings;+ if (targetPage.empty()) targetPage = L"Gridex.HomePage";++ winrt::Windows::UI::Xaml::Interop::TypeName pageType;+ pageType.Name = winrt::hstring(targetPage);+ pageType.Kind = winrt::Windows::UI::Xaml::Interop::TypeKind::Metadata;+ frame.Navigate(pageType);+ });+ });+ }++ void SettingsPage::SaveAiSettings_Click(+ winrt::Windows::Foundation::IInspectable const&,+ mux::RoutedEventArgs const&)+ {+ // Load current (preserve fields not touched here), then overwrite from UI+ auto s = DBModels::AppSettings::Load();+ s.themeIndex = ThemeCombo().SelectedIndex();+ s.aiProviderIndex = AiProviderCombo().SelectedIndex();+ s.aiApiKey = std::wstring(ApiKeyBox().Password());+ s.aiModel = std::wstring(ModelBox().Text());+ s.ollamaEndpoint = std::wstring(OllamaEndpointBox().Text());+ s.editorFontSize = static_cast<int>(EditorFontSizeBox().Value());+ s.rowLimit = static_cast<int>(RowLimitBox().Value());++ bool ok = s.Save();++ muxc::ContentDialog dialog;+ dialog.Title(winrt::box_value(winrt::hstring(+ ok ? L"Settings Saved" : L"Save Failed")));+ dialog.Content(winrt::box_value(winrt::hstring(+ ok ? L"Settings have been saved."+ : L"Could not write to settings file.")));+ dialog.CloseButtonText(L"OK");+ dialog.XamlRoot(this->XamlRoot());+ dialog.ShowAsync();+ }+}diff --git a/windows/Gridex/SettingsPage.h b/windows/Gridex/SettingsPage.hnew file mode 100644index 0000000..a4f1b60--- /dev/null+++ b/windows/Gridex/SettingsPage.h@@ -0,0 +1,22 @@+#pragma once++#include "SettingsPage.g.h"++namespace winrt::Gridex::implementation+{+ struct SettingsPage : SettingsPageT<SettingsPage>+ {+ SettingsPage();++ void SaveAiSettings_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);+ };+}++namespace winrt::Gridex::factory_implementation+{+ struct SettingsPage : SettingsPageT<SettingsPage, implementation::SettingsPage>+ {+ };+}diff --git a/windows/Gridex/SettingsPage.idl b/windows/Gridex/SettingsPage.idlnew file mode 100644index 0000000..d687bd9--- /dev/null+++ b/windows/Gridex/SettingsPage.idl@@ -0,0 +1,8 @@+namespace Gridex+{+ [default_interface]+ runtimeclass SettingsPage : Microsoft.UI.Xaml.Controls.Page+ {+ SettingsPage();+ }+}diff --git a/windows/Gridex/SettingsPage.xaml b/windows/Gridex/SettingsPage.xamlnew file mode 100644index 0000000..854c8cc--- /dev/null+++ b/windows/Gridex/SettingsPage.xaml@@ -0,0 +1,202 @@+<Page+ x:Class="Gridex.SettingsPage"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:local="using:Gridex"+ Background="Transparent">++ <ScrollViewer Padding="32,24">+ <StackPanel MaxWidth="700" Spacing="24">++ <!-- Header with Back button -->+ <StackPanel Spacing="8">+ <Button x:Name="BackBtn"+ Background="Transparent" BorderThickness="0"+ Padding="8,4" HorizontalAlignment="Left"+ ToolTipService.ToolTip="Back">+ <StackPanel Orientation="Horizontal" Spacing="6">+ <FontIcon Glyph="" FontSize="14" />+ <TextBlock Text="Back" FontSize="13" />+ </StackPanel>+ </Button>+ <TextBlock Text="Settings" FontSize="28" FontWeight="SemiBold" />+ <TextBlock Text="Configure Gridex preferences"+ FontSize="13"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ </StackPanel>++ <!-- Appearance -->+ <StackPanel Spacing="12">+ <TextBlock Text="Appearance" FontSize="16" FontWeight="SemiBold" />++ <Grid Padding="16"+ Background="{ThemeResource CardBackgroundFillColorDefaultBrush}"+ CornerRadius="8"+ BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}"+ BorderThickness="1">+ <Grid.RowDefinitions>+ <RowDefinition Height="Auto" />+ <RowDefinition Height="Auto" />+ </Grid.RowDefinitions>+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="*" />+ <ColumnDefinition Width="Auto" />+ </Grid.ColumnDefinitions>++ <StackPanel Grid.Row="0" Grid.Column="0" Spacing="2">+ <TextBlock Text="Theme" FontSize="14" />+ <TextBlock Text="Choose light, dark, or system default"+ FontSize="12"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ </StackPanel>+ <ComboBox x:Name="ThemeCombo" Grid.Row="0" Grid.Column="1"+ MinWidth="140"+ SelectedIndex="0"+>+ <ComboBoxItem Content="System Default" />+ <ComboBoxItem Content="Light" />+ <ComboBoxItem Content="Dark" />+ </ComboBox>++ <Border Grid.Row="1" Grid.ColumnSpan="2"+ Height="1" Margin="0,12,0,0"+ Background="{ThemeResource DividerStrokeColorDefaultBrush}"+ Visibility="Collapsed" />+ </Grid>+ </StackPanel>++ <!-- AI Configuration -->+ <StackPanel Spacing="12">+ <TextBlock Text="AI Assistant" FontSize="16" FontWeight="SemiBold" />++ <Grid Padding="16"+ Background="{ThemeResource CardBackgroundFillColorDefaultBrush}"+ CornerRadius="8"+ BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}"+ BorderThickness="1">+ <StackPanel Spacing="16">+ <StackPanel Spacing="4">+ <TextBlock Text="Provider" FontSize="14" />+ <!-- Order MUST match DBModels::AiProvider enum+ in Models/AiService.h — never reorder, only+ append at the end (the index is persisted+ in settings as aiProviderIndex). -->+ <ComboBox x:Name="AiProviderCombo" MinWidth="200"+ SelectedIndex="0">+ <ComboBoxItem Content="Anthropic (Claude)" />+ <ComboBoxItem Content="OpenAI (GPT)" />+ <ComboBoxItem Content="Ollama (Local)" />+ <ComboBoxItem Content="Google Gemini" />+ <ComboBoxItem Content="OpenRouter" />+ </ComboBox>+ </StackPanel>++ <StackPanel Spacing="4">+ <TextBlock Text="API Key" FontSize="14" />+ <PasswordBox x:Name="ApiKeyBox"+ PlaceholderText="Enter your API key..."+ Width="400"+ HorizontalAlignment="Left" />+ </StackPanel>++ <StackPanel Spacing="4">+ <TextBlock Text="Model" FontSize="14" />+ <TextBox x:Name="ModelBox"+ PlaceholderText="e.g. claude-sonnet-4-20250514, gpt-4o, llama3, gemini-2.0-flash, openai/gpt-4o-mini"+ Width="400"+ HorizontalAlignment="Left" />+ </StackPanel>++ <StackPanel x:Name="OllamaEndpointPanel" Spacing="4">+ <TextBlock Text="Ollama Endpoint" FontSize="14" />+ <TextBox x:Name="OllamaEndpointBox"+ PlaceholderText="http://localhost:11434"+ Width="400"+ HorizontalAlignment="Left" />+ </StackPanel>+ </StackPanel>+ </Grid>+ </StackPanel>++ <!-- Editor -->+ <StackPanel Spacing="12">+ <TextBlock Text="Editor" FontSize="16" FontWeight="SemiBold" />++ <Grid Padding="16"+ Background="{ThemeResource CardBackgroundFillColorDefaultBrush}"+ CornerRadius="8"+ BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}"+ BorderThickness="1">+ <StackPanel Spacing="12">+ <StackPanel Spacing="4">+ <TextBlock Text="Font Size" FontSize="14" />+ <NumberBox x:Name="EditorFontSizeBox" Value="13"+ Minimum="8" Maximum="24"+ SpinButtonPlacementMode="Inline"+ Width="120"+ HorizontalAlignment="Left" />+ </StackPanel>++ <StackPanel Spacing="4">+ <TextBlock Text="Default Row Limit" FontSize="14" />+ <NumberBox x:Name="RowLimitBox" Value="100"+ Minimum="10" Maximum="10000"+ SpinButtonPlacementMode="Inline"+ Width="160"+ HorizontalAlignment="Left" />+ </StackPanel>+ </StackPanel>+ </Grid>+ </StackPanel>++ <!-- About -->+ <StackPanel Spacing="8">+ <TextBlock Text="About" FontSize="16" FontWeight="SemiBold" />+ <TextBlock FontSize="13"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}">+ <Run Text="Gridex" FontWeight="SemiBold" />+ <Run Text=" — AI-Native Database IDE" />+ </TextBlock>+ <TextBlock x:Name="VersionText"+ FontSize="12"+ Foreground="{ThemeResource TextFillColorTertiaryBrush}" />++ <!-- Open Source attribution -->+ <TextBlock FontSize="11"+ Margin="0,8,0,0"+ Foreground="{ThemeResource TextFillColorTertiaryBrush}"+ TextWrapping="Wrap">+ <Run Text="ER Diagram rendering powered by " />+ <Run Text="D2" FontWeight="SemiBold" />+ <Run Text=" (MPL-2.0) © Terrastruct, Inc." />+ <LineBreak />+ <Run Text="Database connectivity via libpq, libmariadb, sqlite3. UI via WinUI 3 + WebView2." />+ </TextBlock>++ <Button x:Name="ViewLicensesButton"+ Content="View Open Source Licenses..."+ Margin="0,8,0,0"+ Padding="12,4"+ FontSize="12" />+ </StackPanel>++ <!-- Save All — applies to every section above -->+ <Border Margin="0,8,0,32"+ Padding="0,16,0,0"+ BorderBrush="{ThemeResource DividerStrokeColorDefaultBrush}"+ BorderThickness="0,1,0,0">+ <StackPanel Orientation="Horizontal" Spacing="12"+ HorizontalAlignment="Right">+ <TextBlock x:Name="SaveStatusText"+ VerticalAlignment="Center"+ FontSize="12"+ Foreground="{ThemeResource TextFillColorTertiaryBrush}" />+ <Button x:Name="SaveAiButton"+ Content="Save All Settings"+ Padding="20,8"+ Style="{StaticResource AccentButtonStyle}" />+ </StackPanel>+ </Border>+ </StackPanel>+ </ScrollViewer>+</Page>diff --git a/windows/Gridex/SidebarPanel.cpp b/windows/Gridex/SidebarPanel.cppnew file mode 100644index 0000000..f5e0ba7--- /dev/null+++ b/windows/Gridex/SidebarPanel.cpp@@ -0,0 +1,584 @@+#include "pch.h"+#include "xaml-includes.h"+#include <winrt/Windows.UI.h>+#include <winrt/Windows.ApplicationModel.DataTransfer.h>+#include "SidebarPanel.h"+#if __has_include("SidebarPanel.g.cpp")+#include "SidebarPanel.g.cpp"+#endif++#include <algorithm>++namespace winrt::Gridex::implementation+{+ namespace mux = winrt::Microsoft::UI::Xaml;+ namespace muxc = winrt::Microsoft::UI::Xaml::Controls;+ namespace muxm = winrt::Microsoft::UI::Xaml::Media;++ SidebarPanel::SidebarPanel()+ {+ InitializeComponent();++ // Wire schema picker in code-behind (no IDL needed)+ this->Loaded([this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ // Wire Add/Delete buttons+ AddItemBtn().Click(+ [this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ if (OnAddTable) OnAddTable();+ });+ DeleteItemBtn().Click(+ [this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ if (!selectedItemName_.empty() && OnDeleteTable)+ OnDeleteTable(selectedItemName_, selectedItemSchema_);+ });++ SchemaPicker().SelectionChanged(+ [this](winrt::Windows::Foundation::IInspectable const&, muxc::SelectionChangedEventArgs const&)+ {+ if (suppressSchemaEvent_) return; // Guard during SetSchemas+ auto selected = SchemaPicker().SelectedItem();+ if (!selected) return;+ auto item = selected.try_as<muxc::ComboBoxItem>();+ if (!item) return;+ auto content = item.Content();+ if (!content) return;+ auto schema = winrt::unbox_value<winrt::hstring>(content);+ if (OnSchemaChanged)+ OnSchemaChanged(std::wstring(schema));+ });+ });+ }++ void SidebarPanel::SetSchemas(const std::vector<std::wstring>& schemas)+ {+ suppressSchemaEvent_ = true; // Don't fire OnSchemaChanged during population+ SchemaPicker().Items().Clear();+ for (auto& s : schemas)+ {+ muxc::ComboBoxItem item;+ item.Content(winrt::box_value(winrt::hstring(s)));+ SchemaPicker().Items().Append(item);+ }+ if (!schemas.empty())+ SchemaPicker().SelectedIndex(0);+ suppressSchemaEvent_ = false;+ }++ void SidebarPanel::SetItems(const std::vector<DBModels::SidebarItem>& items)+ {+ items_ = items;+ RenderTree();+ }++ // ── Tab clicks ──────────────────────────────────────+ void SidebarPanel::ItemsTab_Click(+ winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ ItemsTab().IsChecked(true);+ QueriesTab().IsChecked(false);+ HistoryTab().IsChecked(false);+ ItemsContent().Visibility(mux::Visibility::Visible);+ QueriesContent().Visibility(mux::Visibility::Collapsed);+ HistoryContent().Visibility(mux::Visibility::Collapsed);+ SearchBox().PlaceholderText(L"Search for item...");+ }+ void SidebarPanel::QueriesTab_Click(+ winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ ItemsTab().IsChecked(false);+ QueriesTab().IsChecked(true);+ HistoryTab().IsChecked(false);+ ItemsContent().Visibility(mux::Visibility::Collapsed);+ QueriesContent().Visibility(mux::Visibility::Visible);+ HistoryContent().Visibility(mux::Visibility::Collapsed);+ SearchBox().PlaceholderText(L"Search queries...");++ // Show placeholder if empty+ if (QueriesContainer().Children().Size() == 0)+ {+ muxc::TextBlock placeholder;+ placeholder.Text(L"No saved queries yet");+ placeholder.FontSize(12.0);+ placeholder.Opacity(0.4);+ placeholder.HorizontalAlignment(mux::HorizontalAlignment::Center);+ placeholder.Margin(mux::Thickness{ 0, 40, 0, 0 });+ QueriesContainer().Children().Append(placeholder);+ }+ }+ void SidebarPanel::HistoryTab_Click(+ winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ ItemsTab().IsChecked(false);+ QueriesTab().IsChecked(false);+ HistoryTab().IsChecked(true);+ ItemsContent().Visibility(mux::Visibility::Collapsed);+ QueriesContent().Visibility(mux::Visibility::Collapsed);+ HistoryContent().Visibility(mux::Visibility::Visible);+ SearchBox().PlaceholderText(L"Search history...");+ }++ void SidebarPanel::SetHistory(const std::vector<std::pair<std::wstring, std::wstring>>& entries)+ {+ HistoryContainer().Children().Clear();++ if (entries.empty())+ {+ muxc::TextBlock placeholder;+ placeholder.Text(L"No query history");+ placeholder.FontSize(12.0);+ placeholder.Opacity(0.4);+ placeholder.HorizontalAlignment(mux::HorizontalAlignment::Center);+ placeholder.Margin(mux::Thickness{ 0, 40, 0, 0 });+ HistoryContainer().Children().Append(placeholder);+ return;+ }++ // Show newest first (reverse order)+ for (int i = static_cast<int>(entries.size()) - 1; i >= 0; i--)+ {+ auto& [timestamp, sql] = entries[i];++ muxc::Button item;+ item.HorizontalAlignment(mux::HorizontalAlignment::Stretch);+ item.HorizontalContentAlignment(mux::HorizontalAlignment::Left);+ item.Padding(mux::Thickness{ 12, 6, 12, 6 });+ item.Background(muxm::SolidColorBrush(winrt::Windows::UI::Colors::Transparent()));+ item.BorderThickness(mux::Thickness{ 0, 0, 0, 0 });++ muxc::StackPanel sp;+ sp.Spacing(2.0);++ // Timestamp+ muxc::TextBlock timeTb;+ timeTb.Text(winrt::hstring(timestamp));+ timeTb.FontSize(10.0);+ timeTb.Opacity(0.4);+ sp.Children().Append(timeTb);++ // SQL (truncated)+ muxc::TextBlock sqlTb;+ std::wstring sqlDisplay = sql;+ if (sqlDisplay.size() > 80)+ sqlDisplay = sqlDisplay.substr(0, 80) + L"...";+ // Replace newlines+ for (auto& c : sqlDisplay)+ if (c == L'\n' || c == L'\r') c = L' ';+ sqlTb.Text(winrt::hstring(sqlDisplay));+ sqlTb.FontSize(11.0);+ sqlTb.FontFamily(mux::Media::FontFamily(L"Cascadia Code,Consolas,monospace"));+ sqlTb.TextTrimming(mux::TextTrimming::CharacterEllipsis);+ sqlTb.MaxLines(2);+ sp.Children().Append(sqlTb);++ item.Content(sp);++ // Click → fill query editor+ std::wstring capturedSql = sql;+ item.Click([this, capturedSql](auto&&, auto&&)+ {+ if (OnHistoryItemClicked)+ OnHistoryItemClicked(capturedSql);+ });++ HistoryContainer().Children().Append(item);++ // Separator+ muxc::Border sep;+ sep.Height(1.0);+ sep.Background(muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(15, 128, 128, 128)));+ HistoryContainer().Children().Append(sep);+ }+ }++ // ── Search ──────────────────────────────────────────+ void SidebarPanel::SearchBox_TextChanged(+ winrt::Windows::Foundation::IInspectable const& sender, mux::RoutedEventArgs const&)+ {+ auto tb = sender.as<muxc::TextBox>();+ searchQuery_ = std::wstring(tb.Text());+ std::transform(searchQuery_.begin(), searchQuery_.end(), searchQuery_.begin(), ::towlower);+ RenderTree();+ }++ bool SidebarPanel::MatchesSearch(const DBModels::SidebarItem& item) const+ {+ if (searchQuery_.empty()) return true;+ std::wstring titleLower = item.title;+ std::transform(titleLower.begin(), titleLower.end(), titleLower.begin(), ::towlower);+ if (titleLower.find(searchQuery_) != std::wstring::npos) return true;+ for (auto& child : item.children)+ if (MatchesSearch(child)) return true;+ return false;+ }++ // ── Expand/Collapse ─────────────────────────────────+ void SidebarPanel::ToggleGroup(const std::wstring& groupId)+ {+ // Recursively find and toggle+ std::function<bool(std::vector<DBModels::SidebarItem>&)> toggle =+ [&](std::vector<DBModels::SidebarItem>& items) -> bool+ {+ for (auto& item : items)+ {+ if (item.id == groupId)+ {+ item.isExpanded = !item.isExpanded;+ return true;+ }+ if (toggle(item.children)) return true;+ }+ return false;+ };+ toggle(items_);+ RenderTree();+ }++ // ── Render ───────────────────────────────────────────+ void SidebarPanel::RenderTree()+ {+ if (!TreeContainer()) return;+ TreeContainer().Children().Clear();+ for (auto& item : items_)+ {+ if (MatchesSearch(item))+ RenderItem(TreeContainer(), item, 0);+ }+ }++ void SidebarPanel::RenderItem(+ muxc::StackPanel const& container,+ const DBModels::SidebarItem& item,+ int depth)+ {+ bool isGroup = (item.type == DBModels::SidebarItemType::Group ||+ item.type == DBModels::SidebarItemType::Schema ||+ item.type == DBModels::SidebarItemType::Database);++ if (isGroup)+ {+ // Mutable copy for group header (toggle needs mutable)+ auto mutableItem = item;+ RenderGroupHeader(container, mutableItem, depth);++ // Render children if expanded+ if (item.isExpanded)+ {+ for (auto& child : item.children)+ {+ if (MatchesSearch(child))+ RenderItem(container, child, depth + 1);+ }+ }+ return;+ }++ // ── Leaf item row ──+ muxc::Button btn;+ btn.HorizontalAlignment(mux::HorizontalAlignment::Stretch);+ btn.HorizontalContentAlignment(mux::HorizontalAlignment::Left);+ btn.Background(muxm::SolidColorBrush(winrt::Windows::UI::Colors::Transparent()));+ btn.BorderThickness(mux::Thickness{ 0,0,0,0 });+ btn.Padding(mux::Thickness{+ static_cast<double>(12 + depth * 16), 4.0, 8.0, 4.0 });+ btn.MinHeight(28.0);++ muxc::StackPanel row;+ row.Orientation(muxc::Orientation::Horizontal);+ row.Spacing(8.0);++ // Type icon with color+ muxc::FontIcon icon;+ icon.FontSize(12.0);+ icon.Glyph(winrt::hstring(DBModels::SidebarItemIcon(item.type)));++ // Color by type (matching macOS)+ if (item.type == DBModels::SidebarItemType::Table)+ icon.Foreground(muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(255, 204, 128, 51))); // orange/brown+ else if (item.type == DBModels::SidebarItemType::View ||+ item.type == DBModels::SidebarItemType::MaterializedView)+ icon.Foreground(muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(255, 149, 97, 226))); // purple+ else if (item.type == DBModels::SidebarItemType::Function)+ icon.Foreground(muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(255, 56, 132, 244))); // blue+ row.Children().Append(icon);++ // Name+ muxc::TextBlock label;+ label.Text(winrt::hstring(item.title));+ label.FontSize(12.0);+ label.VerticalAlignment(mux::VerticalAlignment::Center);+ row.Children().Append(label);++ btn.Content(row);++ DBModels::SidebarItem capturedItem = item;+ btn.Click([this, capturedItem](auto&&, auto&&)+ {+ HandleItemClick(capturedItem);+ });++ // Right-click context menu for tables/views+ if (item.type == DBModels::SidebarItemType::Table ||+ item.type == DBModels::SidebarItemType::View ||+ item.type == DBModels::SidebarItemType::MaterializedView)+ {+ muxc::MenuFlyout contextMenu;+ std::wstring tblName = item.title;++ if (currentDbType_ == DBModels::DatabaseType::Redis)+ {+ // ── Redis-specific menu (matches macOS layout) ──+ // Browse Keys - opens pattern input dialog (Ctrl+F style),+ // then loads Keys table filtered by SCAN MATCH pattern+ muxc::MenuFlyoutItem browseItem;+ browseItem.Text(L"Browse Keys...");+ browseItem.Icon(muxc::FontIcon());+ browseItem.Icon().as<muxc::FontIcon>().Glyph(L"\xE721"); // Search+ browseItem.Click([this](auto&&, auto&&)+ { if (OnBrowseRedisKeys) OnBrowseRedisKeys(); });+ contextMenu.Items().Append(browseItem);++ // Copy Name (still useful — table name = "Keys")+ muxc::MenuFlyoutItem copyItem;+ copyItem.Text(L"Copy Name");+ copyItem.Icon(muxc::FontIcon());+ copyItem.Icon().as<muxc::FontIcon>().Glyph(L"\xE8C8");+ copyItem.Click([tblName](auto&&, auto&&)+ {+ winrt::Windows::ApplicationModel::DataTransfer::DataPackage dp;+ dp.SetText(winrt::hstring(tblName));+ winrt::Windows::ApplicationModel::DataTransfer::Clipboard::SetContent(dp);+ });+ contextMenu.Items().Append(copyItem);++ contextMenu.Items().Append(muxc::MenuFlyoutSeparator());++ // Refresh — re-list keys from server+ muxc::MenuFlyoutItem refreshItem;+ refreshItem.Text(L"Refresh");+ refreshItem.Icon(muxc::FontIcon());+ refreshItem.Icon().as<muxc::FontIcon>().Glyph(L"\xE72C");+ refreshItem.Click([this](auto&&, auto&&)+ { if (OnRefreshSidebar) OnRefreshSidebar(); });+ contextMenu.Items().Append(refreshItem);++ contextMenu.Items().Append(muxc::MenuFlyoutSeparator());++ // Flush Database - destructive, host shows confirmation+ muxc::MenuFlyoutItem flushItem;+ flushItem.Text(L"Flush Database...");+ flushItem.Icon(muxc::FontIcon());+ flushItem.Icon().as<muxc::FontIcon>().Glyph(L"\xE74D");+ flushItem.Click([this](auto&&, auto&&)+ { if (OnFlushRedisDb) OnFlushRedisDb(); });+ contextMenu.Items().Append(flushItem);++ btn.ContextFlyout(contextMenu);+ }+ else+ {+ // ── SQL DB menu (Postgres / MySQL / SQLite) ──+ // Open+ muxc::MenuFlyoutItem openItem;+ openItem.Text(L"Open");+ openItem.Icon(muxc::FontIcon());+ openItem.Icon().as<muxc::FontIcon>().Glyph(L"\xE8A7");+ openItem.Click([this, capturedItem](auto&&, auto&&)+ { HandleItemClick(capturedItem); });+ contextMenu.Items().Append(openItem);++ // Copy Name+ muxc::MenuFlyoutItem copyItem;+ copyItem.Text(L"Copy Name");+ copyItem.Icon(muxc::FontIcon());+ copyItem.Icon().as<muxc::FontIcon>().Glyph(L"\xE8C8");+ copyItem.Click([tblName](auto&&, auto&&)+ {+ winrt::Windows::ApplicationModel::DataTransfer::DataPackage dp;+ dp.SetText(winrt::hstring(tblName));+ winrt::Windows::ApplicationModel::DataTransfer::Clipboard::SetContent(dp);+ });+ contextMenu.Items().Append(copyItem);++ contextMenu.Items().Append(muxc::MenuFlyoutSeparator());++ // Export submenu+ muxc::MenuFlyoutSubItem exportSub;+ exportSub.Text(L"Export");+ exportSub.Icon(muxc::FontIcon());+ exportSub.Icon().as<muxc::FontIcon>().Glyph(L"\xEDE1");++ std::wstring exportName = item.title;+ std::wstring exportSchema = item.schema;++ muxc::MenuFlyoutItem csvItem;+ csvItem.Text(L"CSV");+ csvItem.Click([this, exportName, exportSchema](auto&&, auto&&)+ { if (OnExportTable) OnExportTable(exportName, exportSchema, L"csv"); });+ exportSub.Items().Append(csvItem);++ muxc::MenuFlyoutItem jsonItem;+ jsonItem.Text(L"JSON");+ jsonItem.Click([this, exportName, exportSchema](auto&&, auto&&)+ { if (OnExportTable) OnExportTable(exportName, exportSchema, L"json"); });+ exportSub.Items().Append(jsonItem);++ muxc::MenuFlyoutItem sqlItem;+ sqlItem.Text(L"SQL (INSERT)");+ sqlItem.Click([this, exportName, exportSchema](auto&&, auto&&)+ { if (OnExportTable) OnExportTable(exportName, exportSchema, L"sql"); });+ exportSub.Items().Append(sqlItem);++ contextMenu.Items().Append(exportSub);++ // Import — load CSV/JSON/SQL into THIS specific table+ muxc::MenuFlyoutItem importItem;+ importItem.Text(L"Import...");+ importItem.Icon(muxc::FontIcon());+ importItem.Icon().as<muxc::FontIcon>().Glyph(L"\xE8B5");+ importItem.Click([this, exportName, exportSchema](auto&&, auto&&)+ { if (OnImportTable) OnImportTable(exportName, exportSchema); });+ contextMenu.Items().Append(importItem);++ // Delete Table — destructive. Only offered for real tables+ // (not views) since DROP VIEW needs a different code path.+ // Host shows a confirmation dialog before actually running+ // DROP TABLE.+ if (item.type == DBModels::SidebarItemType::Table)+ {+ contextMenu.Items().Append(muxc::MenuFlyoutSeparator());++ muxc::MenuFlyoutItem deleteItem;+ deleteItem.Text(L"Delete Table...");+ deleteItem.Icon(muxc::FontIcon());+ deleteItem.Icon().as<muxc::FontIcon>().Glyph(L"\xE74D"); // trash+ deleteItem.Click([this, exportName, exportSchema](auto&&, auto&&)+ { if (OnDeleteTable) OnDeleteTable(exportName, exportSchema); });+ contextMenu.Items().Append(deleteItem);+ }++ btn.ContextFlyout(contextMenu);+ }+ }++ container.Children().Append(btn);+ }++ void SidebarPanel::RenderGroupHeader(+ muxc::StackPanel const& container,+ DBModels::SidebarItem& item,+ int depth)+ {+ muxc::Button btn;+ btn.HorizontalAlignment(mux::HorizontalAlignment::Stretch);+ btn.HorizontalContentAlignment(mux::HorizontalAlignment::Left);+ btn.Background(muxm::SolidColorBrush(winrt::Windows::UI::Colors::Transparent()));+ btn.BorderThickness(mux::Thickness{ 0,0,0,0 });+ btn.Padding(mux::Thickness{+ static_cast<double>(8 + depth * 16), 5.0, 8.0, 5.0 });+ btn.MinHeight(30.0);++ muxc::Grid row;+ muxc::ColumnDefinition c1;+ c1.Width(mux::GridLengthHelper::FromValueAndType(1, mux::GridUnitType::Star));+ muxc::ColumnDefinition c2;+ c2.Width(mux::GridLengthHelper::FromPixels(30));+ row.ColumnDefinitions().Append(c1);+ row.ColumnDefinitions().Append(c2);++ // Left: disclosure arrow + icon + title+ muxc::StackPanel left;+ left.Orientation(muxc::Orientation::Horizontal);+ left.Spacing(6.0);+ left.VerticalAlignment(mux::VerticalAlignment::Center);++ // Disclosure triangle+ muxc::FontIcon arrow;+ arrow.FontSize(8.0);+ arrow.Glyph(item.isExpanded ? L"\xE70D" : L"\xE76C"); // ChevronDown : ChevronRight+ arrow.Opacity(0.5);+ arrow.VerticalAlignment(mux::VerticalAlignment::Center);+ left.Children().Append(arrow);++ // Folder icon+ muxc::FontIcon folderIcon;+ folderIcon.FontSize(12.0);+ folderIcon.Glyph(L"\xE8B7"); // Folder+ folderIcon.Opacity(0.6);+ left.Children().Append(folderIcon);++ // Title+ muxc::TextBlock title;+ title.Text(winrt::hstring(item.title));+ title.FontSize(12.0);+ title.VerticalAlignment(mux::VerticalAlignment::Center);+ left.Children().Append(title);++ muxc::Grid::SetColumn(left, 0);+ row.Children().Append(left);++ // Right: count badge+ if (item.count > 0)+ {+ muxc::TextBlock badge;+ badge.Text(winrt::hstring(std::to_wstring(item.count)));+ badge.FontSize(10.0);+ badge.Opacity(0.4);+ badge.VerticalAlignment(mux::VerticalAlignment::Center);+ badge.HorizontalAlignment(mux::HorizontalAlignment::Right);+ muxc::Grid::SetColumn(badge, 1);+ row.Children().Append(badge);+ }++ btn.Content(row);++ // Click toggles expand/collapse+ std::wstring groupId = item.id;+ btn.Click([this, groupId](auto&&, auto&&)+ {+ ToggleGroup(groupId);+ });++ // Right-click context menu on Database/Schema groups -> Show ER Diagram+ if (item.type == DBModels::SidebarItemType::Database ||+ item.type == DBModels::SidebarItemType::Schema)+ {+ muxc::MenuFlyout groupMenu;+ muxc::MenuFlyoutItem erItem;+ erItem.Text(L"Show ER Diagram");+ erItem.Icon(muxc::FontIcon());+ erItem.Icon().as<muxc::FontIcon>().Glyph(L"\xF169");+ std::wstring groupSchema = item.title; // schema/db name+ erItem.Click([this, groupSchema](auto&&, auto&&)+ {+ if (OnShowERDiagram) OnShowERDiagram(groupSchema);+ });+ groupMenu.Items().Append(erItem);+ btn.ContextFlyout(groupMenu);+ }++ container.Children().Append(btn);+ }++ void SidebarPanel::HandleItemClick(const DBModels::SidebarItem& item)+ {+ // Track selection for delete button+ selectedItemName_ = item.title;+ selectedItemSchema_ = item.schema;++ if (item.type == DBModels::SidebarItemType::Table ||+ item.type == DBModels::SidebarItemType::View ||+ item.type == DBModels::SidebarItemType::MaterializedView ||+ item.type == DBModels::SidebarItemType::Function)+ {+ if (OnItemSelected)+ OnItemSelected(item.title, item.schema);+ }+ }+}diff --git a/windows/Gridex/SidebarPanel.h b/windows/Gridex/SidebarPanel.hnew file mode 100644index 0000000..b121214--- /dev/null+++ b/windows/Gridex/SidebarPanel.h@@ -0,0 +1,108 @@+#pragma once++#include "SidebarPanel.g.h"+#include "Models/SidebarItem.h"+#include "Models/DatabaseType.h"+#include <functional>+#include <vector>++namespace winrt::Gridex::implementation+{+ struct SidebarPanel : SidebarPanelT<SidebarPanel>+ {+ SidebarPanel();++ void SetItems(const std::vector<DBModels::SidebarItem>& items);++ // Inform the sidebar of the active connection's DB type so it can+ // render type-specific context menus (e.g. Redis Browse Keys vs+ // SQL Open/Export/Import).+ void SetDatabaseType(DBModels::DatabaseType type) { currentDbType_ = type; }++ // Callback invoked when user clicks a table/view/function+ std::function<void(const std::wstring& name, const std::wstring& schema)> OnItemSelected;++ // Callback invoked when schema picker changes+ std::function<void(const std::wstring& schema)> OnSchemaChanged;++ // Callbacks for add/delete table buttons+ std::function<void()> OnAddTable;+ std::function<void(const std::wstring& tableName, const std::wstring& schema)> OnDeleteTable;++ // Callback for export table (tableName, schema, format: "csv"/"json"/"sql")+ std::function<void(const std::wstring& tableName, const std::wstring& schema,+ const std::wstring& format)> OnExportTable;++ // Callback for import data into a specific table (right-click target)+ std::function<void(const std::wstring& tableName,+ const std::wstring& schema)> OnImportTable;++ // Callback for "Show ER Diagram" on a Database/Schema group+ std::function<void(const std::wstring& schema)> OnShowERDiagram;++ // Callback for Redis-only "Flush Database" — adapter issues FLUSHDB+ std::function<void()> OnFlushRedisDb;++ // Callback for Redis-only "Refresh Keys" — reload sidebar listing+ std::function<void()> OnRefreshSidebar;++ // Callback for Redis-only "Browse Keys" — host shows pattern input+ // dialog and triggers a filtered fetchRows+ std::function<void()> OnBrowseRedisKeys;++ // Get currently selected sidebar item name (for delete)+ std::wstring GetSelectedItemName() const { return selectedItemName_; }+ std::wstring GetSelectedItemSchema() const { return selectedItemSchema_; }++ // Set query history entries for History tab+ void SetHistory(const std::vector<std::pair<std::wstring, std::wstring>>& entries);++ // Callback when history item clicked (sql)+ std::function<void(const std::wstring& sql)> OnHistoryItemClicked;++ // Populate schema picker ComboBox from adapter.listSchemas()+ void SetSchemas(const std::vector<std::wstring>& schemas);++ // Tab clicks+ void ItemsTab_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);+ void QueriesTab_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);+ void HistoryTab_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);+ void SearchBox_TextChanged(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);++ private:+ std::vector<DBModels::SidebarItem> items_;+ std::wstring searchQuery_;+ bool suppressSchemaEvent_ = false;+ std::wstring selectedItemName_;+ std::wstring selectedItemSchema_;+ DBModels::DatabaseType currentDbType_ = DBModels::DatabaseType::PostgreSQL;++ void RenderTree();+ void RenderItem(+ winrt::Microsoft::UI::Xaml::Controls::StackPanel const& container,+ const DBModels::SidebarItem& item,+ int depth);+ void RenderGroupHeader(+ winrt::Microsoft::UI::Xaml::Controls::StackPanel const& container,+ DBModels::SidebarItem& item,+ int depth);+ void HandleItemClick(const DBModels::SidebarItem& item);+ void ToggleGroup(const std::wstring& groupId);+ bool MatchesSearch(const DBModels::SidebarItem& item) const;+ };+}++namespace winrt::Gridex::factory_implementation+{+ struct SidebarPanel : SidebarPanelT<SidebarPanel, implementation::SidebarPanel>+ {+ };+}diff --git a/windows/Gridex/SidebarPanel.idl b/windows/Gridex/SidebarPanel.idlnew file mode 100644index 0000000..8164d39--- /dev/null+++ b/windows/Gridex/SidebarPanel.idl@@ -0,0 +1,8 @@+namespace Gridex+{+ [default_interface]+ runtimeclass SidebarPanel : Microsoft.UI.Xaml.Controls.UserControl+ {+ SidebarPanel();+ }+}diff --git a/windows/Gridex/SidebarPanel.xaml b/windows/Gridex/SidebarPanel.xamlnew file mode 100644index 0000000..38c6c31--- /dev/null+++ b/windows/Gridex/SidebarPanel.xaml@@ -0,0 +1,105 @@+<UserControl+ x:Class="Gridex.SidebarPanel"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:local="using:Gridex">++ <Grid Background="{ThemeResource LayerFillColorDefaultBrush}">+ <Grid.RowDefinitions>+ <RowDefinition Height="Auto" />+ <RowDefinition Height="Auto" />+ <RowDefinition Height="Auto" />+ <RowDefinition Height="*" />+ <RowDefinition Height="Auto" />+ </Grid.RowDefinitions>++ <!-- Tab bar: Items | Queries | History -->+ <Grid Grid.Row="0" Padding="8,6">+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="Auto" />+ </Grid.ColumnDefinitions>+ <ToggleButton x:Name="ItemsTab" Grid.Column="0"+ IsChecked="True" Padding="6,4"+ Background="Transparent" BorderThickness="0"+ Click="ItemsTab_Click"+ ToolTipService.ToolTip="Database Objects">+ <FontIcon Glyph="" FontSize="13" />+ </ToggleButton>+ <ToggleButton x:Name="QueriesTab" Grid.Column="1"+ Padding="6,4"+ Background="Transparent" BorderThickness="0"+ Click="QueriesTab_Click"+ ToolTipService.ToolTip="Saved Queries">+ <FontIcon Glyph="" FontSize="13" />+ </ToggleButton>+ <ToggleButton x:Name="HistoryTab" Grid.Column="2"+ Padding="6,4"+ Background="Transparent" BorderThickness="0"+ Click="HistoryTab_Click"+ ToolTipService.ToolTip="Query History">+ <FontIcon Glyph="" FontSize="13" />+ </ToggleButton>+ </Grid>++ <!-- Search box -->+ <TextBox Grid.Row="1" x:Name="SearchBox"+ PlaceholderText="Search for item..."+ Margin="8,0,8,6" Padding="8,6"+ FontSize="12"+ TextChanged="SearchBox_TextChanged" />++ <!-- Separator -->+ <Border Grid.Row="2" Height="1"+ Background="{ThemeResource DividerStrokeColorDefaultBrush}" />++ <!-- Content area: Items / Queries / History -->+ <Grid Grid.Row="3">+ <!-- Items: Tree of tables/views/functions -->+ <ScrollViewer x:Name="ItemsContent" VerticalScrollBarVisibility="Auto">+ <StackPanel x:Name="TreeContainer" Spacing="0" Padding="0,4" />+ </ScrollViewer>++ <!-- Queries: Saved queries list (placeholder for now) -->+ <ScrollViewer x:Name="QueriesContent" Visibility="Collapsed"+ VerticalScrollBarVisibility="Auto">+ <StackPanel x:Name="QueriesContainer" Spacing="0" Padding="0,4" />+ </ScrollViewer>++ <!-- History: Query log entries -->+ <ScrollViewer x:Name="HistoryContent" Visibility="Collapsed"+ VerticalScrollBarVisibility="Auto">+ <StackPanel x:Name="HistoryContainer" Spacing="0" Padding="0,4" />+ </ScrollViewer>+ </Grid>++ <!-- Bottom bar: Add + Delete + Schema picker -->+ <Grid Grid.Row="4" Padding="8,4"+ BorderBrush="{ThemeResource DividerStrokeColorDefaultBrush}"+ BorderThickness="0,1,0,0">+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="*" />+ <ColumnDefinition Width="Auto" />+ </Grid.ColumnDefinitions>+ <Button x:Name="AddItemBtn" Grid.Column="0" Width="28" Height="28" Padding="0"+ Background="Transparent" BorderThickness="0"+ ToolTipService.ToolTip="Create Table">+ <FontIcon Glyph="" FontSize="12" />+ </Button>+ <Button x:Name="DeleteItemBtn" Grid.Column="1" Width="28" Height="28" Padding="0"+ Background="Transparent" BorderThickness="0"+ ToolTipService.ToolTip="Drop Table">+ <FontIcon Glyph="" FontSize="11"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ </Button>+ <ComboBox x:Name="SchemaPicker" Grid.Column="3"+ MinWidth="90" Padding="6,2"+ FontSize="11" SelectedIndex="0">+ <ComboBoxItem Content="public" />+ </ComboBox>+ </Grid>+ </Grid>+</UserControl>diff --git a/windows/Gridex/StatusBarControl.cpp b/windows/Gridex/StatusBarControl.cppnew file mode 100644index 0000000..129ee93--- /dev/null+++ b/windows/Gridex/StatusBarControl.cpp@@ -0,0 +1,58 @@+#include "pch.h"+#include "xaml-includes.h"+#include "StatusBarControl.h"+#include <winrt/Microsoft.UI.Xaml.Controls.h>+#if __has_include("StatusBarControl.g.cpp")+#include "StatusBarControl.g.cpp"+#endif++namespace winrt::Gridex::implementation+{+ namespace mux = winrt::Microsoft::UI::Xaml;+ namespace muxc = winrt::Microsoft::UI::Xaml::Controls;++ StatusBarControl::StatusBarControl()+ {+ InitializeComponent();+ }++ void StatusBarControl::SetStatus(+ const std::wstring& connection,+ const std::wstring& schema,+ int rowCount,+ double queryTimeMs,+ double renderTimeMs)+ {+ connection_ = connection;+ schema_ = schema;+ rowCount_ = rowCount;+ queryTimeMs_ = queryTimeMs;+ renderTimeMs_ = renderTimeMs;++ ConnectionText().Text(winrt::hstring(connection_));+ SchemaText().Text(winrt::hstring(schema_));++ std::wstring rowStr = std::to_wstring(rowCount_) + L" rows";+ RowCountText().Text(winrt::hstring(rowStr));++ // "Exec Nms · Render Nms" — two-way split so a slow UI build on a+ // wide table does not get mis-attributed to a slow SQL query.+ std::wstring timeStr =+ L"Exec " + std::to_wstring(static_cast<int>(queryTimeMs_)) + L"ms" ++ L" \x00B7 " ++ L"Render " + std::to_wstring(static_cast<int>(renderTimeMs_)) + L"ms";+ QueryTimeText().Text(winrt::hstring(timeStr));++ // Tooltip clarifies what each number actually measures -- users+ // otherwise read "Exec" as pure server execution when it really+ // includes the full driver round-trip and result transfer.+ muxc::ToolTip tip;+ tip.Content(winrt::box_value(winrt::hstring(+ L"Exec = driver blocking call: send SQL, server execution, "+ L"receive all result bytes. Dominated by network transfer on "+ L"remote databases with wide rows.\n"+ L"Render = UI cost to build the visual grid (StackPanel + "+ L"TextBlock per cell).")));+ muxc::ToolTipService::SetToolTip(QueryTimeText(), tip);+ }+}diff --git a/windows/Gridex/StatusBarControl.h b/windows/Gridex/StatusBarControl.hnew file mode 100644index 0000000..76c7e73--- /dev/null+++ b/windows/Gridex/StatusBarControl.h@@ -0,0 +1,40 @@+#pragma once++#include "StatusBarControl.g.h"+#include <string>++namespace winrt::Gridex::implementation+{+ struct StatusBarControl : StatusBarControlT<StatusBarControl>+ {+ StatusBarControl();++ // Update all status fields at once. Two separate timings are+ // displayed so wide-table slowness is attributed to the right+ // layer instead of lumped under a single misleading number:+ // queryTimeMs = driver blocking call wall-clock (Exec) —+ // includes SQL send, server execution, and+ // full result transfer back to the client.+ // renderTimeMs = UI grid build time (Render)+ void SetStatus(+ const std::wstring& connection,+ const std::wstring& schema,+ int rowCount,+ double queryTimeMs,+ double renderTimeMs);++ private:+ std::wstring connection_;+ std::wstring schema_;+ int rowCount_ = 0;+ double queryTimeMs_ = 0.0;+ double renderTimeMs_ = 0.0;+ };+}++namespace winrt::Gridex::factory_implementation+{+ struct StatusBarControl : StatusBarControlT<StatusBarControl, implementation::StatusBarControl>+ {+ };+}diff --git a/windows/Gridex/StatusBarControl.idl b/windows/Gridex/StatusBarControl.idlnew file mode 100644index 0000000..286dd71--- /dev/null+++ b/windows/Gridex/StatusBarControl.idl@@ -0,0 +1,8 @@+namespace Gridex+{+ [default_interface]+ runtimeclass StatusBarControl : Microsoft.UI.Xaml.Controls.UserControl+ {+ StatusBarControl();+ }+}diff --git a/windows/Gridex/StatusBarControl.xaml b/windows/Gridex/StatusBarControl.xamlnew file mode 100644index 0000000..d3505d6--- /dev/null+++ b/windows/Gridex/StatusBarControl.xaml@@ -0,0 +1,47 @@+<UserControl+ x:Class="Gridex.StatusBarControl"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:local="using:Gridex">++ <Grid Padding="12,4"+ Background="{ThemeResource LayerFillColorDefaultBrush}"+ BorderBrush="{ThemeResource DividerStrokeColorDefaultBrush}"+ BorderThickness="0,1,0,0"+ MinHeight="28">+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="*" />+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="Auto" />+ </Grid.ColumnDefinitions>++ <!-- Connection info -->+ <TextBlock Grid.Column="0" x:Name="ConnectionText"+ FontSize="11" VerticalAlignment="Center"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />++ <Border Grid.Column="1" Width="1" Height="12" Margin="8,0"+ Background="{ThemeResource DividerStrokeColorDefaultBrush}" />++ <!-- Schema -->+ <TextBlock Grid.Column="2" x:Name="SchemaText"+ FontSize="11" VerticalAlignment="Center"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />++ <!-- Row count -->+ <TextBlock Grid.Column="4" x:Name="RowCountText"+ FontSize="11" VerticalAlignment="Center"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />++ <Border Grid.Column="5" Width="1" Height="12" Margin="8,0"+ Background="{ThemeResource DividerStrokeColorDefaultBrush}" />++ <!-- Query time -->+ <TextBlock Grid.Column="5" x:Name="QueryTimeText"+ FontSize="11" VerticalAlignment="Center" Margin="8,0,0,0"+ Foreground="{ThemeResource TextFillColorTertiaryBrush}" />+ </Grid>+</UserControl>diff --git a/windows/Gridex/StructureView.cpp b/windows/Gridex/StructureView.cppnew file mode 100644index 0000000..c5a7fac--- /dev/null+++ b/windows/Gridex/StructureView.cpp@@ -0,0 +1,513 @@+#include "pch.h"+#include "xaml-includes.h"+#include <winrt/Windows.UI.Text.h>+#include "StructureView.h"+#if __has_include("StructureView.g.cpp")+#include "StructureView.g.cpp"+#endif++namespace winrt::Gridex::implementation+{+ namespace mux = winrt::Microsoft::UI::Xaml;+ namespace muxc = winrt::Microsoft::UI::Xaml::Controls;+ namespace muxm = winrt::Microsoft::UI::Xaml::Media;++ StructureView::StructureView()+ {+ InitializeComponent();++ this->Loaded([this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ AddColumnBtn().Click(+ [this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ // Add new column with defaults+ DBModels::ColumnInfo newCol;+ newCol.name = L"new_column";+ newCol.dataType = L"text";+ newCol.nullable = true;+ newCol.ordinalPosition = static_cast<int>(columns_.size()) + 1;+ columns_.push_back(newCol);++ AlterOp op;+ op.type = AlterOp::AddColumn;+ op.column = L"new_column";+ op.newValue = L"text";+ TrackAlter(op);+ Rebuild();+ });++ ApplyAlterBtn().Click(+ [this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ if (pendingAlters_.empty()) return;+ auto sqls = GenerateAlterSQL();+ if (OnApplyAlter && !sqls.empty())+ OnApplyAlter(sqls);+ pendingAlters_.clear();+ UpdatePendingUI();+ });+ });+ }++ void StructureView::SetTableContext(const std::wstring& table, const std::wstring& schema,+ DBModels::DatabaseType dbType)+ {+ tableName_ = table;+ schemaName_ = schema;+ dbType_ = dbType;+ }++ void StructureView::SetData(+ const std::vector<DBModels::ColumnInfo>& columns,+ const std::vector<DBModels::IndexInfo>& indexes,+ const std::vector<DBModels::ForeignKeyInfo>& foreignKeys,+ const std::vector<DBModels::ConstraintInfo>& constraints)+ {+ columns_ = columns;+ indexes_ = indexes;+ foreignKeys_ = foreignKeys;+ constraints_ = constraints;+ pendingAlters_.clear();+ UpdatePendingUI();+ Rebuild();+ }++ void StructureView::Rebuild()+ {+ StructureContainer().Children().Clear();++ // Columns section+ AddSectionHeader(StructureContainer(), L"Columns");+ for (int i = 0; i < static_cast<int>(columns_.size()); i++)+ AddColumnRow(StructureContainer(), columns_[i], i, i % 2 == 1);++ // Indexes section+ if (!indexes_.empty())+ {+ AddSectionHeader(StructureContainer(), L"Indexes");+ for (int i = 0; i < static_cast<int>(indexes_.size()); i++)+ AddIndexRow(StructureContainer(), indexes_[i], i % 2 == 1);+ }+ }++ void StructureView::AddSectionHeader(+ muxc::StackPanel const& container,+ const std::wstring& title)+ {+ muxc::TextBlock hdr;+ hdr.Text(winrt::hstring(title));+ hdr.FontSize(11.0);+ hdr.FontWeight(winrt::Windows::UI::Text::FontWeights::SemiBold());+ hdr.Padding(mux::Thickness{ 12.0, 10.0, 8.0, 4.0 });+ hdr.Opacity(0.6);+ container.Children().Append(hdr);+ }++ void StructureView::AddColumnRow(+ muxc::StackPanel const& container,+ const DBModels::ColumnInfo& col,+ int colIndex,+ bool isAlternate)+ {+ muxc::Grid row;+ row.MinHeight(32.0);+ row.Padding(mux::Thickness{ 12.0, 4.0, 8.0, 4.0 });++ auto bgColor = isAlternate+ ? winrt::Windows::UI::ColorHelper::FromArgb(8, 128, 128, 128)+ : winrt::Windows::UI::Colors::Transparent();+ row.Background(muxm::SolidColorBrush(bgColor));++ // Columns: name | type | nullable | badges | delete btn+ muxc::ColumnDefinition c1; c1.Width(mux::GridLengthHelper::FromPixels(150));+ muxc::ColumnDefinition c2; c2.Width(mux::GridLengthHelper::FromPixels(120));+ muxc::ColumnDefinition c3; c3.Width(mux::GridLengthHelper::FromPixels(70));+ muxc::ColumnDefinition c4; c4.Width(mux::GridLengthHelper::FromValueAndType(1, mux::GridUnitType::Star));+ muxc::ColumnDefinition c5; c5.Width(mux::GridLengthHelper::FromPixels(28));+ row.ColumnDefinitions().Append(c1);+ row.ColumnDefinitions().Append(c2);+ row.ColumnDefinitions().Append(c3);+ row.ColumnDefinitions().Append(c4);+ row.ColumnDefinitions().Append(c5);++ // Name — editable TextBox+ muxc::TextBox nameBox;+ nameBox.Text(winrt::hstring(col.name));+ nameBox.FontSize(12.0);+ nameBox.BorderThickness(mux::Thickness{ 0,0,0,0 });+ nameBox.Background(muxm::SolidColorBrush(winrt::Windows::UI::Colors::Transparent()));+ nameBox.Padding(mux::Thickness{ 2,0,2,0 });+ nameBox.VerticalAlignment(mux::VerticalAlignment::Center);+ if (col.isPrimaryKey)+ nameBox.FontWeight(winrt::Windows::UI::Text::FontWeights::SemiBold());+ muxc::Grid::SetColumn(nameBox, 0);++ std::wstring origName = col.name;+ nameBox.LostFocus([this, colIndex, origName]+ (winrt::Windows::Foundation::IInspectable const& sender, mux::RoutedEventArgs const&)+ {+ auto tb = sender.try_as<muxc::TextBox>();+ if (!tb) return;+ std::wstring newName(tb.Text());+ if (newName != origName && !newName.empty())+ {+ columns_[colIndex].name = newName;+ AlterOp op;+ op.type = AlterOp::RenameColumn;+ op.column = origName;+ op.newValue = newName;+ TrackAlter(op);+ }+ });+ row.Children().Append(nameBox);++ // Type — ComboBox with DB-specific types+ muxc::ComboBox typeCombo;+ typeCombo.FontSize(11.0);+ typeCombo.MinWidth(0.0);+ typeCombo.MinHeight(0.0);+ typeCombo.Padding(mux::Thickness{ 4,2,4,2 });+ typeCombo.BorderThickness(mux::Thickness{ 0,0,0,0 });+ typeCombo.Background(muxm::SolidColorBrush(winrt::Windows::UI::Colors::Transparent()));+ typeCombo.VerticalAlignment(mux::VerticalAlignment::Center);+ typeCombo.IsEditable(true); // Allow custom types not in list+ muxc::Grid::SetColumn(typeCombo, 1);++ auto typeList = DBModels::ColumnTypesForDB(dbType_);+ int selectedIdx = -1;+ for (int t = 0; t < static_cast<int>(typeList.size()); t++)+ {+ muxc::ComboBoxItem item;+ item.Content(winrt::box_value(winrt::hstring(typeList[t])));+ item.FontSize(11.0);+ typeCombo.Items().Append(item);+ // Match current type (case-insensitive prefix match)+ std::wstring lower1 = col.dataType, lower2 = typeList[t];+ std::transform(lower1.begin(), lower1.end(), lower1.begin(), ::towlower);+ std::transform(lower2.begin(), lower2.end(), lower2.begin(), ::towlower);+ if (lower1 == lower2 || lower1.find(lower2) == 0)+ selectedIdx = t;+ }+ if (selectedIdx >= 0)+ typeCombo.SelectedIndex(selectedIdx);+ else+ typeCombo.Text(winrt::hstring(col.dataType)); // custom type not in list++ std::wstring origType = col.dataType;+ std::wstring colName = col.name;+ typeCombo.SelectionChanged(+ [this, colIndex, colName, origType](winrt::Windows::Foundation::IInspectable const& sender,+ muxc::SelectionChangedEventArgs const&)+ {+ auto combo = sender.try_as<muxc::ComboBox>();+ if (!combo) return;+ auto selected = combo.SelectedItem();+ if (!selected) return;+ auto item = selected.try_as<muxc::ComboBoxItem>();+ if (!item) return;+ std::wstring newType(winrt::unbox_value<winrt::hstring>(item.Content()));+ if (newType != origType && !newType.empty() && colIndex < static_cast<int>(columns_.size()))+ {+ columns_[colIndex].dataType = newType;+ AlterOp op;+ op.type = AlterOp::AlterType;+ op.column = colName;+ op.oldValue = origType;+ op.newValue = newType;+ TrackAlter(op);+ }+ });+ row.Children().Append(typeCombo);++ // Nullable — toggle+ muxc::ToggleSwitch nullToggle;+ nullToggle.IsOn(col.nullable);+ nullToggle.OnContent(winrt::box_value(winrt::hstring(L"null")));+ nullToggle.OffContent(winrt::box_value(winrt::hstring(L"req")));+ nullToggle.MinWidth(0.0);+ nullToggle.MinHeight(0.0);+ nullToggle.VerticalAlignment(mux::VerticalAlignment::Center);+ muxc::Grid::SetColumn(nullToggle, 2);++ nullToggle.Toggled([this, colIndex, colName]+ (winrt::Windows::Foundation::IInspectable const& sender, mux::RoutedEventArgs const&)+ {+ auto ts = sender.try_as<muxc::ToggleSwitch>();+ if (!ts) return;+ bool newNullable = ts.IsOn();+ columns_[colIndex].nullable = newNullable;+ AlterOp op;+ op.type = AlterOp::AlterNullable;+ op.column = colName;+ op.newValue = newNullable ? L"NULL" : L"NOT NULL";+ TrackAlter(op);+ });+ row.Children().Append(nullToggle);++ // Badges (PK / FK) — read-only+ muxc::StackPanel badges;+ badges.Orientation(muxc::Orientation::Horizontal);+ badges.Spacing(4.0);+ badges.VerticalAlignment(mux::VerticalAlignment::Center);++ if (col.isPrimaryKey)+ {+ muxc::Border pkBadge;+ pkBadge.CornerRadius(mux::CornerRadiusHelper::FromUniformRadius(3));+ pkBadge.Padding(mux::Thickness{ 4.0, 1.0, 4.0, 1.0 });+ pkBadge.Background(muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(40, 0, 120, 212)));+ muxc::TextBlock pkText;+ pkText.Text(L"PK");+ pkText.FontSize(9.0);+ pkBadge.Child(pkText);+ badges.Children().Append(pkBadge);+ }+ if (col.isForeignKey)+ {+ muxc::Border fkBadge;+ fkBadge.CornerRadius(mux::CornerRadiusHelper::FromUniformRadius(3));+ fkBadge.Padding(mux::Thickness{ 4.0, 1.0, 4.0, 1.0 });+ fkBadge.Background(muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(40, 99, 153, 34)));+ muxc::TextBlock fkText;+ fkText.Text(L"FK");+ fkText.FontSize(9.0);+ fkBadge.Child(fkText);+ badges.Children().Append(fkBadge);+ }+ muxc::Grid::SetColumn(badges, 3);+ row.Children().Append(badges);++ // Delete column button+ muxc::Button delBtn;+ delBtn.Width(24.0);+ delBtn.Height(24.0);+ delBtn.Padding(mux::Thickness{ 0,0,0,0 });+ delBtn.Background(muxm::SolidColorBrush(winrt::Windows::UI::Colors::Transparent()));+ delBtn.BorderThickness(mux::Thickness{ 0,0,0,0 });+ delBtn.Opacity(0.4);+ delBtn.VerticalAlignment(mux::VerticalAlignment::Center);+ muxc::FontIcon delIcon;+ delIcon.Glyph(L"\xE74D");+ delIcon.FontSize(10.0);+ delBtn.Content(delIcon);+ muxc::Grid::SetColumn(delBtn, 4);++ // Don't allow deleting PK columns+ if (!col.isPrimaryKey)+ {+ delBtn.Click([this, colIndex, colName]+ (winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ if (colIndex < static_cast<int>(columns_.size()))+ {+ AlterOp op;+ op.type = AlterOp::DropColumn;+ op.column = colName;+ TrackAlter(op);+ columns_.erase(columns_.begin() + colIndex);+ Rebuild();+ }+ });+ }+ else+ {+ delBtn.IsEnabled(false);+ delBtn.Opacity(0.1);+ }+ row.Children().Append(delBtn);++ container.Children().Append(row);+ }++ void StructureView::AddIndexRow(+ muxc::StackPanel const& container,+ const DBModels::IndexInfo& idx,+ bool isAlternate)+ {+ muxc::Grid row;+ row.MinHeight(28.0);+ row.Padding(mux::Thickness{ 12.0, 4.0, 8.0, 4.0 });++ auto bgColor = isAlternate+ ? winrt::Windows::UI::ColorHelper::FromArgb(8, 128, 128, 128)+ : winrt::Windows::UI::Colors::Transparent();+ row.Background(muxm::SolidColorBrush(bgColor));++ muxc::ColumnDefinition c1; c1.Width(mux::GridLengthHelper::FromPixels(200));+ muxc::ColumnDefinition c2; c2.Width(mux::GridLengthHelper::FromPixels(120));+ muxc::ColumnDefinition c3; c3.Width(mux::GridLengthHelper::FromValueAndType(1, mux::GridUnitType::Star));+ row.ColumnDefinitions().Append(c1);+ row.ColumnDefinitions().Append(c2);+ row.ColumnDefinitions().Append(c3);++ muxc::TextBlock nameText;+ nameText.Text(winrt::hstring(idx.name));+ nameText.FontSize(12.0);+ nameText.VerticalAlignment(mux::VerticalAlignment::Center);+ nameText.TextTrimming(mux::TextTrimming::CharacterEllipsis);+ muxc::Grid::SetColumn(nameText, 0);+ row.Children().Append(nameText);++ muxc::TextBlock colText;+ colText.Text(winrt::hstring(idx.columns));+ colText.FontSize(11.0);+ colText.Opacity(0.7);+ colText.VerticalAlignment(mux::VerticalAlignment::Center);+ muxc::Grid::SetColumn(colText, 1);+ row.Children().Append(colText);++ std::wstring flags;+ if (idx.isPrimary) flags += L"PRIMARY ";+ if (idx.isUnique) flags += L"UNIQUE ";+ flags += idx.algorithm;++ muxc::TextBlock flagText;+ flagText.Text(winrt::hstring(flags));+ flagText.FontSize(10.0);+ flagText.Opacity(0.5);+ flagText.VerticalAlignment(mux::VerticalAlignment::Center);+ muxc::Grid::SetColumn(flagText, 2);+ row.Children().Append(flagText);++ container.Children().Append(row);+ }++ // ── Alter tracking ─────────────────────────────────++ void StructureView::TrackAlter(const AlterOp& op)+ {+ // If renaming/retyping a column that was just added in this+ // batch (still pending, not yet on the server), fold the+ // change into the original AddColumn op instead of emitting+ // a separate ALTER/RENAME that references a column the server+ // doesn't know about yet.+ if (op.type == AlterOp::RenameColumn ||+ op.type == AlterOp::AlterType ||+ op.type == AlterOp::AlterNullable ||+ op.type == AlterOp::AlterDefault)+ {+ for (auto& pending : pendingAlters_)+ {+ if (pending.type == AlterOp::AddColumn && pending.column == op.column)+ {+ if (op.type == AlterOp::RenameColumn)+ pending.column = op.newValue; // use new name in ADD COLUMN+ else if (op.type == AlterOp::AlterType)+ pending.newValue = op.newValue; // use new type in ADD COLUMN+ // AlterNullable / AlterDefault on a pending ADD are+ // edge cases — skip for now (ADD COLUMN doesn't carry+ // NOT NULL / DEFAULT in our SQL template).+ UpdatePendingUI();+ return;+ }+ }+ }++ pendingAlters_.push_back(op);+ UpdatePendingUI();+ }++ void StructureView::UpdatePendingUI()+ {+ int count = static_cast<int>(pendingAlters_.size());+ if (count > 0)+ {+ PendingAlterText().Text(winrt::hstring(std::to_wstring(count) + L" change(s)"));+ ApplyAlterBtn().Visibility(mux::Visibility::Visible);+ }+ else+ {+ PendingAlterText().Text(L"");+ ApplyAlterBtn().Visibility(mux::Visibility::Collapsed);+ }+ }++ std::vector<std::wstring> StructureView::GenerateAlterSQL() const+ {+ std::vector<std::wstring> sqls;+ const bool isMSSQL = (dbType_ == DBModels::DatabaseType::MSSQLServer);+ const bool isMySQL = (dbType_ == DBModels::DatabaseType::MySQL);++ // Dialect-aware table + column quoting+ // MSSQL: [schema].[table], [column]+ // MySQL: `schema`.`table`, `column`+ // PostgreSQL/SQLite: "schema"."table", "column"+ std::wstring tbl;+ if (isMSSQL)+ tbl = L"[" + schemaName_ + L"].[" + tableName_ + L"]";+ else if (isMySQL)+ tbl = L"`" + schemaName_ + L"`.`" + tableName_ + L"`";+ else+ tbl = L"\"" + schemaName_ + L"\".\"" + tableName_ + L"\"";++ auto qCol = [&](const std::wstring& c) -> std::wstring {+ if (isMSSQL) return L"[" + c + L"]";+ if (isMySQL) return L"`" + c + L"`";+ return L"\"" + c + L"\"";+ };++ for (auto& op : pendingAlters_)+ {+ std::wstring sql;+ switch (op.type)+ {+ case AlterOp::AddColumn:+ // MSSQL: ALTER TABLE [t] ADD [col] type (no COLUMN keyword)+ // MySQL: ALTER TABLE `t` ADD COLUMN `col` type+ // PG: ALTER TABLE "t" ADD COLUMN "col" type+ if (isMSSQL)+ sql = L"ALTER TABLE " + tbl + L" ADD " + qCol(op.column) + L" " + op.newValue;+ else+ sql = L"ALTER TABLE " + tbl + L" ADD COLUMN " + qCol(op.column) + L" " + op.newValue;+ break;++ case AlterOp::DropColumn:+ sql = L"ALTER TABLE " + tbl + L" DROP COLUMN " + qCol(op.column);+ break;++ case AlterOp::AlterType:+ if (isMSSQL)+ // MSSQL: ALTER TABLE [t] ALTER COLUMN [col] newtype+ sql = L"ALTER TABLE " + tbl + L" ALTER COLUMN " + qCol(op.column) + L" " + op.newValue;+ else if (isMySQL)+ sql = L"ALTER TABLE " + tbl + L" MODIFY COLUMN " + qCol(op.column) + L" " + op.newValue;+ else+ sql = L"ALTER TABLE " + tbl + L" ALTER COLUMN " + qCol(op.column) + L" TYPE " + op.newValue;+ break;++ case AlterOp::AlterNullable:+ if (isMSSQL)+ {+ // MSSQL requires full column definition for ALTER COLUMN+ // Just skip for now — complex to reconstruct full type+null+ }+ else if (op.newValue == L"NOT NULL")+ sql = L"ALTER TABLE " + tbl + L" ALTER COLUMN " + qCol(op.column) + L" SET NOT NULL";+ else+ sql = L"ALTER TABLE " + tbl + L" ALTER COLUMN " + qCol(op.column) + L" DROP NOT NULL";+ break;++ case AlterOp::AlterDefault:+ if (isMSSQL)+ // MSSQL uses ADD DEFAULT ... FOR+ sql = L"ALTER TABLE " + tbl + L" ADD DEFAULT " + op.newValue + L" FOR " + qCol(op.column);+ else+ sql = L"ALTER TABLE " + tbl + L" ALTER COLUMN " + qCol(op.column) + L" SET DEFAULT " + op.newValue;+ break;++ case AlterOp::RenameColumn:+ if (isMSSQL)+ // MSSQL uses sp_rename+ sql = L"EXEC sp_rename '" + schemaName_ + L"." + tableName_ + L"." + op.column + L"', '" + op.newValue + L"', 'COLUMN'";+ else+ sql = L"ALTER TABLE " + tbl + L" RENAME COLUMN " + qCol(op.column) + L" TO " + qCol(op.newValue);+ break;+ }+ if (!sql.empty()) sqls.push_back(sql);+ }+ return sqls;+ }+}diff --git a/windows/Gridex/StructureView.h b/windows/Gridex/StructureView.hnew file mode 100644index 0000000..3b7e95d--- /dev/null+++ b/windows/Gridex/StructureView.h@@ -0,0 +1,72 @@+#pragma once++#include "StructureView.g.h"+#include "Models/ColumnInfo.h"+#include "Models/DatabaseType.h"+#include <vector>+#include <functional>++namespace winrt::Gridex::implementation+{+ // Pending ALTER operations+ struct AlterOp+ {+ enum Type { AddColumn, DropColumn, AlterType, AlterNullable, AlterDefault, RenameColumn };+ Type type;+ std::wstring column;+ std::wstring oldValue;+ std::wstring newValue;+ };++ struct StructureView : StructureViewT<StructureView>+ {+ StructureView();++ void SetData(+ const std::vector<DBModels::ColumnInfo>& columns,+ const std::vector<DBModels::IndexInfo>& indexes,+ const std::vector<DBModels::ForeignKeyInfo>& foreignKeys,+ const std::vector<DBModels::ConstraintInfo>& constraints);++ // Callback: execute ALTER SQL (table, schema, sql statements)+ std::function<void(const std::vector<std::wstring>& sqls)> OnApplyAlter;++ // Set current table/schema/dbtype for ALTER generation+ void SetTableContext(const std::wstring& table, const std::wstring& schema,+ DBModels::DatabaseType dbType = DBModels::DatabaseType::PostgreSQL);++ private:+ std::vector<DBModels::ColumnInfo> columns_;+ std::vector<DBModels::IndexInfo> indexes_;+ std::vector<DBModels::ForeignKeyInfo> foreignKeys_;+ std::vector<DBModels::ConstraintInfo> constraints_;+ std::vector<AlterOp> pendingAlters_;+ std::wstring tableName_;+ std::wstring schemaName_;+ DBModels::DatabaseType dbType_ = DBModels::DatabaseType::PostgreSQL;++ void Rebuild();+ void AddSectionHeader(+ winrt::Microsoft::UI::Xaml::Controls::StackPanel const& container,+ const std::wstring& title);+ void AddColumnRow(+ winrt::Microsoft::UI::Xaml::Controls::StackPanel const& container,+ const DBModels::ColumnInfo& col,+ int colIndex,+ bool isAlternate);+ void AddIndexRow(+ winrt::Microsoft::UI::Xaml::Controls::StackPanel const& container,+ const DBModels::IndexInfo& idx,+ bool isAlternate);+ void TrackAlter(const AlterOp& op);+ void UpdatePendingUI();+ std::vector<std::wstring> GenerateAlterSQL() const;+ };+}++namespace winrt::Gridex::factory_implementation+{+ struct StructureView : StructureViewT<StructureView, implementation::StructureView>+ {+ };+}diff --git a/windows/Gridex/StructureView.idl b/windows/Gridex/StructureView.idlnew file mode 100644index 0000000..18e631c--- /dev/null+++ b/windows/Gridex/StructureView.idl@@ -0,0 +1,8 @@+namespace Gridex+{+ [default_interface]+ runtimeclass StructureView : Microsoft.UI.Xaml.Controls.UserControl+ {+ StructureView();+ }+}diff --git a/windows/Gridex/StructureView.xaml b/windows/Gridex/StructureView.xamlnew file mode 100644index 0000000..656533a--- /dev/null+++ b/windows/Gridex/StructureView.xaml@@ -0,0 +1,46 @@+<UserControl+ x:Class="Gridex.StructureView"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:local="using:Gridex">++ <Grid>+ <Grid.RowDefinitions>+ <RowDefinition Height="*" />+ <RowDefinition Height="Auto" />+ </Grid.RowDefinitions>++ <ScrollViewer Grid.Row="0" VerticalScrollBarVisibility="Auto">+ <StackPanel x:Name="StructureContainer" Spacing="0" />+ </ScrollViewer>++ <!-- Bottom toolbar: Add Column + Apply Changes -->+ <Grid Grid.Row="1" Padding="8,4"+ Background="{ThemeResource LayerFillColorDefaultBrush}"+ BorderBrush="{ThemeResource DividerStrokeColorDefaultBrush}"+ BorderThickness="0,1,0,0">+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="*" />+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="Auto" />+ </Grid.ColumnDefinitions>++ <Button x:Name="AddColumnBtn" Grid.Column="0"+ Padding="8,4" Background="Transparent" BorderThickness="0">+ <StackPanel Orientation="Horizontal" Spacing="4">+ <FontIcon Glyph="" FontSize="10" />+ <TextBlock Text="Column" FontSize="11" />+ </StackPanel>+ </Button>++ <TextBlock x:Name="PendingAlterText" Grid.Column="2"+ FontSize="11" VerticalAlignment="Center"+ Foreground="Orange" Margin="0,0,8,0" />+ <Button x:Name="ApplyAlterBtn" Grid.Column="3"+ Content="Apply" Padding="10,4" FontSize="11"+ Style="{StaticResource AccentButtonStyle}"+ Visibility="Collapsed" />+ </Grid>+ </Grid>+</UserControl>diff --git a/windows/Gridex/TabBarControl.cpp b/windows/Gridex/TabBarControl.cppnew file mode 100644index 0000000..66afefb--- /dev/null+++ b/windows/Gridex/TabBarControl.cpp@@ -0,0 +1,136 @@+#include "pch.h"+#include "xaml-includes.h"+#include <winrt/Windows.UI.h>+#include "TabBarControl.h"+#if __has_include("TabBarControl.g.cpp")+#include "TabBarControl.g.cpp"+#endif++namespace winrt::Gridex::implementation+{+ namespace mux = winrt::Microsoft::UI::Xaml;+ namespace muxc = winrt::Microsoft::UI::Xaml::Controls;+ namespace muxm = winrt::Microsoft::UI::Xaml::Media;++ TabBarControl::TabBarControl()+ {+ InitializeComponent();++ this->Loaded([this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ NewTabBtn().Click([this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ if (OnNewTab) OnNewTab();+ });+ });+ }++ void TabBarControl::AddTab(winrt::hstring const& id, winrt::hstring const& title)+ {+ TabEntry entry{ std::wstring(id), std::wstring(title) };+ tabs_.push_back(entry);+ RebuildStrip();+ }++ void TabBarControl::SetActiveTab(winrt::hstring const& id)+ {+ activeId_ = std::wstring(id);+ RebuildStrip();+ }++ void TabBarControl::CloseTab(winrt::hstring const& id)+ {+ std::wstring closeId(id);+ tabs_.erase(+ std::remove_if(tabs_.begin(), tabs_.end(),+ [&](const TabEntry& e) { return e.id == closeId; }),+ tabs_.end());++ bool wasActive = (activeId_ == closeId);+ if (wasActive)+ activeId_ = tabs_.empty() ? L"" : tabs_.back().id;++ RebuildStrip();++ // Notify host so it can sync its own tab state and content view+ if (OnTabClosed) OnTabClosed(closeId);+ // If active tab changed (because we closed the active one), fire that too+ if (wasActive && OnTabChanged) OnTabChanged(activeId_);+ }++ void TabBarControl::RebuildStrip()+ {+ TabStrip().Children().Clear();++ for (auto& entry : tabs_)+ {+ bool isActive = (entry.id == activeId_);++ muxc::Button btn;+ btn.Padding(mux::Thickness{ 12.0, 0.0, 8.0, 0.0 });+ btn.Height(36.0);+ btn.BorderThickness(mux::Thickness{ 0, 0, 0, isActive ? 2.0 : 0.0 });+ if (isActive)+ {+ mux::Media::SolidColorBrush accent;+ accent.Color(winrt::Windows::UI::ColorHelper::FromArgb(255, 0, 120, 212));+ btn.BorderBrush(accent);+ btn.Background(muxm::SolidColorBrush(winrt::Windows::UI::Colors::Transparent()));+ }+ else+ {+ btn.Background(muxm::SolidColorBrush(winrt::Windows::UI::Colors::Transparent()));+ }++ muxc::StackPanel row;+ row.Orientation(muxc::Orientation::Horizontal);+ row.Spacing(6.0);++ muxc::TextBlock lbl;+ lbl.Text(winrt::hstring(entry.title));+ lbl.FontSize(12.0);+ lbl.VerticalAlignment(mux::VerticalAlignment::Center);+ lbl.Opacity(isActive ? 1.0 : 0.7);+ row.Children().Append(lbl);++ // Close (x) button+ muxc::Button closeBtn;+ closeBtn.Width(16.0);+ closeBtn.Height(16.0);+ closeBtn.Padding(mux::Thickness{ 0,0,0,0 });+ closeBtn.Background(muxm::SolidColorBrush(winrt::Windows::UI::Colors::Transparent()));+ closeBtn.BorderThickness(mux::Thickness{ 0,0,0,0 });+ muxc::FontIcon closeIcon;+ closeIcon.Glyph(L"\xE711");+ closeIcon.FontSize(8.0);+ closeBtn.Content(closeIcon);++ std::wstring capturedId = entry.id;+ closeBtn.Click([this, capturedId](auto&&, auto&&)+ {+ CloseTab(winrt::hstring(capturedId));+ });+ row.Children().Append(closeBtn);++ btn.Content(row);++ std::wstring tabId = entry.id;+ btn.Click([this, tabId](auto&&, auto&&)+ {+ SelectTab(tabId);+ });++ TabStrip().Children().Append(btn);+ }+ }++ void TabBarControl::SelectTab(const std::wstring& id)+ {+ activeId_ = id;+ RebuildStrip();+ if (OnTabChanged)+ OnTabChanged(id);+ }++ // NewTab_Click removed — wired in code-behind via Loaded+}diff --git a/windows/Gridex/TabBarControl.h b/windows/Gridex/TabBarControl.hnew file mode 100644index 0000000..0ab39b2--- /dev/null+++ b/windows/Gridex/TabBarControl.h@@ -0,0 +1,46 @@+#pragma once++#include "TabBarControl.g.h"+#include <functional>+#include <vector>+#include <string>++namespace winrt::Gridex::implementation+{+ struct TabEntry+ {+ std::wstring id;+ std::wstring title;+ };++ struct TabBarControl : TabBarControlT<TabBarControl>+ {+ TabBarControl();++ void AddTab(winrt::hstring const& id, winrt::hstring const& title);+ void SetActiveTab(winrt::hstring const& id);+ void CloseTab(winrt::hstring const& id);++ // Callback fired when active tab changes+ std::function<void(const std::wstring& id)> OnTabChanged;+ // Callback fired when + button pressed+ std::function<void()> OnNewTab;+ // Callback fired when a tab is closed via the X button+ std::function<void(const std::wstring& id)> OnTabClosed;+++ private:+ std::vector<TabEntry> tabs_;+ std::wstring activeId_;++ void RebuildStrip();+ void SelectTab(const std::wstring& id);+ };+}++namespace winrt::Gridex::factory_implementation+{+ struct TabBarControl : TabBarControlT<TabBarControl, implementation::TabBarControl>+ {+ };+}diff --git a/windows/Gridex/TabBarControl.idl b/windows/Gridex/TabBarControl.idlnew file mode 100644index 0000000..506b18c--- /dev/null+++ b/windows/Gridex/TabBarControl.idl@@ -0,0 +1,8 @@+namespace Gridex+{+ [default_interface]+ runtimeclass TabBarControl : Microsoft.UI.Xaml.Controls.UserControl+ {+ TabBarControl();+ }+}diff --git a/windows/Gridex/TabBarControl.xaml b/windows/Gridex/TabBarControl.xamlnew file mode 100644index 0000000..c6dab8c--- /dev/null+++ b/windows/Gridex/TabBarControl.xaml@@ -0,0 +1,29 @@+<UserControl+ x:Class="Gridex.TabBarControl"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:local="using:Gridex">++ <Grid MinHeight="36"+ Background="{ThemeResource LayerFillColorDefaultBrush}"+ BorderBrush="{ThemeResource DividerStrokeColorDefaultBrush}"+ BorderThickness="0,0,0,1">+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="*" />+ <ColumnDefinition Width="Auto" />+ </Grid.ColumnDefinitions>++ <!-- Tab strip -->+ <ScrollViewer Grid.Column="0" HorizontalScrollBarVisibility="Auto"+ VerticalScrollBarVisibility="Disabled">+ <StackPanel x:Name="TabStrip" Orientation="Horizontal" Spacing="0" />+ </ScrollViewer>++ <!-- New tab button -->+ <Button x:Name="NewTabBtn" Grid.Column="1" Width="36" Height="36" Padding="0"+ Background="Transparent" BorderThickness="0"+ ToolTipService.ToolTip="New Query Tab">+ <FontIcon Glyph="" FontSize="12" />+ </Button>+ </Grid>+</UserControl>diff --git a/windows/Gridex/WorkspacePage.cpp b/windows/Gridex/WorkspacePage.cppnew file mode 100644index 0000000..901eed7--- /dev/null+++ b/windows/Gridex/WorkspacePage.cpp@@ -0,0 +1,3829 @@+#include "pch.h"+#include "xaml-includes.h"+#include <winrt/Windows.UI.Text.h>+#include <winrt/Windows.System.h>+#include "WorkspacePage.h"+#include "SidebarPanel.h"+#include "TabBarControl.h"+#include "DataGridView.h"+#include "QueryEditorView.h"+#include "StructureView.h"+#include "StatusBarControl.h"+#include "DetailsPanel.h"+#include "FilterBar.h"+#include "Models/ExportService.h"+#include "Models/ImportService.h"+#include "Models/DumpRestoreService.h"+#include "Models/ERDiagramService.h"+#include "Models/AppSettings.h"+#include "App.xaml.h"+#include <winrt/Microsoft.UI.Xaml.Controls.h>+#include <winrt/Microsoft.UI.Input.h>+#include <winrt/Microsoft.Web.WebView2.Core.h>+#include <winrt/Windows.ApplicationModel.DataTransfer.h>+#include <winrt/Microsoft.UI.Xaml.Interop.h>+#include <winrt/Microsoft.Windows.Storage.Pickers.h>+#include <winrt/Microsoft.UI.Windowing.h>+#include <microsoft.ui.xaml.window.h>+#include <ShlObj.h>+#include <chrono>+#include <fstream>+#include <thread>+#if __has_include("WorkspacePage.g.cpp")+#include "WorkspacePage.g.cpp"+#endif++namespace winrt::Gridex::implementation+{+ namespace mux = winrt::Microsoft::UI::Xaml;+ namespace muxc = winrt::Microsoft::UI::Xaml::Controls;+ namespace muxm = winrt::Microsoft::UI::Xaml::Media;++ // Definitions for the cross-instance connection cache declared in+ // WorkspacePage.h. Populated by SetConnection, consumed by the+ // Loaded handler when a fresh WorkspacePage lands without one+ // (e.g. after Back from SettingsPage).+ DBModels::ConnectionConfig WorkspacePage::sLastConfig_{};+ std::wstring WorkspacePage::sLastPassword_{};+ bool WorkspacePage::sHasLastConnection_ = false;++ WorkspacePage::WorkspacePage()+ {+ InitializeComponent();++ this->Loaded([this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ isLoaded_ = true;+ WireAllButtons();+ ApplyAiSettings(); // Load AI config from settings.json → DetailsPanel++ if (hasConnection_)+ {+ InitializeConnection();+ return;+ }++ // Fresh instance (Frame created it via default ctor after Back+ // from Settings, etc.) — restore the last active connection+ // from the process-wide cache instead of falling back to the+ // hard-coded demo sidebar.+ if (sHasLastConnection_)+ {+ SetConnection(sLastConfig_, sLastPassword_);+ return;+ }++ LoadDemoSidebarData();+ });+ }++ // ── Load AI config from persisted settings into DetailsPanel ───+ void WorkspacePage::ApplyAiSettings()+ {+ auto s = DBModels::AppSettings::Load();+ DBModels::AiConfig cfg;+ cfg.provider = static_cast<DBModels::AiProvider>(s.aiProviderIndex);+ cfg.apiKey = s.aiApiKey;+ cfg.model = s.aiModel;+ cfg.ollamaEndpoint = s.ollamaEndpoint;+ Details().as<DetailsPanel>()->SetAiConfig(cfg);+ }++ // ── Button Wiring (code-behind, no IDL needed) ──────+ void WorkspacePage::WireAllButtons()+ {+ if (buttonsWired_) return;+ buttonsWired_ = true;++ // ── Keyboard shortcuts ─────────────────────────+ // Ctrl+S → commit pending row changes (mirrors the Commit toolbar button)+ {+ auto commitAccel = mux::Input::KeyboardAccelerator();+ commitAccel.Key(winrt::Windows::System::VirtualKey::S);+ commitAccel.Modifiers(winrt::Windows::System::VirtualKeyModifiers::Control);+ commitAccel.Invoked([this](auto&&, mux::Input::KeyboardAcceleratorInvokedEventArgs const& args)+ {+ CommitChanges();+ args.Handled(true);+ });+ this->KeyboardAccelerators().Append(commitAccel);+ }++ // Ctrl+Z → discard pending row changes+ {+ auto discardAccel = mux::Input::KeyboardAccelerator();+ discardAccel.Key(winrt::Windows::System::VirtualKey::Z);+ discardAccel.Modifiers(winrt::Windows::System::VirtualKeyModifiers::Control);+ discardAccel.Invoked([this](auto&&, mux::Input::KeyboardAcceleratorInvokedEventArgs const& args)+ {+ DiscardChanges();+ args.Handled(true);+ });+ this->KeyboardAccelerators().Append(discardAccel);+ }++ // Ctrl+T → open a new SQL query tab+ {+ auto newTabAccel = mux::Input::KeyboardAccelerator();+ newTabAccel.Key(winrt::Windows::System::VirtualKey::T);+ newTabAccel.Modifiers(winrt::Windows::System::VirtualKeyModifiers::Control);+ newTabAccel.Invoked([this](auto&&, mux::Input::KeyboardAcceleratorInvokedEventArgs const& args)+ {+ OpenNewQueryTab();+ args.Handled(true);+ });+ this->KeyboardAccelerators().Append(newTabAccel);+ }++ // Ctrl+W → close the currently active tab (no-op if none)+ {+ auto closeTabAccel = mux::Input::KeyboardAccelerator();+ closeTabAccel.Key(winrt::Windows::System::VirtualKey::W);+ closeTabAccel.Modifiers(winrt::Windows::System::VirtualKeyModifiers::Control);+ closeTabAccel.Invoked([this](auto&&, mux::Input::KeyboardAcceleratorInvokedEventArgs const& args)+ {+ if (!state_.activeTabId.empty())+ {+ // CloseTab fires OnTabClosed synchronously which mutates+ // state_.tabs and state_.activeTabId. Safe here because+ // we're not iterating the tabs vector.+ TabBar().as<TabBarControl>()->CloseTab(+ winrt::hstring(state_.activeTabId));+ }+ args.Handled(true);+ });+ this->KeyboardAccelerators().Append(closeTabAccel);+ }++ // DataGrid callbacks+ DataGrid().as<DataGridView>()->OnRowSelected = [this](int rowIndex)+ {+ if (rowIndex >= 0 && rowIndex < static_cast<int>(state_.currentData.rows.size()))+ {+ Details().as<DetailsPanel>()->ShowRow(+ state_.currentData.columnNames,+ state_.currentData.rows[rowIndex]);+ }+ };++ // Delete key on grid → same as Delete toolbar button (mark row+ // deleted; commit still requires explicit Commit action / Ctrl+S).+ DataGrid().as<DataGridView>()->OnDeleteRequested = [this]()+ {+ DeleteSelectedRow();+ };++ // Wire structure view ALTER apply+ Structure().as<StructureView>()->OnApplyAlter = [this](const std::vector<std::wstring>& sqls)+ {+ if (!connMgr_.isConnected() || sqls.empty()) return;+ auto adapter = connMgr_.getActiveAdapter();+ if (!adapter) return;++ try+ {+ for (auto& sql : sqls)+ {+ auto result = adapter->execute(sql);+ LogQuery(result);+ if (!result.success)+ {+ muxc::ContentDialog errDlg;+ errDlg.Title(winrt::box_value(winrt::hstring(L"ALTER Failed")));+ errDlg.Content(winrt::box_value(winrt::hstring(+ L"SQL: " + sql + L"\n\n" + result.error)));+ errDlg.CloseButtonText(L"OK");+ errDlg.XamlRoot(this->XamlRoot());+ errDlg.ShowAsync();+ return;+ }+ }+ // Reload table structure+ ReloadCurrentTable();+ }+ catch (...) {}+ };++ // Wire details panel field edit → ChangeTracker + DataGrid sync+ Details().as<DetailsPanel>()->OnFieldEdited = [this](+ const std::wstring& column, const std::wstring& oldValue, const std::wstring& newValue)+ {+ int rowIndex = DataGrid().as<DataGridView>()->GetSelectedRowIndex();+ if (rowIndex < 0) return;++ // Update DataGrid data+ if (rowIndex < static_cast<int>(state_.currentData.rows.size()))+ state_.currentData.rows[rowIndex][column] = newValue;++ // Track change+ auto pk = ExtractPrimaryKey(rowIndex);+ changeTracker_.trackUpdate(rowIndex, column, oldValue, newValue, pk);+ UpdatePendingUI();++ // Refresh grid row display+ DataGrid().as<DataGridView>()->SetData(state_.currentData);+ };++ // Wire details panel "+" context picker: expose the current DB's+ // table list so the chat flyout can populate, and a structure+ // fetcher that returns a DDL-like snippet the assistant can read.+ Details().as<DetailsPanel>()->OnRequestTableList = [this]() -> std::vector<std::wstring>+ {+ std::vector<std::wstring> names;+ for (auto& group : state_.sidebarItems)+ {+ if (group.id != L"tables" && group.id != L"views") continue;+ for (auto& item : group.children) names.push_back(item.title);+ }+ return names;+ };++ Details().as<DetailsPanel>()->OnFetchTableStructure =+ [this](const std::wstring& tableName) -> std::wstring+ {+ auto adapter = connMgr_.getActiveAdapter();+ if (!adapter) return {};+ try+ {+ auto cols = adapter->describeTable(tableName, currentSchema_);+ auto indexes = adapter->listIndexes(tableName, currentSchema_);+ auto fks = adapter->listForeignKeys(tableName, currentSchema_);++ std::wstring out;+ out += L"Table: " + tableName + L"\n";+ out += L"Columns:\n";+ for (auto& c : cols)+ {+ out += L" " + c.name + L" " + c.dataType;+ if (c.isPrimaryKey) out += L" PRIMARY KEY";+ if (!c.nullable) out += L" NOT NULL";+ if (!c.defaultValue.empty())+ out += L" DEFAULT " + c.defaultValue;+ out += L"\n";+ }+ if (!indexes.empty())+ {+ out += L"Indexes:\n";+ for (auto& i : indexes)+ {+ out += L" " + i.name + L" (" + i.columns + L")";+ if (i.isUnique) out += L" UNIQUE";+ out += L"\n";+ }+ }+ if (!fks.empty())+ {+ out += L"Foreign Keys:\n";+ for (auto& f : fks)+ {+ out += L" " + f.column + L" -> "+ + f.referencedTable + L"(" + f.referencedColumn + L")\n";+ }+ }+ return out;+ }+ catch (...) { return {}; }+ };++ // Wire cell edit → ChangeTracker+ DataGrid().as<DataGridView>()->OnCellEdited = [this](int rowIndex,+ const std::wstring& column, const std::wstring& oldValue, const std::wstring& newValue)+ {+ auto pk = ExtractPrimaryKey(rowIndex);+ changeTracker_.trackUpdate(rowIndex, column, oldValue, newValue, pk);+ UpdatePendingUI();+ };++ DataGrid().as<DataGridView>()->OnSortRequested = [this](const std::wstring& column, bool ascending)+ {+ if (!connMgr_.isConnected()) return;+ for (auto& tab : state_.tabs)+ {+ if (tab.id == state_.activeTabId && tab.type == DBModels::TabType::DataGrid)+ {+ auto adapter = connMgr_.getActiveAdapter();+ if (!adapter) return;+ try+ {+ state_.currentData = adapter->fetchRows(+ tab.tableName, tab.schema,+ state_.pageSize, (state_.currentPage) * state_.pageSize,+ column, ascending);+ LogQuery(state_.currentData);+ DataGrid().as<DataGridView>()->SetData(state_.currentData);+ UpdatePaginationUI();+ }+ catch (...) {}+ break;+ }+ }+ };++ // QueryEditor callback+ QueryEditor().as<QueryEditorView>()->OnExecuteQuery = [this](const std::wstring& sql) -> DBModels::QueryResult+ {+ if (connMgr_.isConnected())+ {+ auto adapter = connMgr_.getActiveAdapter();+ if (adapter)+ {+ try+ {+ auto result = adapter->execute(sql);+ LogQuery(result);+ return result;+ }+ catch (const std::exception& ex)+ {+ DBModels::QueryResult err;+ err.success = false;+ int sz = MultiByteToWideChar(CP_UTF8, 0, ex.what(), -1, nullptr, 0);+ std::wstring msg(sz, L'\0');+ MultiByteToWideChar(CP_UTF8, 0, ex.what(), -1, &msg[0], sz);+ err.error = msg;+ return err;+ }+ }+ }+ DBModels::QueryResult demo;+ demo.success = true;+ return demo;+ };++ // Tab bar callbacks+ TabBar().as<TabBarControl>()->OnNewTab = [this]() { OpenNewQueryTab(); };++ // When a tab is closed (via X button or Ctrl+W), sync state_.tabs+ // but do NOT touch state_.activeTabId or call SwitchContentView+ // here. TabBarControl::CloseTab fires OnTabChanged(newActiveId)+ // right after OnTabClosed when the closed tab was the active+ // one, and OnTabChanged owns all the "switch to a different+ // tab" logic (save cache, restore from cache, load data, repaint).+ //+ // Previously this handler also bumped state_.activeTabId to the+ // new active tab and called SwitchContentView. That corrupted+ // the cache: the subsequent OnTabChanged → SaveCurrentTabCache+ // used the newly-bumped activeTabId to decide which tab to+ // save into, so state_.currentData (still the closed tab's+ // data) got written onto the NEW active tab's cachedData, and+ // the restore path showed the wrong data in the grid. Leaving+ // activeTabId pointing at the closed-but-erased tab is safe+ // because SaveCurrentTabCache's lookup simply finds nothing+ // and becomes a no-op, then OnTabChanged bumps activeTabId+ // cleanly before loading the new tab.+ TabBar().as<TabBarControl>()->OnTabClosed = [this](const std::wstring& id)+ {+ // Cleanup ER diagram temp SVG if applicable+ for (const auto& t : state_.tabs)+ {+ if (t.id == id && t.type == DBModels::TabType::ERDiagram &&+ !t.erSvgPath.empty())+ {+ DeleteFileW(t.erSvgPath.c_str());+ }+ }+ state_.tabs.erase(+ std::remove_if(state_.tabs.begin(), state_.tabs.end(),+ [&id](const DBModels::ContentTab& t) { return t.id == id; }),+ state_.tabs.end());++ // When the closed tab was NOT the active one, TabBarControl+ // won't fire OnTabChanged -- the active tab's content is+ // still visually correct, so no repaint needed.+ // When the closed tab WAS active, OnTabChanged runs next+ // and handles everything.+ if (state_.tabs.empty())+ {+ // Last tab closed: OnTabChanged will fire with empty id+ // and SwitchContentView there will show EmptyContentState.+ // Nothing to do here.+ }+ };+ TabBar().as<TabBarControl>()->OnTabChanged = [this](const std::wstring& id)+ {+ // Save current tab data to cache before switching+ SaveCurrentTabCache();++ state_.activeTabId = id;+ bool isERDiagramTab = false;+ for (auto& tab : state_.tabs)+ {+ if (tab.id == id)+ {+ if (tab.type == DBModels::TabType::DataGrid)+ {+ // Restore from cache if available, else load fresh+ if (tab.cachedData.has_value())+ {+ state_.currentData = tab.cachedData.value();+ state_.currentColumns = tab.cachedColumns;+ state_.currentIndexes = tab.cachedIndexes;+ state_.currentForeignKeys = tab.cachedForeignKeys;+ state_.currentPage = tab.cachedPage;+ DataGrid().as<DataGridView>()->SetData(state_.currentData);+ Structure().as<StructureView>()->SetTableContext(+ tab.tableName, tab.schema, state_.connection.databaseType);+ Structure().as<StructureView>()->SetData(+ state_.currentColumns, state_.currentIndexes,+ state_.currentForeignKeys, state_.currentConstraints);+ UpdatePaginationUI();+ }+ else+ {+ state_.currentPage = 0;+ if (connMgr_.isConnected())+ LoadTableDataFromDB(tab.tableName);+ else+ LoadDemoTableData(tab.tableName);+ }+ }+ else if (tab.type == DBModels::TabType::QueryEditor)+ {+ // Restore this tab's SQL into the shared+ // QueryEditorView. Without this, all query+ // tabs display the same text (whatever was+ // last typed in any of them).+ QueryEditor().as<QueryEditorView>()->SetSql(tab.cachedSql);+ }+ else if (tab.type == DBModels::TabType::ERDiagram)+ {+ isERDiagramTab = true;+ LoadERDiagramIntoView(tab);+ }+ break;+ }+ }+ if (!isERDiagramTab)+ {+ showingData_ = true;+ DataToggle().IsChecked(true);+ StructureToggle().IsChecked(false);+ }+ SwitchContentView();+ };++ // Sidebar schema picker+ Sidebar().as<SidebarPanel>()->OnSchemaChanged = [this](const std::wstring& schema)+ {+ currentSchema_ = schema;+ state_.statusSchema = schema;+ if (!connMgr_.isConnected()) return;++ LoadSidebarFromDB();++ // Sync the open DataGrid tab to the new schema. Without this,+ // switching Redis logical DBs (db0 -> db5) updated the sidebar+ // key list but left the table view showing stale keys from the+ // previous DB. Also rewrite tab.schema so subsequent tab+ // switches fetch from the right DB.+ for (auto& tab : state_.tabs)+ {+ if (tab.id == state_.activeTabId &&+ tab.type == DBModels::TabType::DataGrid)+ {+ tab.schema = schema;+ LoadTableDataFromDB(tab.tableName);+ break;+ }+ }+ };++ // Sidebar history item click → open query tab with SQL+ Sidebar().as<SidebarPanel>()->OnHistoryItemClicked = [this](const std::wstring& sql)+ {+ OpenNewQueryTab();+ // Set the SQL in the query editor+ QueryEditor().as<QueryEditorView>()->SetSql(sql);+ };++ // Sidebar add table — show dialog to create new table+ Sidebar().as<SidebarPanel>()->OnAddTable = [this]()+ {+ if (!connMgr_.isConnected()) return;++ // Simple dialog: table name input+ muxc::ContentDialog dlg;+ dlg.Title(winrt::box_value(winrt::hstring(L"Create Table")));++ muxc::StackPanel content;+ content.Spacing(8.0);+ muxc::TextBox nameBox;+ nameBox.PlaceholderText(L"Table name");+ nameBox.Width(300.0);+ content.Children().Append(nameBox);++ muxc::TextBox columnsBox;+ if (state_.connection.databaseType == DBModels::DatabaseType::MSSQLServer)+ columnsBox.PlaceholderText(L"Columns (e.g.: id INT IDENTITY(1,1) PRIMARY KEY, name NVARCHAR(255) NOT NULL)");+ else+ columnsBox.PlaceholderText(L"Columns (e.g.: id uuid PRIMARY KEY DEFAULT gen_random_uuid(), name text NOT NULL)");+ columnsBox.AcceptsReturn(true);+ columnsBox.TextWrapping(mux::TextWrapping::Wrap);+ columnsBox.Width(300.0);+ columnsBox.Height(120.0);+ columnsBox.FontFamily(mux::Media::FontFamily(L"Cascadia Code,Consolas,monospace"));+ columnsBox.FontSize(12.0);+ content.Children().Append(columnsBox);+ dlg.Content(content);++ dlg.PrimaryButtonText(L"Create");+ dlg.CloseButtonText(L"Cancel");+ dlg.XamlRoot(this->XamlRoot());++ auto op = dlg.ShowAsync();+ op.Completed([this, nameBox, columnsBox](auto&& asyncOp, auto&&)+ {+ if (asyncOp.GetResults() != muxc::ContentDialogResult::Primary) return;+ this->DispatcherQueue().TryEnqueue([this, nameBox, columnsBox]()+ {+ std::wstring tblName(nameBox.Text());+ std::wstring cols(columnsBox.Text());+ if (tblName.empty()) return;++ // Build CREATE TABLE with dialect-aware quoting and defaults+ auto dbType = state_.connection.databaseType;+ std::wstring sql;+ if (dbType == DBModels::DatabaseType::MSSQLServer)+ {+ sql = L"CREATE TABLE [" + currentSchema_ + L"].[" + tblName + L"] (";+ if (cols.empty())+ sql += L"id INT IDENTITY(1,1) PRIMARY KEY";+ else+ sql += cols;+ }+ else if (dbType == DBModels::DatabaseType::MySQL)+ {+ sql = L"CREATE TABLE `" + currentSchema_ + L"`.`" + tblName + L"` (";+ if (cols.empty())+ sql += L"id BIGINT AUTO_INCREMENT PRIMARY KEY";+ else+ sql += cols;+ }+ else if (dbType == DBModels::DatabaseType::SQLite)+ {+ sql = L"CREATE TABLE \"" + tblName + L"\" (";+ if (cols.empty())+ sql += L"id INTEGER PRIMARY KEY AUTOINCREMENT";+ else+ sql += cols;+ }+ else+ {+ // PostgreSQL default+ sql = L"CREATE TABLE \"" + currentSchema_ + L"\".\"" + tblName + L"\" (";+ if (cols.empty())+ sql += L"id uuid PRIMARY KEY DEFAULT gen_random_uuid()";+ else+ sql += cols;+ }+ sql += L")";++ auto adapter = connMgr_.getActiveAdapter();+ if (!adapter) return;+ try+ {+ auto result = adapter->execute(sql);+ LogQuery(result);+ if (result.success)+ LoadSidebarFromDB(); // refresh+ }+ catch (...) {}+ });+ });+ };++ // Sidebar delete table — confirm then DROP+ Sidebar().as<SidebarPanel>()->OnDeleteTable = [this](const std::wstring& tableName, const std::wstring& schema)+ {+ if (!connMgr_.isConnected() || tableName.empty()) return;++ muxc::ContentDialog dlg;+ dlg.Title(winrt::box_value(winrt::hstring(L"Drop Table")));+ dlg.Content(winrt::box_value(winrt::hstring(+ L"Are you sure you want to drop \"" + schema + L"\".\"" + tableName + L"\"?\n\nThis action cannot be undone.")));+ dlg.PrimaryButtonText(L"Drop");+ dlg.CloseButtonText(L"Cancel");+ dlg.DefaultButton(muxc::ContentDialogButton::Close);+ dlg.XamlRoot(this->XamlRoot());++ auto op = dlg.ShowAsync();+ op.Completed([this, tableName, schema](auto&& asyncOp, auto&&)+ {+ if (asyncOp.GetResults() != muxc::ContentDialogResult::Primary) return;+ this->DispatcherQueue().TryEnqueue([this, tableName, schema]()+ {+ auto adapter = connMgr_.getActiveAdapter();+ if (!adapter) return;+ try+ {+ // Quote identifiers per dialect and only prepend+ // the schema when the adapter supports schemas+ // (PostgreSQL does, MySQL databases sort of do via+ // `schema`.`table`, SQLite has none).+ auto dbType = state_.connection.databaseType;+ std::wstring qt, qs;+ if (dbType == DBModels::DatabaseType::MySQL)+ {+ qt = L"`" + tableName + L"`";+ if (!schema.empty()) qs = L"`" + schema + L"`.";+ }+ else if (dbType == DBModels::DatabaseType::SQLite)+ {+ qt = L"\"" + tableName + L"\"";+ // SQLite has no schemas+ }+ else // PostgreSQL and anything else SQL-ish+ {+ qt = L"\"" + tableName + L"\"";+ if (!schema.empty()) qs = L"\"" + schema + L"\".";+ }++ std::wstring sql = L"DROP TABLE " + qs + qt;+ auto result = adapter->execute(sql);+ LogQuery(result);+ if (result.success)+ {+ // Close any open tab pointing at the dropped+ // table so the UI stops showing stale rows.+ //+ // Double-erase trap: TabBarControl::CloseTab+ // synchronously fires OnTabClosed, which in turn+ // runs state_.tabs.erase(remove_if ...) in this+ // file. If we call CloseTab while iterating+ // state_.tabs here, the container is erased+ // from underneath the iterator (vector assert+ // "erase iterator outside range"). Snapshot the+ // matching ids first, then drive CloseTab off+ // the snapshot.+ std::vector<std::wstring> idsToClose;+ for (const auto& t : state_.tabs)+ {+ if (t.type == DBModels::TabType::DataGrid &&+ t.tableName == tableName &&+ t.schema == schema)+ {+ idsToClose.push_back(t.id);+ }+ }+ for (const auto& id : idsToClose)+ {+ TabBar().as<TabBarControl>()->CloseTab(+ winrt::hstring(id));+ }+ LoadSidebarFromDB(); // refresh+ SwitchContentView();+ }+ else+ {+ muxc::ContentDialog errDlg;+ errDlg.Title(winrt::box_value(winrt::hstring(L"Drop Failed")));+ errDlg.Content(winrt::box_value(winrt::hstring(result.error)));+ errDlg.CloseButtonText(L"OK");+ errDlg.XamlRoot(this->XamlRoot());+ errDlg.ShowAsync();+ }+ }+ catch (...) {}+ });+ });+ };++ // Sidebar export table — right-click → Export → CSV/JSON/SQL+ Sidebar().as<SidebarPanel>()->OnExportTable = [this](+ const std::wstring& tableName, const std::wstring& schema, const std::wstring& format)+ {+ // Launch async export (fire-and-forget coroutine)+ ExportTableAsync(tableName, schema, format);+ };++ // Sidebar import — right-click table → Import (target = that table)+ Sidebar().as<SidebarPanel>()->OnImportTable = [this](+ const std::wstring& tableName, const std::wstring& schema)+ {+ ImportDataAsync(tableName, schema);+ };++ // Sidebar ER diagram — right-click Database/Schema group → Show ER Diagram+ Sidebar().as<SidebarPanel>()->OnShowERDiagram = [this](const std::wstring& schema)+ {+ ShowERDiagramAsync(schema);+ };++ // Redis-only: Refresh keys listing (sidebar context menu → Refresh)+ Sidebar().as<SidebarPanel>()->OnRefreshSidebar = [this]()+ {+ if (connMgr_.isConnected()) LoadSidebarFromDB();+ };++ // Redis-only: Flush DB — show confirmation, then issue FLUSHDB via execute()+ Sidebar().as<SidebarPanel>()->OnFlushRedisDb = [this]()+ {+ FlushRedisDbAsync();+ };++ // Redis-only: Browse Keys — show pattern input dialog, then open Keys table+ Sidebar().as<SidebarPanel>()->OnBrowseRedisKeys = [this]()+ {+ BrowseRedisKeysAsync();+ };++ // Filter bar callbacks+ FilterBarControl().as<FilterBar>()->OnApplyFilter = [this](const winrt::Gridex::implementation::FilterCondition& cond)+ {+ ApplyFilter(cond.column, cond.op, cond.value);+ };+ FilterBarControl().as<FilterBar>()->OnClearFilter = [this]()+ {+ ReloadCurrentTable();+ };++ // Toolbar buttons (all wired in code-behind)+ HomeBtn().Click([this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ // Walk visual tree to find hosting Frame, then navigate to HomePage+ muxc::Frame frame{ nullptr };+ auto fe = this->try_as<mux::FrameworkElement>();+ while (fe)+ {+ if (auto f = fe.try_as<muxc::Frame>()) { frame = f; break; }+ fe = fe.Parent().try_as<mux::FrameworkElement>();+ }+ if (!frame) frame = this->Frame();+ if (!frame) return;++ winrt::Windows::UI::Xaml::Interop::TypeName pageType;+ pageType.Name = L"Gridex.HomePage";+ pageType.Kind = winrt::Windows::UI::Xaml::Interop::TypeKind::Metadata;+ frame.Navigate(pageType);+ });++ SidebarToggleBtn().Click([this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ { ToggleSidebar_Click({}, {}); });++ DeleteBtn().Click([this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ { DeleteSelectedRow(); });++ CommitToolbarBtn().Click([this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ { CommitChanges(); });++ DetailsToggleBtn().Click([this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ { ToggleDetails_Click({}, {}); });++ AiToggleBtn().Click([this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ { ToggleAI_Click({}, {}); });++ DumpBtn().Click([this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ { DumpDatabaseAsync(); });++ RestoreBtn().Click([this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ { RestoreDatabaseAsync(); });++ ERDiagramBtn().Click([this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ { ShowERDiagramAsync(currentSchema_); });++ // ER view action buttons (act on the active ERDiagram tab)+ ERCopyD2Btn().Click([this](auto&&, auto&&)+ {+ for (const auto& t : state_.tabs)+ {+ if (t.id == state_.activeTabId && t.type == DBModels::TabType::ERDiagram)+ {+ winrt::Windows::ApplicationModel::DataTransfer::DataPackage pkg;+ pkg.SetText(winrt::hstring(t.erD2Text));+ winrt::Windows::ApplicationModel::DataTransfer::Clipboard::SetContent(pkg);+ break;+ }+ }+ });++ ERSaveSvgBtn().Click([this](auto&&, auto&&) -> winrt::fire_and_forget+ {+ std::wstring svgPath, schema;+ for (const auto& t : state_.tabs)+ {+ if (t.id == state_.activeTabId && t.type == DBModels::TabType::ERDiagram)+ {+ svgPath = t.erSvgPath;+ schema = t.schema;+ break;+ }+ }+ if (svgPath.empty()) co_return;+ try+ {+ winrt::Microsoft::UI::WindowId windowId{+ reinterpret_cast<uint64_t>(+ winrt::Gridex::implementation::App::MainHwnd) };+ winrt::Microsoft::Windows::Storage::Pickers::FileSavePicker picker(windowId);+ picker.SuggestedFileName(winrt::hstring(schema + L"_er"));+ auto exts = winrt::single_threaded_vector<winrt::hstring>();+ exts.Append(L".svg");+ picker.FileTypeChoices().Insert(L"SVG", exts);+ auto pickedFile = co_await picker.PickSaveFileAsync();+ if (!pickedFile) co_return;+ CopyFileW(svgPath.c_str(),+ std::wstring(pickedFile.Path()).c_str(), FALSE);+ }+ catch (...) {}+ });++ // Floating ER controls (overlay top-right of WebView)+ auto runScript = [this](winrt::hstring js)+ {+ try { ERDiagramWebView().ExecuteScriptAsync(js); }+ catch (...) {}+ };+ ERZoomInBtn().Click([runScript](auto&&, auto&&)+ { runScript(L"window.__er&&window.__er.zoomIn()"); });+ ERZoomOutBtn().Click([runScript](auto&&, auto&&)+ { runScript(L"window.__er&&window.__er.zoomOut()"); });+ ERZoomLabelBtn().Click([runScript](auto&&, auto&&)+ { runScript(L"window.__er&&window.__er.resetZoom()"); });+ ERResetLayoutBtn().Click([runScript](auto&&, auto&&)+ { runScript(L"window.__er&&window.__er.resetLayout()"); });+ ERFullscreenBtn().Click([this](auto&&, auto&&)+ { ToggleERFullscreen(); });++ ERSaveD2Btn().Click([this](auto&&, auto&&) -> winrt::fire_and_forget+ {+ std::wstring d2Text, schema;+ for (const auto& t : state_.tabs)+ {+ if (t.id == state_.activeTabId && t.type == DBModels::TabType::ERDiagram)+ {+ d2Text = t.erD2Text;+ schema = t.schema;+ break;+ }+ }+ if (d2Text.empty()) co_return;+ try+ {+ winrt::Microsoft::UI::WindowId windowId{+ reinterpret_cast<uint64_t>(+ winrt::Gridex::implementation::App::MainHwnd) };+ winrt::Microsoft::Windows::Storage::Pickers::FileSavePicker picker(windowId);+ picker.SuggestedFileName(winrt::hstring(schema + L"_er"));+ auto exts = winrt::single_threaded_vector<winrt::hstring>();+ exts.Append(L".d2");+ picker.FileTypeChoices().Insert(L"D2 Source", exts);+ auto pickedFile = co_await picker.PickSaveFileAsync();+ if (!pickedFile) co_return;++ std::wstring path(pickedFile.Path());+ std::ofstream f(path, std::ios::binary);+ if (!f.is_open()) co_return;+ f.write("\xEF\xBB\xBF", 3);+ int sz = WideCharToMultiByte(CP_UTF8, 0, d2Text.c_str(),+ static_cast<int>(d2Text.size()), nullptr, 0, nullptr, nullptr);+ std::string utf8(sz, '\0');+ WideCharToMultiByte(CP_UTF8, 0, d2Text.c_str(),+ static_cast<int>(d2Text.size()), &utf8[0], sz, nullptr, nullptr);+ f.write(utf8.c_str(), utf8.size());+ }+ catch (...) {}+ });++ SettingsBtn().Click([this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ // Walk up visual tree to find hosting Frame (Page.Frame can be null in WinUI 3)+ muxc::Frame frame{ nullptr };+ auto fe = this->try_as<mux::FrameworkElement>();+ while (fe)+ {+ if (auto f = fe.try_as<muxc::Frame>()) { frame = f; break; }+ fe = fe.Parent().try_as<mux::FrameworkElement>();+ }+ if (!frame) frame = this->Frame();+ if (!frame)+ {+ muxc::ContentDialog err;+ err.Title(winrt::box_value(winrt::hstring(L"Navigation Error")));+ err.Content(winrt::box_value(winrt::hstring(+ L"Could not locate hosting Frame.\nUse Ctrl+Shift+P instead.")));+ err.CloseButtonText(L"OK");+ err.XamlRoot(this->XamlRoot());+ err.ShowAsync();+ return;+ }++ // Remember this page so Settings' Back button returns here+ auto s = DBModels::AppSettings::Load();+ s.lastPageBeforeSettings = L"Gridex.WorkspacePage";+ s.Save();++ winrt::Windows::UI::Xaml::Interop::TypeName pageType;+ pageType.Name = L"Gridex.SettingsPage";+ pageType.Kind = winrt::Windows::UI::Xaml::Interop::TypeKind::Metadata;+ frame.Navigate(pageType);+ });++ // Bottom bar buttons+ DataToggle().Click([this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ { DataToggle_Click({}, {}); });++ StructureToggle().Click([this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ { StructureToggle_Click({}, {}); });++ AddRowBtn().Click([this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ { AddNewRow(); });++ PrevPageBtn().Click([this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ { PrevPage(); });++ NextPageBtn().Click([this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ { NextPage(); });++ DiscardBtn().Click([this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ { DiscardChanges(); });++ CommitBottomBtn().Click([this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ { CommitChanges(); });++ FilterToggleBtn().Click([this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ { ToggleFilter_Click({}, {}); });++ ClearLogBtn().Click([this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ connMgr_.clearQueryLog();+ QueryLogEntries().Children().Clear();+ });++ WireResizeGrips();+ }++ // ── Drag-to-resize: left sidebar / right sidebar / query log ─────+ //+ // 3 transparent grip elements (LeftSidebarResizer / RightSidebarResizer+ // / QueryLogResizer) sit between panels in the XAML. Each one captures+ // the pointer on press, tracks the delta on move, and updates the+ // adjacent ColumnDefinition.Width or panel.Height live.+ //+ // Cursor uses UIElement.ProtectedCursor — the officially supported+ // WinUI 3 cursor API. cppwinrt strips ProtectedCursor from the public+ // projection of UIElement ("protected" in metadata, intended for+ // control authors), but the underlying ABI interface+ // winrt::Microsoft::UI::Xaml::IUIElementProtected IS publicly+ // declared and every UIElement implements it. Casting via+ // .as<IUIElementProtected>() gives us a consume_ wrapper that exposes+ // ProtectedCursor as a regular method call.+ //+ // Win32 SetCursor() in PointerMoved does NOT work reliably here —+ // the WinUI input pipeline issues its own SetCursor on every+ // WM_SETCURSOR message, racing with the user handler.++ void WorkspacePage::WireResizeGrips()+ {+ using winrt::Microsoft::UI::Input::InputSystemCursor;+ using winrt::Microsoft::UI::Input::InputSystemCursorShape;+ using winrt::Microsoft::UI::Xaml::IUIElementProtected;++ // Cursors are shared across all grip instances; created once on+ // first entry and reused — InputSystemCursor objects are cheap COM+ // refs, safe to statically cache.+ static auto sizeWECursor = InputSystemCursor::Create(+ InputSystemCursorShape::SizeWestEast);+ static auto sizeNSCursor = InputSystemCursor::Create(+ InputSystemCursorShape::SizeNorthSouth);++ // Set the persistent cursor on each grip via the ABI interface.+ // Safe to call here because WireResizeGrips runs from WireAllButtons+ // which is invoked after the Loaded event — the visual tree is+ // live by this point (ProtectedCursor throws otherwise).+ LeftSidebarResizer().as<IUIElementProtected>().ProtectedCursor(sizeWECursor);+ RightSidebarResizer().as<IUIElementProtected>().ProtectedCursor(sizeWECursor);+ QueryLogResizer().as<IUIElementProtected>().ProtectedCursor(sizeNSCursor);++ // ── Left sidebar resizer ────────────────────────+ LeftSidebarResizer().PointerPressed(+ [this](winrt::Windows::Foundation::IInspectable const& sender,+ mux::Input::PointerRoutedEventArgs const& e)+ {+ leftResizing_ = true;+ auto pt = e.GetCurrentPoint(this->try_as<mux::UIElement>());+ leftResizeStartX_ = pt.Position().X;+ leftResizeStartWidth_ = SidebarColumn().ActualWidth();+ if (auto el = sender.try_as<mux::UIElement>())+ el.CapturePointer(e.Pointer());+ e.Handled(true);+ });+ LeftSidebarResizer().PointerMoved(+ [this](winrt::Windows::Foundation::IInspectable const&,+ mux::Input::PointerRoutedEventArgs const& e)+ {+ if (!leftResizing_) return;+ auto pt = e.GetCurrentPoint(this->try_as<mux::UIElement>());+ double delta = pt.Position().X - leftResizeStartX_;+ double w = leftResizeStartWidth_ + delta;+ if (w < 160.0) w = 160.0;+ if (w > 600.0) w = 600.0;+ SidebarColumn().Width(mux::GridLengthHelper::FromPixels(w));+ e.Handled(true);+ });+ LeftSidebarResizer().PointerReleased(+ [this](winrt::Windows::Foundation::IInspectable const& sender,+ mux::Input::PointerRoutedEventArgs const& e)+ {+ if (leftResizing_)+ {+ leftResizing_ = false;+ if (auto el = sender.try_as<mux::UIElement>())+ el.ReleasePointerCapture(e.Pointer());+ // Sync toggle "remembered width" so collapse/expand+ // via SidebarToggleBtn restores the user's choice.+ prevSidebarWidth_ = SidebarColumn().ActualWidth();+ }+ e.Handled(true);+ });++ // ── Right sidebar (Details) resizer ─────────────+ RightSidebarResizer().PointerPressed(+ [this](winrt::Windows::Foundation::IInspectable const& sender,+ mux::Input::PointerRoutedEventArgs const& e)+ {+ rightResizing_ = true;+ auto pt = e.GetCurrentPoint(this->try_as<mux::UIElement>());+ rightResizeStartX_ = pt.Position().X;+ rightResizeStartWidth_ = DetailsColumn().ActualWidth();+ if (auto el = sender.try_as<mux::UIElement>())+ el.CapturePointer(e.Pointer());+ e.Handled(true);+ });+ RightSidebarResizer().PointerMoved(+ [this](winrt::Windows::Foundation::IInspectable const&,+ mux::Input::PointerRoutedEventArgs const& e)+ {+ if (!rightResizing_) return;+ auto pt = e.GetCurrentPoint(this->try_as<mux::UIElement>());+ // Dragging RIGHT shrinks the right panel; LEFT grows it.+ double delta = pt.Position().X - rightResizeStartX_;+ double w = rightResizeStartWidth_ - delta;+ if (w < 180.0) w = 180.0;+ if (w > 700.0) w = 700.0;+ DetailsColumn().Width(mux::GridLengthHelper::FromPixels(w));+ e.Handled(true);+ });+ RightSidebarResizer().PointerReleased(+ [this](winrt::Windows::Foundation::IInspectable const& sender,+ mux::Input::PointerRoutedEventArgs const& e)+ {+ if (rightResizing_)+ {+ rightResizing_ = false;+ if (auto el = sender.try_as<mux::UIElement>())+ el.ReleasePointerCapture(e.Pointer());+ prevDetailsWidth_ = DetailsColumn().ActualWidth();+ }+ e.Handled(true);+ });++ // ── Query log top resizer (vertical drag) ───────+ QueryLogResizer().PointerPressed(+ [this](winrt::Windows::Foundation::IInspectable const& sender,+ mux::Input::PointerRoutedEventArgs const& e)+ {+ logResizing_ = true;+ auto pt = e.GetCurrentPoint(this->try_as<mux::UIElement>());+ logResizeStartY_ = pt.Position().Y;+ logResizeStartHeight_ = QueryLogPanel().ActualHeight();+ if (auto el = sender.try_as<mux::UIElement>())+ el.CapturePointer(e.Pointer());+ e.Handled(true);+ });+ QueryLogResizer().PointerMoved(+ [this](winrt::Windows::Foundation::IInspectable const&,+ mux::Input::PointerRoutedEventArgs const& e)+ {+ if (!logResizing_) return;+ auto pt = e.GetCurrentPoint(this->try_as<mux::UIElement>());+ // Dragging UP grows the panel (delta is negative).+ double delta = pt.Position().Y - logResizeStartY_;+ double h = logResizeStartHeight_ - delta;+ if (h < 60.0) h = 60.0;+ if (h > 600.0) h = 600.0;+ QueryLogPanel().Height(h);+ e.Handled(true);+ });+ QueryLogResizer().PointerReleased(+ [this](winrt::Windows::Foundation::IInspectable const& sender,+ mux::Input::PointerRoutedEventArgs const& e)+ {+ if (logResizing_)+ {+ logResizing_ = false;+ if (auto el = sender.try_as<mux::UIElement>())+ el.ReleasePointerCapture(e.Pointer());+ }+ e.Handled(true);+ });+ }++ // ── Connection Setup ────────────────────────────────++ void WorkspacePage::SetConnection(const DBModels::ConnectionConfig& config, const std::wstring& password)+ {+ state_.connection = config;+ pendingPassword_ = password;+ hasConnection_ = true;++ state_.statusConnection = config.username + L"@" + config.host ++ L":" + std::to_wstring(config.port);+ state_.statusSchema = currentSchema_;++ // Remember this connection at process scope so a freshly+ // re-constructed WorkspacePage (e.g. after returning from+ // Settings) can auto-restore it instead of showing demo data.+ sLastConfig_ = config;+ sLastPassword_ = password;+ sHasLastConnection_ = true;++ if (isLoaded_)+ InitializeConnection();+ }++ void WorkspacePage::InitializeConnection()+ {+ auto& config = state_.connection;++ // Redis uses integer logical DBs (0..15) with a "db<N>" display+ // label. If the user pasted a non-numeric name like "app_db" into+ // the database field (common for people copying a SQL connection+ // config), Redis falls back to SELECT 0 -- but the stale label+ // stays visible in the top-left DbPickerText. Normalize before+ // anything else so the rest of InitializeConnection sees a+ // consistent "db<N>" identifier.+ if (config.databaseType == DBModels::DatabaseType::Redis)+ {+ int dbIdx = 0;+ if (!config.database.empty())+ {+ // Accept both "5" and "db5" forms; default to 0 otherwise.+ std::wstring d = config.database;+ if (d.size() > 2 && d[0] == L'd' && d[1] == L'b')+ d = d.substr(2);+ try { dbIdx = std::stoi(d); } catch (...) { dbIdx = 0; }+ }+ std::wstring label = L"db" + std::to_wstring(dbIdx);+ state_.connection.database = label;+ currentSchema_ = label;+ state_.statusSchema = label;+ }+ // MongoDB: don't pre-set config.database here — the adapter+ // will extract it from the URI during connect(). Setting it+ // to "test" here pollutes config.database which the adapter+ // reads first (priority 1), bypassing the URI parse. The+ // post-connect sync block below reads adapter->currentDatabase()+ // and updates currentSchema_ + config.database correctly.+ else if (config.databaseType == DBModels::DatabaseType::MongoDB)+ {+ // Only set if user explicitly typed a database name in the form+ if (!config.database.empty())+ {+ currentSchema_ = config.database;+ state_.statusSchema = config.database;+ }+ }+ // SQL Server: default schema is "dbo", not "public"+ else if (config.databaseType == DBModels::DatabaseType::MSSQLServer)+ {+ currentSchema_ = L"dbo";+ state_.statusSchema = L"dbo";+ }+ // MySQL: schema = database name (MySQL has no separate schema concept)+ else if (config.databaseType == DBModels::DatabaseType::MySQL)+ {+ if (!config.database.empty())+ {+ currentSchema_ = config.database;+ state_.statusSchema = config.database;+ }+ }++ UpdateBreadcrumb();++ if (!config.database.empty())+ DbPickerText().Text(winrt::hstring(config.database));++ try+ {+ connMgr_.connect(config, pendingPassword_);++ // MongoDB only: re-read the actual database name from the+ // adapter. The database may have been specified inside the+ // URI while config.database was left empty. Other DB types+ // (PostgreSQL, MySQL, SQLite, Redis) use currentSchema_ for+ // schema names (e.g. "public"), NOT database names — syncing+ // here would overwrite "public" with the database name and+ // break listTables.+ if (config.databaseType == DBModels::DatabaseType::MongoDB)+ {+ auto adapter = connMgr_.getActiveAdapter();+ if (adapter)+ {+ auto actualDb = adapter->currentDatabase();+ if (!actualDb.empty())+ {+ currentSchema_ = actualDb;+ state_.statusSchema = actualDb;+ if (config.database.empty())+ state_.connection.database = actualDb;+ DbPickerText().Text(winrt::hstring(actualDb));+ }+ }+ }++ // Tell sidebar the active DB type so context menus render correctly+ // (Redis gets Browse Keys / Flush DB; SQL gets Open / Export / Import)+ Sidebar().as<SidebarPanel>()->SetDatabaseType(config.databaseType);++ // Redis does not support SQL-style row updates -- inline edits+ // would silently overwrite hash / list / set values via SET+ // and corrupt the data. Flip the grid + details pane into+ // read-only mode for Redis connections so users can inspect+ // values freely but cannot accidentally destroy them. SQL+ // adapters stay editable as before.+ const bool isRedis =+ config.databaseType == DBModels::DatabaseType::Redis;+ DataGrid().as<DataGridView>()->SetReadOnly(isRedis);+ Details().as<DetailsPanel>()->SetReadOnly(isRedis);++ LoadSidebarFromDB();+ LoadDatabasePicker();++ auto adapter = connMgr_.getActiveAdapter();+ if (adapter)+ {+ auto ver = adapter->serverVersion();+ state_.statusConnection = config.username + L"@" + config.host ++ L":" + std::to_wstring(config.port) + L" (" ++ DBModels::DatabaseTypeDisplayName(config.databaseType) + L" " + ver + L")";++ // Load schemas into sidebar picker+ try+ {+ auto schemas = adapter->listSchemas();+ Sidebar().as<SidebarPanel>()->SetSchemas(schemas);+ }+ catch (...) {}+ }++ StatusBar().as<StatusBarControl>()->SetStatus(+ state_.statusConnection, state_.statusSchema, 0, 0.0, 0.0);+ }+ catch (const std::exception& ex)+ {+ std::string what = ex.what();+ int sz = MultiByteToWideChar(CP_UTF8, 0, what.c_str(), (int)what.size(), nullptr, 0);+ std::wstring errMsg(sz, L'\0');+ MultiByteToWideChar(CP_UTF8, 0, what.c_str(), (int)what.size(), &errMsg[0], sz);+ muxc::ContentDialog errDialog;+ errDialog.Title(winrt::box_value(winrt::hstring(L"Connection Failed")));+ errDialog.Content(winrt::box_value(winrt::hstring(+ L"Could not connect to " + config.name + L":\n\n" + errMsg)));+ errDialog.CloseButtonText(L"OK");+ errDialog.XamlRoot(this->XamlRoot());+ errDialog.ShowAsync();++ LoadDemoSidebarData();+ StatusBar().as<StatusBarControl>()->SetStatus(+ L"Disconnected", L"--", 0, 0.0, 0.0);+ }+ }++ // ── Sidebar Data Loading ────────────────────────────++ void WorkspacePage::LoadSidebarFromDB()+ {+ auto adapter = connMgr_.getActiveAdapter();+ if (!adapter) { LoadDemoSidebarData(); return; }++ try+ {+ // Query each independently — one failure shouldn't block others+ std::vector<std::wstring> funcs;+ std::vector<DBModels::TableInfo> tables;+ std::vector<DBModels::TableInfo> views;+ try { funcs = adapter->listFunctions(currentSchema_); } catch (...) {}+ try { tables = adapter->listTables(currentSchema_); } catch (...) {}+ try { views = adapter->listViews(currentSchema_); } catch (...) {}++ // Build sidebar groups — always show all 3 groups (like macOS version)+ state_.sidebarItems.clear();++ // Functions group (always shown). SQL Server includes stored+ // procedures here too, so label it "Routines" for clarity.+ {+ DBModels::SidebarItem g;+ g.id = L"functions";+ g.title = (state_.connection.databaseType == DBModels::DatabaseType::MSSQLServer)+ ? L"Routines" : L"Functions";+ g.type = DBModels::SidebarItemType::Group;+ g.isExpanded = !funcs.empty(); // auto-expand if there are items+ for (auto& name : funcs)+ {+ DBModels::SidebarItem item;+ item.id = std::wstring(L"fn_") + name; item.title = name;+ item.type = DBModels::SidebarItemType::Function; item.schema = currentSchema_;+ g.children.push_back(item);+ }+ g.count = static_cast<int>(funcs.size());+ state_.sidebarItems.push_back(g);+ }++ // Tables group (always shown, expanded by default)+ {+ DBModels::SidebarItem g;+ g.id = L"tables"; g.title = L"Tables";+ g.type = DBModels::SidebarItemType::Group; g.isExpanded = true;+ for (auto& tbl : tables)+ {+ DBModels::SidebarItem item;+ item.id = tbl.name; item.title = tbl.name;+ item.type = DBModels::SidebarItemType::Table; item.schema = currentSchema_;+ g.children.push_back(item);+ }+ g.count = static_cast<int>(tables.size());+ state_.sidebarItems.push_back(g);+ }++ // Views group (always shown)+ {+ DBModels::SidebarItem g;+ g.id = L"views"; g.title = L"Views";+ g.type = DBModels::SidebarItemType::Group; g.isExpanded = false;+ for (auto& v : views)+ {+ DBModels::SidebarItem item;+ item.id = v.name; item.title = v.name;+ item.type = DBModels::SidebarItemType::View; item.schema = currentSchema_;+ g.children.push_back(item);+ }+ g.count = static_cast<int>(views.size());+ state_.sidebarItems.push_back(g);+ }++ Sidebar().as<SidebarPanel>()->SetItems(state_.sidebarItems);+ Sidebar().as<SidebarPanel>()->OnItemSelected = [this](const std::wstring& name, const std::wstring& schema)+ {+ OnTableSelected(name, schema);+ };++ // Feed table/function names to query editor autocomplete+ {+ std::vector<std::wstring> tableNames, funcNames;+ for (auto& tbl : tables) tableNames.push_back(tbl.name);+ for (auto& v : views) tableNames.push_back(v.name);+ funcNames = funcs;+ // Columns will be added per-table when table data loads+ QueryEditor().as<QueryEditorView>()->SetSchemaCompletions(+ tableNames, {}, funcNames);+ }+ }+ catch (const std::exception&)+ {+ LoadDemoSidebarData();+ }+ }++ void WorkspacePage::LoadTableDataFromDB(const std::wstring& tableName)+ {+ // Show the loader on the UI thread, then push the actual DB work+ // onto a background std::thread. Previously the "heavy" work ran+ // inside a Low-priority TryEnqueue lambda which is STILL the UI+ // thread — the ProgressRing had no frames to animate and the+ // overlay often never even reached the screen before fetchRows+ // blocked for seconds. Moving fetchRows / describeTable /+ // listIndexes / listForeignKeys off the UI thread lets the+ // loader actually render and keeps the window responsive.+ DataLoadingOverlay().Visibility(mux::Visibility::Visible);++ auto adapter = connMgr_.getActiveAdapter();+ if (!adapter)+ {+ LoadDemoTableData(tableName);+ DataLoadingOverlay().Visibility(mux::Visibility::Collapsed);+ return;+ }++ // Snapshot the inputs on the UI thread — `state_` and `currentSchema_`+ // must not be read from the background thread.+ const std::wstring schema = currentSchema_;+ const int pageSize = state_.pageSize;+ const int offset = state_.currentPage * state_.pageSize;+ const uint64_t requestId = ++loadTableRequestCounter_;++ auto dispatcher = this->DispatcherQueue();+ auto weakSelf = get_weak();++ // Results package marshaled from worker → UI thread. shared_ptr+ // so the std::function copy inside TryEnqueue stays cheap.+ struct LoadResult+ {+ bool ok = false;+ std::wstring error;+ DBModels::QueryResult data;+ std::vector<DBModels::ColumnInfo> cols;+ std::vector<DBModels::IndexInfo> idx;+ std::vector<DBModels::ForeignKeyInfo> fks;+ };++ std::thread([weakSelf, dispatcher, adapter, tableName, schema,+ pageSize, offset, requestId]() mutable+ {+ auto result = std::make_shared<LoadResult>();+ try+ {+ result->data = adapter->fetchRows(tableName, schema, pageSize, offset);+ result->cols = adapter->describeTable(tableName, schema);+ result->idx = adapter->listIndexes(tableName, schema);+ result->fks = adapter->listForeignKeys(tableName, schema);+ result->ok = true;+ }+ catch (const std::exception& e)+ {+ result->ok = false;+ // std::exception::what() is narrow; widen for the log /+ // future error UI. ASCII-only paths are the common case.+ const std::string w = e.what();+ result->error.assign(w.begin(), w.end());+ }+ catch (...)+ {+ result->ok = false;+ result->error = L"Unknown error loading table";+ }++ // Marshal back to UI thread.+ dispatcher.TryEnqueue([weakSelf, tableName, requestId, result]() mutable+ {+ auto self = weakSelf.get();+ if (!self) return;++ // Drop stale results: user clicked another table while+ // this query was in flight. The latest request always+ // wins; earlier ones just vanish silently.+ if (requestId != self->loadTableRequestCounter_) return;++ auto hideOverlay = [self]()+ {+ self->DataLoadingOverlay().Visibility(mux::Visibility::Collapsed);+ };++ if (!result->ok)+ {+ self->LoadDemoTableData(tableName);+ hideOverlay();+ return;+ }++ self->state_.currentData = std::move(result->data);+ self->state_.currentColumns = std::move(result->cols);+ self->state_.currentIndexes = std::move(result->idx);+ self->state_.currentForeignKeys = std::move(result->fks);+ self->state_.currentConstraints.clear();++ self->state_.statusRowCount = self->state_.currentData.totalRows;+ self->state_.statusQueryTimeMs = self->state_.currentData.executionTimeMs;++ // Measure the UI build cost separately from the driver+ // call time already reported by the adapter. Split is+ // shown as "Exec · Render" in the status bar + query log+ // so wide-table slowness is attributed to the right+ // layer instead of lumped under a single number.+ auto renderStart = std::chrono::steady_clock::now();+ self->DataGrid().as<DataGridView>()->SetData(self->state_.currentData);+ auto renderEnd = std::chrono::steady_clock::now();+ self->state_.statusRenderTimeMs =+ std::chrono::duration<double, std::milli>(renderEnd - renderStart).count();++ // Log after render so the entry carries both timings.+ self->LogQuery(self->state_.currentData, self->state_.statusRenderTimeMs);++ self->Structure().as<StructureView>()->SetTableContext(+ tableName, self->currentSchema_, self->state_.connection.databaseType);+ self->Structure().as<StructureView>()->SetData(+ self->state_.currentColumns, self->state_.currentIndexes,+ self->state_.currentForeignKeys, self->state_.currentConstraints);+ self->StatusBar().as<StatusBarControl>()->SetStatus(+ self->state_.statusConnection, self->state_.statusSchema,+ self->state_.statusRowCount,+ self->state_.statusQueryTimeMs,+ self->state_.statusRenderTimeMs);+ self->UpdatePaginationUI();++ self->FilterBarControl().as<FilterBar>()->SetColumns(+ self->state_.currentData.columnNames);++ // Update query editor autocomplete with column names from+ // the current table + sidebar-derived table/function lists.+ {+ std::vector<std::wstring> tblNames, colNames, fnNames;+ for (auto& group : self->state_.sidebarItems)+ for (auto& item : group.children)+ {+ if (group.id == L"tables" || group.id == L"views")+ tblNames.push_back(item.title);+ else if (group.id == L"functions")+ fnNames.push_back(item.title);+ }+ colNames = self->state_.currentData.columnNames;+ self->QueryEditor().as<QueryEditorView>()->SetSchemaCompletions(+ tblNames, colNames, fnNames);+ }++ self->SaveCurrentTabCache();+ hideOverlay();+ });+ }).detach();+ }++ // ── Content Navigation ──────────────────────────────++ void WorkspacePage::UpdateBreadcrumb()+ {+ auto& conn = state_.connection;+ ConnectionNameText().Text(winrt::hstring(conn.name));++ std::wstring info = DBModels::DatabaseTypeDisplayName(conn.databaseType);+ if (!conn.username.empty()) info += L" : " + conn.username;+ if (!conn.database.empty()) info += L" : " + conn.database;+ ConnectionInfoText().Text(winrt::hstring(info));++ if (conn.colorTag.has_value())+ {+ auto& tagInfo = DBModels::GetColorTagInfo(conn.colorTag.value());+ auto color = winrt::Windows::UI::ColorHelper::FromArgb(255, tagInfo.r, tagInfo.g, tagInfo.b);+ ConnectionDot().Fill(muxm::SolidColorBrush(color));+ }+ else+ {+ ConnectionDot().Fill(muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(255, 128, 128, 128)));+ }+ }++ void WorkspacePage::ToggleSidebar_Click(+ winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ sidebarVisible_ = !sidebarVisible_;+ SidebarColumn().Width(sidebarVisible_+ ? mux::GridLengthHelper::FromPixels(280)+ : mux::GridLengthHelper::FromPixels(0));+ Sidebar().Visibility(sidebarVisible_ ? mux::Visibility::Visible : mux::Visibility::Collapsed);+ }++ void WorkspacePage::ToggleDetails_Click(+ winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ detailsVisible_ = !detailsVisible_;+ DetailsColumn().Width(detailsVisible_+ ? mux::GridLengthHelper::FromPixels(260)+ : mux::GridLengthHelper::FromPixels(0));+ Details().Visibility(detailsVisible_ ? mux::Visibility::Visible : mux::Visibility::Collapsed);+ }++ void WorkspacePage::DataToggle_Click(+ winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ showingData_ = true;+ DataToggle().IsChecked(true);+ StructureToggle().IsChecked(false);+ SwitchContentView();+ }++ void WorkspacePage::StructureToggle_Click(+ winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ showingData_ = false;+ DataToggle().IsChecked(false);+ StructureToggle().IsChecked(true);+ SwitchContentView();+ }++ void WorkspacePage::SwitchContentView()+ {+ if (state_.tabs.empty())+ {+ EmptyContentState().Visibility(mux::Visibility::Visible);+ DataGrid().Visibility(mux::Visibility::Collapsed);+ Structure().Visibility(mux::Visibility::Collapsed);+ QueryEditor().Visibility(mux::Visibility::Collapsed);+ ERDiagramView().Visibility(mux::Visibility::Collapsed);+ return;+ }++ EmptyContentState().Visibility(mux::Visibility::Collapsed);++ DBModels::TabType activeType = DBModels::TabType::DataGrid;+ for (auto& tab : state_.tabs)+ if (tab.id == state_.activeTabId) { activeType = tab.type; break; }++ if (activeType == DBModels::TabType::ERDiagram)+ {+ DataGrid().Visibility(mux::Visibility::Collapsed);+ Structure().Visibility(mux::Visibility::Collapsed);+ QueryEditor().Visibility(mux::Visibility::Collapsed);+ ERDiagramView().Visibility(mux::Visibility::Visible);+ }+ else if (activeType == DBModels::TabType::QueryEditor)+ {+ DataGrid().Visibility(mux::Visibility::Collapsed);+ Structure().Visibility(mux::Visibility::Collapsed);+ QueryEditor().Visibility(mux::Visibility::Visible);+ ERDiagramView().Visibility(mux::Visibility::Collapsed);+ }+ else if (showingData_)+ {+ DataGrid().Visibility(mux::Visibility::Visible);+ Structure().Visibility(mux::Visibility::Collapsed);+ QueryEditor().Visibility(mux::Visibility::Collapsed);+ ERDiagramView().Visibility(mux::Visibility::Collapsed);+ }+ else+ {+ DataGrid().Visibility(mux::Visibility::Collapsed);+ Structure().Visibility(mux::Visibility::Visible);+ QueryEditor().Visibility(mux::Visibility::Collapsed);+ ERDiagramView().Visibility(mux::Visibility::Collapsed);+ }+ }++ void WorkspacePage::ToggleFilter_Click(+ winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ filterVisible_ = !filterVisible_;+ FilterBarControl().Visibility(filterVisible_ ? mux::Visibility::Visible : mux::Visibility::Collapsed);+ }++ void WorkspacePage::ToggleAI_Click(+ winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ if (!detailsVisible_)+ {+ detailsVisible_ = true;+ DetailsColumn().Width(mux::GridLengthHelper::FromPixels(260));+ Details().Visibility(mux::Visibility::Visible);+ }+ Details().as<DetailsPanel>()->AssistantTab_Click(nullptr, {});+ }++ void WorkspacePage::OnTableSelected(const std::wstring& tableName, const std::wstring& schema)+ {+ // Discard pending changes when switching tables+ if (changeTracker_.hasChanges())+ {+ changeTracker_.discardAll();+ UpdatePendingUI();+ }++ // Reuse existing tab+ for (auto& tab : state_.tabs)+ {+ if (tab.tableName == tableName && tab.schema == schema && tab.type == DBModels::TabType::DataGrid)+ {+ state_.activeTabId = tab.id;+ TabBar().as<TabBarControl>()->SetActiveTab(winrt::hstring(tab.id));+ state_.currentPage = 0;+ if (connMgr_.isConnected())+ LoadTableDataFromDB(tableName);+ else+ LoadDemoTableData(tableName);+ SwitchContentView();+ return;+ }+ }++ // Create new tab+ GUID guid;+ CoCreateGuid(&guid);+ wchar_t guidStr[40];+ StringFromGUID2(guid, guidStr, 40);++ DBModels::ContentTab tab;+ tab.id = guidStr;+ tab.type = DBModels::TabType::DataGrid;+ tab.title = tableName;+ tab.tableName = tableName;+ tab.schema = schema;+ tab.databaseName = state_.connection.database;++ state_.tabs.push_back(tab);+ state_.activeTabId = tab.id;+ state_.currentPage = 0;+ TabBar().as<TabBarControl>()->AddTab(winrt::hstring(tab.id), winrt::hstring(tab.title));+ TabBar().as<TabBarControl>()->SetActiveTab(winrt::hstring(tab.id));++ if (connMgr_.isConnected())+ LoadTableDataFromDB(tableName);+ else+ LoadDemoTableData(tableName);+ showingData_ = true;+ DataToggle().IsChecked(true);+ StructureToggle().IsChecked(false);+ SwitchContentView();+ }++ void WorkspacePage::OpenNewQueryTab()+ {+ // Save the outgoing tab's state (SQL text for a query tab, grid+ // data for a DataGrid tab) before we change activeTabId. Without+ // this the old tab's content is lost and the new empty tab shows+ // the previous tab's SQL.+ SaveCurrentTabCache();++ GUID guid;+ CoCreateGuid(&guid);+ wchar_t guidStr[40];+ StringFromGUID2(guid, guidStr, 40);++ DBModels::ContentTab tab;+ tab.id = guidStr;+ tab.type = DBModels::TabType::QueryEditor;+ tab.title = L"Query";+ tab.databaseName = state_.connection.database;++ state_.tabs.push_back(tab);+ state_.activeTabId = tab.id;+ TabBar().as<TabBarControl>()->AddTab(winrt::hstring(tab.id), winrt::hstring(tab.title));+ TabBar().as<TabBarControl>()->SetActiveTab(winrt::hstring(tab.id));++ // Clear the shared QueryEditorView for the fresh tab — otherwise+ // it still holds whatever text was typed in the previous tab.+ QueryEditor().as<QueryEditorView>()->SetSql(L"");++ SwitchContentView();+ }++ // ── CRUD Operations ─────────────────────────────────++ DBModels::TableRow WorkspacePage::ExtractPrimaryKey(int rowIndex)+ {+ DBModels::TableRow pk;+ if (rowIndex < 0 || rowIndex >= static_cast<int>(state_.currentData.rows.size()))+ return pk;++ auto& row = state_.currentData.rows[rowIndex];+ for (auto& col : state_.currentColumns)+ {+ if (col.isPrimaryKey)+ {+ auto it = row.find(col.name);+ if (it != row.end())+ pk[col.name] = it->second;+ }+ }+ return pk;+ }++ void WorkspacePage::DeleteSelectedRow()+ {+ int idx = DataGrid().as<DataGridView>()->GetSelectedRowIndex();+ if (idx < 0)+ {+ // No row selected — show tip+ return;+ }++ // Check if row is already marked for deletion+ auto deleted = changeTracker_.deletedRowIndices();+ if (deleted.count(idx)) return;++ auto pk = ExtractPrimaryKey(idx);+ if (pk.empty())+ {+ muxc::ContentDialog dlg;+ dlg.Title(winrt::box_value(winrt::hstring(L"Cannot Delete")));+ dlg.Content(winrt::box_value(winrt::hstring(L"This table has no primary key. Cannot identify row for deletion.")));+ dlg.CloseButtonText(L"OK");+ dlg.XamlRoot(this->XamlRoot());+ dlg.ShowAsync();+ return;+ }++ changeTracker_.trackDelete(idx, pk);+ DataGrid().as<DataGridView>()->MarkRowDeleted(idx);+ UpdatePendingUI();+ }++ // Check if a default value is a SQL expression (not a literal)+ static bool IsSqlExpression(const std::wstring& val)+ {+ if (val.empty()) return false;+ // Functions: gen_random_uuid(), now(), nextval('seq'), uuid_generate_v4()+ if (val.find(L"(") != std::wstring::npos) return true;+ // Keywords: CURRENT_TIMESTAMP, CURRENT_DATE, CURRENT_USER+ if (val.find(L"CURRENT_") != std::wstring::npos) return true;+ if (val == L"true" || val == L"false") return false; // boolean literals are OK+ return false;+ }++ void WorkspacePage::AddNewRow()+ {+ if (state_.currentColumns.empty()) return;++ // Build empty row — skip columns with SQL expression defaults (let DB handle)+ DBModels::TableRow newRow;+ for (auto& col : state_.currentColumns)+ {+ // MSSQL IDENTITY columns: server auto-generates the value,+ // including them in INSERT causes "Cannot insert explicit+ // value for identity column" error.+ if (col.comment == L"IDENTITY")+ continue;+ if (col.isPrimaryKey && IsSqlExpression(col.defaultValue))+ continue; // PK with auto-gen default — omit from INSERT+ if (IsSqlExpression(col.defaultValue))+ continue; // DB will generate: now(), nextval(), etc.+ if (!col.defaultValue.empty() && col.defaultValue != L"NULL")+ newRow[col.name] = col.defaultValue; // static default like '0', 'active'+ else if (col.nullable)+ newRow[col.name] = L"NULL";+ else+ newRow[col.name] = L""; // required column, user must fill+ }++ // Build display row (for grid) — include auto-gen placeholders+ DBModels::TableRow displayRow = newRow;+ for (auto& col : state_.currentColumns)+ {+ if (displayRow.find(col.name) == displayRow.end())+ displayRow[col.name] = col.defaultValue; // show e.g. "gen_random_uuid()"+ }++ state_.currentData.rows.push_back(displayRow);+ int newRowIndex = static_cast<int>(state_.currentData.rows.size()) - 1;+ changeTracker_.trackInsert(newRow, newRowIndex); // INSERT only has user-editable columns+ DataGrid().as<DataGridView>()->SetData(state_.currentData);+ UpdatePendingUI();+ }++ void WorkspacePage::CommitChanges()+ {+ if (!changeTracker_.hasChanges()) return;+ if (!connMgr_.isConnected()) return;++ // Find active table+ std::wstring tableName, schema;+ for (auto& tab : state_.tabs)+ {+ if (tab.id == state_.activeTabId && tab.type == DBModels::TabType::DataGrid)+ {+ tableName = tab.tableName;+ schema = tab.schema;+ break;+ }+ }+ if (tableName.empty()) return;++ const bool isMongo =+ state_.connection.databaseType == DBModels::DatabaseType::MongoDB;++ // MongoDB doesn't use SQL. Build a human-readable preview+ // for SQL adapters; for MongoDB just summarize the operations.+ std::wstring preview;+ std::vector<std::wstring> statements;+ if (!isMongo)+ {+ statements = changeTracker_.generateSQL(+ tableName, schema, state_.connection.databaseType);+ if (statements.empty()) return;+ preview = std::to_wstring(statements.size()) + L" statement(s):\n\n";+ for (auto& s : statements) preview += s + L"\n";+ }+ else+ {+ auto& edits = changeTracker_.pendingEdits();+ int ins = 0, upd = 0, del = 0;+ for (auto& e : edits)+ {+ if (e.type == DBModels::EditType::Insert) ++ins;+ else if (e.type == DBModels::EditType::Update) ++upd;+ else if (e.type == DBModels::EditType::Delete) ++del;+ }+ preview = L"MongoDB operations on " + tableName + L":\n";+ if (ins) preview += L" Insert: " + std::to_wstring(ins) + L" document(s)\n";+ if (upd) preview += L" Update: " + std::to_wstring(upd) + L" field(s)\n";+ if (del) preview += L" Delete: " + std::to_wstring(del) + L" document(s)\n";+ }++ // Show confirmation dialog+ muxc::ContentDialog dlg;+ dlg.Title(winrt::box_value(winrt::hstring(L"Commit Changes")));++ muxc::ScrollViewer sv;+ sv.MaxHeight(300);+ muxc::TextBlock tb;+ tb.Text(winrt::hstring(preview));+ tb.FontFamily(mux::Media::FontFamily(L"Cascadia Code,Consolas,monospace"));+ tb.FontSize(12);+ tb.IsTextSelectionEnabled(true);+ tb.TextWrapping(mux::TextWrapping::Wrap);+ sv.Content(tb);+ dlg.Content(sv);++ dlg.PrimaryButtonText(L"Execute");+ dlg.CloseButtonText(L"Cancel");+ dlg.DefaultButton(muxc::ContentDialogButton::Primary);+ dlg.XamlRoot(this->XamlRoot());++ auto op = dlg.ShowAsync();+ op.Completed([this, statements, tableName, schema, isMongo](auto&& asyncOp, auto&&)+ {+ auto result = asyncOp.GetResults();+ if (result != muxc::ContentDialogResult::Primary) return;++ this->DispatcherQueue().TryEnqueue([this, statements, tableName, schema, isMongo]()+ {+ auto adapter = connMgr_.getActiveAdapter();+ if (!adapter) return;++ try+ {+ if (isMongo)+ {+ // MongoDB: call adapter CRUD methods directly+ for (auto& edit : changeTracker_.pendingEdits())+ {+ if (edit.type == DBModels::EditType::Insert)+ adapter->insertRow(tableName, schema, edit.insertValues);+ else if (edit.type == DBModels::EditType::Update)+ {+ DBModels::TableRow setVals;+ setVals[edit.column] = edit.newValue;+ adapter->updateRow(tableName, schema, setVals, edit.primaryKey);+ }+ else if (edit.type == DBModels::EditType::Delete)+ adapter->deleteRow(tableName, schema, edit.primaryKey);+ }+ }+ else+ {+ // SQL adapters: execute generated SQL in a transaction+ adapter->beginTransaction();+ for (auto& sql : statements)+ {+ auto r = adapter->execute(sql);+ LogQuery(r);+ if (!r.success)+ {+ adapter->rollbackTransaction();+ muxc::ContentDialog errDlg;+ errDlg.Title(winrt::box_value(winrt::hstring(L"Commit Failed")));+ errDlg.Content(winrt::box_value(winrt::hstring(r.error)));+ errDlg.CloseButtonText(L"OK");+ errDlg.XamlRoot(this->XamlRoot());+ errDlg.ShowAsync();+ return;+ }+ }+ adapter->commitTransaction();+ }++ changeTracker_.discardAll();+ ReloadCurrentTable();+ UpdatePendingUI();+ }+ catch (const std::exception& ex)+ {+ if (!isMongo) try { adapter->rollbackTransaction(); } catch (...) {}++ int sz = MultiByteToWideChar(CP_UTF8, 0, ex.what(), -1, nullptr, 0);+ std::wstring msg(sz, L'\0');+ MultiByteToWideChar(CP_UTF8, 0, ex.what(), -1, &msg[0], sz);++ muxc::ContentDialog errDlg;+ errDlg.Title(winrt::box_value(winrt::hstring(L"Commit Error")));+ errDlg.Content(winrt::box_value(winrt::hstring(msg)));+ errDlg.CloseButtonText(L"OK");+ errDlg.XamlRoot(this->XamlRoot());+ errDlg.ShowAsync();+ }+ });+ });+ }++ void WorkspacePage::DiscardChanges()+ {+ changeTracker_.discardAll();+ DataGrid().as<DataGridView>()->ClearRowMarks();+ ReloadCurrentTable();+ UpdatePendingUI();+ }++ // ── Pagination ──────────────────────────────────────++ void WorkspacePage::PrevPage()+ {+ if (state_.currentPage <= 0) return;+ state_.currentPage--;+ LoadCurrentTablePage(state_.currentPage);+ }++ void WorkspacePage::NextPage()+ {+ int totalPages = state_.currentData.totalPages();+ if (state_.currentPage + 1 >= totalPages) return;+ state_.currentPage++;+ LoadCurrentTablePage(state_.currentPage);+ }++ void WorkspacePage::LoadCurrentTablePage(int page)+ {+ state_.currentPage = page;+ for (auto& tab : state_.tabs)+ {+ if (tab.id == state_.activeTabId && tab.type == DBModels::TabType::DataGrid)+ {+ if (connMgr_.isConnected())+ LoadTableDataFromDB(tab.tableName);+ else+ LoadDemoTableData(tab.tableName);+ break;+ }+ }+ }++ void WorkspacePage::UpdatePaginationUI()+ {+ int start = state_.currentPage * state_.pageSize + 1;+ int end = start + static_cast<int>(state_.currentData.rows.size()) - 1;+ int total = state_.currentData.totalRows;++ if (total == 0)+ {+ PaginationText().Text(L"0 rows");+ }+ else+ {+ PaginationText().Text(winrt::hstring(+ std::to_wstring(start) + L"-" + std::to_wstring(end) ++ L" of " + std::to_wstring(total) + L" rows"));+ }++ PrevPageBtn().IsEnabled(state_.currentPage > 0);+ NextPageBtn().IsEnabled(state_.currentPage + 1 < state_.currentData.totalPages());+ }++ // ── Database Picker ─────────────────────────────────++ void WorkspacePage::LoadDatabasePicker()+ {+ auto adapter = connMgr_.getActiveAdapter();+ if (!adapter) return;++ try+ {+ auto dbs = adapter->listDatabases();+ DbPickerFlyout().Items().Clear();++ for (auto& dbName : dbs)+ {+ muxc::MenuFlyoutItem item;+ item.Text(winrt::hstring(dbName));++ // Highlight current+ if (dbName == state_.connection.database)+ item.FontWeight(winrt::Windows::UI::Text::FontWeights::Bold());++ item.Click([this, dbName](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ SwitchDatabase(dbName);+ });++ DbPickerFlyout().Items().Append(item);+ }+ }+ catch (...) {}+ }++ void WorkspacePage::SwitchDatabase(const std::wstring& dbName)+ {+ if (dbName == state_.connection.database) return;++ // Discard any pending changes+ if (changeTracker_.hasChanges())+ {+ changeTracker_.discardAll();+ UpdatePendingUI();+ }++ state_.connection.database = dbName;+ DbPickerText().Text(winrt::hstring(dbName));++ auto adapter = connMgr_.getActiveAdapter();+ if (!adapter) return;++ try+ {+ // Redis: logical DBs live on the same connection. No reconnect+ // needed. The adapter's fetchRows / listTables already issue a+ // SELECT <n> based on the schema parameter, so we just route+ // the new dbName through currentSchema_ and rebuild the sidebar+ // + reload the active tab. Without this path, listTables kept+ // reading currentSchema_ ("public" from the header default)+ // and the key list never actually changed when the user+ // flipped between db0 / db1 / db2 / ...+ if (state_.connection.databaseType == DBModels::DatabaseType::Redis)+ {+ currentSchema_ = dbName;+ state_.statusSchema = dbName;++ LoadSidebarFromDB();+ LoadDatabasePicker();+ UpdateBreadcrumb();++ // Reload the active DataGrid tab (if any) against the new DB+ for (auto& tab : state_.tabs)+ {+ if (tab.id == state_.activeTabId &&+ tab.type == DBModels::TabType::DataGrid)+ {+ tab.schema = dbName;+ LoadTableDataFromDB(tab.tableName);+ break;+ }+ }+ return;+ }++ // MongoDB: no reconnect needed — just update the adapter's+ // internal database name and reload the sidebar. MongoDB+ // connections are server-wide (not database-scoped).+ if (state_.connection.databaseType == DBModels::DatabaseType::MongoDB)+ {+ currentSchema_ = dbName;+ state_.statusSchema = dbName;++ LoadSidebarFromDB();+ LoadDatabasePicker();+ UpdateBreadcrumb();++ // Clear tabs since collections differ per database.+ // Snapshot tab IDs first to avoid iterator invalidation+ // (CloseTab fires OnTabClosed which erases from state_.tabs).+ std::vector<std::wstring> ids;+ for (auto& t : state_.tabs) ids.push_back(t.id);+ for (auto& id : ids)+ TabBar().as<TabBarControl>()->CloseTab(winrt::hstring(id));+ SwitchContentView();+ return;+ }++ // MySQL and SQL Server can switch with USE, PostgreSQL needs reconnect+ if (state_.connection.databaseType == DBModels::DatabaseType::MySQL)+ {+ adapter->execute(L"USE `" + dbName + L"`");+ }+ else if (state_.connection.databaseType == DBModels::DatabaseType::MSSQLServer)+ {+ adapter->execute(L"USE [" + dbName + L"]");+ }+ else+ {+ connMgr_.disconnect();+ connMgr_.connect(state_.connection, pendingPassword_);+ }++ LoadSidebarFromDB();+ LoadDatabasePicker();+ UpdateBreadcrumb();++ // Clear tabs+ state_.tabs.clear();+ state_.activeTabId.clear();+ // TabBar doesn't have a ClearAll, so rebuild later on table select+ }+ catch (const std::exception& ex)+ {+ std::string what = ex.what();+ int sz = MultiByteToWideChar(CP_UTF8, 0, what.c_str(), (int)what.size(), nullptr, 0);+ std::wstring errMsg(sz, L'\0');+ MultiByteToWideChar(CP_UTF8, 0, what.c_str(), (int)what.size(), &errMsg[0], sz);++ muxc::ContentDialog dlg;+ dlg.Title(winrt::box_value(winrt::hstring(L"Switch Failed")));+ dlg.Content(winrt::box_value(winrt::hstring(errMsg)));+ dlg.CloseButtonText(L"OK");+ dlg.XamlRoot(this->XamlRoot());+ dlg.ShowAsync();+ }+ }++ // ── Filter ──────────────────────────────────────────++ void WorkspacePage::ApplyFilter(const std::wstring& column, const std::wstring& op, const std::wstring& value)+ {+ if (!connMgr_.isConnected()) return;++ std::wstring tableName;+ for (auto& tab : state_.tabs)+ {+ if (tab.id == state_.activeTabId && tab.type == DBModels::TabType::DataGrid)+ {+ tableName = tab.tableName;+ break;+ }+ }+ if (tableName.empty()) return;++ // Build WHERE clause+ std::wstring where;+ std::wstring qCol = L"\"" + column + L"\"";+ if (state_.connection.databaseType == DBModels::DatabaseType::MySQL)+ qCol = L"`" + column + L"`";++ if (op == L"equals") where = qCol + L" = '" + value + L"'";+ else if (op == L"not equals") where = qCol + L" != '" + value + L"'";+ else if (op == L"contains") where = qCol + L" LIKE '%" + value + L"%'";+ else if (op == L"starts with") where = qCol + L" LIKE '" + value + L"%'";+ else if (op == L"ends with") where = qCol + L" LIKE '%" + value + L"'";+ else if (op == L"greater than") where = qCol + L" > '" + value + L"'";+ else if (op == L"less than") where = qCol + L" < '" + value + L"'";+ else if (op == L"is null") where = qCol + L" IS NULL";+ else if (op == L"is not null") where = qCol + L" IS NOT NULL";+ else where = qCol + L" = '" + value + L"'";++ // Build filtered query+ std::wstring schemaQ = (state_.connection.databaseType == DBModels::DatabaseType::MySQL)+ ? L"`" + currentSchema_ + L"`"+ : L"\"" + currentSchema_ + L"\"";+ std::wstring tableQ = (state_.connection.databaseType == DBModels::DatabaseType::MySQL)+ ? L"`" + tableName + L"`"+ : L"\"" + tableName + L"\"";++ std::wstring sql;+ if (state_.connection.databaseType == DBModels::DatabaseType::SQLite)+ sql = L"SELECT * FROM " + tableQ + L" WHERE " + where + L" LIMIT " + std::to_wstring(state_.pageSize);+ else+ sql = L"SELECT * FROM " + schemaQ + L"." + tableQ + L" WHERE " + where + L" LIMIT " + std::to_wstring(state_.pageSize);++ auto adapter = connMgr_.getActiveAdapter();+ if (!adapter) return;++ try+ {+ state_.currentData = adapter->execute(sql);++ auto renderStart = std::chrono::steady_clock::now();+ DataGrid().as<DataGridView>()->SetData(state_.currentData);+ auto renderEnd = std::chrono::steady_clock::now();+ state_.statusRenderTimeMs =+ std::chrono::duration<double, std::milli>(renderEnd - renderStart).count();+ state_.statusQueryTimeMs = state_.currentData.executionTimeMs;++ LogQuery(state_.currentData, state_.statusRenderTimeMs);++ StatusBar().as<StatusBarControl>()->SetStatus(+ state_.statusConnection, state_.statusSchema,+ state_.currentData.totalRows,+ state_.statusQueryTimeMs,+ state_.statusRenderTimeMs);+ UpdatePaginationUI();+ }+ catch (...) {}+ }++ // ── Query Log ───────────────────────────────────────++ void WorkspacePage::LogQuery(const DBModels::QueryResult& result, double renderTimeMs)+ {+ DBModels::QueryLogEntry entry;+ entry.sql = result.sql;+ entry.status = result.success ? L"success" : L"error";+ entry.rowCount = result.totalRows;+ entry.durationMs = result.executionTimeMs;+ entry.renderDurationMs = renderTimeMs;+ entry.timestamp = std::chrono::system_clock::now();+ entry.error = result.error;+ connMgr_.addQueryLog(entry);+ RefreshQueryLog();+ }++ void WorkspacePage::RefreshQueryLog()+ {+ QueryLogEntries().Children().Clear();++ auto& log = connMgr_.getQueryLog();+ // Show last 50 entries max+ int startIdx = static_cast<int>(log.size()) > 50 ? static_cast<int>(log.size()) - 50 : 0;++ for (int i = startIdx; i < static_cast<int>(log.size()); i++)+ {+ auto& entry = log[i];++ // Timestamp + duration line+ auto tt = std::chrono::system_clock::to_time_t(entry.timestamp);+ struct tm tm_buf;+ localtime_s(&tm_buf, &tt);+ wchar_t timeBuf[64];+ wcsftime(timeBuf, 64, L"%Y-%m-%d %H:%M:%S", &tm_buf);++ // Display format: "-- TS (Exec Nms · Render Nms)" when the+ // entry carries a render timing, else "-- TS (Nms)" for+ // pure metadata queries that never hit the data grid.+ std::wstring metaLine = std::wstring(L"-- ") + timeBuf + L" (";+ if (entry.renderDurationMs > 0.0)+ {+ metaLine += L"Exec " + std::to_wstring(static_cast<int>(entry.durationMs)) + L"ms";+ metaLine += L" \x00B7 ";+ metaLine += L"Render " + std::to_wstring(static_cast<int>(entry.renderDurationMs)) + L"ms";+ }+ else+ {+ metaLine += std::to_wstring(static_cast<int>(entry.durationMs)) + L"ms";+ }+ metaLine += L")";++ muxc::TextBlock metaTb;+ metaTb.Text(winrt::hstring(metaLine));+ metaTb.FontSize(11);+ metaTb.FontFamily(mux::Media::FontFamily(L"Cascadia Code,Consolas,monospace"));+ metaTb.IsTextSelectionEnabled(true);+ metaTb.Opacity(0.5);+ QueryLogEntries().Children().Append(metaTb);++ // SQL line+ if (!entry.sql.empty())+ {+ muxc::TextBlock sqlTb;+ sqlTb.Text(winrt::hstring(entry.sql));+ sqlTb.FontSize(12);+ sqlTb.FontFamily(mux::Media::FontFamily(L"Cascadia Code,Consolas,monospace"));+ sqlTb.IsTextSelectionEnabled(true);+ sqlTb.TextWrapping(mux::TextWrapping::Wrap);++ if (!entry.error.empty())+ sqlTb.Foreground(muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(255, 196, 43, 28)));++ QueryLogEntries().Children().Append(sqlTb);+ }++ // Error line+ if (!entry.error.empty())+ {+ muxc::TextBlock errTb;+ errTb.Text(winrt::hstring(L"-- ERROR: " + entry.error));+ errTb.FontSize(11);+ errTb.FontFamily(mux::Media::FontFamily(L"Cascadia Code,Consolas,monospace"));+ errTb.IsTextSelectionEnabled(true);+ errTb.Foreground(muxm::SolidColorBrush(+ winrt::Windows::UI::ColorHelper::FromArgb(255, 196, 43, 28)));+ errTb.Opacity(0.8);+ QueryLogEntries().Children().Append(errTb);+ }+ }++ // Auto-scroll to bottom+ QueryLogScroller().ChangeView(nullptr, QueryLogScroller().ExtentHeight(), nullptr);++ // Also update sidebar History tab+ auto& logEntries = connMgr_.getQueryLog();+ std::vector<std::pair<std::wstring, std::wstring>> historyItems;+ for (auto& entry : logEntries)+ {+ if (entry.sql.empty()) continue;+ auto tt = std::chrono::system_clock::to_time_t(entry.timestamp);+ struct tm tm_buf;+ localtime_s(&tm_buf, &tt);+ wchar_t timeBuf[64];+ wcsftime(timeBuf, 64, L"%H:%M:%S", &tm_buf);+ std::wstring ts = timeBuf;+ ts += L" (" + std::to_wstring(static_cast<int>(entry.durationMs)) + L"ms)";+ historyItems.push_back({ ts, entry.sql });+ }+ Sidebar().as<SidebarPanel>()->SetHistory(historyItems);+ }++ // ── Pending Changes UI ──────────────────────────────++ void WorkspacePage::UpdatePendingUI()+ {+ int count = changeTracker_.changeCount();+ if (count > 0)+ {+ PendingChangesPanel().Visibility(mux::Visibility::Visible);+ PendingCountText().Text(winrt::hstring(std::to_wstring(count) + L" pending"));+ }+ else+ {+ PendingChangesPanel().Visibility(mux::Visibility::Collapsed);+ }+ }++ // ── Import (async) ────────────────────────────────────++ winrt::fire_and_forget WorkspacePage::ImportDataAsync(+ std::wstring targetTable, std::wstring targetSchema)+ {+ auto showError = [this](const std::wstring& msg) -> winrt::fire_and_forget+ {+ muxc::ContentDialog d;+ d.Title(winrt::box_value(winrt::hstring(L"Import")));+ d.Content(winrt::box_value(winrt::hstring(msg)));+ d.CloseButtonText(L"OK");+ d.XamlRoot(this->XamlRoot());+ co_await d.ShowAsync();+ };++ if (!connMgr_.isConnected())+ {+ showError(L"Not connected to any database.");+ co_return;+ }+ auto adapter = connMgr_.getActiveAdapter();+ if (!adapter) co_return;++ if (targetTable.empty())+ {+ showError(L"No target table specified.");+ co_return;+ }++ // ── Pick file via new Windows App SDK Pickers (supports elevated) ──+ std::wstring filePath;+ bool pickerFailed = false;+ try+ {+ // Get WindowId from stored HWND (C interop function)+ winrt::Microsoft::UI::WindowId windowId{+ reinterpret_cast<uint64_t>(+ winrt::Gridex::implementation::App::MainHwnd) };++ // New Microsoft.Windows.Storage.Pickers API (WinAppSDK 1.8+)+ winrt::Microsoft::Windows::Storage::Pickers::FileOpenPicker picker(windowId);+ picker.FileTypeFilter().Append(L".csv");+ picker.FileTypeFilter().Append(L".json");+ picker.FileTypeFilter().Append(L".sql");++ auto pickedFile = co_await picker.PickSingleFileAsync();+ if (!pickedFile) co_return; // User cancelled+ filePath = std::wstring(pickedFile.Path());+ }+ catch (...)+ {+ pickerFailed = true;+ }++ // Fallback: manual path input if native picker crashed+ if (pickerFailed)+ {+ muxc::ContentDialog dlg;+ dlg.Title(winrt::box_value(winrt::hstring(+ L"Import into " + targetTable)));++ muxc::StackPanel panel;+ panel.Spacing(10.0);++ muxc::TextBlock lbl;+ lbl.Text(L"File path:");+ lbl.FontSize(12.0);+ lbl.Opacity(0.7);+ panel.Children().Append(lbl);++ muxc::TextBox pathBox;+ pathBox.PlaceholderText(L"C:\\Users\\...\\data.csv");+ pathBox.FontFamily(muxm::FontFamily(L"Cascadia Code,Consolas,monospace"));+ pathBox.FontSize(12.0);+ panel.Children().Append(pathBox);++ muxc::TextBlock hint;+ hint.Text(L"Supported: .csv, .json, .sql");+ hint.FontSize(11.0);+ hint.Opacity(0.4);+ panel.Children().Append(hint);++ dlg.Content(panel);+ dlg.PrimaryButtonText(L"Import");+ dlg.CloseButtonText(L"Cancel");+ dlg.DefaultButton(muxc::ContentDialogButton::Primary);+ dlg.XamlRoot(this->XamlRoot());++ auto r = co_await dlg.ShowAsync();+ if (r != muxc::ContentDialogResult::Primary) co_return;+ filePath = std::wstring(pathBox.Text());+ if (filePath.empty()) co_return;+ }++ // ── Read & parse file ───────────────────────+ std::wstring content = DBModels::ImportService::ReadFileAsWstring(filePath);+ if (content.empty())+ {+ muxc::ContentDialog errDlg;+ errDlg.Title(winrt::box_value(winrt::hstring(L"Import Failed")));+ errDlg.Content(winrt::box_value(winrt::hstring(+ L"Cannot read file:\n" + filePath)));+ errDlg.CloseButtonText(L"OK");+ errDlg.XamlRoot(this->XamlRoot());+ co_await errDlg.ShowAsync();+ co_return;+ }++ std::wstring fmt = DBModels::ImportService::DetectFormat(filePath);+ if (fmt.empty())+ {+ muxc::ContentDialog errDlg;+ errDlg.Title(winrt::box_value(winrt::hstring(L"Import Failed")));+ errDlg.Content(winrt::box_value(winrt::hstring(+ L"Unsupported file format. Use .csv, .json, or .sql")));+ errDlg.CloseButtonText(L"OK");+ errDlg.XamlRoot(this->XamlRoot());+ co_await errDlg.ShowAsync();+ co_return;+ }++ DBModels::ImportResult parsed;+ if (fmt == L"csv") parsed = DBModels::ImportService::ParseCsv(content);+ else if (fmt == L"json") parsed = DBModels::ImportService::ParseJson(content);+ else if (fmt == L"sql") parsed = DBModels::ImportService::ParseSql(content);++ if (!parsed.success)+ {+ muxc::ContentDialog errDlg;+ errDlg.Title(winrt::box_value(winrt::hstring(L"Parse Error")));+ errDlg.Content(winrt::box_value(winrt::hstring(parsed.error)));+ errDlg.CloseButtonText(L"OK");+ errDlg.XamlRoot(this->XamlRoot());+ co_await errDlg.ShowAsync();+ co_return;+ }++ // ── Confirm dialog ──────────────────────────+ std::wstring confirmMsg;+ if (fmt == L"sql")+ confirmMsg = std::to_wstring(parsed.totalParsed) ++ L" SQL statements will be executed.";+ else+ confirmMsg = std::to_wstring(parsed.totalParsed) ++ L" rows will be inserted into \"" + targetTable + L"\".";++ muxc::ContentDialog confirmDlg;+ confirmDlg.Title(winrt::box_value(winrt::hstring(L"Confirm Import")));+ confirmDlg.Content(winrt::box_value(winrt::hstring(confirmMsg)));+ confirmDlg.PrimaryButtonText(L"Import");+ confirmDlg.CloseButtonText(L"Cancel");+ confirmDlg.DefaultButton(muxc::ContentDialogButton::Primary);+ confirmDlg.XamlRoot(this->XamlRoot());++ auto confirmResult = co_await confirmDlg.ShowAsync();+ if (confirmResult != muxc::ContentDialogResult::Primary) co_return;++ // ── Execute import ──────────────────────────+ int successCount = 0;+ int failCount = 0;+ std::wstring lastError;++ try+ {+ adapter->beginTransaction();++ if (fmt == L"sql")+ {+ for (auto& stmt : parsed.sqlStatements)+ {+ try+ {+ auto r = adapter->execute(stmt);+ if (r.success) successCount++;+ else { failCount++; lastError = r.error; }+ }+ catch (...) { failCount++; }+ }+ }+ else+ {+ // CSV/JSON: insert rows via adapter->insertRow+ for (auto& row : parsed.rows)+ {+ try+ {+ auto r = adapter->insertRow(+ targetTable, targetSchema, row);+ if (r.success) successCount++;+ else { failCount++; lastError = r.error; }+ }+ catch (...) { failCount++; }+ }+ }++ if (failCount == 0)+ adapter->commitTransaction();+ else+ adapter->rollbackTransaction();+ }+ catch (...)+ {+ try { adapter->rollbackTransaction(); } catch (...) {}+ }++ // ── Result dialog ───────────────────────────+ std::wstring resultMsg;+ if (failCount == 0)+ resultMsg = std::to_wstring(successCount) + L" rows imported successfully.";+ else+ resultMsg = std::to_wstring(successCount) + L" succeeded, " ++ std::to_wstring(failCount) + L" failed.\n" ++ L"Transaction rolled back.\n\nLast error: " + lastError;++ muxc::ContentDialog resultDlg;+ resultDlg.Title(winrt::box_value(winrt::hstring(+ failCount == 0 ? L"Import Complete" : L"Import Failed")));+ resultDlg.Content(winrt::box_value(winrt::hstring(resultMsg)));+ resultDlg.CloseButtonText(L"OK");+ resultDlg.XamlRoot(this->XamlRoot());+ co_await resultDlg.ShowAsync();++ // Reload table to show new data+ if (failCount == 0) ReloadCurrentTable();+ }++ // ── Dump Database (async) ─────────────────────────────++ winrt::fire_and_forget WorkspacePage::DumpDatabaseAsync()+ {+ auto showInfo = [this](const std::wstring& title, const std::wstring& msg)+ {+ HWND owner = winrt::Gridex::implementation::App::MainHwnd;+ MessageBoxW(owner, msg.c_str(), title.c_str(), MB_OK | MB_ICONINFORMATION);+ };+ auto showError = [this](const std::wstring& msg)+ {+ HWND owner = winrt::Gridex::implementation::App::MainHwnd;+ MessageBoxW(owner, msg.c_str(), L"Dump Failed", MB_OK | MB_ICONERROR);+ };++ if (!connMgr_.isConnected())+ {+ showError(L"Not connected to any database.");+ co_return;+ }+ auto adapter = connMgr_.getActiveAdapter();+ if (!adapter) co_return;++ // Use the same schema the sidebar is showing (PostgreSQL: "public",+ // MySQL: db name, SQLite: empty/main). This matches whatever+ // listTables(currentSchema_) returns elsewhere in the page.+ std::wstring schema = currentSchema_;++ // ── Options dialog: batch size ─────────────+ muxc::ContentDialog dlg;+ dlg.Title(winrt::box_value(winrt::hstring(L"Dump Database")));++ muxc::StackPanel panel;+ panel.Spacing(12.0);++ muxc::TextBlock info;+ info.Text(winrt::hstring(L"Schema: " + schema));+ info.FontSize(12.0);+ info.Opacity(0.7);+ panel.Children().Append(info);++ muxc::TextBlock batchLabel;+ batchLabel.Text(L"Rows per batch (LIMIT/OFFSET fetch size):");+ batchLabel.FontSize(12.0);+ panel.Children().Append(batchLabel);++ muxc::NumberBox batchBox;+ batchBox.Value(static_cast<double>(DBModels::DumpRestoreService::DEFAULT_BATCH_SIZE));+ batchBox.Minimum(100);+ batchBox.Maximum(50000);+ batchBox.SpinButtonPlacementMode(muxc::NumberBoxSpinButtonPlacementMode::Inline);+ batchBox.Width(160);+ batchBox.HorizontalAlignment(mux::HorizontalAlignment::Left);+ panel.Children().Append(batchBox);++ muxc::TextBlock hint;+ hint.Text(L"Larger batches = fewer round-trips but more memory.\n"+ L"Lower for tables with very large rows (BLOB, JSON).");+ hint.FontSize(11.0);+ hint.Opacity(0.5);+ hint.TextWrapping(mux::TextWrapping::Wrap);+ panel.Children().Append(hint);++ dlg.Content(panel);+ dlg.PrimaryButtonText(L"Choose File...");+ dlg.CloseButtonText(L"Cancel");+ dlg.DefaultButton(muxc::ContentDialogButton::Primary);+ dlg.XamlRoot(this->XamlRoot());++ auto dialogResult = co_await dlg.ShowAsync();+ if (dialogResult != muxc::ContentDialogResult::Primary) co_return;++ int batchSize = static_cast<int>(batchBox.Value());+ if (batchSize <= 0) batchSize = DBModels::DumpRestoreService::DEFAULT_BATCH_SIZE;++ // ── File save picker ──────────────────────+ std::wstring filePath;+ try+ {+ winrt::Microsoft::UI::WindowId windowId{+ reinterpret_cast<uint64_t>(+ winrt::Gridex::implementation::App::MainHwnd) };++ winrt::Microsoft::Windows::Storage::Pickers::FileSavePicker picker(windowId);+ picker.SuggestedFileName(winrt::hstring(schema + L"_dump"));+ auto exts = winrt::single_threaded_vector<winrt::hstring>();+ exts.Append(L".sql");+ picker.FileTypeChoices().Insert(L"SQL Files", exts);++ auto pickedFile = co_await picker.PickSaveFileAsync();+ if (!pickedFile) co_return;+ filePath = std::wstring(pickedFile.Path());+ }+ catch (...)+ {+ showError(L"Could not open save dialog.");+ co_return;+ }++ // ── Background job + progress dialog ──────+ auto state = std::make_shared<DumpRestoreJobState>();+ auto dbType = connMgr_.getConfig().databaseType;++ auto progress = [state](const std::wstring& msg)+ {+ std::lock_guard lock(state->mtx);+ state->log += msg + L"\n";+ };++ std::thread([state, adapter, dbType, schema, filePath, batchSize, progress]() mutable+ {+ try+ {+ state->dumpResult = DBModels::DumpRestoreService::DumpDatabase(+ adapter, dbType, schema, filePath, batchSize, progress);+ }+ catch (...)+ {+ state->dumpResult.success = false;+ state->dumpResult.error = L"Unexpected exception";+ }+ state->done = true;+ }).detach();++ DumpBtn().IsEnabled(false);+ co_await ShowProgressDialogAsync(state, L"Dumping Database",+ L"Dumping " + schema + L" to " + filePath);+ DumpBtn().IsEnabled(true);++ const auto& res = state->dumpResult;+ if (res.success)+ {+ showInfo(L"Dump Complete",+ std::to_wstring(res.tablesProcessed) + L" tables, " ++ std::to_wstring(res.rowsExported) + L" rows exported to:\n" ++ filePath);+ }+ else+ {+ showError(L"Dump failed: " + res.error);+ }+ }++ // ── Restore Database (async) ──────────────────────────++ winrt::fire_and_forget WorkspacePage::RestoreDatabaseAsync()+ {+ auto showInfo = [this](const std::wstring& title, const std::wstring& msg)+ {+ HWND owner = winrt::Gridex::implementation::App::MainHwnd;+ MessageBoxW(owner, msg.c_str(), title.c_str(), MB_OK | MB_ICONINFORMATION);+ };+ auto showError = [this](const std::wstring& msg)+ {+ HWND owner = winrt::Gridex::implementation::App::MainHwnd;+ MessageBoxW(owner, msg.c_str(), L"Restore Failed", MB_OK | MB_ICONERROR);+ };++ if (!connMgr_.isConnected())+ {+ showError(L"Not connected to any database.");+ co_return;+ }+ auto adapter = connMgr_.getActiveAdapter();+ if (!adapter) co_return;++ // ── File open picker ──────────────────────+ std::wstring filePath;+ try+ {+ winrt::Microsoft::UI::WindowId windowId{+ reinterpret_cast<uint64_t>(+ winrt::Gridex::implementation::App::MainHwnd) };++ winrt::Microsoft::Windows::Storage::Pickers::FileOpenPicker picker(windowId);+ picker.FileTypeFilter().Append(L".sql");++ auto pickedFile = co_await picker.PickSingleFileAsync();+ if (!pickedFile) co_return;+ filePath = std::wstring(pickedFile.Path());+ }+ catch (...)+ {+ showError(L"Could not open file dialog.");+ co_return;+ }++ // ── Confirm dialog ──────────────────────────+ muxc::ContentDialog confirm;+ confirm.Title(winrt::box_value(winrt::hstring(L"Confirm Restore")));+ confirm.Content(winrt::box_value(winrt::hstring(+ L"This will execute SQL statements from:\n\n" + filePath ++ L"\n\nExisting tables may be dropped. Continue?")));+ confirm.PrimaryButtonText(L"Restore");+ confirm.CloseButtonText(L"Cancel");+ confirm.DefaultButton(muxc::ContentDialogButton::Close);+ confirm.XamlRoot(this->XamlRoot());++ auto r = co_await confirm.ShowAsync();+ if (r != muxc::ContentDialogResult::Primary) co_return;++ // ── Background job + progress dialog ──────+ auto state = std::make_shared<DumpRestoreJobState>();++ auto progress = [state](const std::wstring& msg)+ {+ std::lock_guard lock(state->mtx);+ state->log += msg + L"\n";+ };++ std::thread([state, adapter, filePath, progress]() mutable+ {+ try+ {+ state->restoreResult = DBModels::DumpRestoreService::RestoreDatabase(+ adapter, filePath, progress);+ }+ catch (...)+ {+ state->restoreResult.success = false;+ state->restoreResult.error = L"Unexpected exception";+ }+ state->done = true;+ }).detach();++ RestoreBtn().IsEnabled(false);+ co_await ShowProgressDialogAsync(state, L"Restoring Database",+ L"Restoring from " + filePath);+ RestoreBtn().IsEnabled(true);++ const auto& res = state->restoreResult;+ if (res.success)+ {+ showInfo(L"Restore Complete",+ std::to_wstring(res.statementsExecuted) ++ L" statements executed successfully.");+ ReloadCurrentTable();+ }+ else+ {+ showError(+ std::to_wstring(res.statementsExecuted) + L" succeeded, " ++ std::to_wstring(res.statementsFailed) + L" failed.\n" ++ L"Transaction rolled back.\n\n" + res.error);+ }+ }++ // ── ER Diagram (async) — opens as a tab, not a dialog ──++ winrt::fire_and_forget WorkspacePage::ShowERDiagramAsync(std::wstring schema)+ {+ auto showError = [this](const std::wstring& msg)+ {+ HWND owner = winrt::Gridex::implementation::App::MainHwnd;+ MessageBoxW(owner, msg.c_str(), L"ER Diagram", MB_OK | MB_ICONERROR);+ };++ if (!connMgr_.isConnected())+ {+ showError(L"Not connected to any database.");+ co_return;+ }+ auto adapter = connMgr_.getActiveAdapter();+ if (!adapter) co_return;++ if (schema.empty()) schema = currentSchema_;+ if (schema.empty()) schema = adapter->currentDatabase();++ // Reuse existing ER tab for this schema if any+ for (auto& tab : state_.tabs)+ {+ if (tab.type == DBModels::TabType::ERDiagram && tab.schema == schema)+ {+ state_.activeTabId = tab.id;+ TabBar().as<TabBarControl>()->SetActiveTab(winrt::hstring(tab.id));+ LoadERDiagramIntoView(tab);+ SwitchContentView();+ co_return;+ }+ }++ // Open new ER tab immediately with loading state, then run generation+ // on a background thread so the UI (spinner) stays responsive.+ GUID guid;+ CoCreateGuid(&guid);+ wchar_t guidStr[40];+ StringFromGUID2(guid, guidStr, 40);++ DBModels::ContentTab tab;+ tab.id = guidStr;+ tab.type = DBModels::TabType::ERDiagram;+ tab.title = L"ER: " + schema;+ tab.schema = schema;+ tab.databaseName = state_.connection.database;+ // erD2Text/erSvgPath empty for now -> loading state++ std::wstring tabId = tab.id;+ state_.tabs.push_back(tab);+ state_.activeTabId = tabId;+ TabBar().as<TabBarControl>()->AddTab(winrt::hstring(tabId), winrt::hstring(tab.title));+ TabBar().as<TabBarControl>()->SetActiveTab(winrt::hstring(tabId));++ // LoadERDiagramIntoView shows the loading panel when erSvgPath is empty+ ERDiagramBtn().IsEnabled(false);+ LoadERDiagramIntoView(state_.tabs.back());+ SwitchContentView();++ // Run generation on background thread. Capture only plain C++ data+ // (adapter shared_ptr, wstring) and the agile DispatcherQueue.+ auto dispatcher = this->DispatcherQueue();+ auto weakSelf = get_weak();++ std::thread([weakSelf, dispatcher, adapter, schema, tabId]()+ {+ DBModels::ERDiagramResult result;+ try+ {+ result = DBModels::ERDiagramService::Generate(adapter, schema);+ }+ catch (...)+ {+ result.success = false;+ result.error = L"Unknown error during generation";+ }++ // Dispatch result back to UI thread+ dispatcher.TryEnqueue([weakSelf, tabId, result]() mutable+ {+ auto self = weakSelf.get();+ if (!self) return;+ self->ApplyERDiagramResult(tabId, result);+ });+ }).detach();++ co_return;+ }++ // Apply background-generated result to the matching ER tab + view.+ void WorkspacePage::ApplyERDiagramResult(+ const std::wstring& tabId, const DBModels::ERDiagramResult& result)+ {+ ERDiagramBtn().IsEnabled(true);++ // Find the tab — it may have been closed while generation ran+ DBModels::ContentTab* tabPtr = nullptr;+ for (auto& t : state_.tabs)+ if (t.id == tabId) { tabPtr = &t; break; }+ if (!tabPtr)+ {+ // Tab was closed; clean up generated SVG+ if (!result.svgPath.empty()) DeleteFileW(result.svgPath.c_str());+ return;+ }++ if (!result.success)+ {+ ERDiagramSubtitle().Text(winrt::hstring(+ L"Generation failed: " + result.error));+ ERDiagramLoadingText().Text(winrt::hstring(L"Failed: " + result.error));+ return;+ }++ tabPtr->erD2Text = result.d2Text;+ tabPtr->erSvgPath = result.svgPath;+ tabPtr->erTableCount = result.tableCount;+ tabPtr->erRelationshipCount = result.relationshipCount;++ // Only update the view if this tab is still the active one.+ // LoadERDiagramIntoView toggles loader/webview visibility internally.+ if (state_.activeTabId == tabId)+ LoadERDiagramIntoView(*tabPtr);+ }++ // Populate the ER view (subtitle + WebView2) from a tab's cached payload.+ // WebView2 hosts the d2-generated SVG inside a minimal HTML page so the+ // browser engine handles font rendering, panning, and scrolling natively.+ void WorkspacePage::LoadERDiagramIntoView(const DBModels::ContentTab& tab)+ {+ // If still generating (no SVG yet), show the loading panel instead+ if (tab.erSvgPath.empty())+ {+ ERDiagramSubtitle().Text(winrt::hstring(+ L"Schema: " + tab.schema + L" - generating..."));+ ERDiagramLoadingText().Text(L"Generating ER diagram...");+ ERDiagramLoadingPanel().Visibility(mux::Visibility::Visible);+ ERDiagramWebView().Visibility(mux::Visibility::Collapsed);+ return;+ }++ // SVG ready -> hide loader, show WebView+ ERDiagramLoadingPanel().Visibility(mux::Visibility::Collapsed);+ ERDiagramWebView().Visibility(mux::Visibility::Visible);++ ERDiagramSubtitle().Text(winrt::hstring(+ L"Schema: " + tab.schema + L" - " ++ std::to_wstring(tab.erTableCount) + L" tables, " ++ std::to_wstring(tab.erRelationshipCount) + L" relationships"));++ // Read SVG file content+ std::ifstream svgFile(tab.erSvgPath, std::ios::binary);+ if (!svgFile.is_open()) return;+ std::string svgBytes((std::istreambuf_iterator<char>(svgFile)),+ std::istreambuf_iterator<char>());+ svgFile.close();+ if (svgBytes.empty()) return;++ // Build minimal HTML wrapper with the SVG inlined.+ // - Body acts as the infinite white canvas (min 20000x20000)+ // - SVG overflow:visible so tables dragged outside the original+ // diagram bounds still render (instead of getting clipped)+ // - Body bg white matches d2's white background -> seamless canvas+ std::string html =+ "<!DOCTYPE html><html><head><meta charset=\"UTF-8\">"+ "<style>"+ "html,body{margin:0;padding:0;background:#FFFFFF;"+ "font-family:'Segoe UI',sans-serif;}"+ "body{overflow:auto;padding:16px;"+ "min-width:20000px;min-height:20000px;}"+ "body>svg{display:block;overflow:visible;}"+ "body>svg svg{overflow:visible;}"+ "</style></head><body>";+ html += svgBytes;+ html +=+ "<script>(function(){"+ // Render SVG at intrinsic viewBox size. Body provides the+ // 'infinite' white canvas via min-width/min-height. Tables can+ // be dragged outside the SVG bounds because svg overflow:visible.+ "var outer=document.querySelector('body>svg');"+ "if(outer&&outer.viewBox&&outer.viewBox.baseVal){"+ "var vb=outer.viewBox.baseVal;"+ "if(vb.width>0&&vb.height>0){"+ "outer.setAttribute('width',vb.width);"+ "outer.setAttribute('height',vb.height);"+ "}"+ "}"+ // Add arrowhead marker for FK direction (FK column -> parent table)+ "var svgNS='http://www.w3.org/2000/svg';"+ "var defs=document.createElementNS(svgNS,'defs');"+ "var marker=document.createElementNS(svgNS,'marker');"+ "marker.setAttribute('id','fk-arrow');"+ "marker.setAttribute('viewBox','0 0 10 10');"+ "marker.setAttribute('refX','9');"+ "marker.setAttribute('refY','5');"+ "marker.setAttribute('markerWidth','7');"+ "marker.setAttribute('markerHeight','7');"+ "marker.setAttribute('orient','auto-start-reverse');"+ "var arrowPath=document.createElementNS(svgNS,'path');"+ "arrowPath.setAttribute('d','M 0 0 L 10 5 L 0 10 z');"+ "arrowPath.setAttribute('fill','#7AA7D9');"+ "marker.appendChild(arrowPath);"+ "defs.appendChild(marker);"+ "outer.appendChild(defs);"+ // Zoom state shared between wheel handler and toolbar buttons+ "var scale=1;"+ "var target=outer||document.body;"+ "target.style.transformOrigin='0 0';"+ "function postZoom(){"+ "if(window.chrome&&window.chrome.webview){"+ "try{window.chrome.webview.postMessage('zoom:'+Math.round(scale*100));}catch(e){}"+ "}"+ "}"+ "function applyScale(){"+ "target.style.transform='scale('+scale+')';"+ "postZoom();"+ "}"+ // Custom wheel: Ctrl=zoom (up=in), Shift=horizontal, default=vertical+ "document.addEventListener('wheel',function(e){"+ "if(e.ctrlKey){"+ "e.preventDefault();"+ "var d=e.deltaY<0?0.1:-0.1;"+ "scale=Math.max(0.25,Math.min(4,scale+d));"+ "applyScale();"+ "}else if(e.shiftKey){"+ "e.preventDefault();"+ "window.scrollBy({left:e.deltaY,behavior:'auto'});"+ "}"+ "},{passive:false});"+ // Drag-to-reposition tables. FK lines auto-follow via overlay+ // <line> elements that we draw between table edges.+ "var dragSvg=outer.querySelector('svg.d2-svg')||outer;"+ "function svgPoint(e){"+ "var pt=outer.createSVGPoint();"+ "pt.x=e.clientX;pt.y=e.clientY;"+ "return pt.matrixTransform(outer.getScreenCTM().inverse());"+ "}"+ "function parseTransform(s){"+ "var m=/translate\\(([-\\d.]+)[\\s,]+([-\\d.]+)\\)/.exec(s||'');"+ "return m?[parseFloat(m[1]),parseFloat(m[2])]:[0,0];"+ "}"+ // Decode d2 base64 class name; returns null if not base64+ "function decodeCls(c){"+ "if(!c||!/^[A-Za-z0-9+/]+=*$/.test(c))return null;"+ "try{return atob(c);}catch(e){return null;}"+ "}"+ // Get element bbox in outer SVG user-space coords+ "function vbox(el){"+ "var r=el.getBoundingClientRect();"+ "var inv=outer.getScreenCTM().inverse();"+ "var p1=outer.createSVGPoint();p1.x=r.left;p1.y=r.top;p1=p1.matrixTransform(inv);"+ "var p2=outer.createSVGPoint();p2.x=r.right;p2.y=r.bottom;p2=p2.matrixTransform(inv);"+ "return{x:p1.x,y:p1.y,width:p2.x-p1.x,height:p2.y-p1.y};"+ "}"+ // Pick the closest edge anchor (left|right|top|bottom) on each+ // table based on the relative direction between centers, then+ // build a cubic Bezier whose control points extend perpendicular+ // to that edge. Result: smooth S-curves that always enter/exit+ // tables at right angles, like Lucidchart / Apple Notes style.+ "function bezierPath(sb,db){"+ "var sc={x:sb.x+sb.width/2,y:sb.y+sb.height/2};"+ "var dc={x:db.x+db.width/2,y:db.y+db.height/2};"+ "var dx=dc.x-sc.x,dy=dc.y-sc.y;"+ "var horiz=Math.abs(dx)>=Math.abs(dy);"+ "var p1,p2,c1,c2,cd;"+ "if(horiz){"+ "if(dx>=0){"+ "p1={x:sb.x+sb.width,y:sc.y};"+ "p2={x:db.x,y:dc.y};"+ "}else{"+ "p1={x:sb.x,y:sc.y};"+ "p2={x:db.x+db.width,y:dc.y};"+ "}"+ "cd=Math.max(40,Math.abs(p2.x-p1.x)*0.5);"+ "var sx=dx>=0?1:-1;"+ "c1={x:p1.x+sx*cd,y:p1.y};"+ "c2={x:p2.x-sx*cd,y:p2.y};"+ "}else{"+ "if(dy>=0){"+ "p1={x:sc.x,y:sb.y+sb.height};"+ "p2={x:dc.x,y:db.y};"+ "}else{"+ "p1={x:sc.x,y:sb.y};"+ "p2={x:dc.x,y:db.y+db.height};"+ "}"+ "cd=Math.max(40,Math.abs(p2.y-p1.y)*0.5);"+ "var sy=dy>=0?1:-1;"+ "c1={x:p1.x,y:p1.y+sy*cd};"+ "c2={x:p2.x,y:p2.y-sy*cd};"+ "}"+ "return'M '+p1.x+' '+p1.y+' C '+c1.x+' '+c1.y+', '+c2.x+' '+c2.y+', '+p2.x+' '+p2.y;"+ "}"+ // Build table map: name -> group element+ "var tables={};"+ "var allGroups=dragSvg.querySelectorAll('g');"+ "allGroups.forEach(function(g){"+ "var n=decodeCls(g.getAttribute('class'));"+ "if(!n||n.charAt(0)==='(')return;"+ "if(!g.querySelector('.class_header'))return;"+ "tables[n]={group:g};"+ "});"+ // Build connections, hide originals, create overlay lines+ "var connections=[];"+ "allGroups.forEach(function(g){"+ "var n=decodeCls(g.getAttribute('class'));"+ "if(!n||n.charAt(0)!=='(')return;"+ "var nn=n.replace(/>/g,'>').replace(/</g,'<');"+ "var m=/^\\((\\S+)\\s*->\\s*(\\S+)\\)/.exec(nn);"+ "if(!m)return;"+ "var src=tables[m[1]],dst=tables[m[2]];"+ "if(!src||!dst)return;"+ "g.setAttribute('display','none');"+ "g.style.display='none';"+ // Use <path> with cubic Bezier instead of straight <line>+ "var path=document.createElementNS(svgNS,'path');"+ "path.setAttribute('stroke','#7AA7D9');"+ "path.setAttribute('stroke-width','1.5');"+ "path.setAttribute('fill','none');"+ // Arrow at path end points to dst (the parent/referenced table)+ "path.setAttribute('marker-end','url(#fk-arrow)');"+ // Append to OUTER svg so path coords match vbox() output+ // (vbox uses outer.getScreenCTM, while inner has its own viewBox)+ "outer.appendChild(path);"+ "connections.push({src:src,dst:dst,path:path});"+ "});"+ "function updateLine(c){"+ "var sb=vbox(c.src.group);"+ "var db=vbox(c.dst.group);"+ "c.path.setAttribute('d',bezierPath(sb,db));"+ "}"+ "connections.forEach(updateLine);"+ // Drag handlers+ "var dragging=null,dragTable=null,startX=0,startY=0,baseTx=0,baseTy=0;"+ "function refreshDraggedLines(){"+ "if(!dragTable)return;"+ "connections.forEach(function(c){"+ "if(c.src===dragTable||c.dst===dragTable)updateLine(c);"+ "});"+ "}"+ "var draggableGroups=[];"+ "var headers=dragSvg.querySelectorAll('.class_header');"+ "headers.forEach(function(h){"+ "var grp=h.parentElement;"+ "while(grp&&grp.tagName.toLowerCase()==='g'){"+ "var cls=grp.getAttribute('class')||'';"+ "if(cls!=='shape'&&cls.indexOf('d2-svg')===-1&&cls.indexOf('text')===-1)break;"+ "grp=grp.parentElement;"+ "}"+ "if(!grp||grp.tagName.toLowerCase()!=='g')return;"+ // Save original transform so Reset Layout can restore it+ "grp.__origTransform=grp.getAttribute('transform')||'';"+ "draggableGroups.push(grp);"+ // Bug fix: d2 renders the table name as a separate <text>+ // sibling on top of class_header. Clicks on the text used to+ // be swallowed by the text element so drag never started.+ // Use header rect's screen bbox to find any sibling element+ // visually inside it, and disable pointer-events on those+ // so clicks fall through to the header rect underneath.+ "try{"+ "var hr=h.getBoundingClientRect();"+ "var hp=h.parentElement;"+ "if(hp){"+ "Array.prototype.slice.call(hp.children).forEach(function(sib){"+ "if(sib===h)return;"+ "var sr=sib.getBoundingClientRect();"+ "var cy=(sr.top+sr.bottom)/2;"+ "var cx=(sr.left+sr.right)/2;"+ "if(cy>=hr.top&&cy<=hr.bottom&&cx>=hr.left&&cx<=hr.right){"+ "sib.style.pointerEvents='none';"+ "}"+ "});"+ "}"+ "}catch(err){}"+ "h.style.cursor='move';"+ "h.addEventListener('mousedown',function(e){"+ "if(e.button!==0)return;"+ "e.preventDefault();e.stopPropagation();"+ "dragging=grp;"+ // Find which table this group belongs to+ "var n=decodeCls(grp.getAttribute('class'));"+ "dragTable=n&&tables[n]?tables[n]:null;"+ "var p=svgPoint(e);"+ "var tr=parseTransform(grp.getAttribute('transform'));"+ "baseTx=tr[0];baseTy=tr[1];"+ "startX=p.x;startY=p.y;"+ "document.body.style.userSelect='none';"+ "});"+ "});"+ "document.addEventListener('mousemove',function(e){"+ "if(!dragging)return;"+ "var p=svgPoint(e);"+ "var nx=baseTx+(p.x-startX);"+ "var ny=baseTy+(p.y-startY);"+ "dragging.setAttribute('transform','translate('+nx+','+ny+')');"+ "refreshDraggedLines();"+ "});"+ "document.addEventListener('mouseup',function(){"+ "if(dragging){dragging=null;dragTable=null;document.body.style.userSelect='';}"+ "});"+ // Toolbar API exposed to host (called via ExecuteScriptAsync).+ // Wrapped in window.__er namespace to avoid global pollution.+ "window.__er={"+ "zoomIn:function(){"+ "scale=Math.min(4,scale+0.1);applyScale();"+ "},"+ "zoomOut:function(){"+ "scale=Math.max(0.25,scale-0.1);applyScale();"+ "},"+ "resetZoom:function(){"+ "scale=1;applyScale();window.scrollTo(0,0);"+ "},"+ "resetLayout:function(){"+ // Restore table positions only — preserve zoom and scroll+ "draggableGroups.forEach(function(g){"+ "g.setAttribute('transform',g.__origTransform);"+ "});"+ "connections.forEach(updateLine);"+ "}"+ "};"+ // Send initial zoom % so the label is correct after load+ "postZoom();"+ "})();</script>"+ "</body></html>";++ // UTF-8 -> wstring for NavigateToString+ int sz = MultiByteToWideChar(CP_UTF8, 0, html.c_str(),+ static_cast<int>(html.size()), nullptr, 0);+ std::wstring wHtml(sz, L'\0');+ MultiByteToWideChar(CP_UTF8, 0, html.c_str(),+ static_cast<int>(html.size()), &wHtml[0], sz);++ EnsureWebViewAndNavigate(winrt::hstring(wHtml));+ }++ // Initialize WebView2 (first-time async init) then navigate to HTML.+ //+ // We create our OWN CoreWebView2Environment with an explicit user data+ // folder under %LOCALAPPDATA%\Gridex\WebView2 instead of relying on the+ // default (which lands next to the exe and is often non-writable for+ // MSIX-deployed apps, OR collides with stale state from a previous build+ // — both of which throw hresult_error from EnsureCoreWebView2Async).+ winrt::fire_and_forget WorkspacePage::EnsureWebViewAndNavigate(winrt::hstring html)+ {+ try+ {+ auto wv = ERDiagramWebView();++ // Build a writable user data folder under %LOCALAPPDATA%\Gridex+ wchar_t localAppData[MAX_PATH] = {};+ SHGetFolderPathW(nullptr, CSIDL_LOCAL_APPDATA, nullptr, 0, localAppData);+ std::wstring userDataFolder = std::wstring(localAppData) + L"\\Gridex\\WebView2";+ CreateDirectoryW((std::wstring(localAppData) + L"\\Gridex").c_str(), nullptr);+ CreateDirectoryW(userDataFolder.c_str(), nullptr);++ namespace WV2C = winrt::Microsoft::Web::WebView2::Core;++ // Create environment pointing at our writable folder.+ // Empty browserExecutableFolder = use the system-installed Edge runtime.+ auto env = co_await WV2C::CoreWebView2Environment::CreateWithOptionsAsync(+ L"", // browserExecutableFolder+ winrt::hstring(userDataFolder), // userDataFolder+ WV2C::CoreWebView2EnvironmentOptions{});++ // First-time init — must be awaited before navigating+ co_await wv.EnsureCoreWebView2Async(env);++ // Hook WebMessageReceived once for zoom % updates from JS+ if (!webMessageWired_)+ {+ webMessageWired_ = true;+ auto core = wv.CoreWebView2();+ auto weakSelf = get_weak();+ core.WebMessageReceived(+ [weakSelf](auto const&, auto const& args)+ {+ auto self = weakSelf.get();+ if (!self) return;+ try+ {+ std::wstring m{ args.TryGetWebMessageAsString() };+ if (m.rfind(L"zoom:", 0) == 0)+ {+ auto pct = m.substr(5);+ self->ERZoomLabel().Text(winrt::hstring(pct + L"%"));+ }+ }+ catch (...) {}+ });+ }++ wv.NavigateToString(html);+ }+ catch (...) { /* leave empty if WebView fails to init */ }+ }++ // Toggle ER diagram fullscreen: hide all surrounding chrome so the+ // WebView fills the entire window. Restoring brings everything back.+ void WorkspacePage::ToggleERFullscreen()+ {+ erFullscreen_ = !erFullscreen_;++ if (erFullscreen_)+ {+ // Save current sidebar/details widths so we can restore them+ prevSidebarWidth_ = SidebarColumn().Width().Value;+ prevDetailsWidth_ = DetailsColumn().Width().Value;++ SidebarColumn().Width(mux::GridLengthHelper::FromPixels(0));+ DetailsColumn().Width(mux::GridLengthHelper::FromPixels(0));+ TopToolbar().Visibility(mux::Visibility::Collapsed);+ TabBar().Visibility(mux::Visibility::Collapsed);+ QueryLogPanel().Visibility(mux::Visibility::Collapsed);+ BottomBar().Visibility(mux::Visibility::Collapsed);+ StatusBar().Visibility(mux::Visibility::Collapsed);+ ERFullscreenIcon().Glyph(L"\xE73F"); // BackToWindow+ }+ else+ {+ SidebarColumn().Width(+ mux::GridLengthHelper::FromPixels(prevSidebarWidth_ > 0 ? prevSidebarWidth_ : 280));+ DetailsColumn().Width(+ mux::GridLengthHelper::FromPixels(prevDetailsWidth_ > 0 ? prevDetailsWidth_ : 260));+ TopToolbar().Visibility(mux::Visibility::Visible);+ TabBar().Visibility(mux::Visibility::Visible);+ QueryLogPanel().Visibility(mux::Visibility::Visible);+ BottomBar().Visibility(mux::Visibility::Visible);+ StatusBar().Visibility(mux::Visibility::Visible);+ ERFullscreenIcon().Glyph(L"\xE740"); // FullScreen+ }+ }++ // ── Redis: Browse Keys with pattern input dialog ───+ // Mac equivalent: Ctrl+F-style search input. Pattern uses Redis glob+ // syntax: "*" all, "user:*" prefix, "?" single char, "[abc]" set.+ winrt::fire_and_forget WorkspacePage::BrowseRedisKeysAsync()+ {+ if (!connMgr_.isConnected()) co_return;+ auto adapter = connMgr_.getActiveAdapter();+ if (!adapter) co_return;+ if (state_.connection.databaseType != DBModels::DatabaseType::Redis)+ co_return;++ // Build TextBox + helper text for the dialog content+ muxc::StackPanel panel;+ panel.Spacing(8.0);+ panel.Width(380);++ muxc::TextBlock hint;+ hint.Text(L"Glob pattern (Redis SCAN MATCH). Examples:");+ hint.FontSize(12.0);+ hint.Opacity(0.7);+ panel.Children().Append(hint);++ muxc::TextBlock examples;+ examples.Text(+ L" * - all keys\n"+ L" user:* - keys starting with \"user:\"\n"+ L" *:session - keys ending with \":session\"\n"+ L" cache:?:* - one char between cache: and :*");+ examples.FontSize(11.0);+ examples.Opacity(0.55);+ examples.FontFamily(muxm::FontFamily(L"Cascadia Mono,Consolas,monospace"));+ panel.Children().Append(examples);++ muxc::TextBox input;+ input.PlaceholderText(L"*");+ input.Text(L"*"); // default = all keys+ input.AcceptsReturn(false);+ panel.Children().Append(input);++ muxc::ContentDialog dlg;+ dlg.Title(winrt::box_value(winrt::hstring(L"Browse Keys")));+ dlg.Content(panel);+ dlg.PrimaryButtonText(L"Search");+ dlg.CloseButtonText(L"Cancel");+ dlg.DefaultButton(muxc::ContentDialogButton::Primary);+ dlg.XamlRoot(this->XamlRoot());++ auto result = co_await dlg.ShowAsync();+ if (result != muxc::ContentDialogResult::Primary) co_return;++ std::wstring pattern(input.Text());+ if (pattern.empty()) pattern = L"*";++ // Apply pattern to adapter (Redis stores it; SQL adapters no-op)+ adapter->setSearchPattern(pattern);++ // Open or refresh the Keys virtual table for the current schema+ OnTableSelected(L"Keys", currentSchema_);+ }++ // ── Redis: FLUSHDB with confirmation dialog ────────+ winrt::fire_and_forget WorkspacePage::FlushRedisDbAsync()+ {+ if (!connMgr_.isConnected()) co_return;+ auto adapter = connMgr_.getActiveAdapter();+ if (!adapter) co_return;+ if (state_.connection.databaseType != DBModels::DatabaseType::Redis)+ co_return;++ // Confirmation — destructive op, require explicit user yes+ muxc::ContentDialog dlg;+ dlg.Title(winrt::box_value(winrt::hstring(L"Flush Database")));+ dlg.Content(winrt::box_value(winrt::hstring(+ L"This will DELETE ALL keys in the current Redis database.\n\n"+ L"This action cannot be undone. Continue?")));+ dlg.PrimaryButtonText(L"Flush");+ dlg.CloseButtonText(L"Cancel");+ dlg.DefaultButton(muxc::ContentDialogButton::Close);+ dlg.XamlRoot(this->XamlRoot());++ auto result = co_await dlg.ShowAsync();+ if (result != muxc::ContentDialogResult::Primary) co_return;++ try+ {+ adapter->execute(L"FLUSHDB");+ LoadSidebarFromDB();+ }+ catch (const std::exception& ex)+ {+ std::string what = ex.what();+ int sz = MultiByteToWideChar(CP_UTF8, 0, what.c_str(), (int)what.size(), nullptr, 0);+ std::wstring err(sz, L'\0');+ MultiByteToWideChar(CP_UTF8, 0, what.c_str(), (int)what.size(), &err[0], sz);++ muxc::ContentDialog errDlg;+ errDlg.Title(winrt::box_value(winrt::hstring(L"Flush Failed")));+ errDlg.Content(winrt::box_value(winrt::hstring(err)));+ errDlg.CloseButtonText(L"OK");+ errDlg.XamlRoot(this->XamlRoot());+ errDlg.ShowAsync();+ }+ }++ // ── Progress dialog for dump/restore background jobs ─────+ winrt::Windows::Foundation::IAsyncAction WorkspacePage::ShowProgressDialogAsync(+ std::shared_ptr<DumpRestoreJobState> state,+ std::wstring title,+ std::wstring subtitle)+ {+ // Build dialog on UI thread+ muxc::ContentDialog dlg;+ dlg.Title(winrt::box_value(winrt::hstring(title)));++ muxc::StackPanel panel;+ panel.Spacing(8.0);+ panel.Width(600);++ muxc::TextBlock subtitleText;+ subtitleText.Text(winrt::hstring(subtitle));+ subtitleText.FontSize(12.0);+ subtitleText.Opacity(0.7);+ subtitleText.TextWrapping(mux::TextWrapping::Wrap);+ panel.Children().Append(subtitleText);++ muxc::ProgressRing ring;+ ring.IsActive(true);+ ring.Width(24);+ ring.Height(24);+ ring.HorizontalAlignment(mux::HorizontalAlignment::Left);+ panel.Children().Append(ring);++ muxc::ScrollViewer scroll;+ scroll.Height(280);+ scroll.HorizontalScrollBarVisibility(muxc::ScrollBarVisibility::Auto);+ scroll.VerticalScrollBarVisibility(muxc::ScrollBarVisibility::Auto);++ muxc::TextBlock logText;+ logText.FontFamily(muxm::FontFamily(L"Cascadia Code,Consolas,monospace"));+ logText.FontSize(11.0);+ logText.IsTextSelectionEnabled(true);+ logText.TextWrapping(mux::TextWrapping::NoWrap);+ scroll.Content(logText);+ panel.Children().Append(scroll);++ dlg.Content(panel);+ dlg.XamlRoot(this->XamlRoot());++ // Poll background state via DispatcherQueueTimer (runs on UI thread)+ auto dispatcher = this->DispatcherQueue();+ auto timer = dispatcher.CreateTimer();+ timer.Interval(std::chrono::milliseconds(150));++ timer.Tick([state, logText, scroll, ring, dlg, timer](auto&&, auto&&) mutable+ {+ std::wstring snapshot;+ {+ std::lock_guard lock(state->mtx);+ snapshot = state->log;+ }+ bool finished = state->done.load();++ auto currentText = std::wstring(logText.Text());+ if (snapshot != currentText)+ {+ logText.Text(winrt::hstring(snapshot));+ // Auto-scroll to bottom — ChangeView needs IReference<double>+ auto vOffset = winrt::box_value(scroll.ScrollableHeight())+ .as<winrt::Windows::Foundation::IReference<double>>();+ scroll.ChangeView(nullptr, vOffset, nullptr);+ }++ if (finished)+ {+ timer.Stop();+ ring.IsActive(false);+ dlg.Hide();+ }+ });++ timer.Start();+ co_await dlg.ShowAsync();+ timer.Stop();+ }++ // ── Export (async with co_await FileSavePicker) ──────++ winrt::fire_and_forget WorkspacePage::ExportTableAsync(+ std::wstring tableName, std::wstring schema, std::wstring format)+ {+ if (!connMgr_.isConnected()) co_return;+ auto adapter = connMgr_.getActiveAdapter();+ if (!adapter) co_return;++ // Fetch all rows+ DBModels::QueryResult result;+ try+ {+ result = adapter->execute(+ L"SELECT * FROM \"" + schema + L"\".\"" + tableName + L"\"");+ LogQuery(result);+ if (!result.success || result.columnNames.empty()) co_return;+ }+ catch (...) { co_return; }++ // Generate content+ std::wstring content;+ std::wstring ext;+ if (format == L"csv") { content = DBModels::ExportService::ToCsv(result); ext = L".csv"; }+ else if (format == L"json") { content = DBModels::ExportService::ToJson(result); ext = L".json"; }+ else if (format == L"sql") { content = DBModels::ExportService::ToSqlInsert(result, tableName); ext = L".sql"; }+ else co_return;++ // Native Save dialog via Microsoft.Windows.Storage.Pickers (WinAppSDK 1.8+)+ std::wstring savePath;+ {+ winrt::Microsoft::UI::WindowId windowId{+ reinterpret_cast<uint64_t>(+ winrt::Gridex::implementation::App::MainHwnd) };++ winrt::Microsoft::Windows::Storage::Pickers::FileSavePicker picker(windowId);+ picker.SuggestedFileName(winrt::hstring(tableName));++ std::wstring filterLabel = (ext == L".csv") ? L"CSV Files"+ : (ext == L".json") ? L"JSON Files"+ : L"SQL Files";+ auto exts = winrt::single_threaded_vector<winrt::hstring>();+ exts.Append(winrt::hstring(ext));+ picker.FileTypeChoices().Insert(winrt::hstring(filterLabel), exts);++ auto pickedFile = co_await picker.PickSaveFileAsync();+ if (!pickedFile) co_return; // User cancelled+ savePath = std::wstring(pickedFile.Path());+ }++ // Write file+ try+ {+ std::string utf8;+ int sz2 = WideCharToMultiByte(CP_UTF8, 0, content.c_str(),+ static_cast<int>(content.size()), nullptr, 0, nullptr, nullptr);+ utf8.resize(sz2);+ WideCharToMultiByte(CP_UTF8, 0, content.c_str(),+ static_cast<int>(content.size()), &utf8[0], sz2, nullptr, nullptr);++ std::ofstream outFile(savePath, std::ios::binary);+ if (!outFile.is_open())+ {+ muxc::ContentDialog errDlg;+ errDlg.Title(winrt::box_value(winrt::hstring(L"Export Failed")));+ errDlg.Content(winrt::box_value(winrt::hstring(L"Cannot write to:\n" + savePath)));+ errDlg.CloseButtonText(L"OK");+ errDlg.XamlRoot(this->XamlRoot());+ co_await errDlg.ShowAsync();+ co_return;+ }++ if (ext == L".csv") outFile.write("\xEF\xBB\xBF", 3);+ outFile.write(utf8.c_str(), utf8.size());+ outFile.close();++ // Success dialog+ muxc::ContentDialog successDlg;+ successDlg.Title(winrt::box_value(winrt::hstring(L"Export Complete")));+ successDlg.Content(winrt::box_value(winrt::hstring(+ std::to_wstring(result.totalRows) + L" rows exported to:\n" + savePath)));+ successDlg.CloseButtonText(L"OK");+ successDlg.XamlRoot(this->XamlRoot());+ co_await successDlg.ShowAsync();+ }+ catch (...) {}+ }++ // ── Tab Cache ────────────────────────────────────────++ void WorkspacePage::SaveCurrentTabCache()+ {+ if (state_.activeTabId.empty()) return;+ for (auto& tab : state_.tabs)+ {+ if (tab.id != state_.activeTabId) continue;++ if (tab.type == DBModels::TabType::DataGrid)+ {+ tab.cachedData = state_.currentData;+ tab.cachedColumns = state_.currentColumns;+ tab.cachedIndexes = state_.currentIndexes;+ tab.cachedForeignKeys = state_.currentForeignKeys;+ tab.cachedPage = state_.currentPage;+ }+ else if (tab.type == DBModels::TabType::QueryEditor)+ {+ // Each query tab keeps its own SQL text so switching+ // tabs does not show another tab's content in the+ // shared QueryEditorView.+ tab.cachedSql = QueryEditor().as<QueryEditorView>()->GetSql();+ }+ break;+ }+ }++ // ── Reload ──────────────────────────────────────────++ void WorkspacePage::ReloadCurrentTable()+ {+ for (auto& tab : state_.tabs)+ {+ if (tab.id == state_.activeTabId && tab.type == DBModels::TabType::DataGrid)+ {+ if (connMgr_.isConnected())+ LoadTableDataFromDB(tab.tableName);+ else+ LoadDemoTableData(tab.tableName);+ break;+ }+ }+ }++ // ── Demo Data (fallback when not connected) ─────────++ void WorkspacePage::LoadDemoSidebarData()+ {+ DBModels::SidebarItem functionsGroup;+ functionsGroup.id = L"functions"; functionsGroup.title = L"Functions";+ functionsGroup.type = DBModels::SidebarItemType::Group; functionsGroup.isExpanded = false;+ for (auto& name : {L"calculate_discount", L"get_customer_orders", L"update_inventory", L"validate_payment"})+ {+ DBModels::SidebarItem item;+ item.id = std::wstring(L"fn_") + name; item.title = name;+ item.type = DBModels::SidebarItemType::Function; item.schema = L"public";+ functionsGroup.children.push_back(item);+ }+ functionsGroup.count = static_cast<int>(functionsGroup.children.size());++ DBModels::SidebarItem tablesGroup;+ tablesGroup.id = L"tables"; tablesGroup.title = L"Tables";+ tablesGroup.type = DBModels::SidebarItemType::Group; tablesGroup.isExpanded = true;+ for (auto& name : {L"brands", L"categories", L"customers", L"departments",+ L"employees", L"inventory", L"order_items", L"orders",+ L"payments", L"products", L"stores", L"suppliers"})+ {+ DBModels::SidebarItem item;+ item.id = name; item.title = name;+ item.type = DBModels::SidebarItemType::Table; item.schema = L"public";+ tablesGroup.children.push_back(item);+ }+ tablesGroup.count = static_cast<int>(tablesGroup.children.size());++ DBModels::SidebarItem viewsGroup;+ viewsGroup.id = L"views"; viewsGroup.title = L"Views";+ viewsGroup.type = DBModels::SidebarItemType::Group; viewsGroup.isExpanded = false;+ for (auto& name : {L"v_monthly_revenue", L"v_top_products", L"v_customer_analysis"})+ {+ DBModels::SidebarItem item;+ item.id = name; item.title = name;+ item.type = DBModels::SidebarItemType::View; item.schema = L"public";+ viewsGroup.children.push_back(item);+ }+ viewsGroup.count = static_cast<int>(viewsGroup.children.size());++ state_.sidebarItems = { functionsGroup, tablesGroup, viewsGroup };+ Sidebar().as<SidebarPanel>()->SetItems(state_.sidebarItems);+ Sidebar().as<SidebarPanel>()->OnItemSelected = [this](const std::wstring& name, const std::wstring& schema)+ {+ OnTableSelected(name, schema);+ };+ }++ void WorkspacePage::LoadDemoTableData(const std::wstring& tableName)+ {+ state_.currentData = DBModels::QueryResult{};+ state_.currentColumns.clear();+ state_.currentIndexes.clear();+ state_.currentForeignKeys.clear();++ state_.currentData.columnNames = {L"id", L"name", L"created_at"};+ state_.currentData.columnTypes = {L"integer", L"varchar(255)", L"timestamp"};+ for (int i = 1; i <= 10; i++)+ {+ DBModels::TableRow row;+ row[L"id"] = std::to_wstring(i);+ row[L"name"] = tableName + L"_item_" + std::to_wstring(i);+ row[L"created_at"] = L"2025-01-01 00:00:00";+ state_.currentData.rows.push_back(row);+ }+ state_.currentData.totalRows = 10;+ state_.currentData.success = true;+ state_.statusRowCount = 10;+ state_.statusQueryTimeMs = 0.5;++ state_.currentColumns = {+ {L"id", L"integer", false, L"", true, false, L"", L"", L"", 1},+ {L"name", L"varchar(255)", true, L"", false, false, L"", L"", L"", 2},+ {L"created_at", L"timestamp", true, L"CURRENT_TIMESTAMP", false, false, L"", L"", L"", 3}+ };++ auto renderStart = std::chrono::steady_clock::now();+ DataGrid().as<DataGridView>()->SetData(state_.currentData);+ auto renderEnd = std::chrono::steady_clock::now();+ state_.statusRenderTimeMs =+ std::chrono::duration<double, std::milli>(renderEnd - renderStart).count();++ Structure().as<StructureView>()->SetData(state_.currentColumns, state_.currentIndexes,+ state_.currentForeignKeys, state_.currentConstraints);+ StatusBar().as<StatusBarControl>()->SetStatus(state_.statusConnection, state_.statusSchema,+ state_.statusRowCount,+ state_.statusQueryTimeMs,+ state_.statusRenderTimeMs);+ UpdatePaginationUI();+ }+}diff --git a/windows/Gridex/WorkspacePage.h b/windows/Gridex/WorkspacePage.hnew file mode 100644index 0000000..1cf5627--- /dev/null+++ b/windows/Gridex/WorkspacePage.h@@ -0,0 +1,196 @@+#pragma once++#include "WorkspacePage.g.h"+#include "Models/WorkspaceState.h"+#include "Models/ConnectionManager.h"+#include "Models/ChangeTracker.h"+#include "Models/DumpRestoreService.h"+#include "Models/ERDiagramService.h"+#include <mutex>+#include <atomic>+#include <memory>++namespace winrt::Gridex::implementation+{+ struct WorkspacePage : WorkspacePageT<WorkspacePage>+ {+ WorkspacePage();++ // Called by HomePage after navigation+ void SetConnection(const DBModels::ConnectionConfig& config, const std::wstring& password);++ // Old XAML-bound handlers (kept for backward compat with existing Click= attrs)+ void ToggleSidebar_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);+ void ToggleDetails_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);+ void DataToggle_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);+ void StructureToggle_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);+ void ToggleFilter_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);+ void ToggleAI_Click(+ winrt::Windows::Foundation::IInspectable const& sender,+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);++ private:+ DBModels::WorkspaceState state_;+ DBModels::ConnectionManager connMgr_;+ DBModels::ChangeTracker changeTracker_;+ std::wstring currentSchema_ = L"public";+ std::wstring pendingPassword_;+ bool hasConnection_ = false;+ bool isLoaded_ = false;++ // Monotonic counter incremented on every LoadTableDataFromDB call.+ // Background worker captures the value at dispatch time; when the+ // worker re-enters the UI thread it checks that this counter has+ // not advanced — if the user clicked another table while the+ // query was running, the stale result is dropped instead of+ // overwriting the fresh one. UI-thread-only, no atomic needed.+ uint64_t loadTableRequestCounter_ = 0;++ // Process-wide cache of the last active workspace connection.+ // HomePage → WorkspacePage instances are destroyed when the user+ // navigates to SettingsPage (Frame.Navigate drops the previous+ // page), so the Back button creates a fresh WorkspacePage with+ // no connection state. Restoring from these statics inside the+ // Loaded handler keeps the DB session visible instead of falling+ // through to LoadDemoSidebarData.+ static DBModels::ConnectionConfig sLastConfig_;+ static std::wstring sLastPassword_;+ static bool sHasLastConnection_;+ bool buttonsWired_ = false;+ bool sidebarVisible_ = true;+ bool detailsVisible_ = true;+ bool filterVisible_ = false;+ bool showingData_ = true;+ bool erFullscreen_ = false;+ bool webMessageWired_ = false;+ double prevSidebarWidth_ = 280.0;+ double prevDetailsWidth_ = 260.0;++ // ── Drag-to-resize state for left/right sidebars + query log ──+ bool leftResizing_ = false;+ double leftResizeStartX_ = 0.0;+ double leftResizeStartWidth_ = 0.0;+ bool rightResizing_ = false;+ double rightResizeStartX_ = 0.0;+ double rightResizeStartWidth_= 0.0;+ bool logResizing_ = false;+ double logResizeStartY_ = 0.0;+ double logResizeStartHeight_ = 0.0;++ // ── Initialization ──────────────────────────+ void InitializeConnection();+ void WireAllButtons();+ void WireResizeGrips();++ // ── Sidebar / Data Loading ──────────────────+ void LoadSidebarFromDB();+ void LoadTableDataFromDB(const std::wstring& tableName);+ void LoadDemoSidebarData();+ void LoadDemoTableData(const std::wstring& tableName);++ // ── Content Navigation ──────────────────────+ void UpdateBreadcrumb();+ void SwitchContentView();+ void OnTableSelected(const std::wstring& tableName, const std::wstring& schema);+ void OpenNewQueryTab();++ // ── CRUD Operations ─────────────────────────+ void DeleteSelectedRow();+ void AddNewRow();+ void CommitChanges();+ void DiscardChanges();+ DBModels::TableRow ExtractPrimaryKey(int rowIndex);++ // ── Pagination ──────────────────────────────+ void PrevPage();+ void NextPage();+ void LoadCurrentTablePage(int page);+ void UpdatePaginationUI();++ // ── Database/Schema Picker ──────────────────+ void LoadDatabasePicker();+ void SwitchDatabase(const std::wstring& dbName);++ // ── Filter ──────────────────────────────────+ void ApplyFilter(const std::wstring& column, const std::wstring& op, const std::wstring& value);++ // ── Query Log ───────────────────────────────+ // Log one executed query into the console log panel. When the+ // query also produced a UI render (table load, filter apply,+ // query editor run), pass the render wall-clock so the log+ // entry shows a proper "Exec + Render" split. Metadata queries+ // that never touch the data grid leave the default 0 — the log+ // then omits the "· Render" suffix.+ void LogQuery(const DBModels::QueryResult& result, double renderTimeMs = 0.0);+ void RefreshQueryLog();++ // ── Pending Changes UI ──────────────────────+ void UpdatePendingUI();++ // ── Tab Cache ────────────────────────────────+ void SaveCurrentTabCache();++ // ── Export (async) ───────────────────────────+ winrt::fire_and_forget ExportTableAsync(+ std::wstring tableName, std::wstring schema, std::wstring format);++ // ── Import (async) — into specific table from sidebar context menu+ winrt::fire_and_forget ImportDataAsync(+ std::wstring targetTable, std::wstring targetSchema);++ // ── Dump / Restore (async) ──────────────────+ winrt::fire_and_forget DumpDatabaseAsync();+ winrt::fire_and_forget RestoreDatabaseAsync();++ // ── ER Diagram (async) ──────────────────────+ winrt::fire_and_forget ShowERDiagramAsync(std::wstring schema);+ void LoadERDiagramIntoView(const DBModels::ContentTab& tab);+ void ApplyERDiagramResult(+ const std::wstring& tabId, const DBModels::ERDiagramResult& result);+ winrt::fire_and_forget EnsureWebViewAndNavigate(winrt::hstring html);+ void ToggleERFullscreen();++ // ── Redis-specific actions ────────────────+ winrt::fire_and_forget FlushRedisDbAsync();+ winrt::fire_and_forget BrowseRedisKeysAsync();++ // Shared progress state for dump/restore background jobs+ struct DumpRestoreJobState+ {+ std::mutex mtx;+ std::wstring log;+ std::atomic<bool> done{ false };+ DBModels::DumpResult dumpResult;+ DBModels::RestoreResult restoreResult;+ };++ // Show modal progress dialog with live log; returns when state->done is true+ winrt::Windows::Foundation::IAsyncAction ShowProgressDialogAsync(+ std::shared_ptr<DumpRestoreJobState> state,+ std::wstring title,+ std::wstring subtitle);++ // ── AI settings sync ────────────────────────+ void ApplyAiSettings();++ // ── Reload ──────────────────────────────────+ void ReloadCurrentTable();+ };+}++namespace winrt::Gridex::factory_implementation+{+ struct WorkspacePage : WorkspacePageT<WorkspacePage, implementation::WorkspacePage>+ {+ };+}diff --git a/windows/Gridex/WorkspacePage.idl b/windows/Gridex/WorkspacePage.idlnew file mode 100644index 0000000..63c8934--- /dev/null+++ b/windows/Gridex/WorkspacePage.idl@@ -0,0 +1,8 @@+namespace Gridex+{+ [default_interface]+ runtimeclass WorkspacePage : Microsoft.UI.Xaml.Controls.Page+ {+ WorkspacePage();+ }+}diff --git a/windows/Gridex/WorkspacePage.xaml b/windows/Gridex/WorkspacePage.xamlnew file mode 100644index 0000000..edd09b0--- /dev/null+++ b/windows/Gridex/WorkspacePage.xaml@@ -0,0 +1,415 @@+<Page+ x:Class="Gridex.WorkspacePage"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:local="using:Gridex"+ Background="Transparent">++ <Grid>+ <Grid.RowDefinitions>+ <RowDefinition Height="Auto" />+ <RowDefinition Height="*" />+ <RowDefinition Height="Auto" />+ </Grid.RowDefinitions>++ <!-- Top Toolbar -->+ <Grid x:Name="TopToolbar" Grid.Row="0" Padding="12,8"+ Background="{ThemeResource LayerFillColorDefaultBrush}"+ BorderBrush="{ThemeResource DividerStrokeColorDefaultBrush}"+ BorderThickness="0,0,0,1">+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="*" />+ <ColumnDefinition Width="Auto" />+ </Grid.ColumnDefinitions>++ <!-- Left: Home + Sidebar Toggle + Database Picker -->+ <StackPanel Grid.Column="0" Orientation="Horizontal" Spacing="4">+ <Button x:Name="HomeBtn" Width="32" Height="32" Padding="0"+ Background="Transparent" BorderThickness="0"+ ToolTipService.ToolTip="Back to Connections (Ctrl+H)">+ <FontIcon Glyph="" FontSize="14" />+ </Button>+ <Button x:Name="SidebarToggleBtn" Width="32" Height="32" Padding="0"+ Background="Transparent" BorderThickness="0"+ ToolTipService.ToolTip="Toggle Sidebar">+ <FontIcon Glyph="" FontSize="14" />+ </Button>++ <!-- Database Picker (dynamically populated) -->+ <DropDownButton x:Name="DbPickerButton" Padding="6,4"+ Background="Transparent" BorderThickness="0"+ ToolTipService.ToolTip="Switch Database">+ <StackPanel Orientation="Horizontal" Spacing="6">+ <FontIcon Glyph="" FontSize="13" />+ <TextBlock x:Name="DbPickerText" Text="app_db" FontSize="12" />+ </StackPanel>+ <DropDownButton.Flyout>+ <MenuFlyout x:Name="DbPickerFlyout" />+ </DropDownButton.Flyout>+ </DropDownButton>+ </StackPanel>++ <!-- Center: Connection Breadcrumb -->+ <StackPanel Grid.Column="1" Orientation="Horizontal" Spacing="8"+ Margin="12,0,0,0" VerticalAlignment="Center">+ <Ellipse x:Name="ConnectionDot" Width="8" Height="8" />+ <TextBlock x:Name="ConnectionNameText" FontWeight="SemiBold" FontSize="12"+ Foreground="{ThemeResource TextFillColorPrimaryBrush}" />+ <TextBlock x:Name="ConnectionInfoText" FontSize="11"+ Foreground="{ThemeResource TextFillColorTertiaryBrush}" />+ </StackPanel>++ <!-- Right: Delete + Commit | Details + AI -->+ <StackPanel Grid.Column="3" Orientation="Horizontal" Spacing="4">+ <Button x:Name="DumpBtn" Width="32" Height="32" Padding="0"+ Background="Transparent" BorderThickness="0"+ ToolTipService.ToolTip="Dump Database">+ <FontIcon Glyph="" FontSize="14" />+ </Button>+ <Button x:Name="RestoreBtn" Width="32" Height="32" Padding="0"+ Background="Transparent" BorderThickness="0"+ ToolTipService.ToolTip="Restore Database">+ <FontIcon Glyph="" FontSize="14" />+ </Button>+ <Button x:Name="ERDiagramBtn" Width="32" Height="32" Padding="0"+ Background="Transparent" BorderThickness="0"+ ToolTipService.ToolTip="ER Diagram (current schema)">+ <FontIcon Glyph="" FontSize="14" />+ </Button>+ <Button x:Name="DeleteBtn" Width="32" Height="32" Padding="0"+ Background="Transparent" BorderThickness="0"+ ToolTipService.ToolTip="Delete Selected Rows">+ <FontIcon Glyph="" FontSize="14" />+ </Button>+ <Button x:Name="CommitToolbarBtn" Width="32" Height="32" Padding="0"+ Background="Transparent" BorderThickness="0"+ ToolTipService.ToolTip="Commit Changes">+ <FontIcon Glyph="" FontSize="14" />+ </Button>+ <Border Width="1" Height="20" Margin="4,0"+ Background="{ThemeResource DividerStrokeColorDefaultBrush}" />+ <Button x:Name="DetailsToggleBtn" Width="32" Height="32" Padding="0"+ Background="Transparent" BorderThickness="0"+ ToolTipService.ToolTip="Toggle Details Panel">+ <FontIcon Glyph="" FontSize="14" />+ </Button>+ <Button x:Name="AiToggleBtn" Width="32" Height="32" Padding="0"+ Background="Transparent" BorderThickness="0"+ ToolTipService.ToolTip="Toggle AI Assistant">+ <FontIcon Glyph="" FontSize="14" />+ </Button>+ <Button x:Name="SettingsBtn" Width="32" Height="32" Padding="0"+ Background="Transparent" BorderThickness="0"+ ToolTipService.ToolTip="Settings (Ctrl+Shift+P)">+ <FontIcon Glyph="" FontSize="14" />+ </Button>+ </StackPanel>+ </Grid>++ <!-- Main 3-Panel Layout -->+ <Grid Grid.Row="1">+ <Grid.ColumnDefinitions>+ <ColumnDefinition x:Name="SidebarColumn" Width="280" />+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="*" MinWidth="400" />+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition x:Name="DetailsColumn" Width="260" />+ </Grid.ColumnDefinitions>++ <!-- Sidebar -->+ <local:SidebarPanel x:Name="Sidebar" Grid.Column="0" />++ <!-- Left resize grip: 5px transparent hit area with 1px visible+ divider centered inside. Drag handlers wired in code-behind. -->+ <Grid x:Name="LeftSidebarResizer" Grid.Column="1" Width="5"+ Background="Transparent">+ <Border Width="1" HorizontalAlignment="Center"+ Background="{ThemeResource DividerStrokeColorDefaultBrush}"+ IsHitTestVisible="False" />+ </Grid>++ <!-- Main Content Area -->+ <Grid Grid.Column="2">+ <Grid.RowDefinitions>+ <RowDefinition Height="Auto" />+ <RowDefinition Height="*" />+ <RowDefinition Height="Auto" />+ <RowDefinition Height="Auto" />+ <RowDefinition Height="Auto" />+ </Grid.RowDefinitions>++ <!-- Tab Bar -->+ <local:TabBarControl x:Name="TabBar" Grid.Row="0" />++ <!-- Content Switcher -->+ <Grid x:Name="ContentArea" Grid.Row="1">+ <!-- Empty state -->+ <StackPanel x:Name="EmptyContentState"+ VerticalAlignment="Center"+ HorizontalAlignment="Center"+ Spacing="8">+ <FontIcon Glyph="" FontSize="48"+ Foreground="{ThemeResource TextFillColorTertiaryBrush}"+ HorizontalAlignment="Center" />+ <TextBlock Text="Select a table or run a query"+ FontSize="14"+ HorizontalAlignment="Center"+ Foreground="{ThemeResource TextFillColorTertiaryBrush}" />+ </StackPanel>++ <!-- DataGrid -->+ <local:DataGridView x:Name="DataGrid" Visibility="Collapsed" />+ <!-- Structure View -->+ <local:StructureView x:Name="Structure" Visibility="Collapsed" />+ <!-- Query Editor -->+ <local:QueryEditorView x:Name="QueryEditor" Visibility="Collapsed" />+ <!-- Loader overlay shown while LoadTableDataFromDB is+ in flight. Sits as the last child of ContentArea so+ it stacks on top of DataGrid / Structure / etc. -->+ <Grid x:Name="DataLoadingOverlay"+ Visibility="Collapsed"+ Background="{ThemeResource SolidBackgroundFillColorBaseBrush}">+ <StackPanel HorizontalAlignment="Center"+ VerticalAlignment="Center"+ Spacing="12">+ <ProgressRing IsActive="True"+ Width="40" Height="40"+ HorizontalAlignment="Center" />+ <TextBlock x:Name="DataLoadingText"+ Text="Loading table..."+ FontSize="13"+ Opacity="0.7"+ HorizontalAlignment="Center" />+ </StackPanel>+ </Grid>+ <!-- ER Diagram View — WebView2 hosts inline SVG (Direct2D+ doesn't render <text> in SVG, so we use the browser). -->+ <Grid x:Name="ERDiagramView" Visibility="Collapsed">+ <Grid.RowDefinitions>+ <RowDefinition Height="Auto" />+ <RowDefinition Height="*" />+ <RowDefinition Height="Auto" />+ </Grid.RowDefinitions>+ <TextBlock x:Name="ERDiagramSubtitle" Grid.Row="0"+ FontSize="12" Opacity="0.7"+ Margin="12,8,12,4" />+ <!-- Row 1 hosts WebView, loader, and floating controls.+ Loader and WebView swap via Visibility; controls+ overlay top-right. -->+ <Grid Grid.Row="1">+ <WebView2 x:Name="ERDiagramWebView" />+ <StackPanel x:Name="ERDiagramLoadingPanel"+ HorizontalAlignment="Center"+ VerticalAlignment="Center"+ Spacing="12"+ Visibility="Collapsed">+ <ProgressRing IsActive="True"+ Width="48" Height="48"+ HorizontalAlignment="Center" />+ <TextBlock x:Name="ERDiagramLoadingText"+ Text="Generating ER diagram..."+ FontSize="14"+ Opacity="0.7"+ HorizontalAlignment="Center" />+ </StackPanel>++ <!-- Floating top-right controls: zoom in/out,+ zoom %, reset layout, fullscreen toggle -->+ <Border x:Name="ERControlsPanel"+ HorizontalAlignment="Right"+ VerticalAlignment="Top"+ Margin="0,12,12,0"+ CornerRadius="6"+ Background="{ThemeResource SolidBackgroundFillColorBaseBrush}"+ BorderBrush="{ThemeResource DividerStrokeColorDefaultBrush}"+ BorderThickness="1"+ Padding="2">+ <StackPanel Orientation="Horizontal" Spacing="0">+ <Button x:Name="ERZoomOutBtn"+ Width="28" Height="28" Padding="0"+ Background="Transparent" BorderThickness="0"+ ToolTipService.ToolTip="Zoom Out">+ <FontIcon Glyph="" FontSize="12" />+ </Button>+ <Button x:Name="ERZoomLabelBtn"+ MinWidth="48" Height="28" Padding="4,0"+ Background="Transparent" BorderThickness="0"+ ToolTipService.ToolTip="Reset Zoom (100%)">+ <TextBlock x:Name="ERZoomLabel"+ Text="100%" FontSize="11"+ TextAlignment="Center" />+ </Button>+ <Button x:Name="ERZoomInBtn"+ Width="28" Height="28" Padding="0"+ Background="Transparent" BorderThickness="0"+ ToolTipService.ToolTip="Zoom In">+ <FontIcon Glyph="" FontSize="12" />+ </Button>+ <Border Width="1" Height="20" Margin="2,0"+ Background="{ThemeResource DividerStrokeColorDefaultBrush}" />+ <Button x:Name="ERResetLayoutBtn"+ Width="28" Height="28" Padding="0"+ Background="Transparent" BorderThickness="0"+ ToolTipService.ToolTip="Reset Table Positions">+ <FontIcon Glyph="" FontSize="12" />+ </Button>+ <Button x:Name="ERFullscreenBtn"+ Width="28" Height="28" Padding="0"+ Background="Transparent" BorderThickness="0"+ ToolTipService.ToolTip="Toggle Fullscreen">+ <FontIcon x:Name="ERFullscreenIcon"+ Glyph="" FontSize="12" />+ </Button>+ </StackPanel>+ </Border>+ </Grid>+ <StackPanel Grid.Row="2" Orientation="Horizontal" Spacing="8"+ HorizontalAlignment="Right" Padding="12,8">+ <Button x:Name="ERCopyD2Btn" Content="Copy D2" />+ <Button x:Name="ERSaveSvgBtn" Content="Save SVG..." />+ <Button x:Name="ERSaveD2Btn" Content="Save D2..." />+ </StackPanel>+ </Grid>+ </Grid>++ <!-- Query Log Panel. Top row hosts a 5px vertical resize+ grip; the 1px divider line is now drawn inside the grip+ instead of via the panel's BorderThickness. -->+ <Grid x:Name="QueryLogPanel" Grid.Row="2" Height="140">+ <Grid.RowDefinitions>+ <RowDefinition Height="5" />+ <RowDefinition Height="Auto" />+ <RowDefinition Height="*" />+ </Grid.RowDefinitions>++ <!-- Top resize grip — drag vertically to grow/shrink -->+ <Grid x:Name="QueryLogResizer" Grid.Row="0"+ Background="Transparent">+ <Border Height="1" VerticalAlignment="Top"+ Background="{ThemeResource DividerStrokeColorDefaultBrush}"+ IsHitTestVisible="False" />+ </Grid>++ <Grid Grid.Row="1" Padding="8,4"+ Background="{ThemeResource LayerFillColorDefaultBrush}">+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="*" />+ <ColumnDefinition Width="Auto" />+ </Grid.ColumnDefinitions>+ <TextBlock Text="Query Log" FontSize="11" FontWeight="SemiBold"+ VerticalAlignment="Center"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ <Button x:Name="ClearLogBtn" Grid.Column="1"+ Padding="6,2" FontSize="10"+ Background="Transparent" BorderThickness="0"+ Content="Clear" />+ </Grid>++ <ScrollViewer Grid.Row="2" x:Name="QueryLogScroller"+ VerticalScrollBarVisibility="Auto"+ Background="{ThemeResource CardBackgroundFillColorDefaultBrush}">+ <StackPanel x:Name="QueryLogEntries" Spacing="4" Padding="12,6" />+ </ScrollViewer>+ </Grid>++ <!-- Filter Bar -->+ <local:FilterBar x:Name="FilterBarControl" Grid.Row="3" Visibility="Collapsed" />++ <!-- Bottom Bar -->+ <Grid x:Name="BottomBar" Grid.Row="4"+ Padding="8,4"+ Background="{ThemeResource LayerFillColorDefaultBrush}"+ BorderBrush="{ThemeResource DividerStrokeColorDefaultBrush}"+ BorderThickness="0,1,0,0">+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="*" />+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="Auto" />+ </Grid.ColumnDefinitions>++ <!-- Data | Structure toggle -->+ <StackPanel Grid.Column="0" Orientation="Horizontal" Spacing="0">+ <ToggleButton x:Name="DataToggle" Content="Data"+ IsChecked="True" Padding="10,4" />+ <ToggleButton x:Name="StructureToggle" Content="Structure"+ Padding="10,4" />+ </StackPanel>++ <!-- + Row Button -->+ <Button x:Name="AddRowBtn" Grid.Column="1" Margin="8,0,0,0"+ Padding="6,4"+ Background="Transparent" BorderThickness="0"+ ToolTipService.ToolTip="Add Row">+ <StackPanel Orientation="Horizontal" Spacing="4">+ <FontIcon Glyph="" FontSize="10" />+ <TextBlock Text="Row" FontSize="11" />+ </StackPanel>+ </Button>++ <!-- Pagination -->+ <StackPanel Grid.Column="3" Orientation="Horizontal" Spacing="4"+ VerticalAlignment="Center">+ <Button x:Name="PrevPageBtn" Width="24" Height="24" Padding="0"+ Background="Transparent" BorderThickness="0"+ ToolTipService.ToolTip="Previous Page">+ <FontIcon Glyph="" FontSize="10" />+ </Button>+ <TextBlock x:Name="PaginationText" Text="0 rows"+ FontSize="11" VerticalAlignment="Center"+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />+ <Button x:Name="NextPageBtn" Width="24" Height="24" Padding="0"+ Background="Transparent" BorderThickness="0"+ ToolTipService.ToolTip="Next Page">+ <FontIcon Glyph="" FontSize="10" />+ </Button>+ </StackPanel>++ <!-- Pending Changes -->+ <StackPanel x:Name="PendingChangesPanel" Grid.Column="4"+ Orientation="Horizontal" Spacing="6"+ Margin="12,0,0,0" Visibility="Collapsed">+ <TextBlock x:Name="PendingCountText" FontSize="11"+ VerticalAlignment="Center"+ Foreground="Orange" />+ <Button x:Name="DiscardBtn" Content="Discard"+ Padding="6,2" FontSize="11" />+ <Button x:Name="CommitBottomBtn" Content="Commit"+ Padding="6,2" FontSize="11"+ Style="{StaticResource AccentButtonStyle}" />+ </StackPanel>++ <!-- Filter Toggle -->+ <Button x:Name="FilterToggleBtn" Grid.Column="5" Margin="8,0,0,0"+ Padding="6,4"+ Background="Transparent" BorderThickness="0"+ ToolTipService.ToolTip="Toggle Filters">+ <StackPanel Orientation="Horizontal" Spacing="4">+ <FontIcon Glyph="" FontSize="10" />+ <TextBlock Text="Filters" FontSize="11" />+ </StackPanel>+ </Button>+ </Grid>+ </Grid>++ <!-- Right resize grip: mirrors LeftSidebarResizer, drag handlers+ in code-behind adjust DetailsColumn.Width live. -->+ <Grid x:Name="RightSidebarResizer" Grid.Column="3" Width="5"+ Background="Transparent">+ <Border Width="1" HorizontalAlignment="Center"+ Background="{ThemeResource DividerStrokeColorDefaultBrush}"+ IsHitTestVisible="False" />+ </Grid>++ <!-- Details Panel -->+ <local:DetailsPanel x:Name="Details" Grid.Column="4" />+ </Grid>++ <!-- Status Bar -->+ <local:StatusBarControl x:Name="StatusBar" Grid.Row="2" />+ </Grid>+</Page>diff --git a/windows/Gridex/app.manifest b/windows/Gridex/app.manifestnew file mode 100644index 0000000..a5d7dd9--- /dev/null+++ b/windows/Gridex/app.manifest@@ -0,0 +1,19 @@+<?xml version="1.0" encoding="utf-8"?>+<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">+ <assemblyIdentity version="1.0.0.0" name="Gridex.app"/>++ <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">+ <application>+ <!-- The ID below informs the system that this application is compatible with OS features first introduced in Windows 10.+ It is necessary to support features in unpackaged applications, for example the custom titlebar implementation.+ For more info see https://docs.microsoft.com/windows/apps/windows-app-sdk/use-windows-app-sdk-run-time#declare-os-compatibility-in-your-application-manifest -->+ <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />+ </application>+ </compatibility>++ <application xmlns="urn:schemas-microsoft-com:asm.v3">+ <windowsSettings>+ <dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>+ </windowsSettings>+ </application>+</assembly>\ No newline at end of filediff --git a/windows/Gridex/packages.config b/windows/Gridex/packages.confignew file mode 100644index 0000000..97549ab--- /dev/null+++ b/windows/Gridex/packages.config@@ -0,0 +1,18 @@+<?xml version="1.0" encoding="utf-8"?>+<packages>+ <package id="Microsoft.Web.WebView2" version="1.0.3179.45" targetFramework="native" />+ <package id="Microsoft.Windows.CppWinRT" version="2.0.250303.1" targetFramework="native" />+ <package id="Microsoft.Windows.ImplementationLibrary" version="1.0.260126.7" targetFramework="native" />+ <package id="Microsoft.Windows.SDK.BuildTools" version="10.0.28000.1721" targetFramework="native" />+ <package id="Microsoft.Windows.SDK.BuildTools.MSIX" version="1.7.20250829.1" targetFramework="native" developmentDependency="true" />+ <package id="Microsoft.WindowsAppSDK" version="1.8.260317003" targetFramework="native" />+ <package id="Microsoft.WindowsAppSDK.AI" version="1.8.53" targetFramework="native" />+ <package id="Microsoft.WindowsAppSDK.Base" version="1.8.251216001" targetFramework="native" />+ <package id="Microsoft.WindowsAppSDK.DWrite" version="1.8.25122902" targetFramework="native" />+ <package id="Microsoft.WindowsAppSDK.Foundation" version="1.8.260222000" targetFramework="native" />+ <package id="Microsoft.WindowsAppSDK.InteractiveExperiences" version="1.8.260125001" targetFramework="native" />+ <package id="Microsoft.WindowsAppSDK.ML" version="1.8.2141" targetFramework="native" />+ <package id="Microsoft.WindowsAppSDK.Runtime" version="1.8.260317003" targetFramework="native" />+ <package id="Microsoft.WindowsAppSDK.Widgets" version="1.8.251231004" targetFramework="native" />+ <package id="Microsoft.WindowsAppSDK.WinUI" version="1.8.260224000" targetFramework="native" />+</packages>\ No newline at end of filediff --git a/windows/Gridex/pch.cpp b/windows/Gridex/pch.cppnew file mode 100644index 0000000..1d9f38c--- /dev/null+++ b/windows/Gridex/pch.cpp@@ -0,0 +1 @@+#include "pch.h"diff --git a/windows/Gridex/pch.h b/windows/Gridex/pch.hnew file mode 100644index 0000000..f6ad317--- /dev/null+++ b/windows/Gridex/pch.h@@ -0,0 +1,14 @@+#pragma once++// Win32 core+#include <windows.h>+#include <unknwn.h>+#include <restrictederrorinfo.h>+#include <hstring.h>++#undef GetCurrentTime++// WinRT base only — XAML headers included per .cpp file+#include <winrt/Windows.Foundation.h>+#include <winrt/Windows.Foundation.Collections.h>+#include <winrt/Microsoft.UI.Dispatching.h>diff --git a/windows/Gridex/readme.txt b/windows/Gridex/readme.txtnew file mode 100644index 0000000..5134cbe--- /dev/null+++ b/windows/Gridex/readme.txt@@ -0,0 +1,27 @@+========================================================================+ Gridex Project Overview+========================================================================++This project demonstrates how to get started writing WinUI3 apps directly+with standard C++, using the Windows App SDK and C++/WinRT packages and+XAML compiler support to generate implementation headers from interface+(IDL) files. These headers can then be used to implement the local+Windows Runtime classes referenced in the app's XAML pages.++Steps:+1. Create an interface (IDL) file to define any local Windows Runtime+ classes referenced in the app's XAML pages.+2. Build the project once to generate implementation templates under+ the "Generated Files" folder, as well as skeleton class definitions+ under "Generated Files\sources".+3. Use the skeleton class definitions for reference to implement your+ Windows Runtime classes.++========================================================================+Learn more about Windows App SDK here:+https://docs.microsoft.com/windows/apps/windows-app-sdk/+Learn more about WinUI3 here:+https://docs.microsoft.com/windows/apps/winui/winui3/+Learn more about C++/WinRT here:+http://aka.ms/cppwinrt/+========================================================================diff --git a/windows/Gridex/xaml-includes.h b/windows/Gridex/xaml-includes.hnew file mode 100644index 0000000..29fc71a--- /dev/null+++ b/windows/Gridex/xaml-includes.h@@ -0,0 +1,8 @@+#pragma once+// Common WinUI 3 XAML headers — include after pch.h in XAML .cpp files+#include <winrt/Microsoft.UI.Xaml.h>+#include <winrt/Microsoft.UI.Xaml.Controls.h>+#include <winrt/Microsoft.UI.Xaml.Controls.Primitives.h>+#include <winrt/Microsoft.UI.Xaml.Input.h>+#include <winrt/Microsoft.UI.Xaml.Markup.h>+#include <winrt/Microsoft.UI.Xaml.Media.h>diff --git a/windows/NuGet.Config b/windows/NuGet.Confignew file mode 100644index 0000000..b48089a--- /dev/null+++ b/windows/NuGet.Config@@ -0,0 +1,6 @@+<?xml version="1.0" encoding="utf-8"?>+<configuration>+ <config>+ <add key="repositoryPath" value="packages" />+ </config>+</configuration>diff --git a/windows/README.md b/windows/README.mdnew file mode 100644index 0000000..cb2971b--- /dev/null+++ b/windows/README.md@@ -0,0 +1,295 @@+# Gridex — Windows Build Guide++Hướng dẫn build Gridex từ source và tạo installer `Setup.exe` trên Windows, chạy local không phụ thuộc CI.++## Yêu cầu môi trường++| Thành phần | Version | Ghi chú |+|---|---|---|+| Windows | 10/11 x64 | |+| Visual Studio 2022+ | 17.x hoặc Build Tools | Phải có workload **Desktop development with C++** |+| Windows App SDK | 1.8 | Tự kéo qua NuGet `packages.config` |+| .NET SDK | 8.0 hoặc mới hơn | Cần cho `vpk` global tool |+| vcpkg | latest, ở `C:\vcpkg` | Project hardcode path này |+| PowerShell | 5.1 (pwsh cũng OK) | |++### Cài vcpkg deps (1 lần duy nhất)++Project link các lib native qua vcpkg. Cài 1 lần:++**Git Bash / MSYS2**:+```bash+/c/vcpkg/vcpkg.exe install \+ sqlite3 libpq libmariadb openssl hiredis \+ nlohmann-json cpp-httplib \+ --triplet x64-windows+```++**PowerShell**:+```powershell+C:\vcpkg\vcpkg.exe install `+ sqlite3 libpq libmariadb openssl hiredis `+ nlohmann-json cpp-httplib `+ --triplet x64-windows+```++**CMD**:+```cmd+C:\vcpkg\vcpkg.exe install ^+ sqlite3 libpq libmariadb openssl hiredis ^+ nlohmann-json cpp-httplib ^+ --triplet x64-windows+```++> Mỗi shell có cú pháp line-continuation khác nhau: bash dùng `\`, PowerShell dùng backtick `` ` ``, CMD dùng caret `^`. Hoặc bạn có thể gõ 1 dòng duy nhất không xuống dòng cũng được.++## Cấu trúc scripts++Tất cả build scripts nằm ở `windows/scripts/`:++```+windows/scripts/+├── install-vpk-tool.ps1 # Cài vpk CLI (Velopack) 1 lần+├── build-unpackaged.ps1 # Build Gridex.exe + bundle runtime DLLs+├── pack-velopack.ps1 # Pack Gridex.exe → Setup.exe+└── build-and-pack.ps1 # One-shot: install + build + pack+```++## Build Setup.exe++> **Flags bắt buộc cho mọi lệnh `powershell`**:+> - `-NoProfile`: skip load `$PROFILE` cá nhân — tránh aliases / function overrides ảnh hưởng build.+> - `-ExecutionPolicy Bypass`: Windows mặc định chặn script `.ps1` không được ký (policy `Restricted` / `AllSigned`). Flag này chỉ áp dụng cho 1 process duy nhất, không cần `Set-ExecutionPolicy` global.++### Cách nhanh nhất — 1 lệnh duy nhất++**Git Bash / MSYS2**:+```bash+cd /e/dev/be/vura+powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/build-and-pack.ps1 -Version "0.1.4"+```++**PowerShell (5.1 / 7+)**:+```powershell+cd E:\dev\be\vura+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-and-pack.ps1 -Version "0.1.4"+```++**CMD**:+```cmd+cd /d E:\dev\be\vura+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-and-pack.ps1 -Version "0.1.4"+```++Script sẽ:+1. Cài/update `vpk` global tool (skip nếu đã có)+2. Build `Gridex.exe` unpackaged, stamp version `0.1.4` vào About section+3. Pack thành `Setup.exe` qua Velopack với metadata version `0.1.4`++**Output**: `windows/Releases/`+- `Gridex-stable-Setup.exe` — installer user-facing+- `Gridex-0.1.4-stable-full.nupkg` — package Velopack+- `releases.stable.json`, `RELEASES-stable` — feed manifests+- `Gridex-stable-Portable.zip` — bản portable++### Cài thử sau khi build++**Git Bash / MSYS2**:+```bash+./windows/Releases/Gridex-stable-Setup.exe+```++**PowerShell**:+```powershell+.\windows\Releases\Gridex-stable-Setup.exe+```++**CMD**:+```cmd+.\windows\Releases\Gridex-stable-Setup.exe+```++Sau khi cài, mở Settings (`Ctrl+Shift+P`) → cuộn xuống mục **About** → phải thấy đúng số version đã pass vào.++## Build từng bước (khi debug)++Khi cần iterate nhanh hơn hoặc chỉ build exe mà không pack installer:++### Bước 1 — Cài `vpk` (1 lần)++**Git Bash / MSYS2**:+```bash+powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/install-vpk-tool.ps1+```++**PowerShell**:+```powershell+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\install-vpk-tool.ps1+```++**CMD**:+```cmd+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\install-vpk-tool.ps1+```++### Bước 2 — Build `Gridex.exe` (nhiều lần)++**Git Bash / MSYS2**:+```bash+# Dev build — About section hiện "0.0.0-dev"+powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/build-unpackaged.ps1++# Build với version cụ thể — About section hiện đúng string+powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/build-unpackaged.ps1 -Version "0.1.4-test"+```++**PowerShell**:+```powershell+# Dev build — About section hiện "0.0.0-dev"+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-unpackaged.ps1++# Build với version cụ thể — About section hiện đúng string+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-unpackaged.ps1 -Version "0.1.4-test"+```++**CMD**:+```cmd+REM Dev build — About section hiện "0.0.0-dev"+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-unpackaged.ps1++REM Build với version cụ thể — About section hiện đúng string+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-unpackaged.ps1 -Version "0.1.4-test"+```++Chạy trực tiếp exe để test nhanh mà không cần cài installer:++**Git Bash / MSYS2**:+```bash+./windows/Gridex/x64/Release/Gridex/Gridex.exe+```++**PowerShell / CMD**:+```powershell+.\windows\Gridex\x64\Release\Gridex\Gridex.exe+```++### Bước 3 — Pack Setup.exe++**Git Bash / MSYS2**:+```bash+powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/pack-velopack.ps1 -Version "0.1.4-test"+```++**PowerShell**:+```powershell+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\pack-velopack.ps1 -Version "0.1.4-test"+```++**CMD**:+```cmd+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\pack-velopack.ps1 -Version "0.1.4-test"+```++**Lưu ý**: `-Version` truyền vào `pack-velopack.ps1` **phải khớp** với `-Version` truyền vào `build-unpackaged.ps1`, nếu không thì Velopack sẽ in một số, còn About section của app sẽ in số khác. Dùng `build-and-pack.ps1` ở trên để tránh trường hợp này.++## Version stamping — cách hoạt động++- `windows/Gridex/GridexVersion.h` — include unconditional file generated+- `windows/Gridex/GridexVersion.generated.h` — **auto-generated, gitignored**, do `build-unpackaged.ps1` ghi mỗi lần chạy+ - Có `-Version` → `#define GRIDEX_VERSION L"0.1.4"`+ - Không `-Version` → `#define GRIDEX_VERSION L"0.0.0-dev"`+- `windows/Gridex/SettingsPage.xaml.cpp` — đọc `GRIDEX_VERSION` và set vào `VersionText` text block+- CI workflow `.github/workflows/windows-release.yml` tự parse version từ git tag (`v0.1.4` → `0.1.4`) và forward sang script++Build script chỉ rewrite `GridexVersion.generated.h` khi nội dung khác → không force recompile vô ích.++## Channels (optional)++Mặc định Velopack dùng channel `stable`. Nếu muốn phát hành kênh riêng (beta/nightly):++**Git Bash / MSYS2**:+```bash+powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/build-and-pack.ps1 -Version "0.1.4-beta.1" -Channel "beta"+```++**PowerShell**:+```powershell+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-and-pack.ps1 -Version "0.1.4-beta.1" -Channel "beta"+```++**CMD**:+```cmd+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-and-pack.ps1 -Version "0.1.4-beta.1" -Channel "beta"+```++Output sẽ là `Gridex-beta-Setup.exe` + `releases.beta.json` — auto-updater phân luồng theo channel.++## Troubleshooting++### `MSBuild.exe not found`+Chưa cài VS 2022 với workload C++. Cài từ: <https://visualstudio.microsoft.com/downloads/>++### `dotnet SDK not found on PATH`+Cài .NET 8 SDK (hoặc mới hơn) từ: <https://dot.net/download>++### `running scripts is disabled on this system` (SecurityError / UnauthorizedAccess)+Thiếu flag `-ExecutionPolicy Bypass` trong lệnh `powershell`. Dùng đúng các lệnh trong README (đã có sẵn flag).++### `cd: E:devbevura: No such file or directory` trong Git Bash+Bash parse `\d`, `\b`, `\v` thành escape sequence → path hỏng. Fix bằng 1 trong 3 cách:+- Forward slash: `cd /e/dev/be/vura`+- Single quote: `cd 'E:\dev\be\vura'`+- Escape backslash: `cd E:\\dev\\be\\vura`++### `vpk installed but not on PATH`+Thêm `%USERPROFILE%\.dotnet\tools` vào PATH rồi mở lại terminal.++### `packages\Microsoft.Web.WebView2...\build\native\Microsoft.Web.WebView2.targets not found`+NuGet restore chưa chạy. Script có gọi `MSBuild /t:Restore /p:RestorePackagesConfig=true` rồi — nếu lỗi, check `windows/NuGet.Config` còn không.++### `vcpkg install failed` hoặc link lỗi `cannot open libpq.lib`+Chưa cài đủ vcpkg deps. Xem section "Cài vcpkg deps" ở đầu file.++### Gridex.exe crash ngay khi khởi động với `MSVCP140.dll not found`+Máy thiếu VC++ 2015-2022 Redistributable. Script `build-unpackaged.ps1` tự copy CRT DLLs vào output folder → nếu vẫn lỗi thì check VS install path / logs script.++### Setup.exe cài xong nhưng About hiện `0.0.0-dev` dù pack với `-Version 0.1.4`+Dùng `build-and-pack.ps1` thay vì gọi `pack-velopack.ps1` trực tiếp. Trường hợp chạy `pack-velopack.ps1` với version khác version lúc build `Gridex.exe` → xóa `windows\Gridex\x64\Release\` rồi build lại đúng thứ tự.++### Lỗi `pwsh.exe exited with code 9009` trong vcpkg applocal step+Bỏ qua — PowerShell Core chưa cài, vcpkg tự fallback sang `powershell.exe` ngay sau đó. Không ảnh hưởng build.++### Có ký tự lạ `[200~` hoặc `~` xuất hiện khi paste+Terminal đang bật **bracketed paste mode**. Fix: tắt bằng `printf '\e[?2004l'` (bash) hoặc chuyển sang terminal khác (Windows Terminal thường không bị).++## Cleanup++Xoá artifacts sau khi test:++**Git Bash / MSYS2**:+```bash+rm -rf ./windows/Gridex/x64 ./windows/Releases ./windows/Gridex/GridexVersion.generated.h+```++**PowerShell**:+```powershell+Remove-Item -Recurse -Force .\windows\Gridex\x64, .\windows\Releases, .\windows\Gridex\GridexVersion.generated.h -ErrorAction SilentlyContinue+```++**CMD**:+```cmd+rmdir /s /q .\windows\Gridex\x64+rmdir /s /q .\windows\Releases+del /q .\windows\Gridex\GridexVersion.generated.h+```++## CI Release (tham khảo)++CI tự chạy khi push tag matching `v*.*.*`:++```bash+git tag v0.1.4+git push origin v0.1.4+```++GitHub Actions workflow `windows-release.yml` sẽ tự build + pack + upload assets lên GitHub Release. Xem chi tiết ở `.github/workflows/windows-release.yml`.diff --git a/windows/scripts/build-and-pack.ps1 b/windows/scripts/build-and-pack.ps1new file mode 100644index 0000000..f93c93d--- /dev/null+++ b/windows/scripts/build-and-pack.ps1@@ -0,0 +1,35 @@+# build-and-pack.ps1+# ----------------------------------------------------------------------+# One-command orchestrator: install vpk -> build unpackaged -> pack release.+#+# Usage:+# .\windows\scripts\build-and-pack.ps1 # uses 0.0.1-dev+# .\windows\scripts\build-and-pack.ps1 -Version 1.0.0+# .\windows\scripts\build-and-pack.ps1 -Version 1.0.0 -Channel beta+#+# Outputs to: E:\dev\be\vura\windows\Releases\+# ----------------------------------------------------------------------++param(+ [string]$Version = "0.0.1-dev",+ [string]$Channel = "stable"+)++$ErrorActionPreference = "Stop"+$start = Get-Date++Write-Host "==> install vpk tool" -ForegroundColor Magenta+& "$PSScriptRoot\install-vpk-tool.ps1"++Write-Host "==> build unpackaged" -ForegroundColor Magenta+# Forward -Version so GridexVersion.generated.h is stamped before compile.+# Without this the About section inside Gridex.exe stays "0.0.0-dev" while+# Velopack metadata/Setup.exe report the passed version -- confusing mismatch.+& "$PSScriptRoot\build-unpackaged.ps1" -Version $Version++Write-Host "==> pack velopack release" -ForegroundColor Magenta+& "$PSScriptRoot\pack-velopack.ps1" -Version $Version -Channel $Channel++$elapsed = (Get-Date) - $start+Write-Host ""+Write-Host "Done in $([math]::Round($elapsed.TotalSeconds, 1))s. Artifacts at windows\Releases\" -ForegroundColor Greendiff --git a/windows/scripts/build-unpackaged.ps1 b/windows/scripts/build-unpackaged.ps1new file mode 100644index 0000000..09eddf2--- /dev/null+++ b/windows/scripts/build-unpackaged.ps1@@ -0,0 +1,237 @@+# build-unpackaged.ps1+# ----------------------------------------------------------------------+# Build Gridex.vcxproj as an UNPACKAGED WinUI 3 app for Velopack.+#+# The default project config is packaged (MSIX, AppxPackage=true). This+# script DOES NOT mutate the vcxproj -- it only passes the unpackaged+# property overrides via /p: so the existing packaged build path is+# preserved untouched. Re-running the standard MSIX build still works.+#+# Output: E:\dev\be\vura\windows\x64\Release\Gridex\+# ----------------------------------------------------------------------++param(+ [string]$Configuration = "Release",+ [string]$Version = ""+)++$ErrorActionPreference = "Stop"++# Resolve the repo root from the script location: scripts -> windows -> repo+$repoRoot = Resolve-Path (Join-Path $PSScriptRoot "..\..")+$proj = Join-Path $repoRoot "windows\Gridex\Gridex.vcxproj"++if (-not (Test-Path $proj)) {+ throw "Gridex.vcxproj not found at: $proj"+}++# Stamp the version into GridexVersion.generated.h. The header is+# included unconditionally by GridexVersion.h, so MSBuild's incremental+# build can rely on the real file dependency in .tlog (a conditional+# __has_include would be invisible to the dependency scanner and leave+# stale SettingsPage.obj across runs). CI passes -Version from the tag;+# local dev runs fall through to "0.0.0-dev" which makes the About+# section obviously non-release.+$effectiveVersion = if ($Version -ne "") { $Version } else { "0.0.0-dev" }+$genHeader = Join-Path $repoRoot "windows\Gridex\GridexVersion.generated.h"+$genContent = @"+#pragma once+// AUTO-GENERATED by windows\scripts\build-unpackaged.ps1 -- do not edit.+// Defines GRIDEX_VERSION used by SettingsPage About section.+// CI workflow stamps the real tag version; local dev builds get "dev".+#define GRIDEX_VERSION L"$effectiveVersion"+"@+# Only rewrite when the content actually changes -- otherwise we bump+# the file's mtime on every run and force MSBuild to recompile+# SettingsPage.obj for no reason.+$existing = if (Test-Path $genHeader) { Get-Content $genHeader -Raw } else { "" }+if ($existing -ne "$genContent`r`n" -and $existing -ne $genContent) {+ Set-Content -Path $genHeader -Value $genContent -Encoding ASCII+ Write-Host "Stamped version $effectiveVersion -> $genHeader" -ForegroundColor Cyan+} else {+ Write-Host "Version $effectiveVersion already stamped (skip rewrite)" -ForegroundColor DarkGray+}++# Locate VS install + MSBuild via vswhere -- works for any VS 2022++# install layout without hardcoding a path. Falls back to PATH if+# vswhere absent.+$vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"+$vsDir = $null+$msbuild = $null+if (Test-Path $vswhere) {+ $vsDir = & $vswhere -latest -property installationPath+ $msbuild = & $vswhere -latest -requires Microsoft.Component.MSBuild `+ -find "MSBuild\**\Bin\MSBuild.exe" | Select-Object -First 1+}+if (-not $msbuild) {+ $cmd = Get-Command msbuild -ErrorAction SilentlyContinue+ if ($cmd) { $msbuild = $cmd.Source }+}+if (-not $msbuild) {+ throw "MSBuild.exe not found. Install VS 2022 Build Tools (Desktop C++ workload)."+}+Write-Host "MSBuild: $msbuild" -ForegroundColor Cyan++# Step 1: NuGet restore (packages.config project).+#+# Gridex.vcxproj still uses the legacy packages.config format (the+# ..\packages\<id>.<ver>\ layout). MSBuild's plain `/restore` flag only+# handles PackageReference projects; for packages.config we must pass+# RestorePackagesConfig=true (NuGet 5.x+). Without this, a clean+# checkout (e.g. fresh CI runner) fails with+# "The missing file is ..\packages\Microsoft.Web.WebView2.1.0.3179.45\+# build\native\Microsoft.Web.WebView2.targets."+& $msbuild $proj `+ /t:Restore `+ /p:RestorePackagesConfig=true `+ /p:Configuration=$Configuration `+ /p:Platform=x64+if ($LASTEXITCODE -ne 0) {+ throw "MSBuild restore failed with exit code $LASTEXITCODE"+}++# Step 2: Build unpackaged.+#+# Property overrides:+# WindowsPackageType=None -> Build as unpackaged Win32 app+# WindowsAppSDKSelfContained=true -> Bundle WinAppSDK runtime DLLs side-by-side+# AppxPackage=false -> Skip MSIX packaging step+# GenerateAppxPackageOnBuild=false-> Belt-and-braces for AppxPackage flag+#+# Together these flip the project from MSIX to a self-contained Win32 layout+# that Velopack can pack directly with `vpk pack --packDir`.+& $msbuild $proj `+ /p:Configuration=$Configuration `+ /p:Platform=x64 `+ /p:WindowsPackageType=None `+ /p:WindowsAppSDKSelfContained=true `+ /p:AppxPackage=false `+ /p:GenerateAppxPackageOnBuild=false `+ /m++if ($LASTEXITCODE -ne 0) {+ throw "MSBuild failed with exit code $LASTEXITCODE"+}++#+# MSBuild emits the full unpackaged output (including all WinAppSDK runtime+# DLLs) to the PROJECT-nested path, not the solution-level $(SolutionDir)\x64+# path. The solution-level path may also contain stale files from an earlier+# packaged build -- ignore it.+#+$outDir = Join-Path $repoRoot "windows\Gridex\x64\$Configuration\Gridex"+if (-not (Test-Path $outDir)) {+ throw "Build succeeded but output dir missing: $outDir"+}++# --- Bundle VC++ Redistributable runtime DLLs ---------------------------+#+# Gridex.exe imports MSVCP140.dll / VCRUNTIME140.dll / VCRUNTIME140_1.dll+# from the VC++ 2015-2022 Redistributable. These are NOT bundled by WinUI+# 3 self-contained build -- they ship with the system via the VC Redist+# installer. Fresh Windows installs (or stripped images) will crash+# Gridex.exe at startup with "MSVCP140.dll not found" if VC Redist is+# missing (~5-15% of machines).+#+# Fix: copy all CRT DLLs from the VS VC\Redist\MSVC\<ver>\x64\Microsoft.VC*.CRT+# folder into the build output. Microsoft's Visual C++ redistributable+# license explicitly allows this. Adds ~2 MB to Setup.exe.+#+if ($vsDir) {+ $vcRedistRoot = Join-Path $vsDir 'VC\Redist\MSVC'+ if (Test-Path $vcRedistRoot) {+ # Pick the highest numeric version directory (e.g. 14.50.35710)+ $crtVersionDir = Get-ChildItem $vcRedistRoot -Directory |+ Where-Object { $_.Name -match '^\d+\.\d+\.\d+' } |+ Sort-Object { [Version]$_.Name } -Descending |+ Select-Object -First 1+ if ($crtVersionDir) {+ $crtDir = Get-ChildItem (Join-Path $crtVersionDir.FullName 'x64') `+ -Directory -Filter 'Microsoft.VC*.CRT' -ErrorAction SilentlyContinue |+ Select-Object -First 1+ if ($crtDir) {+ $dllCount = 0+ Get-ChildItem (Join-Path $crtDir.FullName '*.dll') | ForEach-Object {+ Copy-Item $_.FullName -Destination $outDir -Force+ $dllCount+++ }+ Write-Host "Copied $dllCount VC runtime DLL(s) from $($crtDir.Name)" -ForegroundColor Cyan+ } else {+ Write-Warning "VC CRT folder not found under $($crtVersionDir.FullName)\x64 -- users will need VC++ Redist installed"+ }+ } else {+ Write-Warning "No versioned VC CRT redist folder found in $vcRedistRoot"+ }+ } else {+ Write-Warning "VC Redist root missing: $vcRedistRoot"+ }+}+# -----------------------------------------------------------------------++# --- Bundle vcpkg runtime DLLs -----------------------------------------+#+# Gridex.exe dynamically links libpq, libmariadb, sqlite3, libssl,+# libcrypto, hiredis (+ their transitive deps like zlib1, brotli*,+# lz4) from vcpkg's x64-windows triplet. MSBuild's vcpkg integration+# is supposed to run applocal.ps1 post-link to copy these DLLs into+# the output folder, but that step is flaky on CI runners -- the+# windows-2022 GitHub runner prints "pwsh.exe exited with code 9009"+# because PowerShell Core isn't on PATH, and the step silently does+# nothing. Without the DLLs, Setup.exe installs fine but the installed+# Gridex.exe crashes at startup with "libpq.dll not found" et al.+#+# Fix: copy the entire vcpkg bin/*.dll set explicitly. A few DLLs are+# transitive deps we don't directly reference (legacy.dll, libecpg*,+# libpgtypes.dll) but copying the whole set is safer than maintaining+# a curated list that drifts when vcpkg updates package layouts.+# Skip .pdb files to keep Setup.exe small.+#+$vcpkgBin = 'C:\vcpkg\installed\x64-windows\bin'+if (Test-Path $vcpkgBin) {+ $dllCount = 0+ Get-ChildItem (Join-Path $vcpkgBin '*.dll') | ForEach-Object {+ Copy-Item $_.FullName -Destination $outDir -Force+ $dllCount+++ }+ Write-Host "Copied $dllCount vcpkg runtime DLL(s) from $vcpkgBin" -ForegroundColor Cyan+} else {+ Write-Warning "vcpkg bin missing: $vcpkgBin -- Setup.exe will be missing libpq/libmariadb/etc."+}+# -----------------------------------------------------------------------++# --- Bundle Microsoft Edge WebView2 Runtime bootstrap ------------------+#+# Gridex uses a WebView2 element in the ER Diagram view. Windows 11 and+# recently-updated Windows 10 ship with the WebView2 Runtime via Edge+# automatically, but fresh/stripped Windows installs may lack it. The+# C++ code in App.xaml.cpp (EnsureWebView2Runtime) silently runs this+# bootstrap installer on first launch if the runtime is missing.+#+# The bootstrap is a ~2 MB stub that downloads the real runtime from+# Microsoft's CDN on demand. We cache it in windows\vendor\webview2\+# to avoid re-downloading on every build.+#+$vendorDir = Join-Path $repoRoot "windows\vendor\webview2"+$bootstrapName = "MicrosoftEdgeWebView2Setup.exe"+$bootstrapPath = Join-Path $vendorDir $bootstrapName+$bootstrapUrl = "https://go.microsoft.com/fwlink/p/?LinkId=2124703"+if (-not (Test-Path $bootstrapPath)) {+ Write-Host "Downloading WebView2 bootstrap installer..." -ForegroundColor Cyan+ New-Item -ItemType Directory -Force -Path $vendorDir | Out-Null+ try {+ $ProgressPreference = 'SilentlyContinue'+ Invoke-WebRequest -Uri $bootstrapUrl -OutFile $bootstrapPath -UseBasicParsing+ $ProgressPreference = 'Continue'+ Write-Host " cached at $bootstrapPath ($([math]::Round((Get-Item $bootstrapPath).Length/1KB,1)) KB)" -ForegroundColor Green+ } catch {+ Write-Warning "Failed to download WebView2 bootstrap: $_"+ }+}+if (Test-Path $bootstrapPath) {+ Copy-Item $bootstrapPath -Destination $outDir -Force+ Write-Host "Bundled WebView2 bootstrap: $bootstrapName" -ForegroundColor Cyan+}+# -----------------------------------------------------------------------++$fileCount = (Get-ChildItem $outDir -File).Count+Write-Host "Unpackaged build output: $outDir ($fileCount files)" -ForegroundColor Greendiff --git a/windows/scripts/install-vpk-tool.ps1 b/windows/scripts/install-vpk-tool.ps1new file mode 100644index 0000000..7f8d3c5--- /dev/null+++ b/windows/scripts/install-vpk-tool.ps1@@ -0,0 +1,48 @@+# install-vpk-tool.ps1+# ----------------------------------------------------------------------+# One-shot installer / upgrader for the Velopack `vpk` .NET global tool.+#+# Pinned major version: 0.0.* (Velopack ships under 0.0.x preview series).+# Bump the version range deliberately when upgrading; do not let CI silently+# pull a newer major.+#+# Prerequisite: .NET 8 SDK (or newer) on PATH.+# ----------------------------------------------------------------------++$ErrorActionPreference = "Stop"++# vpk 0.0.1298 targets net9.0; allow running on any newer .NET runtime+# (e.g. net10). Set before any vpk invocation.+$env:DOTNET_ROLL_FORWARD = "Major"++# Verify dotnet is available before attempting tool install -- gives a clear+# error message instead of an opaque "command not found".+$dotnet = Get-Command dotnet -ErrorAction SilentlyContinue+if (-not $dotnet) {+ throw "dotnet SDK not found on PATH. Install .NET 8 SDK from https://dot.net/download"+}++Write-Host "Installing/upgrading vpk global tool..." -ForegroundColor Cyan++# Try install first; if already installed, fall back to update.+& dotnet tool install --global vpk --version "0.0.*" 2>$null+if ($LASTEXITCODE -ne 0) {+ Write-Host "vpk already installed -- running update instead." -ForegroundColor Yellow+ & dotnet tool update --global vpk --version "0.0.*"+ if ($LASTEXITCODE -ne 0) { throw "vpk install/update failed" }+}++# Verify the binary is on PATH (dotnet global tools live in %USERPROFILE%\.dotnet\tools)+$vpk = Get-Command vpk -ErrorAction SilentlyContinue+if (-not $vpk) {+ throw "vpk installed but not on PATH. Add %USERPROFILE%\.dotnet\tools to PATH and re-run."+}++# vpk has no --version flag; the first line of --help contains the version.+$help = & vpk --help 2>&1+$verLine = $help | Select-String -Pattern "Velopack CLI" | Select-Object -First 1+if ($verLine) {+ Write-Host "vpk: $verLine" -ForegroundColor Green+} else {+ Write-Host "vpk installed (version line not parsed, but tool runs)" -ForegroundColor Yellow+}diff --git a/windows/scripts/pack-velopack.ps1 b/windows/scripts/pack-velopack.ps1new file mode 100644index 0000000..068699b--- /dev/null+++ b/windows/scripts/pack-velopack.ps1@@ -0,0 +1,139 @@+# pack-velopack.ps1+# ----------------------------------------------------------------------+# Wrap `vpk pack` to produce Setup.exe + nupkg + delta + RELEASES manifest+# from the unpackaged MSBuild output.+#+# Requires: install-vpk-tool.ps1 to have run successfully (vpk on PATH).+# Requires: build-unpackaged.ps1 to have run successfully (output present).+#+# Output (default): E:\dev\be\vura\windows\Releases\+# - Setup.exe (user-facing installer)+# - Gridex-<ver>-full.nupkg (full package)+# - Gridex-<ver>-delta.nupkg (only present from v2 onward)+# - releases.stable.json (auto-update feed manifest)+# - RELEASES (legacy feed file)+#+# ----------------------------------------------------------------------+# Feed manifest schemas (captured from a real `vpk pack` run, vpk v0.0.1298,+# with channel=stable, version=0.0.1-dev):+#+# releases.stable.json -- legacy JSON feed used by Velopack update clients:+# {+# "Assets": [+# {+# "PackageId": "Gridex",+# "Version": "0.0.1-dev",+# "Type": "Full" | "Delta",+# "FileName": "Gridex-0.0.1-dev-stable-full.nupkg",+# "SHA1": "<40-hex>",+# "SHA256": "<64-hex>",+# "Size": <bytes>+# }+# ]+# }+#+# assets.stable.json -- new JSON feed listing all release artifacts:+# [+# {"RelativeFileName": "Gridex-stable-Setup.exe", "Type": "Installer"},+# {"RelativeFileName": "Gridex-0.0.1-dev-stable-full.nupkg", "Type": "Full"},+# {"RelativeFileName": "Gridex-stable-Portable.zip", "Type": "Portable"}+# ]+#+# RELEASES-stable -- legacy text feed, one line per nupkg:+# <SHA1> <filename.nupkg> <size-bytes>+# ----------------------------------------------------------------------++param(+ [Parameter(Mandatory=$true)][string]$Version,+ [string]$Channel = "stable",+ # MSBuild puts the full unpackaged output (with all WinAppSDK runtime+ # DLLs) under the project-nested path, NOT $(SolutionDir)\x64.+ [string]$PackDir = "windows\Gridex\x64\Release\Gridex",+ [string]$OutputDir = "windows\Releases"+)++$ErrorActionPreference = "Stop"++# vpk 0.0.1298 targets net9.0; allow running on any newer .NET runtime.+$env:DOTNET_ROLL_FORWARD = "Major"++$repoRoot = Resolve-Path (Join-Path $PSScriptRoot "..\..")++# vpk's --packDir / --outputDir resolve relative to CWD; pin CWD to repo root+# so callers can pass repo-relative paths regardless of where they invoked us.+Push-Location $repoRoot+try {+ $absPack = Join-Path $repoRoot $PackDir+ if (-not (Test-Path $absPack)) {+ throw "Pack source dir not found: $absPack (run build-unpackaged.ps1 first)"+ }++ # Ensure the main exe really exists in the pack dir -- vpk would fail+ # later with a less obvious error.+ $mainExe = Join-Path $absPack "Gridex.exe"+ if (-not (Test-Path $mainExe)) {+ throw "Gridex.exe missing from pack dir: $mainExe"+ }++ Write-Host "Packing Velopack release v$Version (channel=$Channel)..." -ForegroundColor Cyan++ # Velopack Setup.exe icon -- use the same Gridex.ico that gets+ # embedded into Gridex.exe via the .rc file. Path is resolved from+ # the pinned CWD ($repoRoot above).+ $iconPath = "windows\Gridex\Assets\Gridex.ico"+ if (-not (Test-Path $iconPath)) {+ Write-Warning "Setup icon missing at $iconPath -- Velopack will use its default phoenix icon"+ $iconPath = $null+ }++ $vpkArgs = @(+ 'pack',+ '--packId', 'Gridex',+ '--packVersion', $Version,+ '--packDir', $PackDir,+ '--mainExe', 'Gridex.exe',+ '--channel', $Channel,+ '--outputDir', $OutputDir+ )+ if ($iconPath) {+ $vpkArgs += @('--icon', $iconPath)+ }++ & vpk @vpkArgs++ if ($LASTEXITCODE -ne 0) {+ throw "vpk pack failed with exit code $LASTEXITCODE"+ }+}+finally {+ Pop-Location+}++# Sanity-check the artifacts landed where expected.+#+# Velopack naming convention (observed with vpk 0.0.1298):+# Gridex-<channel>-Setup.exe (installer)+# Gridex-<version>-<channel>-full.nupkg (full package)+# Gridex-<channel>-Portable.zip (portable bonus)+# releases.<channel>.json (legacy feed manifest)+# assets.<channel>.json (new feed manifest)+# RELEASES-<channel> (legacy text feed)+#+$absOut = Join-Path $repoRoot $OutputDir+$expected = @(+ "Gridex-$Channel-Setup.exe",+ "Gridex-$Version-$Channel-full.nupkg",+ "releases.$Channel.json",+ "RELEASES-$Channel"+)+foreach ($f in $expected) {+ $p = Join-Path $absOut $f+ if (-not (Test-Path $p)) {+ Write-Warning "Expected artifact missing: $p"+ } else {+ $size = [math]::Round((Get-Item $p).Length / 1MB, 2)+ Write-Host " [OK] $f ($size MB)" -ForegroundColor Green+ }+}++Write-Host "Artifacts: $absOut" -ForegroundColor Green